xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision 8fc99e42676a23421c75e76660640f9765d693b1)
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 	econnp->conn_ixa->ixa_cred = econnp->conn_cred;
2416 	aconnp->conn_cred = NULL;
2417 	econnp->conn_cpid = aconnp->conn_cpid;
2418 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2419 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2420 
2421 	econnp->conn_zoneid = aconnp->conn_zoneid;
2422 	econnp->conn_allzones = aconnp->conn_allzones;
2423 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2424 
2425 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2426 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2427 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2428 
2429 	/* Do the IPC initialization */
2430 	CONN_INC_REF(econnp);
2431 
2432 	/* Done with old IPC. Drop its ref on its connp */
2433 	CONN_DEC_REF(aconnp);
2434 }
2435 
2436 
2437 /*
2438  * Adapt to the information, such as rtt and rtt_sd, provided from the
2439  * DCE and IRE maintained by IP.
2440  *
2441  * Checks for multicast and broadcast destination address.
2442  * Returns zero if ok; an errno on failure.
2443  *
2444  * Note that the MSS calculation here is based on the info given in
2445  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2446  * will be handled in tcp_input_data() when TCP knows which options to use.
2447  *
2448  * Note on how TCP gets its parameters for a connection.
2449  *
2450  * When a tcp_t structure is allocated, it gets all the default parameters.
2451  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2452  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2453  * default.
2454  *
2455  * An incoming SYN with a multicast or broadcast destination address is dropped
2456  * in ip_fanout_v4/v6.
2457  *
2458  * An incoming SYN with a multicast or broadcast source address is always
2459  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2460  * conn_connect.
2461  * The same logic in tcp_set_destination also serves to
2462  * reject an attempt to connect to a broadcast or multicast (destination)
2463  * address.
2464  */
2465 static int
2466 tcp_set_destination(tcp_t *tcp)
2467 {
2468 	uint32_t	mss_max;
2469 	uint32_t	mss;
2470 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2471 	conn_t		*connp = tcp->tcp_connp;
2472 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2473 	iulp_t		uinfo;
2474 	int		error;
2475 	uint32_t	flags;
2476 
2477 	flags = IPDF_LSO | IPDF_ZCOPY;
2478 	/*
2479 	 * Make sure we have a dce for the destination to avoid dce_ident
2480 	 * contention for connected sockets.
2481 	 */
2482 	flags |= IPDF_UNIQUE_DCE;
2483 
2484 	if (!tcps->tcps_ignore_path_mtu)
2485 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2486 
2487 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2488 	mutex_enter(&connp->conn_lock);
2489 	error = conn_connect(connp, &uinfo, flags);
2490 	mutex_exit(&connp->conn_lock);
2491 	if (error != 0)
2492 		return (error);
2493 
2494 	error = tcp_build_hdrs(tcp);
2495 	if (error != 0)
2496 		return (error);
2497 
2498 	tcp->tcp_localnet = uinfo.iulp_localnet;
2499 
2500 	if (uinfo.iulp_rtt != 0) {
2501 		clock_t	rto;
2502 
2503 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2504 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2505 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2506 		    tcps->tcps_rexmit_interval_extra +
2507 		    (tcp->tcp_rtt_sa >> 5);
2508 
2509 		if (rto > tcps->tcps_rexmit_interval_max) {
2510 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2511 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2512 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2513 		} else {
2514 			tcp->tcp_rto = rto;
2515 		}
2516 	}
2517 	if (uinfo.iulp_ssthresh != 0)
2518 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2519 	else
2520 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2521 	if (uinfo.iulp_spipe > 0) {
2522 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2523 		    tcps->tcps_max_buf);
2524 		if (tcps->tcps_snd_lowat_fraction != 0) {
2525 			connp->conn_sndlowat = connp->conn_sndbuf /
2526 			    tcps->tcps_snd_lowat_fraction;
2527 		}
2528 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2529 	}
2530 	/*
2531 	 * Note that up till now, acceptor always inherits receive
2532 	 * window from the listener.  But if there is a metrics
2533 	 * associated with a host, we should use that instead of
2534 	 * inheriting it from listener. Thus we need to pass this
2535 	 * info back to the caller.
2536 	 */
2537 	if (uinfo.iulp_rpipe > 0) {
2538 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2539 		    tcps->tcps_max_buf);
2540 	}
2541 
2542 	if (uinfo.iulp_rtomax > 0) {
2543 		tcp->tcp_second_timer_threshold =
2544 		    uinfo.iulp_rtomax;
2545 	}
2546 
2547 	/*
2548 	 * Use the metric option settings, iulp_tstamp_ok and
2549 	 * iulp_wscale_ok, only for active open. What this means
2550 	 * is that if the other side uses timestamp or window
2551 	 * scale option, TCP will also use those options. That
2552 	 * is for passive open.  If the application sets a
2553 	 * large window, window scale is enabled regardless of
2554 	 * the value in iulp_wscale_ok.  This is the behavior
2555 	 * since 2.6.  So we keep it.
2556 	 * The only case left in passive open processing is the
2557 	 * check for SACK.
2558 	 * For ECN, it should probably be like SACK.  But the
2559 	 * current value is binary, so we treat it like the other
2560 	 * cases.  The metric only controls active open.For passive
2561 	 * open, the ndd param, tcp_ecn_permitted, controls the
2562 	 * behavior.
2563 	 */
2564 	if (!tcp_detached) {
2565 		/*
2566 		 * The if check means that the following can only
2567 		 * be turned on by the metrics only IRE, but not off.
2568 		 */
2569 		if (uinfo.iulp_tstamp_ok)
2570 			tcp->tcp_snd_ts_ok = B_TRUE;
2571 		if (uinfo.iulp_wscale_ok)
2572 			tcp->tcp_snd_ws_ok = B_TRUE;
2573 		if (uinfo.iulp_sack == 2)
2574 			tcp->tcp_snd_sack_ok = B_TRUE;
2575 		if (uinfo.iulp_ecn_ok)
2576 			tcp->tcp_ecn_ok = B_TRUE;
2577 	} else {
2578 		/*
2579 		 * Passive open.
2580 		 *
2581 		 * As above, the if check means that SACK can only be
2582 		 * turned on by the metric only IRE.
2583 		 */
2584 		if (uinfo.iulp_sack > 0) {
2585 			tcp->tcp_snd_sack_ok = B_TRUE;
2586 		}
2587 	}
2588 
2589 	/*
2590 	 * XXX Note that currently, iulp_mtu can be as small as 68
2591 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2592 	 * length of all those options exceeds 28 bytes.  But because
2593 	 * of the tcp_mss_min check below, we may not have a problem if
2594 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2595 	 * the negative problem still exists.  And the check defeats PMTUd.
2596 	 * In fact, if PMTUd finds that the MSS should be smaller than
2597 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2598 	 * value.
2599 	 *
2600 	 * We do not deal with that now.  All those problems related to
2601 	 * PMTUd will be fixed later.
2602 	 */
2603 	ASSERT(uinfo.iulp_mtu != 0);
2604 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2605 
2606 	/* Sanity check for MSS value. */
2607 	if (connp->conn_ipversion == IPV4_VERSION)
2608 		mss_max = tcps->tcps_mss_max_ipv4;
2609 	else
2610 		mss_max = tcps->tcps_mss_max_ipv6;
2611 
2612 	if (tcp->tcp_ipsec_overhead == 0)
2613 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2614 
2615 	mss -= tcp->tcp_ipsec_overhead;
2616 
2617 	if (mss < tcps->tcps_mss_min)
2618 		mss = tcps->tcps_mss_min;
2619 	if (mss > mss_max)
2620 		mss = mss_max;
2621 
2622 	/* Note that this is the maximum MSS, excluding all options. */
2623 	tcp->tcp_mss = mss;
2624 
2625 	/*
2626 	 * Update the tcp connection with LSO capability.
2627 	 */
2628 	tcp_update_lso(tcp, connp->conn_ixa);
2629 
2630 	/*
2631 	 * Initialize the ISS here now that we have the full connection ID.
2632 	 * The RFC 1948 method of initial sequence number generation requires
2633 	 * knowledge of the full connection ID before setting the ISS.
2634 	 */
2635 	tcp_iss_init(tcp);
2636 
2637 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2638 
2639 	/*
2640 	 * Make sure that conn is not marked incipient
2641 	 * for incoming connections. A blind
2642 	 * removal of incipient flag is cheaper than
2643 	 * check and removal.
2644 	 */
2645 	mutex_enter(&connp->conn_lock);
2646 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2647 	mutex_exit(&connp->conn_lock);
2648 	return (0);
2649 }
2650 
2651 static void
2652 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2653 {
2654 	int	error;
2655 	conn_t	*connp = tcp->tcp_connp;
2656 	struct sockaddr	*sa;
2657 	mblk_t  *mp1;
2658 	struct T_bind_req *tbr;
2659 	int	backlog;
2660 	socklen_t	len;
2661 	sin_t	*sin;
2662 	sin6_t	*sin6;
2663 	cred_t		*cr;
2664 
2665 	/*
2666 	 * All Solaris components should pass a db_credp
2667 	 * for this TPI message, hence we ASSERT.
2668 	 * But in case there is some other M_PROTO that looks
2669 	 * like a TPI message sent by some other kernel
2670 	 * component, we check and return an error.
2671 	 */
2672 	cr = msg_getcred(mp, NULL);
2673 	ASSERT(cr != NULL);
2674 	if (cr == NULL) {
2675 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2676 		return;
2677 	}
2678 
2679 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2680 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2681 		if (connp->conn_debug) {
2682 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2683 			    "tcp_tpi_bind: bad req, len %u",
2684 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2685 		}
2686 		tcp_err_ack(tcp, mp, TPROTO, 0);
2687 		return;
2688 	}
2689 	/* Make sure the largest address fits */
2690 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2691 	if (mp1 == NULL) {
2692 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2693 		return;
2694 	}
2695 	mp = mp1;
2696 	tbr = (struct T_bind_req *)mp->b_rptr;
2697 
2698 	backlog = tbr->CONIND_number;
2699 	len = tbr->ADDR_length;
2700 
2701 	switch (len) {
2702 	case 0:		/* request for a generic port */
2703 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2704 		if (connp->conn_family == AF_INET) {
2705 			tbr->ADDR_length = sizeof (sin_t);
2706 			sin = (sin_t *)&tbr[1];
2707 			*sin = sin_null;
2708 			sin->sin_family = AF_INET;
2709 			sa = (struct sockaddr *)sin;
2710 			len = sizeof (sin_t);
2711 			mp->b_wptr = (uchar_t *)&sin[1];
2712 		} else {
2713 			ASSERT(connp->conn_family == AF_INET6);
2714 			tbr->ADDR_length = sizeof (sin6_t);
2715 			sin6 = (sin6_t *)&tbr[1];
2716 			*sin6 = sin6_null;
2717 			sin6->sin6_family = AF_INET6;
2718 			sa = (struct sockaddr *)sin6;
2719 			len = sizeof (sin6_t);
2720 			mp->b_wptr = (uchar_t *)&sin6[1];
2721 		}
2722 		break;
2723 
2724 	case sizeof (sin_t):    /* Complete IPv4 address */
2725 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2726 		    sizeof (sin_t));
2727 		break;
2728 
2729 	case sizeof (sin6_t): /* Complete IPv6 address */
2730 		sa = (struct sockaddr *)mi_offset_param(mp,
2731 		    tbr->ADDR_offset, sizeof (sin6_t));
2732 		break;
2733 
2734 	default:
2735 		if (connp->conn_debug) {
2736 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2737 			    "tcp_tpi_bind: bad address length, %d",
2738 			    tbr->ADDR_length);
2739 		}
2740 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2741 		return;
2742 	}
2743 
2744 	if (backlog > 0) {
2745 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2746 		    tbr->PRIM_type != O_T_BIND_REQ);
2747 	} else {
2748 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2749 		    tbr->PRIM_type != O_T_BIND_REQ);
2750 	}
2751 done:
2752 	if (error > 0) {
2753 		tcp_err_ack(tcp, mp, TSYSERR, error);
2754 	} else if (error < 0) {
2755 		tcp_err_ack(tcp, mp, -error, 0);
2756 	} else {
2757 		/*
2758 		 * Update port information as sockfs/tpi needs it for checking
2759 		 */
2760 		if (connp->conn_family == AF_INET) {
2761 			sin = (sin_t *)sa;
2762 			sin->sin_port = connp->conn_lport;
2763 		} else {
2764 			sin6 = (sin6_t *)sa;
2765 			sin6->sin6_port = connp->conn_lport;
2766 		}
2767 		mp->b_datap->db_type = M_PCPROTO;
2768 		tbr->PRIM_type = T_BIND_ACK;
2769 		putnext(connp->conn_rq, mp);
2770 	}
2771 }
2772 
2773 /*
2774  * If the "bind_to_req_port_only" parameter is set, if the requested port
2775  * number is available, return it, If not return 0
2776  *
2777  * If "bind_to_req_port_only" parameter is not set and
2778  * If the requested port number is available, return it.  If not, return
2779  * the first anonymous port we happen across.  If no anonymous ports are
2780  * available, return 0. addr is the requested local address, if any.
2781  *
2782  * In either case, when succeeding update the tcp_t to record the port number
2783  * and insert it in the bind hash table.
2784  *
2785  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2786  * without setting SO_REUSEADDR. This is needed so that they
2787  * can be viewed as two independent transport protocols.
2788  */
2789 static in_port_t
2790 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2791     int reuseaddr, boolean_t quick_connect,
2792     boolean_t bind_to_req_port_only, boolean_t user_specified)
2793 {
2794 	/* number of times we have run around the loop */
2795 	int count = 0;
2796 	/* maximum number of times to run around the loop */
2797 	int loopmax;
2798 	conn_t *connp = tcp->tcp_connp;
2799 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2800 
2801 	/*
2802 	 * Lookup for free addresses is done in a loop and "loopmax"
2803 	 * influences how long we spin in the loop
2804 	 */
2805 	if (bind_to_req_port_only) {
2806 		/*
2807 		 * If the requested port is busy, don't bother to look
2808 		 * for a new one. Setting loop maximum count to 1 has
2809 		 * that effect.
2810 		 */
2811 		loopmax = 1;
2812 	} else {
2813 		/*
2814 		 * If the requested port is busy, look for a free one
2815 		 * in the anonymous port range.
2816 		 * Set loopmax appropriately so that one does not look
2817 		 * forever in the case all of the anonymous ports are in use.
2818 		 */
2819 		if (connp->conn_anon_priv_bind) {
2820 			/*
2821 			 * loopmax =
2822 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2823 			 */
2824 			loopmax = IPPORT_RESERVED -
2825 			    tcps->tcps_min_anonpriv_port;
2826 		} else {
2827 			loopmax = (tcps->tcps_largest_anon_port -
2828 			    tcps->tcps_smallest_anon_port + 1);
2829 		}
2830 	}
2831 	do {
2832 		uint16_t	lport;
2833 		tf_t		*tbf;
2834 		tcp_t		*ltcp;
2835 		conn_t		*lconnp;
2836 
2837 		lport = htons(port);
2838 
2839 		/*
2840 		 * Ensure that the tcp_t is not currently in the bind hash.
2841 		 * Hold the lock on the hash bucket to ensure that
2842 		 * the duplicate check plus the insertion is an atomic
2843 		 * operation.
2844 		 *
2845 		 * This function does an inline lookup on the bind hash list
2846 		 * Make sure that we access only members of tcp_t
2847 		 * and that we don't look at tcp_tcp, since we are not
2848 		 * doing a CONN_INC_REF.
2849 		 */
2850 		tcp_bind_hash_remove(tcp);
2851 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2852 		mutex_enter(&tbf->tf_lock);
2853 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2854 		    ltcp = ltcp->tcp_bind_hash) {
2855 			if (lport == ltcp->tcp_connp->conn_lport)
2856 				break;
2857 		}
2858 
2859 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2860 			boolean_t not_socket;
2861 			boolean_t exclbind;
2862 
2863 			lconnp = ltcp->tcp_connp;
2864 
2865 			/*
2866 			 * On a labeled system, we must treat bindings to ports
2867 			 * on shared IP addresses by sockets with MAC exemption
2868 			 * privilege as being in all zones, as there's
2869 			 * otherwise no way to identify the right receiver.
2870 			 */
2871 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2872 				continue;
2873 
2874 			/*
2875 			 * If TCP_EXCLBIND is set for either the bound or
2876 			 * binding endpoint, the semantics of bind
2877 			 * is changed according to the following.
2878 			 *
2879 			 * spec = specified address (v4 or v6)
2880 			 * unspec = unspecified address (v4 or v6)
2881 			 * A = specified addresses are different for endpoints
2882 			 *
2883 			 * bound	bind to		allowed
2884 			 * -------------------------------------
2885 			 * unspec	unspec		no
2886 			 * unspec	spec		no
2887 			 * spec		unspec		no
2888 			 * spec		spec		yes if A
2889 			 *
2890 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2891 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2892 			 *
2893 			 * Note:
2894 			 *
2895 			 * 1. Because of TLI semantics, an endpoint can go
2896 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2897 			 * TCPS_BOUND, depending on whether it is originally
2898 			 * a listener or not.  That is why we need to check
2899 			 * for states greater than or equal to TCPS_BOUND
2900 			 * here.
2901 			 *
2902 			 * 2. Ideally, we should only check for state equals
2903 			 * to TCPS_LISTEN. And the following check should be
2904 			 * added.
2905 			 *
2906 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2907 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2908 			 *		...
2909 			 * }
2910 			 *
2911 			 * The semantics will be changed to this.  If the
2912 			 * endpoint on the list is in state not equal to
2913 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2914 			 * set, let the bind succeed.
2915 			 *
2916 			 * Because of (1), we cannot do that for TLI
2917 			 * endpoints.  But we can do that for socket endpoints.
2918 			 * If in future, we can change this going back
2919 			 * semantics, we can use the above check for TLI also.
2920 			 */
2921 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2922 			    TCP_IS_SOCKET(tcp));
2923 			exclbind = lconnp->conn_exclbind ||
2924 			    connp->conn_exclbind;
2925 
2926 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2927 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2928 			    (exclbind && (not_socket ||
2929 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2930 				if (V6_OR_V4_INADDR_ANY(
2931 				    lconnp->conn_bound_addr_v6) ||
2932 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2933 				    IN6_ARE_ADDR_EQUAL(laddr,
2934 				    &lconnp->conn_bound_addr_v6)) {
2935 					break;
2936 				}
2937 				continue;
2938 			}
2939 
2940 			/*
2941 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2942 			 * have disjoint port number spaces, if *_EXCLBIND
2943 			 * is not set and only if the application binds to a
2944 			 * specific port. We use the same autoassigned port
2945 			 * number space for IPv4 and IPv6 sockets.
2946 			 */
2947 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2948 			    bind_to_req_port_only)
2949 				continue;
2950 
2951 			/*
2952 			 * Ideally, we should make sure that the source
2953 			 * address, remote address, and remote port in the
2954 			 * four tuple for this tcp-connection is unique.
2955 			 * However, trying to find out the local source
2956 			 * address would require too much code duplication
2957 			 * with IP, since IP needs needs to have that code
2958 			 * to support userland TCP implementations.
2959 			 */
2960 			if (quick_connect &&
2961 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2962 			    ((connp->conn_fport != lconnp->conn_fport) ||
2963 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2964 			    &lconnp->conn_faddr_v6)))
2965 				continue;
2966 
2967 			if (!reuseaddr) {
2968 				/*
2969 				 * No socket option SO_REUSEADDR.
2970 				 * If existing port is bound to
2971 				 * a non-wildcard IP address
2972 				 * and the requesting stream is
2973 				 * bound to a distinct
2974 				 * different IP addresses
2975 				 * (non-wildcard, also), keep
2976 				 * going.
2977 				 */
2978 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2979 				    !V6_OR_V4_INADDR_ANY(
2980 				    lconnp->conn_bound_addr_v6) &&
2981 				    !IN6_ARE_ADDR_EQUAL(laddr,
2982 				    &lconnp->conn_bound_addr_v6))
2983 					continue;
2984 				if (ltcp->tcp_state >= TCPS_BOUND) {
2985 					/*
2986 					 * This port is being used and
2987 					 * its state is >= TCPS_BOUND,
2988 					 * so we can't bind to it.
2989 					 */
2990 					break;
2991 				}
2992 			} else {
2993 				/*
2994 				 * socket option SO_REUSEADDR is set on the
2995 				 * binding tcp_t.
2996 				 *
2997 				 * If two streams are bound to
2998 				 * same IP address or both addr
2999 				 * and bound source are wildcards
3000 				 * (INADDR_ANY), we want to stop
3001 				 * searching.
3002 				 * We have found a match of IP source
3003 				 * address and source port, which is
3004 				 * refused regardless of the
3005 				 * SO_REUSEADDR setting, so we break.
3006 				 */
3007 				if (IN6_ARE_ADDR_EQUAL(laddr,
3008 				    &lconnp->conn_bound_addr_v6) &&
3009 				    (ltcp->tcp_state == TCPS_LISTEN ||
3010 				    ltcp->tcp_state == TCPS_BOUND))
3011 					break;
3012 			}
3013 		}
3014 		if (ltcp != NULL) {
3015 			/* The port number is busy */
3016 			mutex_exit(&tbf->tf_lock);
3017 		} else {
3018 			/*
3019 			 * This port is ours. Insert in fanout and mark as
3020 			 * bound to prevent others from getting the port
3021 			 * number.
3022 			 */
3023 			tcp->tcp_state = TCPS_BOUND;
3024 			connp->conn_lport = htons(port);
3025 
3026 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3027 			    connp->conn_lport)] == tbf);
3028 			tcp_bind_hash_insert(tbf, tcp, 1);
3029 
3030 			mutex_exit(&tbf->tf_lock);
3031 
3032 			/*
3033 			 * We don't want tcp_next_port_to_try to "inherit"
3034 			 * a port number supplied by the user in a bind.
3035 			 */
3036 			if (user_specified)
3037 				return (port);
3038 
3039 			/*
3040 			 * This is the only place where tcp_next_port_to_try
3041 			 * is updated. After the update, it may or may not
3042 			 * be in the valid range.
3043 			 */
3044 			if (!connp->conn_anon_priv_bind)
3045 				tcps->tcps_next_port_to_try = port + 1;
3046 			return (port);
3047 		}
3048 
3049 		if (connp->conn_anon_priv_bind) {
3050 			port = tcp_get_next_priv_port(tcp);
3051 		} else {
3052 			if (count == 0 && user_specified) {
3053 				/*
3054 				 * We may have to return an anonymous port. So
3055 				 * get one to start with.
3056 				 */
3057 				port =
3058 				    tcp_update_next_port(
3059 				    tcps->tcps_next_port_to_try,
3060 				    tcp, B_TRUE);
3061 				user_specified = B_FALSE;
3062 			} else {
3063 				port = tcp_update_next_port(port + 1, tcp,
3064 				    B_FALSE);
3065 			}
3066 		}
3067 		if (port == 0)
3068 			break;
3069 
3070 		/*
3071 		 * Don't let this loop run forever in the case where
3072 		 * all of the anonymous ports are in use.
3073 		 */
3074 	} while (++count < loopmax);
3075 	return (0);
3076 }
3077 
3078 /*
3079  * tcp_clean_death / tcp_close_detached must not be called more than once
3080  * on a tcp. Thus every function that potentially calls tcp_clean_death
3081  * must check for the tcp state before calling tcp_clean_death.
3082  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
3083  * tcp_timer_handler, all check for the tcp state.
3084  */
3085 /* ARGSUSED */
3086 void
3087 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
3088     ip_recv_attr_t *dummy)
3089 {
3090 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3091 
3092 	freemsg(mp);
3093 	if (tcp->tcp_state > TCPS_BOUND)
3094 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3095 		    ETIMEDOUT, 5);
3096 }
3097 
3098 /*
3099  * We are dying for some reason.  Try to do it gracefully.  (May be called
3100  * as writer.)
3101  *
3102  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3103  * done by a service procedure).
3104  * TBD - Should the return value distinguish between the tcp_t being
3105  * freed and it being reinitialized?
3106  */
3107 static int
3108 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3109 {
3110 	mblk_t	*mp;
3111 	queue_t	*q;
3112 	conn_t	*connp = tcp->tcp_connp;
3113 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3114 
3115 	TCP_CLD_STAT(tag);
3116 
3117 #if TCP_TAG_CLEAN_DEATH
3118 	tcp->tcp_cleandeathtag = tag;
3119 #endif
3120 
3121 	if (tcp->tcp_fused)
3122 		tcp_unfuse(tcp);
3123 
3124 	if (tcp->tcp_linger_tid != 0 &&
3125 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3126 		tcp_stop_lingering(tcp);
3127 	}
3128 
3129 	ASSERT(tcp != NULL);
3130 	ASSERT((connp->conn_family == AF_INET &&
3131 	    connp->conn_ipversion == IPV4_VERSION) ||
3132 	    (connp->conn_family == AF_INET6 &&
3133 	    (connp->conn_ipversion == IPV4_VERSION ||
3134 	    connp->conn_ipversion == IPV6_VERSION)));
3135 
3136 	if (TCP_IS_DETACHED(tcp)) {
3137 		if (tcp->tcp_hard_binding) {
3138 			/*
3139 			 * Its an eager that we are dealing with. We close the
3140 			 * eager but in case a conn_ind has already gone to the
3141 			 * listener, let tcp_accept_finish() send a discon_ind
3142 			 * to the listener and drop the last reference. If the
3143 			 * listener doesn't even know about the eager i.e. the
3144 			 * conn_ind hasn't gone up, blow away the eager and drop
3145 			 * the last reference as well. If the conn_ind has gone
3146 			 * up, state should be BOUND. tcp_accept_finish
3147 			 * will figure out that the connection has received a
3148 			 * RST and will send a DISCON_IND to the application.
3149 			 */
3150 			tcp_closei_local(tcp);
3151 			if (!tcp->tcp_tconnind_started) {
3152 				CONN_DEC_REF(connp);
3153 			} else {
3154 				tcp->tcp_state = TCPS_BOUND;
3155 			}
3156 		} else {
3157 			tcp_close_detached(tcp);
3158 		}
3159 		return (0);
3160 	}
3161 
3162 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3163 
3164 	/*
3165 	 * The connection is dead.  Decrement listener connection counter if
3166 	 * necessary.
3167 	 */
3168 	if (tcp->tcp_listen_cnt != NULL)
3169 		TCP_DECR_LISTEN_CNT(tcp);
3170 
3171 	q = connp->conn_rq;
3172 
3173 	/* Trash all inbound data */
3174 	if (!IPCL_IS_NONSTR(connp)) {
3175 		ASSERT(q != NULL);
3176 		flushq(q, FLUSHALL);
3177 	}
3178 
3179 	/*
3180 	 * If we are at least part way open and there is error
3181 	 * (err==0 implies no error)
3182 	 * notify our client by a T_DISCON_IND.
3183 	 */
3184 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3185 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3186 		    !TCP_IS_SOCKET(tcp)) {
3187 			/*
3188 			 * Send M_FLUSH according to TPI. Because sockets will
3189 			 * (and must) ignore FLUSHR we do that only for TPI
3190 			 * endpoints and sockets in STREAMS mode.
3191 			 */
3192 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3193 		}
3194 		if (connp->conn_debug) {
3195 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3196 			    "tcp_clean_death: discon err %d", err);
3197 		}
3198 		if (IPCL_IS_NONSTR(connp)) {
3199 			/* Direct socket, use upcall */
3200 			(*connp->conn_upcalls->su_disconnected)(
3201 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3202 		} else {
3203 			mp = mi_tpi_discon_ind(NULL, err, 0);
3204 			if (mp != NULL) {
3205 				putnext(q, mp);
3206 			} else {
3207 				if (connp->conn_debug) {
3208 					(void) strlog(TCP_MOD_ID, 0, 1,
3209 					    SL_ERROR|SL_TRACE,
3210 					    "tcp_clean_death, sending M_ERROR");
3211 				}
3212 				(void) putnextctl1(q, M_ERROR, EPROTO);
3213 			}
3214 		}
3215 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3216 			/* SYN_SENT or SYN_RCVD */
3217 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3218 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3219 			/* ESTABLISHED or CLOSE_WAIT */
3220 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3221 		}
3222 	}
3223 
3224 	tcp_reinit(tcp);
3225 	if (IPCL_IS_NONSTR(connp))
3226 		(void) tcp_do_unbind(connp);
3227 
3228 	return (-1);
3229 }
3230 
3231 /*
3232  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3233  * to expire, stop the wait and finish the close.
3234  */
3235 static void
3236 tcp_stop_lingering(tcp_t *tcp)
3237 {
3238 	clock_t	delta = 0;
3239 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3240 	conn_t		*connp = tcp->tcp_connp;
3241 
3242 	tcp->tcp_linger_tid = 0;
3243 	if (tcp->tcp_state > TCPS_LISTEN) {
3244 		tcp_acceptor_hash_remove(tcp);
3245 		mutex_enter(&tcp->tcp_non_sq_lock);
3246 		if (tcp->tcp_flow_stopped) {
3247 			tcp_clrqfull(tcp);
3248 		}
3249 		mutex_exit(&tcp->tcp_non_sq_lock);
3250 
3251 		if (tcp->tcp_timer_tid != 0) {
3252 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3253 			tcp->tcp_timer_tid = 0;
3254 		}
3255 		/*
3256 		 * Need to cancel those timers which will not be used when
3257 		 * TCP is detached.  This has to be done before the conn_wq
3258 		 * is cleared.
3259 		 */
3260 		tcp_timers_stop(tcp);
3261 
3262 		tcp->tcp_detached = B_TRUE;
3263 		connp->conn_rq = NULL;
3264 		connp->conn_wq = NULL;
3265 
3266 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3267 			tcp_time_wait_append(tcp);
3268 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3269 			goto finish;
3270 		}
3271 
3272 		/*
3273 		 * If delta is zero the timer event wasn't executed and was
3274 		 * successfully canceled. In this case we need to restart it
3275 		 * with the minimal delta possible.
3276 		 */
3277 		if (delta >= 0) {
3278 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3279 			    delta ? delta : 1);
3280 		}
3281 	} else {
3282 		tcp_closei_local(tcp);
3283 		CONN_DEC_REF(connp);
3284 	}
3285 finish:
3286 	/* Signal closing thread that it can complete close */
3287 	mutex_enter(&tcp->tcp_closelock);
3288 	tcp->tcp_detached = B_TRUE;
3289 	connp->conn_rq = NULL;
3290 	connp->conn_wq = NULL;
3291 
3292 	tcp->tcp_closed = 1;
3293 	cv_signal(&tcp->tcp_closecv);
3294 	mutex_exit(&tcp->tcp_closelock);
3295 }
3296 
3297 /*
3298  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3299  * expires.
3300  */
3301 static void
3302 tcp_close_linger_timeout(void *arg)
3303 {
3304 	conn_t	*connp = (conn_t *)arg;
3305 	tcp_t 	*tcp = connp->conn_tcp;
3306 
3307 	tcp->tcp_client_errno = ETIMEDOUT;
3308 	tcp_stop_lingering(tcp);
3309 }
3310 
3311 static void
3312 tcp_close_common(conn_t *connp, int flags)
3313 {
3314 	tcp_t		*tcp = connp->conn_tcp;
3315 	mblk_t 		*mp = &tcp->tcp_closemp;
3316 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3317 	mblk_t		*bp;
3318 
3319 	ASSERT(connp->conn_ref >= 2);
3320 
3321 	/*
3322 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3323 	 * add any mp to the pending mp list, after this conn has
3324 	 * started closing.
3325 	 */
3326 	mutex_enter(&connp->conn_lock);
3327 	connp->conn_state_flags |= CONN_CLOSING;
3328 	if (connp->conn_oper_pending_ill != NULL)
3329 		conn_ioctl_cleanup_reqd = B_TRUE;
3330 	CONN_INC_REF_LOCKED(connp);
3331 	mutex_exit(&connp->conn_lock);
3332 	tcp->tcp_closeflags = (uint8_t)flags;
3333 	ASSERT(connp->conn_ref >= 3);
3334 
3335 	/*
3336 	 * tcp_closemp_used is used below without any protection of a lock
3337 	 * as we don't expect any one else to use it concurrently at this
3338 	 * point otherwise it would be a major defect.
3339 	 */
3340 
3341 	if (mp->b_prev == NULL)
3342 		tcp->tcp_closemp_used = B_TRUE;
3343 	else
3344 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3345 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3346 
3347 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3348 
3349 	/*
3350 	 * Cleanup any queued ioctls here. This must be done before the wq/rq
3351 	 * are re-written by tcp_close_output().
3352 	 */
3353 	if (conn_ioctl_cleanup_reqd)
3354 		conn_ioctl_cleanup(connp);
3355 
3356 	/*
3357 	 * As CONN_CLOSING is set, no further ioctls should be passed down to
3358 	 * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
3359 	 * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
3360 	 * conn_ioctl_cleanup should have found it and removed it. If the ioctl
3361 	 * was still in flight at the time, we wait for it here. See comments
3362 	 * for CONN_INC_IOCTLREF in ip.h for details.
3363 	 */
3364 	mutex_enter(&connp->conn_lock);
3365 	while (connp->conn_ioctlref > 0)
3366 		cv_wait(&connp->conn_cv, &connp->conn_lock);
3367 	ASSERT(connp->conn_ioctlref == 0);
3368 	ASSERT(connp->conn_oper_pending_ill == NULL);
3369 	mutex_exit(&connp->conn_lock);
3370 
3371 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3372 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3373 
3374 	mutex_enter(&tcp->tcp_closelock);
3375 	while (!tcp->tcp_closed) {
3376 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3377 			/*
3378 			 * The cv_wait_sig() was interrupted. We now do the
3379 			 * following:
3380 			 *
3381 			 * 1) If the endpoint was lingering, we allow this
3382 			 * to be interrupted by cancelling the linger timeout
3383 			 * and closing normally.
3384 			 *
3385 			 * 2) Revert to calling cv_wait()
3386 			 *
3387 			 * We revert to using cv_wait() to avoid an
3388 			 * infinite loop which can occur if the calling
3389 			 * thread is higher priority than the squeue worker
3390 			 * thread and is bound to the same cpu.
3391 			 */
3392 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3393 				mutex_exit(&tcp->tcp_closelock);
3394 				/* Entering squeue, bump ref count. */
3395 				CONN_INC_REF(connp);
3396 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3397 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3398 				    tcp_linger_interrupted, connp, NULL,
3399 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3400 				mutex_enter(&tcp->tcp_closelock);
3401 			}
3402 			break;
3403 		}
3404 	}
3405 	while (!tcp->tcp_closed)
3406 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3407 	mutex_exit(&tcp->tcp_closelock);
3408 
3409 	/*
3410 	 * In the case of listener streams that have eagers in the q or q0
3411 	 * we wait for the eagers to drop their reference to us. conn_rq and
3412 	 * conn_wq of the eagers point to our queues. By waiting for the
3413 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3414 	 * up their queue pointers and also dropped their references to us.
3415 	 */
3416 	if (tcp->tcp_wait_for_eagers) {
3417 		mutex_enter(&connp->conn_lock);
3418 		while (connp->conn_ref != 1) {
3419 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3420 		}
3421 		mutex_exit(&connp->conn_lock);
3422 	}
3423 
3424 	connp->conn_cpid = NOPID;
3425 }
3426 
3427 static int
3428 tcp_tpi_close(queue_t *q, int flags)
3429 {
3430 	conn_t		*connp;
3431 
3432 	ASSERT(WR(q)->q_next == NULL);
3433 
3434 	if (flags & SO_FALLBACK) {
3435 		/*
3436 		 * stream is being closed while in fallback
3437 		 * simply free the resources that were allocated
3438 		 */
3439 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3440 		qprocsoff(q);
3441 		goto done;
3442 	}
3443 
3444 	connp = Q_TO_CONN(q);
3445 	/*
3446 	 * We are being closed as /dev/tcp or /dev/tcp6.
3447 	 */
3448 	tcp_close_common(connp, flags);
3449 
3450 	qprocsoff(q);
3451 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3452 
3453 	/*
3454 	 * Drop IP's reference on the conn. This is the last reference
3455 	 * on the connp if the state was less than established. If the
3456 	 * connection has gone into timewait state, then we will have
3457 	 * one ref for the TCP and one more ref (total of two) for the
3458 	 * classifier connected hash list (a timewait connections stays
3459 	 * in connected hash till closed).
3460 	 *
3461 	 * We can't assert the references because there might be other
3462 	 * transient reference places because of some walkers or queued
3463 	 * packets in squeue for the timewait state.
3464 	 */
3465 	CONN_DEC_REF(connp);
3466 done:
3467 	q->q_ptr = WR(q)->q_ptr = NULL;
3468 	return (0);
3469 }
3470 
3471 static int
3472 tcp_tpi_close_accept(queue_t *q)
3473 {
3474 	vmem_t	*minor_arena;
3475 	dev_t	conn_dev;
3476 
3477 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3478 
3479 	/*
3480 	 * We had opened an acceptor STREAM for sockfs which is
3481 	 * now being closed due to some error.
3482 	 */
3483 	qprocsoff(q);
3484 
3485 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3486 	conn_dev = (dev_t)RD(q)->q_ptr;
3487 	ASSERT(minor_arena != NULL);
3488 	ASSERT(conn_dev != 0);
3489 	inet_minor_free(minor_arena, conn_dev);
3490 	q->q_ptr = WR(q)->q_ptr = NULL;
3491 	return (0);
3492 }
3493 
3494 /*
3495  * Called by tcp_close() routine via squeue when lingering is
3496  * interrupted by a signal.
3497  */
3498 
3499 /* ARGSUSED */
3500 static void
3501 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3502 {
3503 	conn_t	*connp = (conn_t *)arg;
3504 	tcp_t	*tcp = connp->conn_tcp;
3505 
3506 	freeb(mp);
3507 	if (tcp->tcp_linger_tid != 0 &&
3508 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3509 		tcp_stop_lingering(tcp);
3510 		tcp->tcp_client_errno = EINTR;
3511 	}
3512 }
3513 
3514 /*
3515  * Called by streams close routine via squeues when our client blows off her
3516  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3517  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3518  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3519  * acked.
3520  *
3521  * NOTE: tcp_close potentially returns error when lingering.
3522  * However, the stream head currently does not pass these errors
3523  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3524  * errors to the application (from tsleep()) and not errors
3525  * like ECONNRESET caused by receiving a reset packet.
3526  */
3527 
3528 /* ARGSUSED */
3529 static void
3530 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3531 {
3532 	char	*msg;
3533 	conn_t	*connp = (conn_t *)arg;
3534 	tcp_t	*tcp = connp->conn_tcp;
3535 	clock_t	delta = 0;
3536 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3537 
3538 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3539 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3540 
3541 	mutex_enter(&tcp->tcp_eager_lock);
3542 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3543 		/* Cleanup for listener */
3544 		tcp_eager_cleanup(tcp, 0);
3545 		tcp->tcp_wait_for_eagers = 1;
3546 	}
3547 	mutex_exit(&tcp->tcp_eager_lock);
3548 
3549 	tcp->tcp_lso = B_FALSE;
3550 
3551 	msg = NULL;
3552 	switch (tcp->tcp_state) {
3553 	case TCPS_CLOSED:
3554 	case TCPS_IDLE:
3555 	case TCPS_BOUND:
3556 	case TCPS_LISTEN:
3557 		break;
3558 	case TCPS_SYN_SENT:
3559 		msg = "tcp_close, during connect";
3560 		break;
3561 	case TCPS_SYN_RCVD:
3562 		/*
3563 		 * Close during the connect 3-way handshake
3564 		 * but here there may or may not be pending data
3565 		 * already on queue. Process almost same as in
3566 		 * the ESTABLISHED state.
3567 		 */
3568 		/* FALLTHRU */
3569 	default:
3570 		if (tcp->tcp_fused)
3571 			tcp_unfuse(tcp);
3572 
3573 		/*
3574 		 * If SO_LINGER has set a zero linger time, abort the
3575 		 * connection with a reset.
3576 		 */
3577 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3578 			msg = "tcp_close, zero lingertime";
3579 			break;
3580 		}
3581 
3582 		/*
3583 		 * Abort connection if there is unread data queued.
3584 		 */
3585 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3586 			msg = "tcp_close, unread data";
3587 			break;
3588 		}
3589 		/*
3590 		 * We have done a qwait() above which could have possibly
3591 		 * drained more messages in turn causing transition to a
3592 		 * different state. Check whether we have to do the rest
3593 		 * of the processing or not.
3594 		 */
3595 		if (tcp->tcp_state <= TCPS_LISTEN)
3596 			break;
3597 
3598 		/*
3599 		 * Transmit the FIN before detaching the tcp_t.
3600 		 * After tcp_detach returns this queue/perimeter
3601 		 * no longer owns the tcp_t thus others can modify it.
3602 		 */
3603 		(void) tcp_xmit_end(tcp);
3604 
3605 		/*
3606 		 * If lingering on close then wait until the fin is acked,
3607 		 * the SO_LINGER time passes, or a reset is sent/received.
3608 		 */
3609 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3610 		    !(tcp->tcp_fin_acked) &&
3611 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3612 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3613 				tcp->tcp_client_errno = EWOULDBLOCK;
3614 			} else if (tcp->tcp_client_errno == 0) {
3615 
3616 				ASSERT(tcp->tcp_linger_tid == 0);
3617 
3618 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3619 				    tcp_close_linger_timeout,
3620 				    connp->conn_lingertime * hz);
3621 
3622 				/* tcp_close_linger_timeout will finish close */
3623 				if (tcp->tcp_linger_tid == 0)
3624 					tcp->tcp_client_errno = ENOSR;
3625 				else
3626 					return;
3627 			}
3628 
3629 			/*
3630 			 * Check if we need to detach or just close
3631 			 * the instance.
3632 			 */
3633 			if (tcp->tcp_state <= TCPS_LISTEN)
3634 				break;
3635 		}
3636 
3637 		/*
3638 		 * Make sure that no other thread will access the conn_rq of
3639 		 * this instance (through lookups etc.) as conn_rq will go
3640 		 * away shortly.
3641 		 */
3642 		tcp_acceptor_hash_remove(tcp);
3643 
3644 		mutex_enter(&tcp->tcp_non_sq_lock);
3645 		if (tcp->tcp_flow_stopped) {
3646 			tcp_clrqfull(tcp);
3647 		}
3648 		mutex_exit(&tcp->tcp_non_sq_lock);
3649 
3650 		if (tcp->tcp_timer_tid != 0) {
3651 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3652 			tcp->tcp_timer_tid = 0;
3653 		}
3654 		/*
3655 		 * Need to cancel those timers which will not be used when
3656 		 * TCP is detached.  This has to be done before the conn_wq
3657 		 * is set to NULL.
3658 		 */
3659 		tcp_timers_stop(tcp);
3660 
3661 		tcp->tcp_detached = B_TRUE;
3662 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3663 			tcp_time_wait_append(tcp);
3664 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3665 			ASSERT(connp->conn_ref >= 3);
3666 			goto finish;
3667 		}
3668 
3669 		/*
3670 		 * If delta is zero the timer event wasn't executed and was
3671 		 * successfully canceled. In this case we need to restart it
3672 		 * with the minimal delta possible.
3673 		 */
3674 		if (delta >= 0)
3675 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3676 			    delta ? delta : 1);
3677 
3678 		ASSERT(connp->conn_ref >= 3);
3679 		goto finish;
3680 	}
3681 
3682 	/* Detach did not complete. Still need to remove q from stream. */
3683 	if (msg) {
3684 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3685 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3686 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3687 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3688 		    tcp->tcp_state == TCPS_SYN_RCVD)
3689 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3690 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3691 	}
3692 
3693 	tcp_closei_local(tcp);
3694 	CONN_DEC_REF(connp);
3695 	ASSERT(connp->conn_ref >= 2);
3696 
3697 finish:
3698 	mutex_enter(&tcp->tcp_closelock);
3699 	/*
3700 	 * Don't change the queues in the case of a listener that has
3701 	 * eagers in its q or q0. It could surprise the eagers.
3702 	 * Instead wait for the eagers outside the squeue.
3703 	 */
3704 	if (!tcp->tcp_wait_for_eagers) {
3705 		tcp->tcp_detached = B_TRUE;
3706 		connp->conn_rq = NULL;
3707 		connp->conn_wq = NULL;
3708 	}
3709 
3710 	/* Signal tcp_close() to finish closing. */
3711 	tcp->tcp_closed = 1;
3712 	cv_signal(&tcp->tcp_closecv);
3713 	mutex_exit(&tcp->tcp_closelock);
3714 }
3715 
3716 /*
3717  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3718  * Some stream heads get upset if they see these later on as anything but NULL.
3719  */
3720 static void
3721 tcp_close_mpp(mblk_t **mpp)
3722 {
3723 	mblk_t	*mp;
3724 
3725 	if ((mp = *mpp) != NULL) {
3726 		do {
3727 			mp->b_next = NULL;
3728 			mp->b_prev = NULL;
3729 		} while ((mp = mp->b_cont) != NULL);
3730 
3731 		mp = *mpp;
3732 		*mpp = NULL;
3733 		freemsg(mp);
3734 	}
3735 }
3736 
3737 /* Do detached close. */
3738 static void
3739 tcp_close_detached(tcp_t *tcp)
3740 {
3741 	if (tcp->tcp_fused)
3742 		tcp_unfuse(tcp);
3743 
3744 	/*
3745 	 * Clustering code serializes TCP disconnect callbacks and
3746 	 * cluster tcp list walks by blocking a TCP disconnect callback
3747 	 * if a cluster tcp list walk is in progress. This ensures
3748 	 * accurate accounting of TCPs in the cluster code even though
3749 	 * the TCP list walk itself is not atomic.
3750 	 */
3751 	tcp_closei_local(tcp);
3752 	CONN_DEC_REF(tcp->tcp_connp);
3753 }
3754 
3755 /*
3756  * Stop all TCP timers, and free the timer mblks if requested.
3757  */
3758 void
3759 tcp_timers_stop(tcp_t *tcp)
3760 {
3761 	if (tcp->tcp_timer_tid != 0) {
3762 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3763 		tcp->tcp_timer_tid = 0;
3764 	}
3765 	if (tcp->tcp_ka_tid != 0) {
3766 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3767 		tcp->tcp_ka_tid = 0;
3768 	}
3769 	if (tcp->tcp_ack_tid != 0) {
3770 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3771 		tcp->tcp_ack_tid = 0;
3772 	}
3773 	if (tcp->tcp_push_tid != 0) {
3774 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3775 		tcp->tcp_push_tid = 0;
3776 	}
3777 	if (tcp->tcp_reass_tid != 0) {
3778 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
3779 		tcp->tcp_reass_tid = 0;
3780 	}
3781 }
3782 
3783 /*
3784  * The tcp_t is going away. Remove it from all lists and set it
3785  * to TCPS_CLOSED. The freeing up of memory is deferred until
3786  * tcp_inactive. This is needed since a thread in tcp_rput might have
3787  * done a CONN_INC_REF on this structure before it was removed from the
3788  * hashes.
3789  */
3790 static void
3791 tcp_closei_local(tcp_t *tcp)
3792 {
3793 	conn_t		*connp = tcp->tcp_connp;
3794 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3795 
3796 	if (!TCP_IS_SOCKET(tcp))
3797 		tcp_acceptor_hash_remove(tcp);
3798 
3799 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3800 	tcp->tcp_ibsegs = 0;
3801 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3802 	tcp->tcp_obsegs = 0;
3803 
3804 	/*
3805 	 * If we are an eager connection hanging off a listener that
3806 	 * hasn't formally accepted the connection yet, get off his
3807 	 * list and blow off any data that we have accumulated.
3808 	 */
3809 	if (tcp->tcp_listener != NULL) {
3810 		tcp_t	*listener = tcp->tcp_listener;
3811 		mutex_enter(&listener->tcp_eager_lock);
3812 		/*
3813 		 * tcp_tconnind_started == B_TRUE means that the
3814 		 * conn_ind has already gone to listener. At
3815 		 * this point, eager will be closed but we
3816 		 * leave it in listeners eager list so that
3817 		 * if listener decides to close without doing
3818 		 * accept, we can clean this up. In tcp_tli_accept
3819 		 * we take care of the case of accept on closed
3820 		 * eager.
3821 		 */
3822 		if (!tcp->tcp_tconnind_started) {
3823 			tcp_eager_unlink(tcp);
3824 			mutex_exit(&listener->tcp_eager_lock);
3825 			/*
3826 			 * We don't want to have any pointers to the
3827 			 * listener queue, after we have released our
3828 			 * reference on the listener
3829 			 */
3830 			ASSERT(tcp->tcp_detached);
3831 			connp->conn_rq = NULL;
3832 			connp->conn_wq = NULL;
3833 			CONN_DEC_REF(listener->tcp_connp);
3834 		} else {
3835 			mutex_exit(&listener->tcp_eager_lock);
3836 		}
3837 	}
3838 
3839 	/* Stop all the timers */
3840 	tcp_timers_stop(tcp);
3841 
3842 	if (tcp->tcp_state == TCPS_LISTEN) {
3843 		if (tcp->tcp_ip_addr_cache) {
3844 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3845 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3846 			tcp->tcp_ip_addr_cache = NULL;
3847 		}
3848 	}
3849 
3850 	/* Decrement listerner connection counter if necessary. */
3851 	if (tcp->tcp_listen_cnt != NULL)
3852 		TCP_DECR_LISTEN_CNT(tcp);
3853 
3854 	mutex_enter(&tcp->tcp_non_sq_lock);
3855 	if (tcp->tcp_flow_stopped)
3856 		tcp_clrqfull(tcp);
3857 	mutex_exit(&tcp->tcp_non_sq_lock);
3858 
3859 	tcp_bind_hash_remove(tcp);
3860 	/*
3861 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3862 	 * is trying to remove this tcp from the time wait list, we will
3863 	 * block in tcp_time_wait_remove while trying to acquire the
3864 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3865 	 * requires the ipcl_hash_remove to be ordered after the
3866 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3867 	 */
3868 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3869 		(void) tcp_time_wait_remove(tcp, NULL);
3870 	CL_INET_DISCONNECT(connp);
3871 	ipcl_hash_remove(connp);
3872 	ixa_cleanup(connp->conn_ixa);
3873 
3874 	/*
3875 	 * Mark the conn as CONDEMNED
3876 	 */
3877 	mutex_enter(&connp->conn_lock);
3878 	connp->conn_state_flags |= CONN_CONDEMNED;
3879 	mutex_exit(&connp->conn_lock);
3880 
3881 	ASSERT(tcp->tcp_time_wait_next == NULL);
3882 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3883 	ASSERT(tcp->tcp_time_wait_expire == 0);
3884 	tcp->tcp_state = TCPS_CLOSED;
3885 
3886 	/* Release any SSL context */
3887 	if (tcp->tcp_kssl_ent != NULL) {
3888 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3889 		tcp->tcp_kssl_ent = NULL;
3890 	}
3891 	if (tcp->tcp_kssl_ctx != NULL) {
3892 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3893 		tcp->tcp_kssl_ctx = NULL;
3894 	}
3895 	tcp->tcp_kssl_pending = B_FALSE;
3896 
3897 	tcp_ipsec_cleanup(tcp);
3898 }
3899 
3900 /*
3901  * tcp is dying (called from ipcl_conn_destroy and error cases).
3902  * Free the tcp_t in either case.
3903  */
3904 void
3905 tcp_free(tcp_t *tcp)
3906 {
3907 	mblk_t		*mp;
3908 	conn_t		*connp = tcp->tcp_connp;
3909 
3910 	ASSERT(tcp != NULL);
3911 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3912 
3913 	connp->conn_rq = NULL;
3914 	connp->conn_wq = NULL;
3915 
3916 	tcp_close_mpp(&tcp->tcp_xmit_head);
3917 	tcp_close_mpp(&tcp->tcp_reass_head);
3918 	if (tcp->tcp_rcv_list != NULL) {
3919 		/* Free b_next chain */
3920 		tcp_close_mpp(&tcp->tcp_rcv_list);
3921 	}
3922 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3923 		freemsg(mp);
3924 	}
3925 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3926 		freemsg(mp);
3927 	}
3928 
3929 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3930 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3931 		freeb(tcp->tcp_fused_sigurg_mp);
3932 		tcp->tcp_fused_sigurg_mp = NULL;
3933 	}
3934 
3935 	if (tcp->tcp_ordrel_mp != NULL) {
3936 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3937 		freeb(tcp->tcp_ordrel_mp);
3938 		tcp->tcp_ordrel_mp = NULL;
3939 	}
3940 
3941 	if (tcp->tcp_sack_info != NULL) {
3942 		if (tcp->tcp_notsack_list != NULL) {
3943 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3944 			    tcp);
3945 		}
3946 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3947 	}
3948 
3949 	if (tcp->tcp_hopopts != NULL) {
3950 		mi_free(tcp->tcp_hopopts);
3951 		tcp->tcp_hopopts = NULL;
3952 		tcp->tcp_hopoptslen = 0;
3953 	}
3954 	ASSERT(tcp->tcp_hopoptslen == 0);
3955 	if (tcp->tcp_dstopts != NULL) {
3956 		mi_free(tcp->tcp_dstopts);
3957 		tcp->tcp_dstopts = NULL;
3958 		tcp->tcp_dstoptslen = 0;
3959 	}
3960 	ASSERT(tcp->tcp_dstoptslen == 0);
3961 	if (tcp->tcp_rthdrdstopts != NULL) {
3962 		mi_free(tcp->tcp_rthdrdstopts);
3963 		tcp->tcp_rthdrdstopts = NULL;
3964 		tcp->tcp_rthdrdstoptslen = 0;
3965 	}
3966 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3967 	if (tcp->tcp_rthdr != NULL) {
3968 		mi_free(tcp->tcp_rthdr);
3969 		tcp->tcp_rthdr = NULL;
3970 		tcp->tcp_rthdrlen = 0;
3971 	}
3972 	ASSERT(tcp->tcp_rthdrlen == 0);
3973 
3974 	/*
3975 	 * Following is really a blowing away a union.
3976 	 * It happens to have exactly two members of identical size
3977 	 * the following code is enough.
3978 	 */
3979 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3980 }
3981 
3982 
3983 /*
3984  * Put a connection confirmation message upstream built from the
3985  * address/flowid information with the conn and iph. Report our success or
3986  * failure.
3987  */
3988 static boolean_t
3989 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3990     mblk_t **defermp, ip_recv_attr_t *ira)
3991 {
3992 	sin_t	sin;
3993 	sin6_t	sin6;
3994 	mblk_t	*mp;
3995 	char	*optp = NULL;
3996 	int	optlen = 0;
3997 	conn_t	*connp = tcp->tcp_connp;
3998 
3999 	if (defermp != NULL)
4000 		*defermp = NULL;
4001 
4002 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4003 		/*
4004 		 * Return in T_CONN_CON results of option negotiation through
4005 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4006 		 * negotiation, then what is received from remote end needs
4007 		 * to be taken into account but there is no such thing (yet?)
4008 		 * in our TCP/IP.
4009 		 * Note: We do not use mi_offset_param() here as
4010 		 * tcp_opts_conn_req contents do not directly come from
4011 		 * an application and are either generated in kernel or
4012 		 * from user input that was already verified.
4013 		 */
4014 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4015 		optp = (char *)(mp->b_rptr +
4016 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4017 		optlen = (int)
4018 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4019 	}
4020 
4021 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4022 
4023 		/* packet is IPv4 */
4024 		if (connp->conn_family == AF_INET) {
4025 			sin = sin_null;
4026 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
4027 			sin.sin_port = connp->conn_fport;
4028 			sin.sin_family = AF_INET;
4029 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4030 			    (int)sizeof (sin_t), optp, optlen);
4031 		} else {
4032 			sin6 = sin6_null;
4033 			sin6.sin6_addr = connp->conn_faddr_v6;
4034 			sin6.sin6_port = connp->conn_fport;
4035 			sin6.sin6_family = AF_INET6;
4036 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4037 			    (int)sizeof (sin6_t), optp, optlen);
4038 
4039 		}
4040 	} else {
4041 		ip6_t	*ip6h = (ip6_t *)iphdr;
4042 
4043 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4044 		ASSERT(connp->conn_family == AF_INET6);
4045 		sin6 = sin6_null;
4046 		sin6.sin6_addr = connp->conn_faddr_v6;
4047 		sin6.sin6_port = connp->conn_fport;
4048 		sin6.sin6_family = AF_INET6;
4049 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4050 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4051 		    (int)sizeof (sin6_t), optp, optlen);
4052 	}
4053 
4054 	if (!mp)
4055 		return (B_FALSE);
4056 
4057 	mblk_copycred(mp, idmp);
4058 
4059 	if (defermp == NULL) {
4060 		conn_t *connp = tcp->tcp_connp;
4061 		if (IPCL_IS_NONSTR(connp)) {
4062 			(*connp->conn_upcalls->su_connected)
4063 			    (connp->conn_upper_handle, tcp->tcp_connid,
4064 			    ira->ira_cred, ira->ira_cpid);
4065 			freemsg(mp);
4066 		} else {
4067 			if (ira->ira_cred != NULL) {
4068 				/* So that getpeerucred works for TPI sockfs */
4069 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
4070 			}
4071 			putnext(connp->conn_rq, mp);
4072 		}
4073 	} else {
4074 		*defermp = mp;
4075 	}
4076 
4077 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4078 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4079 	return (B_TRUE);
4080 }
4081 
4082 /*
4083  * Defense for the SYN attack -
4084  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4085  *    one from the list of droppable eagers. This list is a subset of q0.
4086  *    see comments before the definition of MAKE_DROPPABLE().
4087  * 2. Don't drop a SYN request before its first timeout. This gives every
4088  *    request at least til the first timeout to complete its 3-way handshake.
4089  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4090  *    requests currently on the queue that has timed out. This will be used
4091  *    as an indicator of whether an attack is under way, so that appropriate
4092  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4093  *    either when eager goes into ESTABLISHED, or gets freed up.)
4094  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4095  *    # of timeout drops back to <= q0len/32 => SYN alert off
4096  */
4097 static boolean_t
4098 tcp_drop_q0(tcp_t *tcp)
4099 {
4100 	tcp_t	*eager;
4101 	mblk_t	*mp;
4102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4103 
4104 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4105 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4106 
4107 	/* Pick oldest eager from the list of droppable eagers */
4108 	eager = tcp->tcp_eager_prev_drop_q0;
4109 
4110 	/* If list is empty. return B_FALSE */
4111 	if (eager == tcp) {
4112 		return (B_FALSE);
4113 	}
4114 
4115 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4116 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4117 		return (B_FALSE);
4118 
4119 	/*
4120 	 * Take this eager out from the list of droppable eagers since we are
4121 	 * going to drop it.
4122 	 */
4123 	MAKE_UNDROPPABLE(eager);
4124 
4125 	if (tcp->tcp_connp->conn_debug) {
4126 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4127 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4128 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4129 		    tcp->tcp_conn_req_cnt_q0,
4130 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4131 	}
4132 
4133 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4134 
4135 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4136 	CONN_INC_REF(eager->tcp_connp);
4137 
4138 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4139 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
4140 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4141 
4142 	return (B_TRUE);
4143 }
4144 
4145 /*
4146  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4147  */
4148 static mblk_t *
4149 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4150     ip_recv_attr_t *ira)
4151 {
4152 	tcp_t 		*ltcp = lconnp->conn_tcp;
4153 	tcp_t		*tcp = connp->conn_tcp;
4154 	mblk_t		*tpi_mp;
4155 	ipha_t		*ipha;
4156 	ip6_t		*ip6h;
4157 	sin6_t 		sin6;
4158 	uint_t		ifindex = ira->ira_ruifindex;
4159 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4160 
4161 	if (ira->ira_flags & IRAF_IS_IPV4) {
4162 		ipha = (ipha_t *)mp->b_rptr;
4163 
4164 		connp->conn_ipversion = IPV4_VERSION;
4165 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4166 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4167 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4168 
4169 		sin6 = sin6_null;
4170 		sin6.sin6_addr = connp->conn_faddr_v6;
4171 		sin6.sin6_port = connp->conn_fport;
4172 		sin6.sin6_family = AF_INET6;
4173 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4174 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4175 
4176 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4177 			sin6_t	sin6d;
4178 
4179 			sin6d = sin6_null;
4180 			sin6d.sin6_addr = connp->conn_laddr_v6;
4181 			sin6d.sin6_port = connp->conn_lport;
4182 			sin6d.sin6_family = AF_INET;
4183 			tpi_mp = mi_tpi_extconn_ind(NULL,
4184 			    (char *)&sin6d, sizeof (sin6_t),
4185 			    (char *)&tcp,
4186 			    (t_scalar_t)sizeof (intptr_t),
4187 			    (char *)&sin6d, sizeof (sin6_t),
4188 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4189 		} else {
4190 			tpi_mp = mi_tpi_conn_ind(NULL,
4191 			    (char *)&sin6, sizeof (sin6_t),
4192 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4193 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4194 		}
4195 	} else {
4196 		ip6h = (ip6_t *)mp->b_rptr;
4197 
4198 		connp->conn_ipversion = IPV6_VERSION;
4199 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4200 		connp->conn_faddr_v6 = ip6h->ip6_src;
4201 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4202 
4203 		sin6 = sin6_null;
4204 		sin6.sin6_addr = connp->conn_faddr_v6;
4205 		sin6.sin6_port = connp->conn_fport;
4206 		sin6.sin6_family = AF_INET6;
4207 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4208 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4209 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4210 
4211 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4212 			/* Pass up the scope_id of remote addr */
4213 			sin6.sin6_scope_id = ifindex;
4214 		} else {
4215 			sin6.sin6_scope_id = 0;
4216 		}
4217 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4218 			sin6_t	sin6d;
4219 
4220 			sin6d = sin6_null;
4221 			sin6.sin6_addr = connp->conn_laddr_v6;
4222 			sin6d.sin6_port = connp->conn_lport;
4223 			sin6d.sin6_family = AF_INET6;
4224 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4225 				sin6d.sin6_scope_id = ifindex;
4226 
4227 			tpi_mp = mi_tpi_extconn_ind(NULL,
4228 			    (char *)&sin6d, sizeof (sin6_t),
4229 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4230 			    (char *)&sin6d, sizeof (sin6_t),
4231 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4232 		} else {
4233 			tpi_mp = mi_tpi_conn_ind(NULL,
4234 			    (char *)&sin6, sizeof (sin6_t),
4235 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4236 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4237 		}
4238 	}
4239 
4240 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4241 	return (tpi_mp);
4242 }
4243 
4244 /* Handle a SYN on an AF_INET socket */
4245 mblk_t *
4246 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4247     ip_recv_attr_t *ira)
4248 {
4249 	tcp_t 		*ltcp = lconnp->conn_tcp;
4250 	tcp_t		*tcp = connp->conn_tcp;
4251 	sin_t		sin;
4252 	mblk_t		*tpi_mp = NULL;
4253 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4254 	ipha_t		*ipha;
4255 
4256 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4257 	ipha = (ipha_t *)mp->b_rptr;
4258 
4259 	connp->conn_ipversion = IPV4_VERSION;
4260 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4261 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4262 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4263 
4264 	sin = sin_null;
4265 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4266 	sin.sin_port = connp->conn_fport;
4267 	sin.sin_family = AF_INET;
4268 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4269 		sin_t	sind;
4270 
4271 		sind = sin_null;
4272 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4273 		sind.sin_port = connp->conn_lport;
4274 		sind.sin_family = AF_INET;
4275 		tpi_mp = mi_tpi_extconn_ind(NULL,
4276 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4277 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4278 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4279 	} else {
4280 		tpi_mp = mi_tpi_conn_ind(NULL,
4281 		    (char *)&sin, sizeof (sin_t),
4282 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4283 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4284 	}
4285 
4286 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4287 	return (tpi_mp);
4288 }
4289 
4290 /*
4291  * tcp_get_conn/tcp_free_conn
4292  *
4293  * tcp_get_conn is used to get a clean tcp connection structure.
4294  * It tries to reuse the connections put on the freelist by the
4295  * time_wait_collector failing which it goes to kmem_cache. This
4296  * way has two benefits compared to just allocating from and
4297  * freeing to kmem_cache.
4298  * 1) The time_wait_collector can free (which includes the cleanup)
4299  * outside the squeue. So when the interrupt comes, we have a clean
4300  * connection sitting in the freelist. Obviously, this buys us
4301  * performance.
4302  *
4303  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4304  * has multiple disadvantages - tying up the squeue during alloc.
4305  * But allocating the conn/tcp in IP land is also not the best since
4306  * we can't check the 'q' and 'q0' which are protected by squeue and
4307  * blindly allocate memory which might have to be freed here if we are
4308  * not allowed to accept the connection. By using the freelist and
4309  * putting the conn/tcp back in freelist, we don't pay a penalty for
4310  * allocating memory without checking 'q/q0' and freeing it if we can't
4311  * accept the connection.
4312  *
4313  * Care should be taken to put the conn back in the same squeue's freelist
4314  * from which it was allocated. Best results are obtained if conn is
4315  * allocated from listener's squeue and freed to the same. Time wait
4316  * collector will free up the freelist is the connection ends up sitting
4317  * there for too long.
4318  */
4319 void *
4320 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4321 {
4322 	tcp_t			*tcp = NULL;
4323 	conn_t			*connp = NULL;
4324 	squeue_t		*sqp = (squeue_t *)arg;
4325 	tcp_squeue_priv_t 	*tcp_time_wait;
4326 	netstack_t		*ns;
4327 	mblk_t			*tcp_rsrv_mp = NULL;
4328 
4329 	tcp_time_wait =
4330 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4331 
4332 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4333 	tcp = tcp_time_wait->tcp_free_list;
4334 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4335 	if (tcp != NULL) {
4336 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4337 		tcp_time_wait->tcp_free_list_cnt--;
4338 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4339 		tcp->tcp_time_wait_next = NULL;
4340 		connp = tcp->tcp_connp;
4341 		connp->conn_flags |= IPCL_REUSED;
4342 
4343 		ASSERT(tcp->tcp_tcps == NULL);
4344 		ASSERT(connp->conn_netstack == NULL);
4345 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4346 		ns = tcps->tcps_netstack;
4347 		netstack_hold(ns);
4348 		connp->conn_netstack = ns;
4349 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4350 		tcp->tcp_tcps = tcps;
4351 		ipcl_globalhash_insert(connp);
4352 
4353 		connp->conn_ixa->ixa_notify_cookie = tcp;
4354 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4355 		connp->conn_recv = tcp_input_data;
4356 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4357 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4358 		return ((void *)connp);
4359 	}
4360 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4361 	/*
4362 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4363 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4364 	 */
4365 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4366 	if (tcp_rsrv_mp == NULL)
4367 		return (NULL);
4368 
4369 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4370 	    tcps->tcps_netstack)) == NULL) {
4371 		freeb(tcp_rsrv_mp);
4372 		return (NULL);
4373 	}
4374 
4375 	tcp = connp->conn_tcp;
4376 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4377 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4378 
4379 	tcp->tcp_tcps = tcps;
4380 
4381 	connp->conn_recv = tcp_input_data;
4382 	connp->conn_recvicmp = tcp_icmp_input;
4383 	connp->conn_verifyicmp = tcp_verifyicmp;
4384 
4385 	/*
4386 	 * Register tcp_notify to listen to capability changes detected by IP.
4387 	 * This upcall is made in the context of the call to conn_ip_output
4388 	 * thus it is inside the squeue.
4389 	 */
4390 	connp->conn_ixa->ixa_notify = tcp_notify;
4391 	connp->conn_ixa->ixa_notify_cookie = tcp;
4392 
4393 	return ((void *)connp);
4394 }
4395 
4396 /* BEGIN CSTYLED */
4397 /*
4398  *
4399  * The sockfs ACCEPT path:
4400  * =======================
4401  *
4402  * The eager is now established in its own perimeter as soon as SYN is
4403  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4404  * completes the accept processing on the acceptor STREAM. The sending
4405  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4406  * listener but a TLI/XTI listener completes the accept processing
4407  * on the listener perimeter.
4408  *
4409  * Common control flow for 3 way handshake:
4410  * ----------------------------------------
4411  *
4412  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4413  *
4414  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4415  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4416  *
4417  * Sockfs ACCEPT Path:
4418  * -------------------
4419  *
4420  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4421  * as STREAM entry point)
4422  *
4423  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4424  *
4425  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4426  * association (we are not behind eager's squeue but sockfs is protecting us
4427  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4428  * is changed to point at tcp_wput().
4429  *
4430  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4431  * listener (done on listener's perimeter).
4432  *
4433  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4434  * accept.
4435  *
4436  * TLI/XTI client ACCEPT path:
4437  * ---------------------------
4438  *
4439  * soaccept() sends T_CONN_RES on the listener STREAM.
4440  *
4441  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4442  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4443  *
4444  * Locks:
4445  * ======
4446  *
4447  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4448  * and listeners->tcp_eager_next_q.
4449  *
4450  * Referencing:
4451  * ============
4452  *
4453  * 1) We start out in tcp_input_listener by eager placing a ref on
4454  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4455  *
4456  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4457  * doing so we place a ref on the eager. This ref is finally dropped at the
4458  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4459  * reference is dropped by the squeue framework.
4460  *
4461  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4462  *
4463  * The reference must be released by the same entity that added the reference
4464  * In the above scheme, the eager is the entity that adds and releases the
4465  * references. Note that tcp_accept_finish executes in the squeue of the eager
4466  * (albeit after it is attached to the acceptor stream). Though 1. executes
4467  * in the listener's squeue, the eager is nascent at this point and the
4468  * reference can be considered to have been added on behalf of the eager.
4469  *
4470  * Eager getting a Reset or listener closing:
4471  * ==========================================
4472  *
4473  * Once the listener and eager are linked, the listener never does the unlink.
4474  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4475  * a message on all eager perimeter. The eager then does the unlink, clears
4476  * any pointers to the listener's queue and drops the reference to the
4477  * listener. The listener waits in tcp_close outside the squeue until its
4478  * refcount has dropped to 1. This ensures that the listener has waited for
4479  * all eagers to clear their association with the listener.
4480  *
4481  * Similarly, if eager decides to go away, it can unlink itself and close.
4482  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4483  * the reference to eager is still valid because of the extra ref we put
4484  * in tcp_send_conn_ind.
4485  *
4486  * Listener can always locate the eager under the protection
4487  * of the listener->tcp_eager_lock, and then do a refhold
4488  * on the eager during the accept processing.
4489  *
4490  * The acceptor stream accesses the eager in the accept processing
4491  * based on the ref placed on eager before sending T_conn_ind.
4492  * The only entity that can negate this refhold is a listener close
4493  * which is mutually exclusive with an active acceptor stream.
4494  *
4495  * Eager's reference on the listener
4496  * ===================================
4497  *
4498  * If the accept happens (even on a closed eager) the eager drops its
4499  * reference on the listener at the start of tcp_accept_finish. If the
4500  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4501  * the reference is dropped in tcp_closei_local. If the listener closes,
4502  * the reference is dropped in tcp_eager_kill. In all cases the reference
4503  * is dropped while executing in the eager's context (squeue).
4504  */
4505 /* END CSTYLED */
4506 
4507 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4508 
4509 /*
4510  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4511  * tcp_input_data will not see any packets for listeners since the listener
4512  * has conn_recv set to tcp_input_listener.
4513  */
4514 /* ARGSUSED */
4515 void
4516 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4517 {
4518 	tcpha_t		*tcpha;
4519 	uint32_t	seg_seq;
4520 	tcp_t		*eager;
4521 	int		err;
4522 	conn_t		*econnp = NULL;
4523 	squeue_t	*new_sqp;
4524 	mblk_t		*mp1;
4525 	uint_t 		ip_hdr_len;
4526 	conn_t		*lconnp = (conn_t *)arg;
4527 	tcp_t		*listener = lconnp->conn_tcp;
4528 	tcp_stack_t	*tcps = listener->tcp_tcps;
4529 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4530 	uint_t		flags;
4531 	mblk_t		*tpi_mp;
4532 	uint_t		ifindex = ira->ira_ruifindex;
4533 	boolean_t	tlc_set = B_FALSE;
4534 
4535 	ip_hdr_len = ira->ira_ip_hdr_length;
4536 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4537 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4538 
4539 	if (!(flags & TH_SYN)) {
4540 		if ((flags & TH_RST) || (flags & TH_URG)) {
4541 			freemsg(mp);
4542 			return;
4543 		}
4544 		if (flags & TH_ACK) {
4545 			/* Note this executes in listener's squeue */
4546 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4547 			return;
4548 		}
4549 
4550 		freemsg(mp);
4551 		return;
4552 	}
4553 
4554 	if (listener->tcp_state != TCPS_LISTEN)
4555 		goto error2;
4556 
4557 	ASSERT(IPCL_IS_BOUND(lconnp));
4558 
4559 	mutex_enter(&listener->tcp_eager_lock);
4560 
4561 	/*
4562 	 * The system is under memory pressure, so we need to do our part
4563 	 * to relieve the pressure.  So we only accept new request if there
4564 	 * is nothing waiting to be accepted or waiting to complete the 3-way
4565 	 * handshake.  This means that busy listener will not get too many
4566 	 * new requests which they cannot handle in time while non-busy
4567 	 * listener is still functioning properly.
4568 	 */
4569 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
4570 	    listener->tcp_conn_req_cnt_q0 > 0)) {
4571 		mutex_exit(&listener->tcp_eager_lock);
4572 		TCP_STAT(tcps, tcp_listen_mem_drop);
4573 		goto error2;
4574 	}
4575 
4576 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4577 		mutex_exit(&listener->tcp_eager_lock);
4578 		TCP_STAT(tcps, tcp_listendrop);
4579 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4580 		if (lconnp->conn_debug) {
4581 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4582 			    "tcp_input_listener: listen backlog (max=%d) "
4583 			    "overflow (%d pending) on %s",
4584 			    listener->tcp_conn_req_max,
4585 			    listener->tcp_conn_req_cnt_q,
4586 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4587 		}
4588 		goto error2;
4589 	}
4590 
4591 	if (listener->tcp_conn_req_cnt_q0 >=
4592 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4593 		/*
4594 		 * Q0 is full. Drop a pending half-open req from the queue
4595 		 * to make room for the new SYN req. Also mark the time we
4596 		 * drop a SYN.
4597 		 *
4598 		 * A more aggressive defense against SYN attack will
4599 		 * be to set the "tcp_syn_defense" flag now.
4600 		 */
4601 		TCP_STAT(tcps, tcp_listendropq0);
4602 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4603 		if (!tcp_drop_q0(listener)) {
4604 			mutex_exit(&listener->tcp_eager_lock);
4605 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4606 			if (lconnp->conn_debug) {
4607 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4608 				    "tcp_input_listener: listen half-open "
4609 				    "queue (max=%d) full (%d pending) on %s",
4610 				    tcps->tcps_conn_req_max_q0,
4611 				    listener->tcp_conn_req_cnt_q0,
4612 				    tcp_display(listener, NULL,
4613 				    DISP_PORT_ONLY));
4614 			}
4615 			goto error2;
4616 		}
4617 	}
4618 
4619 	/*
4620 	 * Enforce the limit set on the number of connections per listener.
4621 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
4622 	 * for comparison.
4623 	 */
4624 	if (listener->tcp_listen_cnt != NULL) {
4625 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
4626 		int64_t now;
4627 
4628 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
4629 			mutex_exit(&listener->tcp_eager_lock);
4630 			now = ddi_get_lbolt64();
4631 			atomic_add_32(&tlc->tlc_cnt, -1);
4632 			TCP_STAT(tcps, tcp_listen_cnt_drop);
4633 			tlc->tlc_drop++;
4634 			if (now - tlc->tlc_report_time >
4635 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
4636 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
4637 				    "Listener (port %d) connection max (%u) "
4638 				    "reached: %u attempts dropped total\n",
4639 				    ntohs(listener->tcp_connp->conn_lport),
4640 				    tlc->tlc_max, tlc->tlc_drop);
4641 				tlc->tlc_report_time = now;
4642 			}
4643 			goto error2;
4644 		}
4645 		tlc_set = B_TRUE;
4646 	}
4647 
4648 	mutex_exit(&listener->tcp_eager_lock);
4649 
4650 	/*
4651 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4652 	 * or based on the ring (for packets from GLD). Otherwise it is
4653 	 * set based on lbolt i.e., a somewhat random number.
4654 	 */
4655 	ASSERT(ira->ira_sqp != NULL);
4656 	new_sqp = ira->ira_sqp;
4657 
4658 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4659 	if (econnp == NULL)
4660 		goto error2;
4661 
4662 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4663 	econnp->conn_sqp = new_sqp;
4664 	econnp->conn_initial_sqp = new_sqp;
4665 	econnp->conn_ixa->ixa_sqp = new_sqp;
4666 
4667 	econnp->conn_fport = tcpha->tha_lport;
4668 	econnp->conn_lport = tcpha->tha_fport;
4669 
4670 	err = conn_inherit_parent(lconnp, econnp);
4671 	if (err != 0)
4672 		goto error3;
4673 
4674 	/* We already know the laddr of the new connection is ours */
4675 	econnp->conn_ixa->ixa_src_generation = ipst->ips_src_generation;
4676 
4677 	ASSERT(OK_32PTR(mp->b_rptr));
4678 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4679 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4680 
4681 	if (lconnp->conn_family == AF_INET) {
4682 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4683 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4684 	} else {
4685 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4686 	}
4687 
4688 	if (tpi_mp == NULL)
4689 		goto error3;
4690 
4691 	eager = econnp->conn_tcp;
4692 	eager->tcp_detached = B_TRUE;
4693 	SOCK_CONNID_INIT(eager->tcp_connid);
4694 
4695 	tcp_init_values(eager);
4696 
4697 	ASSERT((econnp->conn_ixa->ixa_flags &
4698 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4699 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4700 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4701 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4702 
4703 	if (!tcps->tcps_dev_flow_ctl)
4704 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4705 
4706 	/* Prepare for diffing against previous packets */
4707 	eager->tcp_recvifindex = 0;
4708 	eager->tcp_recvhops = 0xffffffffU;
4709 
4710 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4711 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4712 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4713 			econnp->conn_incoming_ifindex = ifindex;
4714 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4715 			econnp->conn_ixa->ixa_scopeid = ifindex;
4716 		}
4717 	}
4718 
4719 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4720 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4721 	    tcps->tcps_rev_src_routes) {
4722 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4723 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4724 
4725 		/* Source routing option copyover (reverse it) */
4726 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4727 		if (err != 0) {
4728 			freemsg(tpi_mp);
4729 			goto error3;
4730 		}
4731 		ip_pkt_source_route_reverse_v4(ipp);
4732 	}
4733 
4734 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4735 	ASSERT(!eager->tcp_tconnind_started);
4736 	/*
4737 	 * If the SYN came with a credential, it's a loopback packet or a
4738 	 * labeled packet; attach the credential to the TPI message.
4739 	 */
4740 	if (ira->ira_cred != NULL)
4741 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4742 
4743 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4744 
4745 	/* Inherit the listener's SSL protection state */
4746 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4747 		kssl_hold_ent(eager->tcp_kssl_ent);
4748 		eager->tcp_kssl_pending = B_TRUE;
4749 	}
4750 
4751 	/* Inherit the listener's non-STREAMS flag */
4752 	if (IPCL_IS_NONSTR(lconnp)) {
4753 		econnp->conn_flags |= IPCL_NONSTR;
4754 	}
4755 
4756 	ASSERT(eager->tcp_ordrel_mp == NULL);
4757 
4758 	if (!IPCL_IS_NONSTR(econnp)) {
4759 		/*
4760 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4761 		 * at close time, we will always have that to send up.
4762 		 * Otherwise, we need to do special handling in case the
4763 		 * allocation fails at that time.
4764 		 */
4765 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4766 			goto error3;
4767 	}
4768 	/*
4769 	 * Now that the IP addresses and ports are setup in econnp we
4770 	 * can do the IPsec policy work.
4771 	 */
4772 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4773 		if (lconnp->conn_policy != NULL) {
4774 			/*
4775 			 * Inherit the policy from the listener; use
4776 			 * actions from ira
4777 			 */
4778 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4779 				CONN_DEC_REF(econnp);
4780 				freemsg(mp);
4781 				goto error3;
4782 			}
4783 		}
4784 	}
4785 
4786 	/* Inherit various TCP parameters from the listener */
4787 	eager->tcp_naglim = listener->tcp_naglim;
4788 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4789 	eager->tcp_second_timer_threshold =
4790 	    listener->tcp_second_timer_threshold;
4791 	eager->tcp_first_ctimer_threshold =
4792 	    listener->tcp_first_ctimer_threshold;
4793 	eager->tcp_second_ctimer_threshold =
4794 	    listener->tcp_second_ctimer_threshold;
4795 
4796 	/*
4797 	 * tcp_set_destination() may set tcp_rwnd according to the route
4798 	 * metrics. If it does not, the eager's receive window will be set
4799 	 * to the listener's receive window later in this function.
4800 	 */
4801 	eager->tcp_rwnd = 0;
4802 
4803 	/*
4804 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4805 	 * calling tcp_process_options() which set the initial cwnd.
4806 	 */
4807 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4808 
4809 	if (is_system_labeled()) {
4810 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4811 
4812 		ASSERT(ira->ira_tsl != NULL);
4813 		/* Discard any old label */
4814 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4815 			ASSERT(ixa->ixa_tsl != NULL);
4816 			label_rele(ixa->ixa_tsl);
4817 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4818 			ixa->ixa_tsl = NULL;
4819 		}
4820 		if ((lconnp->conn_mlp_type != mlptSingle ||
4821 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4822 		    ira->ira_tsl != NULL) {
4823 			/*
4824 			 * If this is an MLP connection or a MAC-Exempt
4825 			 * connection with an unlabeled node, packets are to be
4826 			 * exchanged using the security label of the received
4827 			 * SYN packet instead of the server application's label.
4828 			 * tsol_check_dest called from ip_set_destination
4829 			 * might later update TSF_UNLABELED by replacing
4830 			 * ixa_tsl with a new label.
4831 			 */
4832 			label_hold(ira->ira_tsl);
4833 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4834 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4835 			    econnp, ts_label_t *, ixa->ixa_tsl)
4836 		} else {
4837 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4838 			DTRACE_PROBE2(syn_accept, conn_t *,
4839 			    econnp, ts_label_t *, ixa->ixa_tsl)
4840 		}
4841 		/*
4842 		 * conn_connect() called from tcp_set_destination will verify
4843 		 * the destination is allowed to receive packets at the
4844 		 * security label of the SYN-ACK we are generating. As part of
4845 		 * that, tsol_check_dest() may create a new effective label for
4846 		 * this connection.
4847 		 * Finally conn_connect() will call conn_update_label.
4848 		 * All that remains for TCP to do is to call
4849 		 * conn_build_hdr_template which is done as part of
4850 		 * tcp_set_destination.
4851 		 */
4852 	}
4853 
4854 	/*
4855 	 * Since we will clear tcp_listener before we clear tcp_detached
4856 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4857 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4858 	 */
4859 	eager->tcp_hard_binding = B_TRUE;
4860 
4861 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4862 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4863 
4864 	CL_INET_CONNECT(econnp, B_FALSE, err);
4865 	if (err != 0) {
4866 		tcp_bind_hash_remove(eager);
4867 		goto error3;
4868 	}
4869 
4870 	/*
4871 	 * No need to check for multicast destination since ip will only pass
4872 	 * up multicasts to those that have expressed interest
4873 	 * TODO: what about rejecting broadcasts?
4874 	 * Also check that source is not a multicast or broadcast address.
4875 	 */
4876 	eager->tcp_state = TCPS_SYN_RCVD;
4877 	SOCK_CONNID_BUMP(eager->tcp_connid);
4878 
4879 	/*
4880 	 * Adapt our mss, ttl, ... based on the remote address.
4881 	 */
4882 
4883 	if (tcp_set_destination(eager) != 0) {
4884 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4885 		/* Undo the bind_hash_insert */
4886 		tcp_bind_hash_remove(eager);
4887 		goto error3;
4888 	}
4889 
4890 	/* Process all TCP options. */
4891 	tcp_process_options(eager, tcpha);
4892 
4893 	/* Is the other end ECN capable? */
4894 	if (tcps->tcps_ecn_permitted >= 1 &&
4895 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4896 		eager->tcp_ecn_ok = B_TRUE;
4897 	}
4898 
4899 	/*
4900 	 * The listener's conn_rcvbuf should be the default window size or a
4901 	 * window size changed via SO_RCVBUF option. First round up the
4902 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4903 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4904 	 * setting.
4905 	 *
4906 	 * Note if there is a rpipe metric associated with the remote host,
4907 	 * we should not inherit receive window size from listener.
4908 	 */
4909 	eager->tcp_rwnd = MSS_ROUNDUP(
4910 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4911 	    eager->tcp_rwnd), eager->tcp_mss);
4912 	if (eager->tcp_snd_ws_ok)
4913 		tcp_set_ws_value(eager);
4914 	/*
4915 	 * Note that this is the only place tcp_rwnd_set() is called for
4916 	 * accepting a connection.  We need to call it here instead of
4917 	 * after the 3-way handshake because we need to tell the other
4918 	 * side our rwnd in the SYN-ACK segment.
4919 	 */
4920 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4921 
4922 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4923 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4924 
4925 	ASSERT(econnp->conn_rcvbuf != 0 &&
4926 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4927 
4928 	/* Put a ref on the listener for the eager. */
4929 	CONN_INC_REF(lconnp);
4930 	mutex_enter(&listener->tcp_eager_lock);
4931 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4932 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4933 	listener->tcp_eager_next_q0 = eager;
4934 	eager->tcp_eager_prev_q0 = listener;
4935 
4936 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4937 	eager->tcp_listener = listener;
4938 	eager->tcp_saved_listener = listener;
4939 
4940 	/*
4941 	 * Set tcp_listen_cnt so that when the connection is done, the counter
4942 	 * is decremented.
4943 	 */
4944 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
4945 
4946 	/*
4947 	 * Tag this detached tcp vector for later retrieval
4948 	 * by our listener client in tcp_accept().
4949 	 */
4950 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4951 	listener->tcp_conn_req_cnt_q0++;
4952 	if (++listener->tcp_conn_req_seqnum == -1) {
4953 		/*
4954 		 * -1 is "special" and defined in TPI as something
4955 		 * that should never be used in T_CONN_IND
4956 		 */
4957 		++listener->tcp_conn_req_seqnum;
4958 	}
4959 	mutex_exit(&listener->tcp_eager_lock);
4960 
4961 	if (listener->tcp_syn_defense) {
4962 		/* Don't drop the SYN that comes from a good IP source */
4963 		ipaddr_t *addr_cache;
4964 
4965 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4966 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4967 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4968 			eager->tcp_dontdrop = B_TRUE;
4969 		}
4970 	}
4971 
4972 	/*
4973 	 * We need to insert the eager in its own perimeter but as soon
4974 	 * as we do that, we expose the eager to the classifier and
4975 	 * should not touch any field outside the eager's perimeter.
4976 	 * So do all the work necessary before inserting the eager
4977 	 * in its own perimeter. Be optimistic that conn_connect()
4978 	 * will succeed but undo everything if it fails.
4979 	 */
4980 	seg_seq = ntohl(tcpha->tha_seq);
4981 	eager->tcp_irs = seg_seq;
4982 	eager->tcp_rack = seg_seq;
4983 	eager->tcp_rnxt = seg_seq + 1;
4984 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4985 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4986 	eager->tcp_state = TCPS_SYN_RCVD;
4987 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4988 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4989 	if (mp1 == NULL) {
4990 		/*
4991 		 * Increment the ref count as we are going to
4992 		 * enqueueing an mp in squeue
4993 		 */
4994 		CONN_INC_REF(econnp);
4995 		goto error;
4996 	}
4997 
4998 	/*
4999 	 * We need to start the rto timer. In normal case, we start
5000 	 * the timer after sending the packet on the wire (or at
5001 	 * least believing that packet was sent by waiting for
5002 	 * conn_ip_output() to return). Since this is the first packet
5003 	 * being sent on the wire for the eager, our initial tcp_rto
5004 	 * is at least tcp_rexmit_interval_min which is a fairly
5005 	 * large value to allow the algorithm to adjust slowly to large
5006 	 * fluctuations of RTT during first few transmissions.
5007 	 *
5008 	 * Starting the timer first and then sending the packet in this
5009 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5010 	 * is of the order of several 100ms and starting the timer
5011 	 * first and then sending the packet will result in difference
5012 	 * of few micro seconds.
5013 	 *
5014 	 * Without this optimization, we are forced to hold the fanout
5015 	 * lock across the ipcl_bind_insert() and sending the packet
5016 	 * so that we don't race against an incoming packet (maybe RST)
5017 	 * for this eager.
5018 	 *
5019 	 * It is necessary to acquire an extra reference on the eager
5020 	 * at this point and hold it until after tcp_send_data() to
5021 	 * ensure against an eager close race.
5022 	 */
5023 
5024 	CONN_INC_REF(econnp);
5025 
5026 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5027 
5028 	/*
5029 	 * Insert the eager in its own perimeter now. We are ready to deal
5030 	 * with any packets on eager.
5031 	 */
5032 	if (ipcl_conn_insert(econnp) != 0)
5033 		goto error;
5034 
5035 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
5036 	freemsg(mp);
5037 	/*
5038 	 * Send the SYN-ACK. Use the right squeue so that conn_ixa is
5039 	 * only used by one thread at a time.
5040 	 */
5041 	if (econnp->conn_sqp == lconnp->conn_sqp) {
5042 		(void) conn_ip_output(mp1, econnp->conn_ixa);
5043 		CONN_DEC_REF(econnp);
5044 	} else {
5045 		SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_send_synack,
5046 		    econnp, NULL, SQ_PROCESS, SQTAG_TCP_SEND_SYNACK);
5047 	}
5048 	return;
5049 error:
5050 	freemsg(mp1);
5051 	eager->tcp_closemp_used = B_TRUE;
5052 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5053 	mp1 = &eager->tcp_closemp;
5054 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5055 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5056 
5057 	/*
5058 	 * If a connection already exists, send the mp to that connections so
5059 	 * that it can be appropriately dealt with.
5060 	 */
5061 	ipst = tcps->tcps_netstack->netstack_ip;
5062 
5063 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
5064 		if (!IPCL_IS_CONNECTED(econnp)) {
5065 			/*
5066 			 * Something bad happened. ipcl_conn_insert()
5067 			 * failed because a connection already existed
5068 			 * in connected hash but we can't find it
5069 			 * anymore (someone blew it away). Just
5070 			 * free this message and hopefully remote
5071 			 * will retransmit at which time the SYN can be
5072 			 * treated as a new connection or dealth with
5073 			 * a TH_RST if a connection already exists.
5074 			 */
5075 			CONN_DEC_REF(econnp);
5076 			freemsg(mp);
5077 		} else {
5078 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
5079 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5080 		}
5081 	} else {
5082 		/* Nobody wants this packet */
5083 		freemsg(mp);
5084 	}
5085 	return;
5086 error3:
5087 	CONN_DEC_REF(econnp);
5088 error2:
5089 	freemsg(mp);
5090 	if (tlc_set)
5091 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
5092 }
5093 
5094 /* ARGSUSED2 */
5095 void
5096 tcp_send_synack(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5097 {
5098 	conn_t	*econnp = (conn_t *)arg;
5099 	tcp_t	*tcp = econnp->conn_tcp;
5100 
5101 	/* Guard against a RST having blown it away while on the squeue */
5102 	if (tcp->tcp_state == TCPS_CLOSED) {
5103 		freemsg(mp);
5104 		return;
5105 	}
5106 
5107 	(void) conn_ip_output(mp, econnp->conn_ixa);
5108 }
5109 
5110 /*
5111  * In an ideal case of vertical partition in NUMA architecture, its
5112  * beneficial to have the listener and all the incoming connections
5113  * tied to the same squeue. The other constraint is that incoming
5114  * connections should be tied to the squeue attached to interrupted
5115  * CPU for obvious locality reason so this leaves the listener to
5116  * be tied to the same squeue. Our only problem is that when listener
5117  * is binding, the CPU that will get interrupted by the NIC whose
5118  * IP address the listener is binding to is not even known. So
5119  * the code below allows us to change that binding at the time the
5120  * CPU is interrupted by virtue of incoming connection's squeue.
5121  *
5122  * This is usefull only in case of a listener bound to a specific IP
5123  * address. For other kind of listeners, they get bound the
5124  * very first time and there is no attempt to rebind them.
5125  */
5126 void
5127 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
5128     ip_recv_attr_t *ira)
5129 {
5130 	conn_t		*connp = (conn_t *)arg;
5131 	squeue_t	*sqp = (squeue_t *)arg2;
5132 	squeue_t	*new_sqp;
5133 	uint32_t	conn_flags;
5134 
5135 	/*
5136 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
5137 	 * or based on the ring (for packets from GLD). Otherwise it is
5138 	 * set based on lbolt i.e., a somewhat random number.
5139 	 */
5140 	ASSERT(ira->ira_sqp != NULL);
5141 	new_sqp = ira->ira_sqp;
5142 
5143 	if (connp->conn_fanout == NULL)
5144 		goto done;
5145 
5146 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5147 		mutex_enter(&connp->conn_fanout->connf_lock);
5148 		mutex_enter(&connp->conn_lock);
5149 		/*
5150 		 * No one from read or write side can access us now
5151 		 * except for already queued packets on this squeue.
5152 		 * But since we haven't changed the squeue yet, they
5153 		 * can't execute. If they are processed after we have
5154 		 * changed the squeue, they are sent back to the
5155 		 * correct squeue down below.
5156 		 * But a listner close can race with processing of
5157 		 * incoming SYN. If incoming SYN processing changes
5158 		 * the squeue then the listener close which is waiting
5159 		 * to enter the squeue would operate on the wrong
5160 		 * squeue. Hence we don't change the squeue here unless
5161 		 * the refcount is exactly the minimum refcount. The
5162 		 * minimum refcount of 4 is counted as - 1 each for
5163 		 * TCP and IP, 1 for being in the classifier hash, and
5164 		 * 1 for the mblk being processed.
5165 		 */
5166 
5167 		if (connp->conn_ref != 4 ||
5168 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5169 			mutex_exit(&connp->conn_lock);
5170 			mutex_exit(&connp->conn_fanout->connf_lock);
5171 			goto done;
5172 		}
5173 		if (connp->conn_sqp != new_sqp) {
5174 			while (connp->conn_sqp != new_sqp)
5175 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5176 			/* No special MT issues for outbound ixa_sqp hint */
5177 			connp->conn_ixa->ixa_sqp = new_sqp;
5178 		}
5179 
5180 		do {
5181 			conn_flags = connp->conn_flags;
5182 			conn_flags |= IPCL_FULLY_BOUND;
5183 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5184 			    conn_flags);
5185 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5186 
5187 		mutex_exit(&connp->conn_fanout->connf_lock);
5188 		mutex_exit(&connp->conn_lock);
5189 
5190 		/*
5191 		 * Assume we have picked a good squeue for the listener. Make
5192 		 * subsequent SYNs not try to change the squeue.
5193 		 */
5194 		connp->conn_recv = tcp_input_listener;
5195 	}
5196 
5197 done:
5198 	if (connp->conn_sqp != sqp) {
5199 		CONN_INC_REF(connp);
5200 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5201 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5202 	} else {
5203 		tcp_input_listener(connp, mp, sqp, ira);
5204 	}
5205 }
5206 
5207 /*
5208  * Successful connect request processing begins when our client passes
5209  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
5210  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
5211  *
5212  * After various error checks are completed, tcp_tpi_connect() lays
5213  * the target address and port into the composite header template.
5214  * Then we ask IP for information, including a source address if we didn't
5215  * already have one. Finally we prepare to send the SYN packet, and then
5216  * send up the T_OK_ACK reply message.
5217  */
5218 static void
5219 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5220 {
5221 	sin_t		*sin;
5222 	struct T_conn_req	*tcr;
5223 	struct sockaddr	*sa;
5224 	socklen_t	len;
5225 	int		error;
5226 	cred_t		*cr;
5227 	pid_t		cpid;
5228 	conn_t		*connp = tcp->tcp_connp;
5229 	queue_t		*q = connp->conn_wq;
5230 
5231 	/*
5232 	 * All Solaris components should pass a db_credp
5233 	 * for this TPI message, hence we ASSERT.
5234 	 * But in case there is some other M_PROTO that looks
5235 	 * like a TPI message sent by some other kernel
5236 	 * component, we check and return an error.
5237 	 */
5238 	cr = msg_getcred(mp, &cpid);
5239 	ASSERT(cr != NULL);
5240 	if (cr == NULL) {
5241 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5242 		return;
5243 	}
5244 
5245 	tcr = (struct T_conn_req *)mp->b_rptr;
5246 
5247 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5248 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5249 		tcp_err_ack(tcp, mp, TPROTO, 0);
5250 		return;
5251 	}
5252 
5253 	/*
5254 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5255 	 * will always have that to send up.  Otherwise, we need to do
5256 	 * special handling in case the allocation fails at that time.
5257 	 * If the end point is TPI, the tcp_t can be reused and the
5258 	 * tcp_ordrel_mp may be allocated already.
5259 	 */
5260 	if (tcp->tcp_ordrel_mp == NULL) {
5261 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5262 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5263 			return;
5264 		}
5265 	}
5266 
5267 	/*
5268 	 * Determine packet type based on type of address passed in
5269 	 * the request should contain an IPv4 or IPv6 address.
5270 	 * Make sure that address family matches the type of
5271 	 * family of the address passed down.
5272 	 */
5273 	switch (tcr->DEST_length) {
5274 	default:
5275 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5276 		return;
5277 
5278 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5279 		/*
5280 		 * XXX: The check for valid DEST_length was not there
5281 		 * in earlier releases and some buggy
5282 		 * TLI apps (e.g Sybase) got away with not feeding
5283 		 * in sin_zero part of address.
5284 		 * We allow that bug to keep those buggy apps humming.
5285 		 * Test suites require the check on DEST_length.
5286 		 * We construct a new mblk with valid DEST_length
5287 		 * free the original so the rest of the code does
5288 		 * not have to keep track of this special shorter
5289 		 * length address case.
5290 		 */
5291 		mblk_t *nmp;
5292 		struct T_conn_req *ntcr;
5293 		sin_t *nsin;
5294 
5295 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5296 		    tcr->OPT_length, BPRI_HI);
5297 		if (nmp == NULL) {
5298 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5299 			return;
5300 		}
5301 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5302 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5303 		ntcr->PRIM_type = T_CONN_REQ;
5304 		ntcr->DEST_length = sizeof (sin_t);
5305 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5306 
5307 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5308 		*nsin = sin_null;
5309 		/* Get pointer to shorter address to copy from original mp */
5310 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5311 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5312 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5313 			freemsg(nmp);
5314 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5315 			return;
5316 		}
5317 		nsin->sin_family = sin->sin_family;
5318 		nsin->sin_port = sin->sin_port;
5319 		nsin->sin_addr = sin->sin_addr;
5320 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5321 		nmp->b_wptr = (uchar_t *)&nsin[1];
5322 		if (tcr->OPT_length != 0) {
5323 			ntcr->OPT_length = tcr->OPT_length;
5324 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5325 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5326 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5327 			    tcr->OPT_length);
5328 			nmp->b_wptr += tcr->OPT_length;
5329 		}
5330 		freemsg(mp);	/* original mp freed */
5331 		mp = nmp;	/* re-initialize original variables */
5332 		tcr = ntcr;
5333 	}
5334 	/* FALLTHRU */
5335 
5336 	case sizeof (sin_t):
5337 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5338 		    sizeof (sin_t));
5339 		len = sizeof (sin_t);
5340 		break;
5341 
5342 	case sizeof (sin6_t):
5343 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5344 		    sizeof (sin6_t));
5345 		len = sizeof (sin6_t);
5346 		break;
5347 	}
5348 
5349 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5350 	if (error != 0) {
5351 		tcp_err_ack(tcp, mp, TSYSERR, error);
5352 		return;
5353 	}
5354 
5355 	/*
5356 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5357 	 * should key on their sequence number and cut them loose.
5358 	 */
5359 
5360 	/*
5361 	 * If options passed in, feed it for verification and handling
5362 	 */
5363 	if (tcr->OPT_length != 0) {
5364 		mblk_t	*ok_mp;
5365 		mblk_t	*discon_mp;
5366 		mblk_t  *conn_opts_mp;
5367 		int t_error, sys_error, do_disconnect;
5368 
5369 		conn_opts_mp = NULL;
5370 
5371 		if (tcp_conprim_opt_process(tcp, mp,
5372 		    &do_disconnect, &t_error, &sys_error) < 0) {
5373 			if (do_disconnect) {
5374 				ASSERT(t_error == 0 && sys_error == 0);
5375 				discon_mp = mi_tpi_discon_ind(NULL,
5376 				    ECONNREFUSED, 0);
5377 				if (!discon_mp) {
5378 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5379 					    TSYSERR, ENOMEM);
5380 					return;
5381 				}
5382 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5383 				if (!ok_mp) {
5384 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5385 					    TSYSERR, ENOMEM);
5386 					return;
5387 				}
5388 				qreply(q, ok_mp);
5389 				qreply(q, discon_mp); /* no flush! */
5390 			} else {
5391 				ASSERT(t_error != 0);
5392 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5393 				    sys_error);
5394 			}
5395 			return;
5396 		}
5397 		/*
5398 		 * Success in setting options, the mp option buffer represented
5399 		 * by OPT_length/offset has been potentially modified and
5400 		 * contains results of option processing. We copy it in
5401 		 * another mp to save it for potentially influencing returning
5402 		 * it in T_CONN_CONN.
5403 		 */
5404 		if (tcr->OPT_length != 0) { /* there are resulting options */
5405 			conn_opts_mp = copyb(mp);
5406 			if (!conn_opts_mp) {
5407 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5408 				    TSYSERR, ENOMEM);
5409 				return;
5410 			}
5411 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5412 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5413 			/*
5414 			 * Note:
5415 			 * These resulting option negotiation can include any
5416 			 * end-to-end negotiation options but there no such
5417 			 * thing (yet?) in our TCP/IP.
5418 			 */
5419 		}
5420 	}
5421 
5422 	/* call the non-TPI version */
5423 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5424 	if (error < 0) {
5425 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5426 	} else if (error > 0) {
5427 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5428 	} else {
5429 		mp = mi_tpi_ok_ack_alloc(mp);
5430 	}
5431 
5432 	/*
5433 	 * Note: Code below is the "failure" case
5434 	 */
5435 	/* return error ack and blow away saved option results if any */
5436 connect_failed:
5437 	if (mp != NULL)
5438 		putnext(connp->conn_rq, mp);
5439 	else {
5440 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5441 		    TSYSERR, ENOMEM);
5442 	}
5443 }
5444 
5445 /*
5446  * Handle connect to IPv4 destinations, including connections for AF_INET6
5447  * sockets connecting to IPv4 mapped IPv6 destinations.
5448  * Returns zero if OK, a positive errno, or a negative TLI error.
5449  */
5450 static int
5451 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5452     uint_t srcid)
5453 {
5454 	ipaddr_t 	dstaddr = *dstaddrp;
5455 	uint16_t 	lport;
5456 	conn_t		*connp = tcp->tcp_connp;
5457 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5458 	int		error;
5459 
5460 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5461 
5462 	/* Check for attempt to connect to INADDR_ANY */
5463 	if (dstaddr == INADDR_ANY)  {
5464 		/*
5465 		 * SunOS 4.x and 4.3 BSD allow an application
5466 		 * to connect a TCP socket to INADDR_ANY.
5467 		 * When they do this, the kernel picks the
5468 		 * address of one interface and uses it
5469 		 * instead.  The kernel usually ends up
5470 		 * picking the address of the loopback
5471 		 * interface.  This is an undocumented feature.
5472 		 * However, we provide the same thing here
5473 		 * in order to have source and binary
5474 		 * compatibility with SunOS 4.x.
5475 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5476 		 * generate the T_CONN_CON.
5477 		 */
5478 		dstaddr = htonl(INADDR_LOOPBACK);
5479 		*dstaddrp = dstaddr;
5480 	}
5481 
5482 	/* Handle __sin6_src_id if socket not bound to an IP address */
5483 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5484 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5485 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5486 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5487 	}
5488 
5489 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5490 	connp->conn_fport = dstport;
5491 
5492 	/*
5493 	 * At this point the remote destination address and remote port fields
5494 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5495 	 * have to see which state tcp was in so we can take appropriate action.
5496 	 */
5497 	if (tcp->tcp_state == TCPS_IDLE) {
5498 		/*
5499 		 * We support a quick connect capability here, allowing
5500 		 * clients to transition directly from IDLE to SYN_SENT
5501 		 * tcp_bindi will pick an unused port, insert the connection
5502 		 * in the bind hash and transition to BOUND state.
5503 		 */
5504 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5505 		    tcp, B_TRUE);
5506 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5507 		    B_FALSE, B_FALSE);
5508 		if (lport == 0)
5509 			return (-TNOADDR);
5510 	}
5511 
5512 	/*
5513 	 * Lookup the route to determine a source address and the uinfo.
5514 	 * Setup TCP parameters based on the metrics/DCE.
5515 	 */
5516 	error = tcp_set_destination(tcp);
5517 	if (error != 0)
5518 		return (error);
5519 
5520 	/*
5521 	 * Don't let an endpoint connect to itself.
5522 	 */
5523 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5524 	    connp->conn_fport == connp->conn_lport)
5525 		return (-TBADADDR);
5526 
5527 	tcp->tcp_state = TCPS_SYN_SENT;
5528 
5529 	return (ipcl_conn_insert_v4(connp));
5530 }
5531 
5532 /*
5533  * Handle connect to IPv6 destinations.
5534  * Returns zero if OK, a positive errno, or a negative TLI error.
5535  */
5536 static int
5537 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5538     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5539 {
5540 	uint16_t 	lport;
5541 	conn_t		*connp = tcp->tcp_connp;
5542 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5543 	int		error;
5544 
5545 	ASSERT(connp->conn_family == AF_INET6);
5546 
5547 	/*
5548 	 * If we're here, it means that the destination address is a native
5549 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5550 	 * reason why it might not be IPv6 is if the socket was bound to an
5551 	 * IPv4-mapped IPv6 address.
5552 	 */
5553 	if (connp->conn_ipversion != IPV6_VERSION)
5554 		return (-TBADADDR);
5555 
5556 	/*
5557 	 * Interpret a zero destination to mean loopback.
5558 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5559 	 * generate the T_CONN_CON.
5560 	 */
5561 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5562 		*dstaddrp = ipv6_loopback;
5563 
5564 	/* Handle __sin6_src_id if socket not bound to an IP address */
5565 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5566 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5567 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5568 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5569 	}
5570 
5571 	/*
5572 	 * Take care of the scope_id now.
5573 	 */
5574 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5575 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5576 		connp->conn_ixa->ixa_scopeid = scope_id;
5577 	} else {
5578 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5579 	}
5580 
5581 	connp->conn_flowinfo = flowinfo;
5582 	connp->conn_faddr_v6 = *dstaddrp;
5583 	connp->conn_fport = dstport;
5584 
5585 	/*
5586 	 * At this point the remote destination address and remote port fields
5587 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5588 	 * have to see which state tcp was in so we can take appropriate action.
5589 	 */
5590 	if (tcp->tcp_state == TCPS_IDLE) {
5591 		/*
5592 		 * We support a quick connect capability here, allowing
5593 		 * clients to transition directly from IDLE to SYN_SENT
5594 		 * tcp_bindi will pick an unused port, insert the connection
5595 		 * in the bind hash and transition to BOUND state.
5596 		 */
5597 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5598 		    tcp, B_TRUE);
5599 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5600 		    B_FALSE, B_FALSE);
5601 		if (lport == 0)
5602 			return (-TNOADDR);
5603 	}
5604 
5605 	/*
5606 	 * Lookup the route to determine a source address and the uinfo.
5607 	 * Setup TCP parameters based on the metrics/DCE.
5608 	 */
5609 	error = tcp_set_destination(tcp);
5610 	if (error != 0)
5611 		return (error);
5612 
5613 	/*
5614 	 * Don't let an endpoint connect to itself.
5615 	 */
5616 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5617 	    connp->conn_fport == connp->conn_lport)
5618 		return (-TBADADDR);
5619 
5620 	tcp->tcp_state = TCPS_SYN_SENT;
5621 
5622 	return (ipcl_conn_insert_v6(connp));
5623 }
5624 
5625 /*
5626  * Disconnect
5627  * Note that unlike other functions this returns a positive tli error
5628  * when it fails; it never returns an errno.
5629  */
5630 static int
5631 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5632 {
5633 	conn_t		*lconnp;
5634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5635 	conn_t		*connp = tcp->tcp_connp;
5636 
5637 	/*
5638 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5639 	 * when the stream is in BOUND state. Do not send a reset,
5640 	 * since the destination IP address is not valid, and it can
5641 	 * be the initialized value of all zeros (broadcast address).
5642 	 */
5643 	if (tcp->tcp_state <= TCPS_BOUND) {
5644 		if (connp->conn_debug) {
5645 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5646 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5647 		}
5648 		return (TOUTSTATE);
5649 	}
5650 
5651 
5652 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5653 
5654 		/*
5655 		 * According to TPI, for non-listeners, ignore seqnum
5656 		 * and disconnect.
5657 		 * Following interpretation of -1 seqnum is historical
5658 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5659 		 * a valid seqnum should not be -1).
5660 		 *
5661 		 *	-1 means disconnect everything
5662 		 *	regardless even on a listener.
5663 		 */
5664 
5665 		int old_state = tcp->tcp_state;
5666 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5667 
5668 		/*
5669 		 * The connection can't be on the tcp_time_wait_head list
5670 		 * since it is not detached.
5671 		 */
5672 		ASSERT(tcp->tcp_time_wait_next == NULL);
5673 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5674 		ASSERT(tcp->tcp_time_wait_expire == 0);
5675 		/*
5676 		 * If it used to be a listener, check to make sure no one else
5677 		 * has taken the port before switching back to LISTEN state.
5678 		 */
5679 		if (connp->conn_ipversion == IPV4_VERSION) {
5680 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5681 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5682 		} else {
5683 			uint_t ifindex = 0;
5684 
5685 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5686 				ifindex = connp->conn_ixa->ixa_scopeid;
5687 
5688 			/* Allow conn_bound_if listeners? */
5689 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5690 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5691 			    ipst);
5692 		}
5693 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5694 			tcp->tcp_state = TCPS_LISTEN;
5695 		} else if (old_state > TCPS_BOUND) {
5696 			tcp->tcp_conn_req_max = 0;
5697 			tcp->tcp_state = TCPS_BOUND;
5698 
5699 			/*
5700 			 * If this end point is not going to become a listener,
5701 			 * decrement the listener connection count if
5702 			 * necessary.  Note that we do not do this if it is
5703 			 * going to be a listner (the above if case) since
5704 			 * then it may remove the counter struct.
5705 			 */
5706 			if (tcp->tcp_listen_cnt != NULL)
5707 				TCP_DECR_LISTEN_CNT(tcp);
5708 		}
5709 		if (lconnp != NULL)
5710 			CONN_DEC_REF(lconnp);
5711 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5712 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5713 		} else if (old_state == TCPS_ESTABLISHED ||
5714 		    old_state == TCPS_CLOSE_WAIT) {
5715 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5716 		}
5717 
5718 		if (tcp->tcp_fused)
5719 			tcp_unfuse(tcp);
5720 
5721 		mutex_enter(&tcp->tcp_eager_lock);
5722 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5723 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5724 			tcp_eager_cleanup(tcp, 0);
5725 		}
5726 		mutex_exit(&tcp->tcp_eager_lock);
5727 
5728 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5729 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5730 
5731 		tcp_reinit(tcp);
5732 
5733 		return (0);
5734 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5735 		return (TBADSEQ);
5736 	}
5737 	return (0);
5738 }
5739 
5740 /*
5741  * Our client hereby directs us to reject the connection request
5742  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5743  * of sending the appropriate RST, not an ICMP error.
5744  */
5745 static void
5746 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5747 {
5748 	t_scalar_t seqnum;
5749 	int	error;
5750 	conn_t	*connp = tcp->tcp_connp;
5751 
5752 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5753 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5754 		tcp_err_ack(tcp, mp, TPROTO, 0);
5755 		return;
5756 	}
5757 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5758 	error = tcp_disconnect_common(tcp, seqnum);
5759 	if (error != 0)
5760 		tcp_err_ack(tcp, mp, error, 0);
5761 	else {
5762 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5763 			/* Send M_FLUSH according to TPI */
5764 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5765 		}
5766 		mp = mi_tpi_ok_ack_alloc(mp);
5767 		if (mp != NULL)
5768 			putnext(connp->conn_rq, mp);
5769 	}
5770 }
5771 
5772 /*
5773  * Diagnostic routine used to return a string associated with the tcp state.
5774  * Note that if the caller does not supply a buffer, it will use an internal
5775  * static string.  This means that if multiple threads call this function at
5776  * the same time, output can be corrupted...  Note also that this function
5777  * does not check the size of the supplied buffer.  The caller has to make
5778  * sure that it is big enough.
5779  */
5780 static char *
5781 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5782 {
5783 	char		buf1[30];
5784 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5785 	char		*buf;
5786 	char		*cp;
5787 	in6_addr_t	local, remote;
5788 	char		local_addrbuf[INET6_ADDRSTRLEN];
5789 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5790 	conn_t		*connp;
5791 
5792 	if (sup_buf != NULL)
5793 		buf = sup_buf;
5794 	else
5795 		buf = priv_buf;
5796 
5797 	if (tcp == NULL)
5798 		return ("NULL_TCP");
5799 
5800 	connp = tcp->tcp_connp;
5801 	switch (tcp->tcp_state) {
5802 	case TCPS_CLOSED:
5803 		cp = "TCP_CLOSED";
5804 		break;
5805 	case TCPS_IDLE:
5806 		cp = "TCP_IDLE";
5807 		break;
5808 	case TCPS_BOUND:
5809 		cp = "TCP_BOUND";
5810 		break;
5811 	case TCPS_LISTEN:
5812 		cp = "TCP_LISTEN";
5813 		break;
5814 	case TCPS_SYN_SENT:
5815 		cp = "TCP_SYN_SENT";
5816 		break;
5817 	case TCPS_SYN_RCVD:
5818 		cp = "TCP_SYN_RCVD";
5819 		break;
5820 	case TCPS_ESTABLISHED:
5821 		cp = "TCP_ESTABLISHED";
5822 		break;
5823 	case TCPS_CLOSE_WAIT:
5824 		cp = "TCP_CLOSE_WAIT";
5825 		break;
5826 	case TCPS_FIN_WAIT_1:
5827 		cp = "TCP_FIN_WAIT_1";
5828 		break;
5829 	case TCPS_CLOSING:
5830 		cp = "TCP_CLOSING";
5831 		break;
5832 	case TCPS_LAST_ACK:
5833 		cp = "TCP_LAST_ACK";
5834 		break;
5835 	case TCPS_FIN_WAIT_2:
5836 		cp = "TCP_FIN_WAIT_2";
5837 		break;
5838 	case TCPS_TIME_WAIT:
5839 		cp = "TCP_TIME_WAIT";
5840 		break;
5841 	default:
5842 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5843 		cp = buf1;
5844 		break;
5845 	}
5846 	switch (format) {
5847 	case DISP_ADDR_AND_PORT:
5848 		if (connp->conn_ipversion == IPV4_VERSION) {
5849 			/*
5850 			 * Note that we use the remote address in the tcp_b
5851 			 * structure.  This means that it will print out
5852 			 * the real destination address, not the next hop's
5853 			 * address if source routing is used.
5854 			 */
5855 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5856 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5857 
5858 		} else {
5859 			local = connp->conn_laddr_v6;
5860 			remote = connp->conn_faddr_v6;
5861 		}
5862 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5863 		    sizeof (local_addrbuf));
5864 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5865 		    sizeof (remote_addrbuf));
5866 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5867 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5868 		    ntohs(connp->conn_fport), cp);
5869 		break;
5870 	case DISP_PORT_ONLY:
5871 	default:
5872 		(void) mi_sprintf(buf, "[%u, %u] %s",
5873 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5874 		break;
5875 	}
5876 
5877 	return (buf);
5878 }
5879 
5880 /*
5881  * Called via squeue to get on to eager's perimeter. It sends a
5882  * TH_RST if eager is in the fanout table. The listener wants the
5883  * eager to disappear either by means of tcp_eager_blowoff() or
5884  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5885  * called (via squeue) if the eager cannot be inserted in the
5886  * fanout table in tcp_input_listener().
5887  */
5888 /* ARGSUSED */
5889 void
5890 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5891 {
5892 	conn_t	*econnp = (conn_t *)arg;
5893 	tcp_t	*eager = econnp->conn_tcp;
5894 	tcp_t	*listener = eager->tcp_listener;
5895 
5896 	/*
5897 	 * We could be called because listener is closing. Since
5898 	 * the eager was using listener's queue's, we avoid
5899 	 * using the listeners queues from now on.
5900 	 */
5901 	ASSERT(eager->tcp_detached);
5902 	econnp->conn_rq = NULL;
5903 	econnp->conn_wq = NULL;
5904 
5905 	/*
5906 	 * An eager's conn_fanout will be NULL if it's a duplicate
5907 	 * for an existing 4-tuples in the conn fanout table.
5908 	 * We don't want to send an RST out in such case.
5909 	 */
5910 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5911 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5912 		    eager, eager->tcp_snxt, 0, TH_RST);
5913 	}
5914 
5915 	/* We are here because listener wants this eager gone */
5916 	if (listener != NULL) {
5917 		mutex_enter(&listener->tcp_eager_lock);
5918 		tcp_eager_unlink(eager);
5919 		if (eager->tcp_tconnind_started) {
5920 			/*
5921 			 * The eager has sent a conn_ind up to the
5922 			 * listener but listener decides to close
5923 			 * instead. We need to drop the extra ref
5924 			 * placed on eager in tcp_input_data() before
5925 			 * sending the conn_ind to listener.
5926 			 */
5927 			CONN_DEC_REF(econnp);
5928 		}
5929 		mutex_exit(&listener->tcp_eager_lock);
5930 		CONN_DEC_REF(listener->tcp_connp);
5931 	}
5932 
5933 	if (eager->tcp_state != TCPS_CLOSED)
5934 		tcp_close_detached(eager);
5935 }
5936 
5937 /*
5938  * Reset any eager connection hanging off this listener marked
5939  * with 'seqnum' and then reclaim it's resources.
5940  */
5941 static boolean_t
5942 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5943 {
5944 	tcp_t	*eager;
5945 	mblk_t 	*mp;
5946 	tcp_stack_t	*tcps = listener->tcp_tcps;
5947 
5948 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5949 	eager = listener;
5950 	mutex_enter(&listener->tcp_eager_lock);
5951 	do {
5952 		eager = eager->tcp_eager_next_q;
5953 		if (eager == NULL) {
5954 			mutex_exit(&listener->tcp_eager_lock);
5955 			return (B_FALSE);
5956 		}
5957 	} while (eager->tcp_conn_req_seqnum != seqnum);
5958 
5959 	if (eager->tcp_closemp_used) {
5960 		mutex_exit(&listener->tcp_eager_lock);
5961 		return (B_TRUE);
5962 	}
5963 	eager->tcp_closemp_used = B_TRUE;
5964 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5965 	CONN_INC_REF(eager->tcp_connp);
5966 	mutex_exit(&listener->tcp_eager_lock);
5967 	mp = &eager->tcp_closemp;
5968 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5969 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5970 	return (B_TRUE);
5971 }
5972 
5973 /*
5974  * Reset any eager connection hanging off this listener
5975  * and then reclaim it's resources.
5976  */
5977 static void
5978 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5979 {
5980 	tcp_t	*eager;
5981 	mblk_t	*mp;
5982 	tcp_stack_t	*tcps = listener->tcp_tcps;
5983 
5984 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5985 
5986 	if (!q0_only) {
5987 		/* First cleanup q */
5988 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5989 		eager = listener->tcp_eager_next_q;
5990 		while (eager != NULL) {
5991 			if (!eager->tcp_closemp_used) {
5992 				eager->tcp_closemp_used = B_TRUE;
5993 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5994 				CONN_INC_REF(eager->tcp_connp);
5995 				mp = &eager->tcp_closemp;
5996 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5997 				    tcp_eager_kill, eager->tcp_connp, NULL,
5998 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5999 			}
6000 			eager = eager->tcp_eager_next_q;
6001 		}
6002 	}
6003 	/* Then cleanup q0 */
6004 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6005 	eager = listener->tcp_eager_next_q0;
6006 	while (eager != listener) {
6007 		if (!eager->tcp_closemp_used) {
6008 			eager->tcp_closemp_used = B_TRUE;
6009 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6010 			CONN_INC_REF(eager->tcp_connp);
6011 			mp = &eager->tcp_closemp;
6012 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6013 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
6014 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6015 		}
6016 		eager = eager->tcp_eager_next_q0;
6017 	}
6018 }
6019 
6020 /*
6021  * If we are an eager connection hanging off a listener that hasn't
6022  * formally accepted the connection yet, get off his list and blow off
6023  * any data that we have accumulated.
6024  */
6025 static void
6026 tcp_eager_unlink(tcp_t *tcp)
6027 {
6028 	tcp_t	*listener = tcp->tcp_listener;
6029 
6030 	ASSERT(listener != NULL);
6031 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6032 	if (tcp->tcp_eager_next_q0 != NULL) {
6033 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6034 
6035 		/* Remove the eager tcp from q0 */
6036 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6037 		    tcp->tcp_eager_prev_q0;
6038 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6039 		    tcp->tcp_eager_next_q0;
6040 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6041 		listener->tcp_conn_req_cnt_q0--;
6042 
6043 		tcp->tcp_eager_next_q0 = NULL;
6044 		tcp->tcp_eager_prev_q0 = NULL;
6045 
6046 		/*
6047 		 * Take the eager out, if it is in the list of droppable
6048 		 * eagers.
6049 		 */
6050 		MAKE_UNDROPPABLE(tcp);
6051 
6052 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6053 			/* we have timed out before */
6054 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6055 			listener->tcp_syn_rcvd_timeout--;
6056 		}
6057 	} else {
6058 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6059 		tcp_t	*prev = NULL;
6060 
6061 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6062 			if (tcpp[0] == tcp) {
6063 				if (listener->tcp_eager_last_q == tcp) {
6064 					/*
6065 					 * If we are unlinking the last
6066 					 * element on the list, adjust
6067 					 * tail pointer. Set tail pointer
6068 					 * to nil when list is empty.
6069 					 */
6070 					ASSERT(tcp->tcp_eager_next_q == NULL);
6071 					if (listener->tcp_eager_last_q ==
6072 					    listener->tcp_eager_next_q) {
6073 						listener->tcp_eager_last_q =
6074 						    NULL;
6075 					} else {
6076 						/*
6077 						 * We won't get here if there
6078 						 * is only one eager in the
6079 						 * list.
6080 						 */
6081 						ASSERT(prev != NULL);
6082 						listener->tcp_eager_last_q =
6083 						    prev;
6084 					}
6085 				}
6086 				tcpp[0] = tcp->tcp_eager_next_q;
6087 				tcp->tcp_eager_next_q = NULL;
6088 				tcp->tcp_eager_last_q = NULL;
6089 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6090 				listener->tcp_conn_req_cnt_q--;
6091 				break;
6092 			}
6093 			prev = tcpp[0];
6094 		}
6095 	}
6096 	tcp->tcp_listener = NULL;
6097 }
6098 
6099 /* Shorthand to generate and send TPI error acks to our client */
6100 static void
6101 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6102 {
6103 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6104 		putnext(tcp->tcp_connp->conn_rq, mp);
6105 }
6106 
6107 /* Shorthand to generate and send TPI error acks to our client */
6108 static void
6109 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6110     int t_error, int sys_error)
6111 {
6112 	struct T_error_ack	*teackp;
6113 
6114 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6115 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6116 		teackp = (struct T_error_ack *)mp->b_rptr;
6117 		teackp->ERROR_prim = primitive;
6118 		teackp->TLI_error = t_error;
6119 		teackp->UNIX_error = sys_error;
6120 		putnext(tcp->tcp_connp->conn_rq, mp);
6121 	}
6122 }
6123 
6124 /*
6125  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6126  * but instead the code relies on:
6127  * - the fact that the address of the array and its size never changes
6128  * - the atomic assignment of the elements of the array
6129  */
6130 /* ARGSUSED */
6131 static int
6132 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6133 {
6134 	int i;
6135 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6136 
6137 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6138 		if (tcps->tcps_g_epriv_ports[i] != 0)
6139 			(void) mi_mpprintf(mp, "%d ",
6140 			    tcps->tcps_g_epriv_ports[i]);
6141 	}
6142 	return (0);
6143 }
6144 
6145 /*
6146  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6147  * threads from changing it at the same time.
6148  */
6149 /* ARGSUSED */
6150 static int
6151 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6152     cred_t *cr)
6153 {
6154 	long	new_value;
6155 	int	i;
6156 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6157 
6158 	/*
6159 	 * Fail the request if the new value does not lie within the
6160 	 * port number limits.
6161 	 */
6162 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6163 	    new_value <= 0 || new_value >= 65536) {
6164 		return (EINVAL);
6165 	}
6166 
6167 	mutex_enter(&tcps->tcps_epriv_port_lock);
6168 	/* Check if the value is already in the list */
6169 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6170 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
6171 			mutex_exit(&tcps->tcps_epriv_port_lock);
6172 			return (EEXIST);
6173 		}
6174 	}
6175 	/* Find an empty slot */
6176 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6177 		if (tcps->tcps_g_epriv_ports[i] == 0)
6178 			break;
6179 	}
6180 	if (i == tcps->tcps_g_num_epriv_ports) {
6181 		mutex_exit(&tcps->tcps_epriv_port_lock);
6182 		return (EOVERFLOW);
6183 	}
6184 	/* Set the new value */
6185 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
6186 	mutex_exit(&tcps->tcps_epriv_port_lock);
6187 	return (0);
6188 }
6189 
6190 /*
6191  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6192  * threads from changing it at the same time.
6193  */
6194 /* ARGSUSED */
6195 static int
6196 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6197     cred_t *cr)
6198 {
6199 	long	new_value;
6200 	int	i;
6201 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6202 
6203 	/*
6204 	 * Fail the request if the new value does not lie within the
6205 	 * port number limits.
6206 	 */
6207 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6208 	    new_value >= 65536) {
6209 		return (EINVAL);
6210 	}
6211 
6212 	mutex_enter(&tcps->tcps_epriv_port_lock);
6213 	/* Check that the value is already in the list */
6214 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6215 		if (tcps->tcps_g_epriv_ports[i] == new_value)
6216 			break;
6217 	}
6218 	if (i == tcps->tcps_g_num_epriv_ports) {
6219 		mutex_exit(&tcps->tcps_epriv_port_lock);
6220 		return (ESRCH);
6221 	}
6222 	/* Clear the value */
6223 	tcps->tcps_g_epriv_ports[i] = 0;
6224 	mutex_exit(&tcps->tcps_epriv_port_lock);
6225 	return (0);
6226 }
6227 
6228 /* Return the TPI/TLI equivalent of our current tcp_state */
6229 static int
6230 tcp_tpistate(tcp_t *tcp)
6231 {
6232 	switch (tcp->tcp_state) {
6233 	case TCPS_IDLE:
6234 		return (TS_UNBND);
6235 	case TCPS_LISTEN:
6236 		/*
6237 		 * Return whether there are outstanding T_CONN_IND waiting
6238 		 * for the matching T_CONN_RES. Therefore don't count q0.
6239 		 */
6240 		if (tcp->tcp_conn_req_cnt_q > 0)
6241 			return (TS_WRES_CIND);
6242 		else
6243 			return (TS_IDLE);
6244 	case TCPS_BOUND:
6245 		return (TS_IDLE);
6246 	case TCPS_SYN_SENT:
6247 		return (TS_WCON_CREQ);
6248 	case TCPS_SYN_RCVD:
6249 		/*
6250 		 * Note: assumption: this has to the active open SYN_RCVD.
6251 		 * The passive instance is detached in SYN_RCVD stage of
6252 		 * incoming connection processing so we cannot get request
6253 		 * for T_info_ack on it.
6254 		 */
6255 		return (TS_WACK_CRES);
6256 	case TCPS_ESTABLISHED:
6257 		return (TS_DATA_XFER);
6258 	case TCPS_CLOSE_WAIT:
6259 		return (TS_WREQ_ORDREL);
6260 	case TCPS_FIN_WAIT_1:
6261 		return (TS_WIND_ORDREL);
6262 	case TCPS_FIN_WAIT_2:
6263 		return (TS_WIND_ORDREL);
6264 
6265 	case TCPS_CLOSING:
6266 	case TCPS_LAST_ACK:
6267 	case TCPS_TIME_WAIT:
6268 	case TCPS_CLOSED:
6269 		/*
6270 		 * Following TS_WACK_DREQ7 is a rendition of "not
6271 		 * yet TS_IDLE" TPI state. There is no best match to any
6272 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6273 		 * choose a value chosen that will map to TLI/XTI level
6274 		 * state of TSTATECHNG (state is process of changing) which
6275 		 * captures what this dummy state represents.
6276 		 */
6277 		return (TS_WACK_DREQ7);
6278 	default:
6279 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6280 		    tcp->tcp_state, tcp_display(tcp, NULL,
6281 		    DISP_PORT_ONLY));
6282 		return (TS_UNBND);
6283 	}
6284 }
6285 
6286 static void
6287 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6288 {
6289 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6290 	conn_t		*connp = tcp->tcp_connp;
6291 
6292 	if (connp->conn_family == AF_INET6)
6293 		*tia = tcp_g_t_info_ack_v6;
6294 	else
6295 		*tia = tcp_g_t_info_ack;
6296 	tia->CURRENT_state = tcp_tpistate(tcp);
6297 	tia->OPT_size = tcp_max_optsize;
6298 	if (tcp->tcp_mss == 0) {
6299 		/* Not yet set - tcp_open does not set mss */
6300 		if (connp->conn_ipversion == IPV4_VERSION)
6301 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6302 		else
6303 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6304 	} else {
6305 		tia->TIDU_size = tcp->tcp_mss;
6306 	}
6307 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6308 }
6309 
6310 static void
6311 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6312     t_uscalar_t cap_bits1)
6313 {
6314 	tcap->CAP_bits1 = 0;
6315 
6316 	if (cap_bits1 & TC1_INFO) {
6317 		tcp_copy_info(&tcap->INFO_ack, tcp);
6318 		tcap->CAP_bits1 |= TC1_INFO;
6319 	}
6320 
6321 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6322 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6323 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6324 	}
6325 
6326 }
6327 
6328 /*
6329  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6330  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6331  * tcp_g_t_info_ack.  The current state of the stream is copied from
6332  * tcp_state.
6333  */
6334 static void
6335 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6336 {
6337 	t_uscalar_t		cap_bits1;
6338 	struct T_capability_ack	*tcap;
6339 
6340 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6341 		freemsg(mp);
6342 		return;
6343 	}
6344 
6345 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6346 
6347 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6348 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6349 	if (mp == NULL)
6350 		return;
6351 
6352 	tcap = (struct T_capability_ack *)mp->b_rptr;
6353 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6354 
6355 	putnext(tcp->tcp_connp->conn_rq, mp);
6356 }
6357 
6358 /*
6359  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6360  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6361  * The current state of the stream is copied from tcp_state.
6362  */
6363 static void
6364 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6365 {
6366 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6367 	    T_INFO_ACK);
6368 	if (!mp) {
6369 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6370 		return;
6371 	}
6372 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6373 	putnext(tcp->tcp_connp->conn_rq, mp);
6374 }
6375 
6376 /* Respond to the TPI addr request */
6377 static void
6378 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6379 {
6380 	struct sockaddr *sa;
6381 	mblk_t	*ackmp;
6382 	struct T_addr_ack *taa;
6383 	conn_t	*connp = tcp->tcp_connp;
6384 	uint_t	addrlen;
6385 
6386 	/* Make it large enough for worst case */
6387 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6388 	    2 * sizeof (sin6_t), 1);
6389 	if (ackmp == NULL) {
6390 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6391 		return;
6392 	}
6393 
6394 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6395 
6396 	bzero(taa, sizeof (struct T_addr_ack));
6397 	ackmp->b_wptr = (uchar_t *)&taa[1];
6398 
6399 	taa->PRIM_type = T_ADDR_ACK;
6400 	ackmp->b_datap->db_type = M_PCPROTO;
6401 
6402 	if (connp->conn_family == AF_INET)
6403 		addrlen = sizeof (sin_t);
6404 	else
6405 		addrlen = sizeof (sin6_t);
6406 
6407 	/*
6408 	 * Note: Following code assumes 32 bit alignment of basic
6409 	 * data structures like sin_t and struct T_addr_ack.
6410 	 */
6411 	if (tcp->tcp_state >= TCPS_BOUND) {
6412 		/*
6413 		 * Fill in local address first
6414 		 */
6415 		taa->LOCADDR_offset = sizeof (*taa);
6416 		taa->LOCADDR_length = addrlen;
6417 		sa = (struct sockaddr *)&taa[1];
6418 		(void) conn_getsockname(connp, sa, &addrlen);
6419 		ackmp->b_wptr += addrlen;
6420 	}
6421 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6422 		/*
6423 		 * Fill in Remote address
6424 		 */
6425 		taa->REMADDR_length = addrlen;
6426 		/* assumed 32-bit alignment */
6427 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6428 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6429 		(void) conn_getpeername(connp, sa, &addrlen);
6430 		ackmp->b_wptr += addrlen;
6431 	}
6432 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6433 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6434 }
6435 
6436 /*
6437  * Handle reinitialization of a tcp structure.
6438  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6439  */
6440 static void
6441 tcp_reinit(tcp_t *tcp)
6442 {
6443 	mblk_t		*mp;
6444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6445 	conn_t		*connp  = tcp->tcp_connp;
6446 
6447 	TCP_STAT(tcps, tcp_reinit_calls);
6448 
6449 	/* tcp_reinit should never be called for detached tcp_t's */
6450 	ASSERT(tcp->tcp_listener == NULL);
6451 	ASSERT((connp->conn_family == AF_INET &&
6452 	    connp->conn_ipversion == IPV4_VERSION) ||
6453 	    (connp->conn_family == AF_INET6 &&
6454 	    (connp->conn_ipversion == IPV4_VERSION ||
6455 	    connp->conn_ipversion == IPV6_VERSION)));
6456 
6457 	/* Cancel outstanding timers */
6458 	tcp_timers_stop(tcp);
6459 
6460 	/*
6461 	 * Reset everything in the state vector, after updating global
6462 	 * MIB data from instance counters.
6463 	 */
6464 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6465 	tcp->tcp_ibsegs = 0;
6466 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6467 	tcp->tcp_obsegs = 0;
6468 
6469 	tcp_close_mpp(&tcp->tcp_xmit_head);
6470 	if (tcp->tcp_snd_zcopy_aware)
6471 		tcp_zcopy_notify(tcp);
6472 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6473 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6474 	mutex_enter(&tcp->tcp_non_sq_lock);
6475 	if (tcp->tcp_flow_stopped &&
6476 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6477 		tcp_clrqfull(tcp);
6478 	}
6479 	mutex_exit(&tcp->tcp_non_sq_lock);
6480 	tcp_close_mpp(&tcp->tcp_reass_head);
6481 	tcp->tcp_reass_tail = NULL;
6482 	if (tcp->tcp_rcv_list != NULL) {
6483 		/* Free b_next chain */
6484 		tcp_close_mpp(&tcp->tcp_rcv_list);
6485 		tcp->tcp_rcv_last_head = NULL;
6486 		tcp->tcp_rcv_last_tail = NULL;
6487 		tcp->tcp_rcv_cnt = 0;
6488 	}
6489 	tcp->tcp_rcv_last_tail = NULL;
6490 
6491 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6492 		freemsg(mp);
6493 		tcp->tcp_urp_mp = NULL;
6494 	}
6495 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6496 		freemsg(mp);
6497 		tcp->tcp_urp_mark_mp = NULL;
6498 	}
6499 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6500 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6501 		freeb(tcp->tcp_fused_sigurg_mp);
6502 		tcp->tcp_fused_sigurg_mp = NULL;
6503 	}
6504 	if (tcp->tcp_ordrel_mp != NULL) {
6505 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6506 		freeb(tcp->tcp_ordrel_mp);
6507 		tcp->tcp_ordrel_mp = NULL;
6508 	}
6509 
6510 	/*
6511 	 * Following is a union with two members which are
6512 	 * identical types and size so the following cleanup
6513 	 * is enough.
6514 	 */
6515 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6516 
6517 	CL_INET_DISCONNECT(connp);
6518 
6519 	/*
6520 	 * The connection can't be on the tcp_time_wait_head list
6521 	 * since it is not detached.
6522 	 */
6523 	ASSERT(tcp->tcp_time_wait_next == NULL);
6524 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6525 	ASSERT(tcp->tcp_time_wait_expire == 0);
6526 
6527 	if (tcp->tcp_kssl_pending) {
6528 		tcp->tcp_kssl_pending = B_FALSE;
6529 
6530 		/* Don't reset if the initialized by bind. */
6531 		if (tcp->tcp_kssl_ent != NULL) {
6532 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6533 			    KSSL_NO_PROXY);
6534 		}
6535 	}
6536 	if (tcp->tcp_kssl_ctx != NULL) {
6537 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6538 		tcp->tcp_kssl_ctx = NULL;
6539 	}
6540 
6541 	/*
6542 	 * Reset/preserve other values
6543 	 */
6544 	tcp_reinit_values(tcp);
6545 	ipcl_hash_remove(connp);
6546 	/* Note that ixa_cred gets cleared in ixa_cleanup */
6547 	ixa_cleanup(connp->conn_ixa);
6548 	tcp_ipsec_cleanup(tcp);
6549 
6550 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6551 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6552 
6553 	if (tcp->tcp_conn_req_max != 0) {
6554 		/*
6555 		 * This is the case when a TLI program uses the same
6556 		 * transport end point to accept a connection.  This
6557 		 * makes the TCP both a listener and acceptor.  When
6558 		 * this connection is closed, we need to set the state
6559 		 * back to TCPS_LISTEN.  Make sure that the eager list
6560 		 * is reinitialized.
6561 		 *
6562 		 * Note that this stream is still bound to the four
6563 		 * tuples of the previous connection in IP.  If a new
6564 		 * SYN with different foreign address comes in, IP will
6565 		 * not find it and will send it to the global queue.  In
6566 		 * the global queue, TCP will do a tcp_lookup_listener()
6567 		 * to find this stream.  This works because this stream
6568 		 * is only removed from connected hash.
6569 		 *
6570 		 */
6571 		tcp->tcp_state = TCPS_LISTEN;
6572 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6573 		tcp->tcp_eager_next_drop_q0 = tcp;
6574 		tcp->tcp_eager_prev_drop_q0 = tcp;
6575 		/*
6576 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6577 		 * to pick a good squeue for the listener when the first SYN
6578 		 * arrives. tcp_input_listener_unbound sets it to
6579 		 * tcp_input_listener on that first SYN.
6580 		 */
6581 		connp->conn_recv = tcp_input_listener_unbound;
6582 
6583 		connp->conn_proto = IPPROTO_TCP;
6584 		connp->conn_faddr_v6 = ipv6_all_zeros;
6585 		connp->conn_fport = 0;
6586 
6587 		(void) ipcl_bind_insert(connp);
6588 	} else {
6589 		tcp->tcp_state = TCPS_BOUND;
6590 	}
6591 
6592 	/*
6593 	 * Initialize to default values
6594 	 */
6595 	tcp_init_values(tcp);
6596 
6597 	ASSERT(tcp->tcp_ptpbhn != NULL);
6598 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6599 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6600 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6601 }
6602 
6603 /*
6604  * Force values to zero that need be zero.
6605  * Do not touch values asociated with the BOUND or LISTEN state
6606  * since the connection will end up in that state after the reinit.
6607  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6608  * structure!
6609  */
6610 static void
6611 tcp_reinit_values(tcp)
6612 	tcp_t *tcp;
6613 {
6614 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6615 	conn_t		*connp = tcp->tcp_connp;
6616 
6617 #ifndef	lint
6618 #define	DONTCARE(x)
6619 #define	PRESERVE(x)
6620 #else
6621 #define	DONTCARE(x)	((x) = (x))
6622 #define	PRESERVE(x)	((x) = (x))
6623 #endif	/* lint */
6624 
6625 	PRESERVE(tcp->tcp_bind_hash_port);
6626 	PRESERVE(tcp->tcp_bind_hash);
6627 	PRESERVE(tcp->tcp_ptpbhn);
6628 	PRESERVE(tcp->tcp_acceptor_hash);
6629 	PRESERVE(tcp->tcp_ptpahn);
6630 
6631 	/* Should be ASSERT NULL on these with new code! */
6632 	ASSERT(tcp->tcp_time_wait_next == NULL);
6633 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6634 	ASSERT(tcp->tcp_time_wait_expire == 0);
6635 	PRESERVE(tcp->tcp_state);
6636 	PRESERVE(connp->conn_rq);
6637 	PRESERVE(connp->conn_wq);
6638 
6639 	ASSERT(tcp->tcp_xmit_head == NULL);
6640 	ASSERT(tcp->tcp_xmit_last == NULL);
6641 	ASSERT(tcp->tcp_unsent == 0);
6642 	ASSERT(tcp->tcp_xmit_tail == NULL);
6643 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6644 
6645 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6646 	tcp->tcp_suna = 0;			/* Displayed in mib */
6647 	tcp->tcp_swnd = 0;
6648 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6649 
6650 	ASSERT(tcp->tcp_ibsegs == 0);
6651 	ASSERT(tcp->tcp_obsegs == 0);
6652 
6653 	if (connp->conn_ht_iphc != NULL) {
6654 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6655 		connp->conn_ht_iphc = NULL;
6656 		connp->conn_ht_iphc_allocated = 0;
6657 		connp->conn_ht_iphc_len = 0;
6658 		connp->conn_ht_ulp = NULL;
6659 		connp->conn_ht_ulp_len = 0;
6660 		tcp->tcp_ipha = NULL;
6661 		tcp->tcp_ip6h = NULL;
6662 		tcp->tcp_tcpha = NULL;
6663 	}
6664 
6665 	/* We clear any IP_OPTIONS and extension headers */
6666 	ip_pkt_free(&connp->conn_xmit_ipp);
6667 
6668 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6669 	DONTCARE(tcp->tcp_ipha);
6670 	DONTCARE(tcp->tcp_ip6h);
6671 	DONTCARE(tcp->tcp_tcpha);
6672 	tcp->tcp_valid_bits = 0;
6673 
6674 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6675 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6676 	tcp->tcp_last_rcv_lbolt = 0;
6677 
6678 	tcp->tcp_init_cwnd = 0;
6679 
6680 	tcp->tcp_urp_last_valid = 0;
6681 	tcp->tcp_hard_binding = 0;
6682 
6683 	tcp->tcp_fin_acked = 0;
6684 	tcp->tcp_fin_rcvd = 0;
6685 	tcp->tcp_fin_sent = 0;
6686 	tcp->tcp_ordrel_done = 0;
6687 
6688 	tcp->tcp_detached = 0;
6689 
6690 	tcp->tcp_snd_ws_ok = B_FALSE;
6691 	tcp->tcp_snd_ts_ok = B_FALSE;
6692 	tcp->tcp_zero_win_probe = 0;
6693 
6694 	tcp->tcp_loopback = 0;
6695 	tcp->tcp_localnet = 0;
6696 	tcp->tcp_syn_defense = 0;
6697 	tcp->tcp_set_timer = 0;
6698 
6699 	tcp->tcp_active_open = 0;
6700 	tcp->tcp_rexmit = B_FALSE;
6701 	tcp->tcp_xmit_zc_clean = B_FALSE;
6702 
6703 	tcp->tcp_snd_sack_ok = B_FALSE;
6704 	tcp->tcp_hwcksum = B_FALSE;
6705 
6706 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6707 
6708 	tcp->tcp_conn_def_q0 = 0;
6709 	tcp->tcp_ip_forward_progress = B_FALSE;
6710 	tcp->tcp_ecn_ok = B_FALSE;
6711 
6712 	tcp->tcp_cwr = B_FALSE;
6713 	tcp->tcp_ecn_echo_on = B_FALSE;
6714 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6715 
6716 	if (tcp->tcp_sack_info != NULL) {
6717 		if (tcp->tcp_notsack_list != NULL) {
6718 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6719 			    tcp);
6720 		}
6721 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6722 		tcp->tcp_sack_info = NULL;
6723 	}
6724 
6725 	tcp->tcp_rcv_ws = 0;
6726 	tcp->tcp_snd_ws = 0;
6727 	tcp->tcp_ts_recent = 0;
6728 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6729 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6730 	tcp->tcp_initial_pmtu = 0;
6731 
6732 	ASSERT(tcp->tcp_reass_head == NULL);
6733 	ASSERT(tcp->tcp_reass_tail == NULL);
6734 
6735 	tcp->tcp_cwnd_cnt = 0;
6736 
6737 	ASSERT(tcp->tcp_rcv_list == NULL);
6738 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6739 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6740 	ASSERT(tcp->tcp_rcv_cnt == 0);
6741 
6742 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6743 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6744 	tcp->tcp_csuna = 0;
6745 
6746 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6747 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6748 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6749 	tcp->tcp_rtt_update = 0;
6750 
6751 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6752 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6753 
6754 	tcp->tcp_rack = 0;			/* Displayed in mib */
6755 	tcp->tcp_rack_cnt = 0;
6756 	tcp->tcp_rack_cur_max = 0;
6757 	tcp->tcp_rack_abs_max = 0;
6758 
6759 	tcp->tcp_max_swnd = 0;
6760 
6761 	ASSERT(tcp->tcp_listener == NULL);
6762 
6763 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6764 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6765 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6766 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6767 
6768 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6769 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6770 	PRESERVE(tcp->tcp_conn_req_max);
6771 	PRESERVE(tcp->tcp_conn_req_seqnum);
6772 
6773 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6774 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6775 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6776 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6777 
6778 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6779 	ASSERT(tcp->tcp_urp_mp == NULL);
6780 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6781 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6782 
6783 	ASSERT(tcp->tcp_eager_next_q == NULL);
6784 	ASSERT(tcp->tcp_eager_last_q == NULL);
6785 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6786 	    tcp->tcp_eager_prev_q0 == NULL) ||
6787 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6788 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6789 
6790 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6791 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6792 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6793 
6794 	tcp->tcp_client_errno = 0;
6795 
6796 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6797 
6798 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6799 
6800 	PRESERVE(connp->conn_bound_addr_v6);
6801 	tcp->tcp_last_sent_len = 0;
6802 	tcp->tcp_dupack_cnt = 0;
6803 
6804 	connp->conn_fport = 0;			/* Displayed in MIB */
6805 	PRESERVE(connp->conn_lport);
6806 
6807 	PRESERVE(tcp->tcp_acceptor_lockp);
6808 
6809 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6810 	PRESERVE(tcp->tcp_acceptor_id);
6811 	DONTCARE(tcp->tcp_ipsec_overhead);
6812 
6813 	PRESERVE(connp->conn_family);
6814 	/* Remove any remnants of mapped address binding */
6815 	if (connp->conn_family == AF_INET6) {
6816 		connp->conn_ipversion = IPV6_VERSION;
6817 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6818 	} else {
6819 		connp->conn_ipversion = IPV4_VERSION;
6820 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6821 	}
6822 
6823 	connp->conn_bound_if = 0;
6824 	connp->conn_recv_ancillary.crb_all = 0;
6825 	tcp->tcp_recvifindex = 0;
6826 	tcp->tcp_recvhops = 0;
6827 	tcp->tcp_closed = 0;
6828 	tcp->tcp_cleandeathtag = 0;
6829 	if (tcp->tcp_hopopts != NULL) {
6830 		mi_free(tcp->tcp_hopopts);
6831 		tcp->tcp_hopopts = NULL;
6832 		tcp->tcp_hopoptslen = 0;
6833 	}
6834 	ASSERT(tcp->tcp_hopoptslen == 0);
6835 	if (tcp->tcp_dstopts != NULL) {
6836 		mi_free(tcp->tcp_dstopts);
6837 		tcp->tcp_dstopts = NULL;
6838 		tcp->tcp_dstoptslen = 0;
6839 	}
6840 	ASSERT(tcp->tcp_dstoptslen == 0);
6841 	if (tcp->tcp_rthdrdstopts != NULL) {
6842 		mi_free(tcp->tcp_rthdrdstopts);
6843 		tcp->tcp_rthdrdstopts = NULL;
6844 		tcp->tcp_rthdrdstoptslen = 0;
6845 	}
6846 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6847 	if (tcp->tcp_rthdr != NULL) {
6848 		mi_free(tcp->tcp_rthdr);
6849 		tcp->tcp_rthdr = NULL;
6850 		tcp->tcp_rthdrlen = 0;
6851 	}
6852 	ASSERT(tcp->tcp_rthdrlen == 0);
6853 
6854 	/* Reset fusion-related fields */
6855 	tcp->tcp_fused = B_FALSE;
6856 	tcp->tcp_unfusable = B_FALSE;
6857 	tcp->tcp_fused_sigurg = B_FALSE;
6858 	tcp->tcp_loopback_peer = NULL;
6859 
6860 	tcp->tcp_lso = B_FALSE;
6861 
6862 	tcp->tcp_in_ack_unsent = 0;
6863 	tcp->tcp_cork = B_FALSE;
6864 	tcp->tcp_tconnind_started = B_FALSE;
6865 
6866 	PRESERVE(tcp->tcp_squeue_bytes);
6867 
6868 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6869 	ASSERT(!tcp->tcp_kssl_pending);
6870 	PRESERVE(tcp->tcp_kssl_ent);
6871 
6872 	tcp->tcp_closemp_used = B_FALSE;
6873 
6874 	PRESERVE(tcp->tcp_rsrv_mp);
6875 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6876 
6877 #ifdef DEBUG
6878 	DONTCARE(tcp->tcmp_stk[0]);
6879 #endif
6880 
6881 	PRESERVE(tcp->tcp_connid);
6882 
6883 	ASSERT(tcp->tcp_listen_cnt == NULL);
6884 	ASSERT(tcp->tcp_reass_tid == 0);
6885 
6886 #undef	DONTCARE
6887 #undef	PRESERVE
6888 }
6889 
6890 static void
6891 tcp_init_values(tcp_t *tcp)
6892 {
6893 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6894 	conn_t		*connp = tcp->tcp_connp;
6895 
6896 	ASSERT((connp->conn_family == AF_INET &&
6897 	    connp->conn_ipversion == IPV4_VERSION) ||
6898 	    (connp->conn_family == AF_INET6 &&
6899 	    (connp->conn_ipversion == IPV4_VERSION ||
6900 	    connp->conn_ipversion == IPV6_VERSION)));
6901 
6902 	/*
6903 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6904 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6905 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6906 	 * during first few transmissions of a connection as seen in slow
6907 	 * links.
6908 	 */
6909 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6910 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6911 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6912 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6913 	    tcps->tcps_conn_grace_period;
6914 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6915 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6916 	tcp->tcp_timer_backoff = 0;
6917 	tcp->tcp_ms_we_have_waited = 0;
6918 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6919 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6920 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6921 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6922 
6923 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6924 
6925 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6926 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6927 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6928 	/*
6929 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6930 	 * passive open.
6931 	 */
6932 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6933 
6934 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6935 
6936 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6937 
6938 	/* Reset fusion-related fields */
6939 	tcp->tcp_fused = B_FALSE;
6940 	tcp->tcp_unfusable = B_FALSE;
6941 	tcp->tcp_fused_sigurg = B_FALSE;
6942 	tcp->tcp_loopback_peer = NULL;
6943 
6944 	/* We rebuild the header template on the next connect/conn_request */
6945 
6946 	connp->conn_mlp_type = mlptSingle;
6947 
6948 	/*
6949 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6950 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6951 	 */
6952 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6953 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6954 
6955 	tcp->tcp_cork = B_FALSE;
6956 	/*
6957 	 * Init the tcp_debug option if it wasn't already set.  This value
6958 	 * determines whether TCP
6959 	 * calls strlog() to print out debug messages.  Doing this
6960 	 * initialization here means that this value is not inherited thru
6961 	 * tcp_reinit().
6962 	 */
6963 	if (!connp->conn_debug)
6964 		connp->conn_debug = tcps->tcps_dbg;
6965 
6966 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6967 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6968 }
6969 
6970 /* At minimum we need 8 bytes in the TCP header for the lookup */
6971 #define	ICMP_MIN_TCP_HDR	8
6972 
6973 /*
6974  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6975  * passed up by IP. The message is always received on the correct tcp_t.
6976  * Assumes that IP has pulled up everything up to and including the ICMP header.
6977  */
6978 /* ARGSUSED2 */
6979 static void
6980 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6981 {
6982 	conn_t		*connp = (conn_t *)arg1;
6983 	icmph_t		*icmph;
6984 	ipha_t		*ipha;
6985 	int		iph_hdr_length;
6986 	tcpha_t		*tcpha;
6987 	uint32_t	seg_seq;
6988 	tcp_t		*tcp = connp->conn_tcp;
6989 
6990 	/* Assume IP provides aligned packets */
6991 	ASSERT(OK_32PTR(mp->b_rptr));
6992 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6993 
6994 	/*
6995 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6996 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6997 	 */
6998 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6999 		tcp_icmp_error_ipv6(tcp, mp, ira);
7000 		return;
7001 	}
7002 
7003 	/* Skip past the outer IP and ICMP headers */
7004 	iph_hdr_length = ira->ira_ip_hdr_length;
7005 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7006 	/*
7007 	 * If we don't have the correct outer IP header length
7008 	 * or if we don't have a complete inner IP header
7009 	 * drop it.
7010 	 */
7011 	if (iph_hdr_length < sizeof (ipha_t) ||
7012 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7013 noticmpv4:
7014 		freemsg(mp);
7015 		return;
7016 	}
7017 	ipha = (ipha_t *)&icmph[1];
7018 
7019 	/* Skip past the inner IP and find the ULP header */
7020 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7021 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
7022 	/*
7023 	 * If we don't have the correct inner IP header length or if the ULP
7024 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7025 	 * bytes of TCP header, drop it.
7026 	 */
7027 	if (iph_hdr_length < sizeof (ipha_t) ||
7028 	    ipha->ipha_protocol != IPPROTO_TCP ||
7029 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7030 		goto noticmpv4;
7031 	}
7032 
7033 	seg_seq = ntohl(tcpha->tha_seq);
7034 	switch (icmph->icmph_type) {
7035 	case ICMP_DEST_UNREACHABLE:
7036 		switch (icmph->icmph_code) {
7037 		case ICMP_FRAGMENTATION_NEEDED:
7038 			/*
7039 			 * Update Path MTU, then try to send something out.
7040 			 */
7041 			tcp_update_pmtu(tcp, B_TRUE);
7042 			tcp_rexmit_after_error(tcp);
7043 			break;
7044 		case ICMP_PORT_UNREACHABLE:
7045 		case ICMP_PROTOCOL_UNREACHABLE:
7046 			switch (tcp->tcp_state) {
7047 			case TCPS_SYN_SENT:
7048 			case TCPS_SYN_RCVD:
7049 				/*
7050 				 * ICMP can snipe away incipient
7051 				 * TCP connections as long as
7052 				 * seq number is same as initial
7053 				 * send seq number.
7054 				 */
7055 				if (seg_seq == tcp->tcp_iss) {
7056 					(void) tcp_clean_death(tcp,
7057 					    ECONNREFUSED, 6);
7058 				}
7059 				break;
7060 			}
7061 			break;
7062 		case ICMP_HOST_UNREACHABLE:
7063 		case ICMP_NET_UNREACHABLE:
7064 			/* Record the error in case we finally time out. */
7065 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
7066 				tcp->tcp_client_errno = EHOSTUNREACH;
7067 			else
7068 				tcp->tcp_client_errno = ENETUNREACH;
7069 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
7070 				if (tcp->tcp_listener != NULL &&
7071 				    tcp->tcp_listener->tcp_syn_defense) {
7072 					/*
7073 					 * Ditch the half-open connection if we
7074 					 * suspect a SYN attack is under way.
7075 					 */
7076 					(void) tcp_clean_death(tcp,
7077 					    tcp->tcp_client_errno, 7);
7078 				}
7079 			}
7080 			break;
7081 		default:
7082 			break;
7083 		}
7084 		break;
7085 	case ICMP_SOURCE_QUENCH: {
7086 		/*
7087 		 * use a global boolean to control
7088 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
7089 		 * The default is false.
7090 		 */
7091 		if (tcp_icmp_source_quench) {
7092 			/*
7093 			 * Reduce the sending rate as if we got a
7094 			 * retransmit timeout
7095 			 */
7096 			uint32_t npkt;
7097 
7098 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
7099 			    tcp->tcp_mss;
7100 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
7101 			tcp->tcp_cwnd = tcp->tcp_mss;
7102 			tcp->tcp_cwnd_cnt = 0;
7103 		}
7104 		break;
7105 	}
7106 	}
7107 	freemsg(mp);
7108 }
7109 
7110 /*
7111  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
7112  * change. But it can refer to fields like tcp_suna and tcp_snxt.
7113  *
7114  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
7115  * error messages received by IP. The message is always received on the correct
7116  * tcp_t.
7117  */
7118 /* ARGSUSED */
7119 static boolean_t
7120 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
7121     ip_recv_attr_t *ira)
7122 {
7123 	tcpha_t		*tcpha = (tcpha_t *)arg2;
7124 	uint32_t	seq = ntohl(tcpha->tha_seq);
7125 	tcp_t		*tcp = connp->conn_tcp;
7126 
7127 	/*
7128 	 * TCP sequence number contained in payload of the ICMP error message
7129 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
7130 	 * the message is either a stale ICMP error, or an attack from the
7131 	 * network. Fail the verification.
7132 	 */
7133 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
7134 		return (B_FALSE);
7135 
7136 	/* For "too big" we also check the ignore flag */
7137 	if (ira->ira_flags & IRAF_IS_IPV4) {
7138 		ASSERT(icmph != NULL);
7139 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
7140 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
7141 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7142 			return (B_FALSE);
7143 	} else {
7144 		ASSERT(icmp6 != NULL);
7145 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
7146 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7147 			return (B_FALSE);
7148 	}
7149 	return (B_TRUE);
7150 }
7151 
7152 /*
7153  * Update the TCP connection according to change of PMTU.
7154  *
7155  * Path MTU might have changed by either increase or decrease, so need to
7156  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
7157  * or negative MSS, since tcp_mss_set() will do it.
7158  */
7159 static void
7160 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
7161 {
7162 	uint32_t	pmtu;
7163 	int32_t		mss;
7164 	conn_t		*connp = tcp->tcp_connp;
7165 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
7166 	iaflags_t	ixaflags;
7167 
7168 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
7169 		return;
7170 
7171 	if (tcp->tcp_state < TCPS_ESTABLISHED)
7172 		return;
7173 
7174 	/*
7175 	 * Always call ip_get_pmtu() to make sure that IP has updated
7176 	 * ixa_flags properly.
7177 	 */
7178 	pmtu = ip_get_pmtu(ixa);
7179 	ixaflags = ixa->ixa_flags;
7180 
7181 	/*
7182 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
7183 	 * IPsec overhead if applied. Make sure to use the most recent
7184 	 * IPsec information.
7185 	 */
7186 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
7187 
7188 	/*
7189 	 * Nothing to change, so just return.
7190 	 */
7191 	if (mss == tcp->tcp_mss)
7192 		return;
7193 
7194 	/*
7195 	 * Currently, for ICMP errors, only PMTU decrease is handled.
7196 	 */
7197 	if (mss > tcp->tcp_mss && decrease_only)
7198 		return;
7199 
7200 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
7201 
7202 	/*
7203 	 * Update ixa_fragsize and ixa_pmtu.
7204 	 */
7205 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
7206 
7207 	/*
7208 	 * Adjust MSS and all relevant variables.
7209 	 */
7210 	tcp_mss_set(tcp, mss);
7211 
7212 	/*
7213 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
7214 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
7215 	 * has a (potentially different) min size we do the same. Make sure to
7216 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
7217 	 * fragment the packet.
7218 	 *
7219 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
7220 	 * when IPv6 fragmentation is needed.
7221 	 */
7222 	if (mss < tcp->tcp_tcps->tcps_mss_min)
7223 		ixaflags |= IXAF_PMTU_TOO_SMALL;
7224 
7225 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
7226 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
7227 
7228 	if ((connp->conn_ipversion == IPV4_VERSION) &&
7229 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
7230 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7231 	}
7232 	ixa->ixa_flags = ixaflags;
7233 }
7234 
7235 /*
7236  * Do slow start retransmission after ICMP errors of PMTU changes.
7237  */
7238 static void
7239 tcp_rexmit_after_error(tcp_t *tcp)
7240 {
7241 	/*
7242 	 * All sent data has been acknowledged or no data left to send, just
7243 	 * to return.
7244 	 */
7245 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7246 	    (tcp->tcp_xmit_head == NULL))
7247 		return;
7248 
7249 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7250 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7251 	else
7252 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7253 
7254 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7255 	tcp->tcp_rexmit = B_TRUE;
7256 	tcp->tcp_dupack_cnt = 0;
7257 	tcp->tcp_snd_burst = TCP_CWND_SS;
7258 	tcp_ss_rexmit(tcp);
7259 }
7260 
7261 /*
7262  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7263  * error messages passed up by IP.
7264  * Assumes that IP has pulled up all the extension headers as well
7265  * as the ICMPv6 header.
7266  */
7267 static void
7268 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7269 {
7270 	icmp6_t		*icmp6;
7271 	ip6_t		*ip6h;
7272 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7273 	tcpha_t		*tcpha;
7274 	uint8_t		*nexthdrp;
7275 	uint32_t	seg_seq;
7276 
7277 	/*
7278 	 * Verify that we have a complete IP header.
7279 	 */
7280 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7281 
7282 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7283 	ip6h = (ip6_t *)&icmp6[1];
7284 	/*
7285 	 * Verify if we have a complete ICMP and inner IP header.
7286 	 */
7287 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7288 noticmpv6:
7289 		freemsg(mp);
7290 		return;
7291 	}
7292 
7293 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7294 		goto noticmpv6;
7295 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7296 	/*
7297 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7298 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7299 	 * packet.
7300 	 */
7301 	if ((*nexthdrp != IPPROTO_TCP) ||
7302 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7303 		goto noticmpv6;
7304 	}
7305 
7306 	seg_seq = ntohl(tcpha->tha_seq);
7307 	switch (icmp6->icmp6_type) {
7308 	case ICMP6_PACKET_TOO_BIG:
7309 		/*
7310 		 * Update Path MTU, then try to send something out.
7311 		 */
7312 		tcp_update_pmtu(tcp, B_TRUE);
7313 		tcp_rexmit_after_error(tcp);
7314 		break;
7315 	case ICMP6_DST_UNREACH:
7316 		switch (icmp6->icmp6_code) {
7317 		case ICMP6_DST_UNREACH_NOPORT:
7318 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7319 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7320 			    (seg_seq == tcp->tcp_iss)) {
7321 				(void) tcp_clean_death(tcp,
7322 				    ECONNREFUSED, 8);
7323 			}
7324 			break;
7325 		case ICMP6_DST_UNREACH_ADMIN:
7326 		case ICMP6_DST_UNREACH_NOROUTE:
7327 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7328 		case ICMP6_DST_UNREACH_ADDR:
7329 			/* Record the error in case we finally time out. */
7330 			tcp->tcp_client_errno = EHOSTUNREACH;
7331 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7332 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7333 			    (seg_seq == tcp->tcp_iss)) {
7334 				if (tcp->tcp_listener != NULL &&
7335 				    tcp->tcp_listener->tcp_syn_defense) {
7336 					/*
7337 					 * Ditch the half-open connection if we
7338 					 * suspect a SYN attack is under way.
7339 					 */
7340 					(void) tcp_clean_death(tcp,
7341 					    tcp->tcp_client_errno, 9);
7342 				}
7343 			}
7344 
7345 
7346 			break;
7347 		default:
7348 			break;
7349 		}
7350 		break;
7351 	case ICMP6_PARAM_PROB:
7352 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7353 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7354 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7355 		    (uchar_t *)nexthdrp) {
7356 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7357 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7358 				(void) tcp_clean_death(tcp,
7359 				    ECONNREFUSED, 10);
7360 			}
7361 			break;
7362 		}
7363 		break;
7364 
7365 	case ICMP6_TIME_EXCEEDED:
7366 	default:
7367 		break;
7368 	}
7369 	freemsg(mp);
7370 }
7371 
7372 /*
7373  * Notify IP that we are having trouble with this connection.  IP should
7374  * make note so it can potentially use a different IRE.
7375  */
7376 static void
7377 tcp_ip_notify(tcp_t *tcp)
7378 {
7379 	conn_t		*connp = tcp->tcp_connp;
7380 	ire_t		*ire;
7381 
7382 	/*
7383 	 * Note: in the case of source routing we want to blow away the
7384 	 * route to the first source route hop.
7385 	 */
7386 	ire = connp->conn_ixa->ixa_ire;
7387 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7388 		if (ire->ire_ipversion == IPV4_VERSION) {
7389 			/*
7390 			 * As per RFC 1122, we send an RTM_LOSING to inform
7391 			 * routing protocols.
7392 			 */
7393 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7394 			    ire->ire_gateway_addr, ire->ire_mask,
7395 			    connp->conn_laddr_v4,  0, 0, 0,
7396 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7397 			    ire->ire_ipst);
7398 		}
7399 		(void) ire_no_good(ire);
7400 	}
7401 }
7402 
7403 #pragma inline(tcp_send_data)
7404 
7405 /*
7406  * Timer callback routine for keepalive probe.  We do a fake resend of
7407  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7408  * check to see if we have heard anything from the other end for the last
7409  * RTO period.  If we have, set the timer to expire for another
7410  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7411  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7412  * the timeout if we have not heard from the other side.  If for more than
7413  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7414  * kill the connection unless the keepalive abort threshold is 0.  In
7415  * that case, we will probe "forever."
7416  */
7417 static void
7418 tcp_keepalive_killer(void *arg)
7419 {
7420 	mblk_t	*mp;
7421 	conn_t	*connp = (conn_t *)arg;
7422 	tcp_t  	*tcp = connp->conn_tcp;
7423 	int32_t	firetime;
7424 	int32_t	idletime;
7425 	int32_t	ka_intrvl;
7426 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7427 
7428 	tcp->tcp_ka_tid = 0;
7429 
7430 	if (tcp->tcp_fused)
7431 		return;
7432 
7433 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7434 	ka_intrvl = tcp->tcp_ka_interval;
7435 
7436 	/*
7437 	 * Keepalive probe should only be sent if the application has not
7438 	 * done a close on the connection.
7439 	 */
7440 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7441 		return;
7442 	}
7443 	/* Timer fired too early, restart it. */
7444 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7445 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7446 		    MSEC_TO_TICK(ka_intrvl));
7447 		return;
7448 	}
7449 
7450 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7451 	/*
7452 	 * If we have not heard from the other side for a long
7453 	 * time, kill the connection unless the keepalive abort
7454 	 * threshold is 0.  In that case, we will probe "forever."
7455 	 */
7456 	if (tcp->tcp_ka_abort_thres != 0 &&
7457 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7458 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7459 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7460 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7461 		return;
7462 	}
7463 
7464 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7465 	    idletime >= ka_intrvl) {
7466 		/* Fake resend of last ACKed byte. */
7467 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7468 
7469 		if (mp1 != NULL) {
7470 			*mp1->b_wptr++ = '\0';
7471 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7472 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7473 			freeb(mp1);
7474 			/*
7475 			 * if allocation failed, fall through to start the
7476 			 * timer back.
7477 			 */
7478 			if (mp != NULL) {
7479 				tcp_send_data(tcp, mp);
7480 				BUMP_MIB(&tcps->tcps_mib,
7481 				    tcpTimKeepaliveProbe);
7482 				if (tcp->tcp_ka_last_intrvl != 0) {
7483 					int max;
7484 					/*
7485 					 * We should probe again at least
7486 					 * in ka_intrvl, but not more than
7487 					 * tcp_rexmit_interval_max.
7488 					 */
7489 					max = tcps->tcps_rexmit_interval_max;
7490 					firetime = MIN(ka_intrvl - 1,
7491 					    tcp->tcp_ka_last_intrvl << 1);
7492 					if (firetime > max)
7493 						firetime = max;
7494 				} else {
7495 					firetime = tcp->tcp_rto;
7496 				}
7497 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7498 				    tcp_keepalive_killer,
7499 				    MSEC_TO_TICK(firetime));
7500 				tcp->tcp_ka_last_intrvl = firetime;
7501 				return;
7502 			}
7503 		}
7504 	} else {
7505 		tcp->tcp_ka_last_intrvl = 0;
7506 	}
7507 
7508 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7509 	if ((firetime = ka_intrvl - idletime) < 0) {
7510 		firetime = ka_intrvl;
7511 	}
7512 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7513 	    MSEC_TO_TICK(firetime));
7514 }
7515 
7516 int
7517 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7518 {
7519 	conn_t	*connp = tcp->tcp_connp;
7520 	queue_t	*q = connp->conn_rq;
7521 	int32_t	mss = tcp->tcp_mss;
7522 	int	maxpsz;
7523 
7524 	if (TCP_IS_DETACHED(tcp))
7525 		return (mss);
7526 	if (tcp->tcp_fused) {
7527 		maxpsz = tcp_fuse_maxpsz(tcp);
7528 		mss = INFPSZ;
7529 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7530 		/*
7531 		 * Set the sd_qn_maxpsz according to the socket send buffer
7532 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7533 		 * instruct the stream head to copyin user data into contiguous
7534 		 * kernel-allocated buffers without breaking it up into smaller
7535 		 * chunks.  We round up the buffer size to the nearest SMSS.
7536 		 */
7537 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7538 		if (tcp->tcp_kssl_ctx == NULL)
7539 			mss = INFPSZ;
7540 		else
7541 			mss = SSL3_MAX_RECORD_LEN;
7542 	} else {
7543 		/*
7544 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7545 		 * (and a multiple of the mss).  This instructs the stream
7546 		 * head to break down larger than SMSS writes into SMSS-
7547 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7548 		 */
7549 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7550 		if (maxpsz > connp->conn_sndbuf / 2) {
7551 			maxpsz = connp->conn_sndbuf / 2;
7552 			/* Round up to nearest mss */
7553 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7554 		}
7555 	}
7556 
7557 	(void) proto_set_maxpsz(q, connp, maxpsz);
7558 	if (!(IPCL_IS_NONSTR(connp)))
7559 		connp->conn_wq->q_maxpsz = maxpsz;
7560 	if (set_maxblk)
7561 		(void) proto_set_tx_maxblk(q, connp, mss);
7562 	return (mss);
7563 }
7564 
7565 /*
7566  * Extract option values from a tcp header.  We put any found values into the
7567  * tcpopt struct and return a bitmask saying which options were found.
7568  */
7569 static int
7570 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7571 {
7572 	uchar_t		*endp;
7573 	int		len;
7574 	uint32_t	mss;
7575 	uchar_t		*up = (uchar_t *)tcpha;
7576 	int		found = 0;
7577 	int32_t		sack_len;
7578 	tcp_seq		sack_begin, sack_end;
7579 	tcp_t		*tcp;
7580 
7581 	endp = up + TCP_HDR_LENGTH(tcpha);
7582 	up += TCP_MIN_HEADER_LENGTH;
7583 	while (up < endp) {
7584 		len = endp - up;
7585 		switch (*up) {
7586 		case TCPOPT_EOL:
7587 			break;
7588 
7589 		case TCPOPT_NOP:
7590 			up++;
7591 			continue;
7592 
7593 		case TCPOPT_MAXSEG:
7594 			if (len < TCPOPT_MAXSEG_LEN ||
7595 			    up[1] != TCPOPT_MAXSEG_LEN)
7596 				break;
7597 
7598 			mss = BE16_TO_U16(up+2);
7599 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7600 			tcpopt->tcp_opt_mss = mss;
7601 			found |= TCP_OPT_MSS_PRESENT;
7602 
7603 			up += TCPOPT_MAXSEG_LEN;
7604 			continue;
7605 
7606 		case TCPOPT_WSCALE:
7607 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7608 				break;
7609 
7610 			if (up[2] > TCP_MAX_WINSHIFT)
7611 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7612 			else
7613 				tcpopt->tcp_opt_wscale = up[2];
7614 			found |= TCP_OPT_WSCALE_PRESENT;
7615 
7616 			up += TCPOPT_WS_LEN;
7617 			continue;
7618 
7619 		case TCPOPT_SACK_PERMITTED:
7620 			if (len < TCPOPT_SACK_OK_LEN ||
7621 			    up[1] != TCPOPT_SACK_OK_LEN)
7622 				break;
7623 			found |= TCP_OPT_SACK_OK_PRESENT;
7624 			up += TCPOPT_SACK_OK_LEN;
7625 			continue;
7626 
7627 		case TCPOPT_SACK:
7628 			if (len <= 2 || up[1] <= 2 || len < up[1])
7629 				break;
7630 
7631 			/* If TCP is not interested in SACK blks... */
7632 			if ((tcp = tcpopt->tcp) == NULL) {
7633 				up += up[1];
7634 				continue;
7635 			}
7636 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7637 			up += TCPOPT_HEADER_LEN;
7638 
7639 			/*
7640 			 * If the list is empty, allocate one and assume
7641 			 * nothing is sack'ed.
7642 			 */
7643 			ASSERT(tcp->tcp_sack_info != NULL);
7644 			if (tcp->tcp_notsack_list == NULL) {
7645 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7646 				    tcp->tcp_suna, tcp->tcp_snxt,
7647 				    &(tcp->tcp_num_notsack_blk),
7648 				    &(tcp->tcp_cnt_notsack_list));
7649 
7650 				/*
7651 				 * Make sure tcp_notsack_list is not NULL.
7652 				 * This happens when kmem_alloc(KM_NOSLEEP)
7653 				 * returns NULL.
7654 				 */
7655 				if (tcp->tcp_notsack_list == NULL) {
7656 					up += sack_len;
7657 					continue;
7658 				}
7659 				tcp->tcp_fack = tcp->tcp_suna;
7660 			}
7661 
7662 			while (sack_len > 0) {
7663 				if (up + 8 > endp) {
7664 					up = endp;
7665 					break;
7666 				}
7667 				sack_begin = BE32_TO_U32(up);
7668 				up += 4;
7669 				sack_end = BE32_TO_U32(up);
7670 				up += 4;
7671 				sack_len -= 8;
7672 				/*
7673 				 * Bounds checking.  Make sure the SACK
7674 				 * info is within tcp_suna and tcp_snxt.
7675 				 * If this SACK blk is out of bound, ignore
7676 				 * it but continue to parse the following
7677 				 * blks.
7678 				 */
7679 				if (SEQ_LEQ(sack_end, sack_begin) ||
7680 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7681 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7682 					continue;
7683 				}
7684 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7685 				    sack_begin, sack_end,
7686 				    &(tcp->tcp_num_notsack_blk),
7687 				    &(tcp->tcp_cnt_notsack_list));
7688 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7689 					tcp->tcp_fack = sack_end;
7690 				}
7691 			}
7692 			found |= TCP_OPT_SACK_PRESENT;
7693 			continue;
7694 
7695 		case TCPOPT_TSTAMP:
7696 			if (len < TCPOPT_TSTAMP_LEN ||
7697 			    up[1] != TCPOPT_TSTAMP_LEN)
7698 				break;
7699 
7700 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7701 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7702 
7703 			found |= TCP_OPT_TSTAMP_PRESENT;
7704 
7705 			up += TCPOPT_TSTAMP_LEN;
7706 			continue;
7707 
7708 		default:
7709 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7710 				break;
7711 			up += up[1];
7712 			continue;
7713 		}
7714 		break;
7715 	}
7716 	return (found);
7717 }
7718 
7719 /*
7720  * Set the MSS associated with a particular tcp based on its current value,
7721  * and a new one passed in. Observe minimums and maximums, and reset other
7722  * state variables that we want to view as multiples of MSS.
7723  *
7724  * The value of MSS could be either increased or descreased.
7725  */
7726 static void
7727 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7728 {
7729 	uint32_t	mss_max;
7730 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7731 	conn_t		*connp = tcp->tcp_connp;
7732 
7733 	if (connp->conn_ipversion == IPV4_VERSION)
7734 		mss_max = tcps->tcps_mss_max_ipv4;
7735 	else
7736 		mss_max = tcps->tcps_mss_max_ipv6;
7737 
7738 	if (mss < tcps->tcps_mss_min)
7739 		mss = tcps->tcps_mss_min;
7740 	if (mss > mss_max)
7741 		mss = mss_max;
7742 	/*
7743 	 * Unless naglim has been set by our client to
7744 	 * a non-mss value, force naglim to track mss.
7745 	 * This can help to aggregate small writes.
7746 	 */
7747 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7748 		tcp->tcp_naglim = mss;
7749 	/*
7750 	 * TCP should be able to buffer at least 4 MSS data for obvious
7751 	 * performance reason.
7752 	 */
7753 	if ((mss << 2) > connp->conn_sndbuf)
7754 		connp->conn_sndbuf = mss << 2;
7755 
7756 	/*
7757 	 * Set the send lowater to at least twice of MSS.
7758 	 */
7759 	if ((mss << 1) > connp->conn_sndlowat)
7760 		connp->conn_sndlowat = mss << 1;
7761 
7762 	/*
7763 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7764 	 * previous ratio to preserve the transmit rate.
7765 	 */
7766 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7767 	tcp->tcp_cwnd_cnt = 0;
7768 
7769 	tcp->tcp_mss = mss;
7770 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7771 }
7772 
7773 /* For /dev/tcp aka AF_INET open */
7774 static int
7775 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7776 {
7777 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7778 }
7779 
7780 /* For /dev/tcp6 aka AF_INET6 open */
7781 static int
7782 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7783 {
7784 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7785 }
7786 
7787 static conn_t *
7788 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7789     int *errorp)
7790 {
7791 	tcp_t		*tcp = NULL;
7792 	conn_t		*connp;
7793 	zoneid_t	zoneid;
7794 	tcp_stack_t	*tcps;
7795 	squeue_t	*sqp;
7796 
7797 	ASSERT(errorp != NULL);
7798 	/*
7799 	 * Find the proper zoneid and netstack.
7800 	 */
7801 	/*
7802 	 * Special case for install: miniroot needs to be able to
7803 	 * access files via NFS as though it were always in the
7804 	 * global zone.
7805 	 */
7806 	if (credp == kcred && nfs_global_client_only != 0) {
7807 		zoneid = GLOBAL_ZONEID;
7808 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7809 		    netstack_tcp;
7810 		ASSERT(tcps != NULL);
7811 	} else {
7812 		netstack_t *ns;
7813 		int err;
7814 
7815 		if ((err = secpolicy_basic_net_access(credp)) != 0) {
7816 			*errorp = err;
7817 			return (NULL);
7818 		}
7819 
7820 		ns = netstack_find_by_cred(credp);
7821 		ASSERT(ns != NULL);
7822 		tcps = ns->netstack_tcp;
7823 		ASSERT(tcps != NULL);
7824 
7825 		/*
7826 		 * For exclusive stacks we set the zoneid to zero
7827 		 * to make TCP operate as if in the global zone.
7828 		 */
7829 		if (tcps->tcps_netstack->netstack_stackid !=
7830 		    GLOBAL_NETSTACKID)
7831 			zoneid = GLOBAL_ZONEID;
7832 		else
7833 			zoneid = crgetzoneid(credp);
7834 	}
7835 
7836 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7837 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7838 	/*
7839 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7840 	 * so we drop it by one.
7841 	 */
7842 	netstack_rele(tcps->tcps_netstack);
7843 	if (connp == NULL) {
7844 		*errorp = ENOSR;
7845 		return (NULL);
7846 	}
7847 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7848 
7849 	connp->conn_sqp = sqp;
7850 	connp->conn_initial_sqp = connp->conn_sqp;
7851 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7852 	tcp = connp->conn_tcp;
7853 
7854 	/*
7855 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7856 	 * to do the following checks when necessary:
7857 	 *
7858 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7859 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7860 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7861 	 */
7862 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7863 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7864 
7865 	if (!tcps->tcps_dev_flow_ctl)
7866 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7867 
7868 	if (isv6) {
7869 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7870 		connp->conn_ipversion = IPV6_VERSION;
7871 		connp->conn_family = AF_INET6;
7872 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7873 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7874 	} else {
7875 		connp->conn_ipversion = IPV4_VERSION;
7876 		connp->conn_family = AF_INET;
7877 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7878 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7879 	}
7880 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7881 
7882 	crhold(credp);
7883 	connp->conn_cred = credp;
7884 	connp->conn_cpid = curproc->p_pid;
7885 	connp->conn_open_time = ddi_get_lbolt64();
7886 
7887 	/* Cache things in the ixa without any refhold */
7888 	connp->conn_ixa->ixa_cred = credp;
7889 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
7890 
7891 	connp->conn_zoneid = zoneid;
7892 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7893 	connp->conn_ixa->ixa_zoneid = zoneid;
7894 	connp->conn_mlp_type = mlptSingle;
7895 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7896 	ASSERT(tcp->tcp_tcps == tcps);
7897 
7898 	/*
7899 	 * If the caller has the process-wide flag set, then default to MAC
7900 	 * exempt mode.  This allows read-down to unlabeled hosts.
7901 	 */
7902 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7903 		connp->conn_mac_mode = CONN_MAC_AWARE;
7904 
7905 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7906 
7907 	if (issocket) {
7908 		tcp->tcp_issocket = 1;
7909 	}
7910 
7911 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7912 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7913 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7914 	connp->conn_so_type = SOCK_STREAM;
7915 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7916 	    tcps->tcps_wroff_xtra;
7917 
7918 	SOCK_CONNID_INIT(tcp->tcp_connid);
7919 	tcp->tcp_state = TCPS_IDLE;
7920 	tcp_init_values(tcp);
7921 	return (connp);
7922 }
7923 
7924 static int
7925 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7926     boolean_t isv6)
7927 {
7928 	tcp_t		*tcp = NULL;
7929 	conn_t		*connp = NULL;
7930 	int		err;
7931 	vmem_t		*minor_arena = NULL;
7932 	dev_t		conn_dev;
7933 	boolean_t	issocket;
7934 
7935 	if (q->q_ptr != NULL)
7936 		return (0);
7937 
7938 	if (sflag == MODOPEN)
7939 		return (EINVAL);
7940 
7941 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7942 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7943 		minor_arena = ip_minor_arena_la;
7944 	} else {
7945 		/*
7946 		 * Either minor numbers in the large arena were exhausted
7947 		 * or a non socket application is doing the open.
7948 		 * Try to allocate from the small arena.
7949 		 */
7950 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7951 			return (EBUSY);
7952 		}
7953 		minor_arena = ip_minor_arena_sa;
7954 	}
7955 
7956 	ASSERT(minor_arena != NULL);
7957 
7958 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7959 
7960 	if (flag & SO_FALLBACK) {
7961 		/*
7962 		 * Non streams socket needs a stream to fallback to
7963 		 */
7964 		RD(q)->q_ptr = (void *)conn_dev;
7965 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7966 		WR(q)->q_ptr = (void *)minor_arena;
7967 		qprocson(q);
7968 		return (0);
7969 	} else if (flag & SO_ACCEPTOR) {
7970 		q->q_qinfo = &tcp_acceptor_rinit;
7971 		/*
7972 		 * the conn_dev and minor_arena will be subsequently used by
7973 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7974 		 * the minor device number for this connection from the q_ptr.
7975 		 */
7976 		RD(q)->q_ptr = (void *)conn_dev;
7977 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7978 		WR(q)->q_ptr = (void *)minor_arena;
7979 		qprocson(q);
7980 		return (0);
7981 	}
7982 
7983 	issocket = flag & SO_SOCKSTR;
7984 	connp = tcp_create_common(credp, isv6, issocket, &err);
7985 
7986 	if (connp == NULL) {
7987 		inet_minor_free(minor_arena, conn_dev);
7988 		q->q_ptr = WR(q)->q_ptr = NULL;
7989 		return (err);
7990 	}
7991 
7992 	connp->conn_rq = q;
7993 	connp->conn_wq = WR(q);
7994 	q->q_ptr = WR(q)->q_ptr = connp;
7995 
7996 	connp->conn_dev = conn_dev;
7997 	connp->conn_minor_arena = minor_arena;
7998 
7999 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
8000 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
8001 
8002 	tcp = connp->conn_tcp;
8003 
8004 	if (issocket) {
8005 		WR(q)->q_qinfo = &tcp_sock_winit;
8006 	} else {
8007 #ifdef  _ILP32
8008 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
8009 #else
8010 		tcp->tcp_acceptor_id = conn_dev;
8011 #endif  /* _ILP32 */
8012 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
8013 	}
8014 
8015 	/*
8016 	 * Put the ref for TCP. Ref for IP was already put
8017 	 * by ipcl_conn_create. Also Make the conn_t globally
8018 	 * visible to walkers
8019 	 */
8020 	mutex_enter(&connp->conn_lock);
8021 	CONN_INC_REF_LOCKED(connp);
8022 	ASSERT(connp->conn_ref == 2);
8023 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8024 	mutex_exit(&connp->conn_lock);
8025 
8026 	qprocson(q);
8027 	return (0);
8028 }
8029 
8030 /*
8031  * Some TCP options can be "set" by requesting them in the option
8032  * buffer. This is needed for XTI feature test though we do not
8033  * allow it in general. We interpret that this mechanism is more
8034  * applicable to OSI protocols and need not be allowed in general.
8035  * This routine filters out options for which it is not allowed (most)
8036  * and lets through those (few) for which it is. [ The XTI interface
8037  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
8038  * ever implemented will have to be allowed here ].
8039  */
8040 static boolean_t
8041 tcp_allow_connopt_set(int level, int name)
8042 {
8043 
8044 	switch (level) {
8045 	case IPPROTO_TCP:
8046 		switch (name) {
8047 		case TCP_NODELAY:
8048 			return (B_TRUE);
8049 		default:
8050 			return (B_FALSE);
8051 		}
8052 		/*NOTREACHED*/
8053 	default:
8054 		return (B_FALSE);
8055 	}
8056 	/*NOTREACHED*/
8057 }
8058 
8059 /*
8060  * This routine gets default values of certain options whose default
8061  * values are maintained by protocol specific code
8062  */
8063 /* ARGSUSED */
8064 int
8065 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
8066 {
8067 	int32_t	*i1 = (int32_t *)ptr;
8068 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
8069 
8070 	switch (level) {
8071 	case IPPROTO_TCP:
8072 		switch (name) {
8073 		case TCP_NOTIFY_THRESHOLD:
8074 			*i1 = tcps->tcps_ip_notify_interval;
8075 			break;
8076 		case TCP_ABORT_THRESHOLD:
8077 			*i1 = tcps->tcps_ip_abort_interval;
8078 			break;
8079 		case TCP_CONN_NOTIFY_THRESHOLD:
8080 			*i1 = tcps->tcps_ip_notify_cinterval;
8081 			break;
8082 		case TCP_CONN_ABORT_THRESHOLD:
8083 			*i1 = tcps->tcps_ip_abort_cinterval;
8084 			break;
8085 		default:
8086 			return (-1);
8087 		}
8088 		break;
8089 	case IPPROTO_IP:
8090 		switch (name) {
8091 		case IP_TTL:
8092 			*i1 = tcps->tcps_ipv4_ttl;
8093 			break;
8094 		default:
8095 			return (-1);
8096 		}
8097 		break;
8098 	case IPPROTO_IPV6:
8099 		switch (name) {
8100 		case IPV6_UNICAST_HOPS:
8101 			*i1 = tcps->tcps_ipv6_hoplimit;
8102 			break;
8103 		default:
8104 			return (-1);
8105 		}
8106 		break;
8107 	default:
8108 		return (-1);
8109 	}
8110 	return (sizeof (int));
8111 }
8112 
8113 /*
8114  * TCP routine to get the values of options.
8115  */
8116 static int
8117 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
8118 {
8119 	int		*i1 = (int *)ptr;
8120 	tcp_t		*tcp = connp->conn_tcp;
8121 	conn_opt_arg_t	coas;
8122 	int		retval;
8123 
8124 	coas.coa_connp = connp;
8125 	coas.coa_ixa = connp->conn_ixa;
8126 	coas.coa_ipp = &connp->conn_xmit_ipp;
8127 	coas.coa_ancillary = B_FALSE;
8128 	coas.coa_changed = 0;
8129 
8130 	switch (level) {
8131 	case SOL_SOCKET:
8132 		switch (name) {
8133 		case SO_SND_COPYAVOID:
8134 			*i1 = tcp->tcp_snd_zcopy_on ?
8135 			    SO_SND_COPYAVOID : 0;
8136 			return (sizeof (int));
8137 		case SO_ACCEPTCONN:
8138 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
8139 			return (sizeof (int));
8140 		}
8141 		break;
8142 	case IPPROTO_TCP:
8143 		switch (name) {
8144 		case TCP_NODELAY:
8145 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
8146 			return (sizeof (int));
8147 		case TCP_MAXSEG:
8148 			*i1 = tcp->tcp_mss;
8149 			return (sizeof (int));
8150 		case TCP_NOTIFY_THRESHOLD:
8151 			*i1 = (int)tcp->tcp_first_timer_threshold;
8152 			return (sizeof (int));
8153 		case TCP_ABORT_THRESHOLD:
8154 			*i1 = tcp->tcp_second_timer_threshold;
8155 			return (sizeof (int));
8156 		case TCP_CONN_NOTIFY_THRESHOLD:
8157 			*i1 = tcp->tcp_first_ctimer_threshold;
8158 			return (sizeof (int));
8159 		case TCP_CONN_ABORT_THRESHOLD:
8160 			*i1 = tcp->tcp_second_ctimer_threshold;
8161 			return (sizeof (int));
8162 		case TCP_INIT_CWND:
8163 			*i1 = tcp->tcp_init_cwnd;
8164 			return (sizeof (int));
8165 		case TCP_KEEPALIVE_THRESHOLD:
8166 			*i1 = tcp->tcp_ka_interval;
8167 			return (sizeof (int));
8168 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8169 			*i1 = tcp->tcp_ka_abort_thres;
8170 			return (sizeof (int));
8171 		case TCP_CORK:
8172 			*i1 = tcp->tcp_cork;
8173 			return (sizeof (int));
8174 		}
8175 		break;
8176 	case IPPROTO_IP:
8177 		if (connp->conn_family != AF_INET)
8178 			return (-1);
8179 		switch (name) {
8180 		case IP_OPTIONS:
8181 		case T_IP_OPTIONS:
8182 			/* Caller ensures enough space */
8183 			return (ip_opt_get_user(connp, ptr));
8184 		default:
8185 			break;
8186 		}
8187 		break;
8188 
8189 	case IPPROTO_IPV6:
8190 		/*
8191 		 * IPPROTO_IPV6 options are only supported for sockets
8192 		 * that are using IPv6 on the wire.
8193 		 */
8194 		if (connp->conn_ipversion != IPV6_VERSION) {
8195 			return (-1);
8196 		}
8197 		switch (name) {
8198 		case IPV6_PATHMTU:
8199 			if (tcp->tcp_state < TCPS_ESTABLISHED)
8200 				return (-1);
8201 			break;
8202 		}
8203 		break;
8204 	}
8205 	mutex_enter(&connp->conn_lock);
8206 	retval = conn_opt_get(&coas, level, name, ptr);
8207 	mutex_exit(&connp->conn_lock);
8208 	return (retval);
8209 }
8210 
8211 /*
8212  * TCP routine to get the values of options.
8213  */
8214 int
8215 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
8216 {
8217 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
8218 }
8219 
8220 /* returns UNIX error, the optlen is a value-result arg */
8221 int
8222 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8223     void *optvalp, socklen_t *optlen, cred_t *cr)
8224 {
8225 	conn_t		*connp = (conn_t *)proto_handle;
8226 	squeue_t	*sqp = connp->conn_sqp;
8227 	int		error;
8228 	t_uscalar_t	max_optbuf_len;
8229 	void		*optvalp_buf;
8230 	int		len;
8231 
8232 	ASSERT(connp->conn_upper_handle != NULL);
8233 
8234 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
8235 	    tcp_opt_obj.odb_opt_des_arr,
8236 	    tcp_opt_obj.odb_opt_arr_cnt,
8237 	    B_FALSE, B_TRUE, cr);
8238 	if (error != 0) {
8239 		if (error < 0) {
8240 			error = proto_tlitosyserr(-error);
8241 		}
8242 		return (error);
8243 	}
8244 
8245 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
8246 
8247 	error = squeue_synch_enter(sqp, connp, NULL);
8248 	if (error == ENOMEM) {
8249 		kmem_free(optvalp_buf, max_optbuf_len);
8250 		return (ENOMEM);
8251 	}
8252 
8253 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8254 	squeue_synch_exit(sqp, connp);
8255 
8256 	if (len == -1) {
8257 		kmem_free(optvalp_buf, max_optbuf_len);
8258 		return (EINVAL);
8259 	}
8260 
8261 	/*
8262 	 * update optlen and copy option value
8263 	 */
8264 	t_uscalar_t size = MIN(len, *optlen);
8265 
8266 	bcopy(optvalp_buf, optvalp, size);
8267 	bcopy(&size, optlen, sizeof (size));
8268 
8269 	kmem_free(optvalp_buf, max_optbuf_len);
8270 	return (0);
8271 }
8272 
8273 /*
8274  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8275  * Parameters are assumed to be verified by the caller.
8276  */
8277 /* ARGSUSED */
8278 int
8279 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8280     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8281     void *thisdg_attrs, cred_t *cr)
8282 {
8283 	tcp_t	*tcp = connp->conn_tcp;
8284 	int	*i1 = (int *)invalp;
8285 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8286 	boolean_t checkonly;
8287 	int	reterr;
8288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8289 	conn_opt_arg_t	coas;
8290 
8291 	coas.coa_connp = connp;
8292 	coas.coa_ixa = connp->conn_ixa;
8293 	coas.coa_ipp = &connp->conn_xmit_ipp;
8294 	coas.coa_ancillary = B_FALSE;
8295 	coas.coa_changed = 0;
8296 
8297 	switch (optset_context) {
8298 	case SETFN_OPTCOM_CHECKONLY:
8299 		checkonly = B_TRUE;
8300 		/*
8301 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8302 		 * inlen != 0 implies value supplied and
8303 		 * 	we have to "pretend" to set it.
8304 		 * inlen == 0 implies that there is no
8305 		 * 	value part in T_CHECK request and just validation
8306 		 * done elsewhere should be enough, we just return here.
8307 		 */
8308 		if (inlen == 0) {
8309 			*outlenp = 0;
8310 			return (0);
8311 		}
8312 		break;
8313 	case SETFN_OPTCOM_NEGOTIATE:
8314 		checkonly = B_FALSE;
8315 		break;
8316 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8317 	case SETFN_CONN_NEGOTIATE:
8318 		checkonly = B_FALSE;
8319 		/*
8320 		 * Negotiating local and "association-related" options
8321 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8322 		 * primitives is allowed by XTI, but we choose
8323 		 * to not implement this style negotiation for Internet
8324 		 * protocols (We interpret it is a must for OSI world but
8325 		 * optional for Internet protocols) for all options.
8326 		 * [ Will do only for the few options that enable test
8327 		 * suites that our XTI implementation of this feature
8328 		 * works for transports that do allow it ]
8329 		 */
8330 		if (!tcp_allow_connopt_set(level, name)) {
8331 			*outlenp = 0;
8332 			return (EINVAL);
8333 		}
8334 		break;
8335 	default:
8336 		/*
8337 		 * We should never get here
8338 		 */
8339 		*outlenp = 0;
8340 		return (EINVAL);
8341 	}
8342 
8343 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8344 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8345 
8346 	/*
8347 	 * For TCP, we should have no ancillary data sent down
8348 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8349 	 * has to be zero.
8350 	 */
8351 	ASSERT(thisdg_attrs == NULL);
8352 
8353 	/*
8354 	 * For fixed length options, no sanity check
8355 	 * of passed in length is done. It is assumed *_optcom_req()
8356 	 * routines do the right thing.
8357 	 */
8358 	switch (level) {
8359 	case SOL_SOCKET:
8360 		switch (name) {
8361 		case SO_KEEPALIVE:
8362 			if (checkonly) {
8363 				/* check only case */
8364 				break;
8365 			}
8366 
8367 			if (!onoff) {
8368 				if (connp->conn_keepalive) {
8369 					if (tcp->tcp_ka_tid != 0) {
8370 						(void) TCP_TIMER_CANCEL(tcp,
8371 						    tcp->tcp_ka_tid);
8372 						tcp->tcp_ka_tid = 0;
8373 					}
8374 					connp->conn_keepalive = 0;
8375 				}
8376 				break;
8377 			}
8378 			if (!connp->conn_keepalive) {
8379 				/* Crank up the keepalive timer */
8380 				tcp->tcp_ka_last_intrvl = 0;
8381 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8382 				    tcp_keepalive_killer,
8383 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8384 				connp->conn_keepalive = 1;
8385 			}
8386 			break;
8387 		case SO_SNDBUF: {
8388 			if (*i1 > tcps->tcps_max_buf) {
8389 				*outlenp = 0;
8390 				return (ENOBUFS);
8391 			}
8392 			if (checkonly)
8393 				break;
8394 
8395 			connp->conn_sndbuf = *i1;
8396 			if (tcps->tcps_snd_lowat_fraction != 0) {
8397 				connp->conn_sndlowat = connp->conn_sndbuf /
8398 				    tcps->tcps_snd_lowat_fraction;
8399 			}
8400 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8401 			/*
8402 			 * If we are flow-controlled, recheck the condition.
8403 			 * There are apps that increase SO_SNDBUF size when
8404 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8405 			 * control condition to be lifted right away.
8406 			 */
8407 			mutex_enter(&tcp->tcp_non_sq_lock);
8408 			if (tcp->tcp_flow_stopped &&
8409 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8410 				tcp_clrqfull(tcp);
8411 			}
8412 			mutex_exit(&tcp->tcp_non_sq_lock);
8413 			*outlenp = inlen;
8414 			return (0);
8415 		}
8416 		case SO_RCVBUF:
8417 			if (*i1 > tcps->tcps_max_buf) {
8418 				*outlenp = 0;
8419 				return (ENOBUFS);
8420 			}
8421 			/* Silently ignore zero */
8422 			if (!checkonly && *i1 != 0) {
8423 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8424 				(void) tcp_rwnd_set(tcp, *i1);
8425 			}
8426 			/*
8427 			 * XXX should we return the rwnd here
8428 			 * and tcp_opt_get ?
8429 			 */
8430 			*outlenp = inlen;
8431 			return (0);
8432 		case SO_SND_COPYAVOID:
8433 			if (!checkonly) {
8434 				if (tcp->tcp_loopback ||
8435 				    (tcp->tcp_kssl_ctx != NULL) ||
8436 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8437 					*outlenp = 0;
8438 					return (EOPNOTSUPP);
8439 				}
8440 				tcp->tcp_snd_zcopy_aware = 1;
8441 			}
8442 			*outlenp = inlen;
8443 			return (0);
8444 		}
8445 		break;
8446 	case IPPROTO_TCP:
8447 		switch (name) {
8448 		case TCP_NODELAY:
8449 			if (!checkonly)
8450 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8451 			break;
8452 		case TCP_NOTIFY_THRESHOLD:
8453 			if (!checkonly)
8454 				tcp->tcp_first_timer_threshold = *i1;
8455 			break;
8456 		case TCP_ABORT_THRESHOLD:
8457 			if (!checkonly)
8458 				tcp->tcp_second_timer_threshold = *i1;
8459 			break;
8460 		case TCP_CONN_NOTIFY_THRESHOLD:
8461 			if (!checkonly)
8462 				tcp->tcp_first_ctimer_threshold = *i1;
8463 			break;
8464 		case TCP_CONN_ABORT_THRESHOLD:
8465 			if (!checkonly)
8466 				tcp->tcp_second_ctimer_threshold = *i1;
8467 			break;
8468 		case TCP_RECVDSTADDR:
8469 			if (tcp->tcp_state > TCPS_LISTEN) {
8470 				*outlenp = 0;
8471 				return (EOPNOTSUPP);
8472 			}
8473 			/* Setting done in conn_opt_set */
8474 			break;
8475 		case TCP_INIT_CWND: {
8476 			uint32_t init_cwnd = *((uint32_t *)invalp);
8477 
8478 			if (checkonly)
8479 				break;
8480 
8481 			/*
8482 			 * Only allow socket with network configuration
8483 			 * privilege to set the initial cwnd to be larger
8484 			 * than allowed by RFC 3390.
8485 			 */
8486 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8487 				tcp->tcp_init_cwnd = init_cwnd;
8488 				break;
8489 			}
8490 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8491 				*outlenp = 0;
8492 				return (reterr);
8493 			}
8494 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8495 				*outlenp = 0;
8496 				return (EINVAL);
8497 			}
8498 			tcp->tcp_init_cwnd = init_cwnd;
8499 			break;
8500 		}
8501 		case TCP_KEEPALIVE_THRESHOLD:
8502 			if (checkonly)
8503 				break;
8504 
8505 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8506 			    *i1 > tcps->tcps_keepalive_interval_high) {
8507 				*outlenp = 0;
8508 				return (EINVAL);
8509 			}
8510 			if (*i1 != tcp->tcp_ka_interval) {
8511 				tcp->tcp_ka_interval = *i1;
8512 				/*
8513 				 * Check if we need to restart the
8514 				 * keepalive timer.
8515 				 */
8516 				if (tcp->tcp_ka_tid != 0) {
8517 					ASSERT(connp->conn_keepalive);
8518 					(void) TCP_TIMER_CANCEL(tcp,
8519 					    tcp->tcp_ka_tid);
8520 					tcp->tcp_ka_last_intrvl = 0;
8521 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8522 					    tcp_keepalive_killer,
8523 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8524 				}
8525 			}
8526 			break;
8527 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8528 			if (!checkonly) {
8529 				if (*i1 <
8530 				    tcps->tcps_keepalive_abort_interval_low ||
8531 				    *i1 >
8532 				    tcps->tcps_keepalive_abort_interval_high) {
8533 					*outlenp = 0;
8534 					return (EINVAL);
8535 				}
8536 				tcp->tcp_ka_abort_thres = *i1;
8537 			}
8538 			break;
8539 		case TCP_CORK:
8540 			if (!checkonly) {
8541 				/*
8542 				 * if tcp->tcp_cork was set and is now
8543 				 * being unset, we have to make sure that
8544 				 * the remaining data gets sent out. Also
8545 				 * unset tcp->tcp_cork so that tcp_wput_data()
8546 				 * can send data even if it is less than mss
8547 				 */
8548 				if (tcp->tcp_cork && onoff == 0 &&
8549 				    tcp->tcp_unsent > 0) {
8550 					tcp->tcp_cork = B_FALSE;
8551 					tcp_wput_data(tcp, NULL, B_FALSE);
8552 				}
8553 				tcp->tcp_cork = onoff;
8554 			}
8555 			break;
8556 		default:
8557 			break;
8558 		}
8559 		break;
8560 	case IPPROTO_IP:
8561 		if (connp->conn_family != AF_INET) {
8562 			*outlenp = 0;
8563 			return (EINVAL);
8564 		}
8565 		switch (name) {
8566 		case IP_SEC_OPT:
8567 			/*
8568 			 * We should not allow policy setting after
8569 			 * we start listening for connections.
8570 			 */
8571 			if (tcp->tcp_state == TCPS_LISTEN) {
8572 				return (EINVAL);
8573 			}
8574 			break;
8575 		}
8576 		break;
8577 	case IPPROTO_IPV6:
8578 		/*
8579 		 * IPPROTO_IPV6 options are only supported for sockets
8580 		 * that are using IPv6 on the wire.
8581 		 */
8582 		if (connp->conn_ipversion != IPV6_VERSION) {
8583 			*outlenp = 0;
8584 			return (EINVAL);
8585 		}
8586 
8587 		switch (name) {
8588 		case IPV6_RECVPKTINFO:
8589 			if (!checkonly) {
8590 				/* Force it to be sent up with the next msg */
8591 				tcp->tcp_recvifindex = 0;
8592 			}
8593 			break;
8594 		case IPV6_RECVTCLASS:
8595 			if (!checkonly) {
8596 				/* Force it to be sent up with the next msg */
8597 				tcp->tcp_recvtclass = 0xffffffffU;
8598 			}
8599 			break;
8600 		case IPV6_RECVHOPLIMIT:
8601 			if (!checkonly) {
8602 				/* Force it to be sent up with the next msg */
8603 				tcp->tcp_recvhops = 0xffffffffU;
8604 			}
8605 			break;
8606 		case IPV6_PKTINFO:
8607 			/* This is an extra check for TCP */
8608 			if (inlen == sizeof (struct in6_pktinfo)) {
8609 				struct in6_pktinfo *pkti;
8610 
8611 				pkti = (struct in6_pktinfo *)invalp;
8612 				/*
8613 				 * RFC 3542 states that ipi6_addr must be
8614 				 * the unspecified address when setting the
8615 				 * IPV6_PKTINFO sticky socket option on a
8616 				 * TCP socket.
8617 				 */
8618 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8619 					return (EINVAL);
8620 			}
8621 			break;
8622 		case IPV6_SEC_OPT:
8623 			/*
8624 			 * We should not allow policy setting after
8625 			 * we start listening for connections.
8626 			 */
8627 			if (tcp->tcp_state == TCPS_LISTEN) {
8628 				return (EINVAL);
8629 			}
8630 			break;
8631 		}
8632 		break;
8633 	}
8634 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8635 	    checkonly, cr);
8636 	if (reterr != 0) {
8637 		*outlenp = 0;
8638 		return (reterr);
8639 	}
8640 
8641 	/*
8642 	 * Common case of OK return with outval same as inval
8643 	 */
8644 	if (invalp != outvalp) {
8645 		/* don't trust bcopy for identical src/dst */
8646 		(void) bcopy(invalp, outvalp, inlen);
8647 	}
8648 	*outlenp = inlen;
8649 
8650 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8651 		/* If we are connected we rebuilt the headers */
8652 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8653 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8654 			reterr = tcp_build_hdrs(tcp);
8655 			if (reterr != 0)
8656 				return (reterr);
8657 		}
8658 	}
8659 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8660 		in6_addr_t nexthop;
8661 
8662 		/*
8663 		 * If we are connected we re-cache the information.
8664 		 * We ignore errors to preserve BSD behavior.
8665 		 * Note that we don't redo IPsec policy lookup here
8666 		 * since the final destination (or source) didn't change.
8667 		 */
8668 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8669 		    &connp->conn_faddr_v6, &nexthop);
8670 
8671 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8672 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8673 			(void) ip_attr_connect(connp, connp->conn_ixa,
8674 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8675 			    &nexthop, connp->conn_fport, NULL, NULL,
8676 			    IPDF_VERIFY_DST);
8677 		}
8678 	}
8679 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8680 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8681 	}
8682 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8683 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8684 		    tcps->tcps_wroff_xtra;
8685 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8686 		    connp->conn_wroff);
8687 	}
8688 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8689 		if (IPCL_IS_NONSTR(connp))
8690 			proto_set_rx_oob_opt(connp, onoff);
8691 	}
8692 	return (0);
8693 }
8694 
8695 /* ARGSUSED */
8696 int
8697 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8698     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8699     void *thisdg_attrs, cred_t *cr)
8700 {
8701 	conn_t	*connp =  Q_TO_CONN(q);
8702 
8703 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8704 	    outlenp, outvalp, thisdg_attrs, cr));
8705 }
8706 
8707 int
8708 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8709     const void *optvalp, socklen_t optlen, cred_t *cr)
8710 {
8711 	conn_t		*connp = (conn_t *)proto_handle;
8712 	squeue_t	*sqp = connp->conn_sqp;
8713 	int		error;
8714 
8715 	ASSERT(connp->conn_upper_handle != NULL);
8716 	/*
8717 	 * Entering the squeue synchronously can result in a context switch,
8718 	 * which can cause a rather sever performance degradation. So we try to
8719 	 * handle whatever options we can without entering the squeue.
8720 	 */
8721 	if (level == IPPROTO_TCP) {
8722 		switch (option_name) {
8723 		case TCP_NODELAY:
8724 			if (optlen != sizeof (int32_t))
8725 				return (EINVAL);
8726 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8727 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8728 			    connp->conn_tcp->tcp_mss;
8729 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8730 			return (0);
8731 		default:
8732 			break;
8733 		}
8734 	}
8735 
8736 	error = squeue_synch_enter(sqp, connp, NULL);
8737 	if (error == ENOMEM) {
8738 		return (ENOMEM);
8739 	}
8740 
8741 	error = proto_opt_check(level, option_name, optlen, NULL,
8742 	    tcp_opt_obj.odb_opt_des_arr,
8743 	    tcp_opt_obj.odb_opt_arr_cnt,
8744 	    B_TRUE, B_FALSE, cr);
8745 
8746 	if (error != 0) {
8747 		if (error < 0) {
8748 			error = proto_tlitosyserr(-error);
8749 		}
8750 		squeue_synch_exit(sqp, connp);
8751 		return (error);
8752 	}
8753 
8754 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8755 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8756 	    NULL, cr);
8757 	squeue_synch_exit(sqp, connp);
8758 
8759 	ASSERT(error >= 0);
8760 
8761 	return (error);
8762 }
8763 
8764 /*
8765  * Build/update the tcp header template (in conn_ht_iphc) based on
8766  * conn_xmit_ipp. The headers include ip6_t, any extension
8767  * headers, and the maximum size tcp header (to avoid reallocation
8768  * on the fly for additional tcp options).
8769  *
8770  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8771  * Returns failure if can't allocate memory.
8772  */
8773 static int
8774 tcp_build_hdrs(tcp_t *tcp)
8775 {
8776 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8777 	conn_t		*connp = tcp->tcp_connp;
8778 	char		buf[TCP_MAX_HDR_LENGTH];
8779 	uint_t		buflen;
8780 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8781 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8782 	tcpha_t		*tcpha;
8783 	uint32_t	cksum;
8784 	int		error;
8785 
8786 	/*
8787 	 * We might be called after the connection is set up, and we might
8788 	 * have TS options already in the TCP header. Thus we  save any
8789 	 * existing tcp header.
8790 	 */
8791 	buflen = connp->conn_ht_ulp_len;
8792 	if (buflen != 0) {
8793 		bcopy(connp->conn_ht_ulp, buf, buflen);
8794 		extralen -= buflen - ulplen;
8795 		ulplen = buflen;
8796 	}
8797 
8798 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8799 	mutex_enter(&connp->conn_lock);
8800 	error = conn_build_hdr_template(connp, ulplen, extralen,
8801 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8802 	mutex_exit(&connp->conn_lock);
8803 	if (error != 0)
8804 		return (error);
8805 
8806 	/*
8807 	 * Any routing header/option has been massaged. The checksum difference
8808 	 * is stored in conn_sum for later use.
8809 	 */
8810 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8811 	tcp->tcp_tcpha = tcpha;
8812 
8813 	/* restore any old tcp header */
8814 	if (buflen != 0) {
8815 		bcopy(buf, connp->conn_ht_ulp, buflen);
8816 	} else {
8817 		tcpha->tha_sum = 0;
8818 		tcpha->tha_urp = 0;
8819 		tcpha->tha_ack = 0;
8820 		tcpha->tha_offset_and_reserved = (5 << 4);
8821 		tcpha->tha_lport = connp->conn_lport;
8822 		tcpha->tha_fport = connp->conn_fport;
8823 	}
8824 
8825 	/*
8826 	 * IP wants our header length in the checksum field to
8827 	 * allow it to perform a single pseudo-header+checksum
8828 	 * calculation on behalf of TCP.
8829 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8830 	 */
8831 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8832 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8833 	ASSERT(cksum < 0x10000);
8834 	tcpha->tha_sum = htons(cksum);
8835 
8836 	if (connp->conn_ipversion == IPV4_VERSION)
8837 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8838 	else
8839 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8840 
8841 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8842 	    connp->conn_wroff) {
8843 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8844 		    tcps->tcps_wroff_xtra;
8845 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8846 		    connp->conn_wroff);
8847 	}
8848 	return (0);
8849 }
8850 
8851 /* Get callback routine passed to nd_load by tcp_param_register */
8852 /* ARGSUSED */
8853 static int
8854 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8855 {
8856 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8857 
8858 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8859 	return (0);
8860 }
8861 
8862 /*
8863  * Walk through the param array specified registering each element with the
8864  * named dispatch handler.
8865  */
8866 static boolean_t
8867 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8868 {
8869 	for (; cnt-- > 0; tcppa++) {
8870 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8871 			if (!nd_load(ndp, tcppa->tcp_param_name,
8872 			    tcp_param_get, tcp_param_set,
8873 			    (caddr_t)tcppa)) {
8874 				nd_free(ndp);
8875 				return (B_FALSE);
8876 			}
8877 		}
8878 	}
8879 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8880 	    KM_SLEEP);
8881 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8882 	    sizeof (tcpparam_t));
8883 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8884 	    tcp_param_get, tcp_param_set_aligned,
8885 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8886 		nd_free(ndp);
8887 		return (B_FALSE);
8888 	}
8889 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8890 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8891 		nd_free(ndp);
8892 		return (B_FALSE);
8893 	}
8894 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8895 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8896 		nd_free(ndp);
8897 		return (B_FALSE);
8898 	}
8899 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8900 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8901 		nd_free(ndp);
8902 		return (B_FALSE);
8903 	}
8904 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8905 	    tcp_1948_phrase_set, NULL)) {
8906 		nd_free(ndp);
8907 		return (B_FALSE);
8908 	}
8909 
8910 
8911 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8912 	    tcp_listener_conf_get, NULL, NULL)) {
8913 		nd_free(ndp);
8914 		return (B_FALSE);
8915 	}
8916 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8917 	    NULL, tcp_listener_conf_add, NULL)) {
8918 		nd_free(ndp);
8919 		return (B_FALSE);
8920 	}
8921 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8922 	    NULL, tcp_listener_conf_del, NULL)) {
8923 		nd_free(ndp);
8924 		return (B_FALSE);
8925 	}
8926 
8927 	/*
8928 	 * Dummy ndd variables - only to convey obsolescence information
8929 	 * through printing of their name (no get or set routines)
8930 	 * XXX Remove in future releases ?
8931 	 */
8932 	if (!nd_load(ndp,
8933 	    "tcp_close_wait_interval(obsoleted - "
8934 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8935 		nd_free(ndp);
8936 		return (B_FALSE);
8937 	}
8938 	return (B_TRUE);
8939 }
8940 
8941 /* ndd set routine for tcp_wroff_xtra. */
8942 /* ARGSUSED */
8943 static int
8944 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8945     cred_t *cr)
8946 {
8947 	long new_value;
8948 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8949 
8950 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8951 	    new_value < tcppa->tcp_param_min ||
8952 	    new_value > tcppa->tcp_param_max) {
8953 		return (EINVAL);
8954 	}
8955 	/*
8956 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8957 	 * round it up.  For future 64 bit requirement, we actually make it
8958 	 * a multiple of 8.
8959 	 */
8960 	if (new_value & 0x7) {
8961 		new_value = (new_value & ~0x7) + 0x8;
8962 	}
8963 	tcppa->tcp_param_val = new_value;
8964 	return (0);
8965 }
8966 
8967 /* Set callback routine passed to nd_load by tcp_param_register */
8968 /* ARGSUSED */
8969 static int
8970 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8971 {
8972 	long	new_value;
8973 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8974 
8975 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8976 	    new_value < tcppa->tcp_param_min ||
8977 	    new_value > tcppa->tcp_param_max) {
8978 		return (EINVAL);
8979 	}
8980 	tcppa->tcp_param_val = new_value;
8981 	return (0);
8982 }
8983 
8984 static void
8985 tcp_reass_timer(void *arg)
8986 {
8987 	conn_t *connp = (conn_t *)arg;
8988 	tcp_t *tcp = connp->conn_tcp;
8989 
8990 	tcp->tcp_reass_tid = 0;
8991 	if (tcp->tcp_reass_head == NULL)
8992 		return;
8993 	ASSERT(tcp->tcp_reass_tail != NULL);
8994 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
8995 		tcp_sack_remove(tcp->tcp_sack_list,
8996 		    TCP_REASS_END(tcp->tcp_reass_tail), &tcp->tcp_num_sack_blk);
8997 	}
8998 	tcp_close_mpp(&tcp->tcp_reass_head);
8999 	tcp->tcp_reass_tail = NULL;
9000 }
9001 
9002 /*
9003  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
9004  * is filled, return as much as we can.  The message passed in may be
9005  * multi-part, chained using b_cont.  "start" is the starting sequence
9006  * number for this piece.
9007  */
9008 static mblk_t *
9009 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
9010 {
9011 	uint32_t	end;
9012 	mblk_t		*mp1;
9013 	mblk_t		*mp2;
9014 	mblk_t		*next_mp;
9015 	uint32_t	u1;
9016 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9017 
9018 
9019 	/* Walk through all the new pieces. */
9020 	do {
9021 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
9022 		    (uintptr_t)INT_MAX);
9023 		end = start + (int)(mp->b_wptr - mp->b_rptr);
9024 		next_mp = mp->b_cont;
9025 		if (start == end) {
9026 			/* Empty.  Blast it. */
9027 			freeb(mp);
9028 			continue;
9029 		}
9030 		mp->b_cont = NULL;
9031 		TCP_REASS_SET_SEQ(mp, start);
9032 		TCP_REASS_SET_END(mp, end);
9033 		mp1 = tcp->tcp_reass_tail;
9034 		if (!mp1) {
9035 			tcp->tcp_reass_tail = mp;
9036 			tcp->tcp_reass_head = mp;
9037 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9038 			UPDATE_MIB(&tcps->tcps_mib,
9039 			    tcpInDataUnorderBytes, end - start);
9040 			continue;
9041 		}
9042 		/* New stuff completely beyond tail? */
9043 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
9044 			/* Link it on end. */
9045 			mp1->b_cont = mp;
9046 			tcp->tcp_reass_tail = mp;
9047 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9048 			UPDATE_MIB(&tcps->tcps_mib,
9049 			    tcpInDataUnorderBytes, end - start);
9050 			continue;
9051 		}
9052 		mp1 = tcp->tcp_reass_head;
9053 		u1 = TCP_REASS_SEQ(mp1);
9054 		/* New stuff at the front? */
9055 		if (SEQ_LT(start, u1)) {
9056 			/* Yes... Check for overlap. */
9057 			mp->b_cont = mp1;
9058 			tcp->tcp_reass_head = mp;
9059 			tcp_reass_elim_overlap(tcp, mp);
9060 			continue;
9061 		}
9062 		/*
9063 		 * The new piece fits somewhere between the head and tail.
9064 		 * We find our slot, where mp1 precedes us and mp2 trails.
9065 		 */
9066 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9067 			u1 = TCP_REASS_SEQ(mp2);
9068 			if (SEQ_LEQ(start, u1))
9069 				break;
9070 		}
9071 		/* Link ourselves in */
9072 		mp->b_cont = mp2;
9073 		mp1->b_cont = mp;
9074 
9075 		/* Trim overlap with following mblk(s) first */
9076 		tcp_reass_elim_overlap(tcp, mp);
9077 
9078 		/* Trim overlap with preceding mblk */
9079 		tcp_reass_elim_overlap(tcp, mp1);
9080 
9081 	} while (start = end, mp = next_mp);
9082 	mp1 = tcp->tcp_reass_head;
9083 	/* Anything ready to go? */
9084 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9085 		return (NULL);
9086 	/* Eat what we can off the queue */
9087 	for (;;) {
9088 		mp = mp1->b_cont;
9089 		end = TCP_REASS_END(mp1);
9090 		TCP_REASS_SET_SEQ(mp1, 0);
9091 		TCP_REASS_SET_END(mp1, 0);
9092 		if (!mp) {
9093 			tcp->tcp_reass_tail = NULL;
9094 			break;
9095 		}
9096 		if (end != TCP_REASS_SEQ(mp)) {
9097 			mp1->b_cont = NULL;
9098 			break;
9099 		}
9100 		mp1 = mp;
9101 	}
9102 	mp1 = tcp->tcp_reass_head;
9103 	tcp->tcp_reass_head = mp;
9104 	return (mp1);
9105 }
9106 
9107 /* Eliminate any overlap that mp may have over later mblks */
9108 static void
9109 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9110 {
9111 	uint32_t	end;
9112 	mblk_t		*mp1;
9113 	uint32_t	u1;
9114 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9115 
9116 	end = TCP_REASS_END(mp);
9117 	while ((mp1 = mp->b_cont) != NULL) {
9118 		u1 = TCP_REASS_SEQ(mp1);
9119 		if (!SEQ_GT(end, u1))
9120 			break;
9121 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9122 			mp->b_wptr -= end - u1;
9123 			TCP_REASS_SET_END(mp, u1);
9124 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9125 			UPDATE_MIB(&tcps->tcps_mib,
9126 			    tcpInDataPartDupBytes, end - u1);
9127 			break;
9128 		}
9129 		mp->b_cont = mp1->b_cont;
9130 		TCP_REASS_SET_SEQ(mp1, 0);
9131 		TCP_REASS_SET_END(mp1, 0);
9132 		freeb(mp1);
9133 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9134 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9135 	}
9136 	if (!mp1)
9137 		tcp->tcp_reass_tail = mp;
9138 }
9139 
9140 static uint_t
9141 tcp_rwnd_reopen(tcp_t *tcp)
9142 {
9143 	uint_t ret = 0;
9144 	uint_t thwin;
9145 	conn_t *connp = tcp->tcp_connp;
9146 
9147 	/* Learn the latest rwnd information that we sent to the other side. */
9148 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9149 	    << tcp->tcp_rcv_ws;
9150 	/* This is peer's calculated send window (our receive window). */
9151 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9152 	/*
9153 	 * Increase the receive window to max.  But we need to do receiver
9154 	 * SWS avoidance.  This means that we need to check the increase of
9155 	 * of receive window is at least 1 MSS.
9156 	 */
9157 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9158 		/*
9159 		 * If the window that the other side knows is less than max
9160 		 * deferred acks segments, send an update immediately.
9161 		 */
9162 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9163 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9164 			ret = TH_ACK_NEEDED;
9165 		}
9166 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9167 	}
9168 	return (ret);
9169 }
9170 
9171 /*
9172  * Send up all messages queued on tcp_rcv_list.
9173  */
9174 static uint_t
9175 tcp_rcv_drain(tcp_t *tcp)
9176 {
9177 	mblk_t *mp;
9178 	uint_t ret = 0;
9179 #ifdef DEBUG
9180 	uint_t cnt = 0;
9181 #endif
9182 	queue_t	*q = tcp->tcp_connp->conn_rq;
9183 
9184 	/* Can't drain on an eager connection */
9185 	if (tcp->tcp_listener != NULL)
9186 		return (ret);
9187 
9188 	/* Can't be a non-STREAMS connection */
9189 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9190 
9191 	/* No need for the push timer now. */
9192 	if (tcp->tcp_push_tid != 0) {
9193 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9194 		tcp->tcp_push_tid = 0;
9195 	}
9196 
9197 	/*
9198 	 * Handle two cases here: we are currently fused or we were
9199 	 * previously fused and have some urgent data to be delivered
9200 	 * upstream.  The latter happens because we either ran out of
9201 	 * memory or were detached and therefore sending the SIGURG was
9202 	 * deferred until this point.  In either case we pass control
9203 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9204 	 * some work.
9205 	 */
9206 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9207 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9208 		    tcp->tcp_fused_sigurg_mp != NULL);
9209 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9210 		    &tcp->tcp_fused_sigurg_mp))
9211 			return (ret);
9212 	}
9213 
9214 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9215 		tcp->tcp_rcv_list = mp->b_next;
9216 		mp->b_next = NULL;
9217 #ifdef DEBUG
9218 		cnt += msgdsize(mp);
9219 #endif
9220 		/* Does this need SSL processing first? */
9221 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9222 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9223 			    mblk_t *, mp);
9224 			tcp_kssl_input(tcp, mp, NULL);
9225 			continue;
9226 		}
9227 		putnext(q, mp);
9228 	}
9229 #ifdef DEBUG
9230 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9231 #endif
9232 	tcp->tcp_rcv_last_head = NULL;
9233 	tcp->tcp_rcv_last_tail = NULL;
9234 	tcp->tcp_rcv_cnt = 0;
9235 
9236 	if (canputnext(q))
9237 		return (tcp_rwnd_reopen(tcp));
9238 
9239 	return (ret);
9240 }
9241 
9242 /*
9243  * Queue data on tcp_rcv_list which is a b_next chain.
9244  * tcp_rcv_last_head/tail is the last element of this chain.
9245  * Each element of the chain is a b_cont chain.
9246  *
9247  * M_DATA messages are added to the current element.
9248  * Other messages are added as new (b_next) elements.
9249  */
9250 void
9251 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9252 {
9253 	ASSERT(seg_len == msgdsize(mp));
9254 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9255 
9256 	if (is_system_labeled()) {
9257 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9258 		/*
9259 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9260 		 * db_cpid unchanged.
9261 		 * The cred could have already been set.
9262 		 */
9263 		if (cr != NULL)
9264 			mblk_setcred(mp, cr, NOPID);
9265 	}
9266 
9267 	if (tcp->tcp_rcv_list == NULL) {
9268 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9269 		tcp->tcp_rcv_list = mp;
9270 		tcp->tcp_rcv_last_head = mp;
9271 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9272 		tcp->tcp_rcv_last_tail->b_cont = mp;
9273 	} else {
9274 		tcp->tcp_rcv_last_head->b_next = mp;
9275 		tcp->tcp_rcv_last_head = mp;
9276 	}
9277 
9278 	while (mp->b_cont)
9279 		mp = mp->b_cont;
9280 
9281 	tcp->tcp_rcv_last_tail = mp;
9282 	tcp->tcp_rcv_cnt += seg_len;
9283 	tcp->tcp_rwnd -= seg_len;
9284 }
9285 
9286 /* The minimum of smoothed mean deviation in RTO calculation. */
9287 #define	TCP_SD_MIN	400
9288 
9289 /*
9290  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9291  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9292  * are the same as those in Appendix A.2 of that paper.
9293  *
9294  * m = new measurement
9295  * sa = smoothed RTT average (8 * average estimates).
9296  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9297  */
9298 static void
9299 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9300 {
9301 	long m = TICK_TO_MSEC(rtt);
9302 	clock_t sa = tcp->tcp_rtt_sa;
9303 	clock_t sv = tcp->tcp_rtt_sd;
9304 	clock_t rto;
9305 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9306 
9307 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9308 	tcp->tcp_rtt_update++;
9309 
9310 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9311 	if (sa != 0) {
9312 		/*
9313 		 * Update average estimator:
9314 		 *	new rtt = 7/8 old rtt + 1/8 Error
9315 		 */
9316 
9317 		/* m is now Error in estimate. */
9318 		m -= sa >> 3;
9319 		if ((sa += m) <= 0) {
9320 			/*
9321 			 * Don't allow the smoothed average to be negative.
9322 			 * We use 0 to denote reinitialization of the
9323 			 * variables.
9324 			 */
9325 			sa = 1;
9326 		}
9327 
9328 		/*
9329 		 * Update deviation estimator:
9330 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9331 		 */
9332 		if (m < 0)
9333 			m = -m;
9334 		m -= sv >> 2;
9335 		sv += m;
9336 	} else {
9337 		/*
9338 		 * This follows BSD's implementation.  So the reinitialized
9339 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9340 		 * link is bandwidth dominated, doubling the window size
9341 		 * during slow start means doubling the RTT.  We want to be
9342 		 * more conservative when we reinitialize our estimates.  3
9343 		 * is just a convenient number.
9344 		 */
9345 		sa = m << 3;
9346 		sv = m << 1;
9347 	}
9348 	if (sv < TCP_SD_MIN) {
9349 		/*
9350 		 * We do not know that if sa captures the delay ACK
9351 		 * effect as in a long train of segments, a receiver
9352 		 * does not delay its ACKs.  So set the minimum of sv
9353 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9354 		 * of BSD DATO.  That means the minimum of mean
9355 		 * deviation is 100 ms.
9356 		 *
9357 		 */
9358 		sv = TCP_SD_MIN;
9359 	}
9360 	tcp->tcp_rtt_sa = sa;
9361 	tcp->tcp_rtt_sd = sv;
9362 	/*
9363 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9364 	 *
9365 	 * Add tcp_rexmit_interval extra in case of extreme environment
9366 	 * where the algorithm fails to work.  The default value of
9367 	 * tcp_rexmit_interval_extra should be 0.
9368 	 *
9369 	 * As we use a finer grained clock than BSD and update
9370 	 * RTO for every ACKs, add in another .25 of RTT to the
9371 	 * deviation of RTO to accomodate burstiness of 1/4 of
9372 	 * window size.
9373 	 */
9374 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9375 
9376 	if (rto > tcps->tcps_rexmit_interval_max) {
9377 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9378 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9379 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9380 	} else {
9381 		tcp->tcp_rto = rto;
9382 	}
9383 
9384 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9385 	tcp->tcp_timer_backoff = 0;
9386 }
9387 
9388 /*
9389  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9390  * send queue which starts at the given sequence number. If the given
9391  * sequence number is equal to last valid sequence number (tcp_snxt), the
9392  * returned mblk is the last valid mblk, and off is set to the length of
9393  * that mblk.
9394  *
9395  * send queue which starts at the given seq. no.
9396  *
9397  * Parameters:
9398  *	tcp_t *tcp: the tcp instance pointer.
9399  *	uint32_t seq: the starting seq. no of the requested segment.
9400  *	int32_t *off: after the execution, *off will be the offset to
9401  *		the returned mblk which points to the requested seq no.
9402  *		It is the caller's responsibility to send in a non-null off.
9403  *
9404  * Return:
9405  *	A mblk_t pointer pointing to the requested segment in send queue.
9406  */
9407 static mblk_t *
9408 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9409 {
9410 	int32_t	cnt;
9411 	mblk_t	*mp;
9412 
9413 	/* Defensive coding.  Make sure we don't send incorrect data. */
9414 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9415 		return (NULL);
9416 
9417 	cnt = seq - tcp->tcp_suna;
9418 	mp = tcp->tcp_xmit_head;
9419 	while (cnt > 0 && mp != NULL) {
9420 		cnt -= mp->b_wptr - mp->b_rptr;
9421 		if (cnt <= 0) {
9422 			cnt += mp->b_wptr - mp->b_rptr;
9423 			break;
9424 		}
9425 		mp = mp->b_cont;
9426 	}
9427 	ASSERT(mp != NULL);
9428 	*off = cnt;
9429 	return (mp);
9430 }
9431 
9432 /*
9433  * This function handles all retransmissions if SACK is enabled for this
9434  * connection.  First it calculates how many segments can be retransmitted
9435  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9436  * segments.  A segment is eligible if sack_cnt for that segment is greater
9437  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9438  * all eligible segments, it checks to see if TCP can send some new segments
9439  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9440  *
9441  * Parameters:
9442  *	tcp_t *tcp: the tcp structure of the connection.
9443  *	uint_t *flags: in return, appropriate value will be set for
9444  *	tcp_input_data().
9445  */
9446 static void
9447 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9448 {
9449 	notsack_blk_t	*notsack_blk;
9450 	int32_t		usable_swnd;
9451 	int32_t		mss;
9452 	uint32_t	seg_len;
9453 	mblk_t		*xmit_mp;
9454 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9455 
9456 	ASSERT(tcp->tcp_sack_info != NULL);
9457 	ASSERT(tcp->tcp_notsack_list != NULL);
9458 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9459 
9460 	/* Defensive coding in case there is a bug... */
9461 	if (tcp->tcp_notsack_list == NULL) {
9462 		return;
9463 	}
9464 	notsack_blk = tcp->tcp_notsack_list;
9465 	mss = tcp->tcp_mss;
9466 
9467 	/*
9468 	 * Limit the num of outstanding data in the network to be
9469 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9470 	 */
9471 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9472 
9473 	/* At least retransmit 1 MSS of data. */
9474 	if (usable_swnd <= 0) {
9475 		usable_swnd = mss;
9476 	}
9477 
9478 	/* Make sure no new RTT samples will be taken. */
9479 	tcp->tcp_csuna = tcp->tcp_snxt;
9480 
9481 	notsack_blk = tcp->tcp_notsack_list;
9482 	while (usable_swnd > 0) {
9483 		mblk_t		*snxt_mp, *tmp_mp;
9484 		tcp_seq		begin = tcp->tcp_sack_snxt;
9485 		tcp_seq		end;
9486 		int32_t		off;
9487 
9488 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9489 			if (SEQ_GT(notsack_blk->end, begin) &&
9490 			    (notsack_blk->sack_cnt >=
9491 			    tcps->tcps_dupack_fast_retransmit)) {
9492 				end = notsack_blk->end;
9493 				if (SEQ_LT(begin, notsack_blk->begin)) {
9494 					begin = notsack_blk->begin;
9495 				}
9496 				break;
9497 			}
9498 		}
9499 		/*
9500 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9501 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9502 		 * set to tcp_cwnd_ssthresh.
9503 		 */
9504 		if (notsack_blk == NULL) {
9505 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9506 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9507 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9508 				ASSERT(tcp->tcp_cwnd > 0);
9509 				return;
9510 			} else {
9511 				usable_swnd = usable_swnd / mss;
9512 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9513 				    MAX(usable_swnd * mss, mss);
9514 				*flags |= TH_XMIT_NEEDED;
9515 				return;
9516 			}
9517 		}
9518 
9519 		/*
9520 		 * Note that we may send more than usable_swnd allows here
9521 		 * because of round off, but no more than 1 MSS of data.
9522 		 */
9523 		seg_len = end - begin;
9524 		if (seg_len > mss)
9525 			seg_len = mss;
9526 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9527 		ASSERT(snxt_mp != NULL);
9528 		/* This should not happen.  Defensive coding again... */
9529 		if (snxt_mp == NULL) {
9530 			return;
9531 		}
9532 
9533 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9534 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9535 		if (xmit_mp == NULL)
9536 			return;
9537 
9538 		usable_swnd -= seg_len;
9539 		tcp->tcp_pipe += seg_len;
9540 		tcp->tcp_sack_snxt = begin + seg_len;
9541 
9542 		tcp_send_data(tcp, xmit_mp);
9543 
9544 		/*
9545 		 * Update the send timestamp to avoid false retransmission.
9546 		 */
9547 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9548 
9549 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9550 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9551 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9552 		/*
9553 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9554 		 * This happens when new data sent during fast recovery is
9555 		 * also lost.  If TCP retransmits those new data, it needs
9556 		 * to extend SACK recover phase to avoid starting another
9557 		 * fast retransmit/recovery unnecessarily.
9558 		 */
9559 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9560 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9561 		}
9562 	}
9563 }
9564 
9565 /*
9566  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9567  * or ICMP errors.
9568  *
9569  * To limit the number of duplicate segments, we limit the number of segment
9570  * to be sent in one time to tcp_snd_burst, the burst variable.
9571  */
9572 static void
9573 tcp_ss_rexmit(tcp_t *tcp)
9574 {
9575 	uint32_t	snxt;
9576 	uint32_t	smax;
9577 	int32_t		win;
9578 	int32_t		mss;
9579 	int32_t		off;
9580 	int32_t		burst = tcp->tcp_snd_burst;
9581 	mblk_t		*snxt_mp;
9582 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9583 
9584 	/*
9585 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9586 	 * all unack'ed segments.
9587 	 */
9588 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9589 		smax = tcp->tcp_rexmit_max;
9590 		snxt = tcp->tcp_rexmit_nxt;
9591 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9592 			snxt = tcp->tcp_suna;
9593 		}
9594 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9595 		win -= snxt - tcp->tcp_suna;
9596 		mss = tcp->tcp_mss;
9597 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9598 
9599 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9600 		    (burst > 0) && (snxt_mp != NULL)) {
9601 			mblk_t	*xmit_mp;
9602 			mblk_t	*old_snxt_mp = snxt_mp;
9603 			uint32_t cnt = mss;
9604 
9605 			if (win < cnt) {
9606 				cnt = win;
9607 			}
9608 			if (SEQ_GT(snxt + cnt, smax)) {
9609 				cnt = smax - snxt;
9610 			}
9611 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9612 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9613 			if (xmit_mp == NULL)
9614 				return;
9615 
9616 			tcp_send_data(tcp, xmit_mp);
9617 
9618 			snxt += cnt;
9619 			win -= cnt;
9620 			/*
9621 			 * Update the send timestamp to avoid false
9622 			 * retransmission.
9623 			 */
9624 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9625 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9626 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9627 
9628 			tcp->tcp_rexmit_nxt = snxt;
9629 			burst--;
9630 		}
9631 		/*
9632 		 * If we have transmitted all we have at the time
9633 		 * we started the retranmission, we can leave
9634 		 * the rest of the job to tcp_wput_data().  But we
9635 		 * need to check the send window first.  If the
9636 		 * win is not 0, go on with tcp_wput_data().
9637 		 */
9638 		if (SEQ_LT(snxt, smax) || win == 0) {
9639 			return;
9640 		}
9641 	}
9642 	/* Only call tcp_wput_data() if there is data to be sent. */
9643 	if (tcp->tcp_unsent) {
9644 		tcp_wput_data(tcp, NULL, B_FALSE);
9645 	}
9646 }
9647 
9648 /*
9649  * Process all TCP option in SYN segment.  Note that this function should
9650  * be called after tcp_set_destination() is called so that the necessary info
9651  * from IRE is already set in the tcp structure.
9652  *
9653  * This function sets up the correct tcp_mss value according to the
9654  * MSS option value and our header size.  It also sets up the window scale
9655  * and timestamp values, and initialize SACK info blocks.  But it does not
9656  * change receive window size after setting the tcp_mss value.  The caller
9657  * should do the appropriate change.
9658  */
9659 void
9660 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9661 {
9662 	int options;
9663 	tcp_opt_t tcpopt;
9664 	uint32_t mss_max;
9665 	char *tmp_tcph;
9666 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9667 	conn_t		*connp = tcp->tcp_connp;
9668 
9669 	tcpopt.tcp = NULL;
9670 	options = tcp_parse_options(tcpha, &tcpopt);
9671 
9672 	/*
9673 	 * Process MSS option.  Note that MSS option value does not account
9674 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9675 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9676 	 * IPv6.
9677 	 */
9678 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9679 		if (connp->conn_ipversion == IPV4_VERSION)
9680 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9681 		else
9682 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9683 	} else {
9684 		if (connp->conn_ipversion == IPV4_VERSION)
9685 			mss_max = tcps->tcps_mss_max_ipv4;
9686 		else
9687 			mss_max = tcps->tcps_mss_max_ipv6;
9688 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9689 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9690 		else if (tcpopt.tcp_opt_mss > mss_max)
9691 			tcpopt.tcp_opt_mss = mss_max;
9692 	}
9693 
9694 	/* Process Window Scale option. */
9695 	if (options & TCP_OPT_WSCALE_PRESENT) {
9696 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9697 		tcp->tcp_snd_ws_ok = B_TRUE;
9698 	} else {
9699 		tcp->tcp_snd_ws = B_FALSE;
9700 		tcp->tcp_snd_ws_ok = B_FALSE;
9701 		tcp->tcp_rcv_ws = B_FALSE;
9702 	}
9703 
9704 	/* Process Timestamp option. */
9705 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9706 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9707 		tmp_tcph = (char *)tcp->tcp_tcpha;
9708 
9709 		tcp->tcp_snd_ts_ok = B_TRUE;
9710 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9711 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9712 		ASSERT(OK_32PTR(tmp_tcph));
9713 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9714 
9715 		/* Fill in our template header with basic timestamp option. */
9716 		tmp_tcph += connp->conn_ht_ulp_len;
9717 		tmp_tcph[0] = TCPOPT_NOP;
9718 		tmp_tcph[1] = TCPOPT_NOP;
9719 		tmp_tcph[2] = TCPOPT_TSTAMP;
9720 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9721 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9722 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9723 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9724 	} else {
9725 		tcp->tcp_snd_ts_ok = B_FALSE;
9726 	}
9727 
9728 	/*
9729 	 * Process SACK options.  If SACK is enabled for this connection,
9730 	 * then allocate the SACK info structure.  Note the following ways
9731 	 * when tcp_snd_sack_ok is set to true.
9732 	 *
9733 	 * For active connection: in tcp_set_destination() called in
9734 	 * tcp_connect().
9735 	 *
9736 	 * For passive connection: in tcp_set_destination() called in
9737 	 * tcp_input_listener().
9738 	 *
9739 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9740 	 * That check makes sure that if we did not send a SACK OK option,
9741 	 * we will not enable SACK for this connection even though the other
9742 	 * side sends us SACK OK option.  For active connection, the SACK
9743 	 * info structure has already been allocated.  So we need to free
9744 	 * it if SACK is disabled.
9745 	 */
9746 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9747 	    (tcp->tcp_snd_sack_ok ||
9748 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9749 		/* This should be true only in the passive case. */
9750 		if (tcp->tcp_sack_info == NULL) {
9751 			ASSERT(TCP_IS_DETACHED(tcp));
9752 			tcp->tcp_sack_info =
9753 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9754 		}
9755 		if (tcp->tcp_sack_info == NULL) {
9756 			tcp->tcp_snd_sack_ok = B_FALSE;
9757 		} else {
9758 			tcp->tcp_snd_sack_ok = B_TRUE;
9759 			if (tcp->tcp_snd_ts_ok) {
9760 				tcp->tcp_max_sack_blk = 3;
9761 			} else {
9762 				tcp->tcp_max_sack_blk = 4;
9763 			}
9764 		}
9765 	} else {
9766 		/*
9767 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9768 		 * no SACK info will be used for this
9769 		 * connection.  This assumes that SACK usage
9770 		 * permission is negotiated.  This may need
9771 		 * to be changed once this is clarified.
9772 		 */
9773 		if (tcp->tcp_sack_info != NULL) {
9774 			ASSERT(tcp->tcp_notsack_list == NULL);
9775 			kmem_cache_free(tcp_sack_info_cache,
9776 			    tcp->tcp_sack_info);
9777 			tcp->tcp_sack_info = NULL;
9778 		}
9779 		tcp->tcp_snd_sack_ok = B_FALSE;
9780 	}
9781 
9782 	/*
9783 	 * Now we know the exact TCP/IP header length, subtract
9784 	 * that from tcp_mss to get our side's MSS.
9785 	 */
9786 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9787 
9788 	/*
9789 	 * Here we assume that the other side's header size will be equal to
9790 	 * our header size.  We calculate the real MSS accordingly.  Need to
9791 	 * take into additional stuffs IPsec puts in.
9792 	 *
9793 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9794 	 */
9795 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9796 	    tcp->tcp_ipsec_overhead -
9797 	    ((connp->conn_ipversion == IPV4_VERSION ?
9798 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9799 
9800 	/*
9801 	 * Set MSS to the smaller one of both ends of the connection.
9802 	 * We should not have called tcp_mss_set() before, but our
9803 	 * side of the MSS should have been set to a proper value
9804 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9805 	 * STREAM head parameters properly.
9806 	 *
9807 	 * If we have a larger-than-16-bit window but the other side
9808 	 * didn't want to do window scale, tcp_rwnd_set() will take
9809 	 * care of that.
9810 	 */
9811 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9812 
9813 	/*
9814 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9815 	 * updated properly.
9816 	 */
9817 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9818 }
9819 
9820 /*
9821  * Sends the T_CONN_IND to the listener. The caller calls this
9822  * functions via squeue to get inside the listener's perimeter
9823  * once the 3 way hand shake is done a T_CONN_IND needs to be
9824  * sent. As an optimization, the caller can call this directly
9825  * if listener's perimeter is same as eager's.
9826  */
9827 /* ARGSUSED */
9828 void
9829 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9830 {
9831 	conn_t			*lconnp = (conn_t *)arg;
9832 	tcp_t			*listener = lconnp->conn_tcp;
9833 	tcp_t			*tcp;
9834 	struct T_conn_ind	*conn_ind;
9835 	ipaddr_t 		*addr_cache;
9836 	boolean_t		need_send_conn_ind = B_FALSE;
9837 	tcp_stack_t		*tcps = listener->tcp_tcps;
9838 
9839 	/* retrieve the eager */
9840 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9841 	ASSERT(conn_ind->OPT_offset != 0 &&
9842 	    conn_ind->OPT_length == sizeof (intptr_t));
9843 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9844 	    conn_ind->OPT_length);
9845 
9846 	/*
9847 	 * TLI/XTI applications will get confused by
9848 	 * sending eager as an option since it violates
9849 	 * the option semantics. So remove the eager as
9850 	 * option since TLI/XTI app doesn't need it anyway.
9851 	 */
9852 	if (!TCP_IS_SOCKET(listener)) {
9853 		conn_ind->OPT_length = 0;
9854 		conn_ind->OPT_offset = 0;
9855 	}
9856 	if (listener->tcp_state != TCPS_LISTEN) {
9857 		/*
9858 		 * If listener has closed, it would have caused a
9859 		 * a cleanup/blowoff to happen for the eager. We
9860 		 * just need to return.
9861 		 */
9862 		freemsg(mp);
9863 		return;
9864 	}
9865 
9866 
9867 	/*
9868 	 * if the conn_req_q is full defer passing up the
9869 	 * T_CONN_IND until space is availabe after t_accept()
9870 	 * processing
9871 	 */
9872 	mutex_enter(&listener->tcp_eager_lock);
9873 
9874 	/*
9875 	 * Take the eager out, if it is in the list of droppable eagers
9876 	 * as we are here because the 3W handshake is over.
9877 	 */
9878 	MAKE_UNDROPPABLE(tcp);
9879 
9880 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9881 		tcp_t *tail;
9882 
9883 		/*
9884 		 * The eager already has an extra ref put in tcp_input_data
9885 		 * so that it stays till accept comes back even though it
9886 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9887 		 */
9888 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9889 		listener->tcp_conn_req_cnt_q0--;
9890 		listener->tcp_conn_req_cnt_q++;
9891 
9892 		/* Move from SYN_RCVD to ESTABLISHED list  */
9893 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9894 		    tcp->tcp_eager_prev_q0;
9895 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9896 		    tcp->tcp_eager_next_q0;
9897 		tcp->tcp_eager_prev_q0 = NULL;
9898 		tcp->tcp_eager_next_q0 = NULL;
9899 
9900 		/*
9901 		 * Insert at end of the queue because sockfs
9902 		 * sends down T_CONN_RES in chronological
9903 		 * order. Leaving the older conn indications
9904 		 * at front of the queue helps reducing search
9905 		 * time.
9906 		 */
9907 		tail = listener->tcp_eager_last_q;
9908 		if (tail != NULL)
9909 			tail->tcp_eager_next_q = tcp;
9910 		else
9911 			listener->tcp_eager_next_q = tcp;
9912 		listener->tcp_eager_last_q = tcp;
9913 		tcp->tcp_eager_next_q = NULL;
9914 		/*
9915 		 * Delay sending up the T_conn_ind until we are
9916 		 * done with the eager. Once we have have sent up
9917 		 * the T_conn_ind, the accept can potentially complete
9918 		 * any time and release the refhold we have on the eager.
9919 		 */
9920 		need_send_conn_ind = B_TRUE;
9921 	} else {
9922 		/*
9923 		 * Defer connection on q0 and set deferred
9924 		 * connection bit true
9925 		 */
9926 		tcp->tcp_conn_def_q0 = B_TRUE;
9927 
9928 		/* take tcp out of q0 ... */
9929 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9930 		    tcp->tcp_eager_next_q0;
9931 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9932 		    tcp->tcp_eager_prev_q0;
9933 
9934 		/* ... and place it at the end of q0 */
9935 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9936 		tcp->tcp_eager_next_q0 = listener;
9937 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9938 		listener->tcp_eager_prev_q0 = tcp;
9939 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9940 	}
9941 
9942 	/* we have timed out before */
9943 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9944 		tcp->tcp_syn_rcvd_timeout = 0;
9945 		listener->tcp_syn_rcvd_timeout--;
9946 		if (listener->tcp_syn_defense &&
9947 		    listener->tcp_syn_rcvd_timeout <=
9948 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9949 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9950 		    listener->tcp_last_rcv_lbolt)) {
9951 			/*
9952 			 * Turn off the defense mode if we
9953 			 * believe the SYN attack is over.
9954 			 */
9955 			listener->tcp_syn_defense = B_FALSE;
9956 			if (listener->tcp_ip_addr_cache) {
9957 				kmem_free((void *)listener->tcp_ip_addr_cache,
9958 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9959 				listener->tcp_ip_addr_cache = NULL;
9960 			}
9961 		}
9962 	}
9963 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9964 	if (addr_cache != NULL) {
9965 		/*
9966 		 * We have finished a 3-way handshake with this
9967 		 * remote host. This proves the IP addr is good.
9968 		 * Cache it!
9969 		 */
9970 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9971 		    tcp->tcp_connp->conn_faddr_v4;
9972 	}
9973 	mutex_exit(&listener->tcp_eager_lock);
9974 	if (need_send_conn_ind)
9975 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9976 }
9977 
9978 /*
9979  * Send the newconn notification to ulp. The eager is blown off if the
9980  * notification fails.
9981  */
9982 static void
9983 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9984 {
9985 	if (IPCL_IS_NONSTR(lconnp)) {
9986 		cred_t	*cr;
9987 		pid_t	cpid = NOPID;
9988 
9989 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9990 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9991 		    lconnp->conn_tcp);
9992 
9993 		cr = msg_getcred(mp, &cpid);
9994 
9995 		/* Keep the message around in case of a fallback to TPI */
9996 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9997 		/*
9998 		 * Notify the ULP about the newconn. It is guaranteed that no
9999 		 * tcp_accept() call will be made for the eager if the
10000 		 * notification fails, so it's safe to blow it off in that
10001 		 * case.
10002 		 *
10003 		 * The upper handle will be assigned when tcp_accept() is
10004 		 * called.
10005 		 */
10006 		if ((*lconnp->conn_upcalls->su_newconn)
10007 		    (lconnp->conn_upper_handle,
10008 		    (sock_lower_handle_t)econnp,
10009 		    &sock_tcp_downcalls, cr, cpid,
10010 		    &econnp->conn_upcalls) == NULL) {
10011 			/* Failed to allocate a socket */
10012 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
10013 			    tcpEstabResets);
10014 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
10015 			    econnp->conn_tcp->tcp_conn_req_seqnum);
10016 		}
10017 	} else {
10018 		putnext(lconnp->conn_rq, mp);
10019 	}
10020 }
10021 
10022 /*
10023  * Handle a packet that has been reclassified by TCP.
10024  * This function drops the ref on connp that the caller had.
10025  */
10026 static void
10027 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
10028 {
10029 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
10030 
10031 	if (connp->conn_incoming_ifindex != 0 &&
10032 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
10033 		freemsg(mp);
10034 		CONN_DEC_REF(connp);
10035 		return;
10036 	}
10037 
10038 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
10039 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
10040 		ip6_t *ip6h;
10041 		ipha_t *ipha;
10042 
10043 		if (ira->ira_flags & IRAF_IS_IPV4) {
10044 			ipha = (ipha_t *)mp->b_rptr;
10045 			ip6h = NULL;
10046 		} else {
10047 			ipha = NULL;
10048 			ip6h = (ip6_t *)mp->b_rptr;
10049 		}
10050 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
10051 		if (mp == NULL) {
10052 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
10053 			/* Note that mp is NULL */
10054 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
10055 			CONN_DEC_REF(connp);
10056 			return;
10057 		}
10058 	}
10059 
10060 	if (IPCL_IS_TCP(connp)) {
10061 		/*
10062 		 * do not drain, certain use cases can blow
10063 		 * the stack
10064 		 */
10065 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10066 		    connp->conn_recv, connp, ira,
10067 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10068 	} else {
10069 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10070 		(connp->conn_recv)(connp, mp, NULL,
10071 		    ira);
10072 		CONN_DEC_REF(connp);
10073 	}
10074 
10075 }
10076 
10077 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10078 
10079 /*
10080  * Handle M_DATA messages from IP. Its called directly from IP via
10081  * squeue for received IP packets.
10082  *
10083  * The first argument is always the connp/tcp to which the mp belongs.
10084  * There are no exceptions to this rule. The caller has already put
10085  * a reference on this connp/tcp and once tcp_input_data() returns,
10086  * the squeue will do the refrele.
10087  *
10088  * The TH_SYN for the listener directly go to tcp_input_listener via
10089  * squeue. ICMP errors go directly to tcp_icmp_input().
10090  *
10091  * sqp: NULL = recursive, sqp != NULL means called from squeue
10092  */
10093 void
10094 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10095 {
10096 	int32_t		bytes_acked;
10097 	int32_t		gap;
10098 	mblk_t		*mp1;
10099 	uint_t		flags;
10100 	uint32_t	new_swnd = 0;
10101 	uchar_t		*iphdr;
10102 	uchar_t		*rptr;
10103 	int32_t		rgap;
10104 	uint32_t	seg_ack;
10105 	int		seg_len;
10106 	uint_t		ip_hdr_len;
10107 	uint32_t	seg_seq;
10108 	tcpha_t		*tcpha;
10109 	int		urp;
10110 	tcp_opt_t	tcpopt;
10111 	ip_pkt_t	ipp;
10112 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10113 	uint32_t	cwnd;
10114 	uint32_t	add;
10115 	int		npkt;
10116 	int		mss;
10117 	conn_t		*connp = (conn_t *)arg;
10118 	squeue_t	*sqp = (squeue_t *)arg2;
10119 	tcp_t		*tcp = connp->conn_tcp;
10120 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10121 
10122 	/*
10123 	 * RST from fused tcp loopback peer should trigger an unfuse.
10124 	 */
10125 	if (tcp->tcp_fused) {
10126 		TCP_STAT(tcps, tcp_fusion_aborted);
10127 		tcp_unfuse(tcp);
10128 	}
10129 
10130 	iphdr = mp->b_rptr;
10131 	rptr = mp->b_rptr;
10132 	ASSERT(OK_32PTR(rptr));
10133 
10134 	ip_hdr_len = ira->ira_ip_hdr_length;
10135 	if (connp->conn_recv_ancillary.crb_all != 0) {
10136 		/*
10137 		 * Record packet information in the ip_pkt_t
10138 		 */
10139 		ipp.ipp_fields = 0;
10140 		if (ira->ira_flags & IRAF_IS_IPV4) {
10141 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10142 			    B_FALSE);
10143 		} else {
10144 			uint8_t nexthdrp;
10145 
10146 			/*
10147 			 * IPv6 packets can only be received by applications
10148 			 * that are prepared to receive IPv6 addresses.
10149 			 * The IP fanout must ensure this.
10150 			 */
10151 			ASSERT(connp->conn_family == AF_INET6);
10152 
10153 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10154 			    &nexthdrp);
10155 			ASSERT(nexthdrp == IPPROTO_TCP);
10156 
10157 			/* Could have caused a pullup? */
10158 			iphdr = mp->b_rptr;
10159 			rptr = mp->b_rptr;
10160 		}
10161 	}
10162 	ASSERT(DB_TYPE(mp) == M_DATA);
10163 	ASSERT(mp->b_next == NULL);
10164 
10165 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10166 	seg_seq = ntohl(tcpha->tha_seq);
10167 	seg_ack = ntohl(tcpha->tha_ack);
10168 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10169 	seg_len = (int)(mp->b_wptr - rptr) -
10170 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10171 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10172 		do {
10173 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10174 			    (uintptr_t)INT_MAX);
10175 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10176 		} while ((mp1 = mp1->b_cont) != NULL &&
10177 		    mp1->b_datap->db_type == M_DATA);
10178 	}
10179 
10180 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10181 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10182 		    seg_len, tcpha, ira);
10183 		return;
10184 	}
10185 
10186 	if (sqp != NULL) {
10187 		/*
10188 		 * This is the correct place to update tcp_last_recv_time. Note
10189 		 * that it is also updated for tcp structure that belongs to
10190 		 * global and listener queues which do not really need updating.
10191 		 * But that should not cause any harm.  And it is updated for
10192 		 * all kinds of incoming segments, not only for data segments.
10193 		 */
10194 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10195 	}
10196 
10197 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10198 
10199 	BUMP_LOCAL(tcp->tcp_ibsegs);
10200 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10201 
10202 	if ((flags & TH_URG) && sqp != NULL) {
10203 		/*
10204 		 * TCP can't handle urgent pointers that arrive before
10205 		 * the connection has been accept()ed since it can't
10206 		 * buffer OOB data.  Discard segment if this happens.
10207 		 *
10208 		 * We can't just rely on a non-null tcp_listener to indicate
10209 		 * that the accept() has completed since unlinking of the
10210 		 * eager and completion of the accept are not atomic.
10211 		 * tcp_detached, when it is not set (B_FALSE) indicates
10212 		 * that the accept() has completed.
10213 		 *
10214 		 * Nor can it reassemble urgent pointers, so discard
10215 		 * if it's not the next segment expected.
10216 		 *
10217 		 * Otherwise, collapse chain into one mblk (discard if
10218 		 * that fails).  This makes sure the headers, retransmitted
10219 		 * data, and new data all are in the same mblk.
10220 		 */
10221 		ASSERT(mp != NULL);
10222 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10223 			freemsg(mp);
10224 			return;
10225 		}
10226 		/* Update pointers into message */
10227 		iphdr = rptr = mp->b_rptr;
10228 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10229 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10230 			/*
10231 			 * Since we can't handle any data with this urgent
10232 			 * pointer that is out of sequence, we expunge
10233 			 * the data.  This allows us to still register
10234 			 * the urgent mark and generate the M_PCSIG,
10235 			 * which we can do.
10236 			 */
10237 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10238 			seg_len = 0;
10239 		}
10240 	}
10241 
10242 	switch (tcp->tcp_state) {
10243 	case TCPS_SYN_SENT:
10244 		if (connp->conn_final_sqp == NULL &&
10245 		    tcp_outbound_squeue_switch && sqp != NULL) {
10246 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10247 			connp->conn_final_sqp = sqp;
10248 			if (connp->conn_final_sqp != connp->conn_sqp) {
10249 				DTRACE_PROBE1(conn__final__sqp__switch,
10250 				    conn_t *, connp);
10251 				CONN_INC_REF(connp);
10252 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10253 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10254 				    tcp_input_data, connp, ira, ip_squeue_flag,
10255 				    SQTAG_CONNECT_FINISH);
10256 				return;
10257 			}
10258 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10259 		}
10260 		if (flags & TH_ACK) {
10261 			/*
10262 			 * Note that our stack cannot send data before a
10263 			 * connection is established, therefore the
10264 			 * following check is valid.  Otherwise, it has
10265 			 * to be changed.
10266 			 */
10267 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10268 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10269 				freemsg(mp);
10270 				if (flags & TH_RST)
10271 					return;
10272 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10273 				    tcp, seg_ack, 0, TH_RST);
10274 				return;
10275 			}
10276 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10277 		}
10278 		if (flags & TH_RST) {
10279 			freemsg(mp);
10280 			if (flags & TH_ACK)
10281 				(void) tcp_clean_death(tcp,
10282 				    ECONNREFUSED, 13);
10283 			return;
10284 		}
10285 		if (!(flags & TH_SYN)) {
10286 			freemsg(mp);
10287 			return;
10288 		}
10289 
10290 		/* Process all TCP options. */
10291 		tcp_process_options(tcp, tcpha);
10292 		/*
10293 		 * The following changes our rwnd to be a multiple of the
10294 		 * MIN(peer MSS, our MSS) for performance reason.
10295 		 */
10296 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10297 		    tcp->tcp_mss));
10298 
10299 		/* Is the other end ECN capable? */
10300 		if (tcp->tcp_ecn_ok) {
10301 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10302 				tcp->tcp_ecn_ok = B_FALSE;
10303 			}
10304 		}
10305 		/*
10306 		 * Clear ECN flags because it may interfere with later
10307 		 * processing.
10308 		 */
10309 		flags &= ~(TH_ECE|TH_CWR);
10310 
10311 		tcp->tcp_irs = seg_seq;
10312 		tcp->tcp_rack = seg_seq;
10313 		tcp->tcp_rnxt = seg_seq + 1;
10314 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10315 		if (!TCP_IS_DETACHED(tcp)) {
10316 			/* Allocate room for SACK options if needed. */
10317 			connp->conn_wroff = connp->conn_ht_iphc_len;
10318 			if (tcp->tcp_snd_sack_ok)
10319 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10320 			if (!tcp->tcp_loopback)
10321 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10322 
10323 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10324 			    connp->conn_wroff);
10325 		}
10326 		if (flags & TH_ACK) {
10327 			/*
10328 			 * If we can't get the confirmation upstream, pretend
10329 			 * we didn't even see this one.
10330 			 *
10331 			 * XXX: how can we pretend we didn't see it if we
10332 			 * have updated rnxt et. al.
10333 			 *
10334 			 * For loopback we defer sending up the T_CONN_CON
10335 			 * until after some checks below.
10336 			 */
10337 			mp1 = NULL;
10338 			/*
10339 			 * tcp_sendmsg() checks tcp_state without entering
10340 			 * the squeue so tcp_state should be updated before
10341 			 * sending up connection confirmation
10342 			 */
10343 			tcp->tcp_state = TCPS_ESTABLISHED;
10344 			if (!tcp_conn_con(tcp, iphdr, mp,
10345 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10346 				tcp->tcp_state = TCPS_SYN_SENT;
10347 				freemsg(mp);
10348 				return;
10349 			}
10350 			/* SYN was acked - making progress */
10351 			tcp->tcp_ip_forward_progress = B_TRUE;
10352 
10353 			/* One for the SYN */
10354 			tcp->tcp_suna = tcp->tcp_iss + 1;
10355 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10356 
10357 			/*
10358 			 * If SYN was retransmitted, need to reset all
10359 			 * retransmission info.  This is because this
10360 			 * segment will be treated as a dup ACK.
10361 			 */
10362 			if (tcp->tcp_rexmit) {
10363 				tcp->tcp_rexmit = B_FALSE;
10364 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10365 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10366 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10367 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10368 				tcp->tcp_ms_we_have_waited = 0;
10369 
10370 				/*
10371 				 * Set tcp_cwnd back to 1 MSS, per
10372 				 * recommendation from
10373 				 * draft-floyd-incr-init-win-01.txt,
10374 				 * Increasing TCP's Initial Window.
10375 				 */
10376 				tcp->tcp_cwnd = tcp->tcp_mss;
10377 			}
10378 
10379 			tcp->tcp_swl1 = seg_seq;
10380 			tcp->tcp_swl2 = seg_ack;
10381 
10382 			new_swnd = ntohs(tcpha->tha_win);
10383 			tcp->tcp_swnd = new_swnd;
10384 			if (new_swnd > tcp->tcp_max_swnd)
10385 				tcp->tcp_max_swnd = new_swnd;
10386 
10387 			/*
10388 			 * Always send the three-way handshake ack immediately
10389 			 * in order to make the connection complete as soon as
10390 			 * possible on the accepting host.
10391 			 */
10392 			flags |= TH_ACK_NEEDED;
10393 
10394 			/*
10395 			 * Special case for loopback.  At this point we have
10396 			 * received SYN-ACK from the remote endpoint.  In
10397 			 * order to ensure that both endpoints reach the
10398 			 * fused state prior to any data exchange, the final
10399 			 * ACK needs to be sent before we indicate T_CONN_CON
10400 			 * to the module upstream.
10401 			 */
10402 			if (tcp->tcp_loopback) {
10403 				mblk_t *ack_mp;
10404 
10405 				ASSERT(!tcp->tcp_unfusable);
10406 				ASSERT(mp1 != NULL);
10407 				/*
10408 				 * For loopback, we always get a pure SYN-ACK
10409 				 * and only need to send back the final ACK
10410 				 * with no data (this is because the other
10411 				 * tcp is ours and we don't do T/TCP).  This
10412 				 * final ACK triggers the passive side to
10413 				 * perform fusion in ESTABLISHED state.
10414 				 */
10415 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10416 					if (tcp->tcp_ack_tid != 0) {
10417 						(void) TCP_TIMER_CANCEL(tcp,
10418 						    tcp->tcp_ack_tid);
10419 						tcp->tcp_ack_tid = 0;
10420 					}
10421 					tcp_send_data(tcp, ack_mp);
10422 					BUMP_LOCAL(tcp->tcp_obsegs);
10423 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10424 
10425 					if (!IPCL_IS_NONSTR(connp)) {
10426 						/* Send up T_CONN_CON */
10427 						if (ira->ira_cred != NULL) {
10428 							mblk_setcred(mp1,
10429 							    ira->ira_cred,
10430 							    ira->ira_cpid);
10431 						}
10432 						putnext(connp->conn_rq, mp1);
10433 					} else {
10434 						(*connp->conn_upcalls->
10435 						    su_connected)
10436 						    (connp->conn_upper_handle,
10437 						    tcp->tcp_connid,
10438 						    ira->ira_cred,
10439 						    ira->ira_cpid);
10440 						freemsg(mp1);
10441 					}
10442 
10443 					freemsg(mp);
10444 					return;
10445 				}
10446 				/*
10447 				 * Forget fusion; we need to handle more
10448 				 * complex cases below.  Send the deferred
10449 				 * T_CONN_CON message upstream and proceed
10450 				 * as usual.  Mark this tcp as not capable
10451 				 * of fusion.
10452 				 */
10453 				TCP_STAT(tcps, tcp_fusion_unfusable);
10454 				tcp->tcp_unfusable = B_TRUE;
10455 				if (!IPCL_IS_NONSTR(connp)) {
10456 					if (ira->ira_cred != NULL) {
10457 						mblk_setcred(mp1, ira->ira_cred,
10458 						    ira->ira_cpid);
10459 					}
10460 					putnext(connp->conn_rq, mp1);
10461 				} else {
10462 					(*connp->conn_upcalls->su_connected)
10463 					    (connp->conn_upper_handle,
10464 					    tcp->tcp_connid, ira->ira_cred,
10465 					    ira->ira_cpid);
10466 					freemsg(mp1);
10467 				}
10468 			}
10469 
10470 			/*
10471 			 * Check to see if there is data to be sent.  If
10472 			 * yes, set the transmit flag.  Then check to see
10473 			 * if received data processing needs to be done.
10474 			 * If not, go straight to xmit_check.  This short
10475 			 * cut is OK as we don't support T/TCP.
10476 			 */
10477 			if (tcp->tcp_unsent)
10478 				flags |= TH_XMIT_NEEDED;
10479 
10480 			if (seg_len == 0 && !(flags & TH_URG)) {
10481 				freemsg(mp);
10482 				goto xmit_check;
10483 			}
10484 
10485 			flags &= ~TH_SYN;
10486 			seg_seq++;
10487 			break;
10488 		}
10489 		tcp->tcp_state = TCPS_SYN_RCVD;
10490 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10491 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10492 		if (mp1 != NULL) {
10493 			tcp_send_data(tcp, mp1);
10494 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10495 		}
10496 		freemsg(mp);
10497 		return;
10498 	case TCPS_SYN_RCVD:
10499 		if (flags & TH_ACK) {
10500 			/*
10501 			 * In this state, a SYN|ACK packet is either bogus
10502 			 * because the other side must be ACKing our SYN which
10503 			 * indicates it has seen the ACK for their SYN and
10504 			 * shouldn't retransmit it or we're crossing SYNs
10505 			 * on active open.
10506 			 */
10507 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10508 				freemsg(mp);
10509 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10510 				    tcp, seg_ack, 0, TH_RST);
10511 				return;
10512 			}
10513 			/*
10514 			 * NOTE: RFC 793 pg. 72 says this should be
10515 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10516 			 * but that would mean we have an ack that ignored
10517 			 * our SYN.
10518 			 */
10519 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10520 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10521 				freemsg(mp);
10522 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10523 				    tcp, seg_ack, 0, TH_RST);
10524 				return;
10525 			}
10526 			/*
10527 			 * No sane TCP stack will send such a small window
10528 			 * without receiving any data.  Just drop this invalid
10529 			 * ACK.  We also shorten the abort timeout in case
10530 			 * this is an attack.
10531 			 */
10532 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
10533 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10534 				freemsg(mp);
10535 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10536 				tcp->tcp_second_ctimer_threshold =
10537 				    tcp_early_abort * SECONDS;
10538 				return;
10539 			}
10540 		}
10541 		break;
10542 	case TCPS_LISTEN:
10543 		/*
10544 		 * Only a TLI listener can come through this path when a
10545 		 * acceptor is going back to be a listener and a packet
10546 		 * for the acceptor hits the classifier. For a socket
10547 		 * listener, this can never happen because a listener
10548 		 * can never accept connection on itself and hence a
10549 		 * socket acceptor can not go back to being a listener.
10550 		 */
10551 		ASSERT(!TCP_IS_SOCKET(tcp));
10552 		/*FALLTHRU*/
10553 	case TCPS_CLOSED:
10554 	case TCPS_BOUND: {
10555 		conn_t	*new_connp;
10556 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10557 
10558 		/*
10559 		 * Don't accept any input on a closed tcp as this TCP logically
10560 		 * does not exist on the system. Don't proceed further with
10561 		 * this TCP. For instance, this packet could trigger another
10562 		 * close of this tcp which would be disastrous for tcp_refcnt.
10563 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10564 		 * be called at most once on a TCP. In this case we need to
10565 		 * refeed the packet into the classifier and figure out where
10566 		 * the packet should go.
10567 		 */
10568 		new_connp = ipcl_classify(mp, ira, ipst);
10569 		if (new_connp != NULL) {
10570 			/* Drops ref on new_connp */
10571 			tcp_reinput(new_connp, mp, ira, ipst);
10572 			return;
10573 		}
10574 		/* We failed to classify. For now just drop the packet */
10575 		freemsg(mp);
10576 		return;
10577 	}
10578 	case TCPS_IDLE:
10579 		/*
10580 		 * Handle the case where the tcp_clean_death() has happened
10581 		 * on a connection (application hasn't closed yet) but a packet
10582 		 * was already queued on squeue before tcp_clean_death()
10583 		 * was processed. Calling tcp_clean_death() twice on same
10584 		 * connection can result in weird behaviour.
10585 		 */
10586 		freemsg(mp);
10587 		return;
10588 	default:
10589 		break;
10590 	}
10591 
10592 	/*
10593 	 * Already on the correct queue/perimeter.
10594 	 * If this is a detached connection and not an eager
10595 	 * connection hanging off a listener then new data
10596 	 * (past the FIN) will cause a reset.
10597 	 * We do a special check here where it
10598 	 * is out of the main line, rather than check
10599 	 * if we are detached every time we see new
10600 	 * data down below.
10601 	 */
10602 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10603 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10604 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10605 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10606 
10607 		freemsg(mp);
10608 		/*
10609 		 * This could be an SSL closure alert. We're detached so just
10610 		 * acknowledge it this last time.
10611 		 */
10612 		if (tcp->tcp_kssl_ctx != NULL) {
10613 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10614 			tcp->tcp_kssl_ctx = NULL;
10615 
10616 			tcp->tcp_rnxt += seg_len;
10617 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10618 			flags |= TH_ACK_NEEDED;
10619 			goto ack_check;
10620 		}
10621 
10622 		tcp_xmit_ctl("new data when detached", tcp,
10623 		    tcp->tcp_snxt, 0, TH_RST);
10624 		(void) tcp_clean_death(tcp, EPROTO, 12);
10625 		return;
10626 	}
10627 
10628 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10629 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10630 	new_swnd = ntohs(tcpha->tha_win) <<
10631 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10632 
10633 	if (tcp->tcp_snd_ts_ok) {
10634 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10635 			/*
10636 			 * This segment is not acceptable.
10637 			 * Drop it and send back an ACK.
10638 			 */
10639 			freemsg(mp);
10640 			flags |= TH_ACK_NEEDED;
10641 			goto ack_check;
10642 		}
10643 	} else if (tcp->tcp_snd_sack_ok) {
10644 		ASSERT(tcp->tcp_sack_info != NULL);
10645 		tcpopt.tcp = tcp;
10646 		/*
10647 		 * SACK info in already updated in tcp_parse_options.  Ignore
10648 		 * all other TCP options...
10649 		 */
10650 		(void) tcp_parse_options(tcpha, &tcpopt);
10651 	}
10652 try_again:;
10653 	mss = tcp->tcp_mss;
10654 	gap = seg_seq - tcp->tcp_rnxt;
10655 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10656 	/*
10657 	 * gap is the amount of sequence space between what we expect to see
10658 	 * and what we got for seg_seq.  A positive value for gap means
10659 	 * something got lost.  A negative value means we got some old stuff.
10660 	 */
10661 	if (gap < 0) {
10662 		/* Old stuff present.  Is the SYN in there? */
10663 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10664 		    (seg_len != 0)) {
10665 			flags &= ~TH_SYN;
10666 			seg_seq++;
10667 			urp--;
10668 			/* Recompute the gaps after noting the SYN. */
10669 			goto try_again;
10670 		}
10671 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10672 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10673 		    (seg_len > -gap ? -gap : seg_len));
10674 		/* Remove the old stuff from seg_len. */
10675 		seg_len += gap;
10676 		/*
10677 		 * Anything left?
10678 		 * Make sure to check for unack'd FIN when rest of data
10679 		 * has been previously ack'd.
10680 		 */
10681 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10682 			/*
10683 			 * Resets are only valid if they lie within our offered
10684 			 * window.  If the RST bit is set, we just ignore this
10685 			 * segment.
10686 			 */
10687 			if (flags & TH_RST) {
10688 				freemsg(mp);
10689 				return;
10690 			}
10691 
10692 			/*
10693 			 * The arriving of dup data packets indicate that we
10694 			 * may have postponed an ack for too long, or the other
10695 			 * side's RTT estimate is out of shape. Start acking
10696 			 * more often.
10697 			 */
10698 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10699 			    tcp->tcp_rack_cnt >= 1 &&
10700 			    tcp->tcp_rack_abs_max > 2) {
10701 				tcp->tcp_rack_abs_max--;
10702 			}
10703 			tcp->tcp_rack_cur_max = 1;
10704 
10705 			/*
10706 			 * This segment is "unacceptable".  None of its
10707 			 * sequence space lies within our advertized window.
10708 			 *
10709 			 * Adjust seg_len to the original value for tracing.
10710 			 */
10711 			seg_len -= gap;
10712 			if (connp->conn_debug) {
10713 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10714 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10715 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10716 				    "seg_len %d, rnxt %u, snxt %u, %s",
10717 				    gap, rgap, flags, seg_seq, seg_ack,
10718 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10719 				    tcp_display(tcp, NULL,
10720 				    DISP_ADDR_AND_PORT));
10721 			}
10722 
10723 			/*
10724 			 * Arrange to send an ACK in response to the
10725 			 * unacceptable segment per RFC 793 page 69. There
10726 			 * is only one small difference between ours and the
10727 			 * acceptability test in the RFC - we accept ACK-only
10728 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10729 			 * will be generated.
10730 			 *
10731 			 * Note that we have to ACK an ACK-only packet at least
10732 			 * for stacks that send 0-length keep-alives with
10733 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10734 			 * section 4.2.3.6. As long as we don't ever generate
10735 			 * an unacceptable packet in response to an incoming
10736 			 * packet that is unacceptable, it should not cause
10737 			 * "ACK wars".
10738 			 */
10739 			flags |=  TH_ACK_NEEDED;
10740 
10741 			/*
10742 			 * Continue processing this segment in order to use the
10743 			 * ACK information it contains, but skip all other
10744 			 * sequence-number processing.	Processing the ACK
10745 			 * information is necessary in order to
10746 			 * re-synchronize connections that may have lost
10747 			 * synchronization.
10748 			 *
10749 			 * We clear seg_len and flag fields related to
10750 			 * sequence number processing as they are not
10751 			 * to be trusted for an unacceptable segment.
10752 			 */
10753 			seg_len = 0;
10754 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10755 			goto process_ack;
10756 		}
10757 
10758 		/* Fix seg_seq, and chew the gap off the front. */
10759 		seg_seq = tcp->tcp_rnxt;
10760 		urp += gap;
10761 		do {
10762 			mblk_t	*mp2;
10763 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10764 			    (uintptr_t)UINT_MAX);
10765 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10766 			if (gap > 0) {
10767 				mp->b_rptr = mp->b_wptr - gap;
10768 				break;
10769 			}
10770 			mp2 = mp;
10771 			mp = mp->b_cont;
10772 			freeb(mp2);
10773 		} while (gap < 0);
10774 		/*
10775 		 * If the urgent data has already been acknowledged, we
10776 		 * should ignore TH_URG below
10777 		 */
10778 		if (urp < 0)
10779 			flags &= ~TH_URG;
10780 	}
10781 	/*
10782 	 * rgap is the amount of stuff received out of window.  A negative
10783 	 * value is the amount out of window.
10784 	 */
10785 	if (rgap < 0) {
10786 		mblk_t	*mp2;
10787 
10788 		if (tcp->tcp_rwnd == 0) {
10789 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10790 		} else {
10791 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10792 			UPDATE_MIB(&tcps->tcps_mib,
10793 			    tcpInDataPastWinBytes, -rgap);
10794 		}
10795 
10796 		/*
10797 		 * seg_len does not include the FIN, so if more than
10798 		 * just the FIN is out of window, we act like we don't
10799 		 * see it.  (If just the FIN is out of window, rgap
10800 		 * will be zero and we will go ahead and acknowledge
10801 		 * the FIN.)
10802 		 */
10803 		flags &= ~TH_FIN;
10804 
10805 		/* Fix seg_len and make sure there is something left. */
10806 		seg_len += rgap;
10807 		if (seg_len <= 0) {
10808 			/*
10809 			 * Resets are only valid if they lie within our offered
10810 			 * window.  If the RST bit is set, we just ignore this
10811 			 * segment.
10812 			 */
10813 			if (flags & TH_RST) {
10814 				freemsg(mp);
10815 				return;
10816 			}
10817 
10818 			/* Per RFC 793, we need to send back an ACK. */
10819 			flags |= TH_ACK_NEEDED;
10820 
10821 			/*
10822 			 * Send SIGURG as soon as possible i.e. even
10823 			 * if the TH_URG was delivered in a window probe
10824 			 * packet (which will be unacceptable).
10825 			 *
10826 			 * We generate a signal if none has been generated
10827 			 * for this connection or if this is a new urgent
10828 			 * byte. Also send a zero-length "unmarked" message
10829 			 * to inform SIOCATMARK that this is not the mark.
10830 			 *
10831 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10832 			 * is sent up. This plus the check for old data
10833 			 * (gap >= 0) handles the wraparound of the sequence
10834 			 * number space without having to always track the
10835 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10836 			 * this max in its rcv_up variable).
10837 			 *
10838 			 * This prevents duplicate SIGURGS due to a "late"
10839 			 * zero-window probe when the T_EXDATA_IND has already
10840 			 * been sent up.
10841 			 */
10842 			if ((flags & TH_URG) &&
10843 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10844 			    tcp->tcp_urp_last))) {
10845 				if (IPCL_IS_NONSTR(connp)) {
10846 					if (!TCP_IS_DETACHED(tcp)) {
10847 						(*connp->conn_upcalls->
10848 						    su_signal_oob)
10849 						    (connp->conn_upper_handle,
10850 						    urp);
10851 					}
10852 				} else {
10853 					mp1 = allocb(0, BPRI_MED);
10854 					if (mp1 == NULL) {
10855 						freemsg(mp);
10856 						return;
10857 					}
10858 					if (!TCP_IS_DETACHED(tcp) &&
10859 					    !putnextctl1(connp->conn_rq,
10860 					    M_PCSIG, SIGURG)) {
10861 						/* Try again on the rexmit. */
10862 						freemsg(mp1);
10863 						freemsg(mp);
10864 						return;
10865 					}
10866 					/*
10867 					 * If the next byte would be the mark
10868 					 * then mark with MARKNEXT else mark
10869 					 * with NOTMARKNEXT.
10870 					 */
10871 					if (gap == 0 && urp == 0)
10872 						mp1->b_flag |= MSGMARKNEXT;
10873 					else
10874 						mp1->b_flag |= MSGNOTMARKNEXT;
10875 					freemsg(tcp->tcp_urp_mark_mp);
10876 					tcp->tcp_urp_mark_mp = mp1;
10877 					flags |= TH_SEND_URP_MARK;
10878 				}
10879 				tcp->tcp_urp_last_valid = B_TRUE;
10880 				tcp->tcp_urp_last = urp + seg_seq;
10881 			}
10882 			/*
10883 			 * If this is a zero window probe, continue to
10884 			 * process the ACK part.  But we need to set seg_len
10885 			 * to 0 to avoid data processing.  Otherwise just
10886 			 * drop the segment and send back an ACK.
10887 			 */
10888 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10889 				flags &= ~(TH_SYN | TH_URG);
10890 				seg_len = 0;
10891 				goto process_ack;
10892 			} else {
10893 				freemsg(mp);
10894 				goto ack_check;
10895 			}
10896 		}
10897 		/* Pitch out of window stuff off the end. */
10898 		rgap = seg_len;
10899 		mp2 = mp;
10900 		do {
10901 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10902 			    (uintptr_t)INT_MAX);
10903 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10904 			if (rgap < 0) {
10905 				mp2->b_wptr += rgap;
10906 				if ((mp1 = mp2->b_cont) != NULL) {
10907 					mp2->b_cont = NULL;
10908 					freemsg(mp1);
10909 				}
10910 				break;
10911 			}
10912 		} while ((mp2 = mp2->b_cont) != NULL);
10913 	}
10914 ok:;
10915 	/*
10916 	 * TCP should check ECN info for segments inside the window only.
10917 	 * Therefore the check should be done here.
10918 	 */
10919 	if (tcp->tcp_ecn_ok) {
10920 		if (flags & TH_CWR) {
10921 			tcp->tcp_ecn_echo_on = B_FALSE;
10922 		}
10923 		/*
10924 		 * Note that both ECN_CE and CWR can be set in the
10925 		 * same segment.  In this case, we once again turn
10926 		 * on ECN_ECHO.
10927 		 */
10928 		if (connp->conn_ipversion == IPV4_VERSION) {
10929 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10930 
10931 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10932 				tcp->tcp_ecn_echo_on = B_TRUE;
10933 			}
10934 		} else {
10935 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10936 
10937 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10938 			    htonl(IPH_ECN_CE << 20)) {
10939 				tcp->tcp_ecn_echo_on = B_TRUE;
10940 			}
10941 		}
10942 	}
10943 
10944 	/*
10945 	 * Check whether we can update tcp_ts_recent.  This test is
10946 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10947 	 * Extensions for High Performance: An Update", Internet Draft.
10948 	 */
10949 	if (tcp->tcp_snd_ts_ok &&
10950 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10951 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10952 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10953 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10954 	}
10955 
10956 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10957 		/*
10958 		 * FIN in an out of order segment.  We record this in
10959 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10960 		 * Clear the FIN so that any check on FIN flag will fail.
10961 		 * Remember that FIN also counts in the sequence number
10962 		 * space.  So we need to ack out of order FIN only segments.
10963 		 */
10964 		if (flags & TH_FIN) {
10965 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10966 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10967 			flags &= ~TH_FIN;
10968 			flags |= TH_ACK_NEEDED;
10969 		}
10970 		if (seg_len > 0) {
10971 			/* Fill in the SACK blk list. */
10972 			if (tcp->tcp_snd_sack_ok) {
10973 				ASSERT(tcp->tcp_sack_info != NULL);
10974 				tcp_sack_insert(tcp->tcp_sack_list,
10975 				    seg_seq, seg_seq + seg_len,
10976 				    &(tcp->tcp_num_sack_blk));
10977 			}
10978 
10979 			/*
10980 			 * Attempt reassembly and see if we have something
10981 			 * ready to go.
10982 			 */
10983 			mp = tcp_reass(tcp, mp, seg_seq);
10984 			/* Always ack out of order packets */
10985 			flags |= TH_ACK_NEEDED | TH_PUSH;
10986 			if (mp) {
10987 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10988 				    (uintptr_t)INT_MAX);
10989 				seg_len = mp->b_cont ? msgdsize(mp) :
10990 				    (int)(mp->b_wptr - mp->b_rptr);
10991 				seg_seq = tcp->tcp_rnxt;
10992 				/*
10993 				 * A gap is filled and the seq num and len
10994 				 * of the gap match that of a previously
10995 				 * received FIN, put the FIN flag back in.
10996 				 */
10997 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10998 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10999 					flags |= TH_FIN;
11000 					tcp->tcp_valid_bits &=
11001 					    ~TCP_OFO_FIN_VALID;
11002 				}
11003 				if (tcp->tcp_reass_tid != 0) {
11004 					(void) TCP_TIMER_CANCEL(tcp,
11005 					    tcp->tcp_reass_tid);
11006 					/*
11007 					 * Restart the timer if there is still
11008 					 * data in the reassembly queue.
11009 					 */
11010 					if (tcp->tcp_reass_head != NULL) {
11011 						tcp->tcp_reass_tid = TCP_TIMER(
11012 						    tcp, tcp_reass_timer,
11013 						    MSEC_TO_TICK(
11014 						    tcps->tcps_reass_timeout));
11015 					} else {
11016 						tcp->tcp_reass_tid = 0;
11017 					}
11018 				}
11019 			} else {
11020 				/*
11021 				 * Keep going even with NULL mp.
11022 				 * There may be a useful ACK or something else
11023 				 * we don't want to miss.
11024 				 *
11025 				 * But TCP should not perform fast retransmit
11026 				 * because of the ack number.  TCP uses
11027 				 * seg_len == 0 to determine if it is a pure
11028 				 * ACK.  And this is not a pure ACK.
11029 				 */
11030 				seg_len = 0;
11031 				ofo_seg = B_TRUE;
11032 
11033 				if (tcps->tcps_reass_timeout != 0 &&
11034 				    tcp->tcp_reass_tid == 0) {
11035 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
11036 					    tcp_reass_timer, MSEC_TO_TICK(
11037 					    tcps->tcps_reass_timeout));
11038 				}
11039 			}
11040 		}
11041 	} else if (seg_len > 0) {
11042 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
11043 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
11044 		/*
11045 		 * If an out of order FIN was received before, and the seq
11046 		 * num and len of the new segment match that of the FIN,
11047 		 * put the FIN flag back in.
11048 		 */
11049 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
11050 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
11051 			flags |= TH_FIN;
11052 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
11053 		}
11054 	}
11055 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
11056 	if (flags & TH_RST) {
11057 		freemsg(mp);
11058 		switch (tcp->tcp_state) {
11059 		case TCPS_SYN_RCVD:
11060 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
11061 			break;
11062 		case TCPS_ESTABLISHED:
11063 		case TCPS_FIN_WAIT_1:
11064 		case TCPS_FIN_WAIT_2:
11065 		case TCPS_CLOSE_WAIT:
11066 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11067 			break;
11068 		case TCPS_CLOSING:
11069 		case TCPS_LAST_ACK:
11070 			(void) tcp_clean_death(tcp, 0, 16);
11071 			break;
11072 		default:
11073 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11074 			(void) tcp_clean_death(tcp, ENXIO, 17);
11075 			break;
11076 		}
11077 		return;
11078 	}
11079 	if (flags & TH_SYN) {
11080 		/*
11081 		 * See RFC 793, Page 71
11082 		 *
11083 		 * The seq number must be in the window as it should
11084 		 * be "fixed" above.  If it is outside window, it should
11085 		 * be already rejected.  Note that we allow seg_seq to be
11086 		 * rnxt + rwnd because we want to accept 0 window probe.
11087 		 */
11088 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11089 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11090 		freemsg(mp);
11091 		/*
11092 		 * If the ACK flag is not set, just use our snxt as the
11093 		 * seq number of the RST segment.
11094 		 */
11095 		if (!(flags & TH_ACK)) {
11096 			seg_ack = tcp->tcp_snxt;
11097 		}
11098 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11099 		    TH_RST|TH_ACK);
11100 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11101 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11102 		return;
11103 	}
11104 	/*
11105 	 * urp could be -1 when the urp field in the packet is 0
11106 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11107 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11108 	 */
11109 	if (flags & TH_URG && urp >= 0) {
11110 		if (!tcp->tcp_urp_last_valid ||
11111 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11112 			/*
11113 			 * Non-STREAMS sockets handle the urgent data a litte
11114 			 * differently from STREAMS based sockets. There is no
11115 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11116 			 * flags to keep SIOCATMARK happy. Instead a
11117 			 * su_signal_oob upcall is made to update the mark.
11118 			 * Neither is a T_EXDATA_IND mblk needed to be
11119 			 * prepended to the urgent data. The urgent data is
11120 			 * delivered using the su_recv upcall, where we set
11121 			 * the MSG_OOB flag to indicate that it is urg data.
11122 			 *
11123 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11124 			 * are used by non-STREAMS sockets.
11125 			 */
11126 			if (IPCL_IS_NONSTR(connp)) {
11127 				if (!TCP_IS_DETACHED(tcp)) {
11128 					(*connp->conn_upcalls->su_signal_oob)
11129 					    (connp->conn_upper_handle, urp);
11130 				}
11131 			} else {
11132 				/*
11133 				 * If we haven't generated the signal yet for
11134 				 * this urgent pointer value, do it now.  Also,
11135 				 * send up a zero-length M_DATA indicating
11136 				 * whether or not this is the mark. The latter
11137 				 * is not needed when a T_EXDATA_IND is sent up.
11138 				 * However, if there are allocation failures
11139 				 * this code relies on the sender retransmitting
11140 				 * and the socket code for determining the mark
11141 				 * should not block waiting for the peer to
11142 				 * transmit. Thus, for simplicity we always
11143 				 * send up the mark indication.
11144 				 */
11145 				mp1 = allocb(0, BPRI_MED);
11146 				if (mp1 == NULL) {
11147 					freemsg(mp);
11148 					return;
11149 				}
11150 				if (!TCP_IS_DETACHED(tcp) &&
11151 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11152 				    SIGURG)) {
11153 					/* Try again on the rexmit. */
11154 					freemsg(mp1);
11155 					freemsg(mp);
11156 					return;
11157 				}
11158 				/*
11159 				 * Mark with NOTMARKNEXT for now.
11160 				 * The code below will change this to MARKNEXT
11161 				 * if we are at the mark.
11162 				 *
11163 				 * If there are allocation failures (e.g. in
11164 				 * dupmsg below) the next time tcp_input_data
11165 				 * sees the urgent segment it will send up the
11166 				 * MSGMARKNEXT message.
11167 				 */
11168 				mp1->b_flag |= MSGNOTMARKNEXT;
11169 				freemsg(tcp->tcp_urp_mark_mp);
11170 				tcp->tcp_urp_mark_mp = mp1;
11171 				flags |= TH_SEND_URP_MARK;
11172 #ifdef DEBUG
11173 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11174 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11175 				    "last %x, %s",
11176 				    seg_seq, urp, tcp->tcp_urp_last,
11177 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11178 #endif /* DEBUG */
11179 			}
11180 			tcp->tcp_urp_last_valid = B_TRUE;
11181 			tcp->tcp_urp_last = urp + seg_seq;
11182 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11183 			/*
11184 			 * An allocation failure prevented the previous
11185 			 * tcp_input_data from sending up the allocated
11186 			 * MSG*MARKNEXT message - send it up this time
11187 			 * around.
11188 			 */
11189 			flags |= TH_SEND_URP_MARK;
11190 		}
11191 
11192 		/*
11193 		 * If the urgent byte is in this segment, make sure that it is
11194 		 * all by itself.  This makes it much easier to deal with the
11195 		 * possibility of an allocation failure on the T_exdata_ind.
11196 		 * Note that seg_len is the number of bytes in the segment, and
11197 		 * urp is the offset into the segment of the urgent byte.
11198 		 * urp < seg_len means that the urgent byte is in this segment.
11199 		 */
11200 		if (urp < seg_len) {
11201 			if (seg_len != 1) {
11202 				uint32_t  tmp_rnxt;
11203 				/*
11204 				 * Break it up and feed it back in.
11205 				 * Re-attach the IP header.
11206 				 */
11207 				mp->b_rptr = iphdr;
11208 				if (urp > 0) {
11209 					/*
11210 					 * There is stuff before the urgent
11211 					 * byte.
11212 					 */
11213 					mp1 = dupmsg(mp);
11214 					if (!mp1) {
11215 						/*
11216 						 * Trim from urgent byte on.
11217 						 * The rest will come back.
11218 						 */
11219 						(void) adjmsg(mp,
11220 						    urp - seg_len);
11221 						tcp_input_data(connp,
11222 						    mp, NULL, ira);
11223 						return;
11224 					}
11225 					(void) adjmsg(mp1, urp - seg_len);
11226 					/* Feed this piece back in. */
11227 					tmp_rnxt = tcp->tcp_rnxt;
11228 					tcp_input_data(connp, mp1, NULL, ira);
11229 					/*
11230 					 * If the data passed back in was not
11231 					 * processed (ie: bad ACK) sending
11232 					 * the remainder back in will cause a
11233 					 * loop. In this case, drop the
11234 					 * packet and let the sender try
11235 					 * sending a good packet.
11236 					 */
11237 					if (tmp_rnxt == tcp->tcp_rnxt) {
11238 						freemsg(mp);
11239 						return;
11240 					}
11241 				}
11242 				if (urp != seg_len - 1) {
11243 					uint32_t  tmp_rnxt;
11244 					/*
11245 					 * There is stuff after the urgent
11246 					 * byte.
11247 					 */
11248 					mp1 = dupmsg(mp);
11249 					if (!mp1) {
11250 						/*
11251 						 * Trim everything beyond the
11252 						 * urgent byte.  The rest will
11253 						 * come back.
11254 						 */
11255 						(void) adjmsg(mp,
11256 						    urp + 1 - seg_len);
11257 						tcp_input_data(connp,
11258 						    mp, NULL, ira);
11259 						return;
11260 					}
11261 					(void) adjmsg(mp1, urp + 1 - seg_len);
11262 					tmp_rnxt = tcp->tcp_rnxt;
11263 					tcp_input_data(connp, mp1, NULL, ira);
11264 					/*
11265 					 * If the data passed back in was not
11266 					 * processed (ie: bad ACK) sending
11267 					 * the remainder back in will cause a
11268 					 * loop. In this case, drop the
11269 					 * packet and let the sender try
11270 					 * sending a good packet.
11271 					 */
11272 					if (tmp_rnxt == tcp->tcp_rnxt) {
11273 						freemsg(mp);
11274 						return;
11275 					}
11276 				}
11277 				tcp_input_data(connp, mp, NULL, ira);
11278 				return;
11279 			}
11280 			/*
11281 			 * This segment contains only the urgent byte.  We
11282 			 * have to allocate the T_exdata_ind, if we can.
11283 			 */
11284 			if (IPCL_IS_NONSTR(connp)) {
11285 				int error;
11286 
11287 				(*connp->conn_upcalls->su_recv)
11288 				    (connp->conn_upper_handle, mp, seg_len,
11289 				    MSG_OOB, &error, NULL);
11290 				/*
11291 				 * We should never be in middle of a
11292 				 * fallback, the squeue guarantees that.
11293 				 */
11294 				ASSERT(error != EOPNOTSUPP);
11295 				mp = NULL;
11296 				goto update_ack;
11297 			} else if (!tcp->tcp_urp_mp) {
11298 				struct T_exdata_ind *tei;
11299 				mp1 = allocb(sizeof (struct T_exdata_ind),
11300 				    BPRI_MED);
11301 				if (!mp1) {
11302 					/*
11303 					 * Sigh... It'll be back.
11304 					 * Generate any MSG*MARK message now.
11305 					 */
11306 					freemsg(mp);
11307 					seg_len = 0;
11308 					if (flags & TH_SEND_URP_MARK) {
11309 
11310 
11311 						ASSERT(tcp->tcp_urp_mark_mp);
11312 						tcp->tcp_urp_mark_mp->b_flag &=
11313 						    ~MSGNOTMARKNEXT;
11314 						tcp->tcp_urp_mark_mp->b_flag |=
11315 						    MSGMARKNEXT;
11316 					}
11317 					goto ack_check;
11318 				}
11319 				mp1->b_datap->db_type = M_PROTO;
11320 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11321 				tei->PRIM_type = T_EXDATA_IND;
11322 				tei->MORE_flag = 0;
11323 				mp1->b_wptr = (uchar_t *)&tei[1];
11324 				tcp->tcp_urp_mp = mp1;
11325 #ifdef DEBUG
11326 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11327 				    "tcp_rput: allocated exdata_ind %s",
11328 				    tcp_display(tcp, NULL,
11329 				    DISP_PORT_ONLY));
11330 #endif /* DEBUG */
11331 				/*
11332 				 * There is no need to send a separate MSG*MARK
11333 				 * message since the T_EXDATA_IND will be sent
11334 				 * now.
11335 				 */
11336 				flags &= ~TH_SEND_URP_MARK;
11337 				freemsg(tcp->tcp_urp_mark_mp);
11338 				tcp->tcp_urp_mark_mp = NULL;
11339 			}
11340 			/*
11341 			 * Now we are all set.  On the next putnext upstream,
11342 			 * tcp_urp_mp will be non-NULL and will get prepended
11343 			 * to what has to be this piece containing the urgent
11344 			 * byte.  If for any reason we abort this segment below,
11345 			 * if it comes back, we will have this ready, or it
11346 			 * will get blown off in close.
11347 			 */
11348 		} else if (urp == seg_len) {
11349 			/*
11350 			 * The urgent byte is the next byte after this sequence
11351 			 * number. If this endpoint is non-STREAMS, then there
11352 			 * is nothing to do here since the socket has already
11353 			 * been notified about the urg pointer by the
11354 			 * su_signal_oob call above.
11355 			 *
11356 			 * In case of STREAMS, some more work might be needed.
11357 			 * If there is data it is marked with MSGMARKNEXT and
11358 			 * and any tcp_urp_mark_mp is discarded since it is not
11359 			 * needed. Otherwise, if the code above just allocated
11360 			 * a zero-length tcp_urp_mark_mp message, that message
11361 			 * is tagged with MSGMARKNEXT. Sending up these
11362 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11363 			 * even though the T_EXDATA_IND will not be sent up
11364 			 * until the urgent byte arrives.
11365 			 */
11366 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11367 				if (seg_len != 0) {
11368 					flags |= TH_MARKNEXT_NEEDED;
11369 					freemsg(tcp->tcp_urp_mark_mp);
11370 					tcp->tcp_urp_mark_mp = NULL;
11371 					flags &= ~TH_SEND_URP_MARK;
11372 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11373 					flags |= TH_SEND_URP_MARK;
11374 					tcp->tcp_urp_mark_mp->b_flag &=
11375 					    ~MSGNOTMARKNEXT;
11376 					tcp->tcp_urp_mark_mp->b_flag |=
11377 					    MSGMARKNEXT;
11378 				}
11379 			}
11380 #ifdef DEBUG
11381 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11382 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11383 			    seg_len, flags,
11384 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11385 #endif /* DEBUG */
11386 		}
11387 #ifdef DEBUG
11388 		else {
11389 			/* Data left until we hit mark */
11390 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11391 			    "tcp_rput: URP %d bytes left, %s",
11392 			    urp - seg_len, tcp_display(tcp, NULL,
11393 			    DISP_PORT_ONLY));
11394 		}
11395 #endif /* DEBUG */
11396 	}
11397 
11398 process_ack:
11399 	if (!(flags & TH_ACK)) {
11400 		freemsg(mp);
11401 		goto xmit_check;
11402 	}
11403 	}
11404 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11405 
11406 	if (bytes_acked > 0)
11407 		tcp->tcp_ip_forward_progress = B_TRUE;
11408 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11409 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11410 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11411 			/* 3-way handshake complete - pass up the T_CONN_IND */
11412 			tcp_t	*listener = tcp->tcp_listener;
11413 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11414 
11415 			tcp->tcp_tconnind_started = B_TRUE;
11416 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11417 			/*
11418 			 * We are here means eager is fine but it can
11419 			 * get a TH_RST at any point between now and till
11420 			 * accept completes and disappear. We need to
11421 			 * ensure that reference to eager is valid after
11422 			 * we get out of eager's perimeter. So we do
11423 			 * an extra refhold.
11424 			 */
11425 			CONN_INC_REF(connp);
11426 
11427 			/*
11428 			 * The listener also exists because of the refhold
11429 			 * done in tcp_input_listener. Its possible that it
11430 			 * might have closed. We will check that once we
11431 			 * get inside listeners context.
11432 			 */
11433 			CONN_INC_REF(listener->tcp_connp);
11434 			if (listener->tcp_connp->conn_sqp ==
11435 			    connp->conn_sqp) {
11436 				/*
11437 				 * We optimize by not calling an SQUEUE_ENTER
11438 				 * on the listener since we know that the
11439 				 * listener and eager squeues are the same.
11440 				 * We are able to make this check safely only
11441 				 * because neither the eager nor the listener
11442 				 * can change its squeue. Only an active connect
11443 				 * can change its squeue
11444 				 */
11445 				tcp_send_conn_ind(listener->tcp_connp, mp,
11446 				    listener->tcp_connp->conn_sqp);
11447 				CONN_DEC_REF(listener->tcp_connp);
11448 			} else if (!tcp->tcp_loopback) {
11449 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11450 				    mp, tcp_send_conn_ind,
11451 				    listener->tcp_connp, NULL, SQ_FILL,
11452 				    SQTAG_TCP_CONN_IND);
11453 			} else {
11454 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11455 				    mp, tcp_send_conn_ind,
11456 				    listener->tcp_connp, NULL, SQ_PROCESS,
11457 				    SQTAG_TCP_CONN_IND);
11458 			}
11459 		}
11460 
11461 		/*
11462 		 * We are seeing the final ack in the three way
11463 		 * hand shake of a active open'ed connection
11464 		 * so we must send up a T_CONN_CON
11465 		 *
11466 		 * tcp_sendmsg() checks tcp_state without entering
11467 		 * the squeue so tcp_state should be updated before
11468 		 * sending up connection confirmation.
11469 		 */
11470 		tcp->tcp_state = TCPS_ESTABLISHED;
11471 		if (tcp->tcp_active_open) {
11472 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11473 				freemsg(mp);
11474 				tcp->tcp_state = TCPS_SYN_RCVD;
11475 				return;
11476 			}
11477 			/*
11478 			 * Don't fuse the loopback endpoints for
11479 			 * simultaneous active opens.
11480 			 */
11481 			if (tcp->tcp_loopback) {
11482 				TCP_STAT(tcps, tcp_fusion_unfusable);
11483 				tcp->tcp_unfusable = B_TRUE;
11484 			}
11485 		}
11486 
11487 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11488 		bytes_acked--;
11489 		/* SYN was acked - making progress */
11490 		tcp->tcp_ip_forward_progress = B_TRUE;
11491 
11492 		/*
11493 		 * If SYN was retransmitted, need to reset all
11494 		 * retransmission info as this segment will be
11495 		 * treated as a dup ACK.
11496 		 */
11497 		if (tcp->tcp_rexmit) {
11498 			tcp->tcp_rexmit = B_FALSE;
11499 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11500 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11501 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11502 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11503 			tcp->tcp_ms_we_have_waited = 0;
11504 			tcp->tcp_cwnd = mss;
11505 		}
11506 
11507 		/*
11508 		 * We set the send window to zero here.
11509 		 * This is needed if there is data to be
11510 		 * processed already on the queue.
11511 		 * Later (at swnd_update label), the
11512 		 * "new_swnd > tcp_swnd" condition is satisfied
11513 		 * the XMIT_NEEDED flag is set in the current
11514 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11515 		 * called if there is already data on queue in
11516 		 * this state.
11517 		 */
11518 		tcp->tcp_swnd = 0;
11519 
11520 		if (new_swnd > tcp->tcp_max_swnd)
11521 			tcp->tcp_max_swnd = new_swnd;
11522 		tcp->tcp_swl1 = seg_seq;
11523 		tcp->tcp_swl2 = seg_ack;
11524 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11525 
11526 		/* Fuse when both sides are in ESTABLISHED state */
11527 		if (tcp->tcp_loopback && do_tcp_fusion)
11528 			tcp_fuse(tcp, iphdr, tcpha);
11529 
11530 	}
11531 	/* This code follows 4.4BSD-Lite2 mostly. */
11532 	if (bytes_acked < 0)
11533 		goto est;
11534 
11535 	/*
11536 	 * If TCP is ECN capable and the congestion experience bit is
11537 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11538 	 * done once per window (or more loosely, per RTT).
11539 	 */
11540 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11541 		tcp->tcp_cwr = B_FALSE;
11542 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11543 		if (!tcp->tcp_cwr) {
11544 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11545 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11546 			tcp->tcp_cwnd = npkt * mss;
11547 			/*
11548 			 * If the cwnd is 0, use the timer to clock out
11549 			 * new segments.  This is required by the ECN spec.
11550 			 */
11551 			if (npkt == 0) {
11552 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11553 				/*
11554 				 * This makes sure that when the ACK comes
11555 				 * back, we will increase tcp_cwnd by 1 MSS.
11556 				 */
11557 				tcp->tcp_cwnd_cnt = 0;
11558 			}
11559 			tcp->tcp_cwr = B_TRUE;
11560 			/*
11561 			 * This marks the end of the current window of in
11562 			 * flight data.  That is why we don't use
11563 			 * tcp_suna + tcp_swnd.  Only data in flight can
11564 			 * provide ECN info.
11565 			 */
11566 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11567 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11568 		}
11569 	}
11570 
11571 	mp1 = tcp->tcp_xmit_head;
11572 	if (bytes_acked == 0) {
11573 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11574 			int dupack_cnt;
11575 
11576 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11577 			/*
11578 			 * Fast retransmit.  When we have seen exactly three
11579 			 * identical ACKs while we have unacked data
11580 			 * outstanding we take it as a hint that our peer
11581 			 * dropped something.
11582 			 *
11583 			 * If TCP is retransmitting, don't do fast retransmit.
11584 			 */
11585 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11586 			    ! tcp->tcp_rexmit) {
11587 				/* Do Limited Transmit */
11588 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11589 				    tcps->tcps_dupack_fast_retransmit) {
11590 					/*
11591 					 * RFC 3042
11592 					 *
11593 					 * What we need to do is temporarily
11594 					 * increase tcp_cwnd so that new
11595 					 * data can be sent if it is allowed
11596 					 * by the receive window (tcp_rwnd).
11597 					 * tcp_wput_data() will take care of
11598 					 * the rest.
11599 					 *
11600 					 * If the connection is SACK capable,
11601 					 * only do limited xmit when there
11602 					 * is SACK info.
11603 					 *
11604 					 * Note how tcp_cwnd is incremented.
11605 					 * The first dup ACK will increase
11606 					 * it by 1 MSS.  The second dup ACK
11607 					 * will increase it by 2 MSS.  This
11608 					 * means that only 1 new segment will
11609 					 * be sent for each dup ACK.
11610 					 */
11611 					if (tcp->tcp_unsent > 0 &&
11612 					    (!tcp->tcp_snd_sack_ok ||
11613 					    (tcp->tcp_snd_sack_ok &&
11614 					    tcp->tcp_notsack_list != NULL))) {
11615 						tcp->tcp_cwnd += mss <<
11616 						    (tcp->tcp_dupack_cnt - 1);
11617 						flags |= TH_LIMIT_XMIT;
11618 					}
11619 				} else if (dupack_cnt ==
11620 				    tcps->tcps_dupack_fast_retransmit) {
11621 
11622 				/*
11623 				 * If we have reduced tcp_ssthresh
11624 				 * because of ECN, do not reduce it again
11625 				 * unless it is already one window of data
11626 				 * away.  After one window of data, tcp_cwr
11627 				 * should then be cleared.  Note that
11628 				 * for non ECN capable connection, tcp_cwr
11629 				 * should always be false.
11630 				 *
11631 				 * Adjust cwnd since the duplicate
11632 				 * ack indicates that a packet was
11633 				 * dropped (due to congestion.)
11634 				 */
11635 				if (!tcp->tcp_cwr) {
11636 					npkt = ((tcp->tcp_snxt -
11637 					    tcp->tcp_suna) >> 1) / mss;
11638 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11639 					    mss;
11640 					tcp->tcp_cwnd = (npkt +
11641 					    tcp->tcp_dupack_cnt) * mss;
11642 				}
11643 				if (tcp->tcp_ecn_ok) {
11644 					tcp->tcp_cwr = B_TRUE;
11645 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11646 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11647 				}
11648 
11649 				/*
11650 				 * We do Hoe's algorithm.  Refer to her
11651 				 * paper "Improving the Start-up Behavior
11652 				 * of a Congestion Control Scheme for TCP,"
11653 				 * appeared in SIGCOMM'96.
11654 				 *
11655 				 * Save highest seq no we have sent so far.
11656 				 * Be careful about the invisible FIN byte.
11657 				 */
11658 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11659 				    (tcp->tcp_unsent == 0)) {
11660 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11661 				} else {
11662 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11663 				}
11664 
11665 				/*
11666 				 * Do not allow bursty traffic during.
11667 				 * fast recovery.  Refer to Fall and Floyd's
11668 				 * paper "Simulation-based Comparisons of
11669 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11670 				 * This is a best current practise.
11671 				 */
11672 				tcp->tcp_snd_burst = TCP_CWND_SS;
11673 
11674 				/*
11675 				 * For SACK:
11676 				 * Calculate tcp_pipe, which is the
11677 				 * estimated number of bytes in
11678 				 * network.
11679 				 *
11680 				 * tcp_fack is the highest sack'ed seq num
11681 				 * TCP has received.
11682 				 *
11683 				 * tcp_pipe is explained in the above quoted
11684 				 * Fall and Floyd's paper.  tcp_fack is
11685 				 * explained in Mathis and Mahdavi's
11686 				 * "Forward Acknowledgment: Refining TCP
11687 				 * Congestion Control" in SIGCOMM '96.
11688 				 */
11689 				if (tcp->tcp_snd_sack_ok) {
11690 					ASSERT(tcp->tcp_sack_info != NULL);
11691 					if (tcp->tcp_notsack_list != NULL) {
11692 						tcp->tcp_pipe = tcp->tcp_snxt -
11693 						    tcp->tcp_fack;
11694 						tcp->tcp_sack_snxt = seg_ack;
11695 						flags |= TH_NEED_SACK_REXMIT;
11696 					} else {
11697 						/*
11698 						 * Always initialize tcp_pipe
11699 						 * even though we don't have
11700 						 * any SACK info.  If later
11701 						 * we get SACK info and
11702 						 * tcp_pipe is not initialized,
11703 						 * funny things will happen.
11704 						 */
11705 						tcp->tcp_pipe =
11706 						    tcp->tcp_cwnd_ssthresh;
11707 					}
11708 				} else {
11709 					flags |= TH_REXMIT_NEEDED;
11710 				} /* tcp_snd_sack_ok */
11711 
11712 				} else {
11713 					/*
11714 					 * Here we perform congestion
11715 					 * avoidance, but NOT slow start.
11716 					 * This is known as the Fast
11717 					 * Recovery Algorithm.
11718 					 */
11719 					if (tcp->tcp_snd_sack_ok &&
11720 					    tcp->tcp_notsack_list != NULL) {
11721 						flags |= TH_NEED_SACK_REXMIT;
11722 						tcp->tcp_pipe -= mss;
11723 						if (tcp->tcp_pipe < 0)
11724 							tcp->tcp_pipe = 0;
11725 					} else {
11726 					/*
11727 					 * We know that one more packet has
11728 					 * left the pipe thus we can update
11729 					 * cwnd.
11730 					 */
11731 					cwnd = tcp->tcp_cwnd + mss;
11732 					if (cwnd > tcp->tcp_cwnd_max)
11733 						cwnd = tcp->tcp_cwnd_max;
11734 					tcp->tcp_cwnd = cwnd;
11735 					if (tcp->tcp_unsent > 0)
11736 						flags |= TH_XMIT_NEEDED;
11737 					}
11738 				}
11739 			}
11740 		} else if (tcp->tcp_zero_win_probe) {
11741 			/*
11742 			 * If the window has opened, need to arrange
11743 			 * to send additional data.
11744 			 */
11745 			if (new_swnd != 0) {
11746 				/* tcp_suna != tcp_snxt */
11747 				/* Packet contains a window update */
11748 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11749 				tcp->tcp_zero_win_probe = 0;
11750 				tcp->tcp_timer_backoff = 0;
11751 				tcp->tcp_ms_we_have_waited = 0;
11752 
11753 				/*
11754 				 * Transmit starting with tcp_suna since
11755 				 * the one byte probe is not ack'ed.
11756 				 * If TCP has sent more than one identical
11757 				 * probe, tcp_rexmit will be set.  That means
11758 				 * tcp_ss_rexmit() will send out the one
11759 				 * byte along with new data.  Otherwise,
11760 				 * fake the retransmission.
11761 				 */
11762 				flags |= TH_XMIT_NEEDED;
11763 				if (!tcp->tcp_rexmit) {
11764 					tcp->tcp_rexmit = B_TRUE;
11765 					tcp->tcp_dupack_cnt = 0;
11766 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11767 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11768 				}
11769 			}
11770 		}
11771 		goto swnd_update;
11772 	}
11773 
11774 	/*
11775 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11776 	 * If the ACK value acks something that we have not yet sent, it might
11777 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11778 	 * other side.
11779 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11780 	 * state is handled above, so we can always just drop the segment and
11781 	 * send an ACK here.
11782 	 *
11783 	 * In the case where the peer shrinks the window, we see the new window
11784 	 * update, but all the data sent previously is queued up by the peer.
11785 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11786 	 * number, which was already sent, and within window, is recorded.
11787 	 * tcp_snxt is then updated.
11788 	 *
11789 	 * If the window has previously shrunk, and an ACK for data not yet
11790 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11791 	 * the ACK is for data within the window at the time the window was
11792 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11793 	 * the sequence number ACK'ed.
11794 	 *
11795 	 * If the ACK covers all the data sent at the time the window was
11796 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11797 	 *
11798 	 * Should we send ACKs in response to ACK only segments?
11799 	 */
11800 
11801 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11802 		if ((tcp->tcp_is_wnd_shrnk) &&
11803 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11804 			uint32_t data_acked_ahead_snxt;
11805 
11806 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11807 			tcp_update_xmit_tail(tcp, seg_ack);
11808 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11809 		} else {
11810 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11811 			/* drop the received segment */
11812 			freemsg(mp);
11813 
11814 			/*
11815 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11816 			 * greater than 0, check if the number of such
11817 			 * bogus ACks is greater than that count.  If yes,
11818 			 * don't send back any ACK.  This prevents TCP from
11819 			 * getting into an ACK storm if somehow an attacker
11820 			 * successfully spoofs an acceptable segment to our
11821 			 * peer.  If this continues (count > 2 X threshold),
11822 			 * we should abort this connection.
11823 			 */
11824 			if (tcp_drop_ack_unsent_cnt > 0 &&
11825 			    ++tcp->tcp_in_ack_unsent >
11826 			    tcp_drop_ack_unsent_cnt) {
11827 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11828 				if (tcp->tcp_in_ack_unsent > 2 *
11829 				    tcp_drop_ack_unsent_cnt) {
11830 					(void) tcp_clean_death(tcp, EPROTO, 20);
11831 				}
11832 				return;
11833 			}
11834 			mp = tcp_ack_mp(tcp);
11835 			if (mp != NULL) {
11836 				BUMP_LOCAL(tcp->tcp_obsegs);
11837 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11838 				tcp_send_data(tcp, mp);
11839 			}
11840 			return;
11841 		}
11842 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11843 	    tcp->tcp_snxt_shrunk)) {
11844 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11845 	}
11846 
11847 	/*
11848 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11849 	 * blocks that are covered by this ACK.
11850 	 */
11851 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11852 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11853 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11854 	}
11855 
11856 	/*
11857 	 * If we got an ACK after fast retransmit, check to see
11858 	 * if it is a partial ACK.  If it is not and the congestion
11859 	 * window was inflated to account for the other side's
11860 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11861 	 */
11862 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11863 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11864 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11865 			tcp->tcp_dupack_cnt = 0;
11866 			/*
11867 			 * Restore the orig tcp_cwnd_ssthresh after
11868 			 * fast retransmit phase.
11869 			 */
11870 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11871 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11872 			}
11873 			tcp->tcp_rexmit_max = seg_ack;
11874 			tcp->tcp_cwnd_cnt = 0;
11875 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11876 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11877 
11878 			/*
11879 			 * Remove all notsack info to avoid confusion with
11880 			 * the next fast retrasnmit/recovery phase.
11881 			 */
11882 			if (tcp->tcp_snd_sack_ok &&
11883 			    tcp->tcp_notsack_list != NULL) {
11884 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11885 				    tcp);
11886 			}
11887 		} else {
11888 			if (tcp->tcp_snd_sack_ok &&
11889 			    tcp->tcp_notsack_list != NULL) {
11890 				flags |= TH_NEED_SACK_REXMIT;
11891 				tcp->tcp_pipe -= mss;
11892 				if (tcp->tcp_pipe < 0)
11893 					tcp->tcp_pipe = 0;
11894 			} else {
11895 				/*
11896 				 * Hoe's algorithm:
11897 				 *
11898 				 * Retransmit the unack'ed segment and
11899 				 * restart fast recovery.  Note that we
11900 				 * need to scale back tcp_cwnd to the
11901 				 * original value when we started fast
11902 				 * recovery.  This is to prevent overly
11903 				 * aggressive behaviour in sending new
11904 				 * segments.
11905 				 */
11906 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11907 				    tcps->tcps_dupack_fast_retransmit * mss;
11908 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11909 				flags |= TH_REXMIT_NEEDED;
11910 			}
11911 		}
11912 	} else {
11913 		tcp->tcp_dupack_cnt = 0;
11914 		if (tcp->tcp_rexmit) {
11915 			/*
11916 			 * TCP is retranmitting.  If the ACK ack's all
11917 			 * outstanding data, update tcp_rexmit_max and
11918 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11919 			 * to the correct value.
11920 			 *
11921 			 * Note that SEQ_LEQ() is used.  This is to avoid
11922 			 * unnecessary fast retransmit caused by dup ACKs
11923 			 * received when TCP does slow start retransmission
11924 			 * after a time out.  During this phase, TCP may
11925 			 * send out segments which are already received.
11926 			 * This causes dup ACKs to be sent back.
11927 			 */
11928 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11929 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11930 					tcp->tcp_rexmit_nxt = seg_ack;
11931 				}
11932 				if (seg_ack != tcp->tcp_rexmit_max) {
11933 					flags |= TH_XMIT_NEEDED;
11934 				}
11935 			} else {
11936 				tcp->tcp_rexmit = B_FALSE;
11937 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11938 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11939 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11940 			}
11941 			tcp->tcp_ms_we_have_waited = 0;
11942 		}
11943 	}
11944 
11945 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11946 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11947 	tcp->tcp_suna = seg_ack;
11948 	if (tcp->tcp_zero_win_probe != 0) {
11949 		tcp->tcp_zero_win_probe = 0;
11950 		tcp->tcp_timer_backoff = 0;
11951 	}
11952 
11953 	/*
11954 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11955 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11956 	 * will not reach here.
11957 	 */
11958 	if (mp1 == NULL) {
11959 		goto fin_acked;
11960 	}
11961 
11962 	/*
11963 	 * Update the congestion window.
11964 	 *
11965 	 * If TCP is not ECN capable or TCP is ECN capable but the
11966 	 * congestion experience bit is not set, increase the tcp_cwnd as
11967 	 * usual.
11968 	 */
11969 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11970 		cwnd = tcp->tcp_cwnd;
11971 		add = mss;
11972 
11973 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11974 			/*
11975 			 * This is to prevent an increase of less than 1 MSS of
11976 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11977 			 * may send out tinygrams in order to preserve mblk
11978 			 * boundaries.
11979 			 *
11980 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11981 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11982 			 * increased by 1 MSS for every RTTs.
11983 			 */
11984 			if (tcp->tcp_cwnd_cnt <= 0) {
11985 				tcp->tcp_cwnd_cnt = cwnd + add;
11986 			} else {
11987 				tcp->tcp_cwnd_cnt -= add;
11988 				add = 0;
11989 			}
11990 		}
11991 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11992 	}
11993 
11994 	/* See if the latest urgent data has been acknowledged */
11995 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11996 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11997 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11998 
11999 	/* Can we update the RTT estimates? */
12000 	if (tcp->tcp_snd_ts_ok) {
12001 		/* Ignore zero timestamp echo-reply. */
12002 		if (tcpopt.tcp_opt_ts_ecr != 0) {
12003 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12004 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
12005 		}
12006 
12007 		/* If needed, restart the timer. */
12008 		if (tcp->tcp_set_timer == 1) {
12009 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12010 			tcp->tcp_set_timer = 0;
12011 		}
12012 		/*
12013 		 * Update tcp_csuna in case the other side stops sending
12014 		 * us timestamps.
12015 		 */
12016 		tcp->tcp_csuna = tcp->tcp_snxt;
12017 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
12018 		/*
12019 		 * An ACK sequence we haven't seen before, so get the RTT
12020 		 * and update the RTO. But first check if the timestamp is
12021 		 * valid to use.
12022 		 */
12023 		if ((mp1->b_next != NULL) &&
12024 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
12025 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12026 			    (int32_t)(intptr_t)mp1->b_prev);
12027 		else
12028 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12029 
12030 		/* Remeber the last sequence to be ACKed */
12031 		tcp->tcp_csuna = seg_ack;
12032 		if (tcp->tcp_set_timer == 1) {
12033 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12034 			tcp->tcp_set_timer = 0;
12035 		}
12036 	} else {
12037 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12038 	}
12039 
12040 	/* Eat acknowledged bytes off the xmit queue. */
12041 	for (;;) {
12042 		mblk_t	*mp2;
12043 		uchar_t	*wptr;
12044 
12045 		wptr = mp1->b_wptr;
12046 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
12047 		bytes_acked -= (int)(wptr - mp1->b_rptr);
12048 		if (bytes_acked < 0) {
12049 			mp1->b_rptr = wptr + bytes_acked;
12050 			/*
12051 			 * Set a new timestamp if all the bytes timed by the
12052 			 * old timestamp have been ack'ed.
12053 			 */
12054 			if (SEQ_GT(seg_ack,
12055 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
12056 				mp1->b_prev =
12057 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
12058 				mp1->b_next = NULL;
12059 			}
12060 			break;
12061 		}
12062 		mp1->b_next = NULL;
12063 		mp1->b_prev = NULL;
12064 		mp2 = mp1;
12065 		mp1 = mp1->b_cont;
12066 
12067 		/*
12068 		 * This notification is required for some zero-copy
12069 		 * clients to maintain a copy semantic. After the data
12070 		 * is ack'ed, client is safe to modify or reuse the buffer.
12071 		 */
12072 		if (tcp->tcp_snd_zcopy_aware &&
12073 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12074 			tcp_zcopy_notify(tcp);
12075 		freeb(mp2);
12076 		if (bytes_acked == 0) {
12077 			if (mp1 == NULL) {
12078 				/* Everything is ack'ed, clear the tail. */
12079 				tcp->tcp_xmit_tail = NULL;
12080 				/*
12081 				 * Cancel the timer unless we are still
12082 				 * waiting for an ACK for the FIN packet.
12083 				 */
12084 				if (tcp->tcp_timer_tid != 0 &&
12085 				    tcp->tcp_snxt == tcp->tcp_suna) {
12086 					(void) TCP_TIMER_CANCEL(tcp,
12087 					    tcp->tcp_timer_tid);
12088 					tcp->tcp_timer_tid = 0;
12089 				}
12090 				goto pre_swnd_update;
12091 			}
12092 			if (mp2 != tcp->tcp_xmit_tail)
12093 				break;
12094 			tcp->tcp_xmit_tail = mp1;
12095 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12096 			    (uintptr_t)INT_MAX);
12097 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12098 			    mp1->b_rptr);
12099 			break;
12100 		}
12101 		if (mp1 == NULL) {
12102 			/*
12103 			 * More was acked but there is nothing more
12104 			 * outstanding.  This means that the FIN was
12105 			 * just acked or that we're talking to a clown.
12106 			 */
12107 fin_acked:
12108 			ASSERT(tcp->tcp_fin_sent);
12109 			tcp->tcp_xmit_tail = NULL;
12110 			if (tcp->tcp_fin_sent) {
12111 				/* FIN was acked - making progress */
12112 				if (!tcp->tcp_fin_acked)
12113 					tcp->tcp_ip_forward_progress = B_TRUE;
12114 				tcp->tcp_fin_acked = B_TRUE;
12115 				if (tcp->tcp_linger_tid != 0 &&
12116 				    TCP_TIMER_CANCEL(tcp,
12117 				    tcp->tcp_linger_tid) >= 0) {
12118 					tcp_stop_lingering(tcp);
12119 					freemsg(mp);
12120 					mp = NULL;
12121 				}
12122 			} else {
12123 				/*
12124 				 * We should never get here because
12125 				 * we have already checked that the
12126 				 * number of bytes ack'ed should be
12127 				 * smaller than or equal to what we
12128 				 * have sent so far (it is the
12129 				 * acceptability check of the ACK).
12130 				 * We can only get here if the send
12131 				 * queue is corrupted.
12132 				 *
12133 				 * Terminate the connection and
12134 				 * panic the system.  It is better
12135 				 * for us to panic instead of
12136 				 * continuing to avoid other disaster.
12137 				 */
12138 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12139 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12140 				panic("Memory corruption "
12141 				    "detected for connection %s.",
12142 				    tcp_display(tcp, NULL,
12143 				    DISP_ADDR_AND_PORT));
12144 				/*NOTREACHED*/
12145 			}
12146 			goto pre_swnd_update;
12147 		}
12148 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12149 	}
12150 	if (tcp->tcp_unsent) {
12151 		flags |= TH_XMIT_NEEDED;
12152 	}
12153 pre_swnd_update:
12154 	tcp->tcp_xmit_head = mp1;
12155 swnd_update:
12156 	/*
12157 	 * The following check is different from most other implementations.
12158 	 * For bi-directional transfer, when segments are dropped, the
12159 	 * "normal" check will not accept a window update in those
12160 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12161 	 * segments which are outside receiver's window.  As TCP accepts
12162 	 * the ack in those retransmitted segments, if the window update in
12163 	 * the same segment is not accepted, TCP will incorrectly calculates
12164 	 * that it can send more segments.  This can create a deadlock
12165 	 * with the receiver if its window becomes zero.
12166 	 */
12167 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12168 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12169 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12170 		/*
12171 		 * The criteria for update is:
12172 		 *
12173 		 * 1. the segment acknowledges some data.  Or
12174 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12175 		 * 3. the segment is not old and the advertised window is
12176 		 * larger than the previous advertised window.
12177 		 */
12178 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12179 			flags |= TH_XMIT_NEEDED;
12180 		tcp->tcp_swnd = new_swnd;
12181 		if (new_swnd > tcp->tcp_max_swnd)
12182 			tcp->tcp_max_swnd = new_swnd;
12183 		tcp->tcp_swl1 = seg_seq;
12184 		tcp->tcp_swl2 = seg_ack;
12185 	}
12186 est:
12187 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12188 
12189 		switch (tcp->tcp_state) {
12190 		case TCPS_FIN_WAIT_1:
12191 			if (tcp->tcp_fin_acked) {
12192 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12193 				/*
12194 				 * We implement the non-standard BSD/SunOS
12195 				 * FIN_WAIT_2 flushing algorithm.
12196 				 * If there is no user attached to this
12197 				 * TCP endpoint, then this TCP struct
12198 				 * could hang around forever in FIN_WAIT_2
12199 				 * state if the peer forgets to send us
12200 				 * a FIN.  To prevent this, we wait only
12201 				 * 2*MSL (a convenient time value) for
12202 				 * the FIN to arrive.  If it doesn't show up,
12203 				 * we flush the TCP endpoint.  This algorithm,
12204 				 * though a violation of RFC-793, has worked
12205 				 * for over 10 years in BSD systems.
12206 				 * Note: SunOS 4.x waits 675 seconds before
12207 				 * flushing the FIN_WAIT_2 connection.
12208 				 */
12209 				TCP_TIMER_RESTART(tcp,
12210 				    tcps->tcps_fin_wait_2_flush_interval);
12211 			}
12212 			break;
12213 		case TCPS_FIN_WAIT_2:
12214 			break;	/* Shutdown hook? */
12215 		case TCPS_LAST_ACK:
12216 			freemsg(mp);
12217 			if (tcp->tcp_fin_acked) {
12218 				(void) tcp_clean_death(tcp, 0, 19);
12219 				return;
12220 			}
12221 			goto xmit_check;
12222 		case TCPS_CLOSING:
12223 			if (tcp->tcp_fin_acked)
12224 				SET_TIME_WAIT(tcps, tcp, connp);
12225 			/*FALLTHRU*/
12226 		case TCPS_CLOSE_WAIT:
12227 			freemsg(mp);
12228 			goto xmit_check;
12229 		default:
12230 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12231 			break;
12232 		}
12233 	}
12234 	if (flags & TH_FIN) {
12235 		/* Make sure we ack the fin */
12236 		flags |= TH_ACK_NEEDED;
12237 		if (!tcp->tcp_fin_rcvd) {
12238 			tcp->tcp_fin_rcvd = B_TRUE;
12239 			tcp->tcp_rnxt++;
12240 			tcpha = tcp->tcp_tcpha;
12241 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12242 
12243 			/*
12244 			 * Generate the ordrel_ind at the end unless we
12245 			 * are an eager guy.
12246 			 * In the eager case tcp_rsrv will do this when run
12247 			 * after tcp_accept is done.
12248 			 */
12249 			if (tcp->tcp_listener == NULL &&
12250 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12251 				flags |= TH_ORDREL_NEEDED;
12252 			switch (tcp->tcp_state) {
12253 			case TCPS_SYN_RCVD:
12254 			case TCPS_ESTABLISHED:
12255 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12256 				/* Keepalive? */
12257 				break;
12258 			case TCPS_FIN_WAIT_1:
12259 				if (!tcp->tcp_fin_acked) {
12260 					tcp->tcp_state = TCPS_CLOSING;
12261 					break;
12262 				}
12263 				/* FALLTHRU */
12264 			case TCPS_FIN_WAIT_2:
12265 				SET_TIME_WAIT(tcps, tcp, connp);
12266 				if (seg_len) {
12267 					/*
12268 					 * implies data piggybacked on FIN.
12269 					 * break to handle data.
12270 					 */
12271 					break;
12272 				}
12273 				freemsg(mp);
12274 				goto ack_check;
12275 			}
12276 		}
12277 	}
12278 	if (mp == NULL)
12279 		goto xmit_check;
12280 	if (seg_len == 0) {
12281 		freemsg(mp);
12282 		goto xmit_check;
12283 	}
12284 	if (mp->b_rptr == mp->b_wptr) {
12285 		/*
12286 		 * The header has been consumed, so we remove the
12287 		 * zero-length mblk here.
12288 		 */
12289 		mp1 = mp;
12290 		mp = mp->b_cont;
12291 		freeb(mp1);
12292 	}
12293 update_ack:
12294 	tcpha = tcp->tcp_tcpha;
12295 	tcp->tcp_rack_cnt++;
12296 	{
12297 		uint32_t cur_max;
12298 
12299 		cur_max = tcp->tcp_rack_cur_max;
12300 		if (tcp->tcp_rack_cnt >= cur_max) {
12301 			/*
12302 			 * We have more unacked data than we should - send
12303 			 * an ACK now.
12304 			 */
12305 			flags |= TH_ACK_NEEDED;
12306 			cur_max++;
12307 			if (cur_max > tcp->tcp_rack_abs_max)
12308 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12309 			else
12310 				tcp->tcp_rack_cur_max = cur_max;
12311 		} else if (TCP_IS_DETACHED(tcp)) {
12312 			/* We don't have an ACK timer for detached TCP. */
12313 			flags |= TH_ACK_NEEDED;
12314 		} else if (seg_len < mss) {
12315 			/*
12316 			 * If we get a segment that is less than an mss, and we
12317 			 * already have unacknowledged data, and the amount
12318 			 * unacknowledged is not a multiple of mss, then we
12319 			 * better generate an ACK now.  Otherwise, this may be
12320 			 * the tail piece of a transaction, and we would rather
12321 			 * wait for the response.
12322 			 */
12323 			uint32_t udif;
12324 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12325 			    (uintptr_t)INT_MAX);
12326 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12327 			if (udif && (udif % mss))
12328 				flags |= TH_ACK_NEEDED;
12329 			else
12330 				flags |= TH_ACK_TIMER_NEEDED;
12331 		} else {
12332 			/* Start delayed ack timer */
12333 			flags |= TH_ACK_TIMER_NEEDED;
12334 		}
12335 	}
12336 	tcp->tcp_rnxt += seg_len;
12337 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12338 
12339 	if (mp == NULL)
12340 		goto xmit_check;
12341 
12342 	/* Update SACK list */
12343 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12344 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12345 		    &(tcp->tcp_num_sack_blk));
12346 	}
12347 
12348 	if (tcp->tcp_urp_mp) {
12349 		tcp->tcp_urp_mp->b_cont = mp;
12350 		mp = tcp->tcp_urp_mp;
12351 		tcp->tcp_urp_mp = NULL;
12352 		/* Ready for a new signal. */
12353 		tcp->tcp_urp_last_valid = B_FALSE;
12354 #ifdef DEBUG
12355 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12356 		    "tcp_rput: sending exdata_ind %s",
12357 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12358 #endif /* DEBUG */
12359 	}
12360 
12361 	/*
12362 	 * Check for ancillary data changes compared to last segment.
12363 	 */
12364 	if (connp->conn_recv_ancillary.crb_all != 0) {
12365 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12366 		if (mp == NULL)
12367 			return;
12368 	}
12369 
12370 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12371 		/*
12372 		 * Side queue inbound data until the accept happens.
12373 		 * tcp_accept/tcp_rput drains this when the accept happens.
12374 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12375 		 * T_EXDATA_IND) it is queued on b_next.
12376 		 * XXX Make urgent data use this. Requires:
12377 		 *	Removing tcp_listener check for TH_URG
12378 		 *	Making M_PCPROTO and MARK messages skip the eager case
12379 		 */
12380 
12381 		if (tcp->tcp_kssl_pending) {
12382 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12383 			    mblk_t *, mp);
12384 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12385 		} else {
12386 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12387 		}
12388 	} else if (IPCL_IS_NONSTR(connp)) {
12389 		/*
12390 		 * Non-STREAMS socket
12391 		 *
12392 		 * Note that no KSSL processing is done here, because
12393 		 * KSSL is not supported for non-STREAMS sockets.
12394 		 */
12395 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12396 		int error;
12397 
12398 		if ((*connp->conn_upcalls->su_recv)(
12399 		    connp->conn_upper_handle,
12400 		    mp, seg_len, 0, &error, &push) <= 0) {
12401 			/*
12402 			 * We should never be in middle of a
12403 			 * fallback, the squeue guarantees that.
12404 			 */
12405 			ASSERT(error != EOPNOTSUPP);
12406 			if (error == ENOSPC)
12407 				tcp->tcp_rwnd -= seg_len;
12408 		} else if (push) {
12409 			/* PUSH bit set and sockfs is not flow controlled */
12410 			flags |= tcp_rwnd_reopen(tcp);
12411 		}
12412 	} else {
12413 		/* STREAMS socket */
12414 		if (mp->b_datap->db_type != M_DATA ||
12415 		    (flags & TH_MARKNEXT_NEEDED)) {
12416 			if (tcp->tcp_rcv_list != NULL) {
12417 				flags |= tcp_rcv_drain(tcp);
12418 			}
12419 			ASSERT(tcp->tcp_rcv_list == NULL ||
12420 			    tcp->tcp_fused_sigurg);
12421 
12422 			if (flags & TH_MARKNEXT_NEEDED) {
12423 #ifdef DEBUG
12424 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12425 				    "tcp_rput: sending MSGMARKNEXT %s",
12426 				    tcp_display(tcp, NULL,
12427 				    DISP_PORT_ONLY));
12428 #endif /* DEBUG */
12429 				mp->b_flag |= MSGMARKNEXT;
12430 				flags &= ~TH_MARKNEXT_NEEDED;
12431 			}
12432 
12433 			/* Does this need SSL processing first? */
12434 			if ((tcp->tcp_kssl_ctx != NULL) &&
12435 			    (DB_TYPE(mp) == M_DATA)) {
12436 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12437 				    mblk_t *, mp);
12438 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12439 			} else {
12440 				if (is_system_labeled())
12441 					tcp_setcred_data(mp, ira);
12442 
12443 				putnext(connp->conn_rq, mp);
12444 				if (!canputnext(connp->conn_rq))
12445 					tcp->tcp_rwnd -= seg_len;
12446 			}
12447 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12448 		    (DB_TYPE(mp) == M_DATA)) {
12449 			/* Does this need SSL processing first? */
12450 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12451 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12452 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12453 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12454 			if (tcp->tcp_rcv_list != NULL) {
12455 				/*
12456 				 * Enqueue the new segment first and then
12457 				 * call tcp_rcv_drain() to send all data
12458 				 * up.  The other way to do this is to
12459 				 * send all queued data up and then call
12460 				 * putnext() to send the new segment up.
12461 				 * This way can remove the else part later
12462 				 * on.
12463 				 *
12464 				 * We don't do this to avoid one more call to
12465 				 * canputnext() as tcp_rcv_drain() needs to
12466 				 * call canputnext().
12467 				 */
12468 				tcp_rcv_enqueue(tcp, mp, seg_len,
12469 				    ira->ira_cred);
12470 				flags |= tcp_rcv_drain(tcp);
12471 			} else {
12472 				if (is_system_labeled())
12473 					tcp_setcred_data(mp, ira);
12474 
12475 				putnext(connp->conn_rq, mp);
12476 				if (!canputnext(connp->conn_rq))
12477 					tcp->tcp_rwnd -= seg_len;
12478 			}
12479 		} else {
12480 			/*
12481 			 * Enqueue all packets when processing an mblk
12482 			 * from the co queue and also enqueue normal packets.
12483 			 */
12484 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12485 		}
12486 		/*
12487 		 * Make sure the timer is running if we have data waiting
12488 		 * for a push bit. This provides resiliency against
12489 		 * implementations that do not correctly generate push bits.
12490 		 */
12491 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12492 			/*
12493 			 * The connection may be closed at this point, so don't
12494 			 * do anything for a detached tcp.
12495 			 */
12496 			if (!TCP_IS_DETACHED(tcp))
12497 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12498 				    tcp_push_timer,
12499 				    MSEC_TO_TICK(
12500 				    tcps->tcps_push_timer_interval));
12501 		}
12502 	}
12503 
12504 xmit_check:
12505 	/* Is there anything left to do? */
12506 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12507 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12508 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12509 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12510 		goto done;
12511 
12512 	/* Any transmit work to do and a non-zero window? */
12513 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12514 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12515 		if (flags & TH_REXMIT_NEEDED) {
12516 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12517 
12518 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12519 			if (snd_size > mss)
12520 				snd_size = mss;
12521 			if (snd_size > tcp->tcp_swnd)
12522 				snd_size = tcp->tcp_swnd;
12523 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12524 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12525 			    B_TRUE);
12526 
12527 			if (mp1 != NULL) {
12528 				tcp->tcp_xmit_head->b_prev =
12529 				    (mblk_t *)LBOLT_FASTPATH;
12530 				tcp->tcp_csuna = tcp->tcp_snxt;
12531 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12532 				UPDATE_MIB(&tcps->tcps_mib,
12533 				    tcpRetransBytes, snd_size);
12534 				tcp_send_data(tcp, mp1);
12535 			}
12536 		}
12537 		if (flags & TH_NEED_SACK_REXMIT) {
12538 			tcp_sack_rxmit(tcp, &flags);
12539 		}
12540 		/*
12541 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12542 		 * out new segment.  Note that tcp_rexmit should not be
12543 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12544 		 */
12545 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12546 			if (!tcp->tcp_rexmit) {
12547 				tcp_wput_data(tcp, NULL, B_FALSE);
12548 			} else {
12549 				tcp_ss_rexmit(tcp);
12550 			}
12551 		}
12552 		/*
12553 		 * Adjust tcp_cwnd back to normal value after sending
12554 		 * new data segments.
12555 		 */
12556 		if (flags & TH_LIMIT_XMIT) {
12557 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12558 			/*
12559 			 * This will restart the timer.  Restarting the
12560 			 * timer is used to avoid a timeout before the
12561 			 * limited transmitted segment's ACK gets back.
12562 			 */
12563 			if (tcp->tcp_xmit_head != NULL)
12564 				tcp->tcp_xmit_head->b_prev =
12565 				    (mblk_t *)LBOLT_FASTPATH;
12566 		}
12567 
12568 		/* Anything more to do? */
12569 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12570 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12571 			goto done;
12572 	}
12573 ack_check:
12574 	if (flags & TH_SEND_URP_MARK) {
12575 		ASSERT(tcp->tcp_urp_mark_mp);
12576 		ASSERT(!IPCL_IS_NONSTR(connp));
12577 		/*
12578 		 * Send up any queued data and then send the mark message
12579 		 */
12580 		if (tcp->tcp_rcv_list != NULL) {
12581 			flags |= tcp_rcv_drain(tcp);
12582 
12583 		}
12584 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12585 		mp1 = tcp->tcp_urp_mark_mp;
12586 		tcp->tcp_urp_mark_mp = NULL;
12587 		if (is_system_labeled())
12588 			tcp_setcred_data(mp1, ira);
12589 
12590 		putnext(connp->conn_rq, mp1);
12591 #ifdef DEBUG
12592 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12593 		    "tcp_rput: sending zero-length %s %s",
12594 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12595 		    "MSGNOTMARKNEXT"),
12596 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12597 #endif /* DEBUG */
12598 		flags &= ~TH_SEND_URP_MARK;
12599 	}
12600 	if (flags & TH_ACK_NEEDED) {
12601 		/*
12602 		 * Time to send an ack for some reason.
12603 		 */
12604 		mp1 = tcp_ack_mp(tcp);
12605 
12606 		if (mp1 != NULL) {
12607 			tcp_send_data(tcp, mp1);
12608 			BUMP_LOCAL(tcp->tcp_obsegs);
12609 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12610 		}
12611 		if (tcp->tcp_ack_tid != 0) {
12612 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12613 			tcp->tcp_ack_tid = 0;
12614 		}
12615 	}
12616 	if (flags & TH_ACK_TIMER_NEEDED) {
12617 		/*
12618 		 * Arrange for deferred ACK or push wait timeout.
12619 		 * Start timer if it is not already running.
12620 		 */
12621 		if (tcp->tcp_ack_tid == 0) {
12622 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12623 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12624 			    (clock_t)tcps->tcps_local_dack_interval :
12625 			    (clock_t)tcps->tcps_deferred_ack_interval));
12626 		}
12627 	}
12628 	if (flags & TH_ORDREL_NEEDED) {
12629 		/*
12630 		 * Send up the ordrel_ind unless we are an eager guy.
12631 		 * In the eager case tcp_rsrv will do this when run
12632 		 * after tcp_accept is done.
12633 		 */
12634 		ASSERT(tcp->tcp_listener == NULL);
12635 		ASSERT(!tcp->tcp_detached);
12636 
12637 		if (IPCL_IS_NONSTR(connp)) {
12638 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12639 			tcp->tcp_ordrel_done = B_TRUE;
12640 			(*connp->conn_upcalls->su_opctl)
12641 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12642 			goto done;
12643 		}
12644 
12645 		if (tcp->tcp_rcv_list != NULL) {
12646 			/*
12647 			 * Push any mblk(s) enqueued from co processing.
12648 			 */
12649 			flags |= tcp_rcv_drain(tcp);
12650 		}
12651 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12652 
12653 		mp1 = tcp->tcp_ordrel_mp;
12654 		tcp->tcp_ordrel_mp = NULL;
12655 		tcp->tcp_ordrel_done = B_TRUE;
12656 		putnext(connp->conn_rq, mp1);
12657 	}
12658 done:
12659 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12660 }
12661 
12662 /*
12663  * This routine adjusts next-to-send sequence number variables, in the
12664  * case where the reciever has shrunk it's window.
12665  */
12666 static void
12667 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12668 {
12669 	mblk_t *xmit_tail;
12670 	int32_t offset;
12671 
12672 	tcp->tcp_snxt = snxt;
12673 
12674 	/* Get the mblk, and the offset in it, as per the shrunk window */
12675 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12676 	ASSERT(xmit_tail != NULL);
12677 	tcp->tcp_xmit_tail = xmit_tail;
12678 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12679 	    xmit_tail->b_rptr - offset;
12680 }
12681 
12682 /*
12683  * This function does PAWS protection check. Returns B_TRUE if the
12684  * segment passes the PAWS test, else returns B_FALSE.
12685  */
12686 boolean_t
12687 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12688 {
12689 	uint8_t	flags;
12690 	int	options;
12691 	uint8_t *up;
12692 	conn_t	*connp = tcp->tcp_connp;
12693 
12694 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12695 	/*
12696 	 * If timestamp option is aligned nicely, get values inline,
12697 	 * otherwise call general routine to parse.  Only do that
12698 	 * if timestamp is the only option.
12699 	 */
12700 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12701 	    TCPOPT_REAL_TS_LEN &&
12702 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12703 	    TCP_MIN_HEADER_LENGTH)) &&
12704 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12705 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12706 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12707 
12708 		options = TCP_OPT_TSTAMP_PRESENT;
12709 	} else {
12710 		if (tcp->tcp_snd_sack_ok) {
12711 			tcpoptp->tcp = tcp;
12712 		} else {
12713 			tcpoptp->tcp = NULL;
12714 		}
12715 		options = tcp_parse_options(tcpha, tcpoptp);
12716 	}
12717 
12718 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12719 		/*
12720 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12721 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12722 		 */
12723 		if ((flags & TH_RST) == 0 &&
12724 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12725 		    tcp->tcp_ts_recent)) {
12726 			if (TSTMP_LT(LBOLT_FASTPATH64,
12727 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12728 				/* This segment is not acceptable. */
12729 				return (B_FALSE);
12730 			} else {
12731 				/*
12732 				 * Connection has been idle for
12733 				 * too long.  Reset the timestamp
12734 				 * and assume the segment is valid.
12735 				 */
12736 				tcp->tcp_ts_recent =
12737 				    tcpoptp->tcp_opt_ts_val;
12738 			}
12739 		}
12740 	} else {
12741 		/*
12742 		 * If we don't get a timestamp on every packet, we
12743 		 * figure we can't really trust 'em, so we stop sending
12744 		 * and parsing them.
12745 		 */
12746 		tcp->tcp_snd_ts_ok = B_FALSE;
12747 
12748 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12749 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12750 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12751 		/*
12752 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12753 		 * doing a slow start here so as to not to lose on the
12754 		 * transfer rate built up so far.
12755 		 */
12756 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12757 		if (tcp->tcp_snd_sack_ok) {
12758 			ASSERT(tcp->tcp_sack_info != NULL);
12759 			tcp->tcp_max_sack_blk = 4;
12760 		}
12761 	}
12762 	return (B_TRUE);
12763 }
12764 
12765 /*
12766  * Attach ancillary data to a received TCP segments for the
12767  * ancillary pieces requested by the application that are
12768  * different than they were in the previous data segment.
12769  *
12770  * Save the "current" values once memory allocation is ok so that
12771  * when memory allocation fails we can just wait for the next data segment.
12772  */
12773 static mblk_t *
12774 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12775     ip_recv_attr_t *ira)
12776 {
12777 	struct T_optdata_ind *todi;
12778 	int optlen;
12779 	uchar_t *optptr;
12780 	struct T_opthdr *toh;
12781 	crb_t addflag;	/* Which pieces to add */
12782 	mblk_t *mp1;
12783 	conn_t	*connp = tcp->tcp_connp;
12784 
12785 	optlen = 0;
12786 	addflag.crb_all = 0;
12787 	/* If app asked for pktinfo and the index has changed ... */
12788 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12789 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12790 		optlen += sizeof (struct T_opthdr) +
12791 		    sizeof (struct in6_pktinfo);
12792 		addflag.crb_ip_recvpktinfo = 1;
12793 	}
12794 	/* If app asked for hoplimit and it has changed ... */
12795 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12796 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12797 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12798 		addflag.crb_ipv6_recvhoplimit = 1;
12799 	}
12800 	/* If app asked for tclass and it has changed ... */
12801 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12802 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12803 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12804 		addflag.crb_ipv6_recvtclass = 1;
12805 	}
12806 	/*
12807 	 * If app asked for hopbyhop headers and it has changed ...
12808 	 * For security labels, note that (1) security labels can't change on
12809 	 * a connected socket at all, (2) we're connected to at most one peer,
12810 	 * (3) if anything changes, then it must be some other extra option.
12811 	 */
12812 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12813 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12814 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12815 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12816 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12817 		addflag.crb_ipv6_recvhopopts = 1;
12818 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12819 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12820 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12821 			return (mp);
12822 	}
12823 	/* If app asked for dst headers before routing headers ... */
12824 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12825 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12826 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12827 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12828 		optlen += sizeof (struct T_opthdr) +
12829 		    ipp->ipp_rthdrdstoptslen;
12830 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12831 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12832 		    &tcp->tcp_rthdrdstoptslen,
12833 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12834 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12835 			return (mp);
12836 	}
12837 	/* If app asked for routing headers and it has changed ... */
12838 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12839 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12840 	    (ipp->ipp_fields & IPPF_RTHDR),
12841 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12842 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12843 		addflag.crb_ipv6_recvrthdr = 1;
12844 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12845 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12846 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12847 			return (mp);
12848 	}
12849 	/* If app asked for dest headers and it has changed ... */
12850 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12851 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12852 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12853 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12854 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12855 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12856 		addflag.crb_ipv6_recvdstopts = 1;
12857 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12858 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12859 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12860 			return (mp);
12861 	}
12862 
12863 	if (optlen == 0) {
12864 		/* Nothing to add */
12865 		return (mp);
12866 	}
12867 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12868 	if (mp1 == NULL) {
12869 		/*
12870 		 * Defer sending ancillary data until the next TCP segment
12871 		 * arrives.
12872 		 */
12873 		return (mp);
12874 	}
12875 	mp1->b_cont = mp;
12876 	mp = mp1;
12877 	mp->b_wptr += sizeof (*todi) + optlen;
12878 	mp->b_datap->db_type = M_PROTO;
12879 	todi = (struct T_optdata_ind *)mp->b_rptr;
12880 	todi->PRIM_type = T_OPTDATA_IND;
12881 	todi->DATA_flag = 1;	/* MORE data */
12882 	todi->OPT_length = optlen;
12883 	todi->OPT_offset = sizeof (*todi);
12884 	optptr = (uchar_t *)&todi[1];
12885 	/*
12886 	 * If app asked for pktinfo and the index has changed ...
12887 	 * Note that the local address never changes for the connection.
12888 	 */
12889 	if (addflag.crb_ip_recvpktinfo) {
12890 		struct in6_pktinfo *pkti;
12891 		uint_t ifindex;
12892 
12893 		ifindex = ira->ira_ruifindex;
12894 		toh = (struct T_opthdr *)optptr;
12895 		toh->level = IPPROTO_IPV6;
12896 		toh->name = IPV6_PKTINFO;
12897 		toh->len = sizeof (*toh) + sizeof (*pkti);
12898 		toh->status = 0;
12899 		optptr += sizeof (*toh);
12900 		pkti = (struct in6_pktinfo *)optptr;
12901 		pkti->ipi6_addr = connp->conn_laddr_v6;
12902 		pkti->ipi6_ifindex = ifindex;
12903 		optptr += sizeof (*pkti);
12904 		ASSERT(OK_32PTR(optptr));
12905 		/* Save as "last" value */
12906 		tcp->tcp_recvifindex = ifindex;
12907 	}
12908 	/* If app asked for hoplimit and it has changed ... */
12909 	if (addflag.crb_ipv6_recvhoplimit) {
12910 		toh = (struct T_opthdr *)optptr;
12911 		toh->level = IPPROTO_IPV6;
12912 		toh->name = IPV6_HOPLIMIT;
12913 		toh->len = sizeof (*toh) + sizeof (uint_t);
12914 		toh->status = 0;
12915 		optptr += sizeof (*toh);
12916 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12917 		optptr += sizeof (uint_t);
12918 		ASSERT(OK_32PTR(optptr));
12919 		/* Save as "last" value */
12920 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12921 	}
12922 	/* If app asked for tclass and it has changed ... */
12923 	if (addflag.crb_ipv6_recvtclass) {
12924 		toh = (struct T_opthdr *)optptr;
12925 		toh->level = IPPROTO_IPV6;
12926 		toh->name = IPV6_TCLASS;
12927 		toh->len = sizeof (*toh) + sizeof (uint_t);
12928 		toh->status = 0;
12929 		optptr += sizeof (*toh);
12930 		*(uint_t *)optptr = ipp->ipp_tclass;
12931 		optptr += sizeof (uint_t);
12932 		ASSERT(OK_32PTR(optptr));
12933 		/* Save as "last" value */
12934 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12935 	}
12936 	if (addflag.crb_ipv6_recvhopopts) {
12937 		toh = (struct T_opthdr *)optptr;
12938 		toh->level = IPPROTO_IPV6;
12939 		toh->name = IPV6_HOPOPTS;
12940 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12941 		toh->status = 0;
12942 		optptr += sizeof (*toh);
12943 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12944 		optptr += ipp->ipp_hopoptslen;
12945 		ASSERT(OK_32PTR(optptr));
12946 		/* Save as last value */
12947 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12948 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12949 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12950 	}
12951 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12952 		toh = (struct T_opthdr *)optptr;
12953 		toh->level = IPPROTO_IPV6;
12954 		toh->name = IPV6_RTHDRDSTOPTS;
12955 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12956 		toh->status = 0;
12957 		optptr += sizeof (*toh);
12958 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12959 		optptr += ipp->ipp_rthdrdstoptslen;
12960 		ASSERT(OK_32PTR(optptr));
12961 		/* Save as last value */
12962 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12963 		    &tcp->tcp_rthdrdstoptslen,
12964 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12965 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12966 	}
12967 	if (addflag.crb_ipv6_recvrthdr) {
12968 		toh = (struct T_opthdr *)optptr;
12969 		toh->level = IPPROTO_IPV6;
12970 		toh->name = IPV6_RTHDR;
12971 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12972 		toh->status = 0;
12973 		optptr += sizeof (*toh);
12974 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12975 		optptr += ipp->ipp_rthdrlen;
12976 		ASSERT(OK_32PTR(optptr));
12977 		/* Save as last value */
12978 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12979 		    (ipp->ipp_fields & IPPF_RTHDR),
12980 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12981 	}
12982 	if (addflag.crb_ipv6_recvdstopts) {
12983 		toh = (struct T_opthdr *)optptr;
12984 		toh->level = IPPROTO_IPV6;
12985 		toh->name = IPV6_DSTOPTS;
12986 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12987 		toh->status = 0;
12988 		optptr += sizeof (*toh);
12989 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12990 		optptr += ipp->ipp_dstoptslen;
12991 		ASSERT(OK_32PTR(optptr));
12992 		/* Save as last value */
12993 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12994 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12995 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12996 	}
12997 	ASSERT(optptr == mp->b_wptr);
12998 	return (mp);
12999 }
13000 
13001 /* ARGSUSED */
13002 static void
13003 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
13004 {
13005 	conn_t	*connp = (conn_t *)arg;
13006 	tcp_t	*tcp = connp->conn_tcp;
13007 	queue_t	*q = connp->conn_rq;
13008 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13009 
13010 	ASSERT(!IPCL_IS_NONSTR(connp));
13011 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13012 	tcp->tcp_rsrv_mp = mp;
13013 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13014 
13015 	TCP_STAT(tcps, tcp_rsrv_calls);
13016 
13017 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
13018 		return;
13019 	}
13020 
13021 	if (tcp->tcp_fused) {
13022 		tcp_fuse_backenable(tcp);
13023 		return;
13024 	}
13025 
13026 	if (canputnext(q)) {
13027 		/* Not flow-controlled, open rwnd */
13028 		tcp->tcp_rwnd = connp->conn_rcvbuf;
13029 
13030 		/*
13031 		 * Send back a window update immediately if TCP is above
13032 		 * ESTABLISHED state and the increase of the rcv window
13033 		 * that the other side knows is at least 1 MSS after flow
13034 		 * control is lifted.
13035 		 */
13036 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
13037 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
13038 			tcp_xmit_ctl(NULL, tcp,
13039 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
13040 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
13041 		}
13042 	}
13043 }
13044 
13045 /*
13046  * The read side service routine is called mostly when we get back-enabled as a
13047  * result of flow control relief.  Since we don't actually queue anything in
13048  * TCP, we have no data to send out of here.  What we do is clear the receive
13049  * window, and send out a window update.
13050  */
13051 static void
13052 tcp_rsrv(queue_t *q)
13053 {
13054 	conn_t		*connp = Q_TO_CONN(q);
13055 	tcp_t		*tcp = connp->conn_tcp;
13056 	mblk_t		*mp;
13057 
13058 	/* No code does a putq on the read side */
13059 	ASSERT(q->q_first == NULL);
13060 
13061 	/*
13062 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
13063 	 * been run.  So just return.
13064 	 */
13065 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13066 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13067 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13068 		return;
13069 	}
13070 	tcp->tcp_rsrv_mp = NULL;
13071 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13072 
13073 	CONN_INC_REF(connp);
13074 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13075 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13076 }
13077 
13078 /*
13079  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13080  * We do not allow the receive window to shrink.  After setting rwnd,
13081  * set the flow control hiwat of the stream.
13082  *
13083  * This function is called in 2 cases:
13084  *
13085  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13086  *    connection (passive open) and in tcp_input_data() for active connect.
13087  *    This is called after tcp_mss_set() when the desired MSS value is known.
13088  *    This makes sure that our window size is a mutiple of the other side's
13089  *    MSS.
13090  * 2) Handling SO_RCVBUF option.
13091  *
13092  * It is ASSUMED that the requested size is a multiple of the current MSS.
13093  *
13094  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13095  * user requests so.
13096  */
13097 int
13098 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13099 {
13100 	uint32_t	mss = tcp->tcp_mss;
13101 	uint32_t	old_max_rwnd;
13102 	uint32_t	max_transmittable_rwnd;
13103 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13104 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13105 	conn_t		*connp = tcp->tcp_connp;
13106 
13107 	/*
13108 	 * Insist on a receive window that is at least
13109 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13110 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13111 	 * and delayed acknowledgement.
13112 	 */
13113 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13114 
13115 	if (tcp->tcp_fused) {
13116 		size_t sth_hiwat;
13117 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13118 
13119 		ASSERT(peer_tcp != NULL);
13120 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13121 		if (!tcp_detached) {
13122 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13123 			    sth_hiwat);
13124 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13125 		}
13126 
13127 		/* Caller could have changed tcp_rwnd; update tha_win */
13128 		if (tcp->tcp_tcpha != NULL) {
13129 			tcp->tcp_tcpha->tha_win =
13130 			    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13131 		}
13132 		if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13133 			tcp->tcp_cwnd_max = rwnd;
13134 
13135 		/*
13136 		 * In the fusion case, the maxpsz stream head value of
13137 		 * our peer is set according to its send buffer size
13138 		 * and our receive buffer size; since the latter may
13139 		 * have changed we need to update the peer's maxpsz.
13140 		 */
13141 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13142 		return (sth_hiwat);
13143 	}
13144 
13145 	if (tcp_detached)
13146 		old_max_rwnd = tcp->tcp_rwnd;
13147 	else
13148 		old_max_rwnd = connp->conn_rcvbuf;
13149 
13150 
13151 	/*
13152 	 * If window size info has already been exchanged, TCP should not
13153 	 * shrink the window.  Shrinking window is doable if done carefully.
13154 	 * We may add that support later.  But so far there is not a real
13155 	 * need to do that.
13156 	 */
13157 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13158 		/* MSS may have changed, do a round up again. */
13159 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13160 	}
13161 
13162 	/*
13163 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13164 	 * can be applied even before the window scale option is decided.
13165 	 */
13166 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13167 	if (rwnd > max_transmittable_rwnd) {
13168 		rwnd = max_transmittable_rwnd -
13169 		    (max_transmittable_rwnd % mss);
13170 		if (rwnd < mss)
13171 			rwnd = max_transmittable_rwnd;
13172 		/*
13173 		 * If we're over the limit we may have to back down tcp_rwnd.
13174 		 * The increment below won't work for us. So we set all three
13175 		 * here and the increment below will have no effect.
13176 		 */
13177 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13178 	}
13179 	if (tcp->tcp_localnet) {
13180 		tcp->tcp_rack_abs_max =
13181 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13182 	} else {
13183 		/*
13184 		 * For a remote host on a different subnet (through a router),
13185 		 * we ack every other packet to be conforming to RFC1122.
13186 		 * tcp_deferred_acks_max is default to 2.
13187 		 */
13188 		tcp->tcp_rack_abs_max =
13189 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13190 	}
13191 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13192 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13193 	else
13194 		tcp->tcp_rack_cur_max = 0;
13195 	/*
13196 	 * Increment the current rwnd by the amount the maximum grew (we
13197 	 * can not overwrite it since we might be in the middle of a
13198 	 * connection.)
13199 	 */
13200 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13201 	connp->conn_rcvbuf = rwnd;
13202 
13203 	/* Are we already connected? */
13204 	if (tcp->tcp_tcpha != NULL) {
13205 		tcp->tcp_tcpha->tha_win =
13206 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13207 	}
13208 
13209 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13210 		tcp->tcp_cwnd_max = rwnd;
13211 
13212 	if (tcp_detached)
13213 		return (rwnd);
13214 
13215 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13216 
13217 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13218 	return (rwnd);
13219 }
13220 
13221 /*
13222  * Return SNMP stuff in buffer in mpdata.
13223  */
13224 mblk_t *
13225 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13226 {
13227 	mblk_t			*mpdata;
13228 	mblk_t			*mp_conn_ctl = NULL;
13229 	mblk_t			*mp_conn_tail;
13230 	mblk_t			*mp_attr_ctl = NULL;
13231 	mblk_t			*mp_attr_tail;
13232 	mblk_t			*mp6_conn_ctl = NULL;
13233 	mblk_t			*mp6_conn_tail;
13234 	mblk_t			*mp6_attr_ctl = NULL;
13235 	mblk_t			*mp6_attr_tail;
13236 	struct opthdr		*optp;
13237 	mib2_tcpConnEntry_t	tce;
13238 	mib2_tcp6ConnEntry_t	tce6;
13239 	mib2_transportMLPEntry_t mlp;
13240 	connf_t			*connfp;
13241 	int			i;
13242 	boolean_t 		ispriv;
13243 	zoneid_t 		zoneid;
13244 	int			v4_conn_idx;
13245 	int			v6_conn_idx;
13246 	conn_t			*connp = Q_TO_CONN(q);
13247 	tcp_stack_t		*tcps;
13248 	ip_stack_t		*ipst;
13249 	mblk_t			*mp2ctl;
13250 
13251 	/*
13252 	 * make a copy of the original message
13253 	 */
13254 	mp2ctl = copymsg(mpctl);
13255 
13256 	if (mpctl == NULL ||
13257 	    (mpdata = mpctl->b_cont) == NULL ||
13258 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13259 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13260 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13261 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13262 		freemsg(mp_conn_ctl);
13263 		freemsg(mp_attr_ctl);
13264 		freemsg(mp6_conn_ctl);
13265 		freemsg(mp6_attr_ctl);
13266 		freemsg(mpctl);
13267 		freemsg(mp2ctl);
13268 		return (NULL);
13269 	}
13270 
13271 	ipst = connp->conn_netstack->netstack_ip;
13272 	tcps = connp->conn_netstack->netstack_tcp;
13273 
13274 	/* build table of connections -- need count in fixed part */
13275 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13276 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13277 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13278 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13279 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13280 
13281 	ispriv =
13282 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13283 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13284 
13285 	v4_conn_idx = v6_conn_idx = 0;
13286 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13287 
13288 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13289 		ipst = tcps->tcps_netstack->netstack_ip;
13290 
13291 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13292 
13293 		connp = NULL;
13294 
13295 		while ((connp =
13296 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13297 			tcp_t *tcp;
13298 			boolean_t needattr;
13299 
13300 			if (connp->conn_zoneid != zoneid)
13301 				continue;	/* not in this zone */
13302 
13303 			tcp = connp->conn_tcp;
13304 			UPDATE_MIB(&tcps->tcps_mib,
13305 			    tcpHCInSegs, tcp->tcp_ibsegs);
13306 			tcp->tcp_ibsegs = 0;
13307 			UPDATE_MIB(&tcps->tcps_mib,
13308 			    tcpHCOutSegs, tcp->tcp_obsegs);
13309 			tcp->tcp_obsegs = 0;
13310 
13311 			tce6.tcp6ConnState = tce.tcpConnState =
13312 			    tcp_snmp_state(tcp);
13313 			if (tce.tcpConnState == MIB2_TCP_established ||
13314 			    tce.tcpConnState == MIB2_TCP_closeWait)
13315 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13316 
13317 			needattr = B_FALSE;
13318 			bzero(&mlp, sizeof (mlp));
13319 			if (connp->conn_mlp_type != mlptSingle) {
13320 				if (connp->conn_mlp_type == mlptShared ||
13321 				    connp->conn_mlp_type == mlptBoth)
13322 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13323 				if (connp->conn_mlp_type == mlptPrivate ||
13324 				    connp->conn_mlp_type == mlptBoth)
13325 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13326 				needattr = B_TRUE;
13327 			}
13328 			if (connp->conn_anon_mlp) {
13329 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13330 				needattr = B_TRUE;
13331 			}
13332 			switch (connp->conn_mac_mode) {
13333 			case CONN_MAC_DEFAULT:
13334 				break;
13335 			case CONN_MAC_AWARE:
13336 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13337 				needattr = B_TRUE;
13338 				break;
13339 			case CONN_MAC_IMPLICIT:
13340 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13341 				needattr = B_TRUE;
13342 				break;
13343 			}
13344 			if (connp->conn_ixa->ixa_tsl != NULL) {
13345 				ts_label_t *tsl;
13346 
13347 				tsl = connp->conn_ixa->ixa_tsl;
13348 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13349 				mlp.tme_doi = label2doi(tsl);
13350 				mlp.tme_label = *label2bslabel(tsl);
13351 				needattr = B_TRUE;
13352 			}
13353 
13354 			/* Create a message to report on IPv6 entries */
13355 			if (connp->conn_ipversion == IPV6_VERSION) {
13356 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13357 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13358 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13359 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13360 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13361 				tce6.tcp6ConnIfIndex =
13362 				    connp->conn_ixa->ixa_scopeid;
13363 			} else {
13364 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13365 			}
13366 			/* Don't want just anybody seeing these... */
13367 			if (ispriv) {
13368 				tce6.tcp6ConnEntryInfo.ce_snxt =
13369 				    tcp->tcp_snxt;
13370 				tce6.tcp6ConnEntryInfo.ce_suna =
13371 				    tcp->tcp_suna;
13372 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13373 				    tcp->tcp_rnxt;
13374 				tce6.tcp6ConnEntryInfo.ce_rack =
13375 				    tcp->tcp_rack;
13376 			} else {
13377 				/*
13378 				 * Netstat, unfortunately, uses this to
13379 				 * get send/receive queue sizes.  How to fix?
13380 				 * Why not compute the difference only?
13381 				 */
13382 				tce6.tcp6ConnEntryInfo.ce_snxt =
13383 				    tcp->tcp_snxt - tcp->tcp_suna;
13384 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13385 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13386 				    tcp->tcp_rnxt - tcp->tcp_rack;
13387 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13388 			}
13389 
13390 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13391 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13392 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13393 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13394 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13395 
13396 			tce6.tcp6ConnCreationProcess =
13397 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13398 			    connp->conn_cpid;
13399 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13400 
13401 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13402 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13403 
13404 			mlp.tme_connidx = v6_conn_idx++;
13405 			if (needattr)
13406 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13407 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13408 			}
13409 			/*
13410 			 * Create an IPv4 table entry for IPv4 entries and also
13411 			 * for IPv6 entries which are bound to in6addr_any
13412 			 * but don't have IPV6_V6ONLY set.
13413 			 * (i.e. anything an IPv4 peer could connect to)
13414 			 */
13415 			if (connp->conn_ipversion == IPV4_VERSION ||
13416 			    (tcp->tcp_state <= TCPS_LISTEN &&
13417 			    !connp->conn_ipv6_v6only &&
13418 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13419 				if (connp->conn_ipversion == IPV6_VERSION) {
13420 					tce.tcpConnRemAddress = INADDR_ANY;
13421 					tce.tcpConnLocalAddress = INADDR_ANY;
13422 				} else {
13423 					tce.tcpConnRemAddress =
13424 					    connp->conn_faddr_v4;
13425 					tce.tcpConnLocalAddress =
13426 					    connp->conn_laddr_v4;
13427 				}
13428 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13429 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13430 				/* Don't want just anybody seeing these... */
13431 				if (ispriv) {
13432 					tce.tcpConnEntryInfo.ce_snxt =
13433 					    tcp->tcp_snxt;
13434 					tce.tcpConnEntryInfo.ce_suna =
13435 					    tcp->tcp_suna;
13436 					tce.tcpConnEntryInfo.ce_rnxt =
13437 					    tcp->tcp_rnxt;
13438 					tce.tcpConnEntryInfo.ce_rack =
13439 					    tcp->tcp_rack;
13440 				} else {
13441 					/*
13442 					 * Netstat, unfortunately, uses this to
13443 					 * get send/receive queue sizes.  How
13444 					 * to fix?
13445 					 * Why not compute the difference only?
13446 					 */
13447 					tce.tcpConnEntryInfo.ce_snxt =
13448 					    tcp->tcp_snxt - tcp->tcp_suna;
13449 					tce.tcpConnEntryInfo.ce_suna = 0;
13450 					tce.tcpConnEntryInfo.ce_rnxt =
13451 					    tcp->tcp_rnxt - tcp->tcp_rack;
13452 					tce.tcpConnEntryInfo.ce_rack = 0;
13453 				}
13454 
13455 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13456 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13457 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13458 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13459 				tce.tcpConnEntryInfo.ce_state =
13460 				    tcp->tcp_state;
13461 
13462 				tce.tcpConnCreationProcess =
13463 				    (connp->conn_cpid < 0) ?
13464 				    MIB2_UNKNOWN_PROCESS :
13465 				    connp->conn_cpid;
13466 				tce.tcpConnCreationTime = connp->conn_open_time;
13467 
13468 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13469 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13470 
13471 				mlp.tme_connidx = v4_conn_idx++;
13472 				if (needattr)
13473 					(void) snmp_append_data2(
13474 					    mp_attr_ctl->b_cont,
13475 					    &mp_attr_tail, (char *)&mlp,
13476 					    sizeof (mlp));
13477 			}
13478 		}
13479 	}
13480 
13481 	/* fixed length structure for IPv4 and IPv6 counters */
13482 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13483 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13484 	    sizeof (mib2_tcp6ConnEntry_t));
13485 	/* synchronize 32- and 64-bit counters */
13486 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13487 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13488 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13489 	optp->level = MIB2_TCP;
13490 	optp->name = 0;
13491 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13492 	    sizeof (tcps->tcps_mib));
13493 	optp->len = msgdsize(mpdata);
13494 	qreply(q, mpctl);
13495 
13496 	/* table of connections... */
13497 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13498 	    sizeof (struct T_optmgmt_ack)];
13499 	optp->level = MIB2_TCP;
13500 	optp->name = MIB2_TCP_CONN;
13501 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13502 	qreply(q, mp_conn_ctl);
13503 
13504 	/* table of MLP attributes... */
13505 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13506 	    sizeof (struct T_optmgmt_ack)];
13507 	optp->level = MIB2_TCP;
13508 	optp->name = EXPER_XPORT_MLP;
13509 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13510 	if (optp->len == 0)
13511 		freemsg(mp_attr_ctl);
13512 	else
13513 		qreply(q, mp_attr_ctl);
13514 
13515 	/* table of IPv6 connections... */
13516 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13517 	    sizeof (struct T_optmgmt_ack)];
13518 	optp->level = MIB2_TCP6;
13519 	optp->name = MIB2_TCP6_CONN;
13520 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13521 	qreply(q, mp6_conn_ctl);
13522 
13523 	/* table of IPv6 MLP attributes... */
13524 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13525 	    sizeof (struct T_optmgmt_ack)];
13526 	optp->level = MIB2_TCP6;
13527 	optp->name = EXPER_XPORT_MLP;
13528 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13529 	if (optp->len == 0)
13530 		freemsg(mp6_attr_ctl);
13531 	else
13532 		qreply(q, mp6_attr_ctl);
13533 	return (mp2ctl);
13534 }
13535 
13536 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13537 /* ARGSUSED */
13538 int
13539 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13540 {
13541 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13542 
13543 	switch (level) {
13544 	case MIB2_TCP:
13545 		switch (name) {
13546 		case 13:
13547 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13548 				return (0);
13549 			/* TODO: delete entry defined by tce */
13550 			return (1);
13551 		default:
13552 			return (0);
13553 		}
13554 	default:
13555 		return (1);
13556 	}
13557 }
13558 
13559 /* Translate TCP state to MIB2 TCP state. */
13560 static int
13561 tcp_snmp_state(tcp_t *tcp)
13562 {
13563 	if (tcp == NULL)
13564 		return (0);
13565 
13566 	switch (tcp->tcp_state) {
13567 	case TCPS_CLOSED:
13568 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13569 	case TCPS_BOUND:
13570 		return (MIB2_TCP_closed);
13571 	case TCPS_LISTEN:
13572 		return (MIB2_TCP_listen);
13573 	case TCPS_SYN_SENT:
13574 		return (MIB2_TCP_synSent);
13575 	case TCPS_SYN_RCVD:
13576 		return (MIB2_TCP_synReceived);
13577 	case TCPS_ESTABLISHED:
13578 		return (MIB2_TCP_established);
13579 	case TCPS_CLOSE_WAIT:
13580 		return (MIB2_TCP_closeWait);
13581 	case TCPS_FIN_WAIT_1:
13582 		return (MIB2_TCP_finWait1);
13583 	case TCPS_CLOSING:
13584 		return (MIB2_TCP_closing);
13585 	case TCPS_LAST_ACK:
13586 		return (MIB2_TCP_lastAck);
13587 	case TCPS_FIN_WAIT_2:
13588 		return (MIB2_TCP_finWait2);
13589 	case TCPS_TIME_WAIT:
13590 		return (MIB2_TCP_timeWait);
13591 	default:
13592 		return (0);
13593 	}
13594 }
13595 
13596 /*
13597  * tcp_timer is the timer service routine.  It handles the retransmission,
13598  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13599  * from the state of the tcp instance what kind of action needs to be done
13600  * at the time it is called.
13601  */
13602 static void
13603 tcp_timer(void *arg)
13604 {
13605 	mblk_t		*mp;
13606 	clock_t		first_threshold;
13607 	clock_t		second_threshold;
13608 	clock_t		ms;
13609 	uint32_t	mss;
13610 	conn_t		*connp = (conn_t *)arg;
13611 	tcp_t		*tcp = connp->conn_tcp;
13612 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13613 
13614 	tcp->tcp_timer_tid = 0;
13615 
13616 	if (tcp->tcp_fused)
13617 		return;
13618 
13619 	first_threshold =  tcp->tcp_first_timer_threshold;
13620 	second_threshold = tcp->tcp_second_timer_threshold;
13621 	switch (tcp->tcp_state) {
13622 	case TCPS_IDLE:
13623 	case TCPS_BOUND:
13624 	case TCPS_LISTEN:
13625 		return;
13626 	case TCPS_SYN_RCVD: {
13627 		tcp_t	*listener = tcp->tcp_listener;
13628 
13629 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13630 			/* it's our first timeout */
13631 			tcp->tcp_syn_rcvd_timeout = 1;
13632 			mutex_enter(&listener->tcp_eager_lock);
13633 			listener->tcp_syn_rcvd_timeout++;
13634 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13635 				/*
13636 				 * Make this eager available for drop if we
13637 				 * need to drop one to accomodate a new
13638 				 * incoming SYN request.
13639 				 */
13640 				MAKE_DROPPABLE(listener, tcp);
13641 			}
13642 			if (!listener->tcp_syn_defense &&
13643 			    (listener->tcp_syn_rcvd_timeout >
13644 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13645 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13646 				/* We may be under attack. Put on a defense. */
13647 				listener->tcp_syn_defense = B_TRUE;
13648 				cmn_err(CE_WARN, "High TCP connect timeout "
13649 				    "rate! System (port %d) may be under a "
13650 				    "SYN flood attack!",
13651 				    ntohs(listener->tcp_connp->conn_lport));
13652 
13653 				listener->tcp_ip_addr_cache = kmem_zalloc(
13654 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13655 				    KM_NOSLEEP);
13656 			}
13657 			mutex_exit(&listener->tcp_eager_lock);
13658 		} else if (listener != NULL) {
13659 			mutex_enter(&listener->tcp_eager_lock);
13660 			tcp->tcp_syn_rcvd_timeout++;
13661 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13662 			    !tcp->tcp_closemp_used) {
13663 				/*
13664 				 * This is our second timeout. Put the tcp in
13665 				 * the list of droppable eagers to allow it to
13666 				 * be dropped, if needed. We don't check
13667 				 * whether tcp_dontdrop is set or not to
13668 				 * protect ourselve from a SYN attack where a
13669 				 * remote host can spoof itself as one of the
13670 				 * good IP source and continue to hold
13671 				 * resources too long.
13672 				 */
13673 				MAKE_DROPPABLE(listener, tcp);
13674 			}
13675 			mutex_exit(&listener->tcp_eager_lock);
13676 		}
13677 	}
13678 		/* FALLTHRU */
13679 	case TCPS_SYN_SENT:
13680 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13681 		second_threshold = tcp->tcp_second_ctimer_threshold;
13682 		break;
13683 	case TCPS_ESTABLISHED:
13684 	case TCPS_FIN_WAIT_1:
13685 	case TCPS_CLOSING:
13686 	case TCPS_CLOSE_WAIT:
13687 	case TCPS_LAST_ACK:
13688 		/* If we have data to rexmit */
13689 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13690 			clock_t	time_to_wait;
13691 
13692 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13693 			if (!tcp->tcp_xmit_head)
13694 				break;
13695 			time_to_wait = ddi_get_lbolt() -
13696 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13697 			time_to_wait = tcp->tcp_rto -
13698 			    TICK_TO_MSEC(time_to_wait);
13699 			/*
13700 			 * If the timer fires too early, 1 clock tick earlier,
13701 			 * restart the timer.
13702 			 */
13703 			if (time_to_wait > msec_per_tick) {
13704 				TCP_STAT(tcps, tcp_timer_fire_early);
13705 				TCP_TIMER_RESTART(tcp, time_to_wait);
13706 				return;
13707 			}
13708 			/*
13709 			 * When we probe zero windows, we force the swnd open.
13710 			 * If our peer acks with a closed window swnd will be
13711 			 * set to zero by tcp_rput(). As long as we are
13712 			 * receiving acks tcp_rput will
13713 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13714 			 * first and second interval actions.  NOTE: the timer
13715 			 * interval is allowed to continue its exponential
13716 			 * backoff.
13717 			 */
13718 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13719 				if (connp->conn_debug) {
13720 					(void) strlog(TCP_MOD_ID, 0, 1,
13721 					    SL_TRACE, "tcp_timer: zero win");
13722 				}
13723 			} else {
13724 				/*
13725 				 * After retransmission, we need to do
13726 				 * slow start.  Set the ssthresh to one
13727 				 * half of current effective window and
13728 				 * cwnd to one MSS.  Also reset
13729 				 * tcp_cwnd_cnt.
13730 				 *
13731 				 * Note that if tcp_ssthresh is reduced because
13732 				 * of ECN, do not reduce it again unless it is
13733 				 * already one window of data away (tcp_cwr
13734 				 * should then be cleared) or this is a
13735 				 * timeout for a retransmitted segment.
13736 				 */
13737 				uint32_t npkt;
13738 
13739 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13740 					npkt = ((tcp->tcp_timer_backoff ?
13741 					    tcp->tcp_cwnd_ssthresh :
13742 					    tcp->tcp_snxt -
13743 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13744 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13745 					    tcp->tcp_mss;
13746 				}
13747 				tcp->tcp_cwnd = tcp->tcp_mss;
13748 				tcp->tcp_cwnd_cnt = 0;
13749 				if (tcp->tcp_ecn_ok) {
13750 					tcp->tcp_cwr = B_TRUE;
13751 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13752 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13753 				}
13754 			}
13755 			break;
13756 		}
13757 		/*
13758 		 * We have something to send yet we cannot send.  The
13759 		 * reason can be:
13760 		 *
13761 		 * 1. Zero send window: we need to do zero window probe.
13762 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13763 		 * segments.
13764 		 * 3. SWS avoidance: receiver may have shrunk window,
13765 		 * reset our knowledge.
13766 		 *
13767 		 * Note that condition 2 can happen with either 1 or
13768 		 * 3.  But 1 and 3 are exclusive.
13769 		 */
13770 		if (tcp->tcp_unsent != 0) {
13771 			/*
13772 			 * Should not hold the zero-copy messages for too long.
13773 			 */
13774 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13775 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13776 				    tcp->tcp_xmit_head, B_TRUE);
13777 
13778 			if (tcp->tcp_cwnd == 0) {
13779 				/*
13780 				 * Set tcp_cwnd to 1 MSS so that a
13781 				 * new segment can be sent out.  We
13782 				 * are "clocking out" new data when
13783 				 * the network is really congested.
13784 				 */
13785 				ASSERT(tcp->tcp_ecn_ok);
13786 				tcp->tcp_cwnd = tcp->tcp_mss;
13787 			}
13788 			if (tcp->tcp_swnd == 0) {
13789 				/* Extend window for zero window probe */
13790 				tcp->tcp_swnd++;
13791 				tcp->tcp_zero_win_probe = B_TRUE;
13792 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13793 			} else {
13794 				/*
13795 				 * Handle timeout from sender SWS avoidance.
13796 				 * Reset our knowledge of the max send window
13797 				 * since the receiver might have reduced its
13798 				 * receive buffer.  Avoid setting tcp_max_swnd
13799 				 * to one since that will essentially disable
13800 				 * the SWS checks.
13801 				 *
13802 				 * Note that since we don't have a SWS
13803 				 * state variable, if the timeout is set
13804 				 * for ECN but not for SWS, this
13805 				 * code will also be executed.  This is
13806 				 * fine as tcp_max_swnd is updated
13807 				 * constantly and it will not affect
13808 				 * anything.
13809 				 */
13810 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13811 			}
13812 			tcp_wput_data(tcp, NULL, B_FALSE);
13813 			return;
13814 		}
13815 		/* Is there a FIN that needs to be to re retransmitted? */
13816 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13817 		    !tcp->tcp_fin_acked)
13818 			break;
13819 		/* Nothing to do, return without restarting timer. */
13820 		TCP_STAT(tcps, tcp_timer_fire_miss);
13821 		return;
13822 	case TCPS_FIN_WAIT_2:
13823 		/*
13824 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13825 		 * We waited some time for for peer's FIN, but it hasn't
13826 		 * arrived.  We flush the connection now to avoid
13827 		 * case where the peer has rebooted.
13828 		 */
13829 		if (TCP_IS_DETACHED(tcp)) {
13830 			(void) tcp_clean_death(tcp, 0, 23);
13831 		} else {
13832 			TCP_TIMER_RESTART(tcp,
13833 			    tcps->tcps_fin_wait_2_flush_interval);
13834 		}
13835 		return;
13836 	case TCPS_TIME_WAIT:
13837 		(void) tcp_clean_death(tcp, 0, 24);
13838 		return;
13839 	default:
13840 		if (connp->conn_debug) {
13841 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13842 			    "tcp_timer: strange state (%d) %s",
13843 			    tcp->tcp_state, tcp_display(tcp, NULL,
13844 			    DISP_PORT_ONLY));
13845 		}
13846 		return;
13847 	}
13848 
13849 	/*
13850 	 * If the system is under memory pressure or the max number of
13851 	 * connections have been established for the listener, be more
13852 	 * aggressive in aborting connections.
13853 	 */
13854 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13855 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13856 		second_threshold = tcp_early_abort * SECONDS;
13857 	}
13858 
13859 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13860 		/*
13861 		 * Should not hold the zero-copy messages for too long.
13862 		 */
13863 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13864 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13865 			    tcp->tcp_xmit_head, B_TRUE);
13866 
13867 		/*
13868 		 * For zero window probe, we need to send indefinitely,
13869 		 * unless we have not heard from the other side for some
13870 		 * time...
13871 		 */
13872 		if ((tcp->tcp_zero_win_probe == 0) ||
13873 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13874 		    second_threshold)) {
13875 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13876 			/*
13877 			 * If TCP is in SYN_RCVD state, send back a
13878 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13879 			 * should be zero in TCPS_SYN_RCVD state.
13880 			 */
13881 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13882 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13883 				    "in SYN_RCVD",
13884 				    tcp, tcp->tcp_snxt,
13885 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13886 			}
13887 			(void) tcp_clean_death(tcp,
13888 			    tcp->tcp_client_errno ?
13889 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13890 			return;
13891 		} else {
13892 			/*
13893 			 * If the system is under memory pressure, we also
13894 			 * abort connection in zero window probing.
13895 			 */
13896 			if (tcps->tcps_reclaim) {
13897 				(void) tcp_clean_death(tcp,
13898 				    tcp->tcp_client_errno ?
13899 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13900 				return;
13901 			}
13902 			/*
13903 			 * Set tcp_ms_we_have_waited to second_threshold
13904 			 * so that in next timeout, we will do the above
13905 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13906 			 * This is also to avoid overflow.
13907 			 *
13908 			 * We don't need to decrement tcp_timer_backoff
13909 			 * to avoid overflow because it will be decremented
13910 			 * later if new timeout value is greater than
13911 			 * tcp_rexmit_interval_max.  In the case when
13912 			 * tcp_rexmit_interval_max is greater than
13913 			 * second_threshold, it means that we will wait
13914 			 * longer than second_threshold to send the next
13915 			 * window probe.
13916 			 */
13917 			tcp->tcp_ms_we_have_waited = second_threshold;
13918 		}
13919 	} else if (ms > first_threshold) {
13920 		/*
13921 		 * Should not hold the zero-copy messages for too long.
13922 		 */
13923 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13924 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13925 			    tcp->tcp_xmit_head, B_TRUE);
13926 
13927 		/*
13928 		 * We have been retransmitting for too long...  The RTT
13929 		 * we calculated is probably incorrect.  Reinitialize it.
13930 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13931 		 * tcp_rtt_update so that we won't accidentally cache a
13932 		 * bad value.  But only do this if this is not a zero
13933 		 * window probe.
13934 		 */
13935 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13936 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13937 			    (tcp->tcp_rtt_sa >> 5);
13938 			tcp->tcp_rtt_sa = 0;
13939 			tcp_ip_notify(tcp);
13940 			tcp->tcp_rtt_update = 0;
13941 		}
13942 	}
13943 	tcp->tcp_timer_backoff++;
13944 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13945 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13946 	    tcps->tcps_rexmit_interval_min) {
13947 		/*
13948 		 * This means the original RTO is tcp_rexmit_interval_min.
13949 		 * So we will use tcp_rexmit_interval_min as the RTO value
13950 		 * and do the backoff.
13951 		 */
13952 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13953 	} else {
13954 		ms <<= tcp->tcp_timer_backoff;
13955 	}
13956 	if (ms > tcps->tcps_rexmit_interval_max) {
13957 		ms = tcps->tcps_rexmit_interval_max;
13958 		/*
13959 		 * ms is at max, decrement tcp_timer_backoff to avoid
13960 		 * overflow.
13961 		 */
13962 		tcp->tcp_timer_backoff--;
13963 	}
13964 	tcp->tcp_ms_we_have_waited += ms;
13965 	if (tcp->tcp_zero_win_probe == 0) {
13966 		tcp->tcp_rto = ms;
13967 	}
13968 	TCP_TIMER_RESTART(tcp, ms);
13969 	/*
13970 	 * This is after a timeout and tcp_rto is backed off.  Set
13971 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13972 	 * restart the timer with a correct value.
13973 	 */
13974 	tcp->tcp_set_timer = 1;
13975 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13976 	if (mss > tcp->tcp_mss)
13977 		mss = tcp->tcp_mss;
13978 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13979 		mss = tcp->tcp_swnd;
13980 
13981 	if ((mp = tcp->tcp_xmit_head) != NULL)
13982 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13983 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13984 	    B_TRUE);
13985 
13986 	/*
13987 	 * When slow start after retransmission begins, start with
13988 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13989 	 * start phase.  tcp_snd_burst controls how many segments
13990 	 * can be sent because of an ack.
13991 	 */
13992 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13993 	tcp->tcp_snd_burst = TCP_CWND_SS;
13994 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13995 	    (tcp->tcp_unsent == 0)) {
13996 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13997 	} else {
13998 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13999 	}
14000 	tcp->tcp_rexmit = B_TRUE;
14001 	tcp->tcp_dupack_cnt = 0;
14002 
14003 	/*
14004 	 * Remove all rexmit SACK blk to start from fresh.
14005 	 */
14006 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
14007 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
14008 	if (mp == NULL) {
14009 		return;
14010 	}
14011 
14012 	tcp->tcp_csuna = tcp->tcp_snxt;
14013 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
14014 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
14015 	tcp_send_data(tcp, mp);
14016 
14017 }
14018 
14019 static int
14020 tcp_do_unbind(conn_t *connp)
14021 {
14022 	tcp_t *tcp = connp->conn_tcp;
14023 
14024 	switch (tcp->tcp_state) {
14025 	case TCPS_BOUND:
14026 	case TCPS_LISTEN:
14027 		break;
14028 	default:
14029 		return (-TOUTSTATE);
14030 	}
14031 
14032 	/*
14033 	 * Need to clean up all the eagers since after the unbind, segments
14034 	 * will no longer be delivered to this listener stream.
14035 	 */
14036 	mutex_enter(&tcp->tcp_eager_lock);
14037 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
14038 		tcp_eager_cleanup(tcp, 0);
14039 	}
14040 	mutex_exit(&tcp->tcp_eager_lock);
14041 
14042 	/* Clean up the listener connection counter if necessary. */
14043 	if (tcp->tcp_listen_cnt != NULL)
14044 		TCP_DECR_LISTEN_CNT(tcp);
14045 	connp->conn_laddr_v6 = ipv6_all_zeros;
14046 	connp->conn_saddr_v6 = ipv6_all_zeros;
14047 	tcp_bind_hash_remove(tcp);
14048 	tcp->tcp_state = TCPS_IDLE;
14049 
14050 	ip_unbind(connp);
14051 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
14052 
14053 	return (0);
14054 }
14055 
14056 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
14057 static void
14058 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
14059 {
14060 	conn_t *connp = tcp->tcp_connp;
14061 	int error;
14062 
14063 	error = tcp_do_unbind(connp);
14064 	if (error > 0) {
14065 		tcp_err_ack(tcp, mp, TSYSERR, error);
14066 	} else if (error < 0) {
14067 		tcp_err_ack(tcp, mp, -error, 0);
14068 	} else {
14069 		/* Send M_FLUSH according to TPI */
14070 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
14071 
14072 		mp = mi_tpi_ok_ack_alloc(mp);
14073 		if (mp != NULL)
14074 			putnext(connp->conn_rq, mp);
14075 	}
14076 }
14077 
14078 /*
14079  * Don't let port fall into the privileged range.
14080  * Since the extra privileged ports can be arbitrary we also
14081  * ensure that we exclude those from consideration.
14082  * tcp_g_epriv_ports is not sorted thus we loop over it until
14083  * there are no changes.
14084  *
14085  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14086  * but instead the code relies on:
14087  * - the fact that the address of the array and its size never changes
14088  * - the atomic assignment of the elements of the array
14089  *
14090  * Returns 0 if there are no more ports available.
14091  *
14092  * TS note: skip multilevel ports.
14093  */
14094 static in_port_t
14095 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14096 {
14097 	int i;
14098 	boolean_t restart = B_FALSE;
14099 	tcp_stack_t *tcps = tcp->tcp_tcps;
14100 
14101 	if (random && tcp_random_anon_port != 0) {
14102 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14103 		    sizeof (in_port_t));
14104 		/*
14105 		 * Unless changed by a sys admin, the smallest anon port
14106 		 * is 32768 and the largest anon port is 65535.  It is
14107 		 * very likely (50%) for the random port to be smaller
14108 		 * than the smallest anon port.  When that happens,
14109 		 * add port % (anon port range) to the smallest anon
14110 		 * port to get the random port.  It should fall into the
14111 		 * valid anon port range.
14112 		 */
14113 		if (port < tcps->tcps_smallest_anon_port) {
14114 			port = tcps->tcps_smallest_anon_port +
14115 			    port % (tcps->tcps_largest_anon_port -
14116 			    tcps->tcps_smallest_anon_port);
14117 		}
14118 	}
14119 
14120 retry:
14121 	if (port < tcps->tcps_smallest_anon_port)
14122 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14123 
14124 	if (port > tcps->tcps_largest_anon_port) {
14125 		if (restart)
14126 			return (0);
14127 		restart = B_TRUE;
14128 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14129 	}
14130 
14131 	if (port < tcps->tcps_smallest_nonpriv_port)
14132 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14133 
14134 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14135 		if (port == tcps->tcps_g_epriv_ports[i]) {
14136 			port++;
14137 			/*
14138 			 * Make sure whether the port is in the
14139 			 * valid range.
14140 			 */
14141 			goto retry;
14142 		}
14143 	}
14144 	if (is_system_labeled() &&
14145 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14146 	    IPPROTO_TCP, B_TRUE)) != 0) {
14147 		port = i;
14148 		goto retry;
14149 	}
14150 	return (port);
14151 }
14152 
14153 /*
14154  * Return the next anonymous port in the privileged port range for
14155  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14156  * downwards.  This is the same behavior as documented in the userland
14157  * library call rresvport(3N).
14158  *
14159  * TS note: skip multilevel ports.
14160  */
14161 static in_port_t
14162 tcp_get_next_priv_port(const tcp_t *tcp)
14163 {
14164 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14165 	in_port_t nextport;
14166 	boolean_t restart = B_FALSE;
14167 	tcp_stack_t *tcps = tcp->tcp_tcps;
14168 retry:
14169 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14170 	    next_priv_port >= IPPORT_RESERVED) {
14171 		next_priv_port = IPPORT_RESERVED - 1;
14172 		if (restart)
14173 			return (0);
14174 		restart = B_TRUE;
14175 	}
14176 	if (is_system_labeled() &&
14177 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14178 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14179 		next_priv_port = nextport;
14180 		goto retry;
14181 	}
14182 	return (next_priv_port--);
14183 }
14184 
14185 /* The write side r/w procedure. */
14186 
14187 #if CCS_STATS
14188 struct {
14189 	struct {
14190 		int64_t count, bytes;
14191 	} tot, hit;
14192 } wrw_stats;
14193 #endif
14194 
14195 /*
14196  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14197  * messages.
14198  */
14199 /* ARGSUSED */
14200 static void
14201 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14202 {
14203 	conn_t	*connp = (conn_t *)arg;
14204 	tcp_t	*tcp = connp->conn_tcp;
14205 
14206 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14207 	/*
14208 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14209 	 * Once the close starts, streamhead and sockfs will not let any data
14210 	 * packets come down (close ensures that there are no threads using the
14211 	 * queue and no new threads will come down) but since qprocsoff()
14212 	 * hasn't happened yet, a M_FLUSH or some non data message might
14213 	 * get reflected back (in response to our own FLUSHRW) and get
14214 	 * processed after tcp_close() is done. The conn would still be valid
14215 	 * because a ref would have added but we need to check the state
14216 	 * before actually processing the packet.
14217 	 */
14218 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14219 		freemsg(mp);
14220 		return;
14221 	}
14222 
14223 	switch (DB_TYPE(mp)) {
14224 	case M_IOCDATA:
14225 		tcp_wput_iocdata(tcp, mp);
14226 		break;
14227 	case M_FLUSH:
14228 		tcp_wput_flush(tcp, mp);
14229 		break;
14230 	default:
14231 		ip_wput_nondata(connp->conn_wq, mp);
14232 		break;
14233 	}
14234 }
14235 
14236 /*
14237  * The TCP fast path write put procedure.
14238  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14239  */
14240 /* ARGSUSED */
14241 void
14242 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14243 {
14244 	int		len;
14245 	int		hdrlen;
14246 	int		plen;
14247 	mblk_t		*mp1;
14248 	uchar_t		*rptr;
14249 	uint32_t	snxt;
14250 	tcpha_t		*tcpha;
14251 	struct datab	*db;
14252 	uint32_t	suna;
14253 	uint32_t	mss;
14254 	ipaddr_t	*dst;
14255 	ipaddr_t	*src;
14256 	uint32_t	sum;
14257 	int		usable;
14258 	conn_t		*connp = (conn_t *)arg;
14259 	tcp_t		*tcp = connp->conn_tcp;
14260 	uint32_t	msize;
14261 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14262 	ip_xmit_attr_t	*ixa;
14263 	clock_t		now;
14264 
14265 	/*
14266 	 * Try and ASSERT the minimum possible references on the
14267 	 * conn early enough. Since we are executing on write side,
14268 	 * the connection is obviously not detached and that means
14269 	 * there is a ref each for TCP and IP. Since we are behind
14270 	 * the squeue, the minimum references needed are 3. If the
14271 	 * conn is in classifier hash list, there should be an
14272 	 * extra ref for that (we check both the possibilities).
14273 	 */
14274 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14275 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14276 
14277 	ASSERT(DB_TYPE(mp) == M_DATA);
14278 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14279 
14280 	mutex_enter(&tcp->tcp_non_sq_lock);
14281 	tcp->tcp_squeue_bytes -= msize;
14282 	mutex_exit(&tcp->tcp_non_sq_lock);
14283 
14284 	/* Bypass tcp protocol for fused tcp loopback */
14285 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14286 		return;
14287 
14288 	mss = tcp->tcp_mss;
14289 	/*
14290 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14291 	 * down. Do backoff, now.
14292 	 */
14293 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14294 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14295 
14296 
14297 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14298 	len = (int)(mp->b_wptr - mp->b_rptr);
14299 
14300 	/*
14301 	 * Criteria for fast path:
14302 	 *
14303 	 *   1. no unsent data
14304 	 *   2. single mblk in request
14305 	 *   3. connection established
14306 	 *   4. data in mblk
14307 	 *   5. len <= mss
14308 	 *   6. no tcp_valid bits
14309 	 */
14310 	if ((tcp->tcp_unsent != 0) ||
14311 	    (tcp->tcp_cork) ||
14312 	    (mp->b_cont != NULL) ||
14313 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14314 	    (len == 0) ||
14315 	    (len > mss) ||
14316 	    (tcp->tcp_valid_bits != 0)) {
14317 		tcp_wput_data(tcp, mp, B_FALSE);
14318 		return;
14319 	}
14320 
14321 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14322 	ASSERT(tcp->tcp_fin_sent == 0);
14323 
14324 	/* queue new packet onto retransmission queue */
14325 	if (tcp->tcp_xmit_head == NULL) {
14326 		tcp->tcp_xmit_head = mp;
14327 	} else {
14328 		tcp->tcp_xmit_last->b_cont = mp;
14329 	}
14330 	tcp->tcp_xmit_last = mp;
14331 	tcp->tcp_xmit_tail = mp;
14332 
14333 	/* find out how much we can send */
14334 	/* BEGIN CSTYLED */
14335 	/*
14336 	 *    un-acked	   usable
14337 	 *  |--------------|-----------------|
14338 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14339 	 */
14340 	/* END CSTYLED */
14341 
14342 	/* start sending from tcp_snxt */
14343 	snxt = tcp->tcp_snxt;
14344 
14345 	/*
14346 	 * Check to see if this connection has been idled for some
14347 	 * time and no ACK is expected.  If it is, we need to slow
14348 	 * start again to get back the connection's "self-clock" as
14349 	 * described in VJ's paper.
14350 	 *
14351 	 * Reinitialize tcp_cwnd after idle.
14352 	 */
14353 	now = LBOLT_FASTPATH;
14354 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14355 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14356 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14357 	}
14358 
14359 	usable = tcp->tcp_swnd;		/* tcp window size */
14360 	if (usable > tcp->tcp_cwnd)
14361 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14362 	usable -= snxt;		/* subtract stuff already sent */
14363 	suna = tcp->tcp_suna;
14364 	usable += suna;
14365 	/* usable can be < 0 if the congestion window is smaller */
14366 	if (len > usable) {
14367 		/* Can't send complete M_DATA in one shot */
14368 		goto slow;
14369 	}
14370 
14371 	mutex_enter(&tcp->tcp_non_sq_lock);
14372 	if (tcp->tcp_flow_stopped &&
14373 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14374 		tcp_clrqfull(tcp);
14375 	}
14376 	mutex_exit(&tcp->tcp_non_sq_lock);
14377 
14378 	/*
14379 	 * determine if anything to send (Nagle).
14380 	 *
14381 	 *   1. len < tcp_mss (i.e. small)
14382 	 *   2. unacknowledged data present
14383 	 *   3. len < nagle limit
14384 	 *   4. last packet sent < nagle limit (previous packet sent)
14385 	 */
14386 	if ((len < mss) && (snxt != suna) &&
14387 	    (len < (int)tcp->tcp_naglim) &&
14388 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14389 		/*
14390 		 * This was the first unsent packet and normally
14391 		 * mss < xmit_hiwater so there is no need to worry
14392 		 * about flow control. The next packet will go
14393 		 * through the flow control check in tcp_wput_data().
14394 		 */
14395 		/* leftover work from above */
14396 		tcp->tcp_unsent = len;
14397 		tcp->tcp_xmit_tail_unsent = len;
14398 
14399 		return;
14400 	}
14401 
14402 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14403 
14404 	if (snxt == suna) {
14405 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14406 	}
14407 
14408 	/* we have always sent something */
14409 	tcp->tcp_rack_cnt = 0;
14410 
14411 	tcp->tcp_snxt = snxt + len;
14412 	tcp->tcp_rack = tcp->tcp_rnxt;
14413 
14414 	if ((mp1 = dupb(mp)) == 0)
14415 		goto no_memory;
14416 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14417 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14418 
14419 	/* adjust tcp header information */
14420 	tcpha = tcp->tcp_tcpha;
14421 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14422 
14423 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14424 	sum = (sum >> 16) + (sum & 0xFFFF);
14425 	tcpha->tha_sum = htons(sum);
14426 
14427 	tcpha->tha_seq = htonl(snxt);
14428 
14429 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14430 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14431 	BUMP_LOCAL(tcp->tcp_obsegs);
14432 
14433 	/* Update the latest receive window size in TCP header. */
14434 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14435 
14436 	tcp->tcp_last_sent_len = (ushort_t)len;
14437 
14438 	plen = len + connp->conn_ht_iphc_len;
14439 
14440 	ixa = connp->conn_ixa;
14441 	ixa->ixa_pktlen = plen;
14442 
14443 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14444 		tcp->tcp_ipha->ipha_length = htons(plen);
14445 	} else {
14446 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14447 	}
14448 
14449 	/* see if we need to allocate a mblk for the headers */
14450 	hdrlen = connp->conn_ht_iphc_len;
14451 	rptr = mp1->b_rptr - hdrlen;
14452 	db = mp1->b_datap;
14453 	if ((db->db_ref != 2) || rptr < db->db_base ||
14454 	    (!OK_32PTR(rptr))) {
14455 		/* NOTE: we assume allocb returns an OK_32PTR */
14456 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14457 		if (!mp) {
14458 			freemsg(mp1);
14459 			goto no_memory;
14460 		}
14461 		mp->b_cont = mp1;
14462 		mp1 = mp;
14463 		/* Leave room for Link Level header */
14464 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14465 		mp1->b_wptr = &rptr[hdrlen];
14466 	}
14467 	mp1->b_rptr = rptr;
14468 
14469 	/* Fill in the timestamp option. */
14470 	if (tcp->tcp_snd_ts_ok) {
14471 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14472 
14473 		U32_TO_BE32(llbolt,
14474 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14475 		U32_TO_BE32(tcp->tcp_ts_recent,
14476 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14477 	} else {
14478 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14479 	}
14480 
14481 	/* copy header into outgoing packet */
14482 	dst = (ipaddr_t *)rptr;
14483 	src = (ipaddr_t *)connp->conn_ht_iphc;
14484 	dst[0] = src[0];
14485 	dst[1] = src[1];
14486 	dst[2] = src[2];
14487 	dst[3] = src[3];
14488 	dst[4] = src[4];
14489 	dst[5] = src[5];
14490 	dst[6] = src[6];
14491 	dst[7] = src[7];
14492 	dst[8] = src[8];
14493 	dst[9] = src[9];
14494 	if (hdrlen -= 40) {
14495 		hdrlen >>= 2;
14496 		dst += 10;
14497 		src += 10;
14498 		do {
14499 			*dst++ = *src++;
14500 		} while (--hdrlen);
14501 	}
14502 
14503 	/*
14504 	 * Set the ECN info in the TCP header.  Note that this
14505 	 * is not the template header.
14506 	 */
14507 	if (tcp->tcp_ecn_ok) {
14508 		SET_ECT(tcp, rptr);
14509 
14510 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14511 		if (tcp->tcp_ecn_echo_on)
14512 			tcpha->tha_flags |= TH_ECE;
14513 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14514 			tcpha->tha_flags |= TH_CWR;
14515 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14516 		}
14517 	}
14518 
14519 	if (tcp->tcp_ip_forward_progress) {
14520 		tcp->tcp_ip_forward_progress = B_FALSE;
14521 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14522 	} else {
14523 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14524 	}
14525 	tcp_send_data(tcp, mp1);
14526 	return;
14527 
14528 	/*
14529 	 * If we ran out of memory, we pretend to have sent the packet
14530 	 * and that it was lost on the wire.
14531 	 */
14532 no_memory:
14533 	return;
14534 
14535 slow:
14536 	/* leftover work from above */
14537 	tcp->tcp_unsent = len;
14538 	tcp->tcp_xmit_tail_unsent = len;
14539 	tcp_wput_data(tcp, NULL, B_FALSE);
14540 }
14541 
14542 /*
14543  * This runs at the tail end of accept processing on the squeue of the
14544  * new connection.
14545  */
14546 /* ARGSUSED */
14547 void
14548 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14549 {
14550 	conn_t			*connp = (conn_t *)arg;
14551 	tcp_t			*tcp = connp->conn_tcp;
14552 	queue_t			*q = connp->conn_rq;
14553 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14554 	/* socket options */
14555 	struct sock_proto_props	sopp;
14556 
14557 	/* We should just receive a single mblk that fits a T_discon_ind */
14558 	ASSERT(mp->b_cont == NULL);
14559 
14560 	/*
14561 	 * Drop the eager's ref on the listener, that was placed when
14562 	 * this eager began life in tcp_input_listener.
14563 	 */
14564 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14565 	if (IPCL_IS_NONSTR(connp)) {
14566 		/* Safe to free conn_ind message */
14567 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14568 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14569 	}
14570 
14571 	tcp->tcp_detached = B_FALSE;
14572 
14573 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14574 		/*
14575 		 * Someone blewoff the eager before we could finish
14576 		 * the accept.
14577 		 *
14578 		 * The only reason eager exists it because we put in
14579 		 * a ref on it when conn ind went up. We need to send
14580 		 * a disconnect indication up while the last reference
14581 		 * on the eager will be dropped by the squeue when we
14582 		 * return.
14583 		 */
14584 		ASSERT(tcp->tcp_listener == NULL);
14585 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14586 			if (IPCL_IS_NONSTR(connp)) {
14587 				ASSERT(tcp->tcp_issocket);
14588 				(*connp->conn_upcalls->su_disconnected)(
14589 				    connp->conn_upper_handle, tcp->tcp_connid,
14590 				    ECONNREFUSED);
14591 				freemsg(mp);
14592 			} else {
14593 				struct	T_discon_ind	*tdi;
14594 
14595 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14596 				/*
14597 				 * Let us reuse the incoming mblk to avoid
14598 				 * memory allocation failure problems. We know
14599 				 * that the size of the incoming mblk i.e.
14600 				 * stroptions is greater than sizeof
14601 				 * T_discon_ind.
14602 				 */
14603 				ASSERT(DB_REF(mp) == 1);
14604 				ASSERT(MBLKSIZE(mp) >=
14605 				    sizeof (struct T_discon_ind));
14606 
14607 				DB_TYPE(mp) = M_PROTO;
14608 				((union T_primitives *)mp->b_rptr)->type =
14609 				    T_DISCON_IND;
14610 				tdi = (struct T_discon_ind *)mp->b_rptr;
14611 				if (tcp->tcp_issocket) {
14612 					tdi->DISCON_reason = ECONNREFUSED;
14613 					tdi->SEQ_number = 0;
14614 				} else {
14615 					tdi->DISCON_reason = ENOPROTOOPT;
14616 					tdi->SEQ_number =
14617 					    tcp->tcp_conn_req_seqnum;
14618 				}
14619 				mp->b_wptr = mp->b_rptr +
14620 				    sizeof (struct T_discon_ind);
14621 				putnext(q, mp);
14622 			}
14623 		}
14624 		tcp->tcp_hard_binding = B_FALSE;
14625 		return;
14626 	}
14627 
14628 	/*
14629 	 * This is the first time we run on the correct
14630 	 * queue after tcp_accept. So fix all the q parameters
14631 	 * here.
14632 	 */
14633 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14634 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14635 
14636 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14637 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14638 	    connp->conn_rcvbuf;
14639 
14640 	/*
14641 	 * Determine what write offset value to use depending on SACK and
14642 	 * whether the endpoint is fused or not.
14643 	 */
14644 	if (tcp->tcp_fused) {
14645 		ASSERT(tcp->tcp_loopback);
14646 		ASSERT(tcp->tcp_loopback_peer != NULL);
14647 		/*
14648 		 * For fused tcp loopback, set the stream head's write
14649 		 * offset value to zero since we won't be needing any room
14650 		 * for TCP/IP headers.  This would also improve performance
14651 		 * since it would reduce the amount of work done by kmem.
14652 		 * Non-fused tcp loopback case is handled separately below.
14653 		 */
14654 		sopp.sopp_wroff = 0;
14655 		/*
14656 		 * Update the peer's transmit parameters according to
14657 		 * our recently calculated high water mark value.
14658 		 */
14659 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14660 	} else if (tcp->tcp_snd_sack_ok) {
14661 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14662 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14663 	} else {
14664 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14665 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14666 	}
14667 
14668 	/*
14669 	 * If this is endpoint is handling SSL, then reserve extra
14670 	 * offset and space at the end.
14671 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14672 	 * overriding the previous setting. The extra cost of signing and
14673 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14674 	 * instead of a single contiguous one by the stream head
14675 	 * largely outweighs the statistical reduction of ACKs, when
14676 	 * applicable. The peer will also save on decryption and verification
14677 	 * costs.
14678 	 */
14679 	if (tcp->tcp_kssl_ctx != NULL) {
14680 		sopp.sopp_wroff += SSL3_WROFFSET;
14681 
14682 		sopp.sopp_flags |= SOCKOPT_TAIL;
14683 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14684 
14685 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14686 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14687 
14688 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14689 	}
14690 
14691 	/* Send the options up */
14692 	if (IPCL_IS_NONSTR(connp)) {
14693 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14694 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14695 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14696 		}
14697 		if (tcp->tcp_loopback) {
14698 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14699 			sopp.sopp_loopback = B_TRUE;
14700 		}
14701 		(*connp->conn_upcalls->su_set_proto_props)
14702 		    (connp->conn_upper_handle, &sopp);
14703 		freemsg(mp);
14704 	} else {
14705 		/*
14706 		 * Let us reuse the incoming mblk to avoid
14707 		 * memory allocation failure problems. We know
14708 		 * that the size of the incoming mblk is at least
14709 		 * stroptions
14710 		 */
14711 		struct stroptions *stropt;
14712 
14713 		ASSERT(DB_REF(mp) == 1);
14714 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14715 
14716 		DB_TYPE(mp) = M_SETOPTS;
14717 		stropt = (struct stroptions *)mp->b_rptr;
14718 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14719 		stropt = (struct stroptions *)mp->b_rptr;
14720 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14721 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14722 		stropt->so_wroff = sopp.sopp_wroff;
14723 		stropt->so_maxblk = sopp.sopp_maxblk;
14724 
14725 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14726 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14727 
14728 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14729 			stropt->so_tail = sopp.sopp_tail;
14730 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14731 		}
14732 
14733 		/* Send the options up */
14734 		putnext(q, mp);
14735 	}
14736 
14737 	/*
14738 	 * Pass up any data and/or a fin that has been received.
14739 	 *
14740 	 * Adjust receive window in case it had decreased
14741 	 * (because there is data <=> tcp_rcv_list != NULL)
14742 	 * while the connection was detached. Note that
14743 	 * in case the eager was flow-controlled, w/o this
14744 	 * code, the rwnd may never open up again!
14745 	 */
14746 	if (tcp->tcp_rcv_list != NULL) {
14747 		if (IPCL_IS_NONSTR(connp)) {
14748 			mblk_t *mp;
14749 			int space_left;
14750 			int error;
14751 			boolean_t push = B_TRUE;
14752 
14753 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14754 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14755 			    &push) >= 0) {
14756 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14757 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14758 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14759 					tcp_xmit_ctl(NULL,
14760 					    tcp, (tcp->tcp_swnd == 0) ?
14761 					    tcp->tcp_suna : tcp->tcp_snxt,
14762 					    tcp->tcp_rnxt, TH_ACK);
14763 				}
14764 			}
14765 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14766 				push = B_TRUE;
14767 				tcp->tcp_rcv_list = mp->b_next;
14768 				mp->b_next = NULL;
14769 				space_left = (*connp->conn_upcalls->su_recv)
14770 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14771 				    0, &error, &push);
14772 				if (space_left < 0) {
14773 					/*
14774 					 * We should never be in middle of a
14775 					 * fallback, the squeue guarantees that.
14776 					 */
14777 					ASSERT(error != EOPNOTSUPP);
14778 				}
14779 			}
14780 			tcp->tcp_rcv_last_head = NULL;
14781 			tcp->tcp_rcv_last_tail = NULL;
14782 			tcp->tcp_rcv_cnt = 0;
14783 		} else {
14784 			/* We drain directly in case of fused tcp loopback */
14785 
14786 			if (!tcp->tcp_fused && canputnext(q)) {
14787 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14788 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14789 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14790 					tcp_xmit_ctl(NULL,
14791 					    tcp, (tcp->tcp_swnd == 0) ?
14792 					    tcp->tcp_suna : tcp->tcp_snxt,
14793 					    tcp->tcp_rnxt, TH_ACK);
14794 				}
14795 			}
14796 
14797 			(void) tcp_rcv_drain(tcp);
14798 		}
14799 
14800 		/*
14801 		 * For fused tcp loopback, back-enable peer endpoint
14802 		 * if it's currently flow-controlled.
14803 		 */
14804 		if (tcp->tcp_fused) {
14805 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14806 
14807 			ASSERT(peer_tcp != NULL);
14808 			ASSERT(peer_tcp->tcp_fused);
14809 
14810 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14811 			if (peer_tcp->tcp_flow_stopped) {
14812 				tcp_clrqfull(peer_tcp);
14813 				TCP_STAT(tcps, tcp_fusion_backenabled);
14814 			}
14815 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14816 		}
14817 	}
14818 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14819 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14820 		tcp->tcp_ordrel_done = B_TRUE;
14821 		if (IPCL_IS_NONSTR(connp)) {
14822 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14823 			(*connp->conn_upcalls->su_opctl)(
14824 			    connp->conn_upper_handle,
14825 			    SOCK_OPCTL_SHUT_RECV, 0);
14826 		} else {
14827 			mp = tcp->tcp_ordrel_mp;
14828 			tcp->tcp_ordrel_mp = NULL;
14829 			putnext(q, mp);
14830 		}
14831 	}
14832 	tcp->tcp_hard_binding = B_FALSE;
14833 
14834 	if (connp->conn_keepalive) {
14835 		tcp->tcp_ka_last_intrvl = 0;
14836 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14837 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14838 	}
14839 
14840 	/*
14841 	 * At this point, eager is fully established and will
14842 	 * have the following references -
14843 	 *
14844 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14845 	 * 1 reference for the squeue which will be dropped by the squeue as
14846 	 *	soon as this function returns.
14847 	 * There will be 1 additonal reference for being in classifier
14848 	 *	hash list provided something bad hasn't happened.
14849 	 */
14850 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14851 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14852 }
14853 
14854 /*
14855  * The function called through squeue to get behind listener's perimeter to
14856  * send a deferred conn_ind.
14857  */
14858 /* ARGSUSED */
14859 void
14860 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14861 {
14862 	conn_t	*lconnp = (conn_t *)arg;
14863 	tcp_t *listener = lconnp->conn_tcp;
14864 	struct T_conn_ind *conn_ind;
14865 	tcp_t *tcp;
14866 
14867 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14868 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14869 	    conn_ind->OPT_length);
14870 
14871 	if (listener->tcp_state != TCPS_LISTEN) {
14872 		/*
14873 		 * If listener has closed, it would have caused a
14874 		 * a cleanup/blowoff to happen for the eager, so
14875 		 * we don't need to do anything more.
14876 		 */
14877 		freemsg(mp);
14878 		return;
14879 	}
14880 
14881 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14882 }
14883 
14884 /*
14885  * Common to TPI and sockfs accept code.
14886  */
14887 /* ARGSUSED2 */
14888 static int
14889 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14890 {
14891 	tcp_t *listener, *eager;
14892 	mblk_t *discon_mp;
14893 
14894 	listener = lconnp->conn_tcp;
14895 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14896 	eager = econnp->conn_tcp;
14897 	ASSERT(eager->tcp_listener != NULL);
14898 
14899 	/*
14900 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14901 	 * use it if something failed.
14902 	 */
14903 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14904 	    sizeof (struct stroptions)), BPRI_HI);
14905 
14906 	if (discon_mp == NULL) {
14907 		return (-TPROTO);
14908 	}
14909 	eager->tcp_issocket = B_TRUE;
14910 
14911 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14912 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14913 	ASSERT(econnp->conn_netstack ==
14914 	    listener->tcp_connp->conn_netstack);
14915 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14916 
14917 	/* Put the ref for IP */
14918 	CONN_INC_REF(econnp);
14919 
14920 	/*
14921 	 * We should have minimum of 3 references on the conn
14922 	 * at this point. One each for TCP and IP and one for
14923 	 * the T_conn_ind that was sent up when the 3-way handshake
14924 	 * completed. In the normal case we would also have another
14925 	 * reference (making a total of 4) for the conn being in the
14926 	 * classifier hash list. However the eager could have received
14927 	 * an RST subsequently and tcp_closei_local could have removed
14928 	 * the eager from the classifier hash list, hence we can't
14929 	 * assert that reference.
14930 	 */
14931 	ASSERT(econnp->conn_ref >= 3);
14932 
14933 	mutex_enter(&listener->tcp_eager_lock);
14934 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14935 
14936 		tcp_t *tail;
14937 		tcp_t *tcp;
14938 		mblk_t *mp1;
14939 
14940 		tcp = listener->tcp_eager_prev_q0;
14941 		/*
14942 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14943 		 * deferred T_conn_ind queue. We need to get to the head
14944 		 * of the queue in order to send up T_conn_ind the same
14945 		 * order as how the 3WHS is completed.
14946 		 */
14947 		while (tcp != listener) {
14948 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14949 			    !tcp->tcp_kssl_pending)
14950 				break;
14951 			else
14952 				tcp = tcp->tcp_eager_prev_q0;
14953 		}
14954 		/* None of the pending eagers can be sent up now */
14955 		if (tcp == listener)
14956 			goto no_more_eagers;
14957 
14958 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14959 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14960 		/* Move from q0 to q */
14961 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14962 		listener->tcp_conn_req_cnt_q0--;
14963 		listener->tcp_conn_req_cnt_q++;
14964 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14965 		    tcp->tcp_eager_prev_q0;
14966 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14967 		    tcp->tcp_eager_next_q0;
14968 		tcp->tcp_eager_prev_q0 = NULL;
14969 		tcp->tcp_eager_next_q0 = NULL;
14970 		tcp->tcp_conn_def_q0 = B_FALSE;
14971 
14972 		/* Make sure the tcp isn't in the list of droppables */
14973 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14974 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14975 
14976 		/*
14977 		 * Insert at end of the queue because sockfs sends
14978 		 * down T_CONN_RES in chronological order. Leaving
14979 		 * the older conn indications at front of the queue
14980 		 * helps reducing search time.
14981 		 */
14982 		tail = listener->tcp_eager_last_q;
14983 		if (tail != NULL) {
14984 			tail->tcp_eager_next_q = tcp;
14985 		} else {
14986 			listener->tcp_eager_next_q = tcp;
14987 		}
14988 		listener->tcp_eager_last_q = tcp;
14989 		tcp->tcp_eager_next_q = NULL;
14990 
14991 		/* Need to get inside the listener perimeter */
14992 		CONN_INC_REF(listener->tcp_connp);
14993 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14994 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14995 		    SQTAG_TCP_SEND_PENDING);
14996 	}
14997 no_more_eagers:
14998 	tcp_eager_unlink(eager);
14999 	mutex_exit(&listener->tcp_eager_lock);
15000 
15001 	/*
15002 	 * At this point, the eager is detached from the listener
15003 	 * but we still have an extra refs on eager (apart from the
15004 	 * usual tcp references). The ref was placed in tcp_input_data
15005 	 * before sending the conn_ind in tcp_send_conn_ind.
15006 	 * The ref will be dropped in tcp_accept_finish().
15007 	 */
15008 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
15009 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
15010 	return (0);
15011 }
15012 
15013 int
15014 tcp_accept(sock_lower_handle_t lproto_handle,
15015     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
15016     cred_t *cr)
15017 {
15018 	conn_t *lconnp, *econnp;
15019 	tcp_t *listener, *eager;
15020 
15021 	lconnp = (conn_t *)lproto_handle;
15022 	listener = lconnp->conn_tcp;
15023 	ASSERT(listener->tcp_state == TCPS_LISTEN);
15024 	econnp = (conn_t *)eproto_handle;
15025 	eager = econnp->conn_tcp;
15026 	ASSERT(eager->tcp_listener != NULL);
15027 
15028 	/*
15029 	 * It is OK to manipulate these fields outside the eager's squeue
15030 	 * because they will not start being used until tcp_accept_finish
15031 	 * has been called.
15032 	 */
15033 	ASSERT(lconnp->conn_upper_handle != NULL);
15034 	ASSERT(econnp->conn_upper_handle == NULL);
15035 	econnp->conn_upper_handle = sock_handle;
15036 	econnp->conn_upcalls = lconnp->conn_upcalls;
15037 	ASSERT(IPCL_IS_NONSTR(econnp));
15038 	return (tcp_accept_common(lconnp, econnp, cr));
15039 }
15040 
15041 
15042 /*
15043  * This is the STREAMS entry point for T_CONN_RES coming down on
15044  * Acceptor STREAM when  sockfs listener does accept processing.
15045  * Read the block comment on top of tcp_input_listener().
15046  */
15047 void
15048 tcp_tpi_accept(queue_t *q, mblk_t *mp)
15049 {
15050 	queue_t *rq = RD(q);
15051 	struct T_conn_res *conn_res;
15052 	tcp_t *eager;
15053 	tcp_t *listener;
15054 	struct T_ok_ack *ok;
15055 	t_scalar_t PRIM_type;
15056 	conn_t *econnp;
15057 	cred_t *cr;
15058 
15059 	ASSERT(DB_TYPE(mp) == M_PROTO);
15060 
15061 	/*
15062 	 * All Solaris components should pass a db_credp
15063 	 * for this TPI message, hence we ASSERT.
15064 	 * But in case there is some other M_PROTO that looks
15065 	 * like a TPI message sent by some other kernel
15066 	 * component, we check and return an error.
15067 	 */
15068 	cr = msg_getcred(mp, NULL);
15069 	ASSERT(cr != NULL);
15070 	if (cr == NULL) {
15071 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15072 		if (mp != NULL)
15073 			putnext(rq, mp);
15074 		return;
15075 	}
15076 	conn_res = (struct T_conn_res *)mp->b_rptr;
15077 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15078 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15079 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15080 		if (mp != NULL)
15081 			putnext(rq, mp);
15082 		return;
15083 	}
15084 	switch (conn_res->PRIM_type) {
15085 	case O_T_CONN_RES:
15086 	case T_CONN_RES:
15087 		/*
15088 		 * We pass up an err ack if allocb fails. This will
15089 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15090 		 * tcp_eager_blowoff to be called. sockfs will then call
15091 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15092 		 * we need to do the allocb up here because we have to
15093 		 * make sure rq->q_qinfo->qi_qclose still points to the
15094 		 * correct function (tcp_tpi_close_accept) in case allocb
15095 		 * fails.
15096 		 */
15097 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15098 		    &eager, conn_res->OPT_length);
15099 		PRIM_type = conn_res->PRIM_type;
15100 		mp->b_datap->db_type = M_PCPROTO;
15101 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15102 		ok = (struct T_ok_ack *)mp->b_rptr;
15103 		ok->PRIM_type = T_OK_ACK;
15104 		ok->CORRECT_prim = PRIM_type;
15105 		econnp = eager->tcp_connp;
15106 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15107 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15108 		econnp->conn_rq = rq;
15109 		econnp->conn_wq = q;
15110 		rq->q_ptr = econnp;
15111 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15112 		q->q_ptr = econnp;
15113 		q->q_qinfo = &tcp_winit;
15114 		listener = eager->tcp_listener;
15115 
15116 		if (tcp_accept_common(listener->tcp_connp,
15117 		    econnp, cr) < 0) {
15118 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15119 			if (mp != NULL)
15120 				putnext(rq, mp);
15121 			return;
15122 		}
15123 
15124 		/*
15125 		 * Send the new local address also up to sockfs. There
15126 		 * should already be enough space in the mp that came
15127 		 * down from soaccept().
15128 		 */
15129 		if (econnp->conn_family == AF_INET) {
15130 			sin_t *sin;
15131 
15132 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15133 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15134 			sin = (sin_t *)mp->b_wptr;
15135 			mp->b_wptr += sizeof (sin_t);
15136 			sin->sin_family = AF_INET;
15137 			sin->sin_port = econnp->conn_lport;
15138 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15139 		} else {
15140 			sin6_t *sin6;
15141 
15142 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15143 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15144 			sin6 = (sin6_t *)mp->b_wptr;
15145 			mp->b_wptr += sizeof (sin6_t);
15146 			sin6->sin6_family = AF_INET6;
15147 			sin6->sin6_port = econnp->conn_lport;
15148 			sin6->sin6_addr = econnp->conn_laddr_v6;
15149 			if (econnp->conn_ipversion == IPV4_VERSION)
15150 				sin6->sin6_flowinfo = 0;
15151 			else
15152 				sin6->sin6_flowinfo = econnp->conn_flowinfo;
15153 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15154 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15155 				sin6->sin6_scope_id =
15156 				    econnp->conn_ixa->ixa_scopeid;
15157 			} else {
15158 				sin6->sin6_scope_id = 0;
15159 			}
15160 			sin6->__sin6_src_id = 0;
15161 		}
15162 
15163 		putnext(rq, mp);
15164 		return;
15165 	default:
15166 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15167 		if (mp != NULL)
15168 			putnext(rq, mp);
15169 		return;
15170 	}
15171 }
15172 
15173 /*
15174  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15175  */
15176 static void
15177 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15178 {
15179 	void	*data;
15180 	mblk_t	*datamp = mp->b_cont;
15181 	conn_t	*connp = Q_TO_CONN(q);
15182 	tcp_t	*tcp = connp->conn_tcp;
15183 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15184 
15185 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15186 		cmdp->cb_error = EPROTO;
15187 		qreply(q, mp);
15188 		return;
15189 	}
15190 
15191 	data = datamp->b_rptr;
15192 
15193 	switch (cmdp->cb_cmd) {
15194 	case TI_GETPEERNAME:
15195 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15196 			cmdp->cb_error = ENOTCONN;
15197 		else
15198 			cmdp->cb_error = conn_getpeername(connp, data,
15199 			    &cmdp->cb_len);
15200 		break;
15201 	case TI_GETMYNAME:
15202 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15203 		break;
15204 	default:
15205 		cmdp->cb_error = EINVAL;
15206 		break;
15207 	}
15208 
15209 	qreply(q, mp);
15210 }
15211 
15212 void
15213 tcp_wput(queue_t *q, mblk_t *mp)
15214 {
15215 	conn_t	*connp = Q_TO_CONN(q);
15216 	tcp_t	*tcp;
15217 	void (*output_proc)();
15218 	t_scalar_t type;
15219 	uchar_t *rptr;
15220 	struct iocblk	*iocp;
15221 	size_t size;
15222 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15223 
15224 	ASSERT(connp->conn_ref >= 2);
15225 
15226 	switch (DB_TYPE(mp)) {
15227 	case M_DATA:
15228 		tcp = connp->conn_tcp;
15229 		ASSERT(tcp != NULL);
15230 
15231 		size = msgdsize(mp);
15232 
15233 		mutex_enter(&tcp->tcp_non_sq_lock);
15234 		tcp->tcp_squeue_bytes += size;
15235 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15236 			tcp_setqfull(tcp);
15237 		}
15238 		mutex_exit(&tcp->tcp_non_sq_lock);
15239 
15240 		CONN_INC_REF(connp);
15241 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15242 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15243 		return;
15244 
15245 	case M_CMD:
15246 		tcp_wput_cmdblk(q, mp);
15247 		return;
15248 
15249 	case M_PROTO:
15250 	case M_PCPROTO:
15251 		/*
15252 		 * if it is a snmp message, don't get behind the squeue
15253 		 */
15254 		tcp = connp->conn_tcp;
15255 		rptr = mp->b_rptr;
15256 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15257 			type = ((union T_primitives *)rptr)->type;
15258 		} else {
15259 			if (connp->conn_debug) {
15260 				(void) strlog(TCP_MOD_ID, 0, 1,
15261 				    SL_ERROR|SL_TRACE,
15262 				    "tcp_wput_proto, dropping one...");
15263 			}
15264 			freemsg(mp);
15265 			return;
15266 		}
15267 		if (type == T_SVR4_OPTMGMT_REQ) {
15268 			/*
15269 			 * All Solaris components should pass a db_credp
15270 			 * for this TPI message, hence we ASSERT.
15271 			 * But in case there is some other M_PROTO that looks
15272 			 * like a TPI message sent by some other kernel
15273 			 * component, we check and return an error.
15274 			 */
15275 			cred_t	*cr = msg_getcred(mp, NULL);
15276 
15277 			ASSERT(cr != NULL);
15278 			if (cr == NULL) {
15279 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15280 				return;
15281 			}
15282 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15283 			    cr)) {
15284 				/*
15285 				 * This was a SNMP request
15286 				 */
15287 				return;
15288 			} else {
15289 				output_proc = tcp_wput_proto;
15290 			}
15291 		} else {
15292 			output_proc = tcp_wput_proto;
15293 		}
15294 		break;
15295 	case M_IOCTL:
15296 		/*
15297 		 * Most ioctls can be processed right away without going via
15298 		 * squeues - process them right here. Those that do require
15299 		 * squeue (currently _SIOCSOCKFALLBACK)
15300 		 * are processed by tcp_wput_ioctl().
15301 		 */
15302 		iocp = (struct iocblk *)mp->b_rptr;
15303 		tcp = connp->conn_tcp;
15304 
15305 		switch (iocp->ioc_cmd) {
15306 		case TCP_IOC_ABORT_CONN:
15307 			tcp_ioctl_abort_conn(q, mp);
15308 			return;
15309 		case TI_GETPEERNAME:
15310 		case TI_GETMYNAME:
15311 			mi_copyin(q, mp, NULL,
15312 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15313 			return;
15314 		case ND_SET:
15315 			/* nd_getset does the necessary checks */
15316 		case ND_GET:
15317 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15318 				qreply(q, mp);
15319 				return;
15320 			}
15321 			CONN_INC_IOCTLREF(connp);
15322 			ip_wput_nondata(q, mp);
15323 			CONN_DEC_IOCTLREF(connp);
15324 			return;
15325 
15326 		default:
15327 			output_proc = tcp_wput_ioctl;
15328 			break;
15329 		}
15330 		break;
15331 	default:
15332 		output_proc = tcp_wput_nondata;
15333 		break;
15334 	}
15335 
15336 	CONN_INC_REF(connp);
15337 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15338 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15339 }
15340 
15341 /*
15342  * Initial STREAMS write side put() procedure for sockets. It tries to
15343  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15344  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15345  * are handled by tcp_wput() as usual.
15346  *
15347  * All further messages will also be handled by tcp_wput() because we cannot
15348  * be sure that the above short cut is safe later.
15349  */
15350 static void
15351 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15352 {
15353 	conn_t			*connp = Q_TO_CONN(wq);
15354 	tcp_t			*tcp = connp->conn_tcp;
15355 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15356 
15357 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15358 	wq->q_qinfo = &tcp_winit;
15359 
15360 	ASSERT(IPCL_IS_TCP(connp));
15361 	ASSERT(TCP_IS_SOCKET(tcp));
15362 
15363 	if (DB_TYPE(mp) == M_PCPROTO &&
15364 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15365 	    car->PRIM_type == T_CAPABILITY_REQ) {
15366 		tcp_capability_req(tcp, mp);
15367 		return;
15368 	}
15369 
15370 	tcp_wput(wq, mp);
15371 }
15372 
15373 /* ARGSUSED */
15374 static void
15375 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15376 {
15377 #ifdef DEBUG
15378 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15379 #endif
15380 	freemsg(mp);
15381 }
15382 
15383 /*
15384  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15385  */
15386 static boolean_t
15387 tcp_zcopy_check(tcp_t *tcp)
15388 {
15389 	conn_t		*connp = tcp->tcp_connp;
15390 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15391 	boolean_t	zc_enabled = B_FALSE;
15392 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15393 
15394 	if (do_tcpzcopy == 2)
15395 		zc_enabled = B_TRUE;
15396 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15397 		zc_enabled = B_TRUE;
15398 
15399 	tcp->tcp_snd_zcopy_on = zc_enabled;
15400 	if (!TCP_IS_DETACHED(tcp)) {
15401 		if (zc_enabled) {
15402 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15403 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15404 			    ZCVMSAFE);
15405 			TCP_STAT(tcps, tcp_zcopy_on);
15406 		} else {
15407 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15408 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15409 			    ZCVMUNSAFE);
15410 			TCP_STAT(tcps, tcp_zcopy_off);
15411 		}
15412 	}
15413 	return (zc_enabled);
15414 }
15415 
15416 /*
15417  * Backoff from a zero-copy message by copying data to a new allocated
15418  * message and freeing the original desballoca'ed segmapped message.
15419  *
15420  * This function is called by following two callers:
15421  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15422  *    the origial desballoca'ed message and notify sockfs. This is in re-
15423  *    transmit state.
15424  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15425  *    to be copied to new message.
15426  */
15427 static mblk_t *
15428 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15429 {
15430 	mblk_t		*nbp;
15431 	mblk_t		*head = NULL;
15432 	mblk_t		*tail = NULL;
15433 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15434 
15435 	ASSERT(bp != NULL);
15436 	while (bp != NULL) {
15437 		if (IS_VMLOANED_MBLK(bp)) {
15438 			TCP_STAT(tcps, tcp_zcopy_backoff);
15439 			if ((nbp = copyb(bp)) == NULL) {
15440 				tcp->tcp_xmit_zc_clean = B_FALSE;
15441 				if (tail != NULL)
15442 					tail->b_cont = bp;
15443 				return ((head == NULL) ? bp : head);
15444 			}
15445 
15446 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15447 				if (fix_xmitlist)
15448 					tcp_zcopy_notify(tcp);
15449 				else
15450 					nbp->b_datap->db_struioflag |=
15451 					    STRUIO_ZCNOTIFY;
15452 			}
15453 			nbp->b_cont = bp->b_cont;
15454 
15455 			/*
15456 			 * Copy saved information and adjust tcp_xmit_tail
15457 			 * if needed.
15458 			 */
15459 			if (fix_xmitlist) {
15460 				nbp->b_prev = bp->b_prev;
15461 				nbp->b_next = bp->b_next;
15462 
15463 				if (tcp->tcp_xmit_tail == bp)
15464 					tcp->tcp_xmit_tail = nbp;
15465 			}
15466 
15467 			/* Free the original message. */
15468 			bp->b_prev = NULL;
15469 			bp->b_next = NULL;
15470 			freeb(bp);
15471 
15472 			bp = nbp;
15473 		}
15474 
15475 		if (head == NULL) {
15476 			head = bp;
15477 		}
15478 		if (tail == NULL) {
15479 			tail = bp;
15480 		} else {
15481 			tail->b_cont = bp;
15482 			tail = bp;
15483 		}
15484 
15485 		/* Move forward. */
15486 		bp = bp->b_cont;
15487 	}
15488 
15489 	if (fix_xmitlist) {
15490 		tcp->tcp_xmit_last = tail;
15491 		tcp->tcp_xmit_zc_clean = B_TRUE;
15492 	}
15493 
15494 	return (head);
15495 }
15496 
15497 static void
15498 tcp_zcopy_notify(tcp_t *tcp)
15499 {
15500 	struct stdata	*stp;
15501 	conn_t		*connp;
15502 
15503 	if (tcp->tcp_detached)
15504 		return;
15505 	connp = tcp->tcp_connp;
15506 	if (IPCL_IS_NONSTR(connp)) {
15507 		(*connp->conn_upcalls->su_zcopy_notify)
15508 		    (connp->conn_upper_handle);
15509 		return;
15510 	}
15511 	stp = STREAM(connp->conn_rq);
15512 	mutex_enter(&stp->sd_lock);
15513 	stp->sd_flag |= STZCNOTIFY;
15514 	cv_broadcast(&stp->sd_zcopy_wait);
15515 	mutex_exit(&stp->sd_lock);
15516 }
15517 
15518 /*
15519  * Update the TCP connection according to change of LSO capability.
15520  */
15521 static void
15522 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15523 {
15524 	/*
15525 	 * We check against IPv4 header length to preserve the old behavior
15526 	 * of only enabling LSO when there are no IP options.
15527 	 * But this restriction might not be necessary at all. Before removing
15528 	 * it, need to verify how LSO is handled for source routing case, with
15529 	 * which IP does software checksum.
15530 	 *
15531 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15532 	 */
15533 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15534 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15535 		return;
15536 
15537 	/*
15538 	 * Either the LSO capability newly became usable, or it has changed.
15539 	 */
15540 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15541 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15542 
15543 		ASSERT(lsoc->ill_lso_max > 0);
15544 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15545 
15546 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15547 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15548 
15549 		/*
15550 		 * If LSO to be enabled, notify the STREAM header with larger
15551 		 * data block.
15552 		 */
15553 		if (!tcp->tcp_lso)
15554 			tcp->tcp_maxpsz_multiplier = 0;
15555 
15556 		tcp->tcp_lso = B_TRUE;
15557 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15558 	} else { /* LSO capability is not usable any more. */
15559 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15560 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15561 
15562 		/*
15563 		 * If LSO to be disabled, notify the STREAM header with smaller
15564 		 * data block. And need to restore fragsize to PMTU.
15565 		 */
15566 		if (tcp->tcp_lso) {
15567 			tcp->tcp_maxpsz_multiplier =
15568 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15569 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15570 			tcp->tcp_lso = B_FALSE;
15571 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15572 		}
15573 	}
15574 
15575 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15576 }
15577 
15578 /*
15579  * Update the TCP connection according to change of ZEROCOPY capability.
15580  */
15581 static void
15582 tcp_update_zcopy(tcp_t *tcp)
15583 {
15584 	conn_t		*connp = tcp->tcp_connp;
15585 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15586 
15587 	if (tcp->tcp_snd_zcopy_on) {
15588 		tcp->tcp_snd_zcopy_on = B_FALSE;
15589 		if (!TCP_IS_DETACHED(tcp)) {
15590 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15591 			    ZCVMUNSAFE);
15592 			TCP_STAT(tcps, tcp_zcopy_off);
15593 		}
15594 	} else {
15595 		tcp->tcp_snd_zcopy_on = B_TRUE;
15596 		if (!TCP_IS_DETACHED(tcp)) {
15597 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15598 			    ZCVMSAFE);
15599 			TCP_STAT(tcps, tcp_zcopy_on);
15600 		}
15601 	}
15602 }
15603 
15604 /*
15605  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15606  * so it's safe to update the TCP connection.
15607  */
15608 /* ARGSUSED1 */
15609 static void
15610 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15611     ixa_notify_arg_t narg)
15612 {
15613 	tcp_t		*tcp = (tcp_t *)arg;
15614 	conn_t		*connp = tcp->tcp_connp;
15615 
15616 	switch (ntype) {
15617 	case IXAN_LSO:
15618 		tcp_update_lso(tcp, connp->conn_ixa);
15619 		break;
15620 	case IXAN_PMTU:
15621 		tcp_update_pmtu(tcp, B_FALSE);
15622 		break;
15623 	case IXAN_ZCOPY:
15624 		tcp_update_zcopy(tcp);
15625 		break;
15626 	default:
15627 		break;
15628 	}
15629 }
15630 
15631 static void
15632 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15633 {
15634 	conn_t		*connp = tcp->tcp_connp;
15635 
15636 	/*
15637 	 * Check here to avoid sending zero-copy message down to IP when
15638 	 * ZEROCOPY capability has turned off. We only need to deal with
15639 	 * the race condition between sockfs and the notification here.
15640 	 * Since we have tried to backoff the tcp_xmit_head when turning
15641 	 * zero-copy off and new messages in tcp_output(), we simply drop
15642 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15643 	 * is not true.
15644 	 */
15645 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15646 	    !tcp->tcp_xmit_zc_clean) {
15647 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15648 		freemsg(mp);
15649 		return;
15650 	}
15651 
15652 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15653 	(void) conn_ip_output(mp, connp->conn_ixa);
15654 }
15655 
15656 /*
15657  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15658  * if the receiver shrinks the window, i.e. moves the right window to the
15659  * left, the we should not send new data, but should retransmit normally the
15660  * old unacked data between suna and suna + swnd. We might has sent data
15661  * that is now outside the new window, pretend that we didn't send  it.
15662  */
15663 static void
15664 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15665 {
15666 	uint32_t	snxt = tcp->tcp_snxt;
15667 
15668 	ASSERT(shrunk_count > 0);
15669 
15670 	if (!tcp->tcp_is_wnd_shrnk) {
15671 		tcp->tcp_snxt_shrunk = snxt;
15672 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15673 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15674 		tcp->tcp_snxt_shrunk = snxt;
15675 	}
15676 
15677 	/* Pretend we didn't send the data outside the window */
15678 	snxt -= shrunk_count;
15679 
15680 	/* Reset all the values per the now shrunk window */
15681 	tcp_update_xmit_tail(tcp, snxt);
15682 	tcp->tcp_unsent += shrunk_count;
15683 
15684 	/*
15685 	 * If the SACK option is set, delete the entire list of
15686 	 * notsack'ed blocks.
15687 	 */
15688 	if (tcp->tcp_sack_info != NULL) {
15689 		if (tcp->tcp_notsack_list != NULL)
15690 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15691 	}
15692 
15693 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15694 		/*
15695 		 * Make sure the timer is running so that we will probe a zero
15696 		 * window.
15697 		 */
15698 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15699 }
15700 
15701 
15702 /*
15703  * The TCP normal data output path.
15704  * NOTE: the logic of the fast path is duplicated from this function.
15705  */
15706 static void
15707 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15708 {
15709 	int		len;
15710 	mblk_t		*local_time;
15711 	mblk_t		*mp1;
15712 	uint32_t	snxt;
15713 	int		tail_unsent;
15714 	int		tcpstate;
15715 	int		usable = 0;
15716 	mblk_t		*xmit_tail;
15717 	int32_t		mss;
15718 	int32_t		num_sack_blk = 0;
15719 	int32_t		total_hdr_len;
15720 	int32_t		tcp_hdr_len;
15721 	int		rc;
15722 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15723 	conn_t		*connp = tcp->tcp_connp;
15724 	clock_t		now = LBOLT_FASTPATH;
15725 
15726 	tcpstate = tcp->tcp_state;
15727 	if (mp == NULL) {
15728 		/*
15729 		 * tcp_wput_data() with NULL mp should only be called when
15730 		 * there is unsent data.
15731 		 */
15732 		ASSERT(tcp->tcp_unsent > 0);
15733 		/* Really tacky... but we need this for detached closes. */
15734 		len = tcp->tcp_unsent;
15735 		goto data_null;
15736 	}
15737 
15738 #if CCS_STATS
15739 	wrw_stats.tot.count++;
15740 	wrw_stats.tot.bytes += msgdsize(mp);
15741 #endif
15742 	ASSERT(mp->b_datap->db_type == M_DATA);
15743 	/*
15744 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15745 	 * or before a connection attempt has begun.
15746 	 */
15747 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15748 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15749 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15750 #ifdef DEBUG
15751 			cmn_err(CE_WARN,
15752 			    "tcp_wput_data: data after ordrel, %s",
15753 			    tcp_display(tcp, NULL,
15754 			    DISP_ADDR_AND_PORT));
15755 #else
15756 			if (connp->conn_debug) {
15757 				(void) strlog(TCP_MOD_ID, 0, 1,
15758 				    SL_TRACE|SL_ERROR,
15759 				    "tcp_wput_data: data after ordrel, %s\n",
15760 				    tcp_display(tcp, NULL,
15761 				    DISP_ADDR_AND_PORT));
15762 			}
15763 #endif /* DEBUG */
15764 		}
15765 		if (tcp->tcp_snd_zcopy_aware &&
15766 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15767 			tcp_zcopy_notify(tcp);
15768 		freemsg(mp);
15769 		mutex_enter(&tcp->tcp_non_sq_lock);
15770 		if (tcp->tcp_flow_stopped &&
15771 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15772 			tcp_clrqfull(tcp);
15773 		}
15774 		mutex_exit(&tcp->tcp_non_sq_lock);
15775 		return;
15776 	}
15777 
15778 	/* Strip empties */
15779 	for (;;) {
15780 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15781 		    (uintptr_t)INT_MAX);
15782 		len = (int)(mp->b_wptr - mp->b_rptr);
15783 		if (len > 0)
15784 			break;
15785 		mp1 = mp;
15786 		mp = mp->b_cont;
15787 		freeb(mp1);
15788 		if (!mp) {
15789 			return;
15790 		}
15791 	}
15792 
15793 	/* If we are the first on the list ... */
15794 	if (tcp->tcp_xmit_head == NULL) {
15795 		tcp->tcp_xmit_head = mp;
15796 		tcp->tcp_xmit_tail = mp;
15797 		tcp->tcp_xmit_tail_unsent = len;
15798 	} else {
15799 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15800 		struct datab *dp;
15801 
15802 		mp1 = tcp->tcp_xmit_last;
15803 		if (len < tcp_tx_pull_len &&
15804 		    (dp = mp1->b_datap)->db_ref == 1 &&
15805 		    dp->db_lim - mp1->b_wptr >= len) {
15806 			ASSERT(len > 0);
15807 			ASSERT(!mp1->b_cont);
15808 			if (len == 1) {
15809 				*mp1->b_wptr++ = *mp->b_rptr;
15810 			} else {
15811 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15812 				mp1->b_wptr += len;
15813 			}
15814 			if (mp1 == tcp->tcp_xmit_tail)
15815 				tcp->tcp_xmit_tail_unsent += len;
15816 			mp1->b_cont = mp->b_cont;
15817 			if (tcp->tcp_snd_zcopy_aware &&
15818 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15819 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15820 			freeb(mp);
15821 			mp = mp1;
15822 		} else {
15823 			tcp->tcp_xmit_last->b_cont = mp;
15824 		}
15825 		len += tcp->tcp_unsent;
15826 	}
15827 
15828 	/* Tack on however many more positive length mblks we have */
15829 	if ((mp1 = mp->b_cont) != NULL) {
15830 		do {
15831 			int tlen;
15832 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15833 			    (uintptr_t)INT_MAX);
15834 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15835 			if (tlen <= 0) {
15836 				mp->b_cont = mp1->b_cont;
15837 				freeb(mp1);
15838 			} else {
15839 				len += tlen;
15840 				mp = mp1;
15841 			}
15842 		} while ((mp1 = mp->b_cont) != NULL);
15843 	}
15844 	tcp->tcp_xmit_last = mp;
15845 	tcp->tcp_unsent = len;
15846 
15847 	if (urgent)
15848 		usable = 1;
15849 
15850 data_null:
15851 	snxt = tcp->tcp_snxt;
15852 	xmit_tail = tcp->tcp_xmit_tail;
15853 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15854 
15855 	/*
15856 	 * Note that tcp_mss has been adjusted to take into account the
15857 	 * timestamp option if applicable.  Because SACK options do not
15858 	 * appear in every TCP segments and they are of variable lengths,
15859 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15860 	 * the actual segment length when we need to send a segment which
15861 	 * includes SACK options.
15862 	 */
15863 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15864 		int32_t	opt_len;
15865 
15866 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15867 		    tcp->tcp_num_sack_blk);
15868 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15869 		    2 + TCPOPT_HEADER_LEN;
15870 		mss = tcp->tcp_mss - opt_len;
15871 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15872 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15873 	} else {
15874 		mss = tcp->tcp_mss;
15875 		total_hdr_len = connp->conn_ht_iphc_len;
15876 		tcp_hdr_len = connp->conn_ht_ulp_len;
15877 	}
15878 
15879 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15880 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15881 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15882 	}
15883 	if (tcpstate == TCPS_SYN_RCVD) {
15884 		/*
15885 		 * The three-way connection establishment handshake is not
15886 		 * complete yet. We want to queue the data for transmission
15887 		 * after entering ESTABLISHED state (RFC793). A jump to
15888 		 * "done" label effectively leaves data on the queue.
15889 		 */
15890 		goto done;
15891 	} else {
15892 		int usable_r;
15893 
15894 		/*
15895 		 * In the special case when cwnd is zero, which can only
15896 		 * happen if the connection is ECN capable, return now.
15897 		 * New segments is sent using tcp_timer().  The timer
15898 		 * is set in tcp_input_data().
15899 		 */
15900 		if (tcp->tcp_cwnd == 0) {
15901 			/*
15902 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15903 			 * finished.
15904 			 */
15905 			ASSERT(tcp->tcp_ecn_ok ||
15906 			    tcp->tcp_state < TCPS_ESTABLISHED);
15907 			return;
15908 		}
15909 
15910 		/* NOTE: trouble if xmitting while SYN not acked? */
15911 		usable_r = snxt - tcp->tcp_suna;
15912 		usable_r = tcp->tcp_swnd - usable_r;
15913 
15914 		/*
15915 		 * Check if the receiver has shrunk the window.  If
15916 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15917 		 * cannot be set as there is unsent data, so FIN cannot
15918 		 * be sent out.  Otherwise, we need to take into account
15919 		 * of FIN as it consumes an "invisible" sequence number.
15920 		 */
15921 		ASSERT(tcp->tcp_fin_sent == 0);
15922 		if (usable_r < 0) {
15923 			/*
15924 			 * The receiver has shrunk the window and we have sent
15925 			 * -usable_r date beyond the window, re-adjust.
15926 			 *
15927 			 * If TCP window scaling is enabled, there can be
15928 			 * round down error as the advertised receive window
15929 			 * is actually right shifted n bits.  This means that
15930 			 * the lower n bits info is wiped out.  It will look
15931 			 * like the window is shrunk.  Do a check here to
15932 			 * see if the shrunk amount is actually within the
15933 			 * error in window calculation.  If it is, just
15934 			 * return.  Note that this check is inside the
15935 			 * shrunk window check.  This makes sure that even
15936 			 * though tcp_process_shrunk_swnd() is not called,
15937 			 * we will stop further processing.
15938 			 */
15939 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15940 				tcp_process_shrunk_swnd(tcp, -usable_r);
15941 			}
15942 			return;
15943 		}
15944 
15945 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15946 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15947 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15948 
15949 		/* usable = MIN(usable, unsent) */
15950 		if (usable_r > len)
15951 			usable_r = len;
15952 
15953 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15954 		if (usable_r > 0) {
15955 			usable = usable_r;
15956 		} else {
15957 			/* Bypass all other unnecessary processing. */
15958 			goto done;
15959 		}
15960 	}
15961 
15962 	local_time = (mblk_t *)now;
15963 
15964 	/*
15965 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15966 	 * BSD.  This is more in line with the true intent of Nagle.
15967 	 *
15968 	 * The conditions are:
15969 	 * 1. The amount of unsent data (or amount of data which can be
15970 	 *    sent, whichever is smaller) is less than Nagle limit.
15971 	 * 2. The last sent size is also less than Nagle limit.
15972 	 * 3. There is unack'ed data.
15973 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15974 	 *    Nagle algorithm.  This reduces the probability that urgent
15975 	 *    bytes get "merged" together.
15976 	 * 5. The app has not closed the connection.  This eliminates the
15977 	 *    wait time of the receiving side waiting for the last piece of
15978 	 *    (small) data.
15979 	 *
15980 	 * If all are satisified, exit without sending anything.  Note
15981 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15982 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15983 	 * 4095).
15984 	 */
15985 	if (usable < (int)tcp->tcp_naglim &&
15986 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15987 	    snxt != tcp->tcp_suna &&
15988 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15989 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15990 		goto done;
15991 	}
15992 
15993 	/*
15994 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15995 	 * is set, then we have to force TCP not to send partial segment
15996 	 * (smaller than MSS bytes). We are calculating the usable now
15997 	 * based on full mss and will save the rest of remaining data for
15998 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15999 	 * something to do zero window probe.
16000 	 */
16001 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
16002 		if (usable < mss)
16003 			goto done;
16004 		usable = (usable / mss) * mss;
16005 	}
16006 
16007 	/* Update the latest receive window size in TCP header. */
16008 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
16009 
16010 	/* Send the packet. */
16011 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
16012 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
16013 	    local_time);
16014 
16015 	/* Pretend that all we were trying to send really got sent */
16016 	if (rc < 0 && tail_unsent < 0) {
16017 		do {
16018 			xmit_tail = xmit_tail->b_cont;
16019 			xmit_tail->b_prev = local_time;
16020 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
16021 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
16022 			tail_unsent += (int)(xmit_tail->b_wptr -
16023 			    xmit_tail->b_rptr);
16024 		} while (tail_unsent < 0);
16025 	}
16026 done:;
16027 	tcp->tcp_xmit_tail = xmit_tail;
16028 	tcp->tcp_xmit_tail_unsent = tail_unsent;
16029 	len = tcp->tcp_snxt - snxt;
16030 	if (len) {
16031 		/*
16032 		 * If new data was sent, need to update the notsack
16033 		 * list, which is, afterall, data blocks that have
16034 		 * not been sack'ed by the receiver.  New data is
16035 		 * not sack'ed.
16036 		 */
16037 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16038 			/* len is a negative value. */
16039 			tcp->tcp_pipe -= len;
16040 			tcp_notsack_update(&(tcp->tcp_notsack_list),
16041 			    tcp->tcp_snxt, snxt,
16042 			    &(tcp->tcp_num_notsack_blk),
16043 			    &(tcp->tcp_cnt_notsack_list));
16044 		}
16045 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
16046 		tcp->tcp_rack = tcp->tcp_rnxt;
16047 		tcp->tcp_rack_cnt = 0;
16048 		if ((snxt + len) == tcp->tcp_suna) {
16049 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16050 		}
16051 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
16052 		/*
16053 		 * Didn't send anything. Make sure the timer is running
16054 		 * so that we will probe a zero window.
16055 		 */
16056 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16057 	}
16058 	/* Note that len is the amount we just sent but with a negative sign */
16059 	tcp->tcp_unsent += len;
16060 	mutex_enter(&tcp->tcp_non_sq_lock);
16061 	if (tcp->tcp_flow_stopped) {
16062 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
16063 			tcp_clrqfull(tcp);
16064 		}
16065 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
16066 		if (!(tcp->tcp_detached))
16067 			tcp_setqfull(tcp);
16068 	}
16069 	mutex_exit(&tcp->tcp_non_sq_lock);
16070 }
16071 
16072 /*
16073  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16074  * with the template header, as well as other options such as time-stamp,
16075  * ECN and/or SACK.
16076  */
16077 static void
16078 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16079 {
16080 	tcpha_t *tcp_tmpl, *tcpha;
16081 	uint32_t *dst, *src;
16082 	int hdrlen;
16083 	conn_t *connp = tcp->tcp_connp;
16084 
16085 	ASSERT(OK_32PTR(rptr));
16086 
16087 	/* Template header */
16088 	tcp_tmpl = tcp->tcp_tcpha;
16089 
16090 	/* Header of outgoing packet */
16091 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16092 
16093 	/* dst and src are opaque 32-bit fields, used for copying */
16094 	dst = (uint32_t *)rptr;
16095 	src = (uint32_t *)connp->conn_ht_iphc;
16096 	hdrlen = connp->conn_ht_iphc_len;
16097 
16098 	/* Fill time-stamp option if needed */
16099 	if (tcp->tcp_snd_ts_ok) {
16100 		U32_TO_BE32((uint32_t)now,
16101 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16102 		U32_TO_BE32(tcp->tcp_ts_recent,
16103 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16104 	} else {
16105 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16106 	}
16107 
16108 	/*
16109 	 * Copy the template header; is this really more efficient than
16110 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16111 	 * but perhaps not for other scenarios.
16112 	 */
16113 	dst[0] = src[0];
16114 	dst[1] = src[1];
16115 	dst[2] = src[2];
16116 	dst[3] = src[3];
16117 	dst[4] = src[4];
16118 	dst[5] = src[5];
16119 	dst[6] = src[6];
16120 	dst[7] = src[7];
16121 	dst[8] = src[8];
16122 	dst[9] = src[9];
16123 	if (hdrlen -= 40) {
16124 		hdrlen >>= 2;
16125 		dst += 10;
16126 		src += 10;
16127 		do {
16128 			*dst++ = *src++;
16129 		} while (--hdrlen);
16130 	}
16131 
16132 	/*
16133 	 * Set the ECN info in the TCP header if it is not a zero
16134 	 * window probe.  Zero window probe is only sent in
16135 	 * tcp_wput_data() and tcp_timer().
16136 	 */
16137 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16138 		SET_ECT(tcp, rptr);
16139 
16140 		if (tcp->tcp_ecn_echo_on)
16141 			tcpha->tha_flags |= TH_ECE;
16142 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16143 			tcpha->tha_flags |= TH_CWR;
16144 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16145 		}
16146 	}
16147 
16148 	/* Fill in SACK options */
16149 	if (num_sack_blk > 0) {
16150 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16151 		sack_blk_t *tmp;
16152 		int32_t	i;
16153 
16154 		wptr[0] = TCPOPT_NOP;
16155 		wptr[1] = TCPOPT_NOP;
16156 		wptr[2] = TCPOPT_SACK;
16157 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16158 		    sizeof (sack_blk_t);
16159 		wptr += TCPOPT_REAL_SACK_LEN;
16160 
16161 		tmp = tcp->tcp_sack_list;
16162 		for (i = 0; i < num_sack_blk; i++) {
16163 			U32_TO_BE32(tmp[i].begin, wptr);
16164 			wptr += sizeof (tcp_seq);
16165 			U32_TO_BE32(tmp[i].end, wptr);
16166 			wptr += sizeof (tcp_seq);
16167 		}
16168 		tcpha->tha_offset_and_reserved +=
16169 		    ((num_sack_blk * 2 + 1) << 4);
16170 	}
16171 }
16172 
16173 /*
16174  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16175  *
16176  * -1 = failed allocation.
16177  *  0 = success; burst count reached, or usable send window is too small,
16178  *      and that we'd rather wait until later before sending again.
16179  */
16180 static int
16181 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16182     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16183     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16184 {
16185 	int		num_burst_seg = tcp->tcp_snd_burst;
16186 	int		num_lso_seg = 1;
16187 	uint_t		lso_usable;
16188 	boolean_t	do_lso_send = B_FALSE;
16189 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16190 	conn_t		*connp = tcp->tcp_connp;
16191 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16192 
16193 	/*
16194 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16195 	 * the underlying connection is LSO capable. Will check whether having
16196 	 * enough available data to initiate LSO transmission in the for(){}
16197 	 * loops.
16198 	 */
16199 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16200 		do_lso_send = B_TRUE;
16201 
16202 	for (;;) {
16203 		struct datab	*db;
16204 		tcpha_t		*tcpha;
16205 		uint32_t	sum;
16206 		mblk_t		*mp, *mp1;
16207 		uchar_t		*rptr;
16208 		int		len;
16209 
16210 		/*
16211 		 * Burst count reached, return successfully.
16212 		 */
16213 		if (num_burst_seg == 0)
16214 			break;
16215 
16216 		/*
16217 		 * Calculate the maximum payload length we can send at one
16218 		 * time.
16219 		 */
16220 		if (do_lso_send) {
16221 			/*
16222 			 * Check whether be able to to do LSO for the current
16223 			 * available data.
16224 			 */
16225 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16226 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16227 				lso_usable = MIN(lso_usable,
16228 				    num_burst_seg * mss);
16229 
16230 				num_lso_seg = lso_usable / mss;
16231 				if (lso_usable % mss) {
16232 					num_lso_seg++;
16233 					tcp->tcp_last_sent_len = (ushort_t)
16234 					    (lso_usable % mss);
16235 				} else {
16236 					tcp->tcp_last_sent_len = (ushort_t)mss;
16237 				}
16238 			} else {
16239 				do_lso_send = B_FALSE;
16240 				num_lso_seg = 1;
16241 				lso_usable = mss;
16242 			}
16243 		}
16244 
16245 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16246 #ifdef DEBUG
16247 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16248 		    do_lso_send);
16249 #endif
16250 		/*
16251 		 * Adjust num_burst_seg here.
16252 		 */
16253 		num_burst_seg -= num_lso_seg;
16254 
16255 		len = mss;
16256 		if (len > *usable) {
16257 			ASSERT(do_lso_send == B_FALSE);
16258 
16259 			len = *usable;
16260 			if (len <= 0) {
16261 				/* Terminate the loop */
16262 				break;	/* success; too small */
16263 			}
16264 			/*
16265 			 * Sender silly-window avoidance.
16266 			 * Ignore this if we are going to send a
16267 			 * zero window probe out.
16268 			 *
16269 			 * TODO: force data into microscopic window?
16270 			 *	==> (!pushed || (unsent > usable))
16271 			 */
16272 			if (len < (tcp->tcp_max_swnd >> 1) &&
16273 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16274 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16275 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16276 				/*
16277 				 * If the retransmit timer is not running
16278 				 * we start it so that we will retransmit
16279 				 * in the case when the receiver has
16280 				 * decremented the window.
16281 				 */
16282 				if (*snxt == tcp->tcp_snxt &&
16283 				    *snxt == tcp->tcp_suna) {
16284 					/*
16285 					 * We are not supposed to send
16286 					 * anything.  So let's wait a little
16287 					 * bit longer before breaking SWS
16288 					 * avoidance.
16289 					 *
16290 					 * What should the value be?
16291 					 * Suggestion: MAX(init rexmit time,
16292 					 * tcp->tcp_rto)
16293 					 */
16294 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16295 				}
16296 				break;	/* success; too small */
16297 			}
16298 		}
16299 
16300 		tcpha = tcp->tcp_tcpha;
16301 
16302 		/*
16303 		 * The reason to adjust len here is that we need to set flags
16304 		 * and calculate checksum.
16305 		 */
16306 		if (do_lso_send)
16307 			len = lso_usable;
16308 
16309 		*usable -= len; /* Approximate - can be adjusted later */
16310 		if (*usable > 0)
16311 			tcpha->tha_flags = TH_ACK;
16312 		else
16313 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16314 
16315 		/*
16316 		 * Prime pump for IP's checksumming on our behalf.
16317 		 * Include the adjustment for a source route if any.
16318 		 * In case of LSO, the partial pseudo-header checksum should
16319 		 * exclusive TCP length, so zero tha_sum before IP calculate
16320 		 * pseudo-header checksum for partial checksum offload.
16321 		 */
16322 		if (do_lso_send) {
16323 			sum = 0;
16324 		} else {
16325 			sum = len + tcp_hdr_len + connp->conn_sum;
16326 			sum = (sum >> 16) + (sum & 0xFFFF);
16327 		}
16328 		tcpha->tha_sum = htons(sum);
16329 		tcpha->tha_seq = htonl(*snxt);
16330 
16331 		/*
16332 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16333 		 * set.  For the case when TCP_FSS_VALID is the only valid
16334 		 * bit (normal active close), branch off only when we think
16335 		 * that the FIN flag needs to be set.  Note for this case,
16336 		 * that (snxt + len) may not reflect the actual seg_len,
16337 		 * as len may be further reduced in tcp_xmit_mp().  If len
16338 		 * gets modified, we will end up here again.
16339 		 */
16340 		if (tcp->tcp_valid_bits != 0 &&
16341 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16342 		    ((*snxt + len) == tcp->tcp_fss))) {
16343 			uchar_t		*prev_rptr;
16344 			uint32_t	prev_snxt = tcp->tcp_snxt;
16345 
16346 			if (*tail_unsent == 0) {
16347 				ASSERT((*xmit_tail)->b_cont != NULL);
16348 				*xmit_tail = (*xmit_tail)->b_cont;
16349 				prev_rptr = (*xmit_tail)->b_rptr;
16350 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16351 				    (*xmit_tail)->b_rptr);
16352 			} else {
16353 				prev_rptr = (*xmit_tail)->b_rptr;
16354 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16355 				    *tail_unsent;
16356 			}
16357 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16358 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16359 			/* Restore tcp_snxt so we get amount sent right. */
16360 			tcp->tcp_snxt = prev_snxt;
16361 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16362 				/*
16363 				 * If the previous timestamp is still in use,
16364 				 * don't stomp on it.
16365 				 */
16366 				if ((*xmit_tail)->b_next == NULL) {
16367 					(*xmit_tail)->b_prev = local_time;
16368 					(*xmit_tail)->b_next =
16369 					    (mblk_t *)(uintptr_t)(*snxt);
16370 				}
16371 			} else
16372 				(*xmit_tail)->b_rptr = prev_rptr;
16373 
16374 			if (mp == NULL) {
16375 				return (-1);
16376 			}
16377 			mp1 = mp->b_cont;
16378 
16379 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16380 				tcp->tcp_last_sent_len = (ushort_t)len;
16381 			while (mp1->b_cont) {
16382 				*xmit_tail = (*xmit_tail)->b_cont;
16383 				(*xmit_tail)->b_prev = local_time;
16384 				(*xmit_tail)->b_next =
16385 				    (mblk_t *)(uintptr_t)(*snxt);
16386 				mp1 = mp1->b_cont;
16387 			}
16388 			*snxt += len;
16389 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16390 			BUMP_LOCAL(tcp->tcp_obsegs);
16391 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16392 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16393 			tcp_send_data(tcp, mp);
16394 			continue;
16395 		}
16396 
16397 		*snxt += len;	/* Adjust later if we don't send all of len */
16398 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16399 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16400 
16401 		if (*tail_unsent) {
16402 			/* Are the bytes above us in flight? */
16403 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16404 			if (rptr != (*xmit_tail)->b_rptr) {
16405 				*tail_unsent -= len;
16406 				if (len <= mss) /* LSO is unusable */
16407 					tcp->tcp_last_sent_len = (ushort_t)len;
16408 				len += total_hdr_len;
16409 				ixa->ixa_pktlen = len;
16410 
16411 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16412 					tcp->tcp_ipha->ipha_length = htons(len);
16413 				} else {
16414 					tcp->tcp_ip6h->ip6_plen =
16415 					    htons(len - IPV6_HDR_LEN);
16416 				}
16417 
16418 				mp = dupb(*xmit_tail);
16419 				if (mp == NULL) {
16420 					return (-1);	/* out_of_mem */
16421 				}
16422 				mp->b_rptr = rptr;
16423 				/*
16424 				 * If the old timestamp is no longer in use,
16425 				 * sample a new timestamp now.
16426 				 */
16427 				if ((*xmit_tail)->b_next == NULL) {
16428 					(*xmit_tail)->b_prev = local_time;
16429 					(*xmit_tail)->b_next =
16430 					    (mblk_t *)(uintptr_t)(*snxt-len);
16431 				}
16432 				goto must_alloc;
16433 			}
16434 		} else {
16435 			*xmit_tail = (*xmit_tail)->b_cont;
16436 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16437 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16438 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16439 			    (*xmit_tail)->b_rptr);
16440 		}
16441 
16442 		(*xmit_tail)->b_prev = local_time;
16443 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16444 
16445 		*tail_unsent -= len;
16446 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16447 			tcp->tcp_last_sent_len = (ushort_t)len;
16448 
16449 		len += total_hdr_len;
16450 		ixa->ixa_pktlen = len;
16451 
16452 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16453 			tcp->tcp_ipha->ipha_length = htons(len);
16454 		} else {
16455 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16456 		}
16457 
16458 		mp = dupb(*xmit_tail);
16459 		if (mp == NULL) {
16460 			return (-1);	/* out_of_mem */
16461 		}
16462 
16463 		len = total_hdr_len;
16464 		/*
16465 		 * There are four reasons to allocate a new hdr mblk:
16466 		 *  1) The bytes above us are in use by another packet
16467 		 *  2) We don't have good alignment
16468 		 *  3) The mblk is being shared
16469 		 *  4) We don't have enough room for a header
16470 		 */
16471 		rptr = mp->b_rptr - len;
16472 		if (!OK_32PTR(rptr) ||
16473 		    ((db = mp->b_datap), db->db_ref != 2) ||
16474 		    rptr < db->db_base) {
16475 			/* NOTE: we assume allocb returns an OK_32PTR */
16476 
16477 		must_alloc:;
16478 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16479 			    tcps->tcps_wroff_xtra, BPRI_MED);
16480 			if (mp1 == NULL) {
16481 				freemsg(mp);
16482 				return (-1);	/* out_of_mem */
16483 			}
16484 			mp1->b_cont = mp;
16485 			mp = mp1;
16486 			/* Leave room for Link Level header */
16487 			len = total_hdr_len;
16488 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16489 			mp->b_wptr = &rptr[len];
16490 		}
16491 
16492 		/*
16493 		 * Fill in the header using the template header, and add
16494 		 * options such as time-stamp, ECN and/or SACK, as needed.
16495 		 */
16496 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16497 
16498 		mp->b_rptr = rptr;
16499 
16500 		if (*tail_unsent) {
16501 			int spill = *tail_unsent;
16502 
16503 			mp1 = mp->b_cont;
16504 			if (mp1 == NULL)
16505 				mp1 = mp;
16506 
16507 			/*
16508 			 * If we're a little short, tack on more mblks until
16509 			 * there is no more spillover.
16510 			 */
16511 			while (spill < 0) {
16512 				mblk_t *nmp;
16513 				int nmpsz;
16514 
16515 				nmp = (*xmit_tail)->b_cont;
16516 				nmpsz = MBLKL(nmp);
16517 
16518 				/*
16519 				 * Excess data in mblk; can we split it?
16520 				 * If LSO is enabled for the connection,
16521 				 * keep on splitting as this is a transient
16522 				 * send path.
16523 				 */
16524 				if (!do_lso_send && (spill + nmpsz > 0)) {
16525 					/*
16526 					 * Don't split if stream head was
16527 					 * told to break up larger writes
16528 					 * into smaller ones.
16529 					 */
16530 					if (tcp->tcp_maxpsz_multiplier > 0)
16531 						break;
16532 
16533 					/*
16534 					 * Next mblk is less than SMSS/2
16535 					 * rounded up to nearest 64-byte;
16536 					 * let it get sent as part of the
16537 					 * next segment.
16538 					 */
16539 					if (tcp->tcp_localnet &&
16540 					    !tcp->tcp_cork &&
16541 					    (nmpsz < roundup((mss >> 1), 64)))
16542 						break;
16543 				}
16544 
16545 				*xmit_tail = nmp;
16546 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16547 				/* Stash for rtt use later */
16548 				(*xmit_tail)->b_prev = local_time;
16549 				(*xmit_tail)->b_next =
16550 				    (mblk_t *)(uintptr_t)(*snxt - len);
16551 				mp1->b_cont = dupb(*xmit_tail);
16552 				mp1 = mp1->b_cont;
16553 
16554 				spill += nmpsz;
16555 				if (mp1 == NULL) {
16556 					*tail_unsent = spill;
16557 					freemsg(mp);
16558 					return (-1);	/* out_of_mem */
16559 				}
16560 			}
16561 
16562 			/* Trim back any surplus on the last mblk */
16563 			if (spill >= 0) {
16564 				mp1->b_wptr -= spill;
16565 				*tail_unsent = spill;
16566 			} else {
16567 				/*
16568 				 * We did not send everything we could in
16569 				 * order to remain within the b_cont limit.
16570 				 */
16571 				*usable -= spill;
16572 				*snxt += spill;
16573 				tcp->tcp_last_sent_len += spill;
16574 				UPDATE_MIB(&tcps->tcps_mib,
16575 				    tcpOutDataBytes, spill);
16576 				/*
16577 				 * Adjust the checksum
16578 				 */
16579 				tcpha = (tcpha_t *)(rptr +
16580 				    ixa->ixa_ip_hdr_length);
16581 				sum += spill;
16582 				sum = (sum >> 16) + (sum & 0xFFFF);
16583 				tcpha->tha_sum = htons(sum);
16584 				if (connp->conn_ipversion == IPV4_VERSION) {
16585 					sum = ntohs(
16586 					    ((ipha_t *)rptr)->ipha_length) +
16587 					    spill;
16588 					((ipha_t *)rptr)->ipha_length =
16589 					    htons(sum);
16590 				} else {
16591 					sum = ntohs(
16592 					    ((ip6_t *)rptr)->ip6_plen) +
16593 					    spill;
16594 					((ip6_t *)rptr)->ip6_plen =
16595 					    htons(sum);
16596 				}
16597 				ixa->ixa_pktlen += spill;
16598 				*tail_unsent = 0;
16599 			}
16600 		}
16601 		if (tcp->tcp_ip_forward_progress) {
16602 			tcp->tcp_ip_forward_progress = B_FALSE;
16603 			ixa->ixa_flags |= IXAF_REACH_CONF;
16604 		} else {
16605 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16606 		}
16607 
16608 		if (do_lso_send) {
16609 			/* Append LSO information to the mp. */
16610 			lso_info_set(mp, mss, HW_LSO);
16611 			ixa->ixa_fragsize = IP_MAXPACKET;
16612 			ixa->ixa_extra_ident = num_lso_seg - 1;
16613 
16614 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16615 			    boolean_t, B_TRUE);
16616 
16617 			tcp_send_data(tcp, mp);
16618 
16619 			/*
16620 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16621 			 */
16622 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16623 			ixa->ixa_extra_ident = 0;
16624 			tcp->tcp_obsegs += num_lso_seg;
16625 			TCP_STAT(tcps, tcp_lso_times);
16626 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16627 		} else {
16628 			/*
16629 			 * Make sure to clean up LSO information. Wherever a
16630 			 * new mp uses the prepended header room after dupb(),
16631 			 * lso_info_cleanup() should be called.
16632 			 */
16633 			lso_info_cleanup(mp);
16634 			tcp_send_data(tcp, mp);
16635 			BUMP_LOCAL(tcp->tcp_obsegs);
16636 		}
16637 	}
16638 
16639 	return (0);
16640 }
16641 
16642 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16643 static void
16644 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16645 {
16646 	uchar_t	fval = *mp->b_rptr;
16647 	mblk_t	*tail;
16648 	conn_t	*connp = tcp->tcp_connp;
16649 	queue_t	*q = connp->conn_wq;
16650 
16651 	/* TODO: How should flush interact with urgent data? */
16652 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16653 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16654 		/*
16655 		 * Flush only data that has not yet been put on the wire.  If
16656 		 * we flush data that we have already transmitted, life, as we
16657 		 * know it, may come to an end.
16658 		 */
16659 		tail = tcp->tcp_xmit_tail;
16660 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16661 		tcp->tcp_xmit_tail_unsent = 0;
16662 		tcp->tcp_unsent = 0;
16663 		if (tail->b_wptr != tail->b_rptr)
16664 			tail = tail->b_cont;
16665 		if (tail) {
16666 			mblk_t **excess = &tcp->tcp_xmit_head;
16667 			for (;;) {
16668 				mblk_t *mp1 = *excess;
16669 				if (mp1 == tail)
16670 					break;
16671 				tcp->tcp_xmit_tail = mp1;
16672 				tcp->tcp_xmit_last = mp1;
16673 				excess = &mp1->b_cont;
16674 			}
16675 			*excess = NULL;
16676 			tcp_close_mpp(&tail);
16677 			if (tcp->tcp_snd_zcopy_aware)
16678 				tcp_zcopy_notify(tcp);
16679 		}
16680 		/*
16681 		 * We have no unsent data, so unsent must be less than
16682 		 * conn_sndlowat, so re-enable flow.
16683 		 */
16684 		mutex_enter(&tcp->tcp_non_sq_lock);
16685 		if (tcp->tcp_flow_stopped) {
16686 			tcp_clrqfull(tcp);
16687 		}
16688 		mutex_exit(&tcp->tcp_non_sq_lock);
16689 	}
16690 	/*
16691 	 * TODO: you can't just flush these, you have to increase rwnd for one
16692 	 * thing.  For another, how should urgent data interact?
16693 	 */
16694 	if (fval & FLUSHR) {
16695 		*mp->b_rptr = fval & ~FLUSHW;
16696 		/* XXX */
16697 		qreply(q, mp);
16698 		return;
16699 	}
16700 	freemsg(mp);
16701 }
16702 
16703 /*
16704  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16705  * messages.
16706  */
16707 static void
16708 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16709 {
16710 	mblk_t		*mp1;
16711 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16712 	STRUCT_HANDLE(strbuf, sb);
16713 	uint_t		addrlen;
16714 	conn_t		*connp = tcp->tcp_connp;
16715 	queue_t 	*q = connp->conn_wq;
16716 
16717 	/* Make sure it is one of ours. */
16718 	switch (iocp->ioc_cmd) {
16719 	case TI_GETMYNAME:
16720 	case TI_GETPEERNAME:
16721 		break;
16722 	default:
16723 		/*
16724 		 * If the conn is closing, then error the ioctl here. Otherwise
16725 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
16726 		 * we're done here.
16727 		 */
16728 		mutex_enter(&connp->conn_lock);
16729 		if (connp->conn_state_flags & CONN_CLOSING) {
16730 			mutex_exit(&connp->conn_lock);
16731 			iocp->ioc_error = EINVAL;
16732 			mp->b_datap->db_type = M_IOCNAK;
16733 			iocp->ioc_count = 0;
16734 			qreply(q, mp);
16735 			return;
16736 		}
16737 
16738 		CONN_INC_IOCTLREF_LOCKED(connp);
16739 		ip_wput_nondata(q, mp);
16740 		CONN_DEC_IOCTLREF(connp);
16741 		return;
16742 	}
16743 	switch (mi_copy_state(q, mp, &mp1)) {
16744 	case -1:
16745 		return;
16746 	case MI_COPY_CASE(MI_COPY_IN, 1):
16747 		break;
16748 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16749 		/* Copy out the strbuf. */
16750 		mi_copyout(q, mp);
16751 		return;
16752 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16753 		/* All done. */
16754 		mi_copy_done(q, mp, 0);
16755 		return;
16756 	default:
16757 		mi_copy_done(q, mp, EPROTO);
16758 		return;
16759 	}
16760 	/* Check alignment of the strbuf */
16761 	if (!OK_32PTR(mp1->b_rptr)) {
16762 		mi_copy_done(q, mp, EINVAL);
16763 		return;
16764 	}
16765 
16766 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16767 
16768 	if (connp->conn_family == AF_INET)
16769 		addrlen = sizeof (sin_t);
16770 	else
16771 		addrlen = sizeof (sin6_t);
16772 
16773 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16774 		mi_copy_done(q, mp, EINVAL);
16775 		return;
16776 	}
16777 
16778 	switch (iocp->ioc_cmd) {
16779 	case TI_GETMYNAME:
16780 		break;
16781 	case TI_GETPEERNAME:
16782 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16783 			mi_copy_done(q, mp, ENOTCONN);
16784 			return;
16785 		}
16786 		break;
16787 	}
16788 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16789 	if (!mp1)
16790 		return;
16791 
16792 	STRUCT_FSET(sb, len, addrlen);
16793 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16794 	case TI_GETMYNAME:
16795 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16796 		    &addrlen);
16797 		break;
16798 	case TI_GETPEERNAME:
16799 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16800 		    &addrlen);
16801 		break;
16802 	}
16803 	mp1->b_wptr += addrlen;
16804 	/* Copy out the address */
16805 	mi_copyout(q, mp);
16806 }
16807 
16808 static void
16809 tcp_use_pure_tpi(tcp_t *tcp)
16810 {
16811 	conn_t		*connp = tcp->tcp_connp;
16812 
16813 #ifdef	_ILP32
16814 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16815 #else
16816 	tcp->tcp_acceptor_id = connp->conn_dev;
16817 #endif
16818 	/*
16819 	 * Insert this socket into the acceptor hash.
16820 	 * We might need it for T_CONN_RES message
16821 	 */
16822 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16823 
16824 	tcp->tcp_issocket = B_FALSE;
16825 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16826 }
16827 
16828 /*
16829  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16830  * messages.
16831  */
16832 /* ARGSUSED */
16833 static void
16834 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16835 {
16836 	conn_t 		*connp = (conn_t *)arg;
16837 	tcp_t		*tcp = connp->conn_tcp;
16838 	queue_t		*q = connp->conn_wq;
16839 	struct iocblk	*iocp;
16840 
16841 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16842 	/*
16843 	 * Try and ASSERT the minimum possible references on the
16844 	 * conn early enough. Since we are executing on write side,
16845 	 * the connection is obviously not detached and that means
16846 	 * there is a ref each for TCP and IP. Since we are behind
16847 	 * the squeue, the minimum references needed are 3. If the
16848 	 * conn is in classifier hash list, there should be an
16849 	 * extra ref for that (we check both the possibilities).
16850 	 */
16851 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16852 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16853 
16854 	iocp = (struct iocblk *)mp->b_rptr;
16855 	switch (iocp->ioc_cmd) {
16856 	case _SIOCSOCKFALLBACK:
16857 		/*
16858 		 * Either sockmod is about to be popped and the socket
16859 		 * would now be treated as a plain stream, or a module
16860 		 * is about to be pushed so we could no longer use read-
16861 		 * side synchronous streams for fused loopback tcp.
16862 		 * Drain any queued data and disable direct sockfs
16863 		 * interface from now on.
16864 		 */
16865 		if (!tcp->tcp_issocket) {
16866 			DB_TYPE(mp) = M_IOCNAK;
16867 			iocp->ioc_error = EINVAL;
16868 		} else {
16869 			tcp_use_pure_tpi(tcp);
16870 			DB_TYPE(mp) = M_IOCACK;
16871 			iocp->ioc_error = 0;
16872 		}
16873 		iocp->ioc_count = 0;
16874 		iocp->ioc_rval = 0;
16875 		qreply(q, mp);
16876 		return;
16877 	}
16878 
16879 	/*
16880 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
16881 	 * conn_ioctlref to hold off tcp_close until we're done here.
16882 	 */
16883 	mutex_enter(&(connp)->conn_lock);
16884 	if ((connp)->conn_state_flags & CONN_CLOSING) {
16885 		mutex_exit(&(connp)->conn_lock);
16886 		iocp->ioc_error = EINVAL;
16887 		mp->b_datap->db_type = M_IOCNAK;
16888 		iocp->ioc_count = 0;
16889 		qreply(q, mp);
16890 		return;
16891 	}
16892 
16893 	CONN_INC_IOCTLREF_LOCKED(connp);
16894 	ip_wput_nondata(q, mp);
16895 	CONN_DEC_IOCTLREF(connp);
16896 }
16897 
16898 /*
16899  * This routine is called by tcp_wput() to handle all TPI requests.
16900  */
16901 /* ARGSUSED */
16902 static void
16903 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16904 {
16905 	conn_t		*connp = (conn_t *)arg;
16906 	tcp_t		*tcp = connp->conn_tcp;
16907 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16908 	uchar_t		*rptr;
16909 	t_scalar_t	type;
16910 	cred_t		*cr;
16911 
16912 	/*
16913 	 * Try and ASSERT the minimum possible references on the
16914 	 * conn early enough. Since we are executing on write side,
16915 	 * the connection is obviously not detached and that means
16916 	 * there is a ref each for TCP and IP. Since we are behind
16917 	 * the squeue, the minimum references needed are 3. If the
16918 	 * conn is in classifier hash list, there should be an
16919 	 * extra ref for that (we check both the possibilities).
16920 	 */
16921 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16922 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16923 
16924 	rptr = mp->b_rptr;
16925 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16926 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16927 		type = ((union T_primitives *)rptr)->type;
16928 		if (type == T_EXDATA_REQ) {
16929 			tcp_output_urgent(connp, mp, arg2, NULL);
16930 		} else if (type != T_DATA_REQ) {
16931 			goto non_urgent_data;
16932 		} else {
16933 			/* TODO: options, flags, ... from user */
16934 			/* Set length to zero for reclamation below */
16935 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16936 			freeb(mp);
16937 		}
16938 		return;
16939 	} else {
16940 		if (connp->conn_debug) {
16941 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16942 			    "tcp_wput_proto, dropping one...");
16943 		}
16944 		freemsg(mp);
16945 		return;
16946 	}
16947 
16948 non_urgent_data:
16949 
16950 	switch ((int)tprim->type) {
16951 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16952 		/*
16953 		 * save the kssl_ent_t from the next block, and convert this
16954 		 * back to a normal bind_req.
16955 		 */
16956 		if (mp->b_cont != NULL) {
16957 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16958 
16959 			if (tcp->tcp_kssl_ent != NULL) {
16960 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16961 				    KSSL_NO_PROXY);
16962 				tcp->tcp_kssl_ent = NULL;
16963 			}
16964 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16965 			    sizeof (kssl_ent_t));
16966 			kssl_hold_ent(tcp->tcp_kssl_ent);
16967 			freemsg(mp->b_cont);
16968 			mp->b_cont = NULL;
16969 		}
16970 		tprim->type = T_BIND_REQ;
16971 
16972 	/* FALLTHROUGH */
16973 	case O_T_BIND_REQ:	/* bind request */
16974 	case T_BIND_REQ:	/* new semantics bind request */
16975 		tcp_tpi_bind(tcp, mp);
16976 		break;
16977 	case T_UNBIND_REQ:	/* unbind request */
16978 		tcp_tpi_unbind(tcp, mp);
16979 		break;
16980 	case O_T_CONN_RES:	/* old connection response XXX */
16981 	case T_CONN_RES:	/* connection response */
16982 		tcp_tli_accept(tcp, mp);
16983 		break;
16984 	case T_CONN_REQ:	/* connection request */
16985 		tcp_tpi_connect(tcp, mp);
16986 		break;
16987 	case T_DISCON_REQ:	/* disconnect request */
16988 		tcp_disconnect(tcp, mp);
16989 		break;
16990 	case T_CAPABILITY_REQ:
16991 		tcp_capability_req(tcp, mp);	/* capability request */
16992 		break;
16993 	case T_INFO_REQ:	/* information request */
16994 		tcp_info_req(tcp, mp);
16995 		break;
16996 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16997 	case T_OPTMGMT_REQ:
16998 		/*
16999 		 * Note:  no support for snmpcom_req() through new
17000 		 * T_OPTMGMT_REQ. See comments in ip.c
17001 		 */
17002 
17003 		/*
17004 		 * All Solaris components should pass a db_credp
17005 		 * for this TPI message, hence we ASSERT.
17006 		 * But in case there is some other M_PROTO that looks
17007 		 * like a TPI message sent by some other kernel
17008 		 * component, we check and return an error.
17009 		 */
17010 		cr = msg_getcred(mp, NULL);
17011 		ASSERT(cr != NULL);
17012 		if (cr == NULL) {
17013 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
17014 			return;
17015 		}
17016 		/*
17017 		 * If EINPROGRESS is returned, the request has been queued
17018 		 * for subsequent processing by ip_restart_optmgmt(), which
17019 		 * will do the CONN_DEC_REF().
17020 		 */
17021 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
17022 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17023 		} else {
17024 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17025 		}
17026 		break;
17027 
17028 	case T_UNITDATA_REQ:	/* unitdata request */
17029 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17030 		break;
17031 	case T_ORDREL_REQ:	/* orderly release req */
17032 		freemsg(mp);
17033 
17034 		if (tcp->tcp_fused)
17035 			tcp_unfuse(tcp);
17036 
17037 		if (tcp_xmit_end(tcp) != 0) {
17038 			/*
17039 			 * We were crossing FINs and got a reset from
17040 			 * the other side. Just ignore it.
17041 			 */
17042 			if (connp->conn_debug) {
17043 				(void) strlog(TCP_MOD_ID, 0, 1,
17044 				    SL_ERROR|SL_TRACE,
17045 				    "tcp_wput_proto, T_ORDREL_REQ out of "
17046 				    "state %s",
17047 				    tcp_display(tcp, NULL,
17048 				    DISP_ADDR_AND_PORT));
17049 			}
17050 		}
17051 		break;
17052 	case T_ADDR_REQ:
17053 		tcp_addr_req(tcp, mp);
17054 		break;
17055 	default:
17056 		if (connp->conn_debug) {
17057 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
17058 			    "tcp_wput_proto, bogus TPI msg, type %d",
17059 			    tprim->type);
17060 		}
17061 		/*
17062 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
17063 		 * to recover.
17064 		 */
17065 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17066 		break;
17067 	}
17068 }
17069 
17070 /*
17071  * The TCP write service routine should never be called...
17072  */
17073 /* ARGSUSED */
17074 static void
17075 tcp_wsrv(queue_t *q)
17076 {
17077 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17078 
17079 	TCP_STAT(tcps, tcp_wsrv_called);
17080 }
17081 
17082 /*
17083  * Send out a control packet on the tcp connection specified.  This routine
17084  * is typically called where we need a simple ACK or RST generated.
17085  */
17086 static void
17087 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
17088 {
17089 	uchar_t		*rptr;
17090 	tcpha_t		*tcpha;
17091 	ipha_t		*ipha = NULL;
17092 	ip6_t		*ip6h = NULL;
17093 	uint32_t	sum;
17094 	int		total_hdr_len;
17095 	int		ip_hdr_len;
17096 	mblk_t		*mp;
17097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17098 	conn_t		*connp = tcp->tcp_connp;
17099 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17100 
17101 	/*
17102 	 * Save sum for use in source route later.
17103 	 */
17104 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
17105 	total_hdr_len = connp->conn_ht_iphc_len;
17106 	ip_hdr_len = ixa->ixa_ip_hdr_length;
17107 
17108 	/* If a text string is passed in with the request, pass it to strlog. */
17109 	if (str != NULL && connp->conn_debug) {
17110 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17111 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17112 		    str, seq, ack, ctl);
17113 	}
17114 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17115 	    BPRI_MED);
17116 	if (mp == NULL) {
17117 		return;
17118 	}
17119 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17120 	mp->b_rptr = rptr;
17121 	mp->b_wptr = &rptr[total_hdr_len];
17122 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17123 
17124 	ixa->ixa_pktlen = total_hdr_len;
17125 
17126 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17127 		ipha = (ipha_t *)rptr;
17128 		ipha->ipha_length = htons(total_hdr_len);
17129 	} else {
17130 		ip6h = (ip6_t *)rptr;
17131 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17132 	}
17133 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17134 	tcpha->tha_flags = (uint8_t)ctl;
17135 	if (ctl & TH_RST) {
17136 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17137 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17138 		/*
17139 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17140 		 */
17141 		if (tcp->tcp_snd_ts_ok &&
17142 		    tcp->tcp_state > TCPS_SYN_SENT) {
17143 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17144 			*(mp->b_wptr) = TCPOPT_EOL;
17145 
17146 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17147 
17148 			if (connp->conn_ipversion == IPV4_VERSION) {
17149 				ipha->ipha_length = htons(total_hdr_len -
17150 				    TCPOPT_REAL_TS_LEN);
17151 			} else {
17152 				ip6h->ip6_plen = htons(total_hdr_len -
17153 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17154 			}
17155 			tcpha->tha_offset_and_reserved -= (3 << 4);
17156 			sum -= TCPOPT_REAL_TS_LEN;
17157 		}
17158 	}
17159 	if (ctl & TH_ACK) {
17160 		if (tcp->tcp_snd_ts_ok) {
17161 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17162 
17163 			U32_TO_BE32(llbolt,
17164 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17165 			U32_TO_BE32(tcp->tcp_ts_recent,
17166 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17167 		}
17168 
17169 		/* Update the latest receive window size in TCP header. */
17170 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17171 		/* Track what we sent to the peer */
17172 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
17173 		tcp->tcp_rack = ack;
17174 		tcp->tcp_rack_cnt = 0;
17175 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17176 	}
17177 	BUMP_LOCAL(tcp->tcp_obsegs);
17178 	tcpha->tha_seq = htonl(seq);
17179 	tcpha->tha_ack = htonl(ack);
17180 	/*
17181 	 * Include the adjustment for a source route if any.
17182 	 */
17183 	sum = (sum >> 16) + (sum & 0xFFFF);
17184 	tcpha->tha_sum = htons(sum);
17185 	tcp_send_data(tcp, mp);
17186 }
17187 
17188 /*
17189  * If this routine returns B_TRUE, TCP can generate a RST in response
17190  * to a segment.  If it returns B_FALSE, TCP should not respond.
17191  */
17192 static boolean_t
17193 tcp_send_rst_chk(tcp_stack_t *tcps)
17194 {
17195 	int64_t	now;
17196 
17197 	/*
17198 	 * TCP needs to protect itself from generating too many RSTs.
17199 	 * This can be a DoS attack by sending us random segments
17200 	 * soliciting RSTs.
17201 	 *
17202 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17203 	 * in each 1 second interval.  In this way, TCP still generate
17204 	 * RSTs in normal cases but when under attack, the impact is
17205 	 * limited.
17206 	 */
17207 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17208 		now = ddi_get_lbolt64();
17209 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17210 		    1*SECONDS) {
17211 			tcps->tcps_last_rst_intrvl = now;
17212 			tcps->tcps_rst_cnt = 1;
17213 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17214 			return (B_FALSE);
17215 		}
17216 	}
17217 	return (B_TRUE);
17218 }
17219 
17220 /*
17221  * Generate a reset based on an inbound packet, connp is set by caller
17222  * when RST is in response to an unexpected inbound packet for which
17223  * there is active tcp state in the system.
17224  *
17225  * IPSEC NOTE : Try to send the reply with the same protection as it came
17226  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17227  * That way the packet will go out at the same level of protection as it
17228  * came in with.
17229  */
17230 static void
17231 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17232     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17233 {
17234 	ipha_t		*ipha = NULL;
17235 	ip6_t		*ip6h = NULL;
17236 	ushort_t	len;
17237 	tcpha_t		*tcpha;
17238 	int		i;
17239 	ipaddr_t	v4addr;
17240 	in6_addr_t	v6addr;
17241 	netstack_t	*ns = ipst->ips_netstack;
17242 	tcp_stack_t	*tcps = ns->netstack_tcp;
17243 	ip_xmit_attr_t	ixas, *ixa;
17244 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17245 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17246 	ushort_t	port;
17247 
17248 	if (!tcp_send_rst_chk(tcps)) {
17249 		TCP_STAT(tcps, tcp_rst_unsent);
17250 		freemsg(mp);
17251 		return;
17252 	}
17253 
17254 	/*
17255 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17256 	 * options from the listener. In that case the caller must ensure that
17257 	 * we are running on the listener = connp squeue.
17258 	 *
17259 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17260 	 * we or ip_output_simple might change in the ixa.
17261 	 */
17262 	if (connp != NULL) {
17263 		ASSERT(connp->conn_on_sqp);
17264 
17265 		ixa = conn_get_ixa_exclusive(connp);
17266 		if (ixa == NULL) {
17267 			TCP_STAT(tcps, tcp_rst_unsent);
17268 			freemsg(mp);
17269 			return;
17270 		}
17271 		need_refrele = B_TRUE;
17272 	} else {
17273 		bzero(&ixas, sizeof (ixas));
17274 		ixa = &ixas;
17275 		/*
17276 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17277 		 * packet was for us.
17278 		 */
17279 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17280 		ixa->ixa_protocol = IPPROTO_TCP;
17281 		ixa->ixa_zoneid = ira->ira_zoneid;
17282 		ixa->ixa_ifindex = 0;
17283 		ixa->ixa_ipst = ipst;
17284 		ixa->ixa_cred = kcred;
17285 		ixa->ixa_cpid = NOPID;
17286 	}
17287 
17288 	if (str && tcps->tcps_dbg) {
17289 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17290 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17291 		    "flags 0x%x",
17292 		    str, seq, ack, ctl);
17293 	}
17294 	if (mp->b_datap->db_ref != 1) {
17295 		mblk_t *mp1 = copyb(mp);
17296 		freemsg(mp);
17297 		mp = mp1;
17298 		if (mp == NULL)
17299 			goto done;
17300 	} else if (mp->b_cont) {
17301 		freemsg(mp->b_cont);
17302 		mp->b_cont = NULL;
17303 		DB_CKSUMFLAGS(mp) = 0;
17304 	}
17305 	/*
17306 	 * We skip reversing source route here.
17307 	 * (for now we replace all IP options with EOL)
17308 	 */
17309 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17310 		ipha = (ipha_t *)mp->b_rptr;
17311 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17312 			mp->b_rptr[i] = IPOPT_EOL;
17313 		/*
17314 		 * Make sure that src address isn't flagrantly invalid.
17315 		 * Not all broadcast address checking for the src address
17316 		 * is possible, since we don't know the netmask of the src
17317 		 * addr.  No check for destination address is done, since
17318 		 * IP will not pass up a packet with a broadcast dest
17319 		 * address to TCP.  Similar checks are done below for IPv6.
17320 		 */
17321 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17322 		    CLASSD(ipha->ipha_src)) {
17323 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17324 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17325 			freemsg(mp);
17326 			goto done;
17327 		}
17328 	} else {
17329 		ip6h = (ip6_t *)mp->b_rptr;
17330 
17331 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17332 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17333 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17334 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17335 			freemsg(mp);
17336 			goto done;
17337 		}
17338 
17339 		/* Remove any extension headers assuming partial overlay */
17340 		if (ip_hdr_len > IPV6_HDR_LEN) {
17341 			uint8_t *to;
17342 
17343 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17344 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17345 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17346 			ip_hdr_len = IPV6_HDR_LEN;
17347 			ip6h = (ip6_t *)mp->b_rptr;
17348 			ip6h->ip6_nxt = IPPROTO_TCP;
17349 		}
17350 	}
17351 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17352 	if (tcpha->tha_flags & TH_RST) {
17353 		freemsg(mp);
17354 		goto done;
17355 	}
17356 	tcpha->tha_offset_and_reserved = (5 << 4);
17357 	len = ip_hdr_len + sizeof (tcpha_t);
17358 	mp->b_wptr = &mp->b_rptr[len];
17359 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17360 		ipha->ipha_length = htons(len);
17361 		/* Swap addresses */
17362 		v4addr = ipha->ipha_src;
17363 		ipha->ipha_src = ipha->ipha_dst;
17364 		ipha->ipha_dst = v4addr;
17365 		ipha->ipha_ident = 0;
17366 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17367 		ixa->ixa_flags |= IXAF_IS_IPV4;
17368 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17369 	} else {
17370 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17371 		/* Swap addresses */
17372 		v6addr = ip6h->ip6_src;
17373 		ip6h->ip6_src = ip6h->ip6_dst;
17374 		ip6h->ip6_dst = v6addr;
17375 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17376 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17377 
17378 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17379 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17380 			ixa->ixa_scopeid = ira->ira_ruifindex;
17381 		}
17382 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17383 	}
17384 	ixa->ixa_pktlen = len;
17385 
17386 	/* Swap the ports */
17387 	port = tcpha->tha_fport;
17388 	tcpha->tha_fport = tcpha->tha_lport;
17389 	tcpha->tha_lport = port;
17390 
17391 	tcpha->tha_ack = htonl(ack);
17392 	tcpha->tha_seq = htonl(seq);
17393 	tcpha->tha_win = 0;
17394 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17395 	tcpha->tha_flags = (uint8_t)ctl;
17396 	if (ctl & TH_RST) {
17397 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17398 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17399 	}
17400 
17401 	/* Discard any old label */
17402 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17403 		ASSERT(ixa->ixa_tsl != NULL);
17404 		label_rele(ixa->ixa_tsl);
17405 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17406 	}
17407 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17408 
17409 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17410 		/*
17411 		 * Apply IPsec based on how IPsec was applied to
17412 		 * the packet that caused the RST.
17413 		 */
17414 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17415 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17416 			/* Note: mp already consumed and ip_drop_packet done */
17417 			goto done;
17418 		}
17419 	} else {
17420 		/*
17421 		 * This is in clear. The RST message we are building
17422 		 * here should go out in clear, independent of our policy.
17423 		 */
17424 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17425 	}
17426 
17427 	/*
17428 	 * NOTE:  one might consider tracing a TCP packet here, but
17429 	 * this function has no active TCP state and no tcp structure
17430 	 * that has a trace buffer.  If we traced here, we would have
17431 	 * to keep a local trace buffer in tcp_record_trace().
17432 	 */
17433 
17434 	(void) ip_output_simple(mp, ixa);
17435 done:
17436 	ixa_cleanup(ixa);
17437 	if (need_refrele) {
17438 		ASSERT(ixa != &ixas);
17439 		ixa_refrele(ixa);
17440 	}
17441 }
17442 
17443 /*
17444  * Initiate closedown sequence on an active connection.  (May be called as
17445  * writer.)  Return value zero for OK return, non-zero for error return.
17446  */
17447 static int
17448 tcp_xmit_end(tcp_t *tcp)
17449 {
17450 	mblk_t		*mp;
17451 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17452 	iulp_t		uinfo;
17453 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17454 	conn_t		*connp = tcp->tcp_connp;
17455 
17456 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17457 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17458 		/*
17459 		 * Invalid state, only states TCPS_SYN_RCVD,
17460 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17461 		 */
17462 		return (-1);
17463 	}
17464 
17465 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17466 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17467 	/*
17468 	 * If there is nothing more unsent, send the FIN now.
17469 	 * Otherwise, it will go out with the last segment.
17470 	 */
17471 	if (tcp->tcp_unsent == 0) {
17472 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17473 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17474 
17475 		if (mp) {
17476 			tcp_send_data(tcp, mp);
17477 		} else {
17478 			/*
17479 			 * Couldn't allocate msg.  Pretend we got it out.
17480 			 * Wait for rexmit timeout.
17481 			 */
17482 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17483 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17484 		}
17485 
17486 		/*
17487 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17488 		 * changed.
17489 		 */
17490 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17491 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17492 		}
17493 	} else {
17494 		/*
17495 		 * If tcp->tcp_cork is set, then the data will not get sent,
17496 		 * so we have to check that and unset it first.
17497 		 */
17498 		if (tcp->tcp_cork)
17499 			tcp->tcp_cork = B_FALSE;
17500 		tcp_wput_data(tcp, NULL, B_FALSE);
17501 	}
17502 
17503 	/*
17504 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17505 	 * is 0, don't update the cache.
17506 	 */
17507 	if (tcps->tcps_rtt_updates == 0 ||
17508 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17509 		return (0);
17510 
17511 	/*
17512 	 * We do not have a good algorithm to update ssthresh at this time.
17513 	 * So don't do any update.
17514 	 */
17515 	bzero(&uinfo, sizeof (uinfo));
17516 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17517 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17518 
17519 	/*
17520 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17521 	 * if source routed but we don't.
17522 	 */
17523 	if (connp->conn_ipversion == IPV4_VERSION) {
17524 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17525 			return (0);
17526 		}
17527 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17528 	} else {
17529 		uint_t ifindex;
17530 
17531 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17532 		    &tcp->tcp_ip6h->ip6_dst))) {
17533 			return (0);
17534 		}
17535 		ifindex = 0;
17536 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17537 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17538 
17539 			/*
17540 			 * If we are going to create a DCE we'd better have
17541 			 * an ifindex
17542 			 */
17543 			if (ixa->ixa_nce != NULL) {
17544 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17545 				    ill_phyint->phyint_ifindex;
17546 			} else {
17547 				return (0);
17548 			}
17549 		}
17550 
17551 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17552 		    ipst);
17553 	}
17554 	return (0);
17555 }
17556 
17557 /*
17558  * Generate a "no listener here" RST in response to an "unknown" segment.
17559  * connp is set by caller when RST is in response to an unexpected
17560  * inbound packet for which there is active tcp state in the system.
17561  * Note that we are reusing the incoming mp to construct the outgoing RST.
17562  */
17563 void
17564 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17565     conn_t *connp)
17566 {
17567 	uchar_t		*rptr;
17568 	uint32_t	seg_len;
17569 	tcpha_t		*tcpha;
17570 	uint32_t	seg_seq;
17571 	uint32_t	seg_ack;
17572 	uint_t		flags;
17573 	ipha_t 		*ipha;
17574 	ip6_t 		*ip6h;
17575 	boolean_t	policy_present;
17576 	netstack_t	*ns = ipst->ips_netstack;
17577 	tcp_stack_t	*tcps = ns->netstack_tcp;
17578 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17579 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17580 
17581 	TCP_STAT(tcps, tcp_no_listener);
17582 
17583 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17584 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17585 		ipha = (ipha_t *)mp->b_rptr;
17586 		ip6h = NULL;
17587 	} else {
17588 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17589 		ipha = NULL;
17590 		ip6h = (ip6_t *)mp->b_rptr;
17591 	}
17592 
17593 	if (policy_present) {
17594 		/*
17595 		 * The conn_t parameter is NULL because we already know
17596 		 * nobody's home.
17597 		 */
17598 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17599 		    ira, ns);
17600 		if (mp == NULL)
17601 			return;
17602 	}
17603 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17604 		DTRACE_PROBE2(
17605 		    tx__ip__log__error__nolistener__tcp,
17606 		    char *, "Could not reply with RST to mp(1)",
17607 		    mblk_t *, mp);
17608 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17609 		freemsg(mp);
17610 		return;
17611 	}
17612 
17613 	rptr = mp->b_rptr;
17614 
17615 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17616 	seg_seq = ntohl(tcpha->tha_seq);
17617 	seg_ack = ntohl(tcpha->tha_ack);
17618 	flags = tcpha->tha_flags;
17619 
17620 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17621 	if (flags & TH_RST) {
17622 		freemsg(mp);
17623 	} else if (flags & TH_ACK) {
17624 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17625 		    ira, ipst, connp);
17626 	} else {
17627 		if (flags & TH_SYN) {
17628 			seg_len++;
17629 		} else {
17630 			/*
17631 			 * Here we violate the RFC.  Note that a normal
17632 			 * TCP will never send a segment without the ACK
17633 			 * flag, except for RST or SYN segment.  This
17634 			 * segment is neither.  Just drop it on the
17635 			 * floor.
17636 			 */
17637 			freemsg(mp);
17638 			TCP_STAT(tcps, tcp_rst_unsent);
17639 			return;
17640 		}
17641 
17642 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17643 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17644 	}
17645 }
17646 
17647 /*
17648  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17649  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17650  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17651  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17652  * otherwise it will dup partial mblks.)
17653  * Otherwise, an appropriate ACK packet will be generated.  This
17654  * routine is not usually called to send new data for the first time.  It
17655  * is mostly called out of the timer for retransmits, and to generate ACKs.
17656  *
17657  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17658  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17659  * of the original mblk chain will be returned in *offset and *end_mp.
17660  */
17661 mblk_t *
17662 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17663     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17664     boolean_t rexmit)
17665 {
17666 	int	data_length;
17667 	int32_t	off = 0;
17668 	uint_t	flags;
17669 	mblk_t	*mp1;
17670 	mblk_t	*mp2;
17671 	uchar_t	*rptr;
17672 	tcpha_t	*tcpha;
17673 	int32_t	num_sack_blk = 0;
17674 	int32_t	sack_opt_len = 0;
17675 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17676 	conn_t		*connp = tcp->tcp_connp;
17677 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17678 
17679 	/* Allocate for our maximum TCP header + link-level */
17680 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17681 	    BPRI_MED);
17682 	if (!mp1)
17683 		return (NULL);
17684 	data_length = 0;
17685 
17686 	/*
17687 	 * Note that tcp_mss has been adjusted to take into account the
17688 	 * timestamp option if applicable.  Because SACK options do not
17689 	 * appear in every TCP segments and they are of variable lengths,
17690 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17691 	 * the actual segment length when we need to send a segment which
17692 	 * includes SACK options.
17693 	 */
17694 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17695 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17696 		    tcp->tcp_num_sack_blk);
17697 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17698 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17699 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17700 			max_to_send -= sack_opt_len;
17701 	}
17702 
17703 	if (offset != NULL) {
17704 		off = *offset;
17705 		/* We use offset as an indicator that end_mp is not NULL. */
17706 		*end_mp = NULL;
17707 	}
17708 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17709 		/* This could be faster with cooperation from downstream */
17710 		if (mp2 != mp1 && !sendall &&
17711 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17712 		    max_to_send)
17713 			/*
17714 			 * Don't send the next mblk since the whole mblk
17715 			 * does not fit.
17716 			 */
17717 			break;
17718 		mp2->b_cont = dupb(mp);
17719 		mp2 = mp2->b_cont;
17720 		if (!mp2) {
17721 			freemsg(mp1);
17722 			return (NULL);
17723 		}
17724 		mp2->b_rptr += off;
17725 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17726 		    (uintptr_t)INT_MAX);
17727 
17728 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17729 		if (data_length > max_to_send) {
17730 			mp2->b_wptr -= data_length - max_to_send;
17731 			data_length = max_to_send;
17732 			off = mp2->b_wptr - mp->b_rptr;
17733 			break;
17734 		} else {
17735 			off = 0;
17736 		}
17737 	}
17738 	if (offset != NULL) {
17739 		*offset = off;
17740 		*end_mp = mp;
17741 	}
17742 	if (seg_len != NULL) {
17743 		*seg_len = data_length;
17744 	}
17745 
17746 	/* Update the latest receive window size in TCP header. */
17747 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17748 
17749 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17750 	mp1->b_rptr = rptr;
17751 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17752 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17753 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17754 	tcpha->tha_seq = htonl(seq);
17755 
17756 	/*
17757 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17758 	 * that this function was called from tcp_wput_data. Thus, when called
17759 	 * to retransmit data the setting of the PUSH bit may appear some
17760 	 * what random in that it might get set when it should not. This
17761 	 * should not pose any performance issues.
17762 	 */
17763 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17764 	    tcp->tcp_unsent == data_length)) {
17765 		flags = TH_ACK | TH_PUSH;
17766 	} else {
17767 		flags = TH_ACK;
17768 	}
17769 
17770 	if (tcp->tcp_ecn_ok) {
17771 		if (tcp->tcp_ecn_echo_on)
17772 			flags |= TH_ECE;
17773 
17774 		/*
17775 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17776 		 * There is no TCP flow control for non-data segments, and
17777 		 * only data segment is transmitted reliably.
17778 		 */
17779 		if (data_length > 0 && !rexmit) {
17780 			SET_ECT(tcp, rptr);
17781 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17782 				flags |= TH_CWR;
17783 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17784 			}
17785 		}
17786 	}
17787 
17788 	if (tcp->tcp_valid_bits) {
17789 		uint32_t u1;
17790 
17791 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17792 		    seq == tcp->tcp_iss) {
17793 			uchar_t	*wptr;
17794 
17795 			/*
17796 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17797 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17798 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17799 			 * our SYN is not ack'ed but the app closes this
17800 			 * TCP connection.
17801 			 */
17802 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17803 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17804 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17805 
17806 			/*
17807 			 * Tack on the MSS option.  It is always needed
17808 			 * for both active and passive open.
17809 			 *
17810 			 * MSS option value should be interface MTU - MIN
17811 			 * TCP/IP header according to RFC 793 as it means
17812 			 * the maximum segment size TCP can receive.  But
17813 			 * to get around some broken middle boxes/end hosts
17814 			 * out there, we allow the option value to be the
17815 			 * same as the MSS option size on the peer side.
17816 			 * In this way, the other side will not send
17817 			 * anything larger than they can receive.
17818 			 *
17819 			 * Note that for SYN_SENT state, the ndd param
17820 			 * tcp_use_smss_as_mss_opt has no effect as we
17821 			 * don't know the peer's MSS option value. So
17822 			 * the only case we need to take care of is in
17823 			 * SYN_RCVD state, which is done later.
17824 			 */
17825 			wptr = mp1->b_wptr;
17826 			wptr[0] = TCPOPT_MAXSEG;
17827 			wptr[1] = TCPOPT_MAXSEG_LEN;
17828 			wptr += 2;
17829 			u1 = tcp->tcp_initial_pmtu -
17830 			    (connp->conn_ipversion == IPV4_VERSION ?
17831 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17832 			    TCP_MIN_HEADER_LENGTH;
17833 			U16_TO_BE16(u1, wptr);
17834 			mp1->b_wptr = wptr + 2;
17835 			/* Update the offset to cover the additional word */
17836 			tcpha->tha_offset_and_reserved += (1 << 4);
17837 
17838 			/*
17839 			 * Note that the following way of filling in
17840 			 * TCP options are not optimal.  Some NOPs can
17841 			 * be saved.  But there is no need at this time
17842 			 * to optimize it.  When it is needed, we will
17843 			 * do it.
17844 			 */
17845 			switch (tcp->tcp_state) {
17846 			case TCPS_SYN_SENT:
17847 				flags = TH_SYN;
17848 
17849 				if (tcp->tcp_snd_ts_ok) {
17850 					uint32_t llbolt =
17851 					    (uint32_t)LBOLT_FASTPATH;
17852 
17853 					wptr = mp1->b_wptr;
17854 					wptr[0] = TCPOPT_NOP;
17855 					wptr[1] = TCPOPT_NOP;
17856 					wptr[2] = TCPOPT_TSTAMP;
17857 					wptr[3] = TCPOPT_TSTAMP_LEN;
17858 					wptr += 4;
17859 					U32_TO_BE32(llbolt, wptr);
17860 					wptr += 4;
17861 					ASSERT(tcp->tcp_ts_recent == 0);
17862 					U32_TO_BE32(0L, wptr);
17863 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17864 					tcpha->tha_offset_and_reserved +=
17865 					    (3 << 4);
17866 				}
17867 
17868 				/*
17869 				 * Set up all the bits to tell other side
17870 				 * we are ECN capable.
17871 				 */
17872 				if (tcp->tcp_ecn_ok) {
17873 					flags |= (TH_ECE | TH_CWR);
17874 				}
17875 				break;
17876 			case TCPS_SYN_RCVD:
17877 				flags |= TH_SYN;
17878 
17879 				/*
17880 				 * Reset the MSS option value to be SMSS
17881 				 * We should probably add back the bytes
17882 				 * for timestamp option and IPsec.  We
17883 				 * don't do that as this is a workaround
17884 				 * for broken middle boxes/end hosts, it
17885 				 * is better for us to be more cautious.
17886 				 * They may not take these things into
17887 				 * account in their SMSS calculation.  Thus
17888 				 * the peer's calculated SMSS may be smaller
17889 				 * than what it can be.  This should be OK.
17890 				 */
17891 				if (tcps->tcps_use_smss_as_mss_opt) {
17892 					u1 = tcp->tcp_mss;
17893 					U16_TO_BE16(u1, wptr);
17894 				}
17895 
17896 				/*
17897 				 * If the other side is ECN capable, reply
17898 				 * that we are also ECN capable.
17899 				 */
17900 				if (tcp->tcp_ecn_ok)
17901 					flags |= TH_ECE;
17902 				break;
17903 			default:
17904 				/*
17905 				 * The above ASSERT() makes sure that this
17906 				 * must be FIN-WAIT-1 state.  Our SYN has
17907 				 * not been ack'ed so retransmit it.
17908 				 */
17909 				flags |= TH_SYN;
17910 				break;
17911 			}
17912 
17913 			if (tcp->tcp_snd_ws_ok) {
17914 				wptr = mp1->b_wptr;
17915 				wptr[0] =  TCPOPT_NOP;
17916 				wptr[1] =  TCPOPT_WSCALE;
17917 				wptr[2] =  TCPOPT_WS_LEN;
17918 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17919 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17920 				tcpha->tha_offset_and_reserved += (1 << 4);
17921 			}
17922 
17923 			if (tcp->tcp_snd_sack_ok) {
17924 				wptr = mp1->b_wptr;
17925 				wptr[0] = TCPOPT_NOP;
17926 				wptr[1] = TCPOPT_NOP;
17927 				wptr[2] = TCPOPT_SACK_PERMITTED;
17928 				wptr[3] = TCPOPT_SACK_OK_LEN;
17929 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17930 				tcpha->tha_offset_and_reserved += (1 << 4);
17931 			}
17932 
17933 			/* allocb() of adequate mblk assures space */
17934 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17935 			    (uintptr_t)INT_MAX);
17936 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17937 			/*
17938 			 * Get IP set to checksum on our behalf
17939 			 * Include the adjustment for a source route if any.
17940 			 */
17941 			u1 += connp->conn_sum;
17942 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17943 			tcpha->tha_sum = htons(u1);
17944 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17945 		}
17946 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17947 		    (seq + data_length) == tcp->tcp_fss) {
17948 			if (!tcp->tcp_fin_acked) {
17949 				flags |= TH_FIN;
17950 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17951 			}
17952 			if (!tcp->tcp_fin_sent) {
17953 				tcp->tcp_fin_sent = B_TRUE;
17954 				switch (tcp->tcp_state) {
17955 				case TCPS_SYN_RCVD:
17956 				case TCPS_ESTABLISHED:
17957 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17958 					break;
17959 				case TCPS_CLOSE_WAIT:
17960 					tcp->tcp_state = TCPS_LAST_ACK;
17961 					break;
17962 				}
17963 				if (tcp->tcp_suna == tcp->tcp_snxt)
17964 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17965 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17966 			}
17967 		}
17968 		/*
17969 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17970 		 * is smaller than seq, u1 will become a very huge value.
17971 		 * So the comparison will fail.  Also note that tcp_urp
17972 		 * should be positive, see RFC 793 page 17.
17973 		 */
17974 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17975 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17976 		    u1 < (uint32_t)(64 * 1024)) {
17977 			flags |= TH_URG;
17978 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17979 			tcpha->tha_urp = htons(u1);
17980 		}
17981 	}
17982 	tcpha->tha_flags = (uchar_t)flags;
17983 	tcp->tcp_rack = tcp->tcp_rnxt;
17984 	tcp->tcp_rack_cnt = 0;
17985 
17986 	if (tcp->tcp_snd_ts_ok) {
17987 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17988 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17989 
17990 			U32_TO_BE32(llbolt,
17991 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17992 			U32_TO_BE32(tcp->tcp_ts_recent,
17993 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17994 		}
17995 	}
17996 
17997 	if (num_sack_blk > 0) {
17998 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17999 		sack_blk_t *tmp;
18000 		int32_t	i;
18001 
18002 		wptr[0] = TCPOPT_NOP;
18003 		wptr[1] = TCPOPT_NOP;
18004 		wptr[2] = TCPOPT_SACK;
18005 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18006 		    sizeof (sack_blk_t);
18007 		wptr += TCPOPT_REAL_SACK_LEN;
18008 
18009 		tmp = tcp->tcp_sack_list;
18010 		for (i = 0; i < num_sack_blk; i++) {
18011 			U32_TO_BE32(tmp[i].begin, wptr);
18012 			wptr += sizeof (tcp_seq);
18013 			U32_TO_BE32(tmp[i].end, wptr);
18014 			wptr += sizeof (tcp_seq);
18015 		}
18016 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
18017 	}
18018 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
18019 	data_length += (int)(mp1->b_wptr - rptr);
18020 
18021 	ixa->ixa_pktlen = data_length;
18022 
18023 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
18024 		((ipha_t *)rptr)->ipha_length = htons(data_length);
18025 	} else {
18026 		ip6_t *ip6 = (ip6_t *)rptr;
18027 
18028 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
18029 	}
18030 
18031 	/*
18032 	 * Prime pump for IP
18033 	 * Include the adjustment for a source route if any.
18034 	 */
18035 	data_length -= ixa->ixa_ip_hdr_length;
18036 	data_length += connp->conn_sum;
18037 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
18038 	tcpha->tha_sum = htons(data_length);
18039 	if (tcp->tcp_ip_forward_progress) {
18040 		tcp->tcp_ip_forward_progress = B_FALSE;
18041 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18042 	} else {
18043 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18044 	}
18045 	return (mp1);
18046 }
18047 
18048 /* This function handles the push timeout. */
18049 void
18050 tcp_push_timer(void *arg)
18051 {
18052 	conn_t	*connp = (conn_t *)arg;
18053 	tcp_t *tcp = connp->conn_tcp;
18054 
18055 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
18056 
18057 	ASSERT(tcp->tcp_listener == NULL);
18058 
18059 	ASSERT(!IPCL_IS_NONSTR(connp));
18060 
18061 	tcp->tcp_push_tid = 0;
18062 
18063 	if (tcp->tcp_rcv_list != NULL &&
18064 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
18065 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
18066 }
18067 
18068 /*
18069  * This function handles delayed ACK timeout.
18070  */
18071 static void
18072 tcp_ack_timer(void *arg)
18073 {
18074 	conn_t	*connp = (conn_t *)arg;
18075 	tcp_t *tcp = connp->conn_tcp;
18076 	mblk_t *mp;
18077 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18078 
18079 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
18080 
18081 	tcp->tcp_ack_tid = 0;
18082 
18083 	if (tcp->tcp_fused)
18084 		return;
18085 
18086 	/*
18087 	 * Do not send ACK if there is no outstanding unack'ed data.
18088 	 */
18089 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
18090 		return;
18091 	}
18092 
18093 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
18094 		/*
18095 		 * Make sure we don't allow deferred ACKs to result in
18096 		 * timer-based ACKing.  If we have held off an ACK
18097 		 * when there was more than an mss here, and the timer
18098 		 * goes off, we have to worry about the possibility
18099 		 * that the sender isn't doing slow-start, or is out
18100 		 * of step with us for some other reason.  We fall
18101 		 * permanently back in the direction of
18102 		 * ACK-every-other-packet as suggested in RFC 1122.
18103 		 */
18104 		if (tcp->tcp_rack_abs_max > 2)
18105 			tcp->tcp_rack_abs_max--;
18106 		tcp->tcp_rack_cur_max = 2;
18107 	}
18108 	mp = tcp_ack_mp(tcp);
18109 
18110 	if (mp != NULL) {
18111 		BUMP_LOCAL(tcp->tcp_obsegs);
18112 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18113 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18114 		tcp_send_data(tcp, mp);
18115 	}
18116 }
18117 
18118 
18119 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18120 static mblk_t *
18121 tcp_ack_mp(tcp_t *tcp)
18122 {
18123 	uint32_t	seq_no;
18124 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18125 	conn_t		*connp = tcp->tcp_connp;
18126 
18127 	/*
18128 	 * There are a few cases to be considered while setting the sequence no.
18129 	 * Essentially, we can come here while processing an unacceptable pkt
18130 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18131 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18132 	 * If we are here for a zero window probe, stick with suna. In all
18133 	 * other cases, we check if suna + swnd encompasses snxt and set
18134 	 * the sequence number to snxt, if so. If snxt falls outside the
18135 	 * window (the receiver probably shrunk its window), we will go with
18136 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18137 	 * receiver.
18138 	 */
18139 	if (tcp->tcp_zero_win_probe) {
18140 		seq_no = tcp->tcp_suna;
18141 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18142 		ASSERT(tcp->tcp_swnd == 0);
18143 		seq_no = tcp->tcp_snxt;
18144 	} else {
18145 		seq_no = SEQ_GT(tcp->tcp_snxt,
18146 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18147 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18148 	}
18149 
18150 	if (tcp->tcp_valid_bits) {
18151 		/*
18152 		 * For the complex case where we have to send some
18153 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18154 		 */
18155 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18156 		    NULL, B_FALSE));
18157 	} else {
18158 		/* Generate a simple ACK */
18159 		int	data_length;
18160 		uchar_t	*rptr;
18161 		tcpha_t	*tcpha;
18162 		mblk_t	*mp1;
18163 		int32_t	total_hdr_len;
18164 		int32_t	tcp_hdr_len;
18165 		int32_t	num_sack_blk = 0;
18166 		int32_t sack_opt_len;
18167 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18168 
18169 		/*
18170 		 * Allocate space for TCP + IP headers
18171 		 * and link-level header
18172 		 */
18173 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18174 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18175 			    tcp->tcp_num_sack_blk);
18176 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18177 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18178 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18179 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18180 		} else {
18181 			total_hdr_len = connp->conn_ht_iphc_len;
18182 			tcp_hdr_len = connp->conn_ht_ulp_len;
18183 		}
18184 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18185 		if (!mp1)
18186 			return (NULL);
18187 
18188 		/* Update the latest receive window size in TCP header. */
18189 		tcp->tcp_tcpha->tha_win =
18190 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18191 		/* copy in prototype TCP + IP header */
18192 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18193 		mp1->b_rptr = rptr;
18194 		mp1->b_wptr = rptr + total_hdr_len;
18195 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18196 
18197 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18198 
18199 		/* Set the TCP sequence number. */
18200 		tcpha->tha_seq = htonl(seq_no);
18201 
18202 		/* Set up the TCP flag field. */
18203 		tcpha->tha_flags = (uchar_t)TH_ACK;
18204 		if (tcp->tcp_ecn_echo_on)
18205 			tcpha->tha_flags |= TH_ECE;
18206 
18207 		tcp->tcp_rack = tcp->tcp_rnxt;
18208 		tcp->tcp_rack_cnt = 0;
18209 
18210 		/* fill in timestamp option if in use */
18211 		if (tcp->tcp_snd_ts_ok) {
18212 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18213 
18214 			U32_TO_BE32(llbolt,
18215 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18216 			U32_TO_BE32(tcp->tcp_ts_recent,
18217 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18218 		}
18219 
18220 		/* Fill in SACK options */
18221 		if (num_sack_blk > 0) {
18222 			uchar_t *wptr = (uchar_t *)tcpha +
18223 			    connp->conn_ht_ulp_len;
18224 			sack_blk_t *tmp;
18225 			int32_t	i;
18226 
18227 			wptr[0] = TCPOPT_NOP;
18228 			wptr[1] = TCPOPT_NOP;
18229 			wptr[2] = TCPOPT_SACK;
18230 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18231 			    sizeof (sack_blk_t);
18232 			wptr += TCPOPT_REAL_SACK_LEN;
18233 
18234 			tmp = tcp->tcp_sack_list;
18235 			for (i = 0; i < num_sack_blk; i++) {
18236 				U32_TO_BE32(tmp[i].begin, wptr);
18237 				wptr += sizeof (tcp_seq);
18238 				U32_TO_BE32(tmp[i].end, wptr);
18239 				wptr += sizeof (tcp_seq);
18240 			}
18241 			tcpha->tha_offset_and_reserved +=
18242 			    ((num_sack_blk * 2 + 1) << 4);
18243 		}
18244 
18245 		ixa->ixa_pktlen = total_hdr_len;
18246 
18247 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18248 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18249 		} else {
18250 			ip6_t *ip6 = (ip6_t *)rptr;
18251 
18252 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18253 		}
18254 
18255 		/*
18256 		 * Prime pump for checksum calculation in IP.  Include the
18257 		 * adjustment for a source route if any.
18258 		 */
18259 		data_length = tcp_hdr_len + connp->conn_sum;
18260 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18261 		tcpha->tha_sum = htons(data_length);
18262 
18263 		if (tcp->tcp_ip_forward_progress) {
18264 			tcp->tcp_ip_forward_progress = B_FALSE;
18265 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18266 		} else {
18267 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18268 		}
18269 		return (mp1);
18270 	}
18271 }
18272 
18273 /*
18274  * Hash list insertion routine for tcp_t structures. Each hash bucket
18275  * contains a list of tcp_t entries, and each entry is bound to a unique
18276  * port. If there are multiple tcp_t's that are bound to the same port, then
18277  * one of them will be linked into the hash bucket list, and the rest will
18278  * hang off of that one entry. For each port, entries bound to a specific IP
18279  * address will be inserted before those those bound to INADDR_ANY.
18280  */
18281 static void
18282 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18283 {
18284 	tcp_t	**tcpp;
18285 	tcp_t	*tcpnext;
18286 	tcp_t	*tcphash;
18287 	conn_t	*connp = tcp->tcp_connp;
18288 	conn_t	*connext;
18289 
18290 	if (tcp->tcp_ptpbhn != NULL) {
18291 		ASSERT(!caller_holds_lock);
18292 		tcp_bind_hash_remove(tcp);
18293 	}
18294 	tcpp = &tbf->tf_tcp;
18295 	if (!caller_holds_lock) {
18296 		mutex_enter(&tbf->tf_lock);
18297 	} else {
18298 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18299 	}
18300 	tcphash = tcpp[0];
18301 	tcpnext = NULL;
18302 	if (tcphash != NULL) {
18303 		/* Look for an entry using the same port */
18304 		while ((tcphash = tcpp[0]) != NULL &&
18305 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18306 			tcpp = &(tcphash->tcp_bind_hash);
18307 
18308 		/* The port was not found, just add to the end */
18309 		if (tcphash == NULL)
18310 			goto insert;
18311 
18312 		/*
18313 		 * OK, there already exists an entry bound to the
18314 		 * same port.
18315 		 *
18316 		 * If the new tcp bound to the INADDR_ANY address
18317 		 * and the first one in the list is not bound to
18318 		 * INADDR_ANY we skip all entries until we find the
18319 		 * first one bound to INADDR_ANY.
18320 		 * This makes sure that applications binding to a
18321 		 * specific address get preference over those binding to
18322 		 * INADDR_ANY.
18323 		 */
18324 		tcpnext = tcphash;
18325 		connext = tcpnext->tcp_connp;
18326 		tcphash = NULL;
18327 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18328 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18329 			while ((tcpnext = tcpp[0]) != NULL) {
18330 				connext = tcpnext->tcp_connp;
18331 				if (!V6_OR_V4_INADDR_ANY(
18332 				    connext->conn_bound_addr_v6))
18333 					tcpp = &(tcpnext->tcp_bind_hash_port);
18334 				else
18335 					break;
18336 			}
18337 			if (tcpnext != NULL) {
18338 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18339 				tcphash = tcpnext->tcp_bind_hash;
18340 				if (tcphash != NULL) {
18341 					tcphash->tcp_ptpbhn =
18342 					    &(tcp->tcp_bind_hash);
18343 					tcpnext->tcp_bind_hash = NULL;
18344 				}
18345 			}
18346 		} else {
18347 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18348 			tcphash = tcpnext->tcp_bind_hash;
18349 			if (tcphash != NULL) {
18350 				tcphash->tcp_ptpbhn =
18351 				    &(tcp->tcp_bind_hash);
18352 				tcpnext->tcp_bind_hash = NULL;
18353 			}
18354 		}
18355 	}
18356 insert:
18357 	tcp->tcp_bind_hash_port = tcpnext;
18358 	tcp->tcp_bind_hash = tcphash;
18359 	tcp->tcp_ptpbhn = tcpp;
18360 	tcpp[0] = tcp;
18361 	if (!caller_holds_lock)
18362 		mutex_exit(&tbf->tf_lock);
18363 }
18364 
18365 /*
18366  * Hash list removal routine for tcp_t structures.
18367  */
18368 static void
18369 tcp_bind_hash_remove(tcp_t *tcp)
18370 {
18371 	tcp_t	*tcpnext;
18372 	kmutex_t *lockp;
18373 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18374 	conn_t		*connp = tcp->tcp_connp;
18375 
18376 	if (tcp->tcp_ptpbhn == NULL)
18377 		return;
18378 
18379 	/*
18380 	 * Extract the lock pointer in case there are concurrent
18381 	 * hash_remove's for this instance.
18382 	 */
18383 	ASSERT(connp->conn_lport != 0);
18384 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18385 	    connp->conn_lport)].tf_lock;
18386 
18387 	ASSERT(lockp != NULL);
18388 	mutex_enter(lockp);
18389 	if (tcp->tcp_ptpbhn) {
18390 		tcpnext = tcp->tcp_bind_hash_port;
18391 		if (tcpnext != NULL) {
18392 			tcp->tcp_bind_hash_port = NULL;
18393 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18394 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18395 			if (tcpnext->tcp_bind_hash != NULL) {
18396 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18397 				    &(tcpnext->tcp_bind_hash);
18398 				tcp->tcp_bind_hash = NULL;
18399 			}
18400 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18401 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18402 			tcp->tcp_bind_hash = NULL;
18403 		}
18404 		*tcp->tcp_ptpbhn = tcpnext;
18405 		tcp->tcp_ptpbhn = NULL;
18406 	}
18407 	mutex_exit(lockp);
18408 }
18409 
18410 
18411 /*
18412  * Hash list lookup routine for tcp_t structures.
18413  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18414  */
18415 static tcp_t *
18416 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18417 {
18418 	tf_t	*tf;
18419 	tcp_t	*tcp;
18420 
18421 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18422 	mutex_enter(&tf->tf_lock);
18423 	for (tcp = tf->tf_tcp; tcp != NULL;
18424 	    tcp = tcp->tcp_acceptor_hash) {
18425 		if (tcp->tcp_acceptor_id == id) {
18426 			CONN_INC_REF(tcp->tcp_connp);
18427 			mutex_exit(&tf->tf_lock);
18428 			return (tcp);
18429 		}
18430 	}
18431 	mutex_exit(&tf->tf_lock);
18432 	return (NULL);
18433 }
18434 
18435 
18436 /*
18437  * Hash list insertion routine for tcp_t structures.
18438  */
18439 void
18440 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18441 {
18442 	tf_t	*tf;
18443 	tcp_t	**tcpp;
18444 	tcp_t	*tcpnext;
18445 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18446 
18447 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18448 
18449 	if (tcp->tcp_ptpahn != NULL)
18450 		tcp_acceptor_hash_remove(tcp);
18451 	tcpp = &tf->tf_tcp;
18452 	mutex_enter(&tf->tf_lock);
18453 	tcpnext = tcpp[0];
18454 	if (tcpnext)
18455 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18456 	tcp->tcp_acceptor_hash = tcpnext;
18457 	tcp->tcp_ptpahn = tcpp;
18458 	tcpp[0] = tcp;
18459 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18460 	mutex_exit(&tf->tf_lock);
18461 }
18462 
18463 /*
18464  * Hash list removal routine for tcp_t structures.
18465  */
18466 static void
18467 tcp_acceptor_hash_remove(tcp_t *tcp)
18468 {
18469 	tcp_t	*tcpnext;
18470 	kmutex_t *lockp;
18471 
18472 	/*
18473 	 * Extract the lock pointer in case there are concurrent
18474 	 * hash_remove's for this instance.
18475 	 */
18476 	lockp = tcp->tcp_acceptor_lockp;
18477 
18478 	if (tcp->tcp_ptpahn == NULL)
18479 		return;
18480 
18481 	ASSERT(lockp != NULL);
18482 	mutex_enter(lockp);
18483 	if (tcp->tcp_ptpahn) {
18484 		tcpnext = tcp->tcp_acceptor_hash;
18485 		if (tcpnext) {
18486 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18487 			tcp->tcp_acceptor_hash = NULL;
18488 		}
18489 		*tcp->tcp_ptpahn = tcpnext;
18490 		tcp->tcp_ptpahn = NULL;
18491 	}
18492 	mutex_exit(lockp);
18493 	tcp->tcp_acceptor_lockp = NULL;
18494 }
18495 
18496 /*
18497  * Type three generator adapted from the random() function in 4.4 BSD:
18498  */
18499 
18500 /*
18501  * Copyright (c) 1983, 1993
18502  *	The Regents of the University of California.  All rights reserved.
18503  *
18504  * Redistribution and use in source and binary forms, with or without
18505  * modification, are permitted provided that the following conditions
18506  * are met:
18507  * 1. Redistributions of source code must retain the above copyright
18508  *    notice, this list of conditions and the following disclaimer.
18509  * 2. Redistributions in binary form must reproduce the above copyright
18510  *    notice, this list of conditions and the following disclaimer in the
18511  *    documentation and/or other materials provided with the distribution.
18512  * 3. All advertising materials mentioning features or use of this software
18513  *    must display the following acknowledgement:
18514  *	This product includes software developed by the University of
18515  *	California, Berkeley and its contributors.
18516  * 4. Neither the name of the University nor the names of its contributors
18517  *    may be used to endorse or promote products derived from this software
18518  *    without specific prior written permission.
18519  *
18520  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18521  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18522  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18523  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18524  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18525  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18526  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18527  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18528  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18529  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18530  * SUCH DAMAGE.
18531  */
18532 
18533 /* Type 3 -- x**31 + x**3 + 1 */
18534 #define	DEG_3		31
18535 #define	SEP_3		3
18536 
18537 
18538 /* Protected by tcp_random_lock */
18539 static int tcp_randtbl[DEG_3 + 1];
18540 
18541 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18542 static int *tcp_random_rptr = &tcp_randtbl[1];
18543 
18544 static int *tcp_random_state = &tcp_randtbl[1];
18545 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18546 
18547 kmutex_t tcp_random_lock;
18548 
18549 void
18550 tcp_random_init(void)
18551 {
18552 	int i;
18553 	hrtime_t hrt;
18554 	time_t wallclock;
18555 	uint64_t result;
18556 
18557 	/*
18558 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18559 	 * a longlong, which may contain resolution down to nanoseconds.
18560 	 * The current time will either be a 32-bit or a 64-bit quantity.
18561 	 * XOR the two together in a 64-bit result variable.
18562 	 * Convert the result to a 32-bit value by multiplying the high-order
18563 	 * 32-bits by the low-order 32-bits.
18564 	 */
18565 
18566 	hrt = gethrtime();
18567 	(void) drv_getparm(TIME, &wallclock);
18568 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18569 	mutex_enter(&tcp_random_lock);
18570 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18571 	    (result & 0xffffffff);
18572 
18573 	for (i = 1; i < DEG_3; i++)
18574 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18575 		    + 12345;
18576 	tcp_random_fptr = &tcp_random_state[SEP_3];
18577 	tcp_random_rptr = &tcp_random_state[0];
18578 	mutex_exit(&tcp_random_lock);
18579 	for (i = 0; i < 10 * DEG_3; i++)
18580 		(void) tcp_random();
18581 }
18582 
18583 /*
18584  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18585  * This range is selected to be approximately centered on TCP_ISS / 2,
18586  * and easy to compute. We get this value by generating a 32-bit random
18587  * number, selecting out the high-order 17 bits, and then adding one so
18588  * that we never return zero.
18589  */
18590 int
18591 tcp_random(void)
18592 {
18593 	int i;
18594 
18595 	mutex_enter(&tcp_random_lock);
18596 	*tcp_random_fptr += *tcp_random_rptr;
18597 
18598 	/*
18599 	 * The high-order bits are more random than the low-order bits,
18600 	 * so we select out the high-order 17 bits and add one so that
18601 	 * we never return zero.
18602 	 */
18603 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18604 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18605 		tcp_random_fptr = tcp_random_state;
18606 		++tcp_random_rptr;
18607 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18608 		tcp_random_rptr = tcp_random_state;
18609 
18610 	mutex_exit(&tcp_random_lock);
18611 	return (i);
18612 }
18613 
18614 static int
18615 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18616     int *t_errorp, int *sys_errorp)
18617 {
18618 	int error;
18619 	int is_absreq_failure;
18620 	t_scalar_t *opt_lenp;
18621 	t_scalar_t opt_offset;
18622 	int prim_type;
18623 	struct T_conn_req *tcreqp;
18624 	struct T_conn_res *tcresp;
18625 	cred_t *cr;
18626 
18627 	/*
18628 	 * All Solaris components should pass a db_credp
18629 	 * for this TPI message, hence we ASSERT.
18630 	 * But in case there is some other M_PROTO that looks
18631 	 * like a TPI message sent by some other kernel
18632 	 * component, we check and return an error.
18633 	 */
18634 	cr = msg_getcred(mp, NULL);
18635 	ASSERT(cr != NULL);
18636 	if (cr == NULL)
18637 		return (-1);
18638 
18639 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18640 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18641 	    prim_type == T_CONN_RES);
18642 
18643 	switch (prim_type) {
18644 	case T_CONN_REQ:
18645 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18646 		opt_offset = tcreqp->OPT_offset;
18647 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18648 		break;
18649 	case O_T_CONN_RES:
18650 	case T_CONN_RES:
18651 		tcresp = (struct T_conn_res *)mp->b_rptr;
18652 		opt_offset = tcresp->OPT_offset;
18653 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18654 		break;
18655 	}
18656 
18657 	*t_errorp = 0;
18658 	*sys_errorp = 0;
18659 	*do_disconnectp = 0;
18660 
18661 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18662 	    opt_offset, cr, &tcp_opt_obj,
18663 	    NULL, &is_absreq_failure);
18664 
18665 	switch (error) {
18666 	case  0:		/* no error */
18667 		ASSERT(is_absreq_failure == 0);
18668 		return (0);
18669 	case ENOPROTOOPT:
18670 		*t_errorp = TBADOPT;
18671 		break;
18672 	case EACCES:
18673 		*t_errorp = TACCES;
18674 		break;
18675 	default:
18676 		*t_errorp = TSYSERR; *sys_errorp = error;
18677 		break;
18678 	}
18679 	if (is_absreq_failure != 0) {
18680 		/*
18681 		 * The connection request should get the local ack
18682 		 * T_OK_ACK and then a T_DISCON_IND.
18683 		 */
18684 		*do_disconnectp = 1;
18685 	}
18686 	return (-1);
18687 }
18688 
18689 /*
18690  * Split this function out so that if the secret changes, I'm okay.
18691  *
18692  * Initialize the tcp_iss_cookie and tcp_iss_key.
18693  */
18694 
18695 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18696 
18697 static void
18698 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18699 {
18700 	struct {
18701 		int32_t current_time;
18702 		uint32_t randnum;
18703 		uint16_t pad;
18704 		uint8_t ether[6];
18705 		uint8_t passwd[PASSWD_SIZE];
18706 	} tcp_iss_cookie;
18707 	time_t t;
18708 
18709 	/*
18710 	 * Start with the current absolute time.
18711 	 */
18712 	(void) drv_getparm(TIME, &t);
18713 	tcp_iss_cookie.current_time = t;
18714 
18715 	/*
18716 	 * XXX - Need a more random number per RFC 1750, not this crap.
18717 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18718 	 */
18719 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18720 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18721 
18722 	/*
18723 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18724 	 * as a good template.
18725 	 */
18726 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18727 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18728 
18729 	/*
18730 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18731 	 */
18732 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18733 
18734 	/*
18735 	 * See 4010593 if this section becomes a problem again,
18736 	 * but the local ethernet address is useful here.
18737 	 */
18738 	(void) localetheraddr(NULL,
18739 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18740 
18741 	/*
18742 	 * Hash 'em all together.  The MD5Final is called per-connection.
18743 	 */
18744 	mutex_enter(&tcps->tcps_iss_key_lock);
18745 	MD5Init(&tcps->tcps_iss_key);
18746 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18747 	    sizeof (tcp_iss_cookie));
18748 	mutex_exit(&tcps->tcps_iss_key_lock);
18749 }
18750 
18751 /*
18752  * Set the RFC 1948 pass phrase
18753  */
18754 /* ARGSUSED */
18755 static int
18756 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18757     cred_t *cr)
18758 {
18759 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18760 
18761 	/*
18762 	 * Basically, value contains a new pass phrase.  Pass it along!
18763 	 */
18764 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18765 	return (0);
18766 }
18767 
18768 /* ARGSUSED */
18769 static int
18770 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18771 {
18772 	bzero(buf, sizeof (tcp_sack_info_t));
18773 	return (0);
18774 }
18775 
18776 /*
18777  * Called by IP when IP is loaded into the kernel
18778  */
18779 void
18780 tcp_ddi_g_init(void)
18781 {
18782 	tcp_timercache = kmem_cache_create("tcp_timercache",
18783 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18784 	    NULL, NULL, NULL, NULL, NULL, 0);
18785 
18786 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18787 	    sizeof (tcp_sack_info_t), 0,
18788 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18789 
18790 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18791 
18792 	/* Initialize the random number generator */
18793 	tcp_random_init();
18794 
18795 	/* A single callback independently of how many netstacks we have */
18796 	ip_squeue_init(tcp_squeue_add);
18797 
18798 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18799 
18800 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18801 
18802 	/*
18803 	 * We want to be informed each time a stack is created or
18804 	 * destroyed in the kernel, so we can maintain the
18805 	 * set of tcp_stack_t's.
18806 	 */
18807 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18808 }
18809 
18810 
18811 #define	INET_NAME	"ip"
18812 
18813 /*
18814  * Initialize the TCP stack instance.
18815  */
18816 static void *
18817 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18818 {
18819 	tcp_stack_t	*tcps;
18820 	tcpparam_t	*pa;
18821 	int		i;
18822 	int		error = 0;
18823 	major_t		major;
18824 
18825 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18826 	tcps->tcps_netstack = ns;
18827 
18828 	/* Initialize locks */
18829 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18830 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18831 
18832 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18833 	tcps->tcps_g_epriv_ports[0] = 2049;
18834 	tcps->tcps_g_epriv_ports[1] = 4045;
18835 	tcps->tcps_min_anonpriv_port = 512;
18836 
18837 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18838 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18839 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18840 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18841 
18842 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18843 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18844 		    MUTEX_DEFAULT, NULL);
18845 	}
18846 
18847 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18848 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18849 		    MUTEX_DEFAULT, NULL);
18850 	}
18851 
18852 	/* TCP's IPsec code calls the packet dropper. */
18853 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18854 
18855 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18856 	tcps->tcps_params = pa;
18857 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18858 
18859 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18860 	    A_CNT(lcl_tcp_param_arr), tcps);
18861 
18862 	/*
18863 	 * Note: To really walk the device tree you need the devinfo
18864 	 * pointer to your device which is only available after probe/attach.
18865 	 * The following is safe only because it uses ddi_root_node()
18866 	 */
18867 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18868 	    tcp_opt_obj.odb_opt_arr_cnt);
18869 
18870 	/*
18871 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18872 	 * by the boot scripts.
18873 	 *
18874 	 * Use NULL name, as the name is caught by the new lockstats.
18875 	 *
18876 	 * Initialize with some random, non-guessable string, like the global
18877 	 * T_INFO_ACK.
18878 	 */
18879 
18880 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18881 	    sizeof (tcp_g_t_info_ack), tcps);
18882 
18883 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18884 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18885 
18886 	major = mod_name_to_major(INET_NAME);
18887 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18888 	ASSERT(error == 0);
18889 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18890 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18891 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18892 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18893 
18894 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18895 	tcps->tcps_reclaim = B_FALSE;
18896 	tcps->tcps_reclaim_tid = 0;
18897 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18898 
18899 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18900 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18901 	    offsetof(tcp_listener_t, tl_link));
18902 
18903 	return (tcps);
18904 }
18905 
18906 /*
18907  * Called when the IP module is about to be unloaded.
18908  */
18909 void
18910 tcp_ddi_g_destroy(void)
18911 {
18912 	tcp_g_kstat_fini(tcp_g_kstat);
18913 	tcp_g_kstat = NULL;
18914 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18915 
18916 	mutex_destroy(&tcp_random_lock);
18917 
18918 	kmem_cache_destroy(tcp_timercache);
18919 	kmem_cache_destroy(tcp_sack_info_cache);
18920 
18921 	netstack_unregister(NS_TCP);
18922 }
18923 
18924 /*
18925  * Free the TCP stack instance.
18926  */
18927 static void
18928 tcp_stack_fini(netstackid_t stackid, void *arg)
18929 {
18930 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18931 	int i;
18932 
18933 	freeb(tcps->tcps_ixa_cleanup_mp);
18934 	tcps->tcps_ixa_cleanup_mp = NULL;
18935 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18936 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18937 
18938 	if (tcps->tcps_reclaim_tid != 0)
18939 		(void) untimeout(tcps->tcps_reclaim_tid);
18940 	mutex_destroy(&tcps->tcps_reclaim_lock);
18941 
18942 	tcp_listener_conf_cleanup(tcps);
18943 
18944 	nd_free(&tcps->tcps_g_nd);
18945 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18946 	tcps->tcps_params = NULL;
18947 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18948 	tcps->tcps_wroff_xtra_param = NULL;
18949 
18950 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18951 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18952 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18953 	}
18954 
18955 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18956 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18957 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18958 	}
18959 
18960 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18961 	tcps->tcps_bind_fanout = NULL;
18962 
18963 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18964 	    TCP_ACCEPTOR_FANOUT_SIZE);
18965 	tcps->tcps_acceptor_fanout = NULL;
18966 
18967 	mutex_destroy(&tcps->tcps_iss_key_lock);
18968 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18969 
18970 	ip_drop_unregister(&tcps->tcps_dropper);
18971 
18972 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18973 	tcps->tcps_kstat = NULL;
18974 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18975 
18976 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18977 	tcps->tcps_mibkp = NULL;
18978 
18979 	ldi_ident_release(tcps->tcps_ldi_ident);
18980 	kmem_free(tcps, sizeof (*tcps));
18981 }
18982 
18983 /*
18984  * Generate ISS, taking into account NDD changes may happen halfway through.
18985  * (If the iss is not zero, set it.)
18986  */
18987 
18988 static void
18989 tcp_iss_init(tcp_t *tcp)
18990 {
18991 	MD5_CTX context;
18992 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18993 	uint32_t answer[4];
18994 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18995 	conn_t		*connp = tcp->tcp_connp;
18996 
18997 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18998 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18999 	switch (tcps->tcps_strong_iss) {
19000 	case 2:
19001 		mutex_enter(&tcps->tcps_iss_key_lock);
19002 		context = tcps->tcps_iss_key;
19003 		mutex_exit(&tcps->tcps_iss_key_lock);
19004 		arg.ports = connp->conn_ports;
19005 		arg.src = connp->conn_laddr_v6;
19006 		arg.dst = connp->conn_faddr_v6;
19007 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
19008 		MD5Final((uchar_t *)answer, &context);
19009 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
19010 		/*
19011 		 * Now that we've hashed into a unique per-connection sequence
19012 		 * space, add a random increment per strong_iss == 1.  So I
19013 		 * guess we'll have to...
19014 		 */
19015 		/* FALLTHRU */
19016 	case 1:
19017 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
19018 		break;
19019 	default:
19020 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19021 		break;
19022 	}
19023 	tcp->tcp_valid_bits = TCP_ISS_VALID;
19024 	tcp->tcp_fss = tcp->tcp_iss - 1;
19025 	tcp->tcp_suna = tcp->tcp_iss;
19026 	tcp->tcp_snxt = tcp->tcp_iss + 1;
19027 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
19028 	tcp->tcp_csuna = tcp->tcp_snxt;
19029 }
19030 
19031 /*
19032  * Exported routine for extracting active tcp connection status.
19033  *
19034  * This is used by the Solaris Cluster Networking software to
19035  * gather a list of connections that need to be forwarded to
19036  * specific nodes in the cluster when configuration changes occur.
19037  *
19038  * The callback is invoked for each tcp_t structure from all netstacks,
19039  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
19040  * from the netstack with the specified stack_id. Returning
19041  * non-zero from the callback routine terminates the search.
19042  */
19043 int
19044 cl_tcp_walk_list(netstackid_t stack_id,
19045     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
19046 {
19047 	netstack_handle_t nh;
19048 	netstack_t *ns;
19049 	int ret = 0;
19050 
19051 	if (stack_id >= 0) {
19052 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
19053 			return (EINVAL);
19054 
19055 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19056 		    ns->netstack_tcp);
19057 		netstack_rele(ns);
19058 		return (ret);
19059 	}
19060 
19061 	netstack_next_init(&nh);
19062 	while ((ns = netstack_next(&nh)) != NULL) {
19063 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19064 		    ns->netstack_tcp);
19065 		netstack_rele(ns);
19066 	}
19067 	netstack_next_fini(&nh);
19068 	return (ret);
19069 }
19070 
19071 static int
19072 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
19073     tcp_stack_t *tcps)
19074 {
19075 	tcp_t *tcp;
19076 	cl_tcp_info_t	cl_tcpi;
19077 	connf_t	*connfp;
19078 	conn_t	*connp;
19079 	int	i;
19080 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19081 
19082 	ASSERT(callback != NULL);
19083 
19084 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19085 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19086 		connp = NULL;
19087 
19088 		while ((connp =
19089 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19090 
19091 			tcp = connp->conn_tcp;
19092 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
19093 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
19094 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
19095 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
19096 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
19097 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
19098 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
19099 
19100 			/*
19101 			 * If the callback returns non-zero
19102 			 * we terminate the traversal.
19103 			 */
19104 			if ((*callback)(&cl_tcpi, arg) != 0) {
19105 				CONN_DEC_REF(tcp->tcp_connp);
19106 				return (1);
19107 			}
19108 		}
19109 	}
19110 
19111 	return (0);
19112 }
19113 
19114 /*
19115  * Macros used for accessing the different types of sockaddr
19116  * structures inside a tcp_ioc_abort_conn_t.
19117  */
19118 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19119 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19120 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19121 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19122 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19123 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19124 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19125 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19126 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19127 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19128 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19129 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19130 
19131 /*
19132  * Return the correct error code to mimic the behavior
19133  * of a connection reset.
19134  */
19135 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19136 		switch ((state)) {		\
19137 		case TCPS_SYN_SENT:		\
19138 		case TCPS_SYN_RCVD:		\
19139 			(err) = ECONNREFUSED;	\
19140 			break;			\
19141 		case TCPS_ESTABLISHED:		\
19142 		case TCPS_FIN_WAIT_1:		\
19143 		case TCPS_FIN_WAIT_2:		\
19144 		case TCPS_CLOSE_WAIT:		\
19145 			(err) = ECONNRESET;	\
19146 			break;			\
19147 		case TCPS_CLOSING:		\
19148 		case TCPS_LAST_ACK:		\
19149 		case TCPS_TIME_WAIT:		\
19150 			(err) = 0;		\
19151 			break;			\
19152 		default:			\
19153 			(err) = ENXIO;		\
19154 		}				\
19155 	}
19156 
19157 /*
19158  * Check if a tcp structure matches the info in acp.
19159  */
19160 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19161 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19162 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19163 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19164 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19165 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19166 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19167 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19168 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19169 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19170 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19171 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19172 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19173 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19174 	&(connp)->conn_laddr_v6)) &&				\
19175 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19176 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19177 	&(connp)->conn_faddr_v6)) &&				\
19178 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19179 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19180 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19181 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19182 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19183 	(acp)->ac_end >= (tcp)->tcp_state))
19184 
19185 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19186 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19187 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19188 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19189 
19190 /*
19191  * Build a message containing a tcp_ioc_abort_conn_t structure
19192  * which is filled in with information from acp and tp.
19193  */
19194 static mblk_t *
19195 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19196 {
19197 	mblk_t *mp;
19198 	tcp_ioc_abort_conn_t *tacp;
19199 
19200 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19201 	if (mp == NULL)
19202 		return (NULL);
19203 
19204 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19205 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19206 	    sizeof (uint32_t));
19207 
19208 	tacp->ac_start = acp->ac_start;
19209 	tacp->ac_end = acp->ac_end;
19210 	tacp->ac_zoneid = acp->ac_zoneid;
19211 
19212 	if (acp->ac_local.ss_family == AF_INET) {
19213 		tacp->ac_local.ss_family = AF_INET;
19214 		tacp->ac_remote.ss_family = AF_INET;
19215 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19216 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19217 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19218 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19219 	} else {
19220 		tacp->ac_local.ss_family = AF_INET6;
19221 		tacp->ac_remote.ss_family = AF_INET6;
19222 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19223 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19224 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19225 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19226 	}
19227 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19228 	return (mp);
19229 }
19230 
19231 /*
19232  * Print a tcp_ioc_abort_conn_t structure.
19233  */
19234 static void
19235 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19236 {
19237 	char lbuf[128];
19238 	char rbuf[128];
19239 	sa_family_t af;
19240 	in_port_t lport, rport;
19241 	ushort_t logflags;
19242 
19243 	af = acp->ac_local.ss_family;
19244 
19245 	if (af == AF_INET) {
19246 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19247 		    lbuf, 128);
19248 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19249 		    rbuf, 128);
19250 		lport = ntohs(TCP_AC_V4LPORT(acp));
19251 		rport = ntohs(TCP_AC_V4RPORT(acp));
19252 	} else {
19253 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19254 		    lbuf, 128);
19255 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19256 		    rbuf, 128);
19257 		lport = ntohs(TCP_AC_V6LPORT(acp));
19258 		rport = ntohs(TCP_AC_V6RPORT(acp));
19259 	}
19260 
19261 	logflags = SL_TRACE | SL_NOTE;
19262 	/*
19263 	 * Don't print this message to the console if the operation was done
19264 	 * to a non-global zone.
19265 	 */
19266 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19267 		logflags |= SL_CONSOLE;
19268 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19269 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19270 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19271 	    acp->ac_start, acp->ac_end);
19272 }
19273 
19274 /*
19275  * Called using SQ_FILL when a message built using
19276  * tcp_ioctl_abort_build_msg is put into a queue.
19277  * Note that when we get here there is no wildcard in acp any more.
19278  */
19279 /* ARGSUSED2 */
19280 static void
19281 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19282     ip_recv_attr_t *dummy)
19283 {
19284 	conn_t			*connp = (conn_t *)arg;
19285 	tcp_t			*tcp = connp->conn_tcp;
19286 	tcp_ioc_abort_conn_t	*acp;
19287 
19288 	/*
19289 	 * Don't accept any input on a closed tcp as this TCP logically does
19290 	 * not exist on the system. Don't proceed further with this TCP.
19291 	 * For eg. this packet could trigger another close of this tcp
19292 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19293 	 * tcp_clean_death / tcp_closei_local must be called at most once
19294 	 * on a TCP.
19295 	 */
19296 	if (tcp->tcp_state == TCPS_CLOSED ||
19297 	    tcp->tcp_state == TCPS_BOUND) {
19298 		freemsg(mp);
19299 		return;
19300 	}
19301 
19302 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19303 	if (tcp->tcp_state <= acp->ac_end) {
19304 		/*
19305 		 * If we get here, we are already on the correct
19306 		 * squeue. This ioctl follows the following path
19307 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19308 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19309 		 * different squeue)
19310 		 */
19311 		int errcode;
19312 
19313 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19314 		(void) tcp_clean_death(tcp, errcode, 26);
19315 	}
19316 	freemsg(mp);
19317 }
19318 
19319 /*
19320  * Abort all matching connections on a hash chain.
19321  */
19322 static int
19323 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19324     boolean_t exact, tcp_stack_t *tcps)
19325 {
19326 	int nmatch, err = 0;
19327 	tcp_t *tcp;
19328 	MBLKP mp, last, listhead = NULL;
19329 	conn_t	*tconnp;
19330 	connf_t	*connfp;
19331 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19332 
19333 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19334 
19335 startover:
19336 	nmatch = 0;
19337 
19338 	mutex_enter(&connfp->connf_lock);
19339 	for (tconnp = connfp->connf_head; tconnp != NULL;
19340 	    tconnp = tconnp->conn_next) {
19341 		tcp = tconnp->conn_tcp;
19342 		/*
19343 		 * We are missing a check on sin6_scope_id for linklocals here,
19344 		 * but current usage is just for aborting based on zoneid
19345 		 * for shared-IP zones.
19346 		 */
19347 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19348 			CONN_INC_REF(tconnp);
19349 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19350 			if (mp == NULL) {
19351 				err = ENOMEM;
19352 				CONN_DEC_REF(tconnp);
19353 				break;
19354 			}
19355 			mp->b_prev = (mblk_t *)tcp;
19356 
19357 			if (listhead == NULL) {
19358 				listhead = mp;
19359 				last = mp;
19360 			} else {
19361 				last->b_next = mp;
19362 				last = mp;
19363 			}
19364 			nmatch++;
19365 			if (exact)
19366 				break;
19367 		}
19368 
19369 		/* Avoid holding lock for too long. */
19370 		if (nmatch >= 500)
19371 			break;
19372 	}
19373 	mutex_exit(&connfp->connf_lock);
19374 
19375 	/* Pass mp into the correct tcp */
19376 	while ((mp = listhead) != NULL) {
19377 		listhead = listhead->b_next;
19378 		tcp = (tcp_t *)mp->b_prev;
19379 		mp->b_next = mp->b_prev = NULL;
19380 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19381 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19382 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19383 	}
19384 
19385 	*count += nmatch;
19386 	if (nmatch >= 500 && err == 0)
19387 		goto startover;
19388 	return (err);
19389 }
19390 
19391 /*
19392  * Abort all connections that matches the attributes specified in acp.
19393  */
19394 static int
19395 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19396 {
19397 	sa_family_t af;
19398 	uint32_t  ports;
19399 	uint16_t *pports;
19400 	int err = 0, count = 0;
19401 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19402 	int index = -1;
19403 	ushort_t logflags;
19404 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19405 
19406 	af = acp->ac_local.ss_family;
19407 
19408 	if (af == AF_INET) {
19409 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19410 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19411 			pports = (uint16_t *)&ports;
19412 			pports[1] = TCP_AC_V4LPORT(acp);
19413 			pports[0] = TCP_AC_V4RPORT(acp);
19414 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19415 		}
19416 	} else {
19417 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19418 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19419 			pports = (uint16_t *)&ports;
19420 			pports[1] = TCP_AC_V6LPORT(acp);
19421 			pports[0] = TCP_AC_V6RPORT(acp);
19422 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19423 		}
19424 	}
19425 
19426 	/*
19427 	 * For cases where remote addr, local port, and remote port are non-
19428 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19429 	 */
19430 	if (index != -1) {
19431 		err = tcp_ioctl_abort_bucket(acp, index,
19432 		    &count, exact, tcps);
19433 	} else {
19434 		/*
19435 		 * loop through all entries for wildcard case
19436 		 */
19437 		for (index = 0;
19438 		    index < ipst->ips_ipcl_conn_fanout_size;
19439 		    index++) {
19440 			err = tcp_ioctl_abort_bucket(acp, index,
19441 			    &count, exact, tcps);
19442 			if (err != 0)
19443 				break;
19444 		}
19445 	}
19446 
19447 	logflags = SL_TRACE | SL_NOTE;
19448 	/*
19449 	 * Don't print this message to the console if the operation was done
19450 	 * to a non-global zone.
19451 	 */
19452 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19453 		logflags |= SL_CONSOLE;
19454 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19455 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19456 	if (err == 0 && count == 0)
19457 		err = ENOENT;
19458 	return (err);
19459 }
19460 
19461 /*
19462  * Process the TCP_IOC_ABORT_CONN ioctl request.
19463  */
19464 static void
19465 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19466 {
19467 	int	err;
19468 	IOCP    iocp;
19469 	MBLKP   mp1;
19470 	sa_family_t laf, raf;
19471 	tcp_ioc_abort_conn_t *acp;
19472 	zone_t		*zptr;
19473 	conn_t		*connp = Q_TO_CONN(q);
19474 	zoneid_t	zoneid = connp->conn_zoneid;
19475 	tcp_t		*tcp = connp->conn_tcp;
19476 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19477 
19478 	iocp = (IOCP)mp->b_rptr;
19479 
19480 	if ((mp1 = mp->b_cont) == NULL ||
19481 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19482 		err = EINVAL;
19483 		goto out;
19484 	}
19485 
19486 	/* check permissions */
19487 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19488 		err = EPERM;
19489 		goto out;
19490 	}
19491 
19492 	if (mp1->b_cont != NULL) {
19493 		freemsg(mp1->b_cont);
19494 		mp1->b_cont = NULL;
19495 	}
19496 
19497 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19498 	laf = acp->ac_local.ss_family;
19499 	raf = acp->ac_remote.ss_family;
19500 
19501 	/* check that a zone with the supplied zoneid exists */
19502 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19503 		zptr = zone_find_by_id(zoneid);
19504 		if (zptr != NULL) {
19505 			zone_rele(zptr);
19506 		} else {
19507 			err = EINVAL;
19508 			goto out;
19509 		}
19510 	}
19511 
19512 	/*
19513 	 * For exclusive stacks we set the zoneid to zero
19514 	 * to make TCP operate as if in the global zone.
19515 	 */
19516 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19517 		acp->ac_zoneid = GLOBAL_ZONEID;
19518 
19519 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19520 	    acp->ac_start > acp->ac_end || laf != raf ||
19521 	    (laf != AF_INET && laf != AF_INET6)) {
19522 		err = EINVAL;
19523 		goto out;
19524 	}
19525 
19526 	tcp_ioctl_abort_dump(acp);
19527 	err = tcp_ioctl_abort(acp, tcps);
19528 
19529 out:
19530 	if (mp1 != NULL) {
19531 		freemsg(mp1);
19532 		mp->b_cont = NULL;
19533 	}
19534 
19535 	if (err != 0)
19536 		miocnak(q, mp, 0, err);
19537 	else
19538 		miocack(q, mp, 0, 0);
19539 }
19540 
19541 /*
19542  * tcp_time_wait_processing() handles processing of incoming packets when
19543  * the tcp is in the TIME_WAIT state.
19544  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19545  * on the time wait list.
19546  */
19547 void
19548 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19549     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19550 {
19551 	int32_t		bytes_acked;
19552 	int32_t		gap;
19553 	int32_t		rgap;
19554 	tcp_opt_t	tcpopt;
19555 	uint_t		flags;
19556 	uint32_t	new_swnd = 0;
19557 	conn_t		*nconnp;
19558 	conn_t		*connp = tcp->tcp_connp;
19559 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19560 
19561 	BUMP_LOCAL(tcp->tcp_ibsegs);
19562 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19563 
19564 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19565 	new_swnd = ntohs(tcpha->tha_win) <<
19566 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19567 	if (tcp->tcp_snd_ts_ok) {
19568 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19569 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19570 			    tcp->tcp_rnxt, TH_ACK);
19571 			goto done;
19572 		}
19573 	}
19574 	gap = seg_seq - tcp->tcp_rnxt;
19575 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19576 	if (gap < 0) {
19577 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19578 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19579 		    (seg_len > -gap ? -gap : seg_len));
19580 		seg_len += gap;
19581 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19582 			if (flags & TH_RST) {
19583 				goto done;
19584 			}
19585 			if ((flags & TH_FIN) && seg_len == -1) {
19586 				/*
19587 				 * When TCP receives a duplicate FIN in
19588 				 * TIME_WAIT state, restart the 2 MSL timer.
19589 				 * See page 73 in RFC 793. Make sure this TCP
19590 				 * is already on the TIME_WAIT list. If not,
19591 				 * just restart the timer.
19592 				 */
19593 				if (TCP_IS_DETACHED(tcp)) {
19594 					if (tcp_time_wait_remove(tcp, NULL) ==
19595 					    B_TRUE) {
19596 						tcp_time_wait_append(tcp);
19597 						TCP_DBGSTAT(tcps,
19598 						    tcp_rput_time_wait);
19599 					}
19600 				} else {
19601 					ASSERT(tcp != NULL);
19602 					TCP_TIMER_RESTART(tcp,
19603 					    tcps->tcps_time_wait_interval);
19604 				}
19605 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19606 				    tcp->tcp_rnxt, TH_ACK);
19607 				goto done;
19608 			}
19609 			flags |=  TH_ACK_NEEDED;
19610 			seg_len = 0;
19611 			goto process_ack;
19612 		}
19613 
19614 		/* Fix seg_seq, and chew the gap off the front. */
19615 		seg_seq = tcp->tcp_rnxt;
19616 	}
19617 
19618 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19619 		/*
19620 		 * Make sure that when we accept the connection, pick
19621 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19622 		 * old connection.
19623 		 *
19624 		 * The next ISS generated is equal to tcp_iss_incr_extra
19625 		 * + ISS_INCR/2 + other components depending on the
19626 		 * value of tcp_strong_iss.  We pre-calculate the new
19627 		 * ISS here and compare with tcp_snxt to determine if
19628 		 * we need to make adjustment to tcp_iss_incr_extra.
19629 		 *
19630 		 * The above calculation is ugly and is a
19631 		 * waste of CPU cycles...
19632 		 */
19633 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19634 		int32_t adj;
19635 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19636 
19637 		switch (tcps->tcps_strong_iss) {
19638 		case 2: {
19639 			/* Add time and MD5 components. */
19640 			uint32_t answer[4];
19641 			struct {
19642 				uint32_t ports;
19643 				in6_addr_t src;
19644 				in6_addr_t dst;
19645 			} arg;
19646 			MD5_CTX context;
19647 
19648 			mutex_enter(&tcps->tcps_iss_key_lock);
19649 			context = tcps->tcps_iss_key;
19650 			mutex_exit(&tcps->tcps_iss_key_lock);
19651 			arg.ports = connp->conn_ports;
19652 			/* We use MAPPED addresses in tcp_iss_init */
19653 			arg.src = connp->conn_laddr_v6;
19654 			arg.dst = connp->conn_faddr_v6;
19655 			MD5Update(&context, (uchar_t *)&arg,
19656 			    sizeof (arg));
19657 			MD5Final((uchar_t *)answer, &context);
19658 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19659 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19660 			break;
19661 		}
19662 		case 1:
19663 			/* Add time component and min random (i.e. 1). */
19664 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19665 			break;
19666 		default:
19667 			/* Add only time component. */
19668 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19669 			break;
19670 		}
19671 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19672 			/*
19673 			 * New ISS not guaranteed to be ISS_INCR/2
19674 			 * ahead of the current tcp_snxt, so add the
19675 			 * difference to tcp_iss_incr_extra.
19676 			 */
19677 			tcps->tcps_iss_incr_extra += adj;
19678 		}
19679 		/*
19680 		 * If tcp_clean_death() can not perform the task now,
19681 		 * drop the SYN packet and let the other side re-xmit.
19682 		 * Otherwise pass the SYN packet back in, since the
19683 		 * old tcp state has been cleaned up or freed.
19684 		 */
19685 		if (tcp_clean_death(tcp, 0, 27) == -1)
19686 			goto done;
19687 		nconnp = ipcl_classify(mp, ira, ipst);
19688 		if (nconnp != NULL) {
19689 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19690 			/* Drops ref on nconnp */
19691 			tcp_reinput(nconnp, mp, ira, ipst);
19692 			return;
19693 		}
19694 		goto done;
19695 	}
19696 
19697 	/*
19698 	 * rgap is the amount of stuff received out of window.  A negative
19699 	 * value is the amount out of window.
19700 	 */
19701 	if (rgap < 0) {
19702 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19703 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19704 		/* Fix seg_len and make sure there is something left. */
19705 		seg_len += rgap;
19706 		if (seg_len <= 0) {
19707 			if (flags & TH_RST) {
19708 				goto done;
19709 			}
19710 			flags |=  TH_ACK_NEEDED;
19711 			seg_len = 0;
19712 			goto process_ack;
19713 		}
19714 	}
19715 	/*
19716 	 * Check whether we can update tcp_ts_recent.  This test is
19717 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19718 	 * Extensions for High Performance: An Update", Internet Draft.
19719 	 */
19720 	if (tcp->tcp_snd_ts_ok &&
19721 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19722 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19723 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19724 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19725 	}
19726 
19727 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19728 		/* Always ack out of order packets */
19729 		flags |= TH_ACK_NEEDED;
19730 		seg_len = 0;
19731 	} else if (seg_len > 0) {
19732 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19733 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19734 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19735 	}
19736 	if (flags & TH_RST) {
19737 		(void) tcp_clean_death(tcp, 0, 28);
19738 		goto done;
19739 	}
19740 	if (flags & TH_SYN) {
19741 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19742 		    TH_RST|TH_ACK);
19743 		/*
19744 		 * Do not delete the TCP structure if it is in
19745 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19746 		 */
19747 		goto done;
19748 	}
19749 process_ack:
19750 	if (flags & TH_ACK) {
19751 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19752 		if (bytes_acked <= 0) {
19753 			if (bytes_acked == 0 && seg_len == 0 &&
19754 			    new_swnd == tcp->tcp_swnd)
19755 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19756 		} else {
19757 			/* Acks something not sent */
19758 			flags |= TH_ACK_NEEDED;
19759 		}
19760 	}
19761 	if (flags & TH_ACK_NEEDED) {
19762 		/*
19763 		 * Time to send an ack for some reason.
19764 		 */
19765 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19766 		    tcp->tcp_rnxt, TH_ACK);
19767 	}
19768 done:
19769 	freemsg(mp);
19770 }
19771 
19772 /*
19773  * TCP Timers Implementation.
19774  */
19775 timeout_id_t
19776 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19777 {
19778 	mblk_t *mp;
19779 	tcp_timer_t *tcpt;
19780 	tcp_t *tcp = connp->conn_tcp;
19781 
19782 	ASSERT(connp->conn_sqp != NULL);
19783 
19784 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19785 
19786 	if (tcp->tcp_timercache == NULL) {
19787 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19788 	} else {
19789 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19790 		mp = tcp->tcp_timercache;
19791 		tcp->tcp_timercache = mp->b_next;
19792 		mp->b_next = NULL;
19793 		ASSERT(mp->b_wptr == NULL);
19794 	}
19795 
19796 	CONN_INC_REF(connp);
19797 	tcpt = (tcp_timer_t *)mp->b_rptr;
19798 	tcpt->connp = connp;
19799 	tcpt->tcpt_proc = f;
19800 	/*
19801 	 * TCP timers are normal timeouts. Plus, they do not require more than
19802 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19803 	 * rounding up the expiration to the next resolution boundary, we can
19804 	 * batch timers in the callout subsystem to make TCP timers more
19805 	 * efficient. The roundup also protects short timers from expiring too
19806 	 * early before they have a chance to be cancelled.
19807 	 */
19808 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19809 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19810 
19811 	return ((timeout_id_t)mp);
19812 }
19813 
19814 static void
19815 tcp_timer_callback(void *arg)
19816 {
19817 	mblk_t *mp = (mblk_t *)arg;
19818 	tcp_timer_t *tcpt;
19819 	conn_t	*connp;
19820 
19821 	tcpt = (tcp_timer_t *)mp->b_rptr;
19822 	connp = tcpt->connp;
19823 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19824 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19825 }
19826 
19827 /* ARGSUSED */
19828 static void
19829 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19830 {
19831 	tcp_timer_t *tcpt;
19832 	conn_t *connp = (conn_t *)arg;
19833 	tcp_t *tcp = connp->conn_tcp;
19834 
19835 	tcpt = (tcp_timer_t *)mp->b_rptr;
19836 	ASSERT(connp == tcpt->connp);
19837 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19838 
19839 	/*
19840 	 * If the TCP has reached the closed state, don't proceed any
19841 	 * further. This TCP logically does not exist on the system.
19842 	 * tcpt_proc could for example access queues, that have already
19843 	 * been qprocoff'ed off.
19844 	 */
19845 	if (tcp->tcp_state != TCPS_CLOSED) {
19846 		(*tcpt->tcpt_proc)(connp);
19847 	} else {
19848 		tcp->tcp_timer_tid = 0;
19849 	}
19850 	tcp_timer_free(connp->conn_tcp, mp);
19851 }
19852 
19853 /*
19854  * There is potential race with untimeout and the handler firing at the same
19855  * time. The mblock may be freed by the handler while we are trying to use
19856  * it. But since both should execute on the same squeue, this race should not
19857  * occur.
19858  */
19859 clock_t
19860 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19861 {
19862 	mblk_t	*mp = (mblk_t *)id;
19863 	tcp_timer_t *tcpt;
19864 	clock_t delta;
19865 
19866 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19867 
19868 	if (mp == NULL)
19869 		return (-1);
19870 
19871 	tcpt = (tcp_timer_t *)mp->b_rptr;
19872 	ASSERT(tcpt->connp == connp);
19873 
19874 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19875 
19876 	if (delta >= 0) {
19877 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19878 		tcp_timer_free(connp->conn_tcp, mp);
19879 		CONN_DEC_REF(connp);
19880 	}
19881 
19882 	return (delta);
19883 }
19884 
19885 /*
19886  * Allocate space for the timer event. The allocation looks like mblk, but it is
19887  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19888  *
19889  * Dealing with failures: If we can't allocate from the timer cache we try
19890  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19891  * points to b_rptr.
19892  * If we can't allocate anything using allocb_tryhard(), we perform a last
19893  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19894  * save the actual allocation size in b_datap.
19895  */
19896 mblk_t *
19897 tcp_timermp_alloc(int kmflags)
19898 {
19899 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19900 	    kmflags & ~KM_PANIC);
19901 
19902 	if (mp != NULL) {
19903 		mp->b_next = mp->b_prev = NULL;
19904 		mp->b_rptr = (uchar_t *)(&mp[1]);
19905 		mp->b_wptr = NULL;
19906 		mp->b_datap = NULL;
19907 		mp->b_queue = NULL;
19908 		mp->b_cont = NULL;
19909 	} else if (kmflags & KM_PANIC) {
19910 		/*
19911 		 * Failed to allocate memory for the timer. Try allocating from
19912 		 * dblock caches.
19913 		 */
19914 		/* ipclassifier calls this from a constructor - hence no tcps */
19915 		TCP_G_STAT(tcp_timermp_allocfail);
19916 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19917 		if (mp == NULL) {
19918 			size_t size = 0;
19919 			/*
19920 			 * Memory is really low. Try tryhard allocation.
19921 			 *
19922 			 * ipclassifier calls this from a constructor -
19923 			 * hence no tcps
19924 			 */
19925 			TCP_G_STAT(tcp_timermp_allocdblfail);
19926 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19927 			    sizeof (tcp_timer_t), &size, kmflags);
19928 			mp->b_rptr = (uchar_t *)(&mp[1]);
19929 			mp->b_next = mp->b_prev = NULL;
19930 			mp->b_wptr = (uchar_t *)-1;
19931 			mp->b_datap = (dblk_t *)size;
19932 			mp->b_queue = NULL;
19933 			mp->b_cont = NULL;
19934 		}
19935 		ASSERT(mp->b_wptr != NULL);
19936 	}
19937 	/* ipclassifier calls this from a constructor - hence no tcps */
19938 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19939 
19940 	return (mp);
19941 }
19942 
19943 /*
19944  * Free per-tcp timer cache.
19945  * It can only contain entries from tcp_timercache.
19946  */
19947 void
19948 tcp_timermp_free(tcp_t *tcp)
19949 {
19950 	mblk_t *mp;
19951 
19952 	while ((mp = tcp->tcp_timercache) != NULL) {
19953 		ASSERT(mp->b_wptr == NULL);
19954 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19955 		kmem_cache_free(tcp_timercache, mp);
19956 	}
19957 }
19958 
19959 /*
19960  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19961  * events there already (currently at most two events are cached).
19962  * If the event is not allocated from the timer cache, free it right away.
19963  */
19964 static void
19965 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19966 {
19967 	mblk_t *mp1 = tcp->tcp_timercache;
19968 
19969 	if (mp->b_wptr != NULL) {
19970 		/*
19971 		 * This allocation is not from a timer cache, free it right
19972 		 * away.
19973 		 */
19974 		if (mp->b_wptr != (uchar_t *)-1)
19975 			freeb(mp);
19976 		else
19977 			kmem_free(mp, (size_t)mp->b_datap);
19978 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19979 		/* Cache this timer block for future allocations */
19980 		mp->b_rptr = (uchar_t *)(&mp[1]);
19981 		mp->b_next = mp1;
19982 		tcp->tcp_timercache = mp;
19983 	} else {
19984 		kmem_cache_free(tcp_timercache, mp);
19985 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19986 	}
19987 }
19988 
19989 /*
19990  * End of TCP Timers implementation.
19991  */
19992 
19993 /*
19994  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19995  * on the specified backing STREAMS q. Note, the caller may make the
19996  * decision to call based on the tcp_t.tcp_flow_stopped value which
19997  * when check outside the q's lock is only an advisory check ...
19998  */
19999 void
20000 tcp_setqfull(tcp_t *tcp)
20001 {
20002 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20003 	conn_t	*connp = tcp->tcp_connp;
20004 
20005 	if (tcp->tcp_closed)
20006 		return;
20007 
20008 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
20009 	if (tcp->tcp_flow_stopped)
20010 		TCP_STAT(tcps, tcp_flwctl_on);
20011 }
20012 
20013 void
20014 tcp_clrqfull(tcp_t *tcp)
20015 {
20016 	conn_t  *connp = tcp->tcp_connp;
20017 
20018 	if (tcp->tcp_closed)
20019 		return;
20020 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
20021 }
20022 
20023 /*
20024  * kstats related to squeues i.e. not per IP instance
20025  */
20026 static void *
20027 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
20028 {
20029 	kstat_t *ksp;
20030 
20031 	tcp_g_stat_t template = {
20032 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
20033 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
20034 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
20035 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
20036 	};
20037 
20038 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
20039 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20040 	    KSTAT_FLAG_VIRTUAL);
20041 
20042 	if (ksp == NULL)
20043 		return (NULL);
20044 
20045 	bcopy(&template, tcp_g_statp, sizeof (template));
20046 	ksp->ks_data = (void *)tcp_g_statp;
20047 
20048 	kstat_install(ksp);
20049 	return (ksp);
20050 }
20051 
20052 static void
20053 tcp_g_kstat_fini(kstat_t *ksp)
20054 {
20055 	if (ksp != NULL) {
20056 		kstat_delete(ksp);
20057 	}
20058 }
20059 
20060 
20061 static void *
20062 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
20063 {
20064 	kstat_t *ksp;
20065 
20066 	tcp_stat_t template = {
20067 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
20068 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
20069 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
20070 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
20071 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
20072 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
20073 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
20074 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
20075 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
20076 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
20077 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
20078 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
20079 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
20080 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
20081 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
20082 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
20083 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
20084 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
20085 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
20086 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
20087 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
20088 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
20089 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
20090 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
20091 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
20092 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
20093 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
20094 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
20095 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
20096 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
20097 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
20098 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
20099 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
20100 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
20101 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
20102 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
20103 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
20104 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
20105 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
20106 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
20107 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
20108 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
20109 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20110 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20111 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20112 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20113 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20114 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20115 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20116 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20117 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20118 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20119 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20120 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20121 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20122 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20123 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20124 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20125 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20126 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20127 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20128 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20129 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20130 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20131 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20132 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20133 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20134 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20135 	};
20136 
20137 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20138 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20139 	    KSTAT_FLAG_VIRTUAL, stackid);
20140 
20141 	if (ksp == NULL)
20142 		return (NULL);
20143 
20144 	bcopy(&template, tcps_statisticsp, sizeof (template));
20145 	ksp->ks_data = (void *)tcps_statisticsp;
20146 	ksp->ks_private = (void *)(uintptr_t)stackid;
20147 
20148 	kstat_install(ksp);
20149 	return (ksp);
20150 }
20151 
20152 static void
20153 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20154 {
20155 	if (ksp != NULL) {
20156 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20157 		kstat_delete_netstack(ksp, stackid);
20158 	}
20159 }
20160 
20161 /*
20162  * TCP Kstats implementation
20163  */
20164 static void *
20165 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20166 {
20167 	kstat_t	*ksp;
20168 
20169 	tcp_named_kstat_t template = {
20170 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20171 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20172 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20173 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20174 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20175 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20176 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20177 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20178 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20179 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20180 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20181 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20182 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20183 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20184 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20185 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20186 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20187 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20188 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20189 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20190 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20191 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20192 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20193 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20194 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20195 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20196 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20197 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20198 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20199 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20200 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20201 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20202 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20203 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20204 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20205 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20206 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20207 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20208 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20209 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20210 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20211 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20212 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20213 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20214 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20215 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20216 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20217 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20218 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20219 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20220 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20221 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20222 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20223 	};
20224 
20225 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20226 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20227 
20228 	if (ksp == NULL)
20229 		return (NULL);
20230 
20231 	template.rtoAlgorithm.value.ui32 = 4;
20232 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20233 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20234 	template.maxConn.value.i32 = -1;
20235 
20236 	bcopy(&template, ksp->ks_data, sizeof (template));
20237 	ksp->ks_update = tcp_kstat_update;
20238 	ksp->ks_private = (void *)(uintptr_t)stackid;
20239 
20240 	kstat_install(ksp);
20241 	return (ksp);
20242 }
20243 
20244 static void
20245 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20246 {
20247 	if (ksp != NULL) {
20248 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20249 		kstat_delete_netstack(ksp, stackid);
20250 	}
20251 }
20252 
20253 static int
20254 tcp_kstat_update(kstat_t *kp, int rw)
20255 {
20256 	tcp_named_kstat_t *tcpkp;
20257 	tcp_t		*tcp;
20258 	connf_t		*connfp;
20259 	conn_t		*connp;
20260 	int 		i;
20261 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20262 	netstack_t	*ns;
20263 	tcp_stack_t	*tcps;
20264 	ip_stack_t	*ipst;
20265 
20266 	if ((kp == NULL) || (kp->ks_data == NULL))
20267 		return (EIO);
20268 
20269 	if (rw == KSTAT_WRITE)
20270 		return (EACCES);
20271 
20272 	ns = netstack_find_by_stackid(stackid);
20273 	if (ns == NULL)
20274 		return (-1);
20275 	tcps = ns->netstack_tcp;
20276 	if (tcps == NULL) {
20277 		netstack_rele(ns);
20278 		return (-1);
20279 	}
20280 
20281 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20282 
20283 	tcpkp->currEstab.value.ui32 = 0;
20284 
20285 	ipst = ns->netstack_ip;
20286 
20287 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20288 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20289 		connp = NULL;
20290 		while ((connp =
20291 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20292 			tcp = connp->conn_tcp;
20293 			switch (tcp_snmp_state(tcp)) {
20294 			case MIB2_TCP_established:
20295 			case MIB2_TCP_closeWait:
20296 				tcpkp->currEstab.value.ui32++;
20297 				break;
20298 			}
20299 		}
20300 	}
20301 
20302 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20303 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20304 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20305 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20306 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20307 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20308 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20309 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20310 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20311 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20312 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20313 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20314 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20315 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20316 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20317 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20318 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20319 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20320 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20321 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20322 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20323 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20324 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20325 	tcpkp->inDataInorderSegs.value.ui32 =
20326 	    tcps->tcps_mib.tcpInDataInorderSegs;
20327 	tcpkp->inDataInorderBytes.value.ui32 =
20328 	    tcps->tcps_mib.tcpInDataInorderBytes;
20329 	tcpkp->inDataUnorderSegs.value.ui32 =
20330 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20331 	tcpkp->inDataUnorderBytes.value.ui32 =
20332 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20333 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20334 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20335 	tcpkp->inDataPartDupSegs.value.ui32 =
20336 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20337 	tcpkp->inDataPartDupBytes.value.ui32 =
20338 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20339 	tcpkp->inDataPastWinSegs.value.ui32 =
20340 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20341 	tcpkp->inDataPastWinBytes.value.ui32 =
20342 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20343 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20344 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20345 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20346 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20347 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20348 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20349 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20350 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20351 	tcpkp->timKeepaliveProbe.value.ui32 =
20352 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20353 	tcpkp->timKeepaliveDrop.value.ui32 =
20354 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20355 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20356 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20357 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20358 	tcpkp->outSackRetransSegs.value.ui32 =
20359 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20360 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20361 
20362 	netstack_rele(ns);
20363 	return (0);
20364 }
20365 
20366 static int
20367 tcp_squeue_switch(int val)
20368 {
20369 	int rval = SQ_FILL;
20370 
20371 	switch (val) {
20372 	case 1:
20373 		rval = SQ_NODRAIN;
20374 		break;
20375 	case 2:
20376 		rval = SQ_PROCESS;
20377 		break;
20378 	default:
20379 		break;
20380 	}
20381 	return (rval);
20382 }
20383 
20384 /*
20385  * This is called once for each squeue - globally for all stack
20386  * instances.
20387  */
20388 static void
20389 tcp_squeue_add(squeue_t *sqp)
20390 {
20391 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20392 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20393 
20394 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20395 	tcp_time_wait->tcp_time_wait_tid =
20396 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20397 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20398 	    CALLOUT_FLAG_ROUNDUP);
20399 	if (tcp_free_list_max_cnt == 0) {
20400 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20401 		    max_ncpus : boot_max_ncpus);
20402 
20403 		/*
20404 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20405 		 */
20406 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20407 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20408 	}
20409 	tcp_time_wait->tcp_free_list_cnt = 0;
20410 }
20411 
20412 /*
20413  * On a labeled system we have some protocols above TCP, such as RPC, which
20414  * appear to assume that every mblk in a chain has a db_credp.
20415  */
20416 static void
20417 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20418 {
20419 	ASSERT(is_system_labeled());
20420 	ASSERT(ira->ira_cred != NULL);
20421 
20422 	while (mp != NULL) {
20423 		mblk_setcred(mp, ira->ira_cred, NOPID);
20424 		mp = mp->b_cont;
20425 	}
20426 }
20427 
20428 static int
20429 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20430     boolean_t bind_to_req_port_only, cred_t *cr)
20431 {
20432 	in_port_t	mlp_port;
20433 	mlp_type_t 	addrtype, mlptype;
20434 	boolean_t	user_specified;
20435 	in_port_t	allocated_port;
20436 	in_port_t	requested_port = *requested_port_ptr;
20437 	conn_t		*connp = tcp->tcp_connp;
20438 	zone_t		*zone;
20439 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20440 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20441 
20442 	/*
20443 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20444 	 */
20445 	ASSERT(cr != NULL);
20446 
20447 	/*
20448 	 * Get a valid port (within the anonymous range and should not
20449 	 * be a privileged one) to use if the user has not given a port.
20450 	 * If multiple threads are here, they may all start with
20451 	 * with the same initial port. But, it should be fine as long as
20452 	 * tcp_bindi will ensure that no two threads will be assigned
20453 	 * the same port.
20454 	 *
20455 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20456 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20457 	 * unless TCP_ANONPRIVBIND option is set.
20458 	 */
20459 	mlptype = mlptSingle;
20460 	mlp_port = requested_port;
20461 	if (requested_port == 0) {
20462 		requested_port = connp->conn_anon_priv_bind ?
20463 		    tcp_get_next_priv_port(tcp) :
20464 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20465 		    tcp, B_TRUE);
20466 		if (requested_port == 0) {
20467 			return (-TNOADDR);
20468 		}
20469 		user_specified = B_FALSE;
20470 
20471 		/*
20472 		 * If the user went through one of the RPC interfaces to create
20473 		 * this socket and RPC is MLP in this zone, then give him an
20474 		 * anonymous MLP.
20475 		 */
20476 		if (connp->conn_anon_mlp && is_system_labeled()) {
20477 			zone = crgetzone(cr);
20478 			addrtype = tsol_mlp_addr_type(
20479 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20480 			    IPV6_VERSION, &v6addr,
20481 			    tcps->tcps_netstack->netstack_ip);
20482 			if (addrtype == mlptSingle) {
20483 				return (-TNOADDR);
20484 			}
20485 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20486 			    PMAPPORT, addrtype);
20487 			mlp_port = PMAPPORT;
20488 		}
20489 	} else {
20490 		int i;
20491 		boolean_t priv = B_FALSE;
20492 
20493 		/*
20494 		 * If the requested_port is in the well-known privileged range,
20495 		 * verify that the stream was opened by a privileged user.
20496 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20497 		 * but instead the code relies on:
20498 		 * - the fact that the address of the array and its size never
20499 		 *   changes
20500 		 * - the atomic assignment of the elements of the array
20501 		 */
20502 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20503 			priv = B_TRUE;
20504 		} else {
20505 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20506 				if (requested_port ==
20507 				    tcps->tcps_g_epriv_ports[i]) {
20508 					priv = B_TRUE;
20509 					break;
20510 				}
20511 			}
20512 		}
20513 		if (priv) {
20514 			if (secpolicy_net_privaddr(cr, requested_port,
20515 			    IPPROTO_TCP) != 0) {
20516 				if (connp->conn_debug) {
20517 					(void) strlog(TCP_MOD_ID, 0, 1,
20518 					    SL_ERROR|SL_TRACE,
20519 					    "tcp_bind: no priv for port %d",
20520 					    requested_port);
20521 				}
20522 				return (-TACCES);
20523 			}
20524 		}
20525 		user_specified = B_TRUE;
20526 
20527 		connp = tcp->tcp_connp;
20528 		if (is_system_labeled()) {
20529 			zone = crgetzone(cr);
20530 			addrtype = tsol_mlp_addr_type(
20531 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20532 			    IPV6_VERSION, &v6addr,
20533 			    tcps->tcps_netstack->netstack_ip);
20534 			if (addrtype == mlptSingle) {
20535 				return (-TNOADDR);
20536 			}
20537 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20538 			    requested_port, addrtype);
20539 		}
20540 	}
20541 
20542 	if (mlptype != mlptSingle) {
20543 		if (secpolicy_net_bindmlp(cr) != 0) {
20544 			if (connp->conn_debug) {
20545 				(void) strlog(TCP_MOD_ID, 0, 1,
20546 				    SL_ERROR|SL_TRACE,
20547 				    "tcp_bind: no priv for multilevel port %d",
20548 				    requested_port);
20549 			}
20550 			return (-TACCES);
20551 		}
20552 
20553 		/*
20554 		 * If we're specifically binding a shared IP address and the
20555 		 * port is MLP on shared addresses, then check to see if this
20556 		 * zone actually owns the MLP.  Reject if not.
20557 		 */
20558 		if (mlptype == mlptShared && addrtype == mlptShared) {
20559 			/*
20560 			 * No need to handle exclusive-stack zones since
20561 			 * ALL_ZONES only applies to the shared stack.
20562 			 */
20563 			zoneid_t mlpzone;
20564 
20565 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20566 			    htons(mlp_port));
20567 			if (connp->conn_zoneid != mlpzone) {
20568 				if (connp->conn_debug) {
20569 					(void) strlog(TCP_MOD_ID, 0, 1,
20570 					    SL_ERROR|SL_TRACE,
20571 					    "tcp_bind: attempt to bind port "
20572 					    "%d on shared addr in zone %d "
20573 					    "(should be %d)",
20574 					    mlp_port, connp->conn_zoneid,
20575 					    mlpzone);
20576 				}
20577 				return (-TACCES);
20578 			}
20579 		}
20580 
20581 		if (!user_specified) {
20582 			int err;
20583 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20584 			    requested_port, B_TRUE);
20585 			if (err != 0) {
20586 				if (connp->conn_debug) {
20587 					(void) strlog(TCP_MOD_ID, 0, 1,
20588 					    SL_ERROR|SL_TRACE,
20589 					    "tcp_bind: cannot establish anon "
20590 					    "MLP for port %d",
20591 					    requested_port);
20592 				}
20593 				return (err);
20594 			}
20595 			connp->conn_anon_port = B_TRUE;
20596 		}
20597 		connp->conn_mlp_type = mlptype;
20598 	}
20599 
20600 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20601 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20602 	    user_specified);
20603 
20604 	if (allocated_port == 0) {
20605 		connp->conn_mlp_type = mlptSingle;
20606 		if (connp->conn_anon_port) {
20607 			connp->conn_anon_port = B_FALSE;
20608 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20609 			    requested_port, B_FALSE);
20610 		}
20611 		if (bind_to_req_port_only) {
20612 			if (connp->conn_debug) {
20613 				(void) strlog(TCP_MOD_ID, 0, 1,
20614 				    SL_ERROR|SL_TRACE,
20615 				    "tcp_bind: requested addr busy");
20616 			}
20617 			return (-TADDRBUSY);
20618 		} else {
20619 			/* If we are out of ports, fail the bind. */
20620 			if (connp->conn_debug) {
20621 				(void) strlog(TCP_MOD_ID, 0, 1,
20622 				    SL_ERROR|SL_TRACE,
20623 				    "tcp_bind: out of ports?");
20624 			}
20625 			return (-TNOADDR);
20626 		}
20627 	}
20628 
20629 	/* Pass the allocated port back */
20630 	*requested_port_ptr = allocated_port;
20631 	return (0);
20632 }
20633 
20634 /*
20635  * Check the address and check/pick a local port number.
20636  */
20637 static int
20638 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20639     boolean_t bind_to_req_port_only)
20640 {
20641 	tcp_t	*tcp = connp->conn_tcp;
20642 	sin_t	*sin;
20643 	sin6_t  *sin6;
20644 	in_port_t	requested_port;
20645 	ipaddr_t	v4addr;
20646 	in6_addr_t	v6addr;
20647 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20648 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20649 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20650 	uint_t		scopeid = 0;
20651 	int		error = 0;
20652 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20653 
20654 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20655 
20656 	if (tcp->tcp_state == TCPS_BOUND) {
20657 		return (0);
20658 	} else if (tcp->tcp_state > TCPS_BOUND) {
20659 		if (connp->conn_debug) {
20660 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20661 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20662 		}
20663 		return (-TOUTSTATE);
20664 	}
20665 
20666 	ASSERT(sa != NULL && len != 0);
20667 
20668 	if (!OK_32PTR((char *)sa)) {
20669 		if (connp->conn_debug) {
20670 			(void) strlog(TCP_MOD_ID, 0, 1,
20671 			    SL_ERROR|SL_TRACE,
20672 			    "tcp_bind: bad address parameter, "
20673 			    "address %p, len %d",
20674 			    (void *)sa, len);
20675 		}
20676 		return (-TPROTO);
20677 	}
20678 
20679 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20680 	if (error != 0) {
20681 		return (error);
20682 	}
20683 
20684 	switch (len) {
20685 	case sizeof (sin_t):	/* Complete IPv4 address */
20686 		sin = (sin_t *)sa;
20687 		requested_port = ntohs(sin->sin_port);
20688 		v4addr = sin->sin_addr.s_addr;
20689 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20690 		if (v4addr != INADDR_ANY) {
20691 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20692 			    B_FALSE);
20693 		}
20694 		break;
20695 
20696 	case sizeof (sin6_t): /* Complete IPv6 address */
20697 		sin6 = (sin6_t *)sa;
20698 		v6addr = sin6->sin6_addr;
20699 		requested_port = ntohs(sin6->sin6_port);
20700 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20701 			if (connp->conn_ipv6_v6only)
20702 				return (EADDRNOTAVAIL);
20703 
20704 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20705 			if (v4addr != INADDR_ANY) {
20706 				laddr_type = ip_laddr_verify_v4(v4addr,
20707 				    zoneid, ipst, B_FALSE);
20708 			}
20709 		} else {
20710 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20711 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20712 					scopeid = sin6->sin6_scope_id;
20713 				laddr_type = ip_laddr_verify_v6(&v6addr,
20714 				    zoneid, ipst, B_FALSE, scopeid);
20715 			}
20716 		}
20717 		break;
20718 
20719 	default:
20720 		if (connp->conn_debug) {
20721 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20722 			    "tcp_bind: bad address length, %d", len);
20723 		}
20724 		return (EAFNOSUPPORT);
20725 		/* return (-TBADADDR); */
20726 	}
20727 
20728 	/* Is the local address a valid unicast address? */
20729 	if (laddr_type == IPVL_BAD)
20730 		return (EADDRNOTAVAIL);
20731 
20732 	connp->conn_bound_addr_v6 = v6addr;
20733 	if (scopeid != 0) {
20734 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20735 		ixa->ixa_scopeid = scopeid;
20736 		connp->conn_incoming_ifindex = scopeid;
20737 	} else {
20738 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20739 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20740 	}
20741 
20742 	connp->conn_laddr_v6 = v6addr;
20743 	connp->conn_saddr_v6 = v6addr;
20744 
20745 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20746 
20747 	error = tcp_bind_select_lport(tcp, &requested_port,
20748 	    bind_to_req_port_only, cr);
20749 	if (error != 0) {
20750 		connp->conn_laddr_v6 = ipv6_all_zeros;
20751 		connp->conn_saddr_v6 = ipv6_all_zeros;
20752 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20753 	}
20754 	return (error);
20755 }
20756 
20757 /*
20758  * Return unix error is tli error is TSYSERR, otherwise return a negative
20759  * tli error.
20760  */
20761 int
20762 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20763     boolean_t bind_to_req_port_only)
20764 {
20765 	int error;
20766 	tcp_t *tcp = connp->conn_tcp;
20767 
20768 	if (tcp->tcp_state >= TCPS_BOUND) {
20769 		if (connp->conn_debug) {
20770 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20771 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20772 		}
20773 		return (-TOUTSTATE);
20774 	}
20775 
20776 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20777 	if (error != 0)
20778 		return (error);
20779 
20780 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20781 	tcp->tcp_conn_req_max = 0;
20782 	return (0);
20783 }
20784 
20785 int
20786 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20787     socklen_t len, cred_t *cr)
20788 {
20789 	int 		error;
20790 	conn_t		*connp = (conn_t *)proto_handle;
20791 	squeue_t	*sqp = connp->conn_sqp;
20792 
20793 	/* All Solaris components should pass a cred for this operation. */
20794 	ASSERT(cr != NULL);
20795 
20796 	ASSERT(sqp != NULL);
20797 	ASSERT(connp->conn_upper_handle != NULL);
20798 
20799 	error = squeue_synch_enter(sqp, connp, NULL);
20800 	if (error != 0) {
20801 		/* failed to enter */
20802 		return (ENOSR);
20803 	}
20804 
20805 	/* binding to a NULL address really means unbind */
20806 	if (sa == NULL) {
20807 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20808 			error = tcp_do_unbind(connp);
20809 		else
20810 			error = EINVAL;
20811 	} else {
20812 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20813 	}
20814 
20815 	squeue_synch_exit(sqp, connp);
20816 
20817 	if (error < 0) {
20818 		if (error == -TOUTSTATE)
20819 			error = EINVAL;
20820 		else
20821 			error = proto_tlitosyserr(-error);
20822 	}
20823 
20824 	return (error);
20825 }
20826 
20827 /*
20828  * If the return value from this function is positive, it's a UNIX error.
20829  * Otherwise, if it's negative, then the absolute value is a TLI error.
20830  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20831  */
20832 int
20833 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20834     cred_t *cr, pid_t pid)
20835 {
20836 	tcp_t		*tcp = connp->conn_tcp;
20837 	sin_t		*sin = (sin_t *)sa;
20838 	sin6_t		*sin6 = (sin6_t *)sa;
20839 	ipaddr_t	*dstaddrp;
20840 	in_port_t	dstport;
20841 	uint_t		srcid;
20842 	int		error;
20843 	uint32_t	mss;
20844 	mblk_t		*syn_mp;
20845 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20846 	int32_t		oldstate;
20847 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20848 
20849 	oldstate = tcp->tcp_state;
20850 
20851 	switch (len) {
20852 	default:
20853 		/*
20854 		 * Should never happen
20855 		 */
20856 		return (EINVAL);
20857 
20858 	case sizeof (sin_t):
20859 		sin = (sin_t *)sa;
20860 		if (sin->sin_port == 0) {
20861 			return (-TBADADDR);
20862 		}
20863 		if (connp->conn_ipv6_v6only) {
20864 			return (EAFNOSUPPORT);
20865 		}
20866 		break;
20867 
20868 	case sizeof (sin6_t):
20869 		sin6 = (sin6_t *)sa;
20870 		if (sin6->sin6_port == 0) {
20871 			return (-TBADADDR);
20872 		}
20873 		break;
20874 	}
20875 	/*
20876 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20877 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20878 	 * need to this before we call tcp_bindi() so that the port lookup
20879 	 * code will look for ports in the correct port space (IPv4 and
20880 	 * IPv6 have separate port spaces).
20881 	 */
20882 	if (connp->conn_family == AF_INET6 &&
20883 	    connp->conn_ipversion == IPV6_VERSION &&
20884 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20885 		if (connp->conn_ipv6_v6only)
20886 			return (EADDRNOTAVAIL);
20887 
20888 		connp->conn_ipversion = IPV4_VERSION;
20889 	}
20890 
20891 	switch (tcp->tcp_state) {
20892 	case TCPS_LISTEN:
20893 		/*
20894 		 * Listening sockets are not allowed to issue connect().
20895 		 */
20896 		if (IPCL_IS_NONSTR(connp))
20897 			return (EOPNOTSUPP);
20898 		/* FALLTHRU */
20899 	case TCPS_IDLE:
20900 		/*
20901 		 * We support quick connect, refer to comments in
20902 		 * tcp_connect_*()
20903 		 */
20904 		/* FALLTHRU */
20905 	case TCPS_BOUND:
20906 		break;
20907 	default:
20908 		return (-TOUTSTATE);
20909 	}
20910 
20911 	/*
20912 	 * We update our cred/cpid based on the caller of connect
20913 	 */
20914 	if (connp->conn_cred != cr) {
20915 		crhold(cr);
20916 		crfree(connp->conn_cred);
20917 		connp->conn_cred = cr;
20918 	}
20919 	connp->conn_cpid = pid;
20920 
20921 	/* Cache things in the ixa without any refhold */
20922 	ixa->ixa_cred = cr;
20923 	ixa->ixa_cpid = pid;
20924 	if (is_system_labeled()) {
20925 		/* We need to restart with a label based on the cred */
20926 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20927 	}
20928 
20929 	if (connp->conn_family == AF_INET6) {
20930 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20931 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20932 			    sin6->sin6_port, sin6->sin6_flowinfo,
20933 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20934 		} else {
20935 			/*
20936 			 * Destination adress is mapped IPv6 address.
20937 			 * Source bound address should be unspecified or
20938 			 * IPv6 mapped address as well.
20939 			 */
20940 			if (!IN6_IS_ADDR_UNSPECIFIED(
20941 			    &connp->conn_bound_addr_v6) &&
20942 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20943 				return (EADDRNOTAVAIL);
20944 			}
20945 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20946 			dstport = sin6->sin6_port;
20947 			srcid = sin6->__sin6_src_id;
20948 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20949 			    srcid);
20950 		}
20951 	} else {
20952 		dstaddrp = &sin->sin_addr.s_addr;
20953 		dstport = sin->sin_port;
20954 		srcid = 0;
20955 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20956 	}
20957 
20958 	if (error != 0)
20959 		goto connect_failed;
20960 
20961 	CL_INET_CONNECT(connp, B_TRUE, error);
20962 	if (error != 0)
20963 		goto connect_failed;
20964 
20965 	/* connect succeeded */
20966 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20967 	tcp->tcp_active_open = 1;
20968 
20969 	/*
20970 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20971 	 */
20972 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20973 
20974 	/*
20975 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20976 	 * to the nearest MSS.
20977 	 *
20978 	 * We do the round up here because we need to get the interface MTU
20979 	 * first before we can do the round up.
20980 	 */
20981 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20982 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20983 	    tcps->tcps_recv_hiwat_minmss * mss);
20984 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20985 	tcp_set_ws_value(tcp);
20986 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20987 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20988 		tcp->tcp_snd_ws_ok = B_TRUE;
20989 
20990 	/*
20991 	 * Set tcp_snd_ts_ok to true
20992 	 * so that tcp_xmit_mp will
20993 	 * include the timestamp
20994 	 * option in the SYN segment.
20995 	 */
20996 	if (tcps->tcps_tstamp_always ||
20997 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20998 		tcp->tcp_snd_ts_ok = B_TRUE;
20999 	}
21000 
21001 	/*
21002 	 * tcp_snd_sack_ok can be set in
21003 	 * tcp_set_destination() if the sack metric
21004 	 * is set.  So check it here also.
21005 	 */
21006 	if (tcps->tcps_sack_permitted == 2 ||
21007 	    tcp->tcp_snd_sack_ok) {
21008 		if (tcp->tcp_sack_info == NULL) {
21009 			tcp->tcp_sack_info = kmem_cache_alloc(
21010 			    tcp_sack_info_cache, KM_SLEEP);
21011 		}
21012 		tcp->tcp_snd_sack_ok = B_TRUE;
21013 	}
21014 
21015 	/*
21016 	 * Should we use ECN?  Note that the current
21017 	 * default value (SunOS 5.9) of tcp_ecn_permitted
21018 	 * is 1.  The reason for doing this is that there
21019 	 * are equipments out there that will drop ECN
21020 	 * enabled IP packets.  Setting it to 1 avoids
21021 	 * compatibility problems.
21022 	 */
21023 	if (tcps->tcps_ecn_permitted == 2)
21024 		tcp->tcp_ecn_ok = B_TRUE;
21025 
21026 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21027 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21028 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
21029 	if (syn_mp != NULL) {
21030 		/*
21031 		 * We must bump the generation before sending the syn
21032 		 * to ensure that we use the right generation in case
21033 		 * this thread issues a "connected" up call.
21034 		 */
21035 		SOCK_CONNID_BUMP(tcp->tcp_connid);
21036 		tcp_send_data(tcp, syn_mp);
21037 	}
21038 
21039 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21040 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21041 	return (0);
21042 
21043 connect_failed:
21044 	connp->conn_faddr_v6 = ipv6_all_zeros;
21045 	connp->conn_fport = 0;
21046 	tcp->tcp_state = oldstate;
21047 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21048 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21049 	return (error);
21050 }
21051 
21052 int
21053 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
21054     socklen_t len, sock_connid_t *id, cred_t *cr)
21055 {
21056 	conn_t		*connp = (conn_t *)proto_handle;
21057 	squeue_t	*sqp = connp->conn_sqp;
21058 	int		error;
21059 
21060 	ASSERT(connp->conn_upper_handle != NULL);
21061 
21062 	/* All Solaris components should pass a cred for this operation. */
21063 	ASSERT(cr != NULL);
21064 
21065 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
21066 	if (error != 0) {
21067 		return (error);
21068 	}
21069 
21070 	error = squeue_synch_enter(sqp, connp, NULL);
21071 	if (error != 0) {
21072 		/* failed to enter */
21073 		return (ENOSR);
21074 	}
21075 
21076 	/*
21077 	 * TCP supports quick connect, so no need to do an implicit bind
21078 	 */
21079 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
21080 	if (error == 0) {
21081 		*id = connp->conn_tcp->tcp_connid;
21082 	} else if (error < 0) {
21083 		if (error == -TOUTSTATE) {
21084 			switch (connp->conn_tcp->tcp_state) {
21085 			case TCPS_SYN_SENT:
21086 				error = EALREADY;
21087 				break;
21088 			case TCPS_ESTABLISHED:
21089 				error = EISCONN;
21090 				break;
21091 			case TCPS_LISTEN:
21092 				error = EOPNOTSUPP;
21093 				break;
21094 			default:
21095 				error = EINVAL;
21096 				break;
21097 			}
21098 		} else {
21099 			error = proto_tlitosyserr(-error);
21100 		}
21101 	}
21102 
21103 	if (connp->conn_tcp->tcp_loopback) {
21104 		struct sock_proto_props sopp;
21105 
21106 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
21107 		sopp.sopp_loopback = B_TRUE;
21108 
21109 		(*connp->conn_upcalls->su_set_proto_props)(
21110 		    connp->conn_upper_handle, &sopp);
21111 	}
21112 done:
21113 	squeue_synch_exit(sqp, connp);
21114 
21115 	return ((error == 0) ? EINPROGRESS : error);
21116 }
21117 
21118 /* ARGSUSED */
21119 sock_lower_handle_t
21120 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21121     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21122 {
21123 	conn_t		*connp;
21124 	boolean_t	isv6 = family == AF_INET6;
21125 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21126 	    (proto != 0 && proto != IPPROTO_TCP)) {
21127 		*errorp = EPROTONOSUPPORT;
21128 		return (NULL);
21129 	}
21130 
21131 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21132 	if (connp == NULL) {
21133 		return (NULL);
21134 	}
21135 
21136 	/*
21137 	 * Put the ref for TCP. Ref for IP was already put
21138 	 * by ipcl_conn_create. Also Make the conn_t globally
21139 	 * visible to walkers
21140 	 */
21141 	mutex_enter(&connp->conn_lock);
21142 	CONN_INC_REF_LOCKED(connp);
21143 	ASSERT(connp->conn_ref == 2);
21144 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21145 
21146 	connp->conn_flags |= IPCL_NONSTR;
21147 	mutex_exit(&connp->conn_lock);
21148 
21149 	ASSERT(errorp != NULL);
21150 	*errorp = 0;
21151 	*sock_downcalls = &sock_tcp_downcalls;
21152 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21153 	    SM_SENDFILESUPP;
21154 
21155 	return ((sock_lower_handle_t)connp);
21156 }
21157 
21158 /* ARGSUSED */
21159 void
21160 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21161     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21162 {
21163 	conn_t *connp = (conn_t *)proto_handle;
21164 	struct sock_proto_props sopp;
21165 
21166 	ASSERT(connp->conn_upper_handle == NULL);
21167 
21168 	/* All Solaris components should pass a cred for this operation. */
21169 	ASSERT(cr != NULL);
21170 
21171 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21172 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21173 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21174 
21175 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21176 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21177 	sopp.sopp_maxpsz = INFPSZ;
21178 	sopp.sopp_maxblk = INFPSZ;
21179 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21180 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21181 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21182 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21183 	    tcp_rinfo.mi_minpsz;
21184 
21185 	connp->conn_upcalls = sock_upcalls;
21186 	connp->conn_upper_handle = sock_handle;
21187 
21188 	ASSERT(connp->conn_rcvbuf != 0 &&
21189 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21190 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21191 }
21192 
21193 /* ARGSUSED */
21194 int
21195 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21196 {
21197 	conn_t *connp = (conn_t *)proto_handle;
21198 
21199 	ASSERT(connp->conn_upper_handle != NULL);
21200 
21201 	/* All Solaris components should pass a cred for this operation. */
21202 	ASSERT(cr != NULL);
21203 
21204 	tcp_close_common(connp, flags);
21205 
21206 	ip_free_helper_stream(connp);
21207 
21208 	/*
21209 	 * Drop IP's reference on the conn. This is the last reference
21210 	 * on the connp if the state was less than established. If the
21211 	 * connection has gone into timewait state, then we will have
21212 	 * one ref for the TCP and one more ref (total of two) for the
21213 	 * classifier connected hash list (a timewait connections stays
21214 	 * in connected hash till closed).
21215 	 *
21216 	 * We can't assert the references because there might be other
21217 	 * transient reference places because of some walkers or queued
21218 	 * packets in squeue for the timewait state.
21219 	 */
21220 	CONN_DEC_REF(connp);
21221 	return (0);
21222 }
21223 
21224 /* ARGSUSED */
21225 int
21226 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21227     cred_t *cr)
21228 {
21229 	tcp_t		*tcp;
21230 	uint32_t	msize;
21231 	conn_t *connp = (conn_t *)proto_handle;
21232 	int32_t		tcpstate;
21233 
21234 	/* All Solaris components should pass a cred for this operation. */
21235 	ASSERT(cr != NULL);
21236 
21237 	ASSERT(connp->conn_ref >= 2);
21238 	ASSERT(connp->conn_upper_handle != NULL);
21239 
21240 	if (msg->msg_controllen != 0) {
21241 		freemsg(mp);
21242 		return (EOPNOTSUPP);
21243 	}
21244 
21245 	switch (DB_TYPE(mp)) {
21246 	case M_DATA:
21247 		tcp = connp->conn_tcp;
21248 		ASSERT(tcp != NULL);
21249 
21250 		tcpstate = tcp->tcp_state;
21251 		if (tcpstate < TCPS_ESTABLISHED) {
21252 			freemsg(mp);
21253 			/*
21254 			 * We return ENOTCONN if the endpoint is trying to
21255 			 * connect or has never been connected, and EPIPE if it
21256 			 * has been disconnected. The connection id helps us
21257 			 * distinguish between the last two cases.
21258 			 */
21259 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21260 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21261 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21262 			freemsg(mp);
21263 			return (EPIPE);
21264 		}
21265 
21266 		msize = msgdsize(mp);
21267 
21268 		mutex_enter(&tcp->tcp_non_sq_lock);
21269 		tcp->tcp_squeue_bytes += msize;
21270 		/*
21271 		 * Squeue Flow Control
21272 		 */
21273 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21274 			tcp_setqfull(tcp);
21275 		}
21276 		mutex_exit(&tcp->tcp_non_sq_lock);
21277 
21278 		/*
21279 		 * The application may pass in an address in the msghdr, but
21280 		 * we ignore the address on connection-oriented sockets.
21281 		 * Just like BSD this code does not generate an error for
21282 		 * TCP (a CONNREQUIRED socket) when sending to an address
21283 		 * passed in with sendto/sendmsg. Instead the data is
21284 		 * delivered on the connection as if no address had been
21285 		 * supplied.
21286 		 */
21287 		CONN_INC_REF(connp);
21288 
21289 		if (msg->msg_flags & MSG_OOB) {
21290 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21291 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21292 		} else {
21293 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21294 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21295 		}
21296 
21297 		return (0);
21298 
21299 	default:
21300 		ASSERT(0);
21301 	}
21302 
21303 	freemsg(mp);
21304 	return (0);
21305 }
21306 
21307 /* ARGSUSED2 */
21308 void
21309 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21310 {
21311 	int len;
21312 	uint32_t msize;
21313 	conn_t *connp = (conn_t *)arg;
21314 	tcp_t *tcp = connp->conn_tcp;
21315 
21316 	msize = msgdsize(mp);
21317 
21318 	len = msize - 1;
21319 	if (len < 0) {
21320 		freemsg(mp);
21321 		return;
21322 	}
21323 
21324 	/*
21325 	 * Try to force urgent data out on the wire. Even if we have unsent
21326 	 * data this will at least send the urgent flag.
21327 	 * XXX does not handle more flag correctly.
21328 	 */
21329 	len += tcp->tcp_unsent;
21330 	len += tcp->tcp_snxt;
21331 	tcp->tcp_urg = len;
21332 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21333 
21334 	/* Bypass tcp protocol for fused tcp loopback */
21335 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21336 		return;
21337 
21338 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21339 	if (DB_TYPE(mp) != M_DATA) {
21340 		mblk_t *mp1 = mp;
21341 		ASSERT(!IPCL_IS_NONSTR(connp));
21342 		mp = mp->b_cont;
21343 		freeb(mp1);
21344 	}
21345 	tcp_wput_data(tcp, mp, B_TRUE);
21346 }
21347 
21348 /* ARGSUSED3 */
21349 int
21350 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21351     socklen_t *addrlenp, cred_t *cr)
21352 {
21353 	conn_t	*connp = (conn_t *)proto_handle;
21354 	tcp_t	*tcp = connp->conn_tcp;
21355 
21356 	ASSERT(connp->conn_upper_handle != NULL);
21357 	/* All Solaris components should pass a cred for this operation. */
21358 	ASSERT(cr != NULL);
21359 
21360 	ASSERT(tcp != NULL);
21361 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21362 		return (ENOTCONN);
21363 
21364 	return (conn_getpeername(connp, addr, addrlenp));
21365 }
21366 
21367 /* ARGSUSED3 */
21368 int
21369 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21370     socklen_t *addrlenp, cred_t *cr)
21371 {
21372 	conn_t	*connp = (conn_t *)proto_handle;
21373 
21374 	/* All Solaris components should pass a cred for this operation. */
21375 	ASSERT(cr != NULL);
21376 
21377 	ASSERT(connp->conn_upper_handle != NULL);
21378 	return (conn_getsockname(connp, addr, addrlenp));
21379 }
21380 
21381 /*
21382  * tcp_fallback
21383  *
21384  * A direct socket is falling back to using STREAMS. The queue
21385  * that is being passed down was created using tcp_open() with
21386  * the SO_FALLBACK flag set. As a result, the queue is not
21387  * associated with a conn, and the q_ptrs instead contain the
21388  * dev and minor area that should be used.
21389  *
21390  * The 'issocket' flag indicates whether the FireEngine
21391  * optimizations should be used. The common case would be that
21392  * optimizations are enabled, and they might be subsequently
21393  * disabled using the _SIOCSOCKFALLBACK ioctl.
21394  */
21395 
21396 /*
21397  * An active connection is falling back to TPI. Gather all the information
21398  * required by the STREAM head and TPI sonode and send it up.
21399  */
21400 void
21401 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21402     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21403 {
21404 	conn_t			*connp = tcp->tcp_connp;
21405 	struct stroptions	*stropt;
21406 	struct T_capability_ack tca;
21407 	struct sockaddr_in6	laddr, faddr;
21408 	socklen_t 		laddrlen, faddrlen;
21409 	short			opts;
21410 	int			error;
21411 	mblk_t			*mp;
21412 
21413 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21414 	connp->conn_minor_arena = WR(q)->q_ptr;
21415 
21416 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21417 
21418 	connp->conn_rq = RD(q);
21419 	connp->conn_wq = WR(q);
21420 
21421 	WR(q)->q_qinfo = &tcp_sock_winit;
21422 
21423 	if (!issocket)
21424 		tcp_use_pure_tpi(tcp);
21425 
21426 	/*
21427 	 * free the helper stream
21428 	 */
21429 	ip_free_helper_stream(connp);
21430 
21431 	/*
21432 	 * Notify the STREAM head about options
21433 	 */
21434 	DB_TYPE(stropt_mp) = M_SETOPTS;
21435 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21436 	stropt_mp->b_wptr += sizeof (struct stroptions);
21437 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21438 
21439 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21440 	    tcp->tcp_tcps->tcps_wroff_xtra);
21441 	if (tcp->tcp_snd_sack_ok)
21442 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21443 	stropt->so_hiwat = connp->conn_rcvbuf;
21444 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21445 
21446 	putnext(RD(q), stropt_mp);
21447 
21448 	/*
21449 	 * Collect the information needed to sync with the sonode
21450 	 */
21451 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21452 
21453 	laddrlen = faddrlen = sizeof (sin6_t);
21454 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21455 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21456 	error = tcp_getpeername((sock_lower_handle_t)connp,
21457 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21458 	if (error != 0)
21459 		faddrlen = 0;
21460 
21461 	opts = 0;
21462 	if (connp->conn_oobinline)
21463 		opts |= SO_OOBINLINE;
21464 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21465 		opts |= SO_DONTROUTE;
21466 
21467 	/*
21468 	 * Notify the socket that the protocol is now quiescent,
21469 	 * and it's therefore safe move data from the socket
21470 	 * to the stream head.
21471 	 */
21472 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21473 	    (struct sockaddr *)&laddr, laddrlen,
21474 	    (struct sockaddr *)&faddr, faddrlen, opts);
21475 
21476 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21477 		tcp->tcp_rcv_list = mp->b_next;
21478 		mp->b_next = NULL;
21479 		/* We never do fallback for kernel RPC */
21480 		putnext(q, mp);
21481 	}
21482 	tcp->tcp_rcv_last_head = NULL;
21483 	tcp->tcp_rcv_last_tail = NULL;
21484 	tcp->tcp_rcv_cnt = 0;
21485 }
21486 
21487 /*
21488  * An eager is falling back to TPI. All we have to do is send
21489  * up a T_CONN_IND.
21490  */
21491 void
21492 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21493 {
21494 	tcp_t *listener = eager->tcp_listener;
21495 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21496 
21497 	ASSERT(listener != NULL);
21498 	ASSERT(mp != NULL);
21499 
21500 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21501 
21502 	/*
21503 	 * TLI/XTI applications will get confused by
21504 	 * sending eager as an option since it violates
21505 	 * the option semantics. So remove the eager as
21506 	 * option since TLI/XTI app doesn't need it anyway.
21507 	 */
21508 	if (!direct_sockfs) {
21509 		struct T_conn_ind *conn_ind;
21510 
21511 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21512 		conn_ind->OPT_length = 0;
21513 		conn_ind->OPT_offset = 0;
21514 	}
21515 
21516 	/*
21517 	 * Sockfs guarantees that the listener will not be closed
21518 	 * during fallback. So we can safely use the listener's queue.
21519 	 */
21520 	putnext(listener->tcp_connp->conn_rq, mp);
21521 }
21522 
21523 int
21524 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21525     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21526 {
21527 	tcp_t			*tcp;
21528 	conn_t 			*connp = (conn_t *)proto_handle;
21529 	int			error;
21530 	mblk_t			*stropt_mp;
21531 	mblk_t			*ordrel_mp;
21532 
21533 	tcp = connp->conn_tcp;
21534 
21535 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21536 	    NULL);
21537 
21538 	/* Pre-allocate the T_ordrel_ind mblk. */
21539 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21540 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21541 	    STR_NOSIG, NULL);
21542 	ordrel_mp->b_datap->db_type = M_PROTO;
21543 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21544 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21545 
21546 	/*
21547 	 * Enter the squeue so that no new packets can come in
21548 	 */
21549 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21550 	if (error != 0) {
21551 		/* failed to enter, free all the pre-allocated messages. */
21552 		freeb(stropt_mp);
21553 		freeb(ordrel_mp);
21554 		/*
21555 		 * We cannot process the eager, so at least send out a
21556 		 * RST so the peer can reconnect.
21557 		 */
21558 		if (tcp->tcp_listener != NULL) {
21559 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21560 			    tcp->tcp_conn_req_seqnum);
21561 		}
21562 		return (ENOMEM);
21563 	}
21564 
21565 	/*
21566 	 * Both endpoints must be of the same type (either STREAMS or
21567 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21568 	 * we have to unfuse.
21569 	 */
21570 	if (tcp->tcp_fused)
21571 		tcp_unfuse(tcp);
21572 
21573 	/*
21574 	 * No longer a direct socket
21575 	 */
21576 	connp->conn_flags &= ~IPCL_NONSTR;
21577 	tcp->tcp_ordrel_mp = ordrel_mp;
21578 
21579 	if (tcp->tcp_listener != NULL) {
21580 		/* The eager will deal with opts when accept() is called */
21581 		freeb(stropt_mp);
21582 		tcp_fallback_eager(tcp, direct_sockfs);
21583 	} else {
21584 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21585 		    quiesced_cb);
21586 	}
21587 
21588 	/*
21589 	 * There should be atleast two ref's (IP + TCP)
21590 	 */
21591 	ASSERT(connp->conn_ref >= 2);
21592 	squeue_synch_exit(connp->conn_sqp, connp);
21593 
21594 	return (0);
21595 }
21596 
21597 /* ARGSUSED */
21598 static void
21599 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21600 {
21601 	conn_t 	*connp = (conn_t *)arg;
21602 	tcp_t	*tcp = connp->conn_tcp;
21603 
21604 	freemsg(mp);
21605 
21606 	if (tcp->tcp_fused)
21607 		tcp_unfuse(tcp);
21608 
21609 	if (tcp_xmit_end(tcp) != 0) {
21610 		/*
21611 		 * We were crossing FINs and got a reset from
21612 		 * the other side. Just ignore it.
21613 		 */
21614 		if (connp->conn_debug) {
21615 			(void) strlog(TCP_MOD_ID, 0, 1,
21616 			    SL_ERROR|SL_TRACE,
21617 			    "tcp_shutdown_output() out of state %s",
21618 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21619 		}
21620 	}
21621 }
21622 
21623 /* ARGSUSED */
21624 int
21625 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21626 {
21627 	conn_t  *connp = (conn_t *)proto_handle;
21628 	tcp_t   *tcp = connp->conn_tcp;
21629 
21630 	ASSERT(connp->conn_upper_handle != NULL);
21631 
21632 	/* All Solaris components should pass a cred for this operation. */
21633 	ASSERT(cr != NULL);
21634 
21635 	/*
21636 	 * X/Open requires that we check the connected state.
21637 	 */
21638 	if (tcp->tcp_state < TCPS_SYN_SENT)
21639 		return (ENOTCONN);
21640 
21641 	/* shutdown the send side */
21642 	if (how != SHUT_RD) {
21643 		mblk_t *bp;
21644 
21645 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21646 		CONN_INC_REF(connp);
21647 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21648 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21649 
21650 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21651 		    SOCK_OPCTL_SHUT_SEND, 0);
21652 	}
21653 
21654 	/* shutdown the recv side */
21655 	if (how != SHUT_WR)
21656 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21657 		    SOCK_OPCTL_SHUT_RECV, 0);
21658 
21659 	return (0);
21660 }
21661 
21662 /*
21663  * SOP_LISTEN() calls into tcp_listen().
21664  */
21665 /* ARGSUSED */
21666 int
21667 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21668 {
21669 	conn_t	*connp = (conn_t *)proto_handle;
21670 	int 	error;
21671 	squeue_t *sqp = connp->conn_sqp;
21672 
21673 	ASSERT(connp->conn_upper_handle != NULL);
21674 
21675 	/* All Solaris components should pass a cred for this operation. */
21676 	ASSERT(cr != NULL);
21677 
21678 	error = squeue_synch_enter(sqp, connp, NULL);
21679 	if (error != 0) {
21680 		/* failed to enter */
21681 		return (ENOBUFS);
21682 	}
21683 
21684 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21685 	if (error == 0) {
21686 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21687 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21688 	} else if (error < 0) {
21689 		if (error == -TOUTSTATE)
21690 			error = EINVAL;
21691 		else
21692 			error = proto_tlitosyserr(-error);
21693 	}
21694 	squeue_synch_exit(sqp, connp);
21695 	return (error);
21696 }
21697 
21698 static int
21699 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21700     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21701 {
21702 	tcp_t		*tcp = connp->conn_tcp;
21703 	int		error = 0;
21704 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21705 
21706 	/* All Solaris components should pass a cred for this operation. */
21707 	ASSERT(cr != NULL);
21708 
21709 	if (tcp->tcp_state >= TCPS_BOUND) {
21710 		if ((tcp->tcp_state == TCPS_BOUND ||
21711 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21712 			/*
21713 			 * Handle listen() increasing backlog.
21714 			 * This is more "liberal" then what the TPI spec
21715 			 * requires but is needed to avoid a t_unbind
21716 			 * when handling listen() since the port number
21717 			 * might be "stolen" between the unbind and bind.
21718 			 */
21719 			goto do_listen;
21720 		}
21721 		if (connp->conn_debug) {
21722 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21723 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21724 		}
21725 		return (-TOUTSTATE);
21726 	} else {
21727 		if (sa == NULL) {
21728 			sin6_t	addr;
21729 			sin_t *sin;
21730 			sin6_t *sin6;
21731 
21732 			ASSERT(IPCL_IS_NONSTR(connp));
21733 			/* Do an implicit bind: Request for a generic port. */
21734 			if (connp->conn_family == AF_INET) {
21735 				len = sizeof (sin_t);
21736 				sin = (sin_t *)&addr;
21737 				*sin = sin_null;
21738 				sin->sin_family = AF_INET;
21739 			} else {
21740 				ASSERT(connp->conn_family == AF_INET6);
21741 				len = sizeof (sin6_t);
21742 				sin6 = (sin6_t *)&addr;
21743 				*sin6 = sin6_null;
21744 				sin6->sin6_family = AF_INET6;
21745 			}
21746 			sa = (struct sockaddr *)&addr;
21747 		}
21748 
21749 		error = tcp_bind_check(connp, sa, len, cr,
21750 		    bind_to_req_port_only);
21751 		if (error)
21752 			return (error);
21753 		/* Fall through and do the fanout insertion */
21754 	}
21755 
21756 do_listen:
21757 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21758 	tcp->tcp_conn_req_max = backlog;
21759 	if (tcp->tcp_conn_req_max) {
21760 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21761 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21762 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21763 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21764 		/*
21765 		 * If this is a listener, do not reset the eager list
21766 		 * and other stuffs.  Note that we don't check if the
21767 		 * existing eager list meets the new tcp_conn_req_max
21768 		 * requirement.
21769 		 */
21770 		if (tcp->tcp_state != TCPS_LISTEN) {
21771 			tcp->tcp_state = TCPS_LISTEN;
21772 			/* Initialize the chain. Don't need the eager_lock */
21773 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21774 			tcp->tcp_eager_next_drop_q0 = tcp;
21775 			tcp->tcp_eager_prev_drop_q0 = tcp;
21776 			tcp->tcp_second_ctimer_threshold =
21777 			    tcps->tcps_ip_abort_linterval;
21778 		}
21779 	}
21780 
21781 	/*
21782 	 * We need to make sure that the conn_recv is set to a non-null
21783 	 * value before we insert the conn into the classifier table.
21784 	 * This is to avoid a race with an incoming packet which does an
21785 	 * ipcl_classify().
21786 	 * We initially set it to tcp_input_listener_unbound to try to
21787 	 * pick a good squeue for the listener when the first SYN arrives.
21788 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21789 	 * first SYN.
21790 	 */
21791 	connp->conn_recv = tcp_input_listener_unbound;
21792 
21793 	/* Insert the listener in the classifier table */
21794 	error = ip_laddr_fanout_insert(connp);
21795 	if (error != 0) {
21796 		/* Undo the bind - release the port number */
21797 		tcp->tcp_state = TCPS_IDLE;
21798 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21799 
21800 		connp->conn_laddr_v6 = ipv6_all_zeros;
21801 		connp->conn_saddr_v6 = ipv6_all_zeros;
21802 		connp->conn_ports = 0;
21803 
21804 		if (connp->conn_anon_port) {
21805 			zone_t		*zone;
21806 
21807 			zone = crgetzone(cr);
21808 			connp->conn_anon_port = B_FALSE;
21809 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21810 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21811 		}
21812 		connp->conn_mlp_type = mlptSingle;
21813 
21814 		tcp_bind_hash_remove(tcp);
21815 		return (error);
21816 	} else {
21817 		/*
21818 		 * If there is a connection limit, allocate and initialize
21819 		 * the counter struct.  Note that since listen can be called
21820 		 * multiple times, the struct may have been allready allocated.
21821 		 */
21822 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21823 		    tcp->tcp_listen_cnt == NULL) {
21824 			tcp_listen_cnt_t *tlc;
21825 			uint32_t ratio;
21826 
21827 			ratio = tcp_find_listener_conf(tcps,
21828 			    ntohs(connp->conn_lport));
21829 			if (ratio != 0) {
21830 				uint32_t mem_ratio, tot_buf;
21831 
21832 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21833 				    KM_SLEEP);
21834 				/*
21835 				 * Calculate the connection limit based on
21836 				 * the configured ratio and maxusers.  Maxusers
21837 				 * are calculated based on memory size,
21838 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21839 				 * and conn_sndbuf may change after a
21840 				 * connection is accepted.  So what we have
21841 				 * is only an approximation.
21842 				 */
21843 				if ((tot_buf = connp->conn_rcvbuf +
21844 				    connp->conn_sndbuf) < MB) {
21845 					mem_ratio = MB / tot_buf;
21846 					tlc->tlc_max = maxusers / ratio *
21847 					    mem_ratio;
21848 				} else {
21849 					mem_ratio = tot_buf / MB;
21850 					tlc->tlc_max = maxusers / ratio /
21851 					    mem_ratio;
21852 				}
21853 				/* At least we should allow two connections! */
21854 				if (tlc->tlc_max <= tcp_min_conn_listener)
21855 					tlc->tlc_max = tcp_min_conn_listener;
21856 				tlc->tlc_cnt = 1;
21857 				tlc->tlc_drop = 0;
21858 				tcp->tcp_listen_cnt = tlc;
21859 			}
21860 		}
21861 	}
21862 	return (error);
21863 }
21864 
21865 void
21866 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21867 {
21868 	conn_t  *connp = (conn_t *)proto_handle;
21869 	tcp_t	*tcp = connp->conn_tcp;
21870 	mblk_t *mp;
21871 	int error;
21872 
21873 	ASSERT(connp->conn_upper_handle != NULL);
21874 
21875 	/*
21876 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21877 	 * is currently running.
21878 	 */
21879 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21880 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21881 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21882 		return;
21883 	}
21884 	tcp->tcp_rsrv_mp = NULL;
21885 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21886 
21887 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21888 	ASSERT(error == 0);
21889 
21890 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21891 	tcp->tcp_rsrv_mp = mp;
21892 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21893 
21894 	if (tcp->tcp_fused) {
21895 		tcp_fuse_backenable(tcp);
21896 	} else {
21897 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21898 		/*
21899 		 * Send back a window update immediately if TCP is above
21900 		 * ESTABLISHED state and the increase of the rcv window
21901 		 * that the other side knows is at least 1 MSS after flow
21902 		 * control is lifted.
21903 		 */
21904 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21905 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21906 			tcp_xmit_ctl(NULL, tcp,
21907 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21908 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21909 		}
21910 	}
21911 
21912 	squeue_synch_exit(connp->conn_sqp, connp);
21913 }
21914 
21915 /* ARGSUSED */
21916 int
21917 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21918     int mode, int32_t *rvalp, cred_t *cr)
21919 {
21920 	conn_t  	*connp = (conn_t *)proto_handle;
21921 	int		error;
21922 
21923 	ASSERT(connp->conn_upper_handle != NULL);
21924 
21925 	/* All Solaris components should pass a cred for this operation. */
21926 	ASSERT(cr != NULL);
21927 
21928 	/*
21929 	 * If we don't have a helper stream then create one.
21930 	 * ip_create_helper_stream takes care of locking the conn_t,
21931 	 * so this check for NULL is just a performance optimization.
21932 	 */
21933 	if (connp->conn_helper_info == NULL) {
21934 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21935 
21936 		/*
21937 		 * Create a helper stream for non-STREAMS socket.
21938 		 */
21939 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21940 		if (error != 0) {
21941 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21942 			    "failed %d\n", error));
21943 			return (error);
21944 		}
21945 	}
21946 
21947 	switch (cmd) {
21948 		case ND_SET:
21949 		case ND_GET:
21950 		case _SIOCSOCKFALLBACK:
21951 		case TCP_IOC_ABORT_CONN:
21952 		case TI_GETPEERNAME:
21953 		case TI_GETMYNAME:
21954 			ip1dbg(("tcp_ioctl: cmd 0x%x on non streams socket",
21955 			    cmd));
21956 			error = EINVAL;
21957 			break;
21958 		default:
21959 			/*
21960 			 * If the conn is not closing, pass on to IP using
21961 			 * helper stream. Bump the ioctlref to prevent tcp_close
21962 			 * from closing the rq/wq out from underneath the ioctl
21963 			 * if it ends up queued or aborted/interrupted.
21964 			 */
21965 			mutex_enter(&connp->conn_lock);
21966 			if (connp->conn_state_flags & (CONN_CLOSING)) {
21967 				mutex_exit(&connp->conn_lock);
21968 				error = EINVAL;
21969 				break;
21970 			}
21971 			CONN_INC_IOCTLREF_LOCKED(connp);
21972 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21973 			    cmd, arg, mode, cr, rvalp);
21974 			CONN_DEC_IOCTLREF(connp);
21975 			break;
21976 	}
21977 	return (error);
21978 }
21979 
21980 sock_downcalls_t sock_tcp_downcalls = {
21981 	tcp_activate,
21982 	tcp_accept,
21983 	tcp_bind,
21984 	tcp_listen,
21985 	tcp_connect,
21986 	tcp_getpeername,
21987 	tcp_getsockname,
21988 	tcp_getsockopt,
21989 	tcp_setsockopt,
21990 	tcp_sendmsg,
21991 	NULL,
21992 	NULL,
21993 	NULL,
21994 	tcp_shutdown,
21995 	tcp_clr_flowctrl,
21996 	tcp_ioctl,
21997 	tcp_close,
21998 };
21999 
22000 /*
22001  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
22002  */
22003 static void
22004 tcp_reclaim_timer(void *arg)
22005 {
22006 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
22007 
22008 	mutex_enter(&tcps->tcps_reclaim_lock);
22009 	tcps->tcps_reclaim = B_FALSE;
22010 	tcps->tcps_reclaim_tid = 0;
22011 	mutex_exit(&tcps->tcps_reclaim_lock);
22012 }
22013 
22014 /*
22015  * Kmem reclaim call back function.  When the system is under memory
22016  * pressure, we set the TCP stack variable tcps_reclaim to true.  This
22017  * variable is reset to false after tcps_reclaim_period msecs.  During this
22018  * period, TCP will be more aggressive in aborting connections not making
22019  * progress, meaning retransmitting for some time (tcp_early_abort seconds).
22020  * TCP will also not accept new connection request for those listeners whose
22021  * q or q0 is not empty.
22022  */
22023 /* ARGSUSED */
22024 void
22025 tcp_conn_reclaim(void *arg)
22026 {
22027 	netstack_handle_t nh;
22028 	netstack_t *ns;
22029 	tcp_stack_t *tcps;
22030 	extern pgcnt_t lotsfree, needfree;
22031 
22032 	if (!tcp_do_reclaim)
22033 		return;
22034 
22035 	/*
22036 	 * The reclaim function may be called even when the system is not
22037 	 * really under memory pressure.
22038 	 */
22039 	if (freemem >= lotsfree + needfree)
22040 		return;
22041 
22042 	netstack_next_init(&nh);
22043 	while ((ns = netstack_next(&nh)) != NULL) {
22044 		tcps = ns->netstack_tcp;
22045 		mutex_enter(&tcps->tcps_reclaim_lock);
22046 		if (!tcps->tcps_reclaim) {
22047 			tcps->tcps_reclaim = B_TRUE;
22048 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
22049 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
22050 		}
22051 		mutex_exit(&tcps->tcps_reclaim_lock);
22052 		netstack_rele(ns);
22053 	}
22054 	netstack_next_fini(&nh);
22055 }
22056 
22057 /*
22058  * Given a tcp_stack_t and a port (in host byte order), find a listener
22059  * configuration for that port and return the ratio.
22060  */
22061 static uint32_t
22062 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
22063 {
22064 	tcp_listener_t	*tl;
22065 	uint32_t ratio = 0;
22066 
22067 	mutex_enter(&tcps->tcps_listener_conf_lock);
22068 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22069 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22070 		if (tl->tl_port == port) {
22071 			ratio = tl->tl_ratio;
22072 			break;
22073 		}
22074 	}
22075 	mutex_exit(&tcps->tcps_listener_conf_lock);
22076 	return (ratio);
22077 }
22078 
22079 /*
22080  * Ndd param helper routine to return the current list of listener limit
22081  * configuration.
22082  */
22083 /* ARGSUSED */
22084 static int
22085 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22086 {
22087 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22088 	tcp_listener_t	*tl;
22089 
22090 	mutex_enter(&tcps->tcps_listener_conf_lock);
22091 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22092 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22093 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
22094 	}
22095 	mutex_exit(&tcps->tcps_listener_conf_lock);
22096 	return (0);
22097 }
22098 
22099 /*
22100  * Ndd param helper routine to add a new listener limit configuration.
22101  */
22102 /* ARGSUSED */
22103 static int
22104 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22105     cred_t *cr)
22106 {
22107 	tcp_listener_t	*new_tl;
22108 	tcp_listener_t	*tl;
22109 	long		lport;
22110 	long		ratio;
22111 	char		*colon;
22112 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22113 
22114 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
22115 	    lport > USHRT_MAX || *colon != ':') {
22116 		return (EINVAL);
22117 	}
22118 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
22119 		return (EINVAL);
22120 
22121 	mutex_enter(&tcps->tcps_listener_conf_lock);
22122 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22123 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22124 		/* There is an existing entry, so update its ratio value. */
22125 		if (tl->tl_port == lport) {
22126 			tl->tl_ratio = ratio;
22127 			mutex_exit(&tcps->tcps_listener_conf_lock);
22128 			return (0);
22129 		}
22130 	}
22131 
22132 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22133 	    NULL) {
22134 		mutex_exit(&tcps->tcps_listener_conf_lock);
22135 		return (ENOMEM);
22136 	}
22137 
22138 	new_tl->tl_port = lport;
22139 	new_tl->tl_ratio = ratio;
22140 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22141 	mutex_exit(&tcps->tcps_listener_conf_lock);
22142 	return (0);
22143 }
22144 
22145 /*
22146  * Ndd param helper routine to remove a listener limit configuration.
22147  */
22148 /* ARGSUSED */
22149 static int
22150 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22151     cred_t *cr)
22152 {
22153 	tcp_listener_t	*tl;
22154 	long		lport;
22155 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22156 
22157 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22158 	    lport > USHRT_MAX) {
22159 		return (EINVAL);
22160 	}
22161 	mutex_enter(&tcps->tcps_listener_conf_lock);
22162 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22163 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22164 		if (tl->tl_port == lport) {
22165 			list_remove(&tcps->tcps_listener_conf, tl);
22166 			mutex_exit(&tcps->tcps_listener_conf_lock);
22167 			kmem_free(tl, sizeof (tcp_listener_t));
22168 			return (0);
22169 		}
22170 	}
22171 	mutex_exit(&tcps->tcps_listener_conf_lock);
22172 	return (ESRCH);
22173 }
22174 
22175 /*
22176  * To remove all listener limit configuration in a tcp_stack_t.
22177  */
22178 static void
22179 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22180 {
22181 	tcp_listener_t	*tl;
22182 
22183 	mutex_enter(&tcps->tcps_listener_conf_lock);
22184 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22185 		list_remove(&tcps->tcps_listener_conf, tl);
22186 		kmem_free(tl, sizeof (tcp_listener_t));
22187 	}
22188 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22189 	list_destroy(&tcps->tcps_listener_conf);
22190 }
22191