xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision d02b2ecc45d7aceb5456026da8da5fbe6402d17b)
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 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
30 
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/sdt.h>
49 #include <sys/vtrace.h>
50 #include <sys/kmem.h>
51 #include <sys/ethernet.h>
52 #include <sys/cpuvar.h>
53 #include <sys/dlpi.h>
54 #include <sys/multidata.h>
55 #include <sys/multidata_impl.h>
56 #include <sys/pattr.h>
57 #include <sys/policy.h>
58 #include <sys/priv.h>
59 #include <sys/zone.h>
60 #include <sys/sunldi.h>
61 
62 #include <sys/errno.h>
63 #include <sys/signal.h>
64 #include <sys/socket.h>
65 #include <sys/sockio.h>
66 #include <sys/isa_defs.h>
67 #include <sys/md5.h>
68 #include <sys/random.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 #include <inet/ipsec_impl.h>
76 
77 #include <inet/common.h>
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip_ndp.h>
82 #include <inet/mi.h>
83 #include <inet/mib2.h>
84 #include <inet/nd.h>
85 #include <inet/optcom.h>
86 #include <inet/snmpcom.h>
87 #include <inet/kstatcom.h>
88 #include <inet/tcp.h>
89 #include <inet/tcp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 #include <inet/tcp_trace.h>
94 
95 #include <inet/ipclassifier.h>
96 #include <inet/ip_ire.h>
97 #include <inet/ip_ftable.h>
98 #include <inet/ip_if.h>
99 #include <inet/ipp_common.h>
100 #include <inet/ip_netinfo.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <sys/sdt.h>
106 #include <rpc/pmap_prot.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
130  * squeue_fill). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * IPsec notes :
221  *
222  * Since a packet is always executed on the correct TCP perimeter
223  * all IPsec processing is defered to IP including checking new
224  * connections and setting IPSEC policies for new connection. The
225  * only exception is tcp_xmit_listeners_reset() which is called
226  * directly from IP and needs to policy check to see if TH_RST
227  * can be sent out.
228  *
229  * PFHooks notes :
230  *
231  * For mdt case, one meta buffer contains multiple packets. Mblks for every
232  * packet are assembled and passed to the hooks. When packets are blocked,
233  * or boundary of any packet is changed, the mdt processing is stopped, and
234  * packets of the meta buffer are send to the IP path one by one.
235  */
236 
237 extern major_t TCP6_MAJ;
238 
239 /*
240  * Values for squeue switch:
241  * 1: squeue_enter_nodrain
242  * 2: squeue_enter
243  * 3: squeue_fill
244  */
245 int tcp_squeue_close = 2;	/* Setable in /etc/system */
246 int tcp_squeue_wput = 2;
247 
248 squeue_func_t tcp_squeue_close_proc;
249 squeue_func_t tcp_squeue_wput_proc;
250 
251 /*
252  * This controls how tiny a write must be before we try to copy it
253  * into the the mblk on the tail of the transmit queue.  Not much
254  * speedup is observed for values larger than sixteen.  Zero will
255  * disable the optimisation.
256  */
257 int tcp_tx_pull_len = 16;
258 
259 /*
260  * TCP Statistics.
261  *
262  * How TCP statistics work.
263  *
264  * There are two types of statistics invoked by two macros.
265  *
266  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
267  * supposed to be used in non MT-hot paths of the code.
268  *
269  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
270  * supposed to be used for DEBUG purposes and may be used on a hot path.
271  *
272  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
273  * (use "kstat tcp" to get them).
274  *
275  * There is also additional debugging facility that marks tcp_clean_death()
276  * instances and saves them in tcp_t structure. It is triggered by
277  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
278  * tcp_clean_death() calls that counts the number of times each tag was hit. It
279  * is triggered by TCP_CLD_COUNTERS define.
280  *
281  * How to add new counters.
282  *
283  * 1) Add a field in the tcp_stat structure describing your counter.
284  * 2) Add a line in the template in tcp_kstat2_init() with the name
285  *    of the counter.
286  *
287  *    IMPORTANT!! - make sure that both are in sync !!
288  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
289  *
290  * Please avoid using private counters which are not kstat-exported.
291  *
292  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
293  * in tcp_t structure.
294  *
295  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
296  */
297 
298 #ifndef TCP_DEBUG_COUNTER
299 #ifdef DEBUG
300 #define	TCP_DEBUG_COUNTER 1
301 #else
302 #define	TCP_DEBUG_COUNTER 0
303 #endif
304 #endif
305 
306 #define	TCP_CLD_COUNTERS 0
307 
308 #define	TCP_TAG_CLEAN_DEATH 1
309 #define	TCP_MAX_CLEAN_DEATH_TAG 32
310 
311 #ifdef lint
312 static int _lint_dummy_;
313 #endif
314 
315 #if TCP_CLD_COUNTERS
316 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
317 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
318 #elif defined(lint)
319 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
320 #else
321 #define	TCP_CLD_STAT(x)
322 #endif
323 
324 #if TCP_DEBUG_COUNTER
325 #define	TCP_DBGSTAT(tcps, x)	\
326 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
327 #define	TCP_G_DBGSTAT(x)	\
328 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
329 #elif defined(lint)
330 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
331 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
332 #else
333 #define	TCP_DBGSTAT(tcps, x)
334 #define	TCP_G_DBGSTAT(x)
335 #endif
336 
337 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
338 
339 tcp_g_stat_t	tcp_g_statistics;
340 kstat_t		*tcp_g_kstat;
341 
342 /*
343  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
344  * tcp write side.
345  */
346 #define	CALL_IP_WPUT(connp, q, mp) {					\
347 	tcp_stack_t	*tcps;						\
348 									\
349 	tcps = connp->conn_netstack->netstack_tcp;			\
350 	ASSERT(((q)->q_flag & QREADR) == 0);				\
351 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
352 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
353 }
354 
355 /* Macros for timestamp comparisons */
356 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
357 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
358 
359 /*
360  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
361  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
362  * by adding three components: a time component which grows by 1 every 4096
363  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
364  * a per-connection component which grows by 125000 for every new connection;
365  * and an "extra" component that grows by a random amount centered
366  * approximately on 64000.  This causes the the ISS generator to cycle every
367  * 4.89 hours if no TCP connections are made, and faster if connections are
368  * made.
369  *
370  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
371  * components: a time component which grows by 250000 every second; and
372  * a per-connection component which grows by 125000 for every new connections.
373  *
374  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
375  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
376  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
377  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
378  * password.
379  */
380 #define	ISS_INCR	250000
381 #define	ISS_NSEC_SHT	12
382 
383 static sin_t	sin_null;	/* Zero address for quick clears */
384 static sin6_t	sin6_null;	/* Zero address for quick clears */
385 
386 /*
387  * This implementation follows the 4.3BSD interpretation of the urgent
388  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
389  * incompatible changes in protocols like telnet and rlogin.
390  */
391 #define	TCP_OLD_URP_INTERPRETATION	1
392 
393 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
394 	(TCP_IS_DETACHED(tcp) && \
395 	    (!(tcp)->tcp_hard_binding))
396 
397 /*
398  * TCP reassembly macros.  We hide starting and ending sequence numbers in
399  * b_next and b_prev of messages on the reassembly queue.  The messages are
400  * chained using b_cont.  These macros are used in tcp_reass() so we don't
401  * have to see the ugly casts and assignments.
402  */
403 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
404 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
405 					(mblk_t *)(uintptr_t)(u))
406 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
407 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
408 					(mblk_t *)(uintptr_t)(u))
409 
410 /*
411  * Implementation of TCP Timers.
412  * =============================
413  *
414  * INTERFACE:
415  *
416  * There are two basic functions dealing with tcp timers:
417  *
418  *	timeout_id_t	tcp_timeout(connp, func, time)
419  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
420  *	TCP_TIMER_RESTART(tcp, intvl)
421  *
422  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
423  * after 'time' ticks passed. The function called by timeout() must adhere to
424  * the same restrictions as a driver soft interrupt handler - it must not sleep
425  * or call other functions that might sleep. The value returned is the opaque
426  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
427  * cancel the request. The call to tcp_timeout() may fail in which case it
428  * returns zero. This is different from the timeout(9F) function which never
429  * fails.
430  *
431  * The call-back function 'func' always receives 'connp' as its single
432  * argument. It is always executed in the squeue corresponding to the tcp
433  * structure. The tcp structure is guaranteed to be present at the time the
434  * call-back is called.
435  *
436  * NOTE: The call-back function 'func' is never called if tcp is in
437  * 	the TCPS_CLOSED state.
438  *
439  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
440  * request. locks acquired by the call-back routine should not be held across
441  * the call to tcp_timeout_cancel() or a deadlock may result.
442  *
443  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
444  * Otherwise, it returns an integer value greater than or equal to 0. In
445  * particular, if the call-back function is already placed on the squeue, it can
446  * not be canceled.
447  *
448  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
449  * 	within squeue context corresponding to the tcp instance. Since the
450  *	call-back is also called via the same squeue, there are no race
451  *	conditions described in untimeout(9F) manual page since all calls are
452  *	strictly serialized.
453  *
454  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
455  *	stored in tcp_timer_tid and starts a new one using
456  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
457  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
458  *	field.
459  *
460  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
461  *	call-back may still be called, so it is possible tcp_timer() will be
462  *	called several times. This should not be a problem since tcp_timer()
463  *	should always check the tcp instance state.
464  *
465  *
466  * IMPLEMENTATION:
467  *
468  * TCP timers are implemented using three-stage process. The call to
469  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
470  * when the timer expires. The tcp_timer_callback() arranges the call of the
471  * tcp_timer_handler() function via squeue corresponding to the tcp
472  * instance. The tcp_timer_handler() calls actual requested timeout call-back
473  * and passes tcp instance as an argument to it. Information is passed between
474  * stages using the tcp_timer_t structure which contains the connp pointer, the
475  * tcp call-back to call and the timeout id returned by the timeout(9F).
476  *
477  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
478  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
479  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
480  * returns the pointer to this mblk.
481  *
482  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
483  * looks like a normal mblk without actual dblk attached to it.
484  *
485  * To optimize performance each tcp instance holds a small cache of timer
486  * mblocks. In the current implementation it caches up to two timer mblocks per
487  * tcp instance. The cache is preserved over tcp frees and is only freed when
488  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
489  * timer processing happens on a corresponding squeue, the cache manipulation
490  * does not require any locks. Experiments show that majority of timer mblocks
491  * allocations are satisfied from the tcp cache and do not involve kmem calls.
492  *
493  * The tcp_timeout() places a refhold on the connp instance which guarantees
494  * that it will be present at the time the call-back function fires. The
495  * tcp_timer_handler() drops the reference after calling the call-back, so the
496  * call-back function does not need to manipulate the references explicitly.
497  */
498 
499 typedef struct tcp_timer_s {
500 	conn_t	*connp;
501 	void 	(*tcpt_proc)(void *);
502 	timeout_id_t   tcpt_tid;
503 } tcp_timer_t;
504 
505 static kmem_cache_t *tcp_timercache;
506 kmem_cache_t	*tcp_sack_info_cache;
507 kmem_cache_t	*tcp_iphc_cache;
508 
509 /*
510  * For scalability, we must not run a timer for every TCP connection
511  * in TIME_WAIT state.  To see why, consider (for time wait interval of
512  * 4 minutes):
513  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
514  *
515  * This list is ordered by time, so you need only delete from the head
516  * until you get to entries which aren't old enough to delete yet.
517  * The list consists of only the detached TIME_WAIT connections.
518  *
519  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
520  * becomes detached TIME_WAIT (either by changing the state and already
521  * being detached or the other way around). This means that the TIME_WAIT
522  * state can be extended (up to doubled) if the connection doesn't become
523  * detached for a long time.
524  *
525  * The list manipulations (including tcp_time_wait_next/prev)
526  * are protected by the tcp_time_wait_lock. The content of the
527  * detached TIME_WAIT connections is protected by the normal perimeters.
528  *
529  * This list is per squeue and squeues are shared across the tcp_stack_t's.
530  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
531  * and conn_netstack.
532  * The tcp_t's that are added to tcp_free_list are disassociated and
533  * have NULL tcp_tcps and conn_netstack pointers.
534  */
535 typedef struct tcp_squeue_priv_s {
536 	kmutex_t	tcp_time_wait_lock;
537 	timeout_id_t	tcp_time_wait_tid;
538 	tcp_t		*tcp_time_wait_head;
539 	tcp_t		*tcp_time_wait_tail;
540 	tcp_t		*tcp_free_list;
541 	uint_t		tcp_free_list_cnt;
542 } tcp_squeue_priv_t;
543 
544 /*
545  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
546  * Running it every 5 seconds seems to give the best results.
547  */
548 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
549 
550 /*
551  * To prevent memory hog, limit the number of entries in tcp_free_list
552  * to 1% of available memory / number of cpus
553  */
554 uint_t tcp_free_list_max_cnt = 0;
555 
556 #define	TCP_XMIT_LOWATER	4096
557 #define	TCP_XMIT_HIWATER	49152
558 #define	TCP_RECV_LOWATER	2048
559 #define	TCP_RECV_HIWATER	49152
560 
561 /*
562  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
563  */
564 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
565 
566 #define	TIDUSZ	4096	/* transport interface data unit size */
567 
568 /*
569  * Bind hash list size and has function.  It has to be a power of 2 for
570  * hashing.
571  */
572 #define	TCP_BIND_FANOUT_SIZE	512
573 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
574 /*
575  * Size of listen and acceptor hash list.  It has to be a power of 2 for
576  * hashing.
577  */
578 #define	TCP_FANOUT_SIZE		256
579 
580 #ifdef	_ILP32
581 #define	TCP_ACCEPTOR_HASH(accid)					\
582 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
583 #else
584 #define	TCP_ACCEPTOR_HASH(accid)					\
585 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
586 #endif	/* _ILP32 */
587 
588 #define	IP_ADDR_CACHE_SIZE	2048
589 #define	IP_ADDR_CACHE_HASH(faddr)					\
590 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
591 
592 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
593 #define	TCP_HSP_HASH_SIZE 256
594 
595 #define	TCP_HSP_HASH(addr)					\
596 	(((addr>>24) ^ (addr >>16) ^			\
597 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
598 
599 /*
600  * TCP options struct returned from tcp_parse_options.
601  */
602 typedef struct tcp_opt_s {
603 	uint32_t	tcp_opt_mss;
604 	uint32_t	tcp_opt_wscale;
605 	uint32_t	tcp_opt_ts_val;
606 	uint32_t	tcp_opt_ts_ecr;
607 	tcp_t		*tcp;
608 } tcp_opt_t;
609 
610 /*
611  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
612  */
613 
614 #ifdef _BIG_ENDIAN
615 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
616 	(TCPOPT_TSTAMP << 8) | 10)
617 #else
618 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
619 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
620 #endif
621 
622 /*
623  * Flags returned from tcp_parse_options.
624  */
625 #define	TCP_OPT_MSS_PRESENT	1
626 #define	TCP_OPT_WSCALE_PRESENT	2
627 #define	TCP_OPT_TSTAMP_PRESENT	4
628 #define	TCP_OPT_SACK_OK_PRESENT	8
629 #define	TCP_OPT_SACK_PRESENT	16
630 
631 /* TCP option length */
632 #define	TCPOPT_NOP_LEN		1
633 #define	TCPOPT_MAXSEG_LEN	4
634 #define	TCPOPT_WS_LEN		3
635 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
636 #define	TCPOPT_TSTAMP_LEN	10
637 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
638 #define	TCPOPT_SACK_OK_LEN	2
639 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
640 #define	TCPOPT_REAL_SACK_LEN	4
641 #define	TCPOPT_MAX_SACK_LEN	36
642 #define	TCPOPT_HEADER_LEN	2
643 
644 /* TCP cwnd burst factor. */
645 #define	TCP_CWND_INFINITE	65535
646 #define	TCP_CWND_SS		3
647 #define	TCP_CWND_NORMAL		5
648 
649 /* Maximum TCP initial cwin (start/restart). */
650 #define	TCP_MAX_INIT_CWND	8
651 
652 /*
653  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
654  * either tcp_slow_start_initial or tcp_slow_start_after idle
655  * depending on the caller.  If the upper layer has not used the
656  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
657  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
658  * If the upper layer has changed set the tcp_init_cwnd, just use
659  * it to calculate the tcp_cwnd.
660  */
661 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
662 {									\
663 	if ((tcp)->tcp_init_cwnd == 0) {				\
664 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
665 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
666 	} else {							\
667 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
668 	}								\
669 	tcp->tcp_cwnd_cnt = 0;						\
670 }
671 
672 /* TCP Timer control structure */
673 typedef struct tcpt_s {
674 	pfv_t	tcpt_pfv;	/* The routine we are to call */
675 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
676 } tcpt_t;
677 
678 /* Host Specific Parameter structure */
679 typedef struct tcp_hsp {
680 	struct tcp_hsp	*tcp_hsp_next;
681 	in6_addr_t	tcp_hsp_addr_v6;
682 	in6_addr_t	tcp_hsp_subnet_v6;
683 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
684 	int32_t		tcp_hsp_sendspace;
685 	int32_t		tcp_hsp_recvspace;
686 	int32_t		tcp_hsp_tstamp;
687 } tcp_hsp_t;
688 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
689 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
690 
691 /*
692  * Functions called directly via squeue having a prototype of edesc_t.
693  */
694 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
695 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
696 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
697 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
698 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
699 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
700 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
701 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
702 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
703 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
704 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
705 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
706 
707 
708 /* Prototype for TCP functions */
709 static void	tcp_random_init(void);
710 int		tcp_random(void);
711 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
712 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
713 		    tcp_t *eager);
714 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
715 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
716     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
717     boolean_t user_specified);
718 static void	tcp_closei_local(tcp_t *tcp);
719 static void	tcp_close_detached(tcp_t *tcp);
720 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
721 			mblk_t *idmp, mblk_t **defermp);
722 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
723 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
724 		    in_port_t dstport, uint_t srcid);
725 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
726 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
727 		    uint32_t scope_id);
728 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
729 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
730 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
731 static char	*tcp_display(tcp_t *tcp, char *, char);
732 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
733 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
734 static void	tcp_eager_unlink(tcp_t *tcp);
735 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
736 		    int unixerr);
737 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
738 		    int tlierr, int unixerr);
739 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
740 		    cred_t *cr);
741 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
742 		    char *value, caddr_t cp, cred_t *cr);
743 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
744 		    char *value, caddr_t cp, cred_t *cr);
745 static int	tcp_tpistate(tcp_t *tcp);
746 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
747     int caller_holds_lock);
748 static void	tcp_bind_hash_remove(tcp_t *tcp);
749 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
750 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
751 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
752 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
753 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
754 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
755 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
756 void		tcp_g_q_setup(tcp_stack_t *);
757 void		tcp_g_q_create(tcp_stack_t *);
758 void		tcp_g_q_destroy(tcp_stack_t *);
759 static int	tcp_header_init_ipv4(tcp_t *tcp);
760 static int	tcp_header_init_ipv6(tcp_t *tcp);
761 int		tcp_init(tcp_t *tcp, queue_t *q);
762 static int	tcp_init_values(tcp_t *tcp);
763 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
764 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
765 		    t_scalar_t addr_length);
766 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
767 static void	tcp_ip_notify(tcp_t *tcp);
768 static mblk_t	*tcp_ire_mp(mblk_t *mp);
769 static void	tcp_iss_init(tcp_t *tcp);
770 static void	tcp_keepalive_killer(void *arg);
771 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
772 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
773 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
774 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
775 static boolean_t tcp_allow_connopt_set(int level, int name);
776 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
777 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
778 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
779 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
780 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
781 		    mblk_t *mblk);
782 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
783 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
784 		    uchar_t *ptr, uint_t len);
785 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
786 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
787     tcp_stack_t *);
788 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
789 		    caddr_t cp, cred_t *cr);
790 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
791 		    caddr_t cp, cred_t *cr);
792 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
793 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
794 		    caddr_t cp, cred_t *cr);
795 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
796 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
797 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
798 static void	tcp_reinit(tcp_t *tcp);
799 static void	tcp_reinit_values(tcp_t *tcp);
800 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
801 		    tcp_t *thisstream, cred_t *cr);
802 
803 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
804 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
805 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
806 static void	tcp_ss_rexmit(tcp_t *tcp);
807 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
808 static void	tcp_process_options(tcp_t *, tcph_t *);
809 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
810 static void	tcp_rsrv(queue_t *q);
811 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
812 static int	tcp_snmp_state(tcp_t *tcp);
813 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
814 		    cred_t *cr);
815 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
816 		    cred_t *cr);
817 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
818 		    cred_t *cr);
819 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
820 		    cred_t *cr);
821 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
822 		    cred_t *cr);
823 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
824 		    caddr_t cp, cred_t *cr);
825 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
826 		    caddr_t cp, cred_t *cr);
827 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
828 		    cred_t *cr);
829 static void	tcp_timer(void *arg);
830 static void	tcp_timer_callback(void *);
831 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
832     boolean_t random);
833 static in_port_t tcp_get_next_priv_port(const tcp_t *);
834 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
835 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
836 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
837 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
838 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
839 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
840 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
841 		    const int num_sack_blk, int *usable, uint_t *snxt,
842 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
843 		    const int mdt_thres);
844 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
845 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
846 		    const int num_sack_blk, int *usable, uint_t *snxt,
847 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
848 		    const int mdt_thres);
849 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
850 		    int num_sack_blk);
851 static void	tcp_wsrv(queue_t *q);
852 static int	tcp_xmit_end(tcp_t *tcp);
853 static void	tcp_ack_timer(void *arg);
854 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
855 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
856 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
857 		    zoneid_t zoneid, tcp_stack_t *);
858 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
859 		    uint32_t ack, int ctl);
860 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
861 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
862 static int	setmaxps(queue_t *q, int maxpsz);
863 static void	tcp_set_rto(tcp_t *, time_t);
864 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
865 		    boolean_t, boolean_t);
866 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
867 		    boolean_t ipsec_mctl);
868 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
869 		    char *opt, int optlen);
870 static int	tcp_build_hdrs(queue_t *, tcp_t *);
871 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
872 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
873 		    tcph_t *tcph);
874 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
875 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
876 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
877 boolean_t	tcp_reserved_port_check(in_port_t, tcp_stack_t *);
878 static tcp_t	*tcp_alloc_temp_tcp(in_port_t, tcp_stack_t *);
879 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
880 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
881 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
882 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
883 		    const boolean_t, const uint32_t, const uint32_t,
884 		    const uint32_t, const uint32_t, tcp_stack_t *);
885 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
886 		    const uint_t, const uint_t, boolean_t *);
887 static mblk_t	*tcp_lso_info_mp(mblk_t *);
888 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
889 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
890 extern mblk_t	*tcp_timermp_alloc(int);
891 extern void	tcp_timermp_free(tcp_t *);
892 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
893 static void	tcp_stop_lingering(tcp_t *tcp);
894 static void	tcp_close_linger_timeout(void *arg);
895 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
896 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
897 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
898 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
899 static void	tcp_g_kstat_fini(kstat_t *);
900 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
901 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
902 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
903 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
904 static int	tcp_kstat_update(kstat_t *kp, int rw);
905 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
906 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
907 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
908 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
909 			tcph_t *tcph, mblk_t *idmp);
910 static squeue_func_t tcp_squeue_switch(int);
911 
912 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
913 static int	tcp_close(queue_t *, int);
914 static int	tcpclose_accept(queue_t *);
915 static int	tcp_modclose(queue_t *);
916 static void	tcp_wput_mod(queue_t *, mblk_t *);
917 
918 static void	tcp_squeue_add(squeue_t *);
919 static boolean_t tcp_zcopy_check(tcp_t *);
920 static void	tcp_zcopy_notify(tcp_t *);
921 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
922 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
923 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
924 
925 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
926 
927 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
928 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
929 
930 /*
931  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
932  *
933  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
934  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
935  * (defined in tcp.h) needs to be filled in and passed into the kernel
936  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
937  * structure contains the four-tuple of a TCP connection and a range of TCP
938  * states (specified by ac_start and ac_end). The use of wildcard addresses
939  * and ports is allowed. Connections with a matching four tuple and a state
940  * within the specified range will be aborted. The valid states for the
941  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
942  * inclusive.
943  *
944  * An application which has its connection aborted by this ioctl will receive
945  * an error that is dependent on the connection state at the time of the abort.
946  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
947  * though a RST packet has been received.  If the connection state is equal to
948  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
949  * and all resources associated with the connection will be freed.
950  */
951 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
952 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
953 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
954 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
955 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
956 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
957     boolean_t, tcp_stack_t *);
958 
959 static struct module_info tcp_rinfo =  {
960 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
961 };
962 
963 static struct module_info tcp_winfo =  {
964 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
965 };
966 
967 /*
968  * Entry points for TCP as a module. It only allows SNMP requests
969  * to pass through.
970  */
971 struct qinit tcp_mod_rinit = {
972 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
973 };
974 
975 struct qinit tcp_mod_winit = {
976 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
977 	&tcp_rinfo
978 };
979 
980 /*
981  * Entry points for TCP as a device. The normal case which supports
982  * the TCP functionality.
983  */
984 struct qinit tcp_rinit = {
985 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
986 };
987 
988 struct qinit tcp_winit = {
989 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
990 };
991 
992 /* Initial entry point for TCP in socket mode. */
993 struct qinit tcp_sock_winit = {
994 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
995 };
996 
997 /*
998  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
999  * an accept. Avoid allocating data structures since eager has already
1000  * been created.
1001  */
1002 struct qinit tcp_acceptor_rinit = {
1003 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1004 };
1005 
1006 struct qinit tcp_acceptor_winit = {
1007 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1008 };
1009 
1010 /*
1011  * Entry points for TCP loopback (read side only)
1012  */
1013 struct qinit tcp_loopback_rinit = {
1014 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1015 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1016 };
1017 
1018 struct streamtab tcpinfo = {
1019 	&tcp_rinit, &tcp_winit
1020 };
1021 
1022 /*
1023  * Have to ensure that tcp_g_q_close is not done by an
1024  * interrupt thread.
1025  */
1026 static taskq_t *tcp_taskq;
1027 
1028 /*
1029  * TCP has a private interface for other kernel modules to reserve a
1030  * port range for them to use.  Once reserved, TCP will not use any ports
1031  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1032  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1033  * has to be verified.
1034  *
1035  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1036  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1037  * range is [port a, port b] inclusive.  And each port range is between
1038  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1039  *
1040  * Note that the default anonymous port range starts from 32768.  There is
1041  * no port "collision" between that and the reserved port range.  If there
1042  * is port collision (because the default smallest anonymous port is lowered
1043  * or some apps specifically bind to ports in the reserved port range), the
1044  * system may not be able to reserve a port range even there are enough
1045  * unbound ports as a reserved port range contains consecutive ports .
1046  */
1047 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1048 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1049 #define	TCP_SMALLEST_RESERVED_PORT		10240
1050 #define	TCP_LARGEST_RESERVED_PORT		20480
1051 
1052 /* Structure to represent those reserved port ranges. */
1053 typedef struct tcp_rport_s {
1054 	in_port_t	lo_port;
1055 	in_port_t	hi_port;
1056 	tcp_t		**temp_tcp_array;
1057 } tcp_rport_t;
1058 
1059 /* Setable only in /etc/system. Move to ndd? */
1060 boolean_t tcp_icmp_source_quench = B_FALSE;
1061 
1062 /*
1063  * Following assumes TPI alignment requirements stay along 32 bit
1064  * boundaries
1065  */
1066 #define	ROUNDUP32(x) \
1067 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1068 
1069 /* Template for response to info request. */
1070 static struct T_info_ack tcp_g_t_info_ack = {
1071 	T_INFO_ACK,		/* PRIM_type */
1072 	0,			/* TSDU_size */
1073 	T_INFINITE,		/* ETSDU_size */
1074 	T_INVALID,		/* CDATA_size */
1075 	T_INVALID,		/* DDATA_size */
1076 	sizeof (sin_t),		/* ADDR_size */
1077 	0,			/* OPT_size - not initialized here */
1078 	TIDUSZ,			/* TIDU_size */
1079 	T_COTS_ORD,		/* SERV_type */
1080 	TCPS_IDLE,		/* CURRENT_state */
1081 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1082 };
1083 
1084 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1085 	T_INFO_ACK,		/* PRIM_type */
1086 	0,			/* TSDU_size */
1087 	T_INFINITE,		/* ETSDU_size */
1088 	T_INVALID,		/* CDATA_size */
1089 	T_INVALID,		/* DDATA_size */
1090 	sizeof (sin6_t),	/* ADDR_size */
1091 	0,			/* OPT_size - not initialized here */
1092 	TIDUSZ,		/* TIDU_size */
1093 	T_COTS_ORD,		/* SERV_type */
1094 	TCPS_IDLE,		/* CURRENT_state */
1095 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1096 };
1097 
1098 #define	MS	1L
1099 #define	SECONDS	(1000 * MS)
1100 #define	MINUTES	(60 * SECONDS)
1101 #define	HOURS	(60 * MINUTES)
1102 #define	DAYS	(24 * HOURS)
1103 
1104 #define	PARAM_MAX (~(uint32_t)0)
1105 
1106 /* Max size IP datagram is 64k - 1 */
1107 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1108 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1109 /* Max of the above */
1110 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1111 
1112 /* Largest TCP port number */
1113 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1114 
1115 /*
1116  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1117  * layer header.  It has to be a multiple of 4.
1118  */
1119 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1120 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1121 
1122 /*
1123  * All of these are alterable, within the min/max values given, at run time.
1124  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1125  * per the TCP spec.
1126  */
1127 /* BEGIN CSTYLED */
1128 static tcpparam_t	lcl_tcp_param_arr[] = {
1129  /*min		max		value		name */
1130  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1131  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1132  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1133  { 1,		1024,		1,		"tcp_conn_req_min" },
1134  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1135  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1136  { 0,		10,		0,		"tcp_debug" },
1137  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1138  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1139  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1140  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1141  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1142  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1143  { 1,		255,		64,		"tcp_ipv4_ttl"},
1144  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1145  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1146  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1147  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1148  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1149  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1150  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1151  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1152  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1153  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1154  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1155  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1156  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1157  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1158  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1159  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1160  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1161  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1162  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1163  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1164  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1165  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1166  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1167  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1168 /*
1169  * Question:  What default value should I set for tcp_strong_iss?
1170  */
1171  { 0,		2,		1,		"tcp_strong_iss"},
1172  { 0,		65536,		20,		"tcp_rtt_updates"},
1173  { 0,		1,		1,		"tcp_wscale_always"},
1174  { 0,		1,		0,		"tcp_tstamp_always"},
1175  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1176  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1177  { 0,		16,		2,		"tcp_deferred_acks_max"},
1178  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1179  { 1,		4,		4,		"tcp_slow_start_initial"},
1180  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1181  { 0,		2,		2,		"tcp_sack_permitted"},
1182  { 0,		1,		0,		"tcp_trace"},
1183  { 0,		1,		1,		"tcp_compression_enabled"},
1184  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1185  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1186  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1187  { 0,		1,		0,		"tcp_rev_src_routes"},
1188  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1189  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1190  { 0,		16,		8,		"tcp_local_dacks_max"},
1191  { 0,		2,		1,		"tcp_ecn_permitted"},
1192  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1193  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1194  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1195  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1196  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1197 };
1198 /* END CSTYLED */
1199 
1200 /*
1201  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1202  * each header fragment in the header buffer.  Each parameter value has
1203  * to be a multiple of 4 (32-bit aligned).
1204  */
1205 static tcpparam_t lcl_tcp_mdt_head_param =
1206 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1207 static tcpparam_t lcl_tcp_mdt_tail_param =
1208 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1209 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1210 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1211 
1212 /*
1213  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1214  * the maximum number of payload buffers associated per Multidata.
1215  */
1216 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1217 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1218 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1219 
1220 /* Round up the value to the nearest mss. */
1221 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1222 
1223 /*
1224  * Set ECN capable transport (ECT) code point in IP header.
1225  *
1226  * Note that there are 2 ECT code points '01' and '10', which are called
1227  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1228  * point ECT(0) for TCP as described in RFC 2481.
1229  */
1230 #define	SET_ECT(tcp, iph) \
1231 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1232 		/* We need to clear the code point first. */ \
1233 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1234 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1235 	} else { \
1236 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1237 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1238 	}
1239 
1240 /*
1241  * The format argument to pass to tcp_display().
1242  * DISP_PORT_ONLY means that the returned string has only port info.
1243  * DISP_ADDR_AND_PORT means that the returned string also contains the
1244  * remote and local IP address.
1245  */
1246 #define	DISP_PORT_ONLY		1
1247 #define	DISP_ADDR_AND_PORT	2
1248 
1249 #define	NDD_TOO_QUICK_MSG \
1250 	"ndd get info rate too high for non-privileged users, try again " \
1251 	"later.\n"
1252 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1253 
1254 #define	IS_VMLOANED_MBLK(mp) \
1255 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1256 
1257 
1258 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1259 boolean_t tcp_mdt_chain = B_TRUE;
1260 
1261 /*
1262  * MDT threshold in the form of effective send MSS multiplier; we take
1263  * the MDT path if the amount of unsent data exceeds the threshold value
1264  * (default threshold is 1*SMSS).
1265  */
1266 uint_t tcp_mdt_smss_threshold = 1;
1267 
1268 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1269 
1270 /*
1271  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1272  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1273  * determined dynamically during tcp_adapt_ire(), which is the default.
1274  */
1275 boolean_t tcp_static_maxpsz = B_FALSE;
1276 
1277 /* Setable in /etc/system */
1278 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1279 uint32_t tcp_random_anon_port = 1;
1280 
1281 /*
1282  * To reach to an eager in Q0 which can be dropped due to an incoming
1283  * new SYN request when Q0 is full, a new doubly linked list is
1284  * introduced. This list allows to select an eager from Q0 in O(1) time.
1285  * This is needed to avoid spending too much time walking through the
1286  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1287  * this new list has to be a member of Q0.
1288  * This list is headed by listener's tcp_t. When the list is empty,
1289  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1290  * of listener's tcp_t point to listener's tcp_t itself.
1291  *
1292  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1293  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1294  * These macros do not affect the eager's membership to Q0.
1295  */
1296 
1297 
1298 #define	MAKE_DROPPABLE(listener, eager)					\
1299 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1300 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1301 		    = (eager);						\
1302 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1303 		(eager)->tcp_eager_next_drop_q0 =			\
1304 		    (listener)->tcp_eager_next_drop_q0;			\
1305 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1306 	}
1307 
1308 #define	MAKE_UNDROPPABLE(eager)						\
1309 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1310 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1311 		    = (eager)->tcp_eager_prev_drop_q0;			\
1312 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1313 		    = (eager)->tcp_eager_next_drop_q0;			\
1314 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1315 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1316 	}
1317 
1318 /*
1319  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1320  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1321  * data, TCP will not respond with an ACK.  RFC 793 requires that
1322  * TCP responds with an ACK for such a bogus ACK.  By not following
1323  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1324  * an attacker successfully spoofs an acceptable segment to our
1325  * peer; or when our peer is "confused."
1326  */
1327 uint32_t tcp_drop_ack_unsent_cnt = 10;
1328 
1329 /*
1330  * Hook functions to enable cluster networking
1331  * On non-clustered systems these vectors must always be NULL.
1332  */
1333 
1334 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1335 			    uint8_t *laddrp, in_port_t lport) = NULL;
1336 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1337 			    uint8_t *laddrp, in_port_t lport) = NULL;
1338 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1339 			    uint8_t *laddrp, in_port_t lport,
1340 			    uint8_t *faddrp, in_port_t fport) = NULL;
1341 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1342 			    uint8_t *laddrp, in_port_t lport,
1343 			    uint8_t *faddrp, in_port_t fport) = NULL;
1344 
1345 /*
1346  * The following are defined in ip.c
1347  */
1348 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1349 				uint8_t *laddrp);
1350 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1351 				uint8_t *laddrp, uint8_t *faddrp);
1352 
1353 #define	CL_INET_CONNECT(tcp)		{			\
1354 	if (cl_inet_connect != NULL) {				\
1355 		/*						\
1356 		 * Running in cluster mode - register active connection	\
1357 		 * information						\
1358 		 */							\
1359 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1360 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1361 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1362 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1363 				    (in_port_t)(tcp)->tcp_lport,	\
1364 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1365 				    (in_port_t)(tcp)->tcp_fport);	\
1366 			}						\
1367 		} else {						\
1368 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1369 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1370 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1371 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1372 				    (in_port_t)(tcp)->tcp_lport,	\
1373 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1374 				    (in_port_t)(tcp)->tcp_fport);	\
1375 			}						\
1376 		}							\
1377 	}								\
1378 }
1379 
1380 #define	CL_INET_DISCONNECT(tcp)	{				\
1381 	if (cl_inet_disconnect != NULL) {				\
1382 		/*							\
1383 		 * Running in cluster mode - deregister active		\
1384 		 * connection information				\
1385 		 */							\
1386 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1387 			if ((tcp)->tcp_ip_src != 0) {			\
1388 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1389 				    AF_INET,				\
1390 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1391 				    (in_port_t)(tcp)->tcp_lport,	\
1392 				    (uint8_t *)				\
1393 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1394 				    (in_port_t)(tcp)->tcp_fport);	\
1395 			}						\
1396 		} else {						\
1397 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1398 			    &(tcp)->tcp_ip_src_v6)) {			\
1399 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1400 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1401 				    (in_port_t)(tcp)->tcp_lport,	\
1402 				    (uint8_t *)				\
1403 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1404 				    (in_port_t)(tcp)->tcp_fport);	\
1405 			}						\
1406 		}							\
1407 	}								\
1408 }
1409 
1410 /*
1411  * Cluster networking hook for traversing current connection list.
1412  * This routine is used to extract the current list of live connections
1413  * which must continue to to be dispatched to this node.
1414  */
1415 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1416 
1417 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1418     void *arg, tcp_stack_t *tcps);
1419 
1420 /*
1421  * Figure out the value of window scale opton.  Note that the rwnd is
1422  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1423  * We cannot find the scale value and then do a round up of tcp_rwnd
1424  * because the scale value may not be correct after that.
1425  *
1426  * Set the compiler flag to make this function inline.
1427  */
1428 static void
1429 tcp_set_ws_value(tcp_t *tcp)
1430 {
1431 	int i;
1432 	uint32_t rwnd = tcp->tcp_rwnd;
1433 
1434 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1435 	    i++, rwnd >>= 1)
1436 		;
1437 	tcp->tcp_rcv_ws = i;
1438 }
1439 
1440 /*
1441  * Remove a connection from the list of detached TIME_WAIT connections.
1442  * It returns B_FALSE if it can't remove the connection from the list
1443  * as the connection has already been removed from the list due to an
1444  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1445  */
1446 static boolean_t
1447 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1448 {
1449 	boolean_t	locked = B_FALSE;
1450 
1451 	if (tcp_time_wait == NULL) {
1452 		tcp_time_wait = *((tcp_squeue_priv_t **)
1453 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1454 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1455 		locked = B_TRUE;
1456 	} else {
1457 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1458 	}
1459 
1460 	if (tcp->tcp_time_wait_expire == 0) {
1461 		ASSERT(tcp->tcp_time_wait_next == NULL);
1462 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1463 		if (locked)
1464 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1465 		return (B_FALSE);
1466 	}
1467 	ASSERT(TCP_IS_DETACHED(tcp));
1468 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1469 
1470 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1471 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1472 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1473 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1474 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1475 			    NULL;
1476 		} else {
1477 			tcp_time_wait->tcp_time_wait_tail = NULL;
1478 		}
1479 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1480 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1481 		ASSERT(tcp->tcp_time_wait_next == NULL);
1482 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1483 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1484 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1485 	} else {
1486 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1487 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1488 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1489 		    tcp->tcp_time_wait_next;
1490 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1491 		    tcp->tcp_time_wait_prev;
1492 	}
1493 	tcp->tcp_time_wait_next = NULL;
1494 	tcp->tcp_time_wait_prev = NULL;
1495 	tcp->tcp_time_wait_expire = 0;
1496 
1497 	if (locked)
1498 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1499 	return (B_TRUE);
1500 }
1501 
1502 /*
1503  * Add a connection to the list of detached TIME_WAIT connections
1504  * and set its time to expire.
1505  */
1506 static void
1507 tcp_time_wait_append(tcp_t *tcp)
1508 {
1509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1510 	tcp_squeue_priv_t *tcp_time_wait =
1511 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1512 		SQPRIVATE_TCP));
1513 
1514 	tcp_timers_stop(tcp);
1515 
1516 	/* Freed above */
1517 	ASSERT(tcp->tcp_timer_tid == 0);
1518 	ASSERT(tcp->tcp_ack_tid == 0);
1519 
1520 	/* must have happened at the time of detaching the tcp */
1521 	ASSERT(tcp->tcp_ptpahn == NULL);
1522 	ASSERT(tcp->tcp_flow_stopped == 0);
1523 	ASSERT(tcp->tcp_time_wait_next == NULL);
1524 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1525 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1526 	ASSERT(tcp->tcp_listener == NULL);
1527 
1528 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1529 	/*
1530 	 * The value computed below in tcp->tcp_time_wait_expire may
1531 	 * appear negative or wrap around. That is ok since our
1532 	 * interest is only in the difference between the current lbolt
1533 	 * value and tcp->tcp_time_wait_expire. But the value should not
1534 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1535 	 * The corresponding comparison in tcp_time_wait_collector() uses
1536 	 * modular arithmetic.
1537 	 */
1538 	tcp->tcp_time_wait_expire +=
1539 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1540 	if (tcp->tcp_time_wait_expire == 0)
1541 		tcp->tcp_time_wait_expire = 1;
1542 
1543 	ASSERT(TCP_IS_DETACHED(tcp));
1544 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1545 	ASSERT(tcp->tcp_time_wait_next == NULL);
1546 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1547 	TCP_DBGSTAT(tcps, tcp_time_wait);
1548 
1549 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1550 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1551 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1552 		tcp_time_wait->tcp_time_wait_head = tcp;
1553 	} else {
1554 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1555 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1556 		    TCPS_TIME_WAIT);
1557 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1558 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1559 	}
1560 	tcp_time_wait->tcp_time_wait_tail = tcp;
1561 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1562 }
1563 
1564 /* ARGSUSED */
1565 void
1566 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1567 {
1568 	conn_t	*connp = (conn_t *)arg;
1569 	tcp_t	*tcp = connp->conn_tcp;
1570 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1571 
1572 	ASSERT(tcp != NULL);
1573 	if (tcp->tcp_state == TCPS_CLOSED) {
1574 		return;
1575 	}
1576 
1577 	ASSERT((tcp->tcp_family == AF_INET &&
1578 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1579 	    (tcp->tcp_family == AF_INET6 &&
1580 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1581 	    tcp->tcp_ipversion == IPV6_VERSION)));
1582 	ASSERT(!tcp->tcp_listener);
1583 
1584 	TCP_STAT(tcps, tcp_time_wait_reap);
1585 	ASSERT(TCP_IS_DETACHED(tcp));
1586 
1587 	/*
1588 	 * Because they have no upstream client to rebind or tcp_close()
1589 	 * them later, we axe the connection here and now.
1590 	 */
1591 	tcp_close_detached(tcp);
1592 }
1593 
1594 /*
1595  * Remove cached/latched IPsec references.
1596  */
1597 void
1598 tcp_ipsec_cleanup(tcp_t *tcp)
1599 {
1600 	conn_t		*connp = tcp->tcp_connp;
1601 
1602 	if (connp->conn_flags & IPCL_TCPCONN) {
1603 		if (connp->conn_latch != NULL) {
1604 			IPLATCH_REFRELE(connp->conn_latch,
1605 			    connp->conn_netstack);
1606 			connp->conn_latch = NULL;
1607 		}
1608 		if (connp->conn_policy != NULL) {
1609 			IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1610 			connp->conn_policy = NULL;
1611 		}
1612 	}
1613 }
1614 
1615 /*
1616  * Cleaup before placing on free list.
1617  * Disassociate from the netstack/tcp_stack_t since the freelist
1618  * is per squeue and not per netstack.
1619  */
1620 void
1621 tcp_cleanup(tcp_t *tcp)
1622 {
1623 	mblk_t		*mp;
1624 	char		*tcp_iphc;
1625 	int		tcp_iphc_len;
1626 	int		tcp_hdr_grown;
1627 	tcp_sack_info_t	*tcp_sack_info;
1628 	conn_t		*connp = tcp->tcp_connp;
1629 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1630 	netstack_t	*ns = tcps->tcps_netstack;
1631 
1632 	tcp_bind_hash_remove(tcp);
1633 
1634 	/* Cleanup that which needs the netstack first */
1635 	tcp_ipsec_cleanup(tcp);
1636 
1637 	tcp_free(tcp);
1638 
1639 	/* Release any SSL context */
1640 	if (tcp->tcp_kssl_ent != NULL) {
1641 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1642 		tcp->tcp_kssl_ent = NULL;
1643 	}
1644 
1645 	if (tcp->tcp_kssl_ctx != NULL) {
1646 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1647 		tcp->tcp_kssl_ctx = NULL;
1648 	}
1649 	tcp->tcp_kssl_pending = B_FALSE;
1650 
1651 	conn_delete_ire(connp, NULL);
1652 
1653 	/*
1654 	 * Since we will bzero the entire structure, we need to
1655 	 * remove it and reinsert it in global hash list. We
1656 	 * know the walkers can't get to this conn because we
1657 	 * had set CONDEMNED flag earlier and checked reference
1658 	 * under conn_lock so walker won't pick it and when we
1659 	 * go the ipcl_globalhash_remove() below, no walker
1660 	 * can get to it.
1661 	 */
1662 	ipcl_globalhash_remove(connp);
1663 
1664 	/*
1665 	 * Now it is safe to decrement the reference counts.
1666 	 * This might be the last reference on the netstack and TCPS
1667 	 * in which case it will cause the tcp_g_q_close and
1668 	 * the freeing of the IP Instance.
1669 	 */
1670 	connp->conn_netstack = NULL;
1671 	netstack_rele(ns);
1672 	ASSERT(tcps != NULL);
1673 	tcp->tcp_tcps = NULL;
1674 	TCPS_REFRELE(tcps);
1675 
1676 	/* Save some state */
1677 	mp = tcp->tcp_timercache;
1678 
1679 	tcp_sack_info = tcp->tcp_sack_info;
1680 	tcp_iphc = tcp->tcp_iphc;
1681 	tcp_iphc_len = tcp->tcp_iphc_len;
1682 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1683 
1684 	if (connp->conn_cred != NULL)
1685 		crfree(connp->conn_cred);
1686 	if (connp->conn_peercred != NULL)
1687 		crfree(connp->conn_peercred);
1688 	bzero(connp, sizeof (conn_t));
1689 	bzero(tcp, sizeof (tcp_t));
1690 
1691 	/* restore the state */
1692 	tcp->tcp_timercache = mp;
1693 
1694 	tcp->tcp_sack_info = tcp_sack_info;
1695 	tcp->tcp_iphc = tcp_iphc;
1696 	tcp->tcp_iphc_len = tcp_iphc_len;
1697 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1698 
1699 
1700 	tcp->tcp_connp = connp;
1701 
1702 	connp->conn_tcp = tcp;
1703 	connp->conn_flags = IPCL_TCPCONN;
1704 	connp->conn_state_flags = CONN_INCIPIENT;
1705 	connp->conn_ulp = IPPROTO_TCP;
1706 	connp->conn_ref = 1;
1707 }
1708 
1709 /*
1710  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1711  * is done forwards from the head.
1712  * This walks all stack instances since
1713  * tcp_time_wait remains global across all stacks.
1714  */
1715 /* ARGSUSED */
1716 void
1717 tcp_time_wait_collector(void *arg)
1718 {
1719 	tcp_t *tcp;
1720 	clock_t now;
1721 	mblk_t *mp;
1722 	conn_t *connp;
1723 	kmutex_t *lock;
1724 	boolean_t removed;
1725 
1726 	squeue_t *sqp = (squeue_t *)arg;
1727 	tcp_squeue_priv_t *tcp_time_wait =
1728 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1729 
1730 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1731 	tcp_time_wait->tcp_time_wait_tid = 0;
1732 
1733 	if (tcp_time_wait->tcp_free_list != NULL &&
1734 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1735 		TCP_G_STAT(tcp_freelist_cleanup);
1736 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1737 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1738 			tcp->tcp_time_wait_next = NULL;
1739 			tcp_time_wait->tcp_free_list_cnt--;
1740 			ASSERT(tcp->tcp_tcps == NULL);
1741 			CONN_DEC_REF(tcp->tcp_connp);
1742 		}
1743 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1744 	}
1745 
1746 	/*
1747 	 * In order to reap time waits reliably, we should use a
1748 	 * source of time that is not adjustable by the user -- hence
1749 	 * the call to ddi_get_lbolt().
1750 	 */
1751 	now = ddi_get_lbolt();
1752 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1753 		/*
1754 		 * Compare times using modular arithmetic, since
1755 		 * lbolt can wrapover.
1756 		 */
1757 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1758 			break;
1759 		}
1760 
1761 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1762 		ASSERT(removed);
1763 
1764 		connp = tcp->tcp_connp;
1765 		ASSERT(connp->conn_fanout != NULL);
1766 		lock = &connp->conn_fanout->connf_lock;
1767 		/*
1768 		 * This is essentially a TW reclaim fast path optimization for
1769 		 * performance where the timewait collector checks under the
1770 		 * fanout lock (so that no one else can get access to the
1771 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1772 		 * the classifier hash list. If ref count is indeed 2, we can
1773 		 * just remove the conn under the fanout lock and avoid
1774 		 * cleaning up the conn under the squeue, provided that
1775 		 * clustering callbacks are not enabled. If clustering is
1776 		 * enabled, we need to make the clustering callback before
1777 		 * setting the CONDEMNED flag and after dropping all locks and
1778 		 * so we forego this optimization and fall back to the slow
1779 		 * path. Also please see the comments in tcp_closei_local
1780 		 * regarding the refcnt logic.
1781 		 *
1782 		 * Since we are holding the tcp_time_wait_lock, its better
1783 		 * not to block on the fanout_lock because other connections
1784 		 * can't add themselves to time_wait list. So we do a
1785 		 * tryenter instead of mutex_enter.
1786 		 */
1787 		if (mutex_tryenter(lock)) {
1788 			mutex_enter(&connp->conn_lock);
1789 			if ((connp->conn_ref == 2) &&
1790 			    (cl_inet_disconnect == NULL)) {
1791 				ipcl_hash_remove_locked(connp,
1792 				    connp->conn_fanout);
1793 				/*
1794 				 * Set the CONDEMNED flag now itself so that
1795 				 * the refcnt cannot increase due to any
1796 				 * walker. But we have still not cleaned up
1797 				 * conn_ire_cache. This is still ok since
1798 				 * we are going to clean it up in tcp_cleanup
1799 				 * immediately and any interface unplumb
1800 				 * thread will wait till the ire is blown away
1801 				 */
1802 				connp->conn_state_flags |= CONN_CONDEMNED;
1803 				mutex_exit(lock);
1804 				mutex_exit(&connp->conn_lock);
1805 				if (tcp_time_wait->tcp_free_list_cnt <
1806 				    tcp_free_list_max_cnt) {
1807 					/* Add to head of tcp_free_list */
1808 					mutex_exit(
1809 					    &tcp_time_wait->tcp_time_wait_lock);
1810 					tcp_cleanup(tcp);
1811 					ASSERT(connp->conn_latch == NULL);
1812 					ASSERT(connp->conn_policy == NULL);
1813 					ASSERT(tcp->tcp_tcps == NULL);
1814 					ASSERT(connp->conn_netstack == NULL);
1815 
1816 					mutex_enter(
1817 					    &tcp_time_wait->tcp_time_wait_lock);
1818 					tcp->tcp_time_wait_next =
1819 					    tcp_time_wait->tcp_free_list;
1820 					tcp_time_wait->tcp_free_list = tcp;
1821 					tcp_time_wait->tcp_free_list_cnt++;
1822 					continue;
1823 				} else {
1824 					/* Do not add to tcp_free_list */
1825 					mutex_exit(
1826 					    &tcp_time_wait->tcp_time_wait_lock);
1827 					tcp_bind_hash_remove(tcp);
1828 					conn_delete_ire(tcp->tcp_connp, NULL);
1829 					tcp_ipsec_cleanup(tcp);
1830 					CONN_DEC_REF(tcp->tcp_connp);
1831 				}
1832 			} else {
1833 				CONN_INC_REF_LOCKED(connp);
1834 				mutex_exit(lock);
1835 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1836 				mutex_exit(&connp->conn_lock);
1837 				/*
1838 				 * We can reuse the closemp here since conn has
1839 				 * detached (otherwise we wouldn't even be in
1840 				 * time_wait list). tcp_closemp_used can safely
1841 				 * be changed without taking a lock as no other
1842 				 * thread can concurrently access it at this
1843 				 * point in the connection lifecycle.
1844 				 */
1845 
1846 				if (tcp->tcp_closemp.b_prev == NULL)
1847 					tcp->tcp_closemp_used = B_TRUE;
1848 				else
1849 					cmn_err(CE_PANIC,
1850 					    "tcp_timewait_collector: "
1851 					    "concurrent use of tcp_closemp: "
1852 					    "connp %p tcp %p\n", (void *)connp,
1853 					    (void *)tcp);
1854 
1855 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1856 				mp = &tcp->tcp_closemp;
1857 				squeue_fill(connp->conn_sqp, mp,
1858 				    tcp_timewait_output, connp,
1859 				    SQTAG_TCP_TIMEWAIT);
1860 			}
1861 		} else {
1862 			mutex_enter(&connp->conn_lock);
1863 			CONN_INC_REF_LOCKED(connp);
1864 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1865 			mutex_exit(&connp->conn_lock);
1866 			/*
1867 			 * We can reuse the closemp here since conn has
1868 			 * detached (otherwise we wouldn't even be in
1869 			 * time_wait list). tcp_closemp_used can safely
1870 			 * be changed without taking a lock as no other
1871 			 * thread can concurrently access it at this
1872 			 * point in the connection lifecycle.
1873 			 */
1874 
1875 			if (tcp->tcp_closemp.b_prev == NULL)
1876 				tcp->tcp_closemp_used = B_TRUE;
1877 			else
1878 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1879 				    "concurrent use of tcp_closemp: "
1880 				    "connp %p tcp %p\n", (void *)connp,
1881 				    (void *)tcp);
1882 
1883 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1884 			mp = &tcp->tcp_closemp;
1885 			squeue_fill(connp->conn_sqp, mp,
1886 			    tcp_timewait_output, connp, 0);
1887 		}
1888 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1889 	}
1890 
1891 	if (tcp_time_wait->tcp_free_list != NULL)
1892 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1893 
1894 	tcp_time_wait->tcp_time_wait_tid =
1895 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1896 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1897 }
1898 /*
1899  * Reply to a clients T_CONN_RES TPI message. This function
1900  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1901  * on the acceptor STREAM and processed in tcp_wput_accept().
1902  * Read the block comment on top of tcp_conn_request().
1903  */
1904 static void
1905 tcp_accept(tcp_t *listener, mblk_t *mp)
1906 {
1907 	tcp_t	*acceptor;
1908 	tcp_t	*eager;
1909 	tcp_t   *tcp;
1910 	struct T_conn_res	*tcr;
1911 	t_uscalar_t	acceptor_id;
1912 	t_scalar_t	seqnum;
1913 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1914 	mblk_t	*ok_mp;
1915 	mblk_t	*mp1;
1916 	tcp_stack_t	*tcps = listener->tcp_tcps;
1917 
1918 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1919 		tcp_err_ack(listener, mp, TPROTO, 0);
1920 		return;
1921 	}
1922 	tcr = (struct T_conn_res *)mp->b_rptr;
1923 
1924 	/*
1925 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1926 	 * read side queue of the streams device underneath us i.e. the
1927 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1928 	 * look it up in the queue_hash.  Under LP64 it sends down the
1929 	 * minor_t of the accepting endpoint.
1930 	 *
1931 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1932 	 * fanout hash lock is held.
1933 	 * This prevents any thread from entering the acceptor queue from
1934 	 * below (since it has not been hard bound yet i.e. any inbound
1935 	 * packets will arrive on the listener or default tcp queue and
1936 	 * go through tcp_lookup).
1937 	 * The CONN_INC_REF will prevent the acceptor from closing.
1938 	 *
1939 	 * XXX It is still possible for a tli application to send down data
1940 	 * on the accepting stream while another thread calls t_accept.
1941 	 * This should not be a problem for well-behaved applications since
1942 	 * the T_OK_ACK is sent after the queue swapping is completed.
1943 	 *
1944 	 * If the accepting fd is the same as the listening fd, avoid
1945 	 * queue hash lookup since that will return an eager listener in a
1946 	 * already established state.
1947 	 */
1948 	acceptor_id = tcr->ACCEPTOR_id;
1949 	mutex_enter(&listener->tcp_eager_lock);
1950 	if (listener->tcp_acceptor_id == acceptor_id) {
1951 		eager = listener->tcp_eager_next_q;
1952 		/* only count how many T_CONN_INDs so don't count q0 */
1953 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1954 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1955 			mutex_exit(&listener->tcp_eager_lock);
1956 			tcp_err_ack(listener, mp, TBADF, 0);
1957 			return;
1958 		}
1959 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1960 			/* Throw away all the eagers on q0. */
1961 			tcp_eager_cleanup(listener, 1);
1962 		}
1963 		if (listener->tcp_syn_defense) {
1964 			listener->tcp_syn_defense = B_FALSE;
1965 			if (listener->tcp_ip_addr_cache != NULL) {
1966 				kmem_free(listener->tcp_ip_addr_cache,
1967 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1968 				listener->tcp_ip_addr_cache = NULL;
1969 			}
1970 		}
1971 		/*
1972 		 * Transfer tcp_conn_req_max to the eager so that when
1973 		 * a disconnect occurs we can revert the endpoint to the
1974 		 * listen state.
1975 		 */
1976 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1977 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1978 		/*
1979 		 * Get a reference on the acceptor just like the
1980 		 * tcp_acceptor_hash_lookup below.
1981 		 */
1982 		acceptor = listener;
1983 		CONN_INC_REF(acceptor->tcp_connp);
1984 	} else {
1985 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1986 		if (acceptor == NULL) {
1987 			if (listener->tcp_debug) {
1988 				(void) strlog(TCP_MOD_ID, 0, 1,
1989 				    SL_ERROR|SL_TRACE,
1990 				    "tcp_accept: did not find acceptor 0x%x\n",
1991 				    acceptor_id);
1992 			}
1993 			mutex_exit(&listener->tcp_eager_lock);
1994 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1995 			return;
1996 		}
1997 		/*
1998 		 * Verify acceptor state. The acceptable states for an acceptor
1999 		 * include TCPS_IDLE and TCPS_BOUND.
2000 		 */
2001 		switch (acceptor->tcp_state) {
2002 		case TCPS_IDLE:
2003 			/* FALLTHRU */
2004 		case TCPS_BOUND:
2005 			break;
2006 		default:
2007 			CONN_DEC_REF(acceptor->tcp_connp);
2008 			mutex_exit(&listener->tcp_eager_lock);
2009 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2010 			return;
2011 		}
2012 	}
2013 
2014 	/* The listener must be in TCPS_LISTEN */
2015 	if (listener->tcp_state != TCPS_LISTEN) {
2016 		CONN_DEC_REF(acceptor->tcp_connp);
2017 		mutex_exit(&listener->tcp_eager_lock);
2018 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2019 		return;
2020 	}
2021 
2022 	/*
2023 	 * Rendezvous with an eager connection request packet hanging off
2024 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2025 	 * tcp structure when the connection packet arrived in
2026 	 * tcp_conn_request().
2027 	 */
2028 	seqnum = tcr->SEQ_number;
2029 	eager = listener;
2030 	do {
2031 		eager = eager->tcp_eager_next_q;
2032 		if (eager == NULL) {
2033 			CONN_DEC_REF(acceptor->tcp_connp);
2034 			mutex_exit(&listener->tcp_eager_lock);
2035 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2036 			return;
2037 		}
2038 	} while (eager->tcp_conn_req_seqnum != seqnum);
2039 	mutex_exit(&listener->tcp_eager_lock);
2040 
2041 	/*
2042 	 * At this point, both acceptor and listener have 2 ref
2043 	 * that they begin with. Acceptor has one additional ref
2044 	 * we placed in lookup while listener has 3 additional
2045 	 * ref for being behind the squeue (tcp_accept() is
2046 	 * done on listener's squeue); being in classifier hash;
2047 	 * and eager's ref on listener.
2048 	 */
2049 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2050 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2051 
2052 	/*
2053 	 * The eager at this point is set in its own squeue and
2054 	 * could easily have been killed (tcp_accept_finish will
2055 	 * deal with that) because of a TH_RST so we can only
2056 	 * ASSERT for a single ref.
2057 	 */
2058 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2059 
2060 	/* Pre allocate the stroptions mblk also */
2061 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2062 	if (opt_mp == NULL) {
2063 		CONN_DEC_REF(acceptor->tcp_connp);
2064 		CONN_DEC_REF(eager->tcp_connp);
2065 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2066 		return;
2067 	}
2068 	DB_TYPE(opt_mp) = M_SETOPTS;
2069 	opt_mp->b_wptr += sizeof (struct stroptions);
2070 
2071 	/*
2072 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2073 	 * from listener to acceptor. The message is chained on opt_mp
2074 	 * which will be sent onto eager's squeue.
2075 	 */
2076 	if (listener->tcp_bound_if != 0) {
2077 		/* allocate optmgmt req */
2078 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2079 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2080 		    sizeof (int));
2081 		if (mp1 != NULL)
2082 			linkb(opt_mp, mp1);
2083 	}
2084 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2085 		uint_t on = 1;
2086 
2087 		/* allocate optmgmt req */
2088 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2089 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2090 		if (mp1 != NULL)
2091 			linkb(opt_mp, mp1);
2092 	}
2093 
2094 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2095 	if ((mp1 = copymsg(mp)) == NULL) {
2096 		CONN_DEC_REF(acceptor->tcp_connp);
2097 		CONN_DEC_REF(eager->tcp_connp);
2098 		freemsg(opt_mp);
2099 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2100 		return;
2101 	}
2102 
2103 	tcr = (struct T_conn_res *)mp1->b_rptr;
2104 
2105 	/*
2106 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2107 	 * which allocates a larger mblk and appends the new
2108 	 * local address to the ok_ack.  The address is copied by
2109 	 * soaccept() for getsockname().
2110 	 */
2111 	{
2112 		int extra;
2113 
2114 		extra = (eager->tcp_family == AF_INET) ?
2115 		    sizeof (sin_t) : sizeof (sin6_t);
2116 
2117 		/*
2118 		 * Try to re-use mp, if possible.  Otherwise, allocate
2119 		 * an mblk and return it as ok_mp.  In any case, mp
2120 		 * is no longer usable upon return.
2121 		 */
2122 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2123 			CONN_DEC_REF(acceptor->tcp_connp);
2124 			CONN_DEC_REF(eager->tcp_connp);
2125 			freemsg(opt_mp);
2126 			/* Original mp has been freed by now, so use mp1 */
2127 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2128 			return;
2129 		}
2130 
2131 		mp = NULL;	/* We should never use mp after this point */
2132 
2133 		switch (extra) {
2134 		case sizeof (sin_t): {
2135 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2136 
2137 				ok_mp->b_wptr += extra;
2138 				sin->sin_family = AF_INET;
2139 				sin->sin_port = eager->tcp_lport;
2140 				sin->sin_addr.s_addr =
2141 				    eager->tcp_ipha->ipha_src;
2142 				break;
2143 			}
2144 		case sizeof (sin6_t): {
2145 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2146 
2147 				ok_mp->b_wptr += extra;
2148 				sin6->sin6_family = AF_INET6;
2149 				sin6->sin6_port = eager->tcp_lport;
2150 				if (eager->tcp_ipversion == IPV4_VERSION) {
2151 					sin6->sin6_flowinfo = 0;
2152 					IN6_IPADDR_TO_V4MAPPED(
2153 					    eager->tcp_ipha->ipha_src,
2154 					    &sin6->sin6_addr);
2155 				} else {
2156 					ASSERT(eager->tcp_ip6h != NULL);
2157 					sin6->sin6_flowinfo =
2158 					    eager->tcp_ip6h->ip6_vcf &
2159 					    ~IPV6_VERS_AND_FLOW_MASK;
2160 					sin6->sin6_addr =
2161 					    eager->tcp_ip6h->ip6_src;
2162 				}
2163 				break;
2164 			}
2165 		default:
2166 			break;
2167 		}
2168 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2169 	}
2170 
2171 	/*
2172 	 * If there are no options we know that the T_CONN_RES will
2173 	 * succeed. However, we can't send the T_OK_ACK upstream until
2174 	 * the tcp_accept_swap is done since it would be dangerous to
2175 	 * let the application start using the new fd prior to the swap.
2176 	 */
2177 	tcp_accept_swap(listener, acceptor, eager);
2178 
2179 	/*
2180 	 * tcp_accept_swap unlinks eager from listener but does not drop
2181 	 * the eager's reference on the listener.
2182 	 */
2183 	ASSERT(eager->tcp_listener == NULL);
2184 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2185 
2186 	/*
2187 	 * The eager is now associated with its own queue. Insert in
2188 	 * the hash so that the connection can be reused for a future
2189 	 * T_CONN_RES.
2190 	 */
2191 	tcp_acceptor_hash_insert(acceptor_id, eager);
2192 
2193 	/*
2194 	 * We now do the processing of options with T_CONN_RES.
2195 	 * We delay till now since we wanted to have queue to pass to
2196 	 * option processing routines that points back to the right
2197 	 * instance structure which does not happen until after
2198 	 * tcp_accept_swap().
2199 	 *
2200 	 * Note:
2201 	 * The sanity of the logic here assumes that whatever options
2202 	 * are appropriate to inherit from listner=>eager are done
2203 	 * before this point, and whatever were to be overridden (or not)
2204 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2205 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2206 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2207 	 * This may not be true at this point in time but can be fixed
2208 	 * independently. This option processing code starts with
2209 	 * the instantiated acceptor instance and the final queue at
2210 	 * this point.
2211 	 */
2212 
2213 	if (tcr->OPT_length != 0) {
2214 		/* Options to process */
2215 		int t_error = 0;
2216 		int sys_error = 0;
2217 		int do_disconnect = 0;
2218 
2219 		if (tcp_conprim_opt_process(eager, mp1,
2220 		    &do_disconnect, &t_error, &sys_error) < 0) {
2221 			eager->tcp_accept_error = 1;
2222 			if (do_disconnect) {
2223 				/*
2224 				 * An option failed which does not allow
2225 				 * connection to be accepted.
2226 				 *
2227 				 * We allow T_CONN_RES to succeed and
2228 				 * put a T_DISCON_IND on the eager queue.
2229 				 */
2230 				ASSERT(t_error == 0 && sys_error == 0);
2231 				eager->tcp_send_discon_ind = 1;
2232 			} else {
2233 				ASSERT(t_error != 0);
2234 				freemsg(ok_mp);
2235 				/*
2236 				 * Original mp was either freed or set
2237 				 * to ok_mp above, so use mp1 instead.
2238 				 */
2239 				tcp_err_ack(listener, mp1, t_error, sys_error);
2240 				goto finish;
2241 			}
2242 		}
2243 		/*
2244 		 * Most likely success in setting options (except if
2245 		 * eager->tcp_send_discon_ind set).
2246 		 * mp1 option buffer represented by OPT_length/offset
2247 		 * potentially modified and contains results of setting
2248 		 * options at this point
2249 		 */
2250 	}
2251 
2252 	/* We no longer need mp1, since all options processing has passed */
2253 	freemsg(mp1);
2254 
2255 	putnext(listener->tcp_rq, ok_mp);
2256 
2257 	mutex_enter(&listener->tcp_eager_lock);
2258 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2259 		tcp_t	*tail;
2260 		mblk_t	*conn_ind;
2261 
2262 		/*
2263 		 * This path should not be executed if listener and
2264 		 * acceptor streams are the same.
2265 		 */
2266 		ASSERT(listener != acceptor);
2267 
2268 		tcp = listener->tcp_eager_prev_q0;
2269 		/*
2270 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2271 		 * deferred T_conn_ind queue. We need to get to the head of
2272 		 * the queue in order to send up T_conn_ind the same order as
2273 		 * how the 3WHS is completed.
2274 		 */
2275 		while (tcp != listener) {
2276 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2277 				break;
2278 			else
2279 				tcp = tcp->tcp_eager_prev_q0;
2280 		}
2281 		ASSERT(tcp != listener);
2282 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2283 		ASSERT(conn_ind != NULL);
2284 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2285 
2286 		/* Move from q0 to q */
2287 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2288 		listener->tcp_conn_req_cnt_q0--;
2289 		listener->tcp_conn_req_cnt_q++;
2290 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2291 		    tcp->tcp_eager_prev_q0;
2292 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2293 		    tcp->tcp_eager_next_q0;
2294 		tcp->tcp_eager_prev_q0 = NULL;
2295 		tcp->tcp_eager_next_q0 = NULL;
2296 		tcp->tcp_conn_def_q0 = B_FALSE;
2297 
2298 		/* Make sure the tcp isn't in the list of droppables */
2299 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2300 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2301 
2302 		/*
2303 		 * Insert at end of the queue because sockfs sends
2304 		 * down T_CONN_RES in chronological order. Leaving
2305 		 * the older conn indications at front of the queue
2306 		 * helps reducing search time.
2307 		 */
2308 		tail = listener->tcp_eager_last_q;
2309 		if (tail != NULL)
2310 			tail->tcp_eager_next_q = tcp;
2311 		else
2312 			listener->tcp_eager_next_q = tcp;
2313 		listener->tcp_eager_last_q = tcp;
2314 		tcp->tcp_eager_next_q = NULL;
2315 		mutex_exit(&listener->tcp_eager_lock);
2316 		putnext(tcp->tcp_rq, conn_ind);
2317 	} else {
2318 		mutex_exit(&listener->tcp_eager_lock);
2319 	}
2320 
2321 	/*
2322 	 * Done with the acceptor - free it
2323 	 *
2324 	 * Note: from this point on, no access to listener should be made
2325 	 * as listener can be equal to acceptor.
2326 	 */
2327 finish:
2328 	ASSERT(acceptor->tcp_detached);
2329 	ASSERT(tcps->tcps_g_q != NULL);
2330 	acceptor->tcp_rq = tcps->tcps_g_q;
2331 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2332 	(void) tcp_clean_death(acceptor, 0, 2);
2333 	CONN_DEC_REF(acceptor->tcp_connp);
2334 
2335 	/*
2336 	 * In case we already received a FIN we have to make tcp_rput send
2337 	 * the ordrel_ind. This will also send up a window update if the window
2338 	 * has opened up.
2339 	 *
2340 	 * In the normal case of a successful connection acceptance
2341 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2342 	 * indication that this was just accepted. This tells tcp_rput to
2343 	 * pass up any data queued in tcp_rcv_list.
2344 	 *
2345 	 * In the fringe case where options sent with T_CONN_RES failed and
2346 	 * we required, we would be indicating a T_DISCON_IND to blow
2347 	 * away this connection.
2348 	 */
2349 
2350 	/*
2351 	 * XXX: we currently have a problem if XTI application closes the
2352 	 * acceptor stream in between. This problem exists in on10-gate also
2353 	 * and is well know but nothing can be done short of major rewrite
2354 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2355 	 * eager same squeue as listener (we can distinguish non socket
2356 	 * listeners at the time of handling a SYN in tcp_conn_request)
2357 	 * and do most of the work that tcp_accept_finish does here itself
2358 	 * and then get behind the acceptor squeue to access the acceptor
2359 	 * queue.
2360 	 */
2361 	/*
2362 	 * We already have a ref on tcp so no need to do one before squeue_fill
2363 	 */
2364 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2365 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2366 }
2367 
2368 /*
2369  * Swap information between the eager and acceptor for a TLI/XTI client.
2370  * The sockfs accept is done on the acceptor stream and control goes
2371  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2372  * called. In either case, both the eager and listener are in their own
2373  * perimeter (squeue) and the code has to deal with potential race.
2374  *
2375  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2376  */
2377 static void
2378 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2379 {
2380 	conn_t	*econnp, *aconnp;
2381 
2382 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2383 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2384 	ASSERT(!eager->tcp_hard_bound);
2385 	ASSERT(!TCP_IS_SOCKET(acceptor));
2386 	ASSERT(!TCP_IS_SOCKET(eager));
2387 	ASSERT(!TCP_IS_SOCKET(listener));
2388 
2389 	acceptor->tcp_detached = B_TRUE;
2390 	/*
2391 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2392 	 * the acceptor id.
2393 	 */
2394 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2395 
2396 	/* remove eager from listen list... */
2397 	mutex_enter(&listener->tcp_eager_lock);
2398 	tcp_eager_unlink(eager);
2399 	ASSERT(eager->tcp_eager_next_q == NULL &&
2400 	    eager->tcp_eager_last_q == NULL);
2401 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2402 	    eager->tcp_eager_prev_q0 == NULL);
2403 	mutex_exit(&listener->tcp_eager_lock);
2404 	eager->tcp_rq = acceptor->tcp_rq;
2405 	eager->tcp_wq = acceptor->tcp_wq;
2406 
2407 	econnp = eager->tcp_connp;
2408 	aconnp = acceptor->tcp_connp;
2409 
2410 	eager->tcp_rq->q_ptr = econnp;
2411 	eager->tcp_wq->q_ptr = econnp;
2412 
2413 	/*
2414 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2415 	 * which might be a different squeue from our peer TCP instance.
2416 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2417 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2418 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2419 	 * above reach global visibility prior to the clearing of tcp_detached.
2420 	 */
2421 	membar_producer();
2422 	eager->tcp_detached = B_FALSE;
2423 
2424 	ASSERT(eager->tcp_ack_tid == 0);
2425 
2426 	econnp->conn_dev = aconnp->conn_dev;
2427 	if (eager->tcp_cred != NULL)
2428 		crfree(eager->tcp_cred);
2429 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2430 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2431 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2432 
2433 	aconnp->conn_cred = NULL;
2434 
2435 	econnp->conn_zoneid = aconnp->conn_zoneid;
2436 	econnp->conn_allzones = aconnp->conn_allzones;
2437 
2438 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2439 	aconnp->conn_mac_exempt = B_FALSE;
2440 
2441 	ASSERT(aconnp->conn_peercred == NULL);
2442 
2443 	/* Do the IPC initialization */
2444 	CONN_INC_REF(econnp);
2445 
2446 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2447 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2448 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2449 	econnp->conn_ulp = aconnp->conn_ulp;
2450 
2451 	/* Done with old IPC. Drop its ref on its connp */
2452 	CONN_DEC_REF(aconnp);
2453 }
2454 
2455 
2456 /*
2457  * Adapt to the information, such as rtt and rtt_sd, provided from the
2458  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2459  *
2460  * Checks for multicast and broadcast destination address.
2461  * Returns zero on failure; non-zero if ok.
2462  *
2463  * Note that the MSS calculation here is based on the info given in
2464  * the IRE.  We do not do any calculation based on TCP options.  They
2465  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2466  * knows which options to use.
2467  *
2468  * Note on how TCP gets its parameters for a connection.
2469  *
2470  * When a tcp_t structure is allocated, it gets all the default parameters.
2471  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2472  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2473  * default.  But if there is an associated tcp_host_param, it will override
2474  * the metrics.
2475  *
2476  * An incoming SYN with a multicast or broadcast destination address, is dropped
2477  * in 1 of 2 places.
2478  *
2479  * 1. If the packet was received over the wire it is dropped in
2480  * ip_rput_process_broadcast()
2481  *
2482  * 2. If the packet was received through internal IP loopback, i.e. the packet
2483  * was generated and received on the same machine, it is dropped in
2484  * ip_wput_local()
2485  *
2486  * An incoming SYN with a multicast or broadcast source address is always
2487  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2488  * reject an attempt to connect to a broadcast or multicast (destination)
2489  * address.
2490  */
2491 static int
2492 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2493 {
2494 	tcp_hsp_t	*hsp;
2495 	ire_t		*ire;
2496 	ire_t		*sire = NULL;
2497 	iulp_t		*ire_uinfo = NULL;
2498 	uint32_t	mss_max;
2499 	uint32_t	mss;
2500 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2501 	conn_t		*connp = tcp->tcp_connp;
2502 	boolean_t	ire_cacheable = B_FALSE;
2503 	zoneid_t	zoneid = connp->conn_zoneid;
2504 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2505 			    MATCH_IRE_SECATTR;
2506 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2507 	ill_t		*ill = NULL;
2508 	boolean_t	incoming = (ire_mp == NULL);
2509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2510 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2511 
2512 	ASSERT(connp->conn_ire_cache == NULL);
2513 
2514 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2515 
2516 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2517 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2518 			return (0);
2519 		}
2520 		/*
2521 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2522 		 * for the destination with the nexthop as gateway.
2523 		 * ire_ctable_lookup() is used because this particular
2524 		 * ire, if it exists, will be marked private.
2525 		 * If that is not available, use the interface ire
2526 		 * for the nexthop.
2527 		 *
2528 		 * TSol: tcp_update_label will detect label mismatches based
2529 		 * only on the destination's label, but that would not
2530 		 * detect label mismatches based on the security attributes
2531 		 * of routes or next hop gateway. Hence we need to pass the
2532 		 * label to ire_ftable_lookup below in order to locate the
2533 		 * right prefix (and/or) ire cache. Similarly we also need
2534 		 * pass the label to the ire_cache_lookup below to locate
2535 		 * the right ire that also matches on the label.
2536 		 */
2537 		if (tcp->tcp_connp->conn_nexthop_set) {
2538 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2539 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2540 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2541 			    ipst);
2542 			if (ire == NULL) {
2543 				ire = ire_ftable_lookup(
2544 				    tcp->tcp_connp->conn_nexthop_v4,
2545 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2546 				    tsl, match_flags, ipst);
2547 				if (ire == NULL)
2548 					return (0);
2549 			} else {
2550 				ire_uinfo = &ire->ire_uinfo;
2551 			}
2552 		} else {
2553 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2554 			    zoneid, tsl, ipst);
2555 			if (ire != NULL) {
2556 				ire_cacheable = B_TRUE;
2557 				ire_uinfo = (ire_mp != NULL) ?
2558 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2559 				    &ire->ire_uinfo;
2560 
2561 			} else {
2562 				if (ire_mp == NULL) {
2563 					ire = ire_ftable_lookup(
2564 					    tcp->tcp_connp->conn_rem,
2565 					    0, 0, 0, NULL, &sire, zoneid, 0,
2566 					    tsl, (MATCH_IRE_RECURSIVE |
2567 					    MATCH_IRE_DEFAULT), ipst);
2568 					if (ire == NULL)
2569 						return (0);
2570 					ire_uinfo = (sire != NULL) ?
2571 					    &sire->ire_uinfo :
2572 					    &ire->ire_uinfo;
2573 				} else {
2574 					ire = (ire_t *)ire_mp->b_rptr;
2575 					ire_uinfo =
2576 					    &((ire_t *)
2577 					    ire_mp->b_rptr)->ire_uinfo;
2578 				}
2579 			}
2580 		}
2581 		ASSERT(ire != NULL);
2582 
2583 		if ((ire->ire_src_addr == INADDR_ANY) ||
2584 		    (ire->ire_type & IRE_BROADCAST)) {
2585 			/*
2586 			 * ire->ire_mp is non null when ire_mp passed in is used
2587 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2588 			 */
2589 			if (ire->ire_mp == NULL)
2590 				ire_refrele(ire);
2591 			if (sire != NULL)
2592 				ire_refrele(sire);
2593 			return (0);
2594 		}
2595 
2596 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2597 			ipaddr_t src_addr;
2598 
2599 			/*
2600 			 * ip_bind_connected() has stored the correct source
2601 			 * address in conn_src.
2602 			 */
2603 			src_addr = tcp->tcp_connp->conn_src;
2604 			tcp->tcp_ipha->ipha_src = src_addr;
2605 			/*
2606 			 * Copy of the src addr. in tcp_t is needed
2607 			 * for the lookup funcs.
2608 			 */
2609 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2610 		}
2611 		/*
2612 		 * Set the fragment bit so that IP will tell us if the MTU
2613 		 * should change. IP tells us the latest setting of
2614 		 * ip_path_mtu_discovery through ire_frag_flag.
2615 		 */
2616 		if (ipst->ips_ip_path_mtu_discovery) {
2617 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2618 			    htons(IPH_DF);
2619 		}
2620 		/*
2621 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2622 		 * for IP_NEXTHOP. No cache ire has been found for the
2623 		 * destination and we are working with the nexthop's
2624 		 * interface ire. Since we need to forward all packets
2625 		 * to the nexthop first, we "blindly" set tcp_localnet
2626 		 * to false, eventhough the destination may also be
2627 		 * onlink.
2628 		 */
2629 		if (ire_uinfo == NULL)
2630 			tcp->tcp_localnet = 0;
2631 		else
2632 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2633 	} else {
2634 		/*
2635 		 * For incoming connection ire_mp = NULL
2636 		 * For outgoing connection ire_mp != NULL
2637 		 * Technically we should check conn_incoming_ill
2638 		 * when ire_mp is NULL and conn_outgoing_ill when
2639 		 * ire_mp is non-NULL. But this is performance
2640 		 * critical path and for IPV*_BOUND_IF, outgoing
2641 		 * and incoming ill are always set to the same value.
2642 		 */
2643 		ill_t	*dst_ill = NULL;
2644 		ipif_t  *dst_ipif = NULL;
2645 
2646 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2647 
2648 		if (connp->conn_outgoing_ill != NULL) {
2649 			/* Outgoing or incoming path */
2650 			int   err;
2651 
2652 			dst_ill = conn_get_held_ill(connp,
2653 			    &connp->conn_outgoing_ill, &err);
2654 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2655 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2656 				return (0);
2657 			}
2658 			match_flags |= MATCH_IRE_ILL;
2659 			dst_ipif = dst_ill->ill_ipif;
2660 		}
2661 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2662 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2663 
2664 		if (ire != NULL) {
2665 			ire_cacheable = B_TRUE;
2666 			ire_uinfo = (ire_mp != NULL) ?
2667 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2668 			    &ire->ire_uinfo;
2669 		} else {
2670 			if (ire_mp == NULL) {
2671 				ire = ire_ftable_lookup_v6(
2672 				    &tcp->tcp_connp->conn_remv6,
2673 				    0, 0, 0, dst_ipif, &sire, zoneid,
2674 				    0, tsl, match_flags, ipst);
2675 				if (ire == NULL) {
2676 					if (dst_ill != NULL)
2677 						ill_refrele(dst_ill);
2678 					return (0);
2679 				}
2680 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2681 				    &ire->ire_uinfo;
2682 			} else {
2683 				ire = (ire_t *)ire_mp->b_rptr;
2684 				ire_uinfo =
2685 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2686 			}
2687 		}
2688 		if (dst_ill != NULL)
2689 			ill_refrele(dst_ill);
2690 
2691 		ASSERT(ire != NULL);
2692 		ASSERT(ire_uinfo != NULL);
2693 
2694 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2695 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2696 			/*
2697 			 * ire->ire_mp is non null when ire_mp passed in is used
2698 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2699 			 */
2700 			if (ire->ire_mp == NULL)
2701 				ire_refrele(ire);
2702 			if (sire != NULL)
2703 				ire_refrele(sire);
2704 			return (0);
2705 		}
2706 
2707 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2708 			in6_addr_t	src_addr;
2709 
2710 			/*
2711 			 * ip_bind_connected_v6() has stored the correct source
2712 			 * address per IPv6 addr. selection policy in
2713 			 * conn_src_v6.
2714 			 */
2715 			src_addr = tcp->tcp_connp->conn_srcv6;
2716 
2717 			tcp->tcp_ip6h->ip6_src = src_addr;
2718 			/*
2719 			 * Copy of the src addr. in tcp_t is needed
2720 			 * for the lookup funcs.
2721 			 */
2722 			tcp->tcp_ip_src_v6 = src_addr;
2723 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2724 			    &connp->conn_srcv6));
2725 		}
2726 		tcp->tcp_localnet =
2727 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2728 	}
2729 
2730 	/*
2731 	 * This allows applications to fail quickly when connections are made
2732 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2733 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2734 	 */
2735 	if ((ire->ire_flags & RTF_REJECT) &&
2736 	    (ire->ire_flags & RTF_PRIVATE))
2737 		goto error;
2738 
2739 	/*
2740 	 * Make use of the cached rtt and rtt_sd values to calculate the
2741 	 * initial RTO.  Note that they are already initialized in
2742 	 * tcp_init_values().
2743 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2744 	 * IP_NEXTHOP, but instead are using the interface ire for the
2745 	 * nexthop, then we do not use the ire_uinfo from that ire to
2746 	 * do any initializations.
2747 	 */
2748 	if (ire_uinfo != NULL) {
2749 		if (ire_uinfo->iulp_rtt != 0) {
2750 			clock_t	rto;
2751 
2752 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2753 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2754 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2755 			    tcps->tcps_rexmit_interval_extra +
2756 			    (tcp->tcp_rtt_sa >> 5);
2757 
2758 			if (rto > tcps->tcps_rexmit_interval_max) {
2759 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2760 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2761 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2762 			} else {
2763 				tcp->tcp_rto = rto;
2764 			}
2765 		}
2766 		if (ire_uinfo->iulp_ssthresh != 0)
2767 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2768 		else
2769 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2770 		if (ire_uinfo->iulp_spipe > 0) {
2771 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2772 			    tcps->tcps_max_buf);
2773 			if (tcps->tcps_snd_lowat_fraction != 0)
2774 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2775 				    tcps->tcps_snd_lowat_fraction;
2776 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2777 		}
2778 		/*
2779 		 * Note that up till now, acceptor always inherits receive
2780 		 * window from the listener.  But if there is a metrics
2781 		 * associated with a host, we should use that instead of
2782 		 * inheriting it from listener. Thus we need to pass this
2783 		 * info back to the caller.
2784 		 */
2785 		if (ire_uinfo->iulp_rpipe > 0) {
2786 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2787 					    tcps->tcps_max_buf);
2788 		}
2789 
2790 		if (ire_uinfo->iulp_rtomax > 0) {
2791 			tcp->tcp_second_timer_threshold =
2792 			    ire_uinfo->iulp_rtomax;
2793 		}
2794 
2795 		/*
2796 		 * Use the metric option settings, iulp_tstamp_ok and
2797 		 * iulp_wscale_ok, only for active open. What this means
2798 		 * is that if the other side uses timestamp or window
2799 		 * scale option, TCP will also use those options. That
2800 		 * is for passive open.  If the application sets a
2801 		 * large window, window scale is enabled regardless of
2802 		 * the value in iulp_wscale_ok.  This is the behavior
2803 		 * since 2.6.  So we keep it.
2804 		 * The only case left in passive open processing is the
2805 		 * check for SACK.
2806 		 * For ECN, it should probably be like SACK.  But the
2807 		 * current value is binary, so we treat it like the other
2808 		 * cases.  The metric only controls active open.For passive
2809 		 * open, the ndd param, tcp_ecn_permitted, controls the
2810 		 * behavior.
2811 		 */
2812 		if (!tcp_detached) {
2813 			/*
2814 			 * The if check means that the following can only
2815 			 * be turned on by the metrics only IRE, but not off.
2816 			 */
2817 			if (ire_uinfo->iulp_tstamp_ok)
2818 				tcp->tcp_snd_ts_ok = B_TRUE;
2819 			if (ire_uinfo->iulp_wscale_ok)
2820 				tcp->tcp_snd_ws_ok = B_TRUE;
2821 			if (ire_uinfo->iulp_sack == 2)
2822 				tcp->tcp_snd_sack_ok = B_TRUE;
2823 			if (ire_uinfo->iulp_ecn_ok)
2824 				tcp->tcp_ecn_ok = B_TRUE;
2825 		} else {
2826 			/*
2827 			 * Passive open.
2828 			 *
2829 			 * As above, the if check means that SACK can only be
2830 			 * turned on by the metric only IRE.
2831 			 */
2832 			if (ire_uinfo->iulp_sack > 0) {
2833 				tcp->tcp_snd_sack_ok = B_TRUE;
2834 			}
2835 		}
2836 	}
2837 
2838 
2839 	/*
2840 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2841 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2842 	 * length of all those options exceeds 28 bytes.  But because
2843 	 * of the tcp_mss_min check below, we may not have a problem if
2844 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2845 	 * the negative problem still exists.  And the check defeats PMTUd.
2846 	 * In fact, if PMTUd finds that the MSS should be smaller than
2847 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2848 	 * value.
2849 	 *
2850 	 * We do not deal with that now.  All those problems related to
2851 	 * PMTUd will be fixed later.
2852 	 */
2853 	ASSERT(ire->ire_max_frag != 0);
2854 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2855 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2856 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2857 			mss = MIN(mss, IPV6_MIN_MTU);
2858 		}
2859 	}
2860 
2861 	/* Sanity check for MSS value. */
2862 	if (tcp->tcp_ipversion == IPV4_VERSION)
2863 		mss_max = tcps->tcps_mss_max_ipv4;
2864 	else
2865 		mss_max = tcps->tcps_mss_max_ipv6;
2866 
2867 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2868 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2869 		/*
2870 		 * After receiving an ICMPv6 "packet too big" message with a
2871 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2872 		 * will insert a 8-byte fragment header in every packet; we
2873 		 * reduce the MSS by that amount here.
2874 		 */
2875 		mss -= sizeof (ip6_frag_t);
2876 	}
2877 
2878 	if (tcp->tcp_ipsec_overhead == 0)
2879 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2880 
2881 	mss -= tcp->tcp_ipsec_overhead;
2882 
2883 	if (mss < tcps->tcps_mss_min)
2884 		mss = tcps->tcps_mss_min;
2885 	if (mss > mss_max)
2886 		mss = mss_max;
2887 
2888 	/* Note that this is the maximum MSS, excluding all options. */
2889 	tcp->tcp_mss = mss;
2890 
2891 	/*
2892 	 * Initialize the ISS here now that we have the full connection ID.
2893 	 * The RFC 1948 method of initial sequence number generation requires
2894 	 * knowledge of the full connection ID before setting the ISS.
2895 	 */
2896 
2897 	tcp_iss_init(tcp);
2898 
2899 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2900 		tcp->tcp_loopback = B_TRUE;
2901 
2902 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2903 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2904 	} else {
2905 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2906 	}
2907 
2908 	if (hsp != NULL) {
2909 		/* Only modify if we're going to make them bigger */
2910 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2911 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2912 			if (tcps->tcps_snd_lowat_fraction != 0)
2913 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2914 					tcps->tcps_snd_lowat_fraction;
2915 		}
2916 
2917 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2918 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2919 		}
2920 
2921 		/* Copy timestamp flag only for active open */
2922 		if (!tcp_detached)
2923 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2924 	}
2925 
2926 	if (sire != NULL)
2927 		IRE_REFRELE(sire);
2928 
2929 	/*
2930 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2931 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2932 	 */
2933 	if (tcp->tcp_loopback ||
2934 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2935 		/*
2936 		 * For incoming, see if this tcp may be MDT-capable.  For
2937 		 * outgoing, this process has been taken care of through
2938 		 * tcp_rput_other.
2939 		 */
2940 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2941 		tcp->tcp_ire_ill_check_done = B_TRUE;
2942 	}
2943 
2944 	mutex_enter(&connp->conn_lock);
2945 	/*
2946 	 * Make sure that conn is not marked incipient
2947 	 * for incoming connections. A blind
2948 	 * removal of incipient flag is cheaper than
2949 	 * check and removal.
2950 	 */
2951 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2952 
2953 	/*
2954 	 * Must not cache forwarding table routes
2955 	 * or recache an IRE after the conn_t has
2956 	 * had conn_ire_cache cleared and is flagged
2957 	 * unusable, (see the CONN_CACHE_IRE() macro).
2958 	 */
2959 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2960 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2961 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2962 			connp->conn_ire_cache = ire;
2963 			IRE_UNTRACE_REF(ire);
2964 			rw_exit(&ire->ire_bucket->irb_lock);
2965 			mutex_exit(&connp->conn_lock);
2966 			return (1);
2967 		}
2968 		rw_exit(&ire->ire_bucket->irb_lock);
2969 	}
2970 	mutex_exit(&connp->conn_lock);
2971 
2972 	if (ire->ire_mp == NULL)
2973 		ire_refrele(ire);
2974 	return (1);
2975 
2976 error:
2977 	if (ire->ire_mp == NULL)
2978 		ire_refrele(ire);
2979 	if (sire != NULL)
2980 		ire_refrele(sire);
2981 	return (0);
2982 }
2983 
2984 /*
2985  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2986  * O_T_BIND_REQ/T_BIND_REQ message.
2987  */
2988 static void
2989 tcp_bind(tcp_t *tcp, mblk_t *mp)
2990 {
2991 	sin_t	*sin;
2992 	sin6_t	*sin6;
2993 	mblk_t	*mp1;
2994 	in_port_t requested_port;
2995 	in_port_t allocated_port;
2996 	struct T_bind_req *tbr;
2997 	boolean_t	bind_to_req_port_only;
2998 	boolean_t	backlog_update = B_FALSE;
2999 	boolean_t	user_specified;
3000 	in6_addr_t	v6addr;
3001 	ipaddr_t	v4addr;
3002 	uint_t	origipversion;
3003 	int	err;
3004 	queue_t *q = tcp->tcp_wq;
3005 	conn_t	*connp;
3006 	mlp_type_t addrtype, mlptype;
3007 	zone_t	*zone;
3008 	cred_t	*cr;
3009 	in_port_t mlp_port;
3010 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3011 
3012 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3013 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3014 		if (tcp->tcp_debug) {
3015 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3016 			    "tcp_bind: bad req, len %u",
3017 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3018 		}
3019 		tcp_err_ack(tcp, mp, TPROTO, 0);
3020 		return;
3021 	}
3022 	/* Make sure the largest address fits */
3023 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3024 	if (mp1 == NULL) {
3025 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3026 		return;
3027 	}
3028 	mp = mp1;
3029 	tbr = (struct T_bind_req *)mp->b_rptr;
3030 	if (tcp->tcp_state >= TCPS_BOUND) {
3031 		if ((tcp->tcp_state == TCPS_BOUND ||
3032 		    tcp->tcp_state == TCPS_LISTEN) &&
3033 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3034 		    tbr->CONIND_number > 0) {
3035 			/*
3036 			 * Handle listen() increasing CONIND_number.
3037 			 * This is more "liberal" then what the TPI spec
3038 			 * requires but is needed to avoid a t_unbind
3039 			 * when handling listen() since the port number
3040 			 * might be "stolen" between the unbind and bind.
3041 			 */
3042 			backlog_update = B_TRUE;
3043 			goto do_bind;
3044 		}
3045 		if (tcp->tcp_debug) {
3046 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3047 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3048 		}
3049 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3050 		return;
3051 	}
3052 	origipversion = tcp->tcp_ipversion;
3053 
3054 	switch (tbr->ADDR_length) {
3055 	case 0:			/* request for a generic port */
3056 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3057 		if (tcp->tcp_family == AF_INET) {
3058 			tbr->ADDR_length = sizeof (sin_t);
3059 			sin = (sin_t *)&tbr[1];
3060 			*sin = sin_null;
3061 			sin->sin_family = AF_INET;
3062 			mp->b_wptr = (uchar_t *)&sin[1];
3063 			tcp->tcp_ipversion = IPV4_VERSION;
3064 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3065 		} else {
3066 			ASSERT(tcp->tcp_family == AF_INET6);
3067 			tbr->ADDR_length = sizeof (sin6_t);
3068 			sin6 = (sin6_t *)&tbr[1];
3069 			*sin6 = sin6_null;
3070 			sin6->sin6_family = AF_INET6;
3071 			mp->b_wptr = (uchar_t *)&sin6[1];
3072 			tcp->tcp_ipversion = IPV6_VERSION;
3073 			V6_SET_ZERO(v6addr);
3074 		}
3075 		requested_port = 0;
3076 		break;
3077 
3078 	case sizeof (sin_t):	/* Complete IPv4 address */
3079 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3080 		    sizeof (sin_t));
3081 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3082 			if (tcp->tcp_debug) {
3083 				(void) strlog(TCP_MOD_ID, 0, 1,
3084 				    SL_ERROR|SL_TRACE,
3085 				    "tcp_bind: bad address parameter, "
3086 				    "offset %d, len %d",
3087 				    tbr->ADDR_offset, tbr->ADDR_length);
3088 			}
3089 			tcp_err_ack(tcp, mp, TPROTO, 0);
3090 			return;
3091 		}
3092 		/*
3093 		 * With sockets sockfs will accept bogus sin_family in
3094 		 * bind() and replace it with the family used in the socket
3095 		 * call.
3096 		 */
3097 		if (sin->sin_family != AF_INET ||
3098 		    tcp->tcp_family != AF_INET) {
3099 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3100 			return;
3101 		}
3102 		requested_port = ntohs(sin->sin_port);
3103 		tcp->tcp_ipversion = IPV4_VERSION;
3104 		v4addr = sin->sin_addr.s_addr;
3105 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3106 		break;
3107 
3108 	case sizeof (sin6_t): /* Complete IPv6 address */
3109 		sin6 = (sin6_t *)mi_offset_param(mp,
3110 		    tbr->ADDR_offset, sizeof (sin6_t));
3111 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3112 			if (tcp->tcp_debug) {
3113 				(void) strlog(TCP_MOD_ID, 0, 1,
3114 				    SL_ERROR|SL_TRACE,
3115 				    "tcp_bind: bad IPv6 address parameter, "
3116 				    "offset %d, len %d", tbr->ADDR_offset,
3117 				    tbr->ADDR_length);
3118 			}
3119 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3120 			return;
3121 		}
3122 		if (sin6->sin6_family != AF_INET6 ||
3123 		    tcp->tcp_family != AF_INET6) {
3124 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3125 			return;
3126 		}
3127 		requested_port = ntohs(sin6->sin6_port);
3128 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3129 		    IPV4_VERSION : IPV6_VERSION;
3130 		v6addr = sin6->sin6_addr;
3131 		break;
3132 
3133 	default:
3134 		if (tcp->tcp_debug) {
3135 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3136 			    "tcp_bind: bad address length, %d",
3137 			    tbr->ADDR_length);
3138 		}
3139 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3140 		return;
3141 	}
3142 	tcp->tcp_bound_source_v6 = v6addr;
3143 
3144 	/* Check for change in ipversion */
3145 	if (origipversion != tcp->tcp_ipversion) {
3146 		ASSERT(tcp->tcp_family == AF_INET6);
3147 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3148 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3149 		if (err) {
3150 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3151 			return;
3152 		}
3153 	}
3154 
3155 	/*
3156 	 * Initialize family specific fields. Copy of the src addr.
3157 	 * in tcp_t is needed for the lookup funcs.
3158 	 */
3159 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3160 		tcp->tcp_ip6h->ip6_src = v6addr;
3161 	} else {
3162 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3163 	}
3164 	tcp->tcp_ip_src_v6 = v6addr;
3165 
3166 	/*
3167 	 * For O_T_BIND_REQ:
3168 	 * Verify that the target port/addr is available, or choose
3169 	 * another.
3170 	 * For  T_BIND_REQ:
3171 	 * Verify that the target port/addr is available or fail.
3172 	 * In both cases when it succeeds the tcp is inserted in the
3173 	 * bind hash table. This ensures that the operation is atomic
3174 	 * under the lock on the hash bucket.
3175 	 */
3176 	bind_to_req_port_only = requested_port != 0 &&
3177 	    tbr->PRIM_type != O_T_BIND_REQ;
3178 	/*
3179 	 * Get a valid port (within the anonymous range and should not
3180 	 * be a privileged one) to use if the user has not given a port.
3181 	 * If multiple threads are here, they may all start with
3182 	 * with the same initial port. But, it should be fine as long as
3183 	 * tcp_bindi will ensure that no two threads will be assigned
3184 	 * the same port.
3185 	 *
3186 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3187 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3188 	 * unless TCP_ANONPRIVBIND option is set.
3189 	 */
3190 	mlptype = mlptSingle;
3191 	mlp_port = requested_port;
3192 	if (requested_port == 0) {
3193 		requested_port = tcp->tcp_anon_priv_bind ?
3194 		    tcp_get_next_priv_port(tcp) :
3195 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3196 			tcp, B_TRUE);
3197 		if (requested_port == 0) {
3198 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3199 			return;
3200 		}
3201 		user_specified = B_FALSE;
3202 
3203 		/*
3204 		 * If the user went through one of the RPC interfaces to create
3205 		 * this socket and RPC is MLP in this zone, then give him an
3206 		 * anonymous MLP.
3207 		 */
3208 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3209 		connp = tcp->tcp_connp;
3210 		if (connp->conn_anon_mlp && is_system_labeled()) {
3211 			zone = crgetzone(cr);
3212 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3213 			    IPV6_VERSION, &v6addr,
3214 			    tcps->tcps_netstack->netstack_ip);
3215 			if (addrtype == mlptSingle) {
3216 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3217 				return;
3218 			}
3219 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3220 			    PMAPPORT, addrtype);
3221 			mlp_port = PMAPPORT;
3222 		}
3223 	} else {
3224 		int i;
3225 		boolean_t priv = B_FALSE;
3226 
3227 		/*
3228 		 * If the requested_port is in the well-known privileged range,
3229 		 * verify that the stream was opened by a privileged user.
3230 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3231 		 * but instead the code relies on:
3232 		 * - the fact that the address of the array and its size never
3233 		 *   changes
3234 		 * - the atomic assignment of the elements of the array
3235 		 */
3236 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3237 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3238 			priv = B_TRUE;
3239 		} else {
3240 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3241 				if (requested_port ==
3242 				    tcps->tcps_g_epriv_ports[i]) {
3243 					priv = B_TRUE;
3244 					break;
3245 				}
3246 			}
3247 		}
3248 		if (priv) {
3249 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3250 				if (tcp->tcp_debug) {
3251 					(void) strlog(TCP_MOD_ID, 0, 1,
3252 					    SL_ERROR|SL_TRACE,
3253 					    "tcp_bind: no priv for port %d",
3254 					    requested_port);
3255 				}
3256 				tcp_err_ack(tcp, mp, TACCES, 0);
3257 				return;
3258 			}
3259 		}
3260 		user_specified = B_TRUE;
3261 
3262 		connp = tcp->tcp_connp;
3263 		if (is_system_labeled()) {
3264 			zone = crgetzone(cr);
3265 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3266 			    IPV6_VERSION, &v6addr,
3267 			    tcps->tcps_netstack->netstack_ip);
3268 			if (addrtype == mlptSingle) {
3269 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3270 				return;
3271 			}
3272 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3273 			    requested_port, addrtype);
3274 		}
3275 	}
3276 
3277 	if (mlptype != mlptSingle) {
3278 		if (secpolicy_net_bindmlp(cr) != 0) {
3279 			if (tcp->tcp_debug) {
3280 				(void) strlog(TCP_MOD_ID, 0, 1,
3281 				    SL_ERROR|SL_TRACE,
3282 				    "tcp_bind: no priv for multilevel port %d",
3283 				    requested_port);
3284 			}
3285 			tcp_err_ack(tcp, mp, TACCES, 0);
3286 			return;
3287 		}
3288 
3289 		/*
3290 		 * If we're specifically binding a shared IP address and the
3291 		 * port is MLP on shared addresses, then check to see if this
3292 		 * zone actually owns the MLP.  Reject if not.
3293 		 */
3294 		if (mlptype == mlptShared && addrtype == mlptShared) {
3295 			/*
3296 			 * No need to handle exclusive-stack zones since
3297 			 * ALL_ZONES only applies to the shared stack.
3298 			 */
3299 			zoneid_t mlpzone;
3300 
3301 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3302 			    htons(mlp_port));
3303 			if (connp->conn_zoneid != mlpzone) {
3304 				if (tcp->tcp_debug) {
3305 					(void) strlog(TCP_MOD_ID, 0, 1,
3306 					    SL_ERROR|SL_TRACE,
3307 					    "tcp_bind: attempt to bind port "
3308 					    "%d on shared addr in zone %d "
3309 					    "(should be %d)",
3310 					    mlp_port, connp->conn_zoneid,
3311 					    mlpzone);
3312 				}
3313 				tcp_err_ack(tcp, mp, TACCES, 0);
3314 				return;
3315 			}
3316 		}
3317 
3318 		if (!user_specified) {
3319 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3320 			    requested_port, B_TRUE);
3321 			if (err != 0) {
3322 				if (tcp->tcp_debug) {
3323 					(void) strlog(TCP_MOD_ID, 0, 1,
3324 					    SL_ERROR|SL_TRACE,
3325 					    "tcp_bind: cannot establish anon "
3326 					    "MLP for port %d",
3327 					    requested_port);
3328 				}
3329 				tcp_err_ack(tcp, mp, TSYSERR, err);
3330 				return;
3331 			}
3332 			connp->conn_anon_port = B_TRUE;
3333 		}
3334 		connp->conn_mlp_type = mlptype;
3335 	}
3336 
3337 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3338 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3339 
3340 	if (allocated_port == 0) {
3341 		connp->conn_mlp_type = mlptSingle;
3342 		if (connp->conn_anon_port) {
3343 			connp->conn_anon_port = B_FALSE;
3344 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3345 			    requested_port, B_FALSE);
3346 		}
3347 		if (bind_to_req_port_only) {
3348 			if (tcp->tcp_debug) {
3349 				(void) strlog(TCP_MOD_ID, 0, 1,
3350 				    SL_ERROR|SL_TRACE,
3351 				    "tcp_bind: requested addr busy");
3352 			}
3353 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3354 		} else {
3355 			/* If we are out of ports, fail the bind. */
3356 			if (tcp->tcp_debug) {
3357 				(void) strlog(TCP_MOD_ID, 0, 1,
3358 				    SL_ERROR|SL_TRACE,
3359 				    "tcp_bind: out of ports?");
3360 			}
3361 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3362 		}
3363 		return;
3364 	}
3365 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3366 do_bind:
3367 	if (!backlog_update) {
3368 		if (tcp->tcp_family == AF_INET)
3369 			sin->sin_port = htons(allocated_port);
3370 		else
3371 			sin6->sin6_port = htons(allocated_port);
3372 	}
3373 	if (tcp->tcp_family == AF_INET) {
3374 		if (tbr->CONIND_number != 0) {
3375 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3376 			    sizeof (sin_t));
3377 		} else {
3378 			/* Just verify the local IP address */
3379 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3380 		}
3381 	} else {
3382 		if (tbr->CONIND_number != 0) {
3383 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3384 			    sizeof (sin6_t));
3385 		} else {
3386 			/* Just verify the local IP address */
3387 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3388 			    IPV6_ADDR_LEN);
3389 		}
3390 	}
3391 	if (mp1 == NULL) {
3392 		if (connp->conn_anon_port) {
3393 			connp->conn_anon_port = B_FALSE;
3394 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3395 			    requested_port, B_FALSE);
3396 		}
3397 		connp->conn_mlp_type = mlptSingle;
3398 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3399 		return;
3400 	}
3401 
3402 	tbr->PRIM_type = T_BIND_ACK;
3403 	mp->b_datap->db_type = M_PCPROTO;
3404 
3405 	/* Chain in the reply mp for tcp_rput() */
3406 	mp1->b_cont = mp;
3407 	mp = mp1;
3408 
3409 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3410 	if (tcp->tcp_conn_req_max) {
3411 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3412 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3413 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3414 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3415 		/*
3416 		 * If this is a listener, do not reset the eager list
3417 		 * and other stuffs.  Note that we don't check if the
3418 		 * existing eager list meets the new tcp_conn_req_max
3419 		 * requirement.
3420 		 */
3421 		if (tcp->tcp_state != TCPS_LISTEN) {
3422 			tcp->tcp_state = TCPS_LISTEN;
3423 			/* Initialize the chain. Don't need the eager_lock */
3424 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3425 			tcp->tcp_eager_next_drop_q0 = tcp;
3426 			tcp->tcp_eager_prev_drop_q0 = tcp;
3427 			tcp->tcp_second_ctimer_threshold =
3428 			    tcps->tcps_ip_abort_linterval;
3429 		}
3430 	}
3431 
3432 	/*
3433 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3434 	 * processing continues in tcp_rput_other().
3435 	 */
3436 	if (tcp->tcp_family == AF_INET6) {
3437 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3438 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3439 	} else {
3440 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3441 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3442 	}
3443 	/*
3444 	 * If the bind cannot complete immediately
3445 	 * IP will arrange to call tcp_rput_other
3446 	 * when the bind completes.
3447 	 */
3448 	if (mp != NULL) {
3449 		tcp_rput_other(tcp, mp);
3450 	} else {
3451 		/*
3452 		 * Bind will be resumed later. Need to ensure
3453 		 * that conn doesn't disappear when that happens.
3454 		 * This will be decremented in ip_resume_tcp_bind().
3455 		 */
3456 		CONN_INC_REF(tcp->tcp_connp);
3457 	}
3458 }
3459 
3460 
3461 /*
3462  * If the "bind_to_req_port_only" parameter is set, if the requested port
3463  * number is available, return it, If not return 0
3464  *
3465  * If "bind_to_req_port_only" parameter is not set and
3466  * If the requested port number is available, return it.  If not, return
3467  * the first anonymous port we happen across.  If no anonymous ports are
3468  * available, return 0. addr is the requested local address, if any.
3469  *
3470  * In either case, when succeeding update the tcp_t to record the port number
3471  * and insert it in the bind hash table.
3472  *
3473  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3474  * without setting SO_REUSEADDR. This is needed so that they
3475  * can be viewed as two independent transport protocols.
3476  */
3477 static in_port_t
3478 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3479     int reuseaddr, boolean_t quick_connect,
3480     boolean_t bind_to_req_port_only, boolean_t user_specified)
3481 {
3482 	/* number of times we have run around the loop */
3483 	int count = 0;
3484 	/* maximum number of times to run around the loop */
3485 	int loopmax;
3486 	conn_t *connp = tcp->tcp_connp;
3487 	zoneid_t zoneid = connp->conn_zoneid;
3488 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3489 
3490 	/*
3491 	 * Lookup for free addresses is done in a loop and "loopmax"
3492 	 * influences how long we spin in the loop
3493 	 */
3494 	if (bind_to_req_port_only) {
3495 		/*
3496 		 * If the requested port is busy, don't bother to look
3497 		 * for a new one. Setting loop maximum count to 1 has
3498 		 * that effect.
3499 		 */
3500 		loopmax = 1;
3501 	} else {
3502 		/*
3503 		 * If the requested port is busy, look for a free one
3504 		 * in the anonymous port range.
3505 		 * Set loopmax appropriately so that one does not look
3506 		 * forever in the case all of the anonymous ports are in use.
3507 		 */
3508 		if (tcp->tcp_anon_priv_bind) {
3509 			/*
3510 			 * loopmax =
3511 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3512 			 */
3513 			loopmax = IPPORT_RESERVED -
3514 			    tcps->tcps_min_anonpriv_port;
3515 		} else {
3516 			loopmax = (tcps->tcps_largest_anon_port -
3517 			    tcps->tcps_smallest_anon_port + 1);
3518 		}
3519 	}
3520 	do {
3521 		uint16_t	lport;
3522 		tf_t		*tbf;
3523 		tcp_t		*ltcp;
3524 		conn_t		*lconnp;
3525 
3526 		lport = htons(port);
3527 
3528 		/*
3529 		 * Ensure that the tcp_t is not currently in the bind hash.
3530 		 * Hold the lock on the hash bucket to ensure that
3531 		 * the duplicate check plus the insertion is an atomic
3532 		 * operation.
3533 		 *
3534 		 * This function does an inline lookup on the bind hash list
3535 		 * Make sure that we access only members of tcp_t
3536 		 * and that we don't look at tcp_tcp, since we are not
3537 		 * doing a CONN_INC_REF.
3538 		 */
3539 		tcp_bind_hash_remove(tcp);
3540 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3541 		mutex_enter(&tbf->tf_lock);
3542 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3543 		    ltcp = ltcp->tcp_bind_hash) {
3544 			boolean_t not_socket;
3545 			boolean_t exclbind;
3546 
3547 			if (lport != ltcp->tcp_lport)
3548 				continue;
3549 
3550 			lconnp = ltcp->tcp_connp;
3551 
3552 			/*
3553 			 * On a labeled system, we must treat bindings to ports
3554 			 * on shared IP addresses by sockets with MAC exemption
3555 			 * privilege as being in all zones, as there's
3556 			 * otherwise no way to identify the right receiver.
3557 			 */
3558 			if (!IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) &&
3559 			    !lconnp->conn_mac_exempt &&
3560 			    !connp->conn_mac_exempt)
3561 				continue;
3562 
3563 			/*
3564 			 * If TCP_EXCLBIND is set for either the bound or
3565 			 * binding endpoint, the semantics of bind
3566 			 * is changed according to the following.
3567 			 *
3568 			 * spec = specified address (v4 or v6)
3569 			 * unspec = unspecified address (v4 or v6)
3570 			 * A = specified addresses are different for endpoints
3571 			 *
3572 			 * bound	bind to		allowed
3573 			 * -------------------------------------
3574 			 * unspec	unspec		no
3575 			 * unspec	spec		no
3576 			 * spec		unspec		no
3577 			 * spec		spec		yes if A
3578 			 *
3579 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3580 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3581 			 *
3582 			 * Note:
3583 			 *
3584 			 * 1. Because of TLI semantics, an endpoint can go
3585 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3586 			 * TCPS_BOUND, depending on whether it is originally
3587 			 * a listener or not.  That is why we need to check
3588 			 * for states greater than or equal to TCPS_BOUND
3589 			 * here.
3590 			 *
3591 			 * 2. Ideally, we should only check for state equals
3592 			 * to TCPS_LISTEN. And the following check should be
3593 			 * added.
3594 			 *
3595 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3596 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3597 			 *		...
3598 			 * }
3599 			 *
3600 			 * The semantics will be changed to this.  If the
3601 			 * endpoint on the list is in state not equal to
3602 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3603 			 * set, let the bind succeed.
3604 			 *
3605 			 * Because of (1), we cannot do that for TLI
3606 			 * endpoints.  But we can do that for socket endpoints.
3607 			 * If in future, we can change this going back
3608 			 * semantics, we can use the above check for TLI also.
3609 			 */
3610 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3611 			    TCP_IS_SOCKET(tcp));
3612 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3613 
3614 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3615 			    (exclbind && (not_socket ||
3616 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3617 				if (V6_OR_V4_INADDR_ANY(
3618 				    ltcp->tcp_bound_source_v6) ||
3619 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3620 				    IN6_ARE_ADDR_EQUAL(laddr,
3621 				    &ltcp->tcp_bound_source_v6)) {
3622 					break;
3623 				}
3624 				continue;
3625 			}
3626 
3627 			/*
3628 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3629 			 * have disjoint port number spaces, if *_EXCLBIND
3630 			 * is not set and only if the application binds to a
3631 			 * specific port. We use the same autoassigned port
3632 			 * number space for IPv4 and IPv6 sockets.
3633 			 */
3634 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3635 			    bind_to_req_port_only)
3636 				continue;
3637 
3638 			/*
3639 			 * Ideally, we should make sure that the source
3640 			 * address, remote address, and remote port in the
3641 			 * four tuple for this tcp-connection is unique.
3642 			 * However, trying to find out the local source
3643 			 * address would require too much code duplication
3644 			 * with IP, since IP needs needs to have that code
3645 			 * to support userland TCP implementations.
3646 			 */
3647 			if (quick_connect &&
3648 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3649 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3650 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3651 				    &ltcp->tcp_remote_v6)))
3652 				continue;
3653 
3654 			if (!reuseaddr) {
3655 				/*
3656 				 * No socket option SO_REUSEADDR.
3657 				 * If existing port is bound to
3658 				 * a non-wildcard IP address
3659 				 * and the requesting stream is
3660 				 * bound to a distinct
3661 				 * different IP addresses
3662 				 * (non-wildcard, also), keep
3663 				 * going.
3664 				 */
3665 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3666 				    !V6_OR_V4_INADDR_ANY(
3667 				    ltcp->tcp_bound_source_v6) &&
3668 				    !IN6_ARE_ADDR_EQUAL(laddr,
3669 					&ltcp->tcp_bound_source_v6))
3670 					continue;
3671 				if (ltcp->tcp_state >= TCPS_BOUND) {
3672 					/*
3673 					 * This port is being used and
3674 					 * its state is >= TCPS_BOUND,
3675 					 * so we can't bind to it.
3676 					 */
3677 					break;
3678 				}
3679 			} else {
3680 				/*
3681 				 * socket option SO_REUSEADDR is set on the
3682 				 * binding tcp_t.
3683 				 *
3684 				 * If two streams are bound to
3685 				 * same IP address or both addr
3686 				 * and bound source are wildcards
3687 				 * (INADDR_ANY), we want to stop
3688 				 * searching.
3689 				 * We have found a match of IP source
3690 				 * address and source port, which is
3691 				 * refused regardless of the
3692 				 * SO_REUSEADDR setting, so we break.
3693 				 */
3694 				if (IN6_ARE_ADDR_EQUAL(laddr,
3695 				    &ltcp->tcp_bound_source_v6) &&
3696 				    (ltcp->tcp_state == TCPS_LISTEN ||
3697 					ltcp->tcp_state == TCPS_BOUND))
3698 					break;
3699 			}
3700 		}
3701 		if (ltcp != NULL) {
3702 			/* The port number is busy */
3703 			mutex_exit(&tbf->tf_lock);
3704 		} else {
3705 			/*
3706 			 * This port is ours. Insert in fanout and mark as
3707 			 * bound to prevent others from getting the port
3708 			 * number.
3709 			 */
3710 			tcp->tcp_state = TCPS_BOUND;
3711 			tcp->tcp_lport = htons(port);
3712 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3713 
3714 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3715 			    tcp->tcp_lport)] == tbf);
3716 			tcp_bind_hash_insert(tbf, tcp, 1);
3717 
3718 			mutex_exit(&tbf->tf_lock);
3719 
3720 			/*
3721 			 * We don't want tcp_next_port_to_try to "inherit"
3722 			 * a port number supplied by the user in a bind.
3723 			 */
3724 			if (user_specified)
3725 				return (port);
3726 
3727 			/*
3728 			 * This is the only place where tcp_next_port_to_try
3729 			 * is updated. After the update, it may or may not
3730 			 * be in the valid range.
3731 			 */
3732 			if (!tcp->tcp_anon_priv_bind)
3733 				tcps->tcps_next_port_to_try = port + 1;
3734 			return (port);
3735 		}
3736 
3737 		if (tcp->tcp_anon_priv_bind) {
3738 			port = tcp_get_next_priv_port(tcp);
3739 		} else {
3740 			if (count == 0 && user_specified) {
3741 				/*
3742 				 * We may have to return an anonymous port. So
3743 				 * get one to start with.
3744 				 */
3745 				port =
3746 				    tcp_update_next_port(
3747 					tcps->tcps_next_port_to_try,
3748 					tcp, B_TRUE);
3749 				user_specified = B_FALSE;
3750 			} else {
3751 				port = tcp_update_next_port(port + 1, tcp,
3752 				    B_FALSE);
3753 			}
3754 		}
3755 		if (port == 0)
3756 			break;
3757 
3758 		/*
3759 		 * Don't let this loop run forever in the case where
3760 		 * all of the anonymous ports are in use.
3761 		 */
3762 	} while (++count < loopmax);
3763 	return (0);
3764 }
3765 
3766 /*
3767  * tcp_clean_death / tcp_close_detached must not be called more than once
3768  * on a tcp. Thus every function that potentially calls tcp_clean_death
3769  * must check for the tcp state before calling tcp_clean_death.
3770  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3771  * tcp_timer_handler, all check for the tcp state.
3772  */
3773 /* ARGSUSED */
3774 void
3775 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3776 {
3777 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3778 
3779 	freemsg(mp);
3780 	if (tcp->tcp_state > TCPS_BOUND)
3781 	    (void) tcp_clean_death(((conn_t *)arg)->conn_tcp, ETIMEDOUT, 5);
3782 }
3783 
3784 /*
3785  * We are dying for some reason.  Try to do it gracefully.  (May be called
3786  * as writer.)
3787  *
3788  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3789  * done by a service procedure).
3790  * TBD - Should the return value distinguish between the tcp_t being
3791  * freed and it being reinitialized?
3792  */
3793 static int
3794 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3795 {
3796 	mblk_t	*mp;
3797 	queue_t	*q;
3798 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3799 
3800 	TCP_CLD_STAT(tag);
3801 
3802 #if TCP_TAG_CLEAN_DEATH
3803 	tcp->tcp_cleandeathtag = tag;
3804 #endif
3805 
3806 	if (tcp->tcp_fused)
3807 		tcp_unfuse(tcp);
3808 
3809 	if (tcp->tcp_linger_tid != 0 &&
3810 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3811 		tcp_stop_lingering(tcp);
3812 	}
3813 
3814 	ASSERT(tcp != NULL);
3815 	ASSERT((tcp->tcp_family == AF_INET &&
3816 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3817 	    (tcp->tcp_family == AF_INET6 &&
3818 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3819 	    tcp->tcp_ipversion == IPV6_VERSION)));
3820 
3821 	if (TCP_IS_DETACHED(tcp)) {
3822 		if (tcp->tcp_hard_binding) {
3823 			/*
3824 			 * Its an eager that we are dealing with. We close the
3825 			 * eager but in case a conn_ind has already gone to the
3826 			 * listener, let tcp_accept_finish() send a discon_ind
3827 			 * to the listener and drop the last reference. If the
3828 			 * listener doesn't even know about the eager i.e. the
3829 			 * conn_ind hasn't gone up, blow away the eager and drop
3830 			 * the last reference as well. If the conn_ind has gone
3831 			 * up, state should be BOUND. tcp_accept_finish
3832 			 * will figure out that the connection has received a
3833 			 * RST and will send a DISCON_IND to the application.
3834 			 */
3835 			tcp_closei_local(tcp);
3836 			if (!tcp->tcp_tconnind_started) {
3837 				CONN_DEC_REF(tcp->tcp_connp);
3838 			} else {
3839 				tcp->tcp_state = TCPS_BOUND;
3840 			}
3841 		} else {
3842 			tcp_close_detached(tcp);
3843 		}
3844 		return (0);
3845 	}
3846 
3847 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3848 
3849 	/*
3850 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3851 	 * is run) postpone cleaning up the endpoint until service routine
3852 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3853 	 * client_errno since tcp_close uses the client_errno field.
3854 	 */
3855 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3856 		if (err != 0)
3857 			tcp->tcp_client_errno = err;
3858 
3859 		tcp->tcp_deferred_clean_death = B_TRUE;
3860 		return (-1);
3861 	}
3862 
3863 	q = tcp->tcp_rq;
3864 
3865 	/* Trash all inbound data */
3866 	flushq(q, FLUSHALL);
3867 
3868 	/*
3869 	 * If we are at least part way open and there is error
3870 	 * (err==0 implies no error)
3871 	 * notify our client by a T_DISCON_IND.
3872 	 */
3873 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3874 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3875 		    !TCP_IS_SOCKET(tcp)) {
3876 			/*
3877 			 * Send M_FLUSH according to TPI. Because sockets will
3878 			 * (and must) ignore FLUSHR we do that only for TPI
3879 			 * endpoints and sockets in STREAMS mode.
3880 			 */
3881 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3882 		}
3883 		if (tcp->tcp_debug) {
3884 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3885 			    "tcp_clean_death: discon err %d", err);
3886 		}
3887 		mp = mi_tpi_discon_ind(NULL, err, 0);
3888 		if (mp != NULL) {
3889 			putnext(q, mp);
3890 		} else {
3891 			if (tcp->tcp_debug) {
3892 				(void) strlog(TCP_MOD_ID, 0, 1,
3893 				    SL_ERROR|SL_TRACE,
3894 				    "tcp_clean_death, sending M_ERROR");
3895 			}
3896 			(void) putnextctl1(q, M_ERROR, EPROTO);
3897 		}
3898 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3899 			/* SYN_SENT or SYN_RCVD */
3900 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3901 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3902 			/* ESTABLISHED or CLOSE_WAIT */
3903 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3904 		}
3905 	}
3906 
3907 	tcp_reinit(tcp);
3908 	return (-1);
3909 }
3910 
3911 /*
3912  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3913  * to expire, stop the wait and finish the close.
3914  */
3915 static void
3916 tcp_stop_lingering(tcp_t *tcp)
3917 {
3918 	clock_t	delta = 0;
3919 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3920 
3921 	tcp->tcp_linger_tid = 0;
3922 	if (tcp->tcp_state > TCPS_LISTEN) {
3923 		tcp_acceptor_hash_remove(tcp);
3924 		mutex_enter(&tcp->tcp_non_sq_lock);
3925 		if (tcp->tcp_flow_stopped) {
3926 			tcp_clrqfull(tcp);
3927 		}
3928 		mutex_exit(&tcp->tcp_non_sq_lock);
3929 
3930 		if (tcp->tcp_timer_tid != 0) {
3931 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3932 			tcp->tcp_timer_tid = 0;
3933 		}
3934 		/*
3935 		 * Need to cancel those timers which will not be used when
3936 		 * TCP is detached.  This has to be done before the tcp_wq
3937 		 * is set to the global queue.
3938 		 */
3939 		tcp_timers_stop(tcp);
3940 
3941 
3942 		tcp->tcp_detached = B_TRUE;
3943 		ASSERT(tcps->tcps_g_q != NULL);
3944 		tcp->tcp_rq = tcps->tcps_g_q;
3945 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3946 
3947 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3948 			tcp_time_wait_append(tcp);
3949 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3950 			goto finish;
3951 		}
3952 
3953 		/*
3954 		 * If delta is zero the timer event wasn't executed and was
3955 		 * successfully canceled. In this case we need to restart it
3956 		 * with the minimal delta possible.
3957 		 */
3958 		if (delta >= 0) {
3959 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3960 			    delta ? delta : 1);
3961 		}
3962 	} else {
3963 		tcp_closei_local(tcp);
3964 		CONN_DEC_REF(tcp->tcp_connp);
3965 	}
3966 finish:
3967 	/* Signal closing thread that it can complete close */
3968 	mutex_enter(&tcp->tcp_closelock);
3969 	tcp->tcp_detached = B_TRUE;
3970 	ASSERT(tcps->tcps_g_q != NULL);
3971 	tcp->tcp_rq = tcps->tcps_g_q;
3972 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3973 	tcp->tcp_closed = 1;
3974 	cv_signal(&tcp->tcp_closecv);
3975 	mutex_exit(&tcp->tcp_closelock);
3976 }
3977 
3978 /*
3979  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3980  * expires.
3981  */
3982 static void
3983 tcp_close_linger_timeout(void *arg)
3984 {
3985 	conn_t	*connp = (conn_t *)arg;
3986 	tcp_t 	*tcp = connp->conn_tcp;
3987 
3988 	tcp->tcp_client_errno = ETIMEDOUT;
3989 	tcp_stop_lingering(tcp);
3990 }
3991 
3992 static int
3993 tcp_close(queue_t *q, int flags)
3994 {
3995 	conn_t		*connp = Q_TO_CONN(q);
3996 	tcp_t		*tcp = connp->conn_tcp;
3997 	mblk_t 		*mp = &tcp->tcp_closemp;
3998 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3999 	boolean_t	linger_interrupted = B_FALSE;
4000 	mblk_t		*bp;
4001 
4002 	ASSERT(WR(q)->q_next == NULL);
4003 	ASSERT(connp->conn_ref >= 2);
4004 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
4005 
4006 	/*
4007 	 * We are being closed as /dev/tcp or /dev/tcp6.
4008 	 *
4009 	 * Mark the conn as closing. ill_pending_mp_add will not
4010 	 * add any mp to the pending mp list, after this conn has
4011 	 * started closing. Same for sq_pending_mp_add
4012 	 */
4013 	mutex_enter(&connp->conn_lock);
4014 	connp->conn_state_flags |= CONN_CLOSING;
4015 	if (connp->conn_oper_pending_ill != NULL)
4016 		conn_ioctl_cleanup_reqd = B_TRUE;
4017 	CONN_INC_REF_LOCKED(connp);
4018 	mutex_exit(&connp->conn_lock);
4019 	tcp->tcp_closeflags = (uint8_t)flags;
4020 	ASSERT(connp->conn_ref >= 3);
4021 
4022 	/*
4023 	 * tcp_closemp_used is used below without any protection of a lock
4024 	 * as we don't expect any one else to use it concurrently at this
4025 	 * point otherwise it would be a major defect.
4026 	 */
4027 
4028 	if (mp->b_prev == NULL)
4029 		tcp->tcp_closemp_used = B_TRUE;
4030 	else
4031 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4032 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4033 
4034 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4035 
4036 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4037 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4038 
4039 	mutex_enter(&tcp->tcp_closelock);
4040 	while (!tcp->tcp_closed) {
4041 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4042 			/*
4043 			 * We got interrupted. Check if we are lingering,
4044 			 * if yes, post a message to stop and wait until
4045 			 * tcp_closed is set. If we aren't lingering,
4046 			 * just go back around.
4047 			 */
4048 			if (tcp->tcp_linger &&
4049 			    tcp->tcp_lingertime > 0 &&
4050 			    !linger_interrupted) {
4051 				mutex_exit(&tcp->tcp_closelock);
4052 				/* Entering squeue, bump ref count. */
4053 				CONN_INC_REF(connp);
4054 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4055 				squeue_enter(connp->conn_sqp, bp,
4056 				    tcp_linger_interrupted, connp,
4057 				    SQTAG_IP_TCP_CLOSE);
4058 				linger_interrupted = B_TRUE;
4059 				mutex_enter(&tcp->tcp_closelock);
4060 			}
4061 		}
4062 	}
4063 	mutex_exit(&tcp->tcp_closelock);
4064 
4065 	/*
4066 	 * In the case of listener streams that have eagers in the q or q0
4067 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4068 	 * tcp_wq of the eagers point to our queues. By waiting for the
4069 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4070 	 * up their queue pointers and also dropped their references to us.
4071 	 */
4072 	if (tcp->tcp_wait_for_eagers) {
4073 		mutex_enter(&connp->conn_lock);
4074 		while (connp->conn_ref != 1) {
4075 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4076 		}
4077 		mutex_exit(&connp->conn_lock);
4078 	}
4079 	/*
4080 	 * ioctl cleanup. The mp is queued in the
4081 	 * ill_pending_mp or in the sq_pending_mp.
4082 	 */
4083 	if (conn_ioctl_cleanup_reqd)
4084 		conn_ioctl_cleanup(connp);
4085 
4086 	qprocsoff(q);
4087 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4088 
4089 	tcp->tcp_cpid = -1;
4090 
4091 	/*
4092 	 * Drop IP's reference on the conn. This is the last reference
4093 	 * on the connp if the state was less than established. If the
4094 	 * connection has gone into timewait state, then we will have
4095 	 * one ref for the TCP and one more ref (total of two) for the
4096 	 * classifier connected hash list (a timewait connections stays
4097 	 * in connected hash till closed).
4098 	 *
4099 	 * We can't assert the references because there might be other
4100 	 * transient reference places because of some walkers or queued
4101 	 * packets in squeue for the timewait state.
4102 	 */
4103 	CONN_DEC_REF(connp);
4104 	q->q_ptr = WR(q)->q_ptr = NULL;
4105 	return (0);
4106 }
4107 
4108 static int
4109 tcpclose_accept(queue_t *q)
4110 {
4111 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4112 
4113 	/*
4114 	 * We had opened an acceptor STREAM for sockfs which is
4115 	 * now being closed due to some error.
4116 	 */
4117 	qprocsoff(q);
4118 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4119 	q->q_ptr = WR(q)->q_ptr = NULL;
4120 	return (0);
4121 }
4122 
4123 /*
4124  * Called by tcp_close() routine via squeue when lingering is
4125  * interrupted by a signal.
4126  */
4127 
4128 /* ARGSUSED */
4129 static void
4130 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4131 {
4132 	conn_t	*connp = (conn_t *)arg;
4133 	tcp_t	*tcp = connp->conn_tcp;
4134 
4135 	freeb(mp);
4136 	if (tcp->tcp_linger_tid != 0 &&
4137 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4138 		tcp_stop_lingering(tcp);
4139 		tcp->tcp_client_errno = EINTR;
4140 	}
4141 }
4142 
4143 /*
4144  * Called by streams close routine via squeues when our client blows off her
4145  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4146  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4147  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4148  * acked.
4149  *
4150  * NOTE: tcp_close potentially returns error when lingering.
4151  * However, the stream head currently does not pass these errors
4152  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4153  * errors to the application (from tsleep()) and not errors
4154  * like ECONNRESET caused by receiving a reset packet.
4155  */
4156 
4157 /* ARGSUSED */
4158 static void
4159 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4160 {
4161 	char	*msg;
4162 	conn_t	*connp = (conn_t *)arg;
4163 	tcp_t	*tcp = connp->conn_tcp;
4164 	clock_t	delta = 0;
4165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4166 
4167 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4168 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4169 
4170 	/* Cancel any pending timeout */
4171 	if (tcp->tcp_ordrelid != 0) {
4172 		if (tcp->tcp_timeout) {
4173 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4174 		}
4175 		tcp->tcp_ordrelid = 0;
4176 		tcp->tcp_timeout = B_FALSE;
4177 	}
4178 
4179 	mutex_enter(&tcp->tcp_eager_lock);
4180 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4181 		/* Cleanup for listener */
4182 		tcp_eager_cleanup(tcp, 0);
4183 		tcp->tcp_wait_for_eagers = 1;
4184 	}
4185 	mutex_exit(&tcp->tcp_eager_lock);
4186 
4187 	connp->conn_mdt_ok = B_FALSE;
4188 	tcp->tcp_mdt = B_FALSE;
4189 
4190 	connp->conn_lso_ok = B_FALSE;
4191 	tcp->tcp_lso = B_FALSE;
4192 
4193 	msg = NULL;
4194 	switch (tcp->tcp_state) {
4195 	case TCPS_CLOSED:
4196 	case TCPS_IDLE:
4197 	case TCPS_BOUND:
4198 	case TCPS_LISTEN:
4199 		break;
4200 	case TCPS_SYN_SENT:
4201 		msg = "tcp_close, during connect";
4202 		break;
4203 	case TCPS_SYN_RCVD:
4204 		/*
4205 		 * Close during the connect 3-way handshake
4206 		 * but here there may or may not be pending data
4207 		 * already on queue. Process almost same as in
4208 		 * the ESTABLISHED state.
4209 		 */
4210 		/* FALLTHRU */
4211 	default:
4212 		if (tcp->tcp_fused)
4213 			tcp_unfuse(tcp);
4214 
4215 		/*
4216 		 * If SO_LINGER has set a zero linger time, abort the
4217 		 * connection with a reset.
4218 		 */
4219 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4220 			msg = "tcp_close, zero lingertime";
4221 			break;
4222 		}
4223 
4224 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4225 		/*
4226 		 * Abort connection if there is unread data queued.
4227 		 */
4228 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4229 			msg = "tcp_close, unread data";
4230 			break;
4231 		}
4232 		/*
4233 		 * tcp_hard_bound is now cleared thus all packets go through
4234 		 * tcp_lookup. This fact is used by tcp_detach below.
4235 		 *
4236 		 * We have done a qwait() above which could have possibly
4237 		 * drained more messages in turn causing transition to a
4238 		 * different state. Check whether we have to do the rest
4239 		 * of the processing or not.
4240 		 */
4241 		if (tcp->tcp_state <= TCPS_LISTEN)
4242 			break;
4243 
4244 		/*
4245 		 * Transmit the FIN before detaching the tcp_t.
4246 		 * After tcp_detach returns this queue/perimeter
4247 		 * no longer owns the tcp_t thus others can modify it.
4248 		 */
4249 		(void) tcp_xmit_end(tcp);
4250 
4251 		/*
4252 		 * If lingering on close then wait until the fin is acked,
4253 		 * the SO_LINGER time passes, or a reset is sent/received.
4254 		 */
4255 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4256 		    !(tcp->tcp_fin_acked) &&
4257 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4258 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4259 				tcp->tcp_client_errno = EWOULDBLOCK;
4260 			} else if (tcp->tcp_client_errno == 0) {
4261 
4262 				ASSERT(tcp->tcp_linger_tid == 0);
4263 
4264 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4265 				    tcp_close_linger_timeout,
4266 				    tcp->tcp_lingertime * hz);
4267 
4268 				/* tcp_close_linger_timeout will finish close */
4269 				if (tcp->tcp_linger_tid == 0)
4270 					tcp->tcp_client_errno = ENOSR;
4271 				else
4272 					return;
4273 			}
4274 
4275 			/*
4276 			 * Check if we need to detach or just close
4277 			 * the instance.
4278 			 */
4279 			if (tcp->tcp_state <= TCPS_LISTEN)
4280 				break;
4281 		}
4282 
4283 		/*
4284 		 * Make sure that no other thread will access the tcp_rq of
4285 		 * this instance (through lookups etc.) as tcp_rq will go
4286 		 * away shortly.
4287 		 */
4288 		tcp_acceptor_hash_remove(tcp);
4289 
4290 		mutex_enter(&tcp->tcp_non_sq_lock);
4291 		if (tcp->tcp_flow_stopped) {
4292 			tcp_clrqfull(tcp);
4293 		}
4294 		mutex_exit(&tcp->tcp_non_sq_lock);
4295 
4296 		if (tcp->tcp_timer_tid != 0) {
4297 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4298 			tcp->tcp_timer_tid = 0;
4299 		}
4300 		/*
4301 		 * Need to cancel those timers which will not be used when
4302 		 * TCP is detached.  This has to be done before the tcp_wq
4303 		 * is set to the global queue.
4304 		 */
4305 		tcp_timers_stop(tcp);
4306 
4307 		tcp->tcp_detached = B_TRUE;
4308 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4309 			tcp_time_wait_append(tcp);
4310 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4311 			ASSERT(connp->conn_ref >= 3);
4312 			goto finish;
4313 		}
4314 
4315 		/*
4316 		 * If delta is zero the timer event wasn't executed and was
4317 		 * successfully canceled. In this case we need to restart it
4318 		 * with the minimal delta possible.
4319 		 */
4320 		if (delta >= 0)
4321 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4322 			    delta ? delta : 1);
4323 
4324 		ASSERT(connp->conn_ref >= 3);
4325 		goto finish;
4326 	}
4327 
4328 	/* Detach did not complete. Still need to remove q from stream. */
4329 	if (msg) {
4330 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4331 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4332 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4333 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4334 		    tcp->tcp_state == TCPS_SYN_RCVD)
4335 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4336 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4337 	}
4338 
4339 	tcp_closei_local(tcp);
4340 	CONN_DEC_REF(connp);
4341 	ASSERT(connp->conn_ref >= 2);
4342 
4343 finish:
4344 	/*
4345 	 * Although packets are always processed on the correct
4346 	 * tcp's perimeter and access is serialized via squeue's,
4347 	 * IP still needs a queue when sending packets in time_wait
4348 	 * state so use WR(tcps_g_q) till ip_output() can be
4349 	 * changed to deal with just connp. For read side, we
4350 	 * could have set tcp_rq to NULL but there are some cases
4351 	 * in tcp_rput_data() from early days of this code which
4352 	 * do a putnext without checking if tcp is closed. Those
4353 	 * need to be identified before both tcp_rq and tcp_wq
4354 	 * can be set to NULL and tcps_g_q can disappear forever.
4355 	 */
4356 	mutex_enter(&tcp->tcp_closelock);
4357 	/*
4358 	 * Don't change the queues in the case of a listener that has
4359 	 * eagers in its q or q0. It could surprise the eagers.
4360 	 * Instead wait for the eagers outside the squeue.
4361 	 */
4362 	if (!tcp->tcp_wait_for_eagers) {
4363 		tcp->tcp_detached = B_TRUE;
4364 		/*
4365 		 * When default queue is closing we set tcps_g_q to NULL
4366 		 * after the close is done.
4367 		 */
4368 		ASSERT(tcps->tcps_g_q != NULL);
4369 		tcp->tcp_rq = tcps->tcps_g_q;
4370 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4371 	}
4372 
4373 	/* Signal tcp_close() to finish closing. */
4374 	tcp->tcp_closed = 1;
4375 	cv_signal(&tcp->tcp_closecv);
4376 	mutex_exit(&tcp->tcp_closelock);
4377 }
4378 
4379 
4380 /*
4381  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4382  * Some stream heads get upset if they see these later on as anything but NULL.
4383  */
4384 static void
4385 tcp_close_mpp(mblk_t **mpp)
4386 {
4387 	mblk_t	*mp;
4388 
4389 	if ((mp = *mpp) != NULL) {
4390 		do {
4391 			mp->b_next = NULL;
4392 			mp->b_prev = NULL;
4393 		} while ((mp = mp->b_cont) != NULL);
4394 
4395 		mp = *mpp;
4396 		*mpp = NULL;
4397 		freemsg(mp);
4398 	}
4399 }
4400 
4401 /* Do detached close. */
4402 static void
4403 tcp_close_detached(tcp_t *tcp)
4404 {
4405 	if (tcp->tcp_fused)
4406 		tcp_unfuse(tcp);
4407 
4408 	/*
4409 	 * Clustering code serializes TCP disconnect callbacks and
4410 	 * cluster tcp list walks by blocking a TCP disconnect callback
4411 	 * if a cluster tcp list walk is in progress. This ensures
4412 	 * accurate accounting of TCPs in the cluster code even though
4413 	 * the TCP list walk itself is not atomic.
4414 	 */
4415 	tcp_closei_local(tcp);
4416 	CONN_DEC_REF(tcp->tcp_connp);
4417 }
4418 
4419 /*
4420  * Stop all TCP timers, and free the timer mblks if requested.
4421  */
4422 void
4423 tcp_timers_stop(tcp_t *tcp)
4424 {
4425 	if (tcp->tcp_timer_tid != 0) {
4426 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4427 		tcp->tcp_timer_tid = 0;
4428 	}
4429 	if (tcp->tcp_ka_tid != 0) {
4430 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4431 		tcp->tcp_ka_tid = 0;
4432 	}
4433 	if (tcp->tcp_ack_tid != 0) {
4434 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4435 		tcp->tcp_ack_tid = 0;
4436 	}
4437 	if (tcp->tcp_push_tid != 0) {
4438 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4439 		tcp->tcp_push_tid = 0;
4440 	}
4441 }
4442 
4443 /*
4444  * The tcp_t is going away. Remove it from all lists and set it
4445  * to TCPS_CLOSED. The freeing up of memory is deferred until
4446  * tcp_inactive. This is needed since a thread in tcp_rput might have
4447  * done a CONN_INC_REF on this structure before it was removed from the
4448  * hashes.
4449  */
4450 static void
4451 tcp_closei_local(tcp_t *tcp)
4452 {
4453 	ire_t 	*ire;
4454 	conn_t	*connp = tcp->tcp_connp;
4455 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4456 
4457 	if (!TCP_IS_SOCKET(tcp))
4458 		tcp_acceptor_hash_remove(tcp);
4459 
4460 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4461 	tcp->tcp_ibsegs = 0;
4462 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4463 	tcp->tcp_obsegs = 0;
4464 
4465 	/*
4466 	 * If we are an eager connection hanging off a listener that
4467 	 * hasn't formally accepted the connection yet, get off his
4468 	 * list and blow off any data that we have accumulated.
4469 	 */
4470 	if (tcp->tcp_listener != NULL) {
4471 		tcp_t	*listener = tcp->tcp_listener;
4472 		mutex_enter(&listener->tcp_eager_lock);
4473 		/*
4474 		 * tcp_tconnind_started == B_TRUE means that the
4475 		 * conn_ind has already gone to listener. At
4476 		 * this point, eager will be closed but we
4477 		 * leave it in listeners eager list so that
4478 		 * if listener decides to close without doing
4479 		 * accept, we can clean this up. In tcp_wput_accept
4480 		 * we take care of the case of accept on closed
4481 		 * eager.
4482 		 */
4483 		if (!tcp->tcp_tconnind_started) {
4484 			tcp_eager_unlink(tcp);
4485 			mutex_exit(&listener->tcp_eager_lock);
4486 			/*
4487 			 * We don't want to have any pointers to the
4488 			 * listener queue, after we have released our
4489 			 * reference on the listener
4490 			 */
4491 			ASSERT(tcps->tcps_g_q != NULL);
4492 			tcp->tcp_rq = tcps->tcps_g_q;
4493 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4494 			CONN_DEC_REF(listener->tcp_connp);
4495 		} else {
4496 			mutex_exit(&listener->tcp_eager_lock);
4497 		}
4498 	}
4499 
4500 	/* Stop all the timers */
4501 	tcp_timers_stop(tcp);
4502 
4503 	if (tcp->tcp_state == TCPS_LISTEN) {
4504 		if (tcp->tcp_ip_addr_cache) {
4505 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4506 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4507 			tcp->tcp_ip_addr_cache = NULL;
4508 		}
4509 	}
4510 	mutex_enter(&tcp->tcp_non_sq_lock);
4511 	if (tcp->tcp_flow_stopped)
4512 		tcp_clrqfull(tcp);
4513 	mutex_exit(&tcp->tcp_non_sq_lock);
4514 
4515 	tcp_bind_hash_remove(tcp);
4516 	/*
4517 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4518 	 * is trying to remove this tcp from the time wait list, we will
4519 	 * block in tcp_time_wait_remove while trying to acquire the
4520 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4521 	 * requires the ipcl_hash_remove to be ordered after the
4522 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4523 	 */
4524 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4525 		(void) tcp_time_wait_remove(tcp, NULL);
4526 	CL_INET_DISCONNECT(tcp);
4527 	ipcl_hash_remove(connp);
4528 
4529 	/*
4530 	 * Delete the cached ire in conn_ire_cache and also mark
4531 	 * the conn as CONDEMNED
4532 	 */
4533 	mutex_enter(&connp->conn_lock);
4534 	connp->conn_state_flags |= CONN_CONDEMNED;
4535 	ire = connp->conn_ire_cache;
4536 	connp->conn_ire_cache = NULL;
4537 	mutex_exit(&connp->conn_lock);
4538 	if (ire != NULL)
4539 		IRE_REFRELE_NOTR(ire);
4540 
4541 	/* Need to cleanup any pending ioctls */
4542 	ASSERT(tcp->tcp_time_wait_next == NULL);
4543 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4544 	ASSERT(tcp->tcp_time_wait_expire == 0);
4545 	tcp->tcp_state = TCPS_CLOSED;
4546 
4547 	/* Release any SSL context */
4548 	if (tcp->tcp_kssl_ent != NULL) {
4549 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4550 		tcp->tcp_kssl_ent = NULL;
4551 	}
4552 	if (tcp->tcp_kssl_ctx != NULL) {
4553 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4554 		tcp->tcp_kssl_ctx = NULL;
4555 	}
4556 	tcp->tcp_kssl_pending = B_FALSE;
4557 
4558 	tcp_ipsec_cleanup(tcp);
4559 }
4560 
4561 /*
4562  * tcp is dying (called from ipcl_conn_destroy and error cases).
4563  * Free the tcp_t in either case.
4564  */
4565 void
4566 tcp_free(tcp_t *tcp)
4567 {
4568 	mblk_t	*mp;
4569 	ip6_pkt_t	*ipp;
4570 
4571 	ASSERT(tcp != NULL);
4572 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4573 
4574 	tcp->tcp_rq = NULL;
4575 	tcp->tcp_wq = NULL;
4576 
4577 	tcp_close_mpp(&tcp->tcp_xmit_head);
4578 	tcp_close_mpp(&tcp->tcp_reass_head);
4579 	if (tcp->tcp_rcv_list != NULL) {
4580 		/* Free b_next chain */
4581 		tcp_close_mpp(&tcp->tcp_rcv_list);
4582 	}
4583 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4584 		freemsg(mp);
4585 	}
4586 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4587 		freemsg(mp);
4588 	}
4589 
4590 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4591 		freeb(tcp->tcp_fused_sigurg_mp);
4592 		tcp->tcp_fused_sigurg_mp = NULL;
4593 	}
4594 
4595 	if (tcp->tcp_sack_info != NULL) {
4596 		if (tcp->tcp_notsack_list != NULL) {
4597 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4598 		}
4599 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4600 	}
4601 
4602 	if (tcp->tcp_hopopts != NULL) {
4603 		mi_free(tcp->tcp_hopopts);
4604 		tcp->tcp_hopopts = NULL;
4605 		tcp->tcp_hopoptslen = 0;
4606 	}
4607 	ASSERT(tcp->tcp_hopoptslen == 0);
4608 	if (tcp->tcp_dstopts != NULL) {
4609 		mi_free(tcp->tcp_dstopts);
4610 		tcp->tcp_dstopts = NULL;
4611 		tcp->tcp_dstoptslen = 0;
4612 	}
4613 	ASSERT(tcp->tcp_dstoptslen == 0);
4614 	if (tcp->tcp_rtdstopts != NULL) {
4615 		mi_free(tcp->tcp_rtdstopts);
4616 		tcp->tcp_rtdstopts = NULL;
4617 		tcp->tcp_rtdstoptslen = 0;
4618 	}
4619 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4620 	if (tcp->tcp_rthdr != NULL) {
4621 		mi_free(tcp->tcp_rthdr);
4622 		tcp->tcp_rthdr = NULL;
4623 		tcp->tcp_rthdrlen = 0;
4624 	}
4625 	ASSERT(tcp->tcp_rthdrlen == 0);
4626 
4627 	ipp = &tcp->tcp_sticky_ipp;
4628 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4629 	    IPPF_RTHDR))
4630 		ip6_pkt_free(ipp);
4631 
4632 	/*
4633 	 * Free memory associated with the tcp/ip header template.
4634 	 */
4635 
4636 	if (tcp->tcp_iphc != NULL)
4637 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4638 
4639 	/*
4640 	 * Following is really a blowing away a union.
4641 	 * It happens to have exactly two members of identical size
4642 	 * the following code is enough.
4643 	 */
4644 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4645 
4646 	if (tcp->tcp_tracebuf != NULL) {
4647 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4648 		tcp->tcp_tracebuf = NULL;
4649 	}
4650 }
4651 
4652 
4653 /*
4654  * Put a connection confirmation message upstream built from the
4655  * address information within 'iph' and 'tcph'.  Report our success or failure.
4656  */
4657 static boolean_t
4658 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4659     mblk_t **defermp)
4660 {
4661 	sin_t	sin;
4662 	sin6_t	sin6;
4663 	mblk_t	*mp;
4664 	char	*optp = NULL;
4665 	int	optlen = 0;
4666 	cred_t	*cr;
4667 
4668 	if (defermp != NULL)
4669 		*defermp = NULL;
4670 
4671 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4672 		/*
4673 		 * Return in T_CONN_CON results of option negotiation through
4674 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4675 		 * negotiation, then what is received from remote end needs
4676 		 * to be taken into account but there is no such thing (yet?)
4677 		 * in our TCP/IP.
4678 		 * Note: We do not use mi_offset_param() here as
4679 		 * tcp_opts_conn_req contents do not directly come from
4680 		 * an application and are either generated in kernel or
4681 		 * from user input that was already verified.
4682 		 */
4683 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4684 		optp = (char *)(mp->b_rptr +
4685 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4686 		optlen = (int)
4687 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4688 	}
4689 
4690 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4691 		ipha_t *ipha = (ipha_t *)iphdr;
4692 
4693 		/* packet is IPv4 */
4694 		if (tcp->tcp_family == AF_INET) {
4695 			sin = sin_null;
4696 			sin.sin_addr.s_addr = ipha->ipha_src;
4697 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4698 			sin.sin_family = AF_INET;
4699 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4700 			    (int)sizeof (sin_t), optp, optlen);
4701 		} else {
4702 			sin6 = sin6_null;
4703 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4704 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4705 			sin6.sin6_family = AF_INET6;
4706 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4707 			    (int)sizeof (sin6_t), optp, optlen);
4708 
4709 		}
4710 	} else {
4711 		ip6_t	*ip6h = (ip6_t *)iphdr;
4712 
4713 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4714 		ASSERT(tcp->tcp_family == AF_INET6);
4715 		sin6 = sin6_null;
4716 		sin6.sin6_addr = ip6h->ip6_src;
4717 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4718 		sin6.sin6_family = AF_INET6;
4719 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4720 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4721 		    (int)sizeof (sin6_t), optp, optlen);
4722 	}
4723 
4724 	if (!mp)
4725 		return (B_FALSE);
4726 
4727 	if ((cr = DB_CRED(idmp)) != NULL) {
4728 		mblk_setcred(mp, cr);
4729 		DB_CPID(mp) = DB_CPID(idmp);
4730 	}
4731 
4732 	if (defermp == NULL)
4733 		putnext(tcp->tcp_rq, mp);
4734 	else
4735 		*defermp = mp;
4736 
4737 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4738 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4739 	return (B_TRUE);
4740 }
4741 
4742 /*
4743  * Defense for the SYN attack -
4744  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4745  *    one from the list of droppable eagers. This list is a subset of q0.
4746  *    see comments before the definition of MAKE_DROPPABLE().
4747  * 2. Don't drop a SYN request before its first timeout. This gives every
4748  *    request at least til the first timeout to complete its 3-way handshake.
4749  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4750  *    requests currently on the queue that has timed out. This will be used
4751  *    as an indicator of whether an attack is under way, so that appropriate
4752  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4753  *    either when eager goes into ESTABLISHED, or gets freed up.)
4754  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4755  *    # of timeout drops back to <= q0len/32 => SYN alert off
4756  */
4757 static boolean_t
4758 tcp_drop_q0(tcp_t *tcp)
4759 {
4760 	tcp_t	*eager;
4761 	mblk_t	*mp;
4762 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4763 
4764 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4765 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4766 
4767 	/* Pick oldest eager from the list of droppable eagers */
4768 	eager = tcp->tcp_eager_prev_drop_q0;
4769 
4770 	/* If list is empty. return B_FALSE */
4771 	if (eager == tcp) {
4772 		return (B_FALSE);
4773 	}
4774 
4775 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4776 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4777 		return (B_FALSE);
4778 
4779 	/*
4780 	 * Take this eager out from the list of droppable eagers since we are
4781 	 * going to drop it.
4782 	 */
4783 	MAKE_UNDROPPABLE(eager);
4784 
4785 	if (tcp->tcp_debug) {
4786 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4787 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4788 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4789 		    tcp->tcp_conn_req_cnt_q0,
4790 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4791 	}
4792 
4793 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4794 
4795 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4796 	CONN_INC_REF(eager->tcp_connp);
4797 
4798 	/* Mark the IRE created for this SYN request temporary */
4799 	tcp_ip_ire_mark_advice(eager);
4800 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4801 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4802 
4803 	return (B_TRUE);
4804 }
4805 
4806 int
4807 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4808     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4809 {
4810 	tcp_t 		*ltcp = lconnp->conn_tcp;
4811 	tcp_t		*tcp = connp->conn_tcp;
4812 	mblk_t		*tpi_mp;
4813 	ipha_t		*ipha;
4814 	ip6_t		*ip6h;
4815 	sin6_t 		sin6;
4816 	in6_addr_t 	v6dst;
4817 	int		err;
4818 	int		ifindex = 0;
4819 	cred_t		*cr;
4820 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4821 
4822 	if (ipvers == IPV4_VERSION) {
4823 		ipha = (ipha_t *)mp->b_rptr;
4824 
4825 		connp->conn_send = ip_output;
4826 		connp->conn_recv = tcp_input;
4827 
4828 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4829 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4830 
4831 		sin6 = sin6_null;
4832 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4833 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4834 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4835 		sin6.sin6_family = AF_INET6;
4836 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4837 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4838 		if (tcp->tcp_recvdstaddr) {
4839 			sin6_t	sin6d;
4840 
4841 			sin6d = sin6_null;
4842 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4843 			    &sin6d.sin6_addr);
4844 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4845 			sin6d.sin6_family = AF_INET;
4846 			tpi_mp = mi_tpi_extconn_ind(NULL,
4847 			    (char *)&sin6d, sizeof (sin6_t),
4848 			    (char *)&tcp,
4849 			    (t_scalar_t)sizeof (intptr_t),
4850 			    (char *)&sin6d, sizeof (sin6_t),
4851 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4852 		} else {
4853 			tpi_mp = mi_tpi_conn_ind(NULL,
4854 			    (char *)&sin6, sizeof (sin6_t),
4855 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4856 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4857 		}
4858 	} else {
4859 		ip6h = (ip6_t *)mp->b_rptr;
4860 
4861 		connp->conn_send = ip_output_v6;
4862 		connp->conn_recv = tcp_input;
4863 
4864 		connp->conn_srcv6 = ip6h->ip6_dst;
4865 		connp->conn_remv6 = ip6h->ip6_src;
4866 
4867 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4868 		ifindex = (int)DB_CKSUMSTUFF(mp);
4869 		DB_CKSUMSTUFF(mp) = 0;
4870 
4871 		sin6 = sin6_null;
4872 		sin6.sin6_addr = ip6h->ip6_src;
4873 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4874 		sin6.sin6_family = AF_INET6;
4875 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4876 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4877 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4878 
4879 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4880 			/* Pass up the scope_id of remote addr */
4881 			sin6.sin6_scope_id = ifindex;
4882 		} else {
4883 			sin6.sin6_scope_id = 0;
4884 		}
4885 		if (tcp->tcp_recvdstaddr) {
4886 			sin6_t	sin6d;
4887 
4888 			sin6d = sin6_null;
4889 			sin6.sin6_addr = ip6h->ip6_dst;
4890 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4891 			sin6d.sin6_family = AF_INET;
4892 			tpi_mp = mi_tpi_extconn_ind(NULL,
4893 			    (char *)&sin6d, sizeof (sin6_t),
4894 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4895 			    (char *)&sin6d, sizeof (sin6_t),
4896 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4897 		} else {
4898 			tpi_mp = mi_tpi_conn_ind(NULL,
4899 			    (char *)&sin6, sizeof (sin6_t),
4900 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4901 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4902 		}
4903 	}
4904 
4905 	if (tpi_mp == NULL)
4906 		return (ENOMEM);
4907 
4908 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4909 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4910 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4911 	connp->conn_fully_bound = B_FALSE;
4912 
4913 	if (tcps->tcps_trace)
4914 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4915 
4916 	/* Inherit information from the "parent" */
4917 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4918 	tcp->tcp_family = ltcp->tcp_family;
4919 	tcp->tcp_wq = ltcp->tcp_wq;
4920 	tcp->tcp_rq = ltcp->tcp_rq;
4921 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4922 	tcp->tcp_detached = B_TRUE;
4923 	if ((err = tcp_init_values(tcp)) != 0) {
4924 		freemsg(tpi_mp);
4925 		return (err);
4926 	}
4927 
4928 	if (ipvers == IPV4_VERSION) {
4929 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4930 			freemsg(tpi_mp);
4931 			return (err);
4932 		}
4933 		ASSERT(tcp->tcp_ipha != NULL);
4934 	} else {
4935 		/* ifindex must be already set */
4936 		ASSERT(ifindex != 0);
4937 
4938 		if (ltcp->tcp_bound_if != 0) {
4939 			/*
4940 			 * Set newtcp's bound_if equal to
4941 			 * listener's value. If ifindex is
4942 			 * not the same as ltcp->tcp_bound_if,
4943 			 * it must be a packet for the ipmp group
4944 			 * of interfaces
4945 			 */
4946 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4947 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4948 			tcp->tcp_bound_if = ifindex;
4949 		}
4950 
4951 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4952 		tcp->tcp_recvifindex = 0;
4953 		tcp->tcp_recvhops = 0xffffffffU;
4954 		ASSERT(tcp->tcp_ip6h != NULL);
4955 	}
4956 
4957 	tcp->tcp_lport = ltcp->tcp_lport;
4958 
4959 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4960 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4961 			/*
4962 			 * Listener had options of some sort; eager inherits.
4963 			 * Free up the eager template and allocate one
4964 			 * of the right size.
4965 			 */
4966 			if (tcp->tcp_hdr_grown) {
4967 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4968 			} else {
4969 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4970 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4971 			}
4972 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4973 			    KM_NOSLEEP);
4974 			if (tcp->tcp_iphc == NULL) {
4975 				tcp->tcp_iphc_len = 0;
4976 				freemsg(tpi_mp);
4977 				return (ENOMEM);
4978 			}
4979 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4980 			tcp->tcp_hdr_grown = B_TRUE;
4981 		}
4982 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4983 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4984 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4985 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4986 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4987 
4988 		/*
4989 		 * Copy the IP+TCP header template from listener to eager
4990 		 */
4991 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4992 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4993 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4994 			    IPPROTO_RAW) {
4995 				tcp->tcp_ip6h =
4996 				    (ip6_t *)(tcp->tcp_iphc +
4997 					sizeof (ip6i_t));
4998 			} else {
4999 				tcp->tcp_ip6h =
5000 				    (ip6_t *)(tcp->tcp_iphc);
5001 			}
5002 			tcp->tcp_ipha = NULL;
5003 		} else {
5004 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5005 			tcp->tcp_ip6h = NULL;
5006 		}
5007 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5008 		    tcp->tcp_ip_hdr_len);
5009 	} else {
5010 		/*
5011 		 * only valid case when ipversion of listener and
5012 		 * eager differ is when listener is IPv6 and
5013 		 * eager is IPv4.
5014 		 * Eager header template has been initialized to the
5015 		 * maximum v4 header sizes, which includes space for
5016 		 * TCP and IP options.
5017 		 */
5018 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5019 		    (tcp->tcp_ipversion == IPV4_VERSION));
5020 		ASSERT(tcp->tcp_iphc_len >=
5021 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5022 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5023 		/* copy IP header fields individually */
5024 		tcp->tcp_ipha->ipha_ttl =
5025 		    ltcp->tcp_ip6h->ip6_hops;
5026 		bcopy(ltcp->tcp_tcph->th_lport,
5027 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5028 	}
5029 
5030 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5031 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5032 	    sizeof (in_port_t));
5033 
5034 	if (ltcp->tcp_lport == 0) {
5035 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5036 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5037 		    sizeof (in_port_t));
5038 	}
5039 
5040 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5041 		ASSERT(ipha != NULL);
5042 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5043 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5044 
5045 		/* Source routing option copyover (reverse it) */
5046 		if (tcps->tcps_rev_src_routes)
5047 			tcp_opt_reverse(tcp, ipha);
5048 	} else {
5049 		ASSERT(ip6h != NULL);
5050 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5051 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5052 	}
5053 
5054 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5055 	ASSERT(!tcp->tcp_tconnind_started);
5056 	/*
5057 	 * If the SYN contains a credential, it's a loopback packet; attach
5058 	 * the credential to the TPI message.
5059 	 */
5060 	if ((cr = DB_CRED(idmp)) != NULL) {
5061 		mblk_setcred(tpi_mp, cr);
5062 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5063 	}
5064 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5065 
5066 	/* Inherit the listener's SSL protection state */
5067 
5068 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5069 		kssl_hold_ent(tcp->tcp_kssl_ent);
5070 		tcp->tcp_kssl_pending = B_TRUE;
5071 	}
5072 
5073 	return (0);
5074 }
5075 
5076 
5077 int
5078 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5079     tcph_t *tcph, mblk_t *idmp)
5080 {
5081 	tcp_t 		*ltcp = lconnp->conn_tcp;
5082 	tcp_t		*tcp = connp->conn_tcp;
5083 	sin_t		sin;
5084 	mblk_t		*tpi_mp = NULL;
5085 	int		err;
5086 	cred_t		*cr;
5087 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5088 
5089 	sin = sin_null;
5090 	sin.sin_addr.s_addr = ipha->ipha_src;
5091 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5092 	sin.sin_family = AF_INET;
5093 	if (ltcp->tcp_recvdstaddr) {
5094 		sin_t	sind;
5095 
5096 		sind = sin_null;
5097 		sind.sin_addr.s_addr = ipha->ipha_dst;
5098 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5099 		sind.sin_family = AF_INET;
5100 		tpi_mp = mi_tpi_extconn_ind(NULL,
5101 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5102 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5103 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5104 	} else {
5105 		tpi_mp = mi_tpi_conn_ind(NULL,
5106 		    (char *)&sin, sizeof (sin_t),
5107 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5108 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5109 	}
5110 
5111 	if (tpi_mp == NULL) {
5112 		return (ENOMEM);
5113 	}
5114 
5115 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5116 	connp->conn_send = ip_output;
5117 	connp->conn_recv = tcp_input;
5118 	connp->conn_fully_bound = B_FALSE;
5119 
5120 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5121 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5122 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5123 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5124 
5125 	if (tcps->tcps_trace) {
5126 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5127 	}
5128 
5129 	/* Inherit information from the "parent" */
5130 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5131 	tcp->tcp_family = ltcp->tcp_family;
5132 	tcp->tcp_wq = ltcp->tcp_wq;
5133 	tcp->tcp_rq = ltcp->tcp_rq;
5134 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5135 	tcp->tcp_detached = B_TRUE;
5136 	if ((err = tcp_init_values(tcp)) != 0) {
5137 		freemsg(tpi_mp);
5138 		return (err);
5139 	}
5140 
5141 	/*
5142 	 * Let's make sure that eager tcp template has enough space to
5143 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5144 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5145 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5146 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5147 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5148 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5149 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5150 	 */
5151 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5152 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5153 
5154 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5155 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5156 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5157 	tcp->tcp_ttl = ltcp->tcp_ttl;
5158 	tcp->tcp_tos = ltcp->tcp_tos;
5159 
5160 	/* Copy the IP+TCP header template from listener to eager */
5161 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5162 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5163 	tcp->tcp_ip6h = NULL;
5164 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5165 	    tcp->tcp_ip_hdr_len);
5166 
5167 	/* Initialize the IP addresses and Ports */
5168 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5169 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5170 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5171 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5172 
5173 	/* Source routing option copyover (reverse it) */
5174 	if (tcps->tcps_rev_src_routes)
5175 		tcp_opt_reverse(tcp, ipha);
5176 
5177 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5178 	ASSERT(!tcp->tcp_tconnind_started);
5179 
5180 	/*
5181 	 * If the SYN contains a credential, it's a loopback packet; attach
5182 	 * the credential to the TPI message.
5183 	 */
5184 	if ((cr = DB_CRED(idmp)) != NULL) {
5185 		mblk_setcred(tpi_mp, cr);
5186 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5187 	}
5188 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5189 
5190 	/* Inherit the listener's SSL protection state */
5191 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5192 		kssl_hold_ent(tcp->tcp_kssl_ent);
5193 		tcp->tcp_kssl_pending = B_TRUE;
5194 	}
5195 
5196 	return (0);
5197 }
5198 
5199 /*
5200  * sets up conn for ipsec.
5201  * if the first mblk is M_CTL it is consumed and mpp is updated.
5202  * in case of error mpp is freed.
5203  */
5204 conn_t *
5205 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5206 {
5207 	conn_t 		*connp = tcp->tcp_connp;
5208 	conn_t 		*econnp;
5209 	squeue_t 	*new_sqp;
5210 	mblk_t 		*first_mp = *mpp;
5211 	mblk_t		*mp = *mpp;
5212 	boolean_t	mctl_present = B_FALSE;
5213 	uint_t		ipvers;
5214 
5215 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5216 	if (econnp == NULL) {
5217 		freemsg(first_mp);
5218 		return (NULL);
5219 	}
5220 	if (DB_TYPE(mp) == M_CTL) {
5221 		if (mp->b_cont == NULL ||
5222 		    mp->b_cont->b_datap->db_type != M_DATA) {
5223 			freemsg(first_mp);
5224 			return (NULL);
5225 		}
5226 		mp = mp->b_cont;
5227 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5228 			freemsg(first_mp);
5229 			return (NULL);
5230 		}
5231 
5232 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5233 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5234 		mctl_present = B_TRUE;
5235 	} else {
5236 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5237 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5238 	}
5239 
5240 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5241 	DB_CKSUMSTART(mp) = 0;
5242 
5243 	ASSERT(OK_32PTR(mp->b_rptr));
5244 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5245 	if (ipvers == IPV4_VERSION) {
5246 		uint16_t  	*up;
5247 		uint32_t	ports;
5248 		ipha_t		*ipha;
5249 
5250 		ipha = (ipha_t *)mp->b_rptr;
5251 		up = (uint16_t *)((uchar_t *)ipha +
5252 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5253 		ports = *(uint32_t *)up;
5254 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5255 		    ipha->ipha_dst, ipha->ipha_src, ports);
5256 	} else {
5257 		uint16_t  	*up;
5258 		uint32_t	ports;
5259 		uint16_t	ip_hdr_len;
5260 		uint8_t		*nexthdrp;
5261 		ip6_t 		*ip6h;
5262 		tcph_t		*tcph;
5263 
5264 		ip6h = (ip6_t *)mp->b_rptr;
5265 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5266 			ip_hdr_len = IPV6_HDR_LEN;
5267 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5268 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5269 			CONN_DEC_REF(econnp);
5270 			freemsg(first_mp);
5271 			return (NULL);
5272 		}
5273 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5274 		up = (uint16_t *)tcph->th_lport;
5275 		ports = *(uint32_t *)up;
5276 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5277 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5278 	}
5279 
5280 	/*
5281 	 * The caller already ensured that there is a sqp present.
5282 	 */
5283 	econnp->conn_sqp = new_sqp;
5284 
5285 	if (connp->conn_policy != NULL) {
5286 		ipsec_in_t *ii;
5287 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5288 		ASSERT(ii->ipsec_in_policy == NULL);
5289 		IPPH_REFHOLD(connp->conn_policy);
5290 		ii->ipsec_in_policy = connp->conn_policy;
5291 
5292 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5293 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5294 			CONN_DEC_REF(econnp);
5295 			freemsg(first_mp);
5296 			return (NULL);
5297 		}
5298 	}
5299 
5300 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5301 		CONN_DEC_REF(econnp);
5302 		freemsg(first_mp);
5303 		return (NULL);
5304 	}
5305 
5306 	/*
5307 	 * If we know we have some policy, pass the "IPSEC"
5308 	 * options size TCP uses this adjust the MSS.
5309 	 */
5310 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5311 	if (mctl_present) {
5312 		freeb(first_mp);
5313 		*mpp = mp;
5314 	}
5315 
5316 	return (econnp);
5317 }
5318 
5319 /*
5320  * tcp_get_conn/tcp_free_conn
5321  *
5322  * tcp_get_conn is used to get a clean tcp connection structure.
5323  * It tries to reuse the connections put on the freelist by the
5324  * time_wait_collector failing which it goes to kmem_cache. This
5325  * way has two benefits compared to just allocating from and
5326  * freeing to kmem_cache.
5327  * 1) The time_wait_collector can free (which includes the cleanup)
5328  * outside the squeue. So when the interrupt comes, we have a clean
5329  * connection sitting in the freelist. Obviously, this buys us
5330  * performance.
5331  *
5332  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5333  * has multiple disadvantages - tying up the squeue during alloc, and the
5334  * fact that IPSec policy initialization has to happen here which
5335  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5336  * But allocating the conn/tcp in IP land is also not the best since
5337  * we can't check the 'q' and 'q0' which are protected by squeue and
5338  * blindly allocate memory which might have to be freed here if we are
5339  * not allowed to accept the connection. By using the freelist and
5340  * putting the conn/tcp back in freelist, we don't pay a penalty for
5341  * allocating memory without checking 'q/q0' and freeing it if we can't
5342  * accept the connection.
5343  *
5344  * Care should be taken to put the conn back in the same squeue's freelist
5345  * from which it was allocated. Best results are obtained if conn is
5346  * allocated from listener's squeue and freed to the same. Time wait
5347  * collector will free up the freelist is the connection ends up sitting
5348  * there for too long.
5349  */
5350 void *
5351 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5352 {
5353 	tcp_t			*tcp = NULL;
5354 	conn_t			*connp = NULL;
5355 	squeue_t		*sqp = (squeue_t *)arg;
5356 	tcp_squeue_priv_t 	*tcp_time_wait;
5357 	netstack_t		*ns;
5358 
5359 	tcp_time_wait =
5360 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5361 
5362 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5363 	tcp = tcp_time_wait->tcp_free_list;
5364 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5365 	if (tcp != NULL) {
5366 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5367 		tcp_time_wait->tcp_free_list_cnt--;
5368 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5369 		tcp->tcp_time_wait_next = NULL;
5370 		connp = tcp->tcp_connp;
5371 		connp->conn_flags |= IPCL_REUSED;
5372 
5373 		ASSERT(tcp->tcp_tcps == NULL);
5374 		ASSERT(connp->conn_netstack == NULL);
5375 		ns = tcps->tcps_netstack;
5376 		netstack_hold(ns);
5377 		connp->conn_netstack = ns;
5378 		tcp->tcp_tcps = tcps;
5379 		TCPS_REFHOLD(tcps);
5380 		ipcl_globalhash_insert(connp);
5381 		return ((void *)connp);
5382 	}
5383 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5384 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5385 		    tcps->tcps_netstack)) == NULL)
5386 		return (NULL);
5387 	tcp = connp->conn_tcp;
5388 	tcp->tcp_tcps = tcps;
5389 	TCPS_REFHOLD(tcps);
5390 	return ((void *)connp);
5391 }
5392 
5393 /*
5394  * Update the cached label for the given tcp_t.  This should be called once per
5395  * connection, and before any packets are sent or tcp_process_options is
5396  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5397  */
5398 static boolean_t
5399 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5400 {
5401 	conn_t *connp = tcp->tcp_connp;
5402 
5403 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5404 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5405 		int added;
5406 
5407 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5408 		    connp->conn_mac_exempt,
5409 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5410 			return (B_FALSE);
5411 
5412 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5413 		if (added == -1)
5414 			return (B_FALSE);
5415 		tcp->tcp_hdr_len += added;
5416 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5417 		tcp->tcp_ip_hdr_len += added;
5418 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5419 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5420 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5421 			    tcp->tcp_hdr_len);
5422 			if (added == -1)
5423 				return (B_FALSE);
5424 			tcp->tcp_hdr_len += added;
5425 			tcp->tcp_tcph = (tcph_t *)
5426 			    ((uchar_t *)tcp->tcp_tcph + added);
5427 			tcp->tcp_ip_hdr_len += added;
5428 		}
5429 	} else {
5430 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5431 
5432 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5433 		    connp->conn_mac_exempt,
5434 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5435 			return (B_FALSE);
5436 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5437 		    &tcp->tcp_label_len, optbuf) != 0)
5438 			return (B_FALSE);
5439 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5440 			return (B_FALSE);
5441 	}
5442 
5443 	connp->conn_ulp_labeled = 1;
5444 
5445 	return (B_TRUE);
5446 }
5447 
5448 /* BEGIN CSTYLED */
5449 /*
5450  *
5451  * The sockfs ACCEPT path:
5452  * =======================
5453  *
5454  * The eager is now established in its own perimeter as soon as SYN is
5455  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5456  * completes the accept processing on the acceptor STREAM. The sending
5457  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5458  * listener but a TLI/XTI listener completes the accept processing
5459  * on the listener perimeter.
5460  *
5461  * Common control flow for 3 way handshake:
5462  * ----------------------------------------
5463  *
5464  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5465  *					-> tcp_conn_request()
5466  *
5467  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5468  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5469  *
5470  * Sockfs ACCEPT Path:
5471  * -------------------
5472  *
5473  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5474  * as STREAM entry point)
5475  *
5476  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5477  *
5478  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5479  * association (we are not behind eager's squeue but sockfs is protecting us
5480  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5481  * is changed to point at tcp_wput().
5482  *
5483  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5484  * listener (done on listener's perimeter).
5485  *
5486  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5487  * accept.
5488  *
5489  * TLI/XTI client ACCEPT path:
5490  * ---------------------------
5491  *
5492  * soaccept() sends T_CONN_RES on the listener STREAM.
5493  *
5494  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5495  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5496  *
5497  * Locks:
5498  * ======
5499  *
5500  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5501  * and listeners->tcp_eager_next_q.
5502  *
5503  * Referencing:
5504  * ============
5505  *
5506  * 1) We start out in tcp_conn_request by eager placing a ref on
5507  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5508  *
5509  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5510  * doing so we place a ref on the eager. This ref is finally dropped at the
5511  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5512  * reference is dropped by the squeue framework.
5513  *
5514  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5515  *
5516  * The reference must be released by the same entity that added the reference
5517  * In the above scheme, the eager is the entity that adds and releases the
5518  * references. Note that tcp_accept_finish executes in the squeue of the eager
5519  * (albeit after it is attached to the acceptor stream). Though 1. executes
5520  * in the listener's squeue, the eager is nascent at this point and the
5521  * reference can be considered to have been added on behalf of the eager.
5522  *
5523  * Eager getting a Reset or listener closing:
5524  * ==========================================
5525  *
5526  * Once the listener and eager are linked, the listener never does the unlink.
5527  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5528  * a message on all eager perimeter. The eager then does the unlink, clears
5529  * any pointers to the listener's queue and drops the reference to the
5530  * listener. The listener waits in tcp_close outside the squeue until its
5531  * refcount has dropped to 1. This ensures that the listener has waited for
5532  * all eagers to clear their association with the listener.
5533  *
5534  * Similarly, if eager decides to go away, it can unlink itself and close.
5535  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5536  * the reference to eager is still valid because of the extra ref we put
5537  * in tcp_send_conn_ind.
5538  *
5539  * Listener can always locate the eager under the protection
5540  * of the listener->tcp_eager_lock, and then do a refhold
5541  * on the eager during the accept processing.
5542  *
5543  * The acceptor stream accesses the eager in the accept processing
5544  * based on the ref placed on eager before sending T_conn_ind.
5545  * The only entity that can negate this refhold is a listener close
5546  * which is mutually exclusive with an active acceptor stream.
5547  *
5548  * Eager's reference on the listener
5549  * ===================================
5550  *
5551  * If the accept happens (even on a closed eager) the eager drops its
5552  * reference on the listener at the start of tcp_accept_finish. If the
5553  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5554  * the reference is dropped in tcp_closei_local. If the listener closes,
5555  * the reference is dropped in tcp_eager_kill. In all cases the reference
5556  * is dropped while executing in the eager's context (squeue).
5557  */
5558 /* END CSTYLED */
5559 
5560 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5561 
5562 /*
5563  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5564  * tcp_rput_data will not see any SYN packets.
5565  */
5566 /* ARGSUSED */
5567 void
5568 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5569 {
5570 	tcph_t		*tcph;
5571 	uint32_t	seg_seq;
5572 	tcp_t		*eager;
5573 	uint_t		ipvers;
5574 	ipha_t		*ipha;
5575 	ip6_t		*ip6h;
5576 	int		err;
5577 	conn_t		*econnp = NULL;
5578 	squeue_t	*new_sqp;
5579 	mblk_t		*mp1;
5580 	uint_t 		ip_hdr_len;
5581 	conn_t		*connp = (conn_t *)arg;
5582 	tcp_t		*tcp = connp->conn_tcp;
5583 	cred_t		*credp;
5584 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5585 	ip_stack_t	*ipst;
5586 
5587 	if (tcp->tcp_state != TCPS_LISTEN)
5588 		goto error2;
5589 
5590 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5591 
5592 	mutex_enter(&tcp->tcp_eager_lock);
5593 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5594 		mutex_exit(&tcp->tcp_eager_lock);
5595 		TCP_STAT(tcps, tcp_listendrop);
5596 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5597 		if (tcp->tcp_debug) {
5598 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5599 			    "tcp_conn_request: listen backlog (max=%d) "
5600 			    "overflow (%d pending) on %s",
5601 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5602 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5603 		}
5604 		goto error2;
5605 	}
5606 
5607 	if (tcp->tcp_conn_req_cnt_q0 >=
5608 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5609 		/*
5610 		 * Q0 is full. Drop a pending half-open req from the queue
5611 		 * to make room for the new SYN req. Also mark the time we
5612 		 * drop a SYN.
5613 		 *
5614 		 * A more aggressive defense against SYN attack will
5615 		 * be to set the "tcp_syn_defense" flag now.
5616 		 */
5617 		TCP_STAT(tcps, tcp_listendropq0);
5618 		tcp->tcp_last_rcv_lbolt = lbolt64;
5619 		if (!tcp_drop_q0(tcp)) {
5620 			mutex_exit(&tcp->tcp_eager_lock);
5621 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5622 			if (tcp->tcp_debug) {
5623 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5624 				    "tcp_conn_request: listen half-open queue "
5625 				    "(max=%d) full (%d pending) on %s",
5626 				    tcps->tcps_conn_req_max_q0,
5627 				    tcp->tcp_conn_req_cnt_q0,
5628 				    tcp_display(tcp, NULL,
5629 				    DISP_PORT_ONLY));
5630 			}
5631 			goto error2;
5632 		}
5633 	}
5634 	mutex_exit(&tcp->tcp_eager_lock);
5635 
5636 	/*
5637 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5638 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5639 	 * link local address.  If IPSec is enabled, db_struioflag has
5640 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5641 	 * otherwise an error case if neither of them is set.
5642 	 */
5643 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5644 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5645 		DB_CKSUMSTART(mp) = 0;
5646 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5647 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5648 		if (econnp == NULL)
5649 			goto error2;
5650 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5651 		econnp->conn_sqp = new_sqp;
5652 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5653 		/*
5654 		 * mp is updated in tcp_get_ipsec_conn().
5655 		 */
5656 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5657 		if (econnp == NULL) {
5658 			/*
5659 			 * mp freed by tcp_get_ipsec_conn.
5660 			 */
5661 			return;
5662 		}
5663 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5664 	} else {
5665 		goto error2;
5666 	}
5667 
5668 	ASSERT(DB_TYPE(mp) == M_DATA);
5669 
5670 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5671 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5672 	ASSERT(OK_32PTR(mp->b_rptr));
5673 	if (ipvers == IPV4_VERSION) {
5674 		ipha = (ipha_t *)mp->b_rptr;
5675 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5676 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5677 	} else {
5678 		ip6h = (ip6_t *)mp->b_rptr;
5679 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5680 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5681 	}
5682 
5683 	if (tcp->tcp_family == AF_INET) {
5684 		ASSERT(ipvers == IPV4_VERSION);
5685 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5686 	} else {
5687 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5688 	}
5689 
5690 	if (err)
5691 		goto error3;
5692 
5693 	eager = econnp->conn_tcp;
5694 
5695 	/* Inherit various TCP parameters from the listener */
5696 	eager->tcp_naglim = tcp->tcp_naglim;
5697 	eager->tcp_first_timer_threshold =
5698 	    tcp->tcp_first_timer_threshold;
5699 	eager->tcp_second_timer_threshold =
5700 	    tcp->tcp_second_timer_threshold;
5701 
5702 	eager->tcp_first_ctimer_threshold =
5703 	    tcp->tcp_first_ctimer_threshold;
5704 	eager->tcp_second_ctimer_threshold =
5705 	    tcp->tcp_second_ctimer_threshold;
5706 
5707 	/*
5708 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5709 	 * If it does not, the eager's receive window will be set to the
5710 	 * listener's receive window later in this function.
5711 	 */
5712 	eager->tcp_rwnd = 0;
5713 
5714 	/*
5715 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5716 	 * calling tcp_process_options() where tcp_mss_set() is called
5717 	 * to set the initial cwnd.
5718 	 */
5719 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5720 
5721 	/*
5722 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5723 	 * zone id before the accept is completed in tcp_wput_accept().
5724 	 */
5725 	econnp->conn_zoneid = connp->conn_zoneid;
5726 	econnp->conn_allzones = connp->conn_allzones;
5727 
5728 	/* Copy nexthop information from listener to eager */
5729 	if (connp->conn_nexthop_set) {
5730 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5731 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5732 	}
5733 
5734 	/*
5735 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5736 	 * eager is accepted
5737 	 */
5738 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5739 	crhold(credp);
5740 
5741 	/*
5742 	 * If the caller has the process-wide flag set, then default to MAC
5743 	 * exempt mode.  This allows read-down to unlabeled hosts.
5744 	 */
5745 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5746 		econnp->conn_mac_exempt = B_TRUE;
5747 
5748 	if (is_system_labeled()) {
5749 		cred_t *cr;
5750 
5751 		if (connp->conn_mlp_type != mlptSingle) {
5752 			cr = econnp->conn_peercred = DB_CRED(mp);
5753 			if (cr != NULL)
5754 				crhold(cr);
5755 			else
5756 				cr = econnp->conn_cred;
5757 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5758 			    econnp, cred_t *, cr)
5759 		} else {
5760 			cr = econnp->conn_cred;
5761 			DTRACE_PROBE2(syn_accept, conn_t *,
5762 			    econnp, cred_t *, cr)
5763 		}
5764 
5765 		if (!tcp_update_label(eager, cr)) {
5766 			DTRACE_PROBE3(
5767 			    tx__ip__log__error__connrequest__tcp,
5768 			    char *, "eager connp(1) label on SYN mp(2) failed",
5769 			    conn_t *, econnp, mblk_t *, mp);
5770 			goto error3;
5771 		}
5772 	}
5773 
5774 	eager->tcp_hard_binding = B_TRUE;
5775 
5776 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5777 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5778 
5779 	CL_INET_CONNECT(eager);
5780 
5781 	/*
5782 	 * No need to check for multicast destination since ip will only pass
5783 	 * up multicasts to those that have expressed interest
5784 	 * TODO: what about rejecting broadcasts?
5785 	 * Also check that source is not a multicast or broadcast address.
5786 	 */
5787 	eager->tcp_state = TCPS_SYN_RCVD;
5788 
5789 
5790 	/*
5791 	 * There should be no ire in the mp as we are being called after
5792 	 * receiving the SYN.
5793 	 */
5794 	ASSERT(tcp_ire_mp(mp) == NULL);
5795 
5796 	/*
5797 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5798 	 */
5799 
5800 	if (tcp_adapt_ire(eager, NULL) == 0) {
5801 		/* Undo the bind_hash_insert */
5802 		tcp_bind_hash_remove(eager);
5803 		goto error3;
5804 	}
5805 
5806 	/* Process all TCP options. */
5807 	tcp_process_options(eager, tcph);
5808 
5809 	/* Is the other end ECN capable? */
5810 	if (tcps->tcps_ecn_permitted >= 1 &&
5811 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5812 		eager->tcp_ecn_ok = B_TRUE;
5813 	}
5814 
5815 	/*
5816 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5817 	 * window size changed via SO_RCVBUF option.  First round up the
5818 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5819 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5820 	 * setting.
5821 	 *
5822 	 * Note if there is a rpipe metric associated with the remote host,
5823 	 * we should not inherit receive window size from listener.
5824 	 */
5825 	eager->tcp_rwnd = MSS_ROUNDUP(
5826 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5827 	    eager->tcp_rwnd), eager->tcp_mss);
5828 	if (eager->tcp_snd_ws_ok)
5829 		tcp_set_ws_value(eager);
5830 	/*
5831 	 * Note that this is the only place tcp_rwnd_set() is called for
5832 	 * accepting a connection.  We need to call it here instead of
5833 	 * after the 3-way handshake because we need to tell the other
5834 	 * side our rwnd in the SYN-ACK segment.
5835 	 */
5836 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5837 
5838 	/*
5839 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5840 	 * via soaccept()->soinheritoptions() which essentially applies
5841 	 * all the listener options to the new STREAM. The options that we
5842 	 * need to take care of are:
5843 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5844 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5845 	 * SO_SNDBUF, SO_RCVBUF.
5846 	 *
5847 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5848 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5849 	 *		tcp_maxpsz_set() gets called later from
5850 	 *		tcp_accept_finish(), the option takes effect.
5851 	 *
5852 	 */
5853 	/* Set the TCP options */
5854 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5855 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5856 	eager->tcp_oobinline = tcp->tcp_oobinline;
5857 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5858 	eager->tcp_broadcast = tcp->tcp_broadcast;
5859 	eager->tcp_useloopback = tcp->tcp_useloopback;
5860 	eager->tcp_dontroute = tcp->tcp_dontroute;
5861 	eager->tcp_linger = tcp->tcp_linger;
5862 	eager->tcp_lingertime = tcp->tcp_lingertime;
5863 	if (tcp->tcp_ka_enabled)
5864 		eager->tcp_ka_enabled = 1;
5865 
5866 	/* Set the IP options */
5867 	econnp->conn_broadcast = connp->conn_broadcast;
5868 	econnp->conn_loopback = connp->conn_loopback;
5869 	econnp->conn_dontroute = connp->conn_dontroute;
5870 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5871 
5872 	/* Put a ref on the listener for the eager. */
5873 	CONN_INC_REF(connp);
5874 	mutex_enter(&tcp->tcp_eager_lock);
5875 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5876 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5877 	tcp->tcp_eager_next_q0 = eager;
5878 	eager->tcp_eager_prev_q0 = tcp;
5879 
5880 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5881 	eager->tcp_listener = tcp;
5882 	eager->tcp_saved_listener = tcp;
5883 
5884 	/*
5885 	 * Tag this detached tcp vector for later retrieval
5886 	 * by our listener client in tcp_accept().
5887 	 */
5888 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5889 	tcp->tcp_conn_req_cnt_q0++;
5890 	if (++tcp->tcp_conn_req_seqnum == -1) {
5891 		/*
5892 		 * -1 is "special" and defined in TPI as something
5893 		 * that should never be used in T_CONN_IND
5894 		 */
5895 		++tcp->tcp_conn_req_seqnum;
5896 	}
5897 	mutex_exit(&tcp->tcp_eager_lock);
5898 
5899 	if (tcp->tcp_syn_defense) {
5900 		/* Don't drop the SYN that comes from a good IP source */
5901 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5902 		if (addr_cache != NULL && eager->tcp_remote ==
5903 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5904 			eager->tcp_dontdrop = B_TRUE;
5905 		}
5906 	}
5907 
5908 	/*
5909 	 * We need to insert the eager in its own perimeter but as soon
5910 	 * as we do that, we expose the eager to the classifier and
5911 	 * should not touch any field outside the eager's perimeter.
5912 	 * So do all the work necessary before inserting the eager
5913 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5914 	 * will succeed but undo everything if it fails.
5915 	 */
5916 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5917 	eager->tcp_irs = seg_seq;
5918 	eager->tcp_rack = seg_seq;
5919 	eager->tcp_rnxt = seg_seq + 1;
5920 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5921 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5922 	eager->tcp_state = TCPS_SYN_RCVD;
5923 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5924 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5925 	if (mp1 == NULL) {
5926 		/*
5927 		 * Increment the ref count as we are going to
5928 		 * enqueueing an mp in squeue
5929 		 */
5930 		CONN_INC_REF(econnp);
5931 		goto error;
5932 	}
5933 	DB_CPID(mp1) = tcp->tcp_cpid;
5934 	eager->tcp_cpid = tcp->tcp_cpid;
5935 	eager->tcp_open_time = lbolt64;
5936 
5937 	/*
5938 	 * We need to start the rto timer. In normal case, we start
5939 	 * the timer after sending the packet on the wire (or at
5940 	 * least believing that packet was sent by waiting for
5941 	 * CALL_IP_WPUT() to return). Since this is the first packet
5942 	 * being sent on the wire for the eager, our initial tcp_rto
5943 	 * is at least tcp_rexmit_interval_min which is a fairly
5944 	 * large value to allow the algorithm to adjust slowly to large
5945 	 * fluctuations of RTT during first few transmissions.
5946 	 *
5947 	 * Starting the timer first and then sending the packet in this
5948 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5949 	 * is of the order of several 100ms and starting the timer
5950 	 * first and then sending the packet will result in difference
5951 	 * of few micro seconds.
5952 	 *
5953 	 * Without this optimization, we are forced to hold the fanout
5954 	 * lock across the ipcl_bind_insert() and sending the packet
5955 	 * so that we don't race against an incoming packet (maybe RST)
5956 	 * for this eager.
5957 	 *
5958 	 * It is necessary to acquire an extra reference on the eager
5959 	 * at this point and hold it until after tcp_send_data() to
5960 	 * ensure against an eager close race.
5961 	 */
5962 
5963 	CONN_INC_REF(eager->tcp_connp);
5964 
5965 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5966 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5967 
5968 
5969 	/*
5970 	 * Insert the eager in its own perimeter now. We are ready to deal
5971 	 * with any packets on eager.
5972 	 */
5973 	if (eager->tcp_ipversion == IPV4_VERSION) {
5974 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5975 			goto error;
5976 		}
5977 	} else {
5978 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5979 			goto error;
5980 		}
5981 	}
5982 
5983 	/* mark conn as fully-bound */
5984 	econnp->conn_fully_bound = B_TRUE;
5985 
5986 	/* Send the SYN-ACK */
5987 	tcp_send_data(eager, eager->tcp_wq, mp1);
5988 	CONN_DEC_REF(eager->tcp_connp);
5989 	freemsg(mp);
5990 
5991 	return;
5992 error:
5993 	freemsg(mp1);
5994 	eager->tcp_closemp_used = B_TRUE;
5995 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5996 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
5997 	    econnp, SQTAG_TCP_CONN_REQ_2);
5998 
5999 	/*
6000 	 * If a connection already exists, send the mp to that connections so
6001 	 * that it can be appropriately dealt with.
6002 	 */
6003 	ipst = tcps->tcps_netstack->netstack_ip;
6004 
6005 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6006 		if (!IPCL_IS_CONNECTED(econnp)) {
6007 			/*
6008 			 * Something bad happened. ipcl_conn_insert()
6009 			 * failed because a connection already existed
6010 			 * in connected hash but we can't find it
6011 			 * anymore (someone blew it away). Just
6012 			 * free this message and hopefully remote
6013 			 * will retransmit at which time the SYN can be
6014 			 * treated as a new connection or dealth with
6015 			 * a TH_RST if a connection already exists.
6016 			 */
6017 			CONN_DEC_REF(econnp);
6018 			freemsg(mp);
6019 		} else {
6020 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6021 			    econnp, SQTAG_TCP_CONN_REQ_1);
6022 		}
6023 	} else {
6024 		/* Nobody wants this packet */
6025 		freemsg(mp);
6026 	}
6027 	return;
6028 error3:
6029 	CONN_DEC_REF(econnp);
6030 error2:
6031 	freemsg(mp);
6032 }
6033 
6034 /*
6035  * In an ideal case of vertical partition in NUMA architecture, its
6036  * beneficial to have the listener and all the incoming connections
6037  * tied to the same squeue. The other constraint is that incoming
6038  * connections should be tied to the squeue attached to interrupted
6039  * CPU for obvious locality reason so this leaves the listener to
6040  * be tied to the same squeue. Our only problem is that when listener
6041  * is binding, the CPU that will get interrupted by the NIC whose
6042  * IP address the listener is binding to is not even known. So
6043  * the code below allows us to change that binding at the time the
6044  * CPU is interrupted by virtue of incoming connection's squeue.
6045  *
6046  * This is usefull only in case of a listener bound to a specific IP
6047  * address. For other kind of listeners, they get bound the
6048  * very first time and there is no attempt to rebind them.
6049  */
6050 void
6051 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6052 {
6053 	conn_t		*connp = (conn_t *)arg;
6054 	squeue_t	*sqp = (squeue_t *)arg2;
6055 	squeue_t	*new_sqp;
6056 	uint32_t	conn_flags;
6057 
6058 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6059 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6060 	} else {
6061 		goto done;
6062 	}
6063 
6064 	if (connp->conn_fanout == NULL)
6065 		goto done;
6066 
6067 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6068 		mutex_enter(&connp->conn_fanout->connf_lock);
6069 		mutex_enter(&connp->conn_lock);
6070 		/*
6071 		 * No one from read or write side can access us now
6072 		 * except for already queued packets on this squeue.
6073 		 * But since we haven't changed the squeue yet, they
6074 		 * can't execute. If they are processed after we have
6075 		 * changed the squeue, they are sent back to the
6076 		 * correct squeue down below.
6077 		 * But a listner close can race with processing of
6078 		 * incoming SYN. If incoming SYN processing changes
6079 		 * the squeue then the listener close which is waiting
6080 		 * to enter the squeue would operate on the wrong
6081 		 * squeue. Hence we don't change the squeue here unless
6082 		 * the refcount is exactly the minimum refcount. The
6083 		 * minimum refcount of 4 is counted as - 1 each for
6084 		 * TCP and IP, 1 for being in the classifier hash, and
6085 		 * 1 for the mblk being processed.
6086 		 */
6087 
6088 		if (connp->conn_ref != 4 ||
6089 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6090 			mutex_exit(&connp->conn_lock);
6091 			mutex_exit(&connp->conn_fanout->connf_lock);
6092 			goto done;
6093 		}
6094 		if (connp->conn_sqp != new_sqp) {
6095 			while (connp->conn_sqp != new_sqp)
6096 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6097 		}
6098 
6099 		do {
6100 			conn_flags = connp->conn_flags;
6101 			conn_flags |= IPCL_FULLY_BOUND;
6102 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6103 			    conn_flags);
6104 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6105 
6106 		mutex_exit(&connp->conn_fanout->connf_lock);
6107 		mutex_exit(&connp->conn_lock);
6108 	}
6109 
6110 done:
6111 	if (connp->conn_sqp != sqp) {
6112 		CONN_INC_REF(connp);
6113 		squeue_fill(connp->conn_sqp, mp,
6114 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6115 	} else {
6116 		tcp_conn_request(connp, mp, sqp);
6117 	}
6118 }
6119 
6120 /*
6121  * Successful connect request processing begins when our client passes
6122  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6123  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6124  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6125  *   upstream <- tcp_rput()                <- IP
6126  * After various error checks are completed, tcp_connect() lays
6127  * the target address and port into the composite header template,
6128  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6129  * request followed by an IRE request, and passes the three mblk message
6130  * down to IP looking like this:
6131  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6132  * Processing continues in tcp_rput() when we receive the following message:
6133  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6134  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6135  * to fire off the connection request, and then passes the T_OK_ACK mblk
6136  * upstream that we filled in below.  There are, of course, numerous
6137  * error conditions along the way which truncate the processing described
6138  * above.
6139  */
6140 static void
6141 tcp_connect(tcp_t *tcp, mblk_t *mp)
6142 {
6143 	sin_t		*sin;
6144 	sin6_t		*sin6;
6145 	queue_t		*q = tcp->tcp_wq;
6146 	struct T_conn_req	*tcr;
6147 	ipaddr_t	*dstaddrp;
6148 	in_port_t	dstport;
6149 	uint_t		srcid;
6150 
6151 	tcr = (struct T_conn_req *)mp->b_rptr;
6152 
6153 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6154 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6155 		tcp_err_ack(tcp, mp, TPROTO, 0);
6156 		return;
6157 	}
6158 
6159 	/*
6160 	 * Determine packet type based on type of address passed in
6161 	 * the request should contain an IPv4 or IPv6 address.
6162 	 * Make sure that address family matches the type of
6163 	 * family of the the address passed down
6164 	 */
6165 	switch (tcr->DEST_length) {
6166 	default:
6167 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6168 		return;
6169 
6170 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6171 		/*
6172 		 * XXX: The check for valid DEST_length was not there
6173 		 * in earlier releases and some buggy
6174 		 * TLI apps (e.g Sybase) got away with not feeding
6175 		 * in sin_zero part of address.
6176 		 * We allow that bug to keep those buggy apps humming.
6177 		 * Test suites require the check on DEST_length.
6178 		 * We construct a new mblk with valid DEST_length
6179 		 * free the original so the rest of the code does
6180 		 * not have to keep track of this special shorter
6181 		 * length address case.
6182 		 */
6183 		mblk_t *nmp;
6184 		struct T_conn_req *ntcr;
6185 		sin_t *nsin;
6186 
6187 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6188 		    tcr->OPT_length, BPRI_HI);
6189 		if (nmp == NULL) {
6190 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6191 			return;
6192 		}
6193 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6194 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6195 		ntcr->PRIM_type = T_CONN_REQ;
6196 		ntcr->DEST_length = sizeof (sin_t);
6197 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6198 
6199 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6200 		*nsin = sin_null;
6201 		/* Get pointer to shorter address to copy from original mp */
6202 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6203 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6204 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6205 			freemsg(nmp);
6206 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6207 			return;
6208 		}
6209 		nsin->sin_family = sin->sin_family;
6210 		nsin->sin_port = sin->sin_port;
6211 		nsin->sin_addr = sin->sin_addr;
6212 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6213 		nmp->b_wptr = (uchar_t *)&nsin[1];
6214 		if (tcr->OPT_length != 0) {
6215 			ntcr->OPT_length = tcr->OPT_length;
6216 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6217 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6218 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6219 			    tcr->OPT_length);
6220 			nmp->b_wptr += tcr->OPT_length;
6221 		}
6222 		freemsg(mp);	/* original mp freed */
6223 		mp = nmp;	/* re-initialize original variables */
6224 		tcr = ntcr;
6225 	}
6226 	/* FALLTHRU */
6227 
6228 	case sizeof (sin_t):
6229 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6230 		    sizeof (sin_t));
6231 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6232 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6233 			return;
6234 		}
6235 		if (tcp->tcp_family != AF_INET ||
6236 		    sin->sin_family != AF_INET) {
6237 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6238 			return;
6239 		}
6240 		if (sin->sin_port == 0) {
6241 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6242 			return;
6243 		}
6244 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6245 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6246 			return;
6247 		}
6248 
6249 		break;
6250 
6251 	case sizeof (sin6_t):
6252 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6253 		    sizeof (sin6_t));
6254 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6255 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6256 			return;
6257 		}
6258 		if (tcp->tcp_family != AF_INET6 ||
6259 		    sin6->sin6_family != AF_INET6) {
6260 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6261 			return;
6262 		}
6263 		if (sin6->sin6_port == 0) {
6264 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6265 			return;
6266 		}
6267 		break;
6268 	}
6269 	/*
6270 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6271 	 * should key on their sequence number and cut them loose.
6272 	 */
6273 
6274 	/*
6275 	 * If options passed in, feed it for verification and handling
6276 	 */
6277 	if (tcr->OPT_length != 0) {
6278 		mblk_t	*ok_mp;
6279 		mblk_t	*discon_mp;
6280 		mblk_t  *conn_opts_mp;
6281 		int t_error, sys_error, do_disconnect;
6282 
6283 		conn_opts_mp = NULL;
6284 
6285 		if (tcp_conprim_opt_process(tcp, mp,
6286 			&do_disconnect, &t_error, &sys_error) < 0) {
6287 			if (do_disconnect) {
6288 				ASSERT(t_error == 0 && sys_error == 0);
6289 				discon_mp = mi_tpi_discon_ind(NULL,
6290 				    ECONNREFUSED, 0);
6291 				if (!discon_mp) {
6292 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6293 					    TSYSERR, ENOMEM);
6294 					return;
6295 				}
6296 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6297 				if (!ok_mp) {
6298 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6299 					    TSYSERR, ENOMEM);
6300 					return;
6301 				}
6302 				qreply(q, ok_mp);
6303 				qreply(q, discon_mp); /* no flush! */
6304 			} else {
6305 				ASSERT(t_error != 0);
6306 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6307 				    sys_error);
6308 			}
6309 			return;
6310 		}
6311 		/*
6312 		 * Success in setting options, the mp option buffer represented
6313 		 * by OPT_length/offset has been potentially modified and
6314 		 * contains results of option processing. We copy it in
6315 		 * another mp to save it for potentially influencing returning
6316 		 * it in T_CONN_CONN.
6317 		 */
6318 		if (tcr->OPT_length != 0) { /* there are resulting options */
6319 			conn_opts_mp = copyb(mp);
6320 			if (!conn_opts_mp) {
6321 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6322 				    TSYSERR, ENOMEM);
6323 				return;
6324 			}
6325 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6326 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6327 			/*
6328 			 * Note:
6329 			 * These resulting option negotiation can include any
6330 			 * end-to-end negotiation options but there no such
6331 			 * thing (yet?) in our TCP/IP.
6332 			 */
6333 		}
6334 	}
6335 
6336 	/*
6337 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6338 	 * make sure that the template IP header in the tcp structure is an
6339 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6340 	 * need to this before we call tcp_bindi() so that the port lookup
6341 	 * code will look for ports in the correct port space (IPv4 and
6342 	 * IPv6 have separate port spaces).
6343 	 */
6344 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6345 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6346 		int err = 0;
6347 
6348 		err = tcp_header_init_ipv4(tcp);
6349 		if (err != 0) {
6350 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6351 			goto connect_failed;
6352 		}
6353 		if (tcp->tcp_lport != 0)
6354 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6355 	}
6356 
6357 	switch (tcp->tcp_state) {
6358 	case TCPS_IDLE:
6359 		/*
6360 		 * We support quick connect, refer to comments in
6361 		 * tcp_connect_*()
6362 		 */
6363 		/* FALLTHRU */
6364 	case TCPS_BOUND:
6365 	case TCPS_LISTEN:
6366 		if (tcp->tcp_family == AF_INET6) {
6367 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6368 				tcp_connect_ipv6(tcp, mp,
6369 				    &sin6->sin6_addr,
6370 				    sin6->sin6_port, sin6->sin6_flowinfo,
6371 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6372 				return;
6373 			}
6374 			/*
6375 			 * Destination adress is mapped IPv6 address.
6376 			 * Source bound address should be unspecified or
6377 			 * IPv6 mapped address as well.
6378 			 */
6379 			if (!IN6_IS_ADDR_UNSPECIFIED(
6380 			    &tcp->tcp_bound_source_v6) &&
6381 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6382 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6383 				    EADDRNOTAVAIL);
6384 				break;
6385 			}
6386 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6387 			dstport = sin6->sin6_port;
6388 			srcid = sin6->__sin6_src_id;
6389 		} else {
6390 			dstaddrp = &sin->sin_addr.s_addr;
6391 			dstport = sin->sin_port;
6392 			srcid = 0;
6393 		}
6394 
6395 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6396 		return;
6397 	default:
6398 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6399 		break;
6400 	}
6401 	/*
6402 	 * Note: Code below is the "failure" case
6403 	 */
6404 	/* return error ack and blow away saved option results if any */
6405 connect_failed:
6406 	if (mp != NULL)
6407 		putnext(tcp->tcp_rq, mp);
6408 	else {
6409 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6410 		    TSYSERR, ENOMEM);
6411 	}
6412 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6413 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6414 }
6415 
6416 /*
6417  * Handle connect to IPv4 destinations, including connections for AF_INET6
6418  * sockets connecting to IPv4 mapped IPv6 destinations.
6419  */
6420 static void
6421 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6422     uint_t srcid)
6423 {
6424 	tcph_t	*tcph;
6425 	mblk_t	*mp1;
6426 	ipaddr_t dstaddr = *dstaddrp;
6427 	int32_t	oldstate;
6428 	uint16_t lport;
6429 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6430 
6431 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6432 
6433 	/* Check for attempt to connect to INADDR_ANY */
6434 	if (dstaddr == INADDR_ANY)  {
6435 		/*
6436 		 * SunOS 4.x and 4.3 BSD allow an application
6437 		 * to connect a TCP socket to INADDR_ANY.
6438 		 * When they do this, the kernel picks the
6439 		 * address of one interface and uses it
6440 		 * instead.  The kernel usually ends up
6441 		 * picking the address of the loopback
6442 		 * interface.  This is an undocumented feature.
6443 		 * However, we provide the same thing here
6444 		 * in order to have source and binary
6445 		 * compatibility with SunOS 4.x.
6446 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6447 		 * generate the T_CONN_CON.
6448 		 */
6449 		dstaddr = htonl(INADDR_LOOPBACK);
6450 		*dstaddrp = dstaddr;
6451 	}
6452 
6453 	/* Handle __sin6_src_id if socket not bound to an IP address */
6454 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6455 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6456 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6457 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6458 		    tcp->tcp_ipha->ipha_src);
6459 	}
6460 
6461 	/*
6462 	 * Don't let an endpoint connect to itself.  Note that
6463 	 * the test here does not catch the case where the
6464 	 * source IP addr was left unspecified by the user. In
6465 	 * this case, the source addr is set in tcp_adapt_ire()
6466 	 * using the reply to the T_BIND message that we send
6467 	 * down to IP here and the check is repeated in tcp_rput_other.
6468 	 */
6469 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6470 	    dstport == tcp->tcp_lport) {
6471 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6472 		goto failed;
6473 	}
6474 
6475 	tcp->tcp_ipha->ipha_dst = dstaddr;
6476 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6477 
6478 	/*
6479 	 * Massage a source route if any putting the first hop
6480 	 * in iph_dst. Compute a starting value for the checksum which
6481 	 * takes into account that the original iph_dst should be
6482 	 * included in the checksum but that ip will include the
6483 	 * first hop in the source route in the tcp checksum.
6484 	 */
6485 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6486 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6487 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6488 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6489 	if ((int)tcp->tcp_sum < 0)
6490 		tcp->tcp_sum--;
6491 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6492 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6493 	    (tcp->tcp_sum >> 16));
6494 	tcph = tcp->tcp_tcph;
6495 	*(uint16_t *)tcph->th_fport = dstport;
6496 	tcp->tcp_fport = dstport;
6497 
6498 	oldstate = tcp->tcp_state;
6499 	/*
6500 	 * At this point the remote destination address and remote port fields
6501 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6502 	 * have to see which state tcp was in so we can take apropriate action.
6503 	 */
6504 	if (oldstate == TCPS_IDLE) {
6505 		/*
6506 		 * We support a quick connect capability here, allowing
6507 		 * clients to transition directly from IDLE to SYN_SENT
6508 		 * tcp_bindi will pick an unused port, insert the connection
6509 		 * in the bind hash and transition to BOUND state.
6510 		 */
6511 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6512 		    tcp, B_TRUE);
6513 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6514 		    B_FALSE, B_FALSE);
6515 		if (lport == 0) {
6516 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6517 			goto failed;
6518 		}
6519 	}
6520 	tcp->tcp_state = TCPS_SYN_SENT;
6521 
6522 	/*
6523 	 * TODO: allow data with connect requests
6524 	 * by unlinking M_DATA trailers here and
6525 	 * linking them in behind the T_OK_ACK mblk.
6526 	 * The tcp_rput() bind ack handler would then
6527 	 * feed them to tcp_wput_data() rather than call
6528 	 * tcp_timer().
6529 	 */
6530 	mp = mi_tpi_ok_ack_alloc(mp);
6531 	if (!mp) {
6532 		tcp->tcp_state = oldstate;
6533 		goto failed;
6534 	}
6535 	if (tcp->tcp_family == AF_INET) {
6536 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6537 		    sizeof (ipa_conn_t));
6538 	} else {
6539 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6540 		    sizeof (ipa6_conn_t));
6541 	}
6542 	if (mp1) {
6543 		/* Hang onto the T_OK_ACK for later. */
6544 		linkb(mp1, mp);
6545 		mblk_setcred(mp1, tcp->tcp_cred);
6546 		if (tcp->tcp_family == AF_INET)
6547 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6548 		else {
6549 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6550 			    &tcp->tcp_sticky_ipp);
6551 		}
6552 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6553 		tcp->tcp_active_open = 1;
6554 		/*
6555 		 * If the bind cannot complete immediately
6556 		 * IP will arrange to call tcp_rput_other
6557 		 * when the bind completes.
6558 		 */
6559 		if (mp1 != NULL)
6560 			tcp_rput_other(tcp, mp1);
6561 		return;
6562 	}
6563 	/* Error case */
6564 	tcp->tcp_state = oldstate;
6565 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6566 
6567 failed:
6568 	/* return error ack and blow away saved option results if any */
6569 	if (mp != NULL)
6570 		putnext(tcp->tcp_rq, mp);
6571 	else {
6572 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6573 		    TSYSERR, ENOMEM);
6574 	}
6575 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6576 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6577 
6578 }
6579 
6580 /*
6581  * Handle connect to IPv6 destinations.
6582  */
6583 static void
6584 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6585     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6586 {
6587 	tcph_t	*tcph;
6588 	mblk_t	*mp1;
6589 	ip6_rthdr_t *rth;
6590 	int32_t  oldstate;
6591 	uint16_t lport;
6592 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6593 
6594 	ASSERT(tcp->tcp_family == AF_INET6);
6595 
6596 	/*
6597 	 * If we're here, it means that the destination address is a native
6598 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6599 	 * reason why it might not be IPv6 is if the socket was bound to an
6600 	 * IPv4-mapped IPv6 address.
6601 	 */
6602 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6603 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6604 		goto failed;
6605 	}
6606 
6607 	/*
6608 	 * Interpret a zero destination to mean loopback.
6609 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6610 	 * generate the T_CONN_CON.
6611 	 */
6612 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6613 		*dstaddrp = ipv6_loopback;
6614 	}
6615 
6616 	/* Handle __sin6_src_id if socket not bound to an IP address */
6617 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6618 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6619 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6620 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6621 	}
6622 
6623 	/*
6624 	 * Take care of the scope_id now and add ip6i_t
6625 	 * if ip6i_t is not already allocated through TCP
6626 	 * sticky options. At this point tcp_ip6h does not
6627 	 * have dst info, thus use dstaddrp.
6628 	 */
6629 	if (scope_id != 0 &&
6630 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6631 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6632 		ip6i_t  *ip6i;
6633 
6634 		ipp->ipp_ifindex = scope_id;
6635 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6636 
6637 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6638 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6639 			/* Already allocated */
6640 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6641 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6642 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6643 		} else {
6644 			int reterr;
6645 
6646 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6647 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6648 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6649 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6650 			if (reterr != 0)
6651 				goto failed;
6652 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6653 		}
6654 	}
6655 
6656 	/*
6657 	 * Don't let an endpoint connect to itself.  Note that
6658 	 * the test here does not catch the case where the
6659 	 * source IP addr was left unspecified by the user. In
6660 	 * this case, the source addr is set in tcp_adapt_ire()
6661 	 * using the reply to the T_BIND message that we send
6662 	 * down to IP here and the check is repeated in tcp_rput_other.
6663 	 */
6664 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6665 	    (dstport == tcp->tcp_lport)) {
6666 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6667 		goto failed;
6668 	}
6669 
6670 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6671 	tcp->tcp_remote_v6 = *dstaddrp;
6672 	tcp->tcp_ip6h->ip6_vcf =
6673 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6674 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6675 
6676 
6677 	/*
6678 	 * Massage a routing header (if present) putting the first hop
6679 	 * in ip6_dst. Compute a starting value for the checksum which
6680 	 * takes into account that the original ip6_dst should be
6681 	 * included in the checksum but that ip will include the
6682 	 * first hop in the source route in the tcp checksum.
6683 	 */
6684 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6685 	if (rth != NULL) {
6686 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6687 		    tcps->tcps_netstack);
6688 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6689 		    (tcp->tcp_sum >> 16));
6690 	} else {
6691 		tcp->tcp_sum = 0;
6692 	}
6693 
6694 	tcph = tcp->tcp_tcph;
6695 	*(uint16_t *)tcph->th_fport = dstport;
6696 	tcp->tcp_fport = dstport;
6697 
6698 	oldstate = tcp->tcp_state;
6699 	/*
6700 	 * At this point the remote destination address and remote port fields
6701 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6702 	 * have to see which state tcp was in so we can take apropriate action.
6703 	 */
6704 	if (oldstate == TCPS_IDLE) {
6705 		/*
6706 		 * We support a quick connect capability here, allowing
6707 		 * clients to transition directly from IDLE to SYN_SENT
6708 		 * tcp_bindi will pick an unused port, insert the connection
6709 		 * in the bind hash and transition to BOUND state.
6710 		 */
6711 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6712 		    tcp, B_TRUE);
6713 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6714 		    B_FALSE, B_FALSE);
6715 		if (lport == 0) {
6716 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6717 			goto failed;
6718 		}
6719 	}
6720 	tcp->tcp_state = TCPS_SYN_SENT;
6721 	/*
6722 	 * TODO: allow data with connect requests
6723 	 * by unlinking M_DATA trailers here and
6724 	 * linking them in behind the T_OK_ACK mblk.
6725 	 * The tcp_rput() bind ack handler would then
6726 	 * feed them to tcp_wput_data() rather than call
6727 	 * tcp_timer().
6728 	 */
6729 	mp = mi_tpi_ok_ack_alloc(mp);
6730 	if (!mp) {
6731 		tcp->tcp_state = oldstate;
6732 		goto failed;
6733 	}
6734 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6735 	if (mp1) {
6736 		/* Hang onto the T_OK_ACK for later. */
6737 		linkb(mp1, mp);
6738 		mblk_setcred(mp1, tcp->tcp_cred);
6739 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6740 		    &tcp->tcp_sticky_ipp);
6741 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6742 		tcp->tcp_active_open = 1;
6743 		/* ip_bind_v6() may return ACK or ERROR */
6744 		if (mp1 != NULL)
6745 			tcp_rput_other(tcp, mp1);
6746 		return;
6747 	}
6748 	/* Error case */
6749 	tcp->tcp_state = oldstate;
6750 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6751 
6752 failed:
6753 	/* return error ack and blow away saved option results if any */
6754 	if (mp != NULL)
6755 		putnext(tcp->tcp_rq, mp);
6756 	else {
6757 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6758 		    TSYSERR, ENOMEM);
6759 	}
6760 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6761 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6762 }
6763 
6764 /*
6765  * We need a stream q for detached closing tcp connections
6766  * to use.  Our client hereby indicates that this q is the
6767  * one to use.
6768  */
6769 static void
6770 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6771 {
6772 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6773 	queue_t	*q = tcp->tcp_wq;
6774 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6775 
6776 #ifdef NS_DEBUG
6777 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6778 	    tcps->tcps_netstack->netstack_stackid);
6779 #endif
6780 	mp->b_datap->db_type = M_IOCACK;
6781 	iocp->ioc_count = 0;
6782 	mutex_enter(&tcps->tcps_g_q_lock);
6783 	if (tcps->tcps_g_q != NULL) {
6784 		mutex_exit(&tcps->tcps_g_q_lock);
6785 		iocp->ioc_error = EALREADY;
6786 	} else {
6787 		mblk_t *mp1;
6788 
6789 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6790 		if (mp1 == NULL) {
6791 			mutex_exit(&tcps->tcps_g_q_lock);
6792 			iocp->ioc_error = ENOMEM;
6793 		} else {
6794 			tcps->tcps_g_q = tcp->tcp_rq;
6795 			mutex_exit(&tcps->tcps_g_q_lock);
6796 			iocp->ioc_error = 0;
6797 			iocp->ioc_rval = 0;
6798 			/*
6799 			 * We are passing tcp_sticky_ipp as NULL
6800 			 * as it is not useful for tcp_default queue
6801 			 */
6802 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6803 			if (mp1 != NULL)
6804 				tcp_rput_other(tcp, mp1);
6805 		}
6806 	}
6807 	qreply(q, mp);
6808 }
6809 
6810 /*
6811  * Our client hereby directs us to reject the connection request
6812  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6813  * of sending the appropriate RST, not an ICMP error.
6814  */
6815 static void
6816 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6817 {
6818 	tcp_t	*ltcp = NULL;
6819 	t_scalar_t seqnum;
6820 	conn_t	*connp;
6821 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6822 
6823 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6824 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6825 		tcp_err_ack(tcp, mp, TPROTO, 0);
6826 		return;
6827 	}
6828 
6829 	/*
6830 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6831 	 * when the stream is in BOUND state. Do not send a reset,
6832 	 * since the destination IP address is not valid, and it can
6833 	 * be the initialized value of all zeros (broadcast address).
6834 	 *
6835 	 * If TCP has sent down a bind request to IP and has not
6836 	 * received the reply, reject the request.  Otherwise, TCP
6837 	 * will be confused.
6838 	 */
6839 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6840 		if (tcp->tcp_debug) {
6841 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6842 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6843 		}
6844 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6845 		return;
6846 	}
6847 
6848 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6849 
6850 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6851 
6852 		/*
6853 		 * According to TPI, for non-listeners, ignore seqnum
6854 		 * and disconnect.
6855 		 * Following interpretation of -1 seqnum is historical
6856 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6857 		 * a valid seqnum should not be -1).
6858 		 *
6859 		 *	-1 means disconnect everything
6860 		 *	regardless even on a listener.
6861 		 */
6862 
6863 		int old_state = tcp->tcp_state;
6864 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6865 
6866 		/*
6867 		 * The connection can't be on the tcp_time_wait_head list
6868 		 * since it is not detached.
6869 		 */
6870 		ASSERT(tcp->tcp_time_wait_next == NULL);
6871 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6872 		ASSERT(tcp->tcp_time_wait_expire == 0);
6873 		ltcp = NULL;
6874 		/*
6875 		 * If it used to be a listener, check to make sure no one else
6876 		 * has taken the port before switching back to LISTEN state.
6877 		 */
6878 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6879 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6880 			    tcp->tcp_ipha->ipha_src,
6881 			    tcp->tcp_connp->conn_zoneid, ipst);
6882 			if (connp != NULL)
6883 				ltcp = connp->conn_tcp;
6884 		} else {
6885 			/* Allow tcp_bound_if listeners? */
6886 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6887 			    &tcp->tcp_ip6h->ip6_src, 0,
6888 			    tcp->tcp_connp->conn_zoneid, ipst);
6889 			if (connp != NULL)
6890 				ltcp = connp->conn_tcp;
6891 		}
6892 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6893 			tcp->tcp_state = TCPS_LISTEN;
6894 		} else if (old_state > TCPS_BOUND) {
6895 			tcp->tcp_conn_req_max = 0;
6896 			tcp->tcp_state = TCPS_BOUND;
6897 		}
6898 		if (ltcp != NULL)
6899 			CONN_DEC_REF(ltcp->tcp_connp);
6900 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6901 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6902 		} else if (old_state == TCPS_ESTABLISHED ||
6903 		    old_state == TCPS_CLOSE_WAIT) {
6904 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6905 		}
6906 
6907 		if (tcp->tcp_fused)
6908 			tcp_unfuse(tcp);
6909 
6910 		mutex_enter(&tcp->tcp_eager_lock);
6911 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6912 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6913 			tcp_eager_cleanup(tcp, 0);
6914 		}
6915 		mutex_exit(&tcp->tcp_eager_lock);
6916 
6917 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6918 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6919 
6920 		tcp_reinit(tcp);
6921 
6922 		if (old_state >= TCPS_ESTABLISHED) {
6923 			/* Send M_FLUSH according to TPI */
6924 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6925 		}
6926 		mp = mi_tpi_ok_ack_alloc(mp);
6927 		if (mp)
6928 			putnext(tcp->tcp_rq, mp);
6929 		return;
6930 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6931 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6932 		return;
6933 	}
6934 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6935 		/* Send M_FLUSH according to TPI */
6936 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6937 	}
6938 	mp = mi_tpi_ok_ack_alloc(mp);
6939 	if (mp)
6940 		putnext(tcp->tcp_rq, mp);
6941 }
6942 
6943 /*
6944  * Diagnostic routine used to return a string associated with the tcp state.
6945  * Note that if the caller does not supply a buffer, it will use an internal
6946  * static string.  This means that if multiple threads call this function at
6947  * the same time, output can be corrupted...  Note also that this function
6948  * does not check the size of the supplied buffer.  The caller has to make
6949  * sure that it is big enough.
6950  */
6951 static char *
6952 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6953 {
6954 	char		buf1[30];
6955 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6956 	char		*buf;
6957 	char		*cp;
6958 	in6_addr_t	local, remote;
6959 	char		local_addrbuf[INET6_ADDRSTRLEN];
6960 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6961 
6962 	if (sup_buf != NULL)
6963 		buf = sup_buf;
6964 	else
6965 		buf = priv_buf;
6966 
6967 	if (tcp == NULL)
6968 		return ("NULL_TCP");
6969 	switch (tcp->tcp_state) {
6970 	case TCPS_CLOSED:
6971 		cp = "TCP_CLOSED";
6972 		break;
6973 	case TCPS_IDLE:
6974 		cp = "TCP_IDLE";
6975 		break;
6976 	case TCPS_BOUND:
6977 		cp = "TCP_BOUND";
6978 		break;
6979 	case TCPS_LISTEN:
6980 		cp = "TCP_LISTEN";
6981 		break;
6982 	case TCPS_SYN_SENT:
6983 		cp = "TCP_SYN_SENT";
6984 		break;
6985 	case TCPS_SYN_RCVD:
6986 		cp = "TCP_SYN_RCVD";
6987 		break;
6988 	case TCPS_ESTABLISHED:
6989 		cp = "TCP_ESTABLISHED";
6990 		break;
6991 	case TCPS_CLOSE_WAIT:
6992 		cp = "TCP_CLOSE_WAIT";
6993 		break;
6994 	case TCPS_FIN_WAIT_1:
6995 		cp = "TCP_FIN_WAIT_1";
6996 		break;
6997 	case TCPS_CLOSING:
6998 		cp = "TCP_CLOSING";
6999 		break;
7000 	case TCPS_LAST_ACK:
7001 		cp = "TCP_LAST_ACK";
7002 		break;
7003 	case TCPS_FIN_WAIT_2:
7004 		cp = "TCP_FIN_WAIT_2";
7005 		break;
7006 	case TCPS_TIME_WAIT:
7007 		cp = "TCP_TIME_WAIT";
7008 		break;
7009 	default:
7010 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7011 		cp = buf1;
7012 		break;
7013 	}
7014 	switch (format) {
7015 	case DISP_ADDR_AND_PORT:
7016 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7017 			/*
7018 			 * Note that we use the remote address in the tcp_b
7019 			 * structure.  This means that it will print out
7020 			 * the real destination address, not the next hop's
7021 			 * address if source routing is used.
7022 			 */
7023 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7024 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7025 
7026 		} else {
7027 			local = tcp->tcp_ip_src_v6;
7028 			remote = tcp->tcp_remote_v6;
7029 		}
7030 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7031 		    sizeof (local_addrbuf));
7032 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7033 		    sizeof (remote_addrbuf));
7034 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7035 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7036 		    ntohs(tcp->tcp_fport), cp);
7037 		break;
7038 	case DISP_PORT_ONLY:
7039 	default:
7040 		(void) mi_sprintf(buf, "[%u, %u] %s",
7041 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7042 		break;
7043 	}
7044 
7045 	return (buf);
7046 }
7047 
7048 /*
7049  * Called via squeue to get on to eager's perimeter. It sends a
7050  * TH_RST if eager is in the fanout table. The listener wants the
7051  * eager to disappear either by means of tcp_eager_blowoff() or
7052  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7053  * called (via squeue) if the eager cannot be inserted in the
7054  * fanout table in tcp_conn_request().
7055  */
7056 /* ARGSUSED */
7057 void
7058 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7059 {
7060 	conn_t	*econnp = (conn_t *)arg;
7061 	tcp_t	*eager = econnp->conn_tcp;
7062 	tcp_t	*listener = eager->tcp_listener;
7063 	tcp_stack_t	*tcps = eager->tcp_tcps;
7064 
7065 	/*
7066 	 * We could be called because listener is closing. Since
7067 	 * the eager is using listener's queue's, its not safe.
7068 	 * Better use the default queue just to send the TH_RST
7069 	 * out.
7070 	 */
7071 	ASSERT(tcps->tcps_g_q != NULL);
7072 	eager->tcp_rq = tcps->tcps_g_q;
7073 	eager->tcp_wq = WR(tcps->tcps_g_q);
7074 
7075 	/*
7076 	 * An eager's conn_fanout will be NULL if it's a duplicate
7077 	 * for an existing 4-tuples in the conn fanout table.
7078 	 * We don't want to send an RST out in such case.
7079 	 */
7080 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7081 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7082 		    eager, eager->tcp_snxt, 0, TH_RST);
7083 	}
7084 
7085 	/* We are here because listener wants this eager gone */
7086 	if (listener != NULL) {
7087 		mutex_enter(&listener->tcp_eager_lock);
7088 		tcp_eager_unlink(eager);
7089 		if (eager->tcp_tconnind_started) {
7090 			/*
7091 			 * The eager has sent a conn_ind up to the
7092 			 * listener but listener decides to close
7093 			 * instead. We need to drop the extra ref
7094 			 * placed on eager in tcp_rput_data() before
7095 			 * sending the conn_ind to listener.
7096 			 */
7097 			CONN_DEC_REF(econnp);
7098 		}
7099 		mutex_exit(&listener->tcp_eager_lock);
7100 		CONN_DEC_REF(listener->tcp_connp);
7101 	}
7102 
7103 	if (eager->tcp_state > TCPS_BOUND)
7104 		tcp_close_detached(eager);
7105 }
7106 
7107 /*
7108  * Reset any eager connection hanging off this listener marked
7109  * with 'seqnum' and then reclaim it's resources.
7110  */
7111 static boolean_t
7112 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7113 {
7114 	tcp_t	*eager;
7115 	mblk_t 	*mp;
7116 	tcp_stack_t	*tcps = listener->tcp_tcps;
7117 
7118 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7119 	eager = listener;
7120 	mutex_enter(&listener->tcp_eager_lock);
7121 	do {
7122 		eager = eager->tcp_eager_next_q;
7123 		if (eager == NULL) {
7124 			mutex_exit(&listener->tcp_eager_lock);
7125 			return (B_FALSE);
7126 		}
7127 	} while (eager->tcp_conn_req_seqnum != seqnum);
7128 
7129 	if (eager->tcp_closemp_used) {
7130 		mutex_exit(&listener->tcp_eager_lock);
7131 		return (B_TRUE);
7132 	}
7133 	eager->tcp_closemp_used = B_TRUE;
7134 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7135 	CONN_INC_REF(eager->tcp_connp);
7136 	mutex_exit(&listener->tcp_eager_lock);
7137 	mp = &eager->tcp_closemp;
7138 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7139 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7140 	return (B_TRUE);
7141 }
7142 
7143 /*
7144  * Reset any eager connection hanging off this listener
7145  * and then reclaim it's resources.
7146  */
7147 static void
7148 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7149 {
7150 	tcp_t	*eager;
7151 	mblk_t	*mp;
7152 	tcp_stack_t	*tcps = listener->tcp_tcps;
7153 
7154 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7155 
7156 	if (!q0_only) {
7157 		/* First cleanup q */
7158 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7159 		eager = listener->tcp_eager_next_q;
7160 		while (eager != NULL) {
7161 			if (!eager->tcp_closemp_used) {
7162 				eager->tcp_closemp_used = B_TRUE;
7163 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7164 				CONN_INC_REF(eager->tcp_connp);
7165 				mp = &eager->tcp_closemp;
7166 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7167 				    tcp_eager_kill, eager->tcp_connp,
7168 				    SQTAG_TCP_EAGER_CLEANUP);
7169 			}
7170 			eager = eager->tcp_eager_next_q;
7171 		}
7172 	}
7173 	/* Then cleanup q0 */
7174 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7175 	eager = listener->tcp_eager_next_q0;
7176 	while (eager != listener) {
7177 		if (!eager->tcp_closemp_used) {
7178 			eager->tcp_closemp_used = B_TRUE;
7179 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7180 			CONN_INC_REF(eager->tcp_connp);
7181 			mp = &eager->tcp_closemp;
7182 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7183 			    tcp_eager_kill, eager->tcp_connp,
7184 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7185 		}
7186 		eager = eager->tcp_eager_next_q0;
7187 	}
7188 }
7189 
7190 /*
7191  * If we are an eager connection hanging off a listener that hasn't
7192  * formally accepted the connection yet, get off his list and blow off
7193  * any data that we have accumulated.
7194  */
7195 static void
7196 tcp_eager_unlink(tcp_t *tcp)
7197 {
7198 	tcp_t	*listener = tcp->tcp_listener;
7199 
7200 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7201 	ASSERT(listener != NULL);
7202 	if (tcp->tcp_eager_next_q0 != NULL) {
7203 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7204 
7205 		/* Remove the eager tcp from q0 */
7206 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7207 		    tcp->tcp_eager_prev_q0;
7208 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7209 		    tcp->tcp_eager_next_q0;
7210 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7211 		listener->tcp_conn_req_cnt_q0--;
7212 
7213 		tcp->tcp_eager_next_q0 = NULL;
7214 		tcp->tcp_eager_prev_q0 = NULL;
7215 
7216 		/*
7217 		 * Take the eager out, if it is in the list of droppable
7218 		 * eagers.
7219 		 */
7220 		MAKE_UNDROPPABLE(tcp);
7221 
7222 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7223 			/* we have timed out before */
7224 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7225 			listener->tcp_syn_rcvd_timeout--;
7226 		}
7227 	} else {
7228 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7229 		tcp_t	*prev = NULL;
7230 
7231 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7232 			if (tcpp[0] == tcp) {
7233 				if (listener->tcp_eager_last_q == tcp) {
7234 					/*
7235 					 * If we are unlinking the last
7236 					 * element on the list, adjust
7237 					 * tail pointer. Set tail pointer
7238 					 * to nil when list is empty.
7239 					 */
7240 					ASSERT(tcp->tcp_eager_next_q == NULL);
7241 					if (listener->tcp_eager_last_q ==
7242 					    listener->tcp_eager_next_q) {
7243 						listener->tcp_eager_last_q =
7244 						NULL;
7245 					} else {
7246 						/*
7247 						 * We won't get here if there
7248 						 * is only one eager in the
7249 						 * list.
7250 						 */
7251 						ASSERT(prev != NULL);
7252 						listener->tcp_eager_last_q =
7253 						    prev;
7254 					}
7255 				}
7256 				tcpp[0] = tcp->tcp_eager_next_q;
7257 				tcp->tcp_eager_next_q = NULL;
7258 				tcp->tcp_eager_last_q = NULL;
7259 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7260 				listener->tcp_conn_req_cnt_q--;
7261 				break;
7262 			}
7263 			prev = tcpp[0];
7264 		}
7265 	}
7266 	tcp->tcp_listener = NULL;
7267 }
7268 
7269 /* Shorthand to generate and send TPI error acks to our client */
7270 static void
7271 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7272 {
7273 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7274 		putnext(tcp->tcp_rq, mp);
7275 }
7276 
7277 /* Shorthand to generate and send TPI error acks to our client */
7278 static void
7279 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7280     int t_error, int sys_error)
7281 {
7282 	struct T_error_ack	*teackp;
7283 
7284 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7285 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7286 		teackp = (struct T_error_ack *)mp->b_rptr;
7287 		teackp->ERROR_prim = primitive;
7288 		teackp->TLI_error = t_error;
7289 		teackp->UNIX_error = sys_error;
7290 		putnext(tcp->tcp_rq, mp);
7291 	}
7292 }
7293 
7294 /*
7295  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7296  * but instead the code relies on:
7297  * - the fact that the address of the array and its size never changes
7298  * - the atomic assignment of the elements of the array
7299  */
7300 /* ARGSUSED */
7301 static int
7302 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7303 {
7304 	int i;
7305 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7306 
7307 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7308 		if (tcps->tcps_g_epriv_ports[i] != 0)
7309 			(void) mi_mpprintf(mp, "%d ",
7310 			    tcps->tcps_g_epriv_ports[i]);
7311 	}
7312 	return (0);
7313 }
7314 
7315 /*
7316  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7317  * threads from changing it at the same time.
7318  */
7319 /* ARGSUSED */
7320 static int
7321 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7322     cred_t *cr)
7323 {
7324 	long	new_value;
7325 	int	i;
7326 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7327 
7328 	/*
7329 	 * Fail the request if the new value does not lie within the
7330 	 * port number limits.
7331 	 */
7332 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7333 	    new_value <= 0 || new_value >= 65536) {
7334 		return (EINVAL);
7335 	}
7336 
7337 	mutex_enter(&tcps->tcps_epriv_port_lock);
7338 	/* Check if the value is already in the list */
7339 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7340 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7341 			mutex_exit(&tcps->tcps_epriv_port_lock);
7342 			return (EEXIST);
7343 		}
7344 	}
7345 	/* Find an empty slot */
7346 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7347 		if (tcps->tcps_g_epriv_ports[i] == 0)
7348 			break;
7349 	}
7350 	if (i == tcps->tcps_g_num_epriv_ports) {
7351 		mutex_exit(&tcps->tcps_epriv_port_lock);
7352 		return (EOVERFLOW);
7353 	}
7354 	/* Set the new value */
7355 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7356 	mutex_exit(&tcps->tcps_epriv_port_lock);
7357 	return (0);
7358 }
7359 
7360 /*
7361  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7362  * threads from changing it at the same time.
7363  */
7364 /* ARGSUSED */
7365 static int
7366 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7367     cred_t *cr)
7368 {
7369 	long	new_value;
7370 	int	i;
7371 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7372 
7373 	/*
7374 	 * Fail the request if the new value does not lie within the
7375 	 * port number limits.
7376 	 */
7377 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7378 	    new_value >= 65536) {
7379 		return (EINVAL);
7380 	}
7381 
7382 	mutex_enter(&tcps->tcps_epriv_port_lock);
7383 	/* Check that the value is already in the list */
7384 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7385 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7386 			break;
7387 	}
7388 	if (i == tcps->tcps_g_num_epriv_ports) {
7389 		mutex_exit(&tcps->tcps_epriv_port_lock);
7390 		return (ESRCH);
7391 	}
7392 	/* Clear the value */
7393 	tcps->tcps_g_epriv_ports[i] = 0;
7394 	mutex_exit(&tcps->tcps_epriv_port_lock);
7395 	return (0);
7396 }
7397 
7398 /* Return the TPI/TLI equivalent of our current tcp_state */
7399 static int
7400 tcp_tpistate(tcp_t *tcp)
7401 {
7402 	switch (tcp->tcp_state) {
7403 	case TCPS_IDLE:
7404 		return (TS_UNBND);
7405 	case TCPS_LISTEN:
7406 		/*
7407 		 * Return whether there are outstanding T_CONN_IND waiting
7408 		 * for the matching T_CONN_RES. Therefore don't count q0.
7409 		 */
7410 		if (tcp->tcp_conn_req_cnt_q > 0)
7411 			return (TS_WRES_CIND);
7412 		else
7413 			return (TS_IDLE);
7414 	case TCPS_BOUND:
7415 		return (TS_IDLE);
7416 	case TCPS_SYN_SENT:
7417 		return (TS_WCON_CREQ);
7418 	case TCPS_SYN_RCVD:
7419 		/*
7420 		 * Note: assumption: this has to the active open SYN_RCVD.
7421 		 * The passive instance is detached in SYN_RCVD stage of
7422 		 * incoming connection processing so we cannot get request
7423 		 * for T_info_ack on it.
7424 		 */
7425 		return (TS_WACK_CRES);
7426 	case TCPS_ESTABLISHED:
7427 		return (TS_DATA_XFER);
7428 	case TCPS_CLOSE_WAIT:
7429 		return (TS_WREQ_ORDREL);
7430 	case TCPS_FIN_WAIT_1:
7431 		return (TS_WIND_ORDREL);
7432 	case TCPS_FIN_WAIT_2:
7433 		return (TS_WIND_ORDREL);
7434 
7435 	case TCPS_CLOSING:
7436 	case TCPS_LAST_ACK:
7437 	case TCPS_TIME_WAIT:
7438 	case TCPS_CLOSED:
7439 		/*
7440 		 * Following TS_WACK_DREQ7 is a rendition of "not
7441 		 * yet TS_IDLE" TPI state. There is no best match to any
7442 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7443 		 * choose a value chosen that will map to TLI/XTI level
7444 		 * state of TSTATECHNG (state is process of changing) which
7445 		 * captures what this dummy state represents.
7446 		 */
7447 		return (TS_WACK_DREQ7);
7448 	default:
7449 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7450 		    tcp->tcp_state, tcp_display(tcp, NULL,
7451 		    DISP_PORT_ONLY));
7452 		return (TS_UNBND);
7453 	}
7454 }
7455 
7456 static void
7457 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7458 {
7459 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7460 
7461 	if (tcp->tcp_family == AF_INET6)
7462 		*tia = tcp_g_t_info_ack_v6;
7463 	else
7464 		*tia = tcp_g_t_info_ack;
7465 	tia->CURRENT_state = tcp_tpistate(tcp);
7466 	tia->OPT_size = tcp_max_optsize;
7467 	if (tcp->tcp_mss == 0) {
7468 		/* Not yet set - tcp_open does not set mss */
7469 		if (tcp->tcp_ipversion == IPV4_VERSION)
7470 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7471 		else
7472 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7473 	} else {
7474 		tia->TIDU_size = tcp->tcp_mss;
7475 	}
7476 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7477 }
7478 
7479 /*
7480  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7481  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7482  * tcp_g_t_info_ack.  The current state of the stream is copied from
7483  * tcp_state.
7484  */
7485 static void
7486 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7487 {
7488 	t_uscalar_t		cap_bits1;
7489 	struct T_capability_ack	*tcap;
7490 
7491 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7492 		freemsg(mp);
7493 		return;
7494 	}
7495 
7496 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7497 
7498 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7499 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7500 	if (mp == NULL)
7501 		return;
7502 
7503 	tcap = (struct T_capability_ack *)mp->b_rptr;
7504 	tcap->CAP_bits1 = 0;
7505 
7506 	if (cap_bits1 & TC1_INFO) {
7507 		tcp_copy_info(&tcap->INFO_ack, tcp);
7508 		tcap->CAP_bits1 |= TC1_INFO;
7509 	}
7510 
7511 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7512 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7513 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7514 	}
7515 
7516 	putnext(tcp->tcp_rq, mp);
7517 }
7518 
7519 /*
7520  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7521  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7522  * The current state of the stream is copied from tcp_state.
7523  */
7524 static void
7525 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7526 {
7527 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7528 	    T_INFO_ACK);
7529 	if (!mp) {
7530 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7531 		return;
7532 	}
7533 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7534 	putnext(tcp->tcp_rq, mp);
7535 }
7536 
7537 /* Respond to the TPI addr request */
7538 static void
7539 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7540 {
7541 	sin_t	*sin;
7542 	mblk_t	*ackmp;
7543 	struct T_addr_ack *taa;
7544 
7545 	/* Make it large enough for worst case */
7546 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7547 	    2 * sizeof (sin6_t), 1);
7548 	if (ackmp == NULL) {
7549 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7550 		return;
7551 	}
7552 
7553 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7554 		tcp_addr_req_ipv6(tcp, ackmp);
7555 		return;
7556 	}
7557 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7558 
7559 	bzero(taa, sizeof (struct T_addr_ack));
7560 	ackmp->b_wptr = (uchar_t *)&taa[1];
7561 
7562 	taa->PRIM_type = T_ADDR_ACK;
7563 	ackmp->b_datap->db_type = M_PCPROTO;
7564 
7565 	/*
7566 	 * Note: Following code assumes 32 bit alignment of basic
7567 	 * data structures like sin_t and struct T_addr_ack.
7568 	 */
7569 	if (tcp->tcp_state >= TCPS_BOUND) {
7570 		/*
7571 		 * Fill in local address
7572 		 */
7573 		taa->LOCADDR_length = sizeof (sin_t);
7574 		taa->LOCADDR_offset = sizeof (*taa);
7575 
7576 		sin = (sin_t *)&taa[1];
7577 
7578 		/* Fill zeroes and then intialize non-zero fields */
7579 		*sin = sin_null;
7580 
7581 		sin->sin_family = AF_INET;
7582 
7583 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7584 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7585 
7586 		ackmp->b_wptr = (uchar_t *)&sin[1];
7587 
7588 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7589 			/*
7590 			 * Fill in Remote address
7591 			 */
7592 			taa->REMADDR_length = sizeof (sin_t);
7593 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7594 						taa->LOCADDR_length);
7595 
7596 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7597 			*sin = sin_null;
7598 			sin->sin_family = AF_INET;
7599 			sin->sin_addr.s_addr = tcp->tcp_remote;
7600 			sin->sin_port = tcp->tcp_fport;
7601 
7602 			ackmp->b_wptr = (uchar_t *)&sin[1];
7603 		}
7604 	}
7605 	putnext(tcp->tcp_rq, ackmp);
7606 }
7607 
7608 /* Assumes that tcp_addr_req gets enough space and alignment */
7609 static void
7610 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7611 {
7612 	sin6_t	*sin6;
7613 	struct T_addr_ack *taa;
7614 
7615 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7616 	ASSERT(OK_32PTR(ackmp->b_rptr));
7617 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7618 	    2 * sizeof (sin6_t));
7619 
7620 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7621 
7622 	bzero(taa, sizeof (struct T_addr_ack));
7623 	ackmp->b_wptr = (uchar_t *)&taa[1];
7624 
7625 	taa->PRIM_type = T_ADDR_ACK;
7626 	ackmp->b_datap->db_type = M_PCPROTO;
7627 
7628 	/*
7629 	 * Note: Following code assumes 32 bit alignment of basic
7630 	 * data structures like sin6_t and struct T_addr_ack.
7631 	 */
7632 	if (tcp->tcp_state >= TCPS_BOUND) {
7633 		/*
7634 		 * Fill in local address
7635 		 */
7636 		taa->LOCADDR_length = sizeof (sin6_t);
7637 		taa->LOCADDR_offset = sizeof (*taa);
7638 
7639 		sin6 = (sin6_t *)&taa[1];
7640 		*sin6 = sin6_null;
7641 
7642 		sin6->sin6_family = AF_INET6;
7643 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7644 		sin6->sin6_port = tcp->tcp_lport;
7645 
7646 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7647 
7648 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7649 			/*
7650 			 * Fill in Remote address
7651 			 */
7652 			taa->REMADDR_length = sizeof (sin6_t);
7653 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7654 						taa->LOCADDR_length);
7655 
7656 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7657 			*sin6 = sin6_null;
7658 			sin6->sin6_family = AF_INET6;
7659 			sin6->sin6_flowinfo =
7660 			    tcp->tcp_ip6h->ip6_vcf &
7661 			    ~IPV6_VERS_AND_FLOW_MASK;
7662 			sin6->sin6_addr = tcp->tcp_remote_v6;
7663 			sin6->sin6_port = tcp->tcp_fport;
7664 
7665 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7666 		}
7667 	}
7668 	putnext(tcp->tcp_rq, ackmp);
7669 }
7670 
7671 /*
7672  * Handle reinitialization of a tcp structure.
7673  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7674  */
7675 static void
7676 tcp_reinit(tcp_t *tcp)
7677 {
7678 	mblk_t	*mp;
7679 	int 	err;
7680 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7681 
7682 	TCP_STAT(tcps, tcp_reinit_calls);
7683 
7684 	/* tcp_reinit should never be called for detached tcp_t's */
7685 	ASSERT(tcp->tcp_listener == NULL);
7686 	ASSERT((tcp->tcp_family == AF_INET &&
7687 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7688 	    (tcp->tcp_family == AF_INET6 &&
7689 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7690 	    tcp->tcp_ipversion == IPV6_VERSION)));
7691 
7692 	/* Cancel outstanding timers */
7693 	tcp_timers_stop(tcp);
7694 
7695 	/*
7696 	 * Reset everything in the state vector, after updating global
7697 	 * MIB data from instance counters.
7698 	 */
7699 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7700 	tcp->tcp_ibsegs = 0;
7701 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7702 	tcp->tcp_obsegs = 0;
7703 
7704 	tcp_close_mpp(&tcp->tcp_xmit_head);
7705 	if (tcp->tcp_snd_zcopy_aware)
7706 		tcp_zcopy_notify(tcp);
7707 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7708 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7709 	mutex_enter(&tcp->tcp_non_sq_lock);
7710 	if (tcp->tcp_flow_stopped &&
7711 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7712 		tcp_clrqfull(tcp);
7713 	}
7714 	mutex_exit(&tcp->tcp_non_sq_lock);
7715 	tcp_close_mpp(&tcp->tcp_reass_head);
7716 	tcp->tcp_reass_tail = NULL;
7717 	if (tcp->tcp_rcv_list != NULL) {
7718 		/* Free b_next chain */
7719 		tcp_close_mpp(&tcp->tcp_rcv_list);
7720 		tcp->tcp_rcv_last_head = NULL;
7721 		tcp->tcp_rcv_last_tail = NULL;
7722 		tcp->tcp_rcv_cnt = 0;
7723 	}
7724 	tcp->tcp_rcv_last_tail = NULL;
7725 
7726 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7727 		freemsg(mp);
7728 		tcp->tcp_urp_mp = NULL;
7729 	}
7730 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7731 		freemsg(mp);
7732 		tcp->tcp_urp_mark_mp = NULL;
7733 	}
7734 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7735 		freeb(tcp->tcp_fused_sigurg_mp);
7736 		tcp->tcp_fused_sigurg_mp = NULL;
7737 	}
7738 
7739 	/*
7740 	 * Following is a union with two members which are
7741 	 * identical types and size so the following cleanup
7742 	 * is enough.
7743 	 */
7744 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7745 
7746 	CL_INET_DISCONNECT(tcp);
7747 
7748 	/*
7749 	 * The connection can't be on the tcp_time_wait_head list
7750 	 * since it is not detached.
7751 	 */
7752 	ASSERT(tcp->tcp_time_wait_next == NULL);
7753 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7754 	ASSERT(tcp->tcp_time_wait_expire == 0);
7755 
7756 	if (tcp->tcp_kssl_pending) {
7757 		tcp->tcp_kssl_pending = B_FALSE;
7758 
7759 		/* Don't reset if the initialized by bind. */
7760 		if (tcp->tcp_kssl_ent != NULL) {
7761 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7762 			    KSSL_NO_PROXY);
7763 		}
7764 	}
7765 	if (tcp->tcp_kssl_ctx != NULL) {
7766 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7767 		tcp->tcp_kssl_ctx = NULL;
7768 	}
7769 
7770 	/*
7771 	 * Reset/preserve other values
7772 	 */
7773 	tcp_reinit_values(tcp);
7774 	ipcl_hash_remove(tcp->tcp_connp);
7775 	conn_delete_ire(tcp->tcp_connp, NULL);
7776 	tcp_ipsec_cleanup(tcp);
7777 
7778 	if (tcp->tcp_conn_req_max != 0) {
7779 		/*
7780 		 * This is the case when a TLI program uses the same
7781 		 * transport end point to accept a connection.  This
7782 		 * makes the TCP both a listener and acceptor.  When
7783 		 * this connection is closed, we need to set the state
7784 		 * back to TCPS_LISTEN.  Make sure that the eager list
7785 		 * is reinitialized.
7786 		 *
7787 		 * Note that this stream is still bound to the four
7788 		 * tuples of the previous connection in IP.  If a new
7789 		 * SYN with different foreign address comes in, IP will
7790 		 * not find it and will send it to the global queue.  In
7791 		 * the global queue, TCP will do a tcp_lookup_listener()
7792 		 * to find this stream.  This works because this stream
7793 		 * is only removed from connected hash.
7794 		 *
7795 		 */
7796 		tcp->tcp_state = TCPS_LISTEN;
7797 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7798 		tcp->tcp_eager_next_drop_q0 = tcp;
7799 		tcp->tcp_eager_prev_drop_q0 = tcp;
7800 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7801 		if (tcp->tcp_family == AF_INET6) {
7802 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7803 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7804 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7805 		} else {
7806 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7807 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7808 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7809 		}
7810 	} else {
7811 		tcp->tcp_state = TCPS_BOUND;
7812 	}
7813 
7814 	/*
7815 	 * Initialize to default values
7816 	 * Can't fail since enough header template space already allocated
7817 	 * at open().
7818 	 */
7819 	err = tcp_init_values(tcp);
7820 	ASSERT(err == 0);
7821 	/* Restore state in tcp_tcph */
7822 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7823 	if (tcp->tcp_ipversion == IPV4_VERSION)
7824 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7825 	else
7826 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7827 	/*
7828 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7829 	 * since the lookup funcs can only lookup on tcp_t
7830 	 */
7831 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7832 
7833 	ASSERT(tcp->tcp_ptpbhn != NULL);
7834 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7835 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7836 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7837 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7838 }
7839 
7840 /*
7841  * Force values to zero that need be zero.
7842  * Do not touch values asociated with the BOUND or LISTEN state
7843  * since the connection will end up in that state after the reinit.
7844  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7845  * structure!
7846  */
7847 static void
7848 tcp_reinit_values(tcp)
7849 	tcp_t *tcp;
7850 {
7851 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7852 
7853 #ifndef	lint
7854 #define	DONTCARE(x)
7855 #define	PRESERVE(x)
7856 #else
7857 #define	DONTCARE(x)	((x) = (x))
7858 #define	PRESERVE(x)	((x) = (x))
7859 #endif	/* lint */
7860 
7861 	PRESERVE(tcp->tcp_bind_hash);
7862 	PRESERVE(tcp->tcp_ptpbhn);
7863 	PRESERVE(tcp->tcp_acceptor_hash);
7864 	PRESERVE(tcp->tcp_ptpahn);
7865 
7866 	/* Should be ASSERT NULL on these with new code! */
7867 	ASSERT(tcp->tcp_time_wait_next == NULL);
7868 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7869 	ASSERT(tcp->tcp_time_wait_expire == 0);
7870 	PRESERVE(tcp->tcp_state);
7871 	PRESERVE(tcp->tcp_rq);
7872 	PRESERVE(tcp->tcp_wq);
7873 
7874 	ASSERT(tcp->tcp_xmit_head == NULL);
7875 	ASSERT(tcp->tcp_xmit_last == NULL);
7876 	ASSERT(tcp->tcp_unsent == 0);
7877 	ASSERT(tcp->tcp_xmit_tail == NULL);
7878 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7879 
7880 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7881 	tcp->tcp_suna = 0;			/* Displayed in mib */
7882 	tcp->tcp_swnd = 0;
7883 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7884 
7885 	ASSERT(tcp->tcp_ibsegs == 0);
7886 	ASSERT(tcp->tcp_obsegs == 0);
7887 
7888 	if (tcp->tcp_iphc != NULL) {
7889 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7890 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7891 	}
7892 
7893 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7894 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7895 	DONTCARE(tcp->tcp_ipha);
7896 	DONTCARE(tcp->tcp_ip6h);
7897 	DONTCARE(tcp->tcp_ip_hdr_len);
7898 	DONTCARE(tcp->tcp_tcph);
7899 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7900 	tcp->tcp_valid_bits = 0;
7901 
7902 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7903 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7904 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7905 	tcp->tcp_last_rcv_lbolt = 0;
7906 
7907 	tcp->tcp_init_cwnd = 0;
7908 
7909 	tcp->tcp_urp_last_valid = 0;
7910 	tcp->tcp_hard_binding = 0;
7911 	tcp->tcp_hard_bound = 0;
7912 	PRESERVE(tcp->tcp_cred);
7913 	PRESERVE(tcp->tcp_cpid);
7914 	PRESERVE(tcp->tcp_open_time);
7915 	PRESERVE(tcp->tcp_exclbind);
7916 
7917 	tcp->tcp_fin_acked = 0;
7918 	tcp->tcp_fin_rcvd = 0;
7919 	tcp->tcp_fin_sent = 0;
7920 	tcp->tcp_ordrel_done = 0;
7921 
7922 	tcp->tcp_debug = 0;
7923 	tcp->tcp_dontroute = 0;
7924 	tcp->tcp_broadcast = 0;
7925 
7926 	tcp->tcp_useloopback = 0;
7927 	tcp->tcp_reuseaddr = 0;
7928 	tcp->tcp_oobinline = 0;
7929 	tcp->tcp_dgram_errind = 0;
7930 
7931 	tcp->tcp_detached = 0;
7932 	tcp->tcp_bind_pending = 0;
7933 	tcp->tcp_unbind_pending = 0;
7934 	tcp->tcp_deferred_clean_death = 0;
7935 
7936 	tcp->tcp_snd_ws_ok = B_FALSE;
7937 	tcp->tcp_snd_ts_ok = B_FALSE;
7938 	tcp->tcp_linger = 0;
7939 	tcp->tcp_ka_enabled = 0;
7940 	tcp->tcp_zero_win_probe = 0;
7941 
7942 	tcp->tcp_loopback = 0;
7943 	tcp->tcp_localnet = 0;
7944 	tcp->tcp_syn_defense = 0;
7945 	tcp->tcp_set_timer = 0;
7946 
7947 	tcp->tcp_active_open = 0;
7948 	ASSERT(tcp->tcp_timeout == B_FALSE);
7949 	tcp->tcp_rexmit = B_FALSE;
7950 	tcp->tcp_xmit_zc_clean = B_FALSE;
7951 
7952 	tcp->tcp_snd_sack_ok = B_FALSE;
7953 	PRESERVE(tcp->tcp_recvdstaddr);
7954 	tcp->tcp_hwcksum = B_FALSE;
7955 
7956 	tcp->tcp_ire_ill_check_done = B_FALSE;
7957 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7958 
7959 	tcp->tcp_mdt = B_FALSE;
7960 	tcp->tcp_mdt_hdr_head = 0;
7961 	tcp->tcp_mdt_hdr_tail = 0;
7962 
7963 	tcp->tcp_conn_def_q0 = 0;
7964 	tcp->tcp_ip_forward_progress = B_FALSE;
7965 	tcp->tcp_anon_priv_bind = 0;
7966 	tcp->tcp_ecn_ok = B_FALSE;
7967 
7968 	tcp->tcp_cwr = B_FALSE;
7969 	tcp->tcp_ecn_echo_on = B_FALSE;
7970 
7971 	if (tcp->tcp_sack_info != NULL) {
7972 		if (tcp->tcp_notsack_list != NULL) {
7973 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7974 		}
7975 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7976 		tcp->tcp_sack_info = NULL;
7977 	}
7978 
7979 	tcp->tcp_rcv_ws = 0;
7980 	tcp->tcp_snd_ws = 0;
7981 	tcp->tcp_ts_recent = 0;
7982 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7983 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7984 	tcp->tcp_if_mtu = 0;
7985 
7986 	ASSERT(tcp->tcp_reass_head == NULL);
7987 	ASSERT(tcp->tcp_reass_tail == NULL);
7988 
7989 	tcp->tcp_cwnd_cnt = 0;
7990 
7991 	ASSERT(tcp->tcp_rcv_list == NULL);
7992 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7993 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7994 	ASSERT(tcp->tcp_rcv_cnt == 0);
7995 
7996 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7997 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7998 	tcp->tcp_csuna = 0;
7999 
8000 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8001 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8002 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8003 	tcp->tcp_rtt_update = 0;
8004 
8005 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8006 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8007 
8008 	tcp->tcp_rack = 0;			/* Displayed in mib */
8009 	tcp->tcp_rack_cnt = 0;
8010 	tcp->tcp_rack_cur_max = 0;
8011 	tcp->tcp_rack_abs_max = 0;
8012 
8013 	tcp->tcp_max_swnd = 0;
8014 
8015 	ASSERT(tcp->tcp_listener == NULL);
8016 
8017 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8018 
8019 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8020 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8021 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8022 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8023 
8024 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8025 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8026 	PRESERVE(tcp->tcp_conn_req_max);
8027 	PRESERVE(tcp->tcp_conn_req_seqnum);
8028 
8029 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8030 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8031 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8032 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8033 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8034 
8035 	tcp->tcp_lingertime = 0;
8036 
8037 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8038 	ASSERT(tcp->tcp_urp_mp == NULL);
8039 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8040 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8041 
8042 	ASSERT(tcp->tcp_eager_next_q == NULL);
8043 	ASSERT(tcp->tcp_eager_last_q == NULL);
8044 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8045 	    tcp->tcp_eager_prev_q0 == NULL) ||
8046 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8047 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8048 
8049 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8050 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8051 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8052 
8053 	tcp->tcp_client_errno = 0;
8054 
8055 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8056 
8057 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8058 
8059 	PRESERVE(tcp->tcp_bound_source_v6);
8060 	tcp->tcp_last_sent_len = 0;
8061 	tcp->tcp_dupack_cnt = 0;
8062 
8063 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8064 	PRESERVE(tcp->tcp_lport);
8065 
8066 	PRESERVE(tcp->tcp_acceptor_lockp);
8067 
8068 	ASSERT(tcp->tcp_ordrelid == 0);
8069 	PRESERVE(tcp->tcp_acceptor_id);
8070 	DONTCARE(tcp->tcp_ipsec_overhead);
8071 
8072 	/*
8073 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8074 	 * in tcp structure and now tracing), Re-initialize all
8075 	 * members of tcp_traceinfo.
8076 	 */
8077 	if (tcp->tcp_tracebuf != NULL) {
8078 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8079 	}
8080 
8081 	PRESERVE(tcp->tcp_family);
8082 	if (tcp->tcp_family == AF_INET6) {
8083 		tcp->tcp_ipversion = IPV6_VERSION;
8084 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8085 	} else {
8086 		tcp->tcp_ipversion = IPV4_VERSION;
8087 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8088 	}
8089 
8090 	tcp->tcp_bound_if = 0;
8091 	tcp->tcp_ipv6_recvancillary = 0;
8092 	tcp->tcp_recvifindex = 0;
8093 	tcp->tcp_recvhops = 0;
8094 	tcp->tcp_closed = 0;
8095 	tcp->tcp_cleandeathtag = 0;
8096 	if (tcp->tcp_hopopts != NULL) {
8097 		mi_free(tcp->tcp_hopopts);
8098 		tcp->tcp_hopopts = NULL;
8099 		tcp->tcp_hopoptslen = 0;
8100 	}
8101 	ASSERT(tcp->tcp_hopoptslen == 0);
8102 	if (tcp->tcp_dstopts != NULL) {
8103 		mi_free(tcp->tcp_dstopts);
8104 		tcp->tcp_dstopts = NULL;
8105 		tcp->tcp_dstoptslen = 0;
8106 	}
8107 	ASSERT(tcp->tcp_dstoptslen == 0);
8108 	if (tcp->tcp_rtdstopts != NULL) {
8109 		mi_free(tcp->tcp_rtdstopts);
8110 		tcp->tcp_rtdstopts = NULL;
8111 		tcp->tcp_rtdstoptslen = 0;
8112 	}
8113 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8114 	if (tcp->tcp_rthdr != NULL) {
8115 		mi_free(tcp->tcp_rthdr);
8116 		tcp->tcp_rthdr = NULL;
8117 		tcp->tcp_rthdrlen = 0;
8118 	}
8119 	ASSERT(tcp->tcp_rthdrlen == 0);
8120 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8121 
8122 	/* Reset fusion-related fields */
8123 	tcp->tcp_fused = B_FALSE;
8124 	tcp->tcp_unfusable = B_FALSE;
8125 	tcp->tcp_fused_sigurg = B_FALSE;
8126 	tcp->tcp_direct_sockfs = B_FALSE;
8127 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8128 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8129 	tcp->tcp_loopback_peer = NULL;
8130 	tcp->tcp_fuse_rcv_hiwater = 0;
8131 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8132 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8133 
8134 	tcp->tcp_lso = B_FALSE;
8135 
8136 	tcp->tcp_in_ack_unsent = 0;
8137 	tcp->tcp_cork = B_FALSE;
8138 	tcp->tcp_tconnind_started = B_FALSE;
8139 
8140 	PRESERVE(tcp->tcp_squeue_bytes);
8141 
8142 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8143 	ASSERT(!tcp->tcp_kssl_pending);
8144 	PRESERVE(tcp->tcp_kssl_ent);
8145 
8146 	tcp->tcp_closemp_used = B_FALSE;
8147 
8148 #ifdef DEBUG
8149 	DONTCARE(tcp->tcmp_stk[0]);
8150 #endif
8151 
8152 
8153 #undef	DONTCARE
8154 #undef	PRESERVE
8155 }
8156 
8157 /*
8158  * Allocate necessary resources and initialize state vector.
8159  * Guaranteed not to fail so that when an error is returned,
8160  * the caller doesn't need to do any additional cleanup.
8161  */
8162 int
8163 tcp_init(tcp_t *tcp, queue_t *q)
8164 {
8165 	int	err;
8166 
8167 	tcp->tcp_rq = q;
8168 	tcp->tcp_wq = WR(q);
8169 	tcp->tcp_state = TCPS_IDLE;
8170 	if ((err = tcp_init_values(tcp)) != 0)
8171 		tcp_timers_stop(tcp);
8172 	return (err);
8173 }
8174 
8175 static int
8176 tcp_init_values(tcp_t *tcp)
8177 {
8178 	int	err;
8179 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8180 
8181 	ASSERT((tcp->tcp_family == AF_INET &&
8182 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8183 	    (tcp->tcp_family == AF_INET6 &&
8184 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8185 	    tcp->tcp_ipversion == IPV6_VERSION)));
8186 
8187 	/*
8188 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8189 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8190 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8191 	 * during first few transmissions of a connection as seen in slow
8192 	 * links.
8193 	 */
8194 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8195 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8196 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8197 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8198 	    tcps->tcps_conn_grace_period;
8199 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8200 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8201 	tcp->tcp_timer_backoff = 0;
8202 	tcp->tcp_ms_we_have_waited = 0;
8203 	tcp->tcp_last_recv_time = lbolt;
8204 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8205 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8206 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8207 
8208 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8209 
8210 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8211 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8212 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8213 	/*
8214 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8215 	 * passive open.
8216 	 */
8217 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8218 
8219 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8220 
8221 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8222 
8223 	tcp->tcp_mdt_hdr_head = 0;
8224 	tcp->tcp_mdt_hdr_tail = 0;
8225 
8226 	/* Reset fusion-related fields */
8227 	tcp->tcp_fused = B_FALSE;
8228 	tcp->tcp_unfusable = B_FALSE;
8229 	tcp->tcp_fused_sigurg = B_FALSE;
8230 	tcp->tcp_direct_sockfs = B_FALSE;
8231 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8232 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8233 	tcp->tcp_loopback_peer = NULL;
8234 	tcp->tcp_fuse_rcv_hiwater = 0;
8235 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8236 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8237 
8238 	/* Initialize the header template */
8239 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8240 		err = tcp_header_init_ipv4(tcp);
8241 	} else {
8242 		err = tcp_header_init_ipv6(tcp);
8243 	}
8244 	if (err)
8245 		return (err);
8246 
8247 	/*
8248 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8249 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8250 	 */
8251 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8252 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8253 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8254 
8255 	tcp->tcp_cork = B_FALSE;
8256 	/*
8257 	 * Init the tcp_debug option.  This value determines whether TCP
8258 	 * calls strlog() to print out debug messages.  Doing this
8259 	 * initialization here means that this value is not inherited thru
8260 	 * tcp_reinit().
8261 	 */
8262 	tcp->tcp_debug = tcps->tcps_dbg;
8263 
8264 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8265 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8266 
8267 	return (0);
8268 }
8269 
8270 /*
8271  * Initialize the IPv4 header. Loses any record of any IP options.
8272  */
8273 static int
8274 tcp_header_init_ipv4(tcp_t *tcp)
8275 {
8276 	tcph_t		*tcph;
8277 	uint32_t	sum;
8278 	conn_t		*connp;
8279 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8280 
8281 	/*
8282 	 * This is a simple initialization. If there's
8283 	 * already a template, it should never be too small,
8284 	 * so reuse it.  Otherwise, allocate space for the new one.
8285 	 */
8286 	if (tcp->tcp_iphc == NULL) {
8287 		ASSERT(tcp->tcp_iphc_len == 0);
8288 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8289 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8290 		if (tcp->tcp_iphc == NULL) {
8291 			tcp->tcp_iphc_len = 0;
8292 			return (ENOMEM);
8293 		}
8294 	}
8295 
8296 	/* options are gone; may need a new label */
8297 	connp = tcp->tcp_connp;
8298 	connp->conn_mlp_type = mlptSingle;
8299 	connp->conn_ulp_labeled = !is_system_labeled();
8300 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8301 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8302 	tcp->tcp_ip6h = NULL;
8303 	tcp->tcp_ipversion = IPV4_VERSION;
8304 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8305 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8306 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8307 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8308 	tcp->tcp_ipha->ipha_version_and_hdr_length
8309 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8310 	tcp->tcp_ipha->ipha_ident = 0;
8311 
8312 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8313 	tcp->tcp_tos = 0;
8314 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8315 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8316 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8317 
8318 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8319 	tcp->tcp_tcph = tcph;
8320 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8321 	/*
8322 	 * IP wants our header length in the checksum field to
8323 	 * allow it to perform a single pseudo-header+checksum
8324 	 * calculation on behalf of TCP.
8325 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8326 	 */
8327 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8328 	sum = (sum >> 16) + (sum & 0xFFFF);
8329 	U16_TO_ABE16(sum, tcph->th_sum);
8330 	return (0);
8331 }
8332 
8333 /*
8334  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8335  */
8336 static int
8337 tcp_header_init_ipv6(tcp_t *tcp)
8338 {
8339 	tcph_t	*tcph;
8340 	uint32_t	sum;
8341 	conn_t	*connp;
8342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8343 
8344 	/*
8345 	 * This is a simple initialization. If there's
8346 	 * already a template, it should never be too small,
8347 	 * so reuse it. Otherwise, allocate space for the new one.
8348 	 * Ensure that there is enough space to "downgrade" the tcp_t
8349 	 * to an IPv4 tcp_t. This requires having space for a full load
8350 	 * of IPv4 options, as well as a full load of TCP options
8351 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8352 	 * than a v6 header and a TCP header with a full load of TCP options
8353 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8354 	 * We want to avoid reallocation in the "downgraded" case when
8355 	 * processing outbound IPv4 options.
8356 	 */
8357 	if (tcp->tcp_iphc == NULL) {
8358 		ASSERT(tcp->tcp_iphc_len == 0);
8359 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8360 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8361 		if (tcp->tcp_iphc == NULL) {
8362 			tcp->tcp_iphc_len = 0;
8363 			return (ENOMEM);
8364 		}
8365 	}
8366 
8367 	/* options are gone; may need a new label */
8368 	connp = tcp->tcp_connp;
8369 	connp->conn_mlp_type = mlptSingle;
8370 	connp->conn_ulp_labeled = !is_system_labeled();
8371 
8372 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8373 	tcp->tcp_ipversion = IPV6_VERSION;
8374 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8375 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8376 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8377 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8378 	tcp->tcp_ipha = NULL;
8379 
8380 	/* Initialize the header template */
8381 
8382 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8383 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8384 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8385 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8386 
8387 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8388 	tcp->tcp_tcph = tcph;
8389 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8390 	/*
8391 	 * IP wants our header length in the checksum field to
8392 	 * allow it to perform a single psuedo-header+checksum
8393 	 * calculation on behalf of TCP.
8394 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8395 	 */
8396 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8397 	sum = (sum >> 16) + (sum & 0xFFFF);
8398 	U16_TO_ABE16(sum, tcph->th_sum);
8399 	return (0);
8400 }
8401 
8402 /* At minimum we need 8 bytes in the TCP header for the lookup */
8403 #define	ICMP_MIN_TCP_HDR	8
8404 
8405 /*
8406  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8407  * passed up by IP. The message is always received on the correct tcp_t.
8408  * Assumes that IP has pulled up everything up to and including the ICMP header.
8409  */
8410 void
8411 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8412 {
8413 	icmph_t *icmph;
8414 	ipha_t	*ipha;
8415 	int	iph_hdr_length;
8416 	tcph_t	*tcph;
8417 	boolean_t ipsec_mctl = B_FALSE;
8418 	boolean_t secure;
8419 	mblk_t *first_mp = mp;
8420 	uint32_t new_mss;
8421 	uint32_t ratio;
8422 	size_t mp_size = MBLKL(mp);
8423 	uint32_t seg_seq;
8424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8425 
8426 	/* Assume IP provides aligned packets - otherwise toss */
8427 	if (!OK_32PTR(mp->b_rptr)) {
8428 		freemsg(mp);
8429 		return;
8430 	}
8431 
8432 	/*
8433 	 * Since ICMP errors are normal data marked with M_CTL when sent
8434 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8435 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8436 	 */
8437 	if ((mp_size == sizeof (ipsec_info_t)) &&
8438 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8439 		ASSERT(mp->b_cont != NULL);
8440 		mp = mp->b_cont;
8441 		/* IP should have done this */
8442 		ASSERT(OK_32PTR(mp->b_rptr));
8443 		mp_size = MBLKL(mp);
8444 		ipsec_mctl = B_TRUE;
8445 	}
8446 
8447 	/*
8448 	 * Verify that we have a complete outer IP header. If not, drop it.
8449 	 */
8450 	if (mp_size < sizeof (ipha_t)) {
8451 noticmpv4:
8452 		freemsg(first_mp);
8453 		return;
8454 	}
8455 
8456 	ipha = (ipha_t *)mp->b_rptr;
8457 	/*
8458 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8459 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8460 	 */
8461 	switch (IPH_HDR_VERSION(ipha)) {
8462 	case IPV6_VERSION:
8463 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8464 		return;
8465 	case IPV4_VERSION:
8466 		break;
8467 	default:
8468 		goto noticmpv4;
8469 	}
8470 
8471 	/* Skip past the outer IP and ICMP headers */
8472 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8473 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8474 	/*
8475 	 * If we don't have the correct outer IP header length or if the ULP
8476 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8477 	 * send it upstream.
8478 	 */
8479 	if (iph_hdr_length < sizeof (ipha_t) ||
8480 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8481 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8482 		goto noticmpv4;
8483 	}
8484 	ipha = (ipha_t *)&icmph[1];
8485 
8486 	/* Skip past the inner IP and find the ULP header */
8487 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8488 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8489 	/*
8490 	 * If we don't have the correct inner IP header length or if the ULP
8491 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8492 	 * bytes of TCP header, drop it.
8493 	 */
8494 	if (iph_hdr_length < sizeof (ipha_t) ||
8495 	    ipha->ipha_protocol != IPPROTO_TCP ||
8496 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8497 		goto noticmpv4;
8498 	}
8499 
8500 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8501 		if (ipsec_mctl) {
8502 			secure = ipsec_in_is_secure(first_mp);
8503 		} else {
8504 			secure = B_FALSE;
8505 		}
8506 		if (secure) {
8507 			/*
8508 			 * If we are willing to accept this in clear
8509 			 * we don't have to verify policy.
8510 			 */
8511 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8512 				if (!tcp_check_policy(tcp, first_mp,
8513 				    ipha, NULL, secure, ipsec_mctl)) {
8514 					/*
8515 					 * tcp_check_policy called
8516 					 * ip_drop_packet() on failure.
8517 					 */
8518 					return;
8519 				}
8520 			}
8521 		}
8522 	} else if (ipsec_mctl) {
8523 		/*
8524 		 * This is a hard_bound connection. IP has already
8525 		 * verified policy. We don't have to do it again.
8526 		 */
8527 		freeb(first_mp);
8528 		first_mp = mp;
8529 		ipsec_mctl = B_FALSE;
8530 	}
8531 
8532 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8533 	/*
8534 	 * TCP SHOULD check that the TCP sequence number contained in
8535 	 * payload of the ICMP error message is within the range
8536 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8537 	 */
8538 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8539 		/*
8540 		 * If the ICMP message is bogus, should we kill the
8541 		 * connection, or should we just drop the bogus ICMP
8542 		 * message? It would probably make more sense to just
8543 		 * drop the message so that if this one managed to get
8544 		 * in, the real connection should not suffer.
8545 		 */
8546 		goto noticmpv4;
8547 	}
8548 
8549 	switch (icmph->icmph_type) {
8550 	case ICMP_DEST_UNREACHABLE:
8551 		switch (icmph->icmph_code) {
8552 		case ICMP_FRAGMENTATION_NEEDED:
8553 			/*
8554 			 * Reduce the MSS based on the new MTU.  This will
8555 			 * eliminate any fragmentation locally.
8556 			 * N.B.  There may well be some funny side-effects on
8557 			 * the local send policy and the remote receive policy.
8558 			 * Pending further research, we provide
8559 			 * tcp_ignore_path_mtu just in case this proves
8560 			 * disastrous somewhere.
8561 			 *
8562 			 * After updating the MSS, retransmit part of the
8563 			 * dropped segment using the new mss by calling
8564 			 * tcp_wput_data().  Need to adjust all those
8565 			 * params to make sure tcp_wput_data() work properly.
8566 			 */
8567 			if (tcps->tcps_ignore_path_mtu)
8568 				break;
8569 
8570 			/*
8571 			 * Decrease the MSS by time stamp options
8572 			 * IP options and IPSEC options. tcp_hdr_len
8573 			 * includes time stamp option and IP option
8574 			 * length.
8575 			 */
8576 
8577 			new_mss = ntohs(icmph->icmph_du_mtu) -
8578 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8579 
8580 			/*
8581 			 * Only update the MSS if the new one is
8582 			 * smaller than the previous one.  This is
8583 			 * to avoid problems when getting multiple
8584 			 * ICMP errors for the same MTU.
8585 			 */
8586 			if (new_mss >= tcp->tcp_mss)
8587 				break;
8588 
8589 			/*
8590 			 * Stop doing PMTU if new_mss is less than 68
8591 			 * or less than tcp_mss_min.
8592 			 * The value 68 comes from rfc 1191.
8593 			 */
8594 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8595 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8596 				    0;
8597 
8598 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8599 			ASSERT(ratio >= 1);
8600 			tcp_mss_set(tcp, new_mss, B_TRUE);
8601 
8602 			/*
8603 			 * Make sure we have something to
8604 			 * send.
8605 			 */
8606 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8607 			    (tcp->tcp_xmit_head != NULL)) {
8608 				/*
8609 				 * Shrink tcp_cwnd in
8610 				 * proportion to the old MSS/new MSS.
8611 				 */
8612 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8613 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8614 				    (tcp->tcp_unsent == 0)) {
8615 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8616 				} else {
8617 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8618 				}
8619 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8620 				tcp->tcp_rexmit = B_TRUE;
8621 				tcp->tcp_dupack_cnt = 0;
8622 				tcp->tcp_snd_burst = TCP_CWND_SS;
8623 				tcp_ss_rexmit(tcp);
8624 			}
8625 			break;
8626 		case ICMP_PORT_UNREACHABLE:
8627 		case ICMP_PROTOCOL_UNREACHABLE:
8628 			switch (tcp->tcp_state) {
8629 			case TCPS_SYN_SENT:
8630 			case TCPS_SYN_RCVD:
8631 				/*
8632 				 * ICMP can snipe away incipient
8633 				 * TCP connections as long as
8634 				 * seq number is same as initial
8635 				 * send seq number.
8636 				 */
8637 				if (seg_seq == tcp->tcp_iss) {
8638 					(void) tcp_clean_death(tcp,
8639 					    ECONNREFUSED, 6);
8640 				}
8641 				break;
8642 			}
8643 			break;
8644 		case ICMP_HOST_UNREACHABLE:
8645 		case ICMP_NET_UNREACHABLE:
8646 			/* Record the error in case we finally time out. */
8647 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8648 				tcp->tcp_client_errno = EHOSTUNREACH;
8649 			else
8650 				tcp->tcp_client_errno = ENETUNREACH;
8651 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8652 				if (tcp->tcp_listener != NULL &&
8653 				    tcp->tcp_listener->tcp_syn_defense) {
8654 					/*
8655 					 * Ditch the half-open connection if we
8656 					 * suspect a SYN attack is under way.
8657 					 */
8658 					tcp_ip_ire_mark_advice(tcp);
8659 					(void) tcp_clean_death(tcp,
8660 					    tcp->tcp_client_errno, 7);
8661 				}
8662 			}
8663 			break;
8664 		default:
8665 			break;
8666 		}
8667 		break;
8668 	case ICMP_SOURCE_QUENCH: {
8669 		/*
8670 		 * use a global boolean to control
8671 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8672 		 * The default is false.
8673 		 */
8674 		if (tcp_icmp_source_quench) {
8675 			/*
8676 			 * Reduce the sending rate as if we got a
8677 			 * retransmit timeout
8678 			 */
8679 			uint32_t npkt;
8680 
8681 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8682 			    tcp->tcp_mss;
8683 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8684 			tcp->tcp_cwnd = tcp->tcp_mss;
8685 			tcp->tcp_cwnd_cnt = 0;
8686 		}
8687 		break;
8688 	}
8689 	}
8690 	freemsg(first_mp);
8691 }
8692 
8693 /*
8694  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8695  * error messages passed up by IP.
8696  * Assumes that IP has pulled up all the extension headers as well
8697  * as the ICMPv6 header.
8698  */
8699 static void
8700 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8701 {
8702 	icmp6_t *icmp6;
8703 	ip6_t	*ip6h;
8704 	uint16_t	iph_hdr_length;
8705 	tcpha_t	*tcpha;
8706 	uint8_t	*nexthdrp;
8707 	uint32_t new_mss;
8708 	uint32_t ratio;
8709 	boolean_t secure;
8710 	mblk_t *first_mp = mp;
8711 	size_t mp_size;
8712 	uint32_t seg_seq;
8713 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8714 
8715 	/*
8716 	 * The caller has determined if this is an IPSEC_IN packet and
8717 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8718 	 */
8719 	if (ipsec_mctl)
8720 		mp = mp->b_cont;
8721 
8722 	mp_size = MBLKL(mp);
8723 
8724 	/*
8725 	 * Verify that we have a complete IP header. If not, send it upstream.
8726 	 */
8727 	if (mp_size < sizeof (ip6_t)) {
8728 noticmpv6:
8729 		freemsg(first_mp);
8730 		return;
8731 	}
8732 
8733 	/*
8734 	 * Verify this is an ICMPV6 packet, else send it upstream.
8735 	 */
8736 	ip6h = (ip6_t *)mp->b_rptr;
8737 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8738 		iph_hdr_length = IPV6_HDR_LEN;
8739 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8740 	    &nexthdrp) ||
8741 	    *nexthdrp != IPPROTO_ICMPV6) {
8742 		goto noticmpv6;
8743 	}
8744 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8745 	ip6h = (ip6_t *)&icmp6[1];
8746 	/*
8747 	 * Verify if we have a complete ICMP and inner IP header.
8748 	 */
8749 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8750 		goto noticmpv6;
8751 
8752 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8753 		goto noticmpv6;
8754 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8755 	/*
8756 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8757 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8758 	 * packet.
8759 	 */
8760 	if ((*nexthdrp != IPPROTO_TCP) ||
8761 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8762 		goto noticmpv6;
8763 	}
8764 
8765 	/*
8766 	 * ICMP errors come on the right queue or come on
8767 	 * listener/global queue for detached connections and
8768 	 * get switched to the right queue. If it comes on the
8769 	 * right queue, policy check has already been done by IP
8770 	 * and thus free the first_mp without verifying the policy.
8771 	 * If it has come for a non-hard bound connection, we need
8772 	 * to verify policy as IP may not have done it.
8773 	 */
8774 	if (!tcp->tcp_hard_bound) {
8775 		if (ipsec_mctl) {
8776 			secure = ipsec_in_is_secure(first_mp);
8777 		} else {
8778 			secure = B_FALSE;
8779 		}
8780 		if (secure) {
8781 			/*
8782 			 * If we are willing to accept this in clear
8783 			 * we don't have to verify policy.
8784 			 */
8785 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8786 				if (!tcp_check_policy(tcp, first_mp,
8787 				    NULL, ip6h, secure, ipsec_mctl)) {
8788 					/*
8789 					 * tcp_check_policy called
8790 					 * ip_drop_packet() on failure.
8791 					 */
8792 					return;
8793 				}
8794 			}
8795 		}
8796 	} else if (ipsec_mctl) {
8797 		/*
8798 		 * This is a hard_bound connection. IP has already
8799 		 * verified policy. We don't have to do it again.
8800 		 */
8801 		freeb(first_mp);
8802 		first_mp = mp;
8803 		ipsec_mctl = B_FALSE;
8804 	}
8805 
8806 	seg_seq = ntohl(tcpha->tha_seq);
8807 	/*
8808 	 * TCP SHOULD check that the TCP sequence number contained in
8809 	 * payload of the ICMP error message is within the range
8810 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8811 	 */
8812 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8813 		/*
8814 		 * If the ICMP message is bogus, should we kill the
8815 		 * connection, or should we just drop the bogus ICMP
8816 		 * message? It would probably make more sense to just
8817 		 * drop the message so that if this one managed to get
8818 		 * in, the real connection should not suffer.
8819 		 */
8820 		goto noticmpv6;
8821 	}
8822 
8823 	switch (icmp6->icmp6_type) {
8824 	case ICMP6_PACKET_TOO_BIG:
8825 		/*
8826 		 * Reduce the MSS based on the new MTU.  This will
8827 		 * eliminate any fragmentation locally.
8828 		 * N.B.  There may well be some funny side-effects on
8829 		 * the local send policy and the remote receive policy.
8830 		 * Pending further research, we provide
8831 		 * tcp_ignore_path_mtu just in case this proves
8832 		 * disastrous somewhere.
8833 		 *
8834 		 * After updating the MSS, retransmit part of the
8835 		 * dropped segment using the new mss by calling
8836 		 * tcp_wput_data().  Need to adjust all those
8837 		 * params to make sure tcp_wput_data() work properly.
8838 		 */
8839 		if (tcps->tcps_ignore_path_mtu)
8840 			break;
8841 
8842 		/*
8843 		 * Decrease the MSS by time stamp options
8844 		 * IP options and IPSEC options. tcp_hdr_len
8845 		 * includes time stamp option and IP option
8846 		 * length.
8847 		 */
8848 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8849 			    tcp->tcp_ipsec_overhead;
8850 
8851 		/*
8852 		 * Only update the MSS if the new one is
8853 		 * smaller than the previous one.  This is
8854 		 * to avoid problems when getting multiple
8855 		 * ICMP errors for the same MTU.
8856 		 */
8857 		if (new_mss >= tcp->tcp_mss)
8858 			break;
8859 
8860 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8861 		ASSERT(ratio >= 1);
8862 		tcp_mss_set(tcp, new_mss, B_TRUE);
8863 
8864 		/*
8865 		 * Make sure we have something to
8866 		 * send.
8867 		 */
8868 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8869 		    (tcp->tcp_xmit_head != NULL)) {
8870 			/*
8871 			 * Shrink tcp_cwnd in
8872 			 * proportion to the old MSS/new MSS.
8873 			 */
8874 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8875 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8876 			    (tcp->tcp_unsent == 0)) {
8877 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8878 			} else {
8879 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8880 			}
8881 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8882 			tcp->tcp_rexmit = B_TRUE;
8883 			tcp->tcp_dupack_cnt = 0;
8884 			tcp->tcp_snd_burst = TCP_CWND_SS;
8885 			tcp_ss_rexmit(tcp);
8886 		}
8887 		break;
8888 
8889 	case ICMP6_DST_UNREACH:
8890 		switch (icmp6->icmp6_code) {
8891 		case ICMP6_DST_UNREACH_NOPORT:
8892 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8893 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8894 			    (seg_seq == tcp->tcp_iss)) {
8895 				(void) tcp_clean_death(tcp,
8896 				    ECONNREFUSED, 8);
8897 			}
8898 			break;
8899 
8900 		case ICMP6_DST_UNREACH_ADMIN:
8901 		case ICMP6_DST_UNREACH_NOROUTE:
8902 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8903 		case ICMP6_DST_UNREACH_ADDR:
8904 			/* Record the error in case we finally time out. */
8905 			tcp->tcp_client_errno = EHOSTUNREACH;
8906 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8907 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8908 			    (seg_seq == tcp->tcp_iss)) {
8909 				if (tcp->tcp_listener != NULL &&
8910 				    tcp->tcp_listener->tcp_syn_defense) {
8911 					/*
8912 					 * Ditch the half-open connection if we
8913 					 * suspect a SYN attack is under way.
8914 					 */
8915 					tcp_ip_ire_mark_advice(tcp);
8916 					(void) tcp_clean_death(tcp,
8917 					    tcp->tcp_client_errno, 9);
8918 				}
8919 			}
8920 
8921 
8922 			break;
8923 		default:
8924 			break;
8925 		}
8926 		break;
8927 
8928 	case ICMP6_PARAM_PROB:
8929 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8930 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8931 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8932 		    (uchar_t *)nexthdrp) {
8933 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8934 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8935 				(void) tcp_clean_death(tcp,
8936 				    ECONNREFUSED, 10);
8937 			}
8938 			break;
8939 		}
8940 		break;
8941 
8942 	case ICMP6_TIME_EXCEEDED:
8943 	default:
8944 		break;
8945 	}
8946 	freemsg(first_mp);
8947 }
8948 
8949 /*
8950  * IP recognizes seven kinds of bind requests:
8951  *
8952  * - A zero-length address binds only to the protocol number.
8953  *
8954  * - A 4-byte address is treated as a request to
8955  * validate that the address is a valid local IPv4
8956  * address, appropriate for an application to bind to.
8957  * IP does the verification, but does not make any note
8958  * of the address at this time.
8959  *
8960  * - A 16-byte address contains is treated as a request
8961  * to validate a local IPv6 address, as the 4-byte
8962  * address case above.
8963  *
8964  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8965  * use it for the inbound fanout of packets.
8966  *
8967  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8968  * use it for the inbound fanout of packets.
8969  *
8970  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8971  * information consisting of local and remote addresses
8972  * and ports.  In this case, the addresses are both
8973  * validated as appropriate for this operation, and, if
8974  * so, the information is retained for use in the
8975  * inbound fanout.
8976  *
8977  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8978  * fanout information, like the 12-byte case above.
8979  *
8980  * IP will also fill in the IRE request mblk with information
8981  * regarding our peer.  In all cases, we notify IP of our protocol
8982  * type by appending a single protocol byte to the bind request.
8983  */
8984 static mblk_t *
8985 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8986 {
8987 	char	*cp;
8988 	mblk_t	*mp;
8989 	struct T_bind_req *tbr;
8990 	ipa_conn_t	*ac;
8991 	ipa6_conn_t	*ac6;
8992 	sin_t		*sin;
8993 	sin6_t		*sin6;
8994 
8995 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8996 	ASSERT((tcp->tcp_family == AF_INET &&
8997 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8998 	    (tcp->tcp_family == AF_INET6 &&
8999 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9000 	    tcp->tcp_ipversion == IPV6_VERSION)));
9001 
9002 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9003 	if (!mp)
9004 		return (mp);
9005 	mp->b_datap->db_type = M_PROTO;
9006 	tbr = (struct T_bind_req *)mp->b_rptr;
9007 	tbr->PRIM_type = bind_prim;
9008 	tbr->ADDR_offset = sizeof (*tbr);
9009 	tbr->CONIND_number = 0;
9010 	tbr->ADDR_length = addr_length;
9011 	cp = (char *)&tbr[1];
9012 	switch (addr_length) {
9013 	case sizeof (ipa_conn_t):
9014 		ASSERT(tcp->tcp_family == AF_INET);
9015 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9016 
9017 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9018 		if (mp->b_cont == NULL) {
9019 			freemsg(mp);
9020 			return (NULL);
9021 		}
9022 		mp->b_cont->b_wptr += sizeof (ire_t);
9023 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9024 
9025 		/* cp known to be 32 bit aligned */
9026 		ac = (ipa_conn_t *)cp;
9027 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9028 		ac->ac_faddr = tcp->tcp_remote;
9029 		ac->ac_fport = tcp->tcp_fport;
9030 		ac->ac_lport = tcp->tcp_lport;
9031 		tcp->tcp_hard_binding = 1;
9032 		break;
9033 
9034 	case sizeof (ipa6_conn_t):
9035 		ASSERT(tcp->tcp_family == AF_INET6);
9036 
9037 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9038 		if (mp->b_cont == NULL) {
9039 			freemsg(mp);
9040 			return (NULL);
9041 		}
9042 		mp->b_cont->b_wptr += sizeof (ire_t);
9043 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9044 
9045 		/* cp known to be 32 bit aligned */
9046 		ac6 = (ipa6_conn_t *)cp;
9047 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9048 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9049 			    &ac6->ac6_laddr);
9050 		} else {
9051 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9052 		}
9053 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9054 		ac6->ac6_fport = tcp->tcp_fport;
9055 		ac6->ac6_lport = tcp->tcp_lport;
9056 		tcp->tcp_hard_binding = 1;
9057 		break;
9058 
9059 	case sizeof (sin_t):
9060 		/*
9061 		 * NOTE: IPV6_ADDR_LEN also has same size.
9062 		 * Use family to discriminate.
9063 		 */
9064 		if (tcp->tcp_family == AF_INET) {
9065 			sin = (sin_t *)cp;
9066 
9067 			*sin = sin_null;
9068 			sin->sin_family = AF_INET;
9069 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9070 			sin->sin_port = tcp->tcp_lport;
9071 			break;
9072 		} else {
9073 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9074 		}
9075 		break;
9076 
9077 	case sizeof (sin6_t):
9078 		ASSERT(tcp->tcp_family == AF_INET6);
9079 		sin6 = (sin6_t *)cp;
9080 
9081 		*sin6 = sin6_null;
9082 		sin6->sin6_family = AF_INET6;
9083 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9084 		sin6->sin6_port = tcp->tcp_lport;
9085 		break;
9086 
9087 	case IP_ADDR_LEN:
9088 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9089 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9090 		break;
9091 
9092 	}
9093 	/* Add protocol number to end */
9094 	cp[addr_length] = (char)IPPROTO_TCP;
9095 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9096 	return (mp);
9097 }
9098 
9099 /*
9100  * Notify IP that we are having trouble with this connection.  IP should
9101  * blow the IRE away and start over.
9102  */
9103 static void
9104 tcp_ip_notify(tcp_t *tcp)
9105 {
9106 	struct iocblk	*iocp;
9107 	ipid_t	*ipid;
9108 	mblk_t	*mp;
9109 
9110 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9111 	if (tcp->tcp_ipversion == IPV6_VERSION)
9112 		return;
9113 
9114 	mp = mkiocb(IP_IOCTL);
9115 	if (mp == NULL)
9116 		return;
9117 
9118 	iocp = (struct iocblk *)mp->b_rptr;
9119 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9120 
9121 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9122 	if (!mp->b_cont) {
9123 		freeb(mp);
9124 		return;
9125 	}
9126 
9127 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9128 	mp->b_cont->b_wptr += iocp->ioc_count;
9129 	bzero(ipid, sizeof (*ipid));
9130 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9131 	ipid->ipid_ire_type = IRE_CACHE;
9132 	ipid->ipid_addr_offset = sizeof (ipid_t);
9133 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9134 	/*
9135 	 * Note: in the case of source routing we want to blow away the
9136 	 * route to the first source route hop.
9137 	 */
9138 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9139 	    sizeof (tcp->tcp_ipha->ipha_dst));
9140 
9141 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9142 }
9143 
9144 /* Unlink and return any mblk that looks like it contains an ire */
9145 static mblk_t *
9146 tcp_ire_mp(mblk_t *mp)
9147 {
9148 	mblk_t	*prev_mp;
9149 
9150 	for (;;) {
9151 		prev_mp = mp;
9152 		mp = mp->b_cont;
9153 		if (mp == NULL)
9154 			break;
9155 		switch (DB_TYPE(mp)) {
9156 		case IRE_DB_TYPE:
9157 		case IRE_DB_REQ_TYPE:
9158 			if (prev_mp != NULL)
9159 				prev_mp->b_cont = mp->b_cont;
9160 			mp->b_cont = NULL;
9161 			return (mp);
9162 		default:
9163 			break;
9164 		}
9165 	}
9166 	return (mp);
9167 }
9168 
9169 /*
9170  * Timer callback routine for keepalive probe.  We do a fake resend of
9171  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9172  * check to see if we have heard anything from the other end for the last
9173  * RTO period.  If we have, set the timer to expire for another
9174  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9175  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9176  * the timeout if we have not heard from the other side.  If for more than
9177  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9178  * kill the connection unless the keepalive abort threshold is 0.  In
9179  * that case, we will probe "forever."
9180  */
9181 static void
9182 tcp_keepalive_killer(void *arg)
9183 {
9184 	mblk_t	*mp;
9185 	conn_t	*connp = (conn_t *)arg;
9186 	tcp_t  	*tcp = connp->conn_tcp;
9187 	int32_t	firetime;
9188 	int32_t	idletime;
9189 	int32_t	ka_intrvl;
9190 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9191 
9192 	tcp->tcp_ka_tid = 0;
9193 
9194 	if (tcp->tcp_fused)
9195 		return;
9196 
9197 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9198 	ka_intrvl = tcp->tcp_ka_interval;
9199 
9200 	/*
9201 	 * Keepalive probe should only be sent if the application has not
9202 	 * done a close on the connection.
9203 	 */
9204 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9205 		return;
9206 	}
9207 	/* Timer fired too early, restart it. */
9208 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9209 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9210 		    MSEC_TO_TICK(ka_intrvl));
9211 		return;
9212 	}
9213 
9214 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9215 	/*
9216 	 * If we have not heard from the other side for a long
9217 	 * time, kill the connection unless the keepalive abort
9218 	 * threshold is 0.  In that case, we will probe "forever."
9219 	 */
9220 	if (tcp->tcp_ka_abort_thres != 0 &&
9221 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9222 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9223 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9224 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9225 		return;
9226 	}
9227 
9228 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9229 	    idletime >= ka_intrvl) {
9230 		/* Fake resend of last ACKed byte. */
9231 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9232 
9233 		if (mp1 != NULL) {
9234 			*mp1->b_wptr++ = '\0';
9235 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9236 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9237 			freeb(mp1);
9238 			/*
9239 			 * if allocation failed, fall through to start the
9240 			 * timer back.
9241 			 */
9242 			if (mp != NULL) {
9243 				TCP_RECORD_TRACE(tcp, mp,
9244 				    TCP_TRACE_SEND_PKT);
9245 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9246 				BUMP_MIB(&tcps->tcps_mib,
9247 				    tcpTimKeepaliveProbe);
9248 				if (tcp->tcp_ka_last_intrvl != 0) {
9249 					int max;
9250 					/*
9251 					 * We should probe again at least
9252 					 * in ka_intrvl, but not more than
9253 					 * tcp_rexmit_interval_max.
9254 					 */
9255 					max = tcps->tcps_rexmit_interval_max;
9256 					firetime = MIN(ka_intrvl - 1,
9257 					    tcp->tcp_ka_last_intrvl << 1);
9258 					if (firetime > max)
9259 						firetime = max;
9260 				} else {
9261 					firetime = tcp->tcp_rto;
9262 				}
9263 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9264 				    tcp_keepalive_killer,
9265 				    MSEC_TO_TICK(firetime));
9266 				tcp->tcp_ka_last_intrvl = firetime;
9267 				return;
9268 			}
9269 		}
9270 	} else {
9271 		tcp->tcp_ka_last_intrvl = 0;
9272 	}
9273 
9274 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9275 	if ((firetime = ka_intrvl - idletime) < 0) {
9276 		firetime = ka_intrvl;
9277 	}
9278 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9279 	    MSEC_TO_TICK(firetime));
9280 }
9281 
9282 int
9283 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9284 {
9285 	queue_t	*q = tcp->tcp_rq;
9286 	int32_t	mss = tcp->tcp_mss;
9287 	int	maxpsz;
9288 
9289 	if (TCP_IS_DETACHED(tcp))
9290 		return (mss);
9291 
9292 	if (tcp->tcp_fused) {
9293 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9294 		mss = INFPSZ;
9295 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9296 		/*
9297 		 * Set the sd_qn_maxpsz according to the socket send buffer
9298 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9299 		 * instruct the stream head to copyin user data into contiguous
9300 		 * kernel-allocated buffers without breaking it up into smaller
9301 		 * chunks.  We round up the buffer size to the nearest SMSS.
9302 		 */
9303 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9304 		if (tcp->tcp_kssl_ctx == NULL)
9305 			mss = INFPSZ;
9306 		else
9307 			mss = SSL3_MAX_RECORD_LEN;
9308 	} else {
9309 		/*
9310 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9311 		 * (and a multiple of the mss).  This instructs the stream
9312 		 * head to break down larger than SMSS writes into SMSS-
9313 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9314 		 */
9315 		maxpsz = tcp->tcp_maxpsz * mss;
9316 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9317 			maxpsz = tcp->tcp_xmit_hiwater/2;
9318 			/* Round up to nearest mss */
9319 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9320 		}
9321 	}
9322 	(void) setmaxps(q, maxpsz);
9323 	tcp->tcp_wq->q_maxpsz = maxpsz;
9324 
9325 	if (set_maxblk)
9326 		(void) mi_set_sth_maxblk(q, mss);
9327 
9328 	return (mss);
9329 }
9330 
9331 /*
9332  * Extract option values from a tcp header.  We put any found values into the
9333  * tcpopt struct and return a bitmask saying which options were found.
9334  */
9335 static int
9336 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9337 {
9338 	uchar_t		*endp;
9339 	int		len;
9340 	uint32_t	mss;
9341 	uchar_t		*up = (uchar_t *)tcph;
9342 	int		found = 0;
9343 	int32_t		sack_len;
9344 	tcp_seq		sack_begin, sack_end;
9345 	tcp_t		*tcp;
9346 
9347 	endp = up + TCP_HDR_LENGTH(tcph);
9348 	up += TCP_MIN_HEADER_LENGTH;
9349 	while (up < endp) {
9350 		len = endp - up;
9351 		switch (*up) {
9352 		case TCPOPT_EOL:
9353 			break;
9354 
9355 		case TCPOPT_NOP:
9356 			up++;
9357 			continue;
9358 
9359 		case TCPOPT_MAXSEG:
9360 			if (len < TCPOPT_MAXSEG_LEN ||
9361 			    up[1] != TCPOPT_MAXSEG_LEN)
9362 				break;
9363 
9364 			mss = BE16_TO_U16(up+2);
9365 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9366 			tcpopt->tcp_opt_mss = mss;
9367 			found |= TCP_OPT_MSS_PRESENT;
9368 
9369 			up += TCPOPT_MAXSEG_LEN;
9370 			continue;
9371 
9372 		case TCPOPT_WSCALE:
9373 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9374 				break;
9375 
9376 			if (up[2] > TCP_MAX_WINSHIFT)
9377 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9378 			else
9379 				tcpopt->tcp_opt_wscale = up[2];
9380 			found |= TCP_OPT_WSCALE_PRESENT;
9381 
9382 			up += TCPOPT_WS_LEN;
9383 			continue;
9384 
9385 		case TCPOPT_SACK_PERMITTED:
9386 			if (len < TCPOPT_SACK_OK_LEN ||
9387 			    up[1] != TCPOPT_SACK_OK_LEN)
9388 				break;
9389 			found |= TCP_OPT_SACK_OK_PRESENT;
9390 			up += TCPOPT_SACK_OK_LEN;
9391 			continue;
9392 
9393 		case TCPOPT_SACK:
9394 			if (len <= 2 || up[1] <= 2 || len < up[1])
9395 				break;
9396 
9397 			/* If TCP is not interested in SACK blks... */
9398 			if ((tcp = tcpopt->tcp) == NULL) {
9399 				up += up[1];
9400 				continue;
9401 			}
9402 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9403 			up += TCPOPT_HEADER_LEN;
9404 
9405 			/*
9406 			 * If the list is empty, allocate one and assume
9407 			 * nothing is sack'ed.
9408 			 */
9409 			ASSERT(tcp->tcp_sack_info != NULL);
9410 			if (tcp->tcp_notsack_list == NULL) {
9411 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9412 				    tcp->tcp_suna, tcp->tcp_snxt,
9413 				    &(tcp->tcp_num_notsack_blk),
9414 				    &(tcp->tcp_cnt_notsack_list));
9415 
9416 				/*
9417 				 * Make sure tcp_notsack_list is not NULL.
9418 				 * This happens when kmem_alloc(KM_NOSLEEP)
9419 				 * returns NULL.
9420 				 */
9421 				if (tcp->tcp_notsack_list == NULL) {
9422 					up += sack_len;
9423 					continue;
9424 				}
9425 				tcp->tcp_fack = tcp->tcp_suna;
9426 			}
9427 
9428 			while (sack_len > 0) {
9429 				if (up + 8 > endp) {
9430 					up = endp;
9431 					break;
9432 				}
9433 				sack_begin = BE32_TO_U32(up);
9434 				up += 4;
9435 				sack_end = BE32_TO_U32(up);
9436 				up += 4;
9437 				sack_len -= 8;
9438 				/*
9439 				 * Bounds checking.  Make sure the SACK
9440 				 * info is within tcp_suna and tcp_snxt.
9441 				 * If this SACK blk is out of bound, ignore
9442 				 * it but continue to parse the following
9443 				 * blks.
9444 				 */
9445 				if (SEQ_LEQ(sack_end, sack_begin) ||
9446 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9447 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9448 					continue;
9449 				}
9450 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9451 				    sack_begin, sack_end,
9452 				    &(tcp->tcp_num_notsack_blk),
9453 				    &(tcp->tcp_cnt_notsack_list));
9454 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9455 					tcp->tcp_fack = sack_end;
9456 				}
9457 			}
9458 			found |= TCP_OPT_SACK_PRESENT;
9459 			continue;
9460 
9461 		case TCPOPT_TSTAMP:
9462 			if (len < TCPOPT_TSTAMP_LEN ||
9463 			    up[1] != TCPOPT_TSTAMP_LEN)
9464 				break;
9465 
9466 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9467 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9468 
9469 			found |= TCP_OPT_TSTAMP_PRESENT;
9470 
9471 			up += TCPOPT_TSTAMP_LEN;
9472 			continue;
9473 
9474 		default:
9475 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9476 				break;
9477 			up += up[1];
9478 			continue;
9479 		}
9480 		break;
9481 	}
9482 	return (found);
9483 }
9484 
9485 /*
9486  * Set the mss associated with a particular tcp based on its current value,
9487  * and a new one passed in. Observe minimums and maximums, and reset
9488  * other state variables that we want to view as multiples of mss.
9489  *
9490  * This function is called in various places mainly because
9491  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9492  *    other side's SYN/SYN-ACK packet arrives.
9493  * 2) PMTUd may get us a new MSS.
9494  * 3) If the other side stops sending us timestamp option, we need to
9495  *    increase the MSS size to use the extra bytes available.
9496  *
9497  * do_ss is used to control whether we will be doing slow start or
9498  * not if there is a change in the mss. Note that for some events like
9499  * tcp_paws_check() we allow the tcp_cwnd to adjust to the new mss but
9500  * do not perform a slow start specifically.
9501  */
9502 static void
9503 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9504 {
9505 	uint32_t	mss_max;
9506 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9507 
9508 	if (tcp->tcp_ipversion == IPV4_VERSION)
9509 		mss_max = tcps->tcps_mss_max_ipv4;
9510 	else
9511 		mss_max = tcps->tcps_mss_max_ipv6;
9512 
9513 	if (mss < tcps->tcps_mss_min)
9514 		mss = tcps->tcps_mss_min;
9515 	if (mss > mss_max)
9516 		mss = mss_max;
9517 	/*
9518 	 * Unless naglim has been set by our client to
9519 	 * a non-mss value, force naglim to track mss.
9520 	 * This can help to aggregate small writes.
9521 	 */
9522 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9523 		tcp->tcp_naglim = mss;
9524 	/*
9525 	 * TCP should be able to buffer at least 4 MSS data for obvious
9526 	 * performance reason.
9527 	 */
9528 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9529 		tcp->tcp_xmit_hiwater = mss << 2;
9530 
9531 	/*
9532 	 * Check if we need to apply the tcp_init_cwnd here.  If
9533 	 * it is set and the MSS gets bigger (should not happen
9534 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9535 	 * The new tcp_cwnd should not get bigger.
9536 	 */
9537 	/*
9538 	 * We need to avoid setting tcp_cwnd to its slow start value
9539 	 * unnecessarily. However we have to let the tcp_cwnd adjust
9540 	 * to the modified mss.
9541 	 */
9542 	if (tcp->tcp_init_cwnd == 0 && do_ss) {
9543 		tcp->tcp_cwnd = MIN(tcps->tcps_slow_start_initial *
9544 		    mss, MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9545 	} else {
9546 		if (tcp->tcp_mss < mss) {
9547 			tcp->tcp_cwnd = MAX(1,
9548 			    (tcp->tcp_init_cwnd * tcp->tcp_mss /
9549 			    mss)) * mss;
9550 		} else {
9551 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9552 		}
9553 	}
9554 	tcp->tcp_mss = mss;
9555 	tcp->tcp_cwnd_cnt = 0;
9556 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9557 }
9558 
9559 static int
9560 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9561 {
9562 	tcp_t		*tcp = NULL;
9563 	conn_t		*connp;
9564 	int		err;
9565 	dev_t		conn_dev;
9566 	zoneid_t	zoneid;
9567 	tcp_stack_t	*tcps = NULL;
9568 
9569 	if (q->q_ptr != NULL)
9570 		return (0);
9571 
9572 	if (!(flag & SO_ACCEPTOR)) {
9573 		/*
9574 		 * Special case for install: miniroot needs to be able to
9575 		 * access files via NFS as though it were always in the
9576 		 * global zone.
9577 		 */
9578 		if (credp == kcred && nfs_global_client_only != 0) {
9579 			zoneid = GLOBAL_ZONEID;
9580 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9581 			    netstack_tcp;
9582 			ASSERT(tcps != NULL);
9583 		} else {
9584 			netstack_t *ns;
9585 
9586 			ns = netstack_find_by_cred(credp);
9587 			ASSERT(ns != NULL);
9588 			tcps = ns->netstack_tcp;
9589 			ASSERT(tcps != NULL);
9590 
9591 			/*
9592 			 * For exclusive stacks we set the zoneid to zero
9593 			 * to make TCP operate as if in the global zone.
9594 			 */
9595 			if (tcps->tcps_netstack->netstack_stackid !=
9596 			    GLOBAL_NETSTACKID)
9597 				zoneid = GLOBAL_ZONEID;
9598 			else
9599 				zoneid = crgetzoneid(credp);
9600 		}
9601 		/*
9602 		 * For stackid zero this is done from strplumb.c, but
9603 		 * non-zero stackids are handled here.
9604 		 */
9605 		if (tcps->tcps_g_q == NULL &&
9606 		    tcps->tcps_netstack->netstack_stackid !=
9607 		    GLOBAL_NETSTACKID) {
9608 			tcp_g_q_setup(tcps);
9609 		}
9610 	}
9611 	if (sflag == MODOPEN) {
9612 		/*
9613 		 * This is a special case. The purpose of a modopen
9614 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9615 		 * through for MIB browsers. Everything else is failed.
9616 		 */
9617 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9618 		/* tcp_get_conn incremented refcnt */
9619 		netstack_rele(tcps->tcps_netstack);
9620 
9621 		if (connp == NULL)
9622 			return (ENOMEM);
9623 
9624 		connp->conn_flags |= IPCL_TCPMOD;
9625 		connp->conn_cred = credp;
9626 		connp->conn_zoneid = zoneid;
9627 		ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9628 		ASSERT(connp->conn_netstack->netstack_tcp == tcps);
9629 		q->q_ptr = WR(q)->q_ptr = connp;
9630 		crhold(credp);
9631 		q->q_qinfo = &tcp_mod_rinit;
9632 		WR(q)->q_qinfo = &tcp_mod_winit;
9633 		qprocson(q);
9634 		return (0);
9635 	}
9636 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9637 		if (tcps != NULL)
9638 			netstack_rele(tcps->tcps_netstack);
9639 		return (EBUSY);
9640 	}
9641 
9642 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9643 
9644 	if (flag & SO_ACCEPTOR) {
9645 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9646 		ASSERT(tcps == NULL);
9647 		q->q_qinfo = &tcp_acceptor_rinit;
9648 		q->q_ptr = (void *)conn_dev;
9649 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9650 		WR(q)->q_ptr = (void *)conn_dev;
9651 		qprocson(q);
9652 		return (0);
9653 	}
9654 
9655 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9656 	/*
9657 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9658 	 * so we drop it by one.
9659 	 */
9660 	netstack_rele(tcps->tcps_netstack);
9661 	if (connp == NULL) {
9662 		inet_minor_free(ip_minor_arena, conn_dev);
9663 		q->q_ptr = NULL;
9664 		return (ENOSR);
9665 	}
9666 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9667 	tcp = connp->conn_tcp;
9668 
9669 	q->q_ptr = WR(q)->q_ptr = connp;
9670 	if (getmajor(*devp) == TCP6_MAJ) {
9671 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9672 		connp->conn_send = ip_output_v6;
9673 		connp->conn_af_isv6 = B_TRUE;
9674 		connp->conn_pkt_isv6 = B_TRUE;
9675 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9676 		tcp->tcp_ipversion = IPV6_VERSION;
9677 		tcp->tcp_family = AF_INET6;
9678 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9679 	} else {
9680 		connp->conn_flags |= IPCL_TCP4;
9681 		connp->conn_send = ip_output;
9682 		connp->conn_af_isv6 = B_FALSE;
9683 		connp->conn_pkt_isv6 = B_FALSE;
9684 		tcp->tcp_ipversion = IPV4_VERSION;
9685 		tcp->tcp_family = AF_INET;
9686 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9687 	}
9688 
9689 	/*
9690 	 * TCP keeps a copy of cred for cache locality reasons but
9691 	 * we put a reference only once. If connp->conn_cred
9692 	 * becomes invalid, tcp_cred should also be set to NULL.
9693 	 */
9694 	tcp->tcp_cred = connp->conn_cred = credp;
9695 	crhold(connp->conn_cred);
9696 	tcp->tcp_cpid = curproc->p_pid;
9697 	tcp->tcp_open_time = lbolt64;
9698 	connp->conn_zoneid = zoneid;
9699 	connp->conn_mlp_type = mlptSingle;
9700 	connp->conn_ulp_labeled = !is_system_labeled();
9701 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9702 	ASSERT(tcp->tcp_tcps == tcps);
9703 
9704 	/*
9705 	 * If the caller has the process-wide flag set, then default to MAC
9706 	 * exempt mode.  This allows read-down to unlabeled hosts.
9707 	 */
9708 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9709 		connp->conn_mac_exempt = B_TRUE;
9710 
9711 	connp->conn_dev = conn_dev;
9712 
9713 	ASSERT(q->q_qinfo == &tcp_rinit);
9714 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9715 
9716 	if (flag & SO_SOCKSTR) {
9717 		/*
9718 		 * No need to insert a socket in tcp acceptor hash.
9719 		 * If it was a socket acceptor stream, we dealt with
9720 		 * it above. A socket listener can never accept a
9721 		 * connection and doesn't need acceptor_id.
9722 		 */
9723 		connp->conn_flags |= IPCL_SOCKET;
9724 		tcp->tcp_issocket = 1;
9725 		WR(q)->q_qinfo = &tcp_sock_winit;
9726 	} else {
9727 #ifdef	_ILP32
9728 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9729 #else
9730 		tcp->tcp_acceptor_id = conn_dev;
9731 #endif	/* _ILP32 */
9732 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9733 	}
9734 
9735 	if (tcps->tcps_trace)
9736 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9737 
9738 	err = tcp_init(tcp, q);
9739 	if (err != 0) {
9740 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9741 		tcp_acceptor_hash_remove(tcp);
9742 		CONN_DEC_REF(connp);
9743 		q->q_ptr = WR(q)->q_ptr = NULL;
9744 		return (err);
9745 	}
9746 
9747 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9748 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9749 
9750 	/* Non-zero default values */
9751 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9752 	/*
9753 	 * Put the ref for TCP. Ref for IP was already put
9754 	 * by ipcl_conn_create. Also Make the conn_t globally
9755 	 * visible to walkers
9756 	 */
9757 	mutex_enter(&connp->conn_lock);
9758 	CONN_INC_REF_LOCKED(connp);
9759 	ASSERT(connp->conn_ref == 2);
9760 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9761 	mutex_exit(&connp->conn_lock);
9762 
9763 	qprocson(q);
9764 	return (0);
9765 }
9766 
9767 /*
9768  * Some TCP options can be "set" by requesting them in the option
9769  * buffer. This is needed for XTI feature test though we do not
9770  * allow it in general. We interpret that this mechanism is more
9771  * applicable to OSI protocols and need not be allowed in general.
9772  * This routine filters out options for which it is not allowed (most)
9773  * and lets through those (few) for which it is. [ The XTI interface
9774  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9775  * ever implemented will have to be allowed here ].
9776  */
9777 static boolean_t
9778 tcp_allow_connopt_set(int level, int name)
9779 {
9780 
9781 	switch (level) {
9782 	case IPPROTO_TCP:
9783 		switch (name) {
9784 		case TCP_NODELAY:
9785 			return (B_TRUE);
9786 		default:
9787 			return (B_FALSE);
9788 		}
9789 		/*NOTREACHED*/
9790 	default:
9791 		return (B_FALSE);
9792 	}
9793 	/*NOTREACHED*/
9794 }
9795 
9796 /*
9797  * This routine gets default values of certain options whose default
9798  * values are maintained by protocol specific code
9799  */
9800 /* ARGSUSED */
9801 int
9802 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9803 {
9804 	int32_t	*i1 = (int32_t *)ptr;
9805 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9806 
9807 	switch (level) {
9808 	case IPPROTO_TCP:
9809 		switch (name) {
9810 		case TCP_NOTIFY_THRESHOLD:
9811 			*i1 = tcps->tcps_ip_notify_interval;
9812 			break;
9813 		case TCP_ABORT_THRESHOLD:
9814 			*i1 = tcps->tcps_ip_abort_interval;
9815 			break;
9816 		case TCP_CONN_NOTIFY_THRESHOLD:
9817 			*i1 = tcps->tcps_ip_notify_cinterval;
9818 			break;
9819 		case TCP_CONN_ABORT_THRESHOLD:
9820 			*i1 = tcps->tcps_ip_abort_cinterval;
9821 			break;
9822 		default:
9823 			return (-1);
9824 		}
9825 		break;
9826 	case IPPROTO_IP:
9827 		switch (name) {
9828 		case IP_TTL:
9829 			*i1 = tcps->tcps_ipv4_ttl;
9830 			break;
9831 		default:
9832 			return (-1);
9833 		}
9834 		break;
9835 	case IPPROTO_IPV6:
9836 		switch (name) {
9837 		case IPV6_UNICAST_HOPS:
9838 			*i1 = tcps->tcps_ipv6_hoplimit;
9839 			break;
9840 		default:
9841 			return (-1);
9842 		}
9843 		break;
9844 	default:
9845 		return (-1);
9846 	}
9847 	return (sizeof (int));
9848 }
9849 
9850 
9851 /*
9852  * TCP routine to get the values of options.
9853  */
9854 int
9855 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9856 {
9857 	int		*i1 = (int *)ptr;
9858 	conn_t		*connp = Q_TO_CONN(q);
9859 	tcp_t		*tcp = connp->conn_tcp;
9860 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9861 
9862 	switch (level) {
9863 	case SOL_SOCKET:
9864 		switch (name) {
9865 		case SO_LINGER:	{
9866 			struct linger *lgr = (struct linger *)ptr;
9867 
9868 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9869 			lgr->l_linger = tcp->tcp_lingertime;
9870 			}
9871 			return (sizeof (struct linger));
9872 		case SO_DEBUG:
9873 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9874 			break;
9875 		case SO_KEEPALIVE:
9876 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9877 			break;
9878 		case SO_DONTROUTE:
9879 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9880 			break;
9881 		case SO_USELOOPBACK:
9882 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9883 			break;
9884 		case SO_BROADCAST:
9885 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9886 			break;
9887 		case SO_REUSEADDR:
9888 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9889 			break;
9890 		case SO_OOBINLINE:
9891 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9892 			break;
9893 		case SO_DGRAM_ERRIND:
9894 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9895 			break;
9896 		case SO_TYPE:
9897 			*i1 = SOCK_STREAM;
9898 			break;
9899 		case SO_SNDBUF:
9900 			*i1 = tcp->tcp_xmit_hiwater;
9901 			break;
9902 		case SO_RCVBUF:
9903 			*i1 = RD(q)->q_hiwat;
9904 			break;
9905 		case SO_SND_COPYAVOID:
9906 			*i1 = tcp->tcp_snd_zcopy_on ?
9907 			    SO_SND_COPYAVOID : 0;
9908 			break;
9909 		case SO_ALLZONES:
9910 			*i1 = connp->conn_allzones ? 1 : 0;
9911 			break;
9912 		case SO_ANON_MLP:
9913 			*i1 = connp->conn_anon_mlp;
9914 			break;
9915 		case SO_MAC_EXEMPT:
9916 			*i1 = connp->conn_mac_exempt;
9917 			break;
9918 		case SO_EXCLBIND:
9919 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9920 			break;
9921 		case SO_PROTOTYPE:
9922 			*i1 = IPPROTO_TCP;
9923 			break;
9924 		case SO_DOMAIN:
9925 			*i1 = tcp->tcp_family;
9926 			break;
9927 		default:
9928 			return (-1);
9929 		}
9930 		break;
9931 	case IPPROTO_TCP:
9932 		switch (name) {
9933 		case TCP_NODELAY:
9934 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9935 			break;
9936 		case TCP_MAXSEG:
9937 			*i1 = tcp->tcp_mss;
9938 			break;
9939 		case TCP_NOTIFY_THRESHOLD:
9940 			*i1 = (int)tcp->tcp_first_timer_threshold;
9941 			break;
9942 		case TCP_ABORT_THRESHOLD:
9943 			*i1 = tcp->tcp_second_timer_threshold;
9944 			break;
9945 		case TCP_CONN_NOTIFY_THRESHOLD:
9946 			*i1 = tcp->tcp_first_ctimer_threshold;
9947 			break;
9948 		case TCP_CONN_ABORT_THRESHOLD:
9949 			*i1 = tcp->tcp_second_ctimer_threshold;
9950 			break;
9951 		case TCP_RECVDSTADDR:
9952 			*i1 = tcp->tcp_recvdstaddr;
9953 			break;
9954 		case TCP_ANONPRIVBIND:
9955 			*i1 = tcp->tcp_anon_priv_bind;
9956 			break;
9957 		case TCP_EXCLBIND:
9958 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9959 			break;
9960 		case TCP_INIT_CWND:
9961 			*i1 = tcp->tcp_init_cwnd;
9962 			break;
9963 		case TCP_KEEPALIVE_THRESHOLD:
9964 			*i1 = tcp->tcp_ka_interval;
9965 			break;
9966 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9967 			*i1 = tcp->tcp_ka_abort_thres;
9968 			break;
9969 		case TCP_CORK:
9970 			*i1 = tcp->tcp_cork;
9971 			break;
9972 		default:
9973 			return (-1);
9974 		}
9975 		break;
9976 	case IPPROTO_IP:
9977 		if (tcp->tcp_family != AF_INET)
9978 			return (-1);
9979 		switch (name) {
9980 		case IP_OPTIONS:
9981 		case T_IP_OPTIONS: {
9982 			/*
9983 			 * This is compatible with BSD in that in only return
9984 			 * the reverse source route with the final destination
9985 			 * as the last entry. The first 4 bytes of the option
9986 			 * will contain the final destination.
9987 			 */
9988 			int	opt_len;
9989 
9990 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9991 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9992 			ASSERT(opt_len >= 0);
9993 			/* Caller ensures enough space */
9994 			if (opt_len > 0) {
9995 				/*
9996 				 * TODO: Do we have to handle getsockopt on an
9997 				 * initiator as well?
9998 				 */
9999 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10000 			}
10001 			return (0);
10002 			}
10003 		case IP_TOS:
10004 		case T_IP_TOS:
10005 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10006 			break;
10007 		case IP_TTL:
10008 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10009 			break;
10010 		case IP_NEXTHOP:
10011 			/* Handled at IP level */
10012 			return (-EINVAL);
10013 		default:
10014 			return (-1);
10015 		}
10016 		break;
10017 	case IPPROTO_IPV6:
10018 		/*
10019 		 * IPPROTO_IPV6 options are only supported for sockets
10020 		 * that are using IPv6 on the wire.
10021 		 */
10022 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10023 			return (-1);
10024 		}
10025 		switch (name) {
10026 		case IPV6_UNICAST_HOPS:
10027 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10028 			break;	/* goto sizeof (int) option return */
10029 		case IPV6_BOUND_IF:
10030 			/* Zero if not set */
10031 			*i1 = tcp->tcp_bound_if;
10032 			break;	/* goto sizeof (int) option return */
10033 		case IPV6_RECVPKTINFO:
10034 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10035 				*i1 = 1;
10036 			else
10037 				*i1 = 0;
10038 			break;	/* goto sizeof (int) option return */
10039 		case IPV6_RECVTCLASS:
10040 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10041 				*i1 = 1;
10042 			else
10043 				*i1 = 0;
10044 			break;	/* goto sizeof (int) option return */
10045 		case IPV6_RECVHOPLIMIT:
10046 			if (tcp->tcp_ipv6_recvancillary &
10047 			    TCP_IPV6_RECVHOPLIMIT)
10048 				*i1 = 1;
10049 			else
10050 				*i1 = 0;
10051 			break;	/* goto sizeof (int) option return */
10052 		case IPV6_RECVHOPOPTS:
10053 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10054 				*i1 = 1;
10055 			else
10056 				*i1 = 0;
10057 			break;	/* goto sizeof (int) option return */
10058 		case IPV6_RECVDSTOPTS:
10059 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10060 				*i1 = 1;
10061 			else
10062 				*i1 = 0;
10063 			break;	/* goto sizeof (int) option return */
10064 		case _OLD_IPV6_RECVDSTOPTS:
10065 			if (tcp->tcp_ipv6_recvancillary &
10066 			    TCP_OLD_IPV6_RECVDSTOPTS)
10067 				*i1 = 1;
10068 			else
10069 				*i1 = 0;
10070 			break;	/* goto sizeof (int) option return */
10071 		case IPV6_RECVRTHDR:
10072 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10073 				*i1 = 1;
10074 			else
10075 				*i1 = 0;
10076 			break;	/* goto sizeof (int) option return */
10077 		case IPV6_RECVRTHDRDSTOPTS:
10078 			if (tcp->tcp_ipv6_recvancillary &
10079 			    TCP_IPV6_RECVRTDSTOPTS)
10080 				*i1 = 1;
10081 			else
10082 				*i1 = 0;
10083 			break;	/* goto sizeof (int) option return */
10084 		case IPV6_PKTINFO: {
10085 			/* XXX assumes that caller has room for max size! */
10086 			struct in6_pktinfo *pkti;
10087 
10088 			pkti = (struct in6_pktinfo *)ptr;
10089 			if (ipp->ipp_fields & IPPF_IFINDEX)
10090 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10091 			else
10092 				pkti->ipi6_ifindex = 0;
10093 			if (ipp->ipp_fields & IPPF_ADDR)
10094 				pkti->ipi6_addr = ipp->ipp_addr;
10095 			else
10096 				pkti->ipi6_addr = ipv6_all_zeros;
10097 			return (sizeof (struct in6_pktinfo));
10098 		}
10099 		case IPV6_TCLASS:
10100 			if (ipp->ipp_fields & IPPF_TCLASS)
10101 				*i1 = ipp->ipp_tclass;
10102 			else
10103 				*i1 = IPV6_FLOW_TCLASS(
10104 				    IPV6_DEFAULT_VERS_AND_FLOW);
10105 			break;	/* goto sizeof (int) option return */
10106 		case IPV6_NEXTHOP: {
10107 			sin6_t *sin6 = (sin6_t *)ptr;
10108 
10109 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10110 				return (0);
10111 			*sin6 = sin6_null;
10112 			sin6->sin6_family = AF_INET6;
10113 			sin6->sin6_addr = ipp->ipp_nexthop;
10114 			return (sizeof (sin6_t));
10115 		}
10116 		case IPV6_HOPOPTS:
10117 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10118 				return (0);
10119 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10120 				return (0);
10121 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10122 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10123 			if (tcp->tcp_label_len > 0) {
10124 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10125 				ptr[1] = (ipp->ipp_hopoptslen -
10126 				    tcp->tcp_label_len + 7) / 8 - 1;
10127 			}
10128 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10129 		case IPV6_RTHDRDSTOPTS:
10130 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10131 				return (0);
10132 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10133 			return (ipp->ipp_rtdstoptslen);
10134 		case IPV6_RTHDR:
10135 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10136 				return (0);
10137 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10138 			return (ipp->ipp_rthdrlen);
10139 		case IPV6_DSTOPTS:
10140 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10141 				return (0);
10142 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10143 			return (ipp->ipp_dstoptslen);
10144 		case IPV6_SRC_PREFERENCES:
10145 			return (ip6_get_src_preferences(connp,
10146 			    (uint32_t *)ptr));
10147 		case IPV6_PATHMTU: {
10148 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10149 
10150 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10151 				return (-1);
10152 
10153 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10154 				connp->conn_fport, mtuinfo,
10155 				connp->conn_netstack));
10156 		}
10157 		default:
10158 			return (-1);
10159 		}
10160 		break;
10161 	default:
10162 		return (-1);
10163 	}
10164 	return (sizeof (int));
10165 }
10166 
10167 /*
10168  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10169  * Parameters are assumed to be verified by the caller.
10170  */
10171 /* ARGSUSED */
10172 int
10173 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10174     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10175     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10176 {
10177 	conn_t	*connp = Q_TO_CONN(q);
10178 	tcp_t	*tcp = connp->conn_tcp;
10179 	int	*i1 = (int *)invalp;
10180 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10181 	boolean_t checkonly;
10182 	int	reterr;
10183 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10184 
10185 	switch (optset_context) {
10186 	case SETFN_OPTCOM_CHECKONLY:
10187 		checkonly = B_TRUE;
10188 		/*
10189 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10190 		 * inlen != 0 implies value supplied and
10191 		 * 	we have to "pretend" to set it.
10192 		 * inlen == 0 implies that there is no
10193 		 * 	value part in T_CHECK request and just validation
10194 		 * done elsewhere should be enough, we just return here.
10195 		 */
10196 		if (inlen == 0) {
10197 			*outlenp = 0;
10198 			return (0);
10199 		}
10200 		break;
10201 	case SETFN_OPTCOM_NEGOTIATE:
10202 		checkonly = B_FALSE;
10203 		break;
10204 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10205 	case SETFN_CONN_NEGOTIATE:
10206 		checkonly = B_FALSE;
10207 		/*
10208 		 * Negotiating local and "association-related" options
10209 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10210 		 * primitives is allowed by XTI, but we choose
10211 		 * to not implement this style negotiation for Internet
10212 		 * protocols (We interpret it is a must for OSI world but
10213 		 * optional for Internet protocols) for all options.
10214 		 * [ Will do only for the few options that enable test
10215 		 * suites that our XTI implementation of this feature
10216 		 * works for transports that do allow it ]
10217 		 */
10218 		if (!tcp_allow_connopt_set(level, name)) {
10219 			*outlenp = 0;
10220 			return (EINVAL);
10221 		}
10222 		break;
10223 	default:
10224 		/*
10225 		 * We should never get here
10226 		 */
10227 		*outlenp = 0;
10228 		return (EINVAL);
10229 	}
10230 
10231 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10232 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10233 
10234 	/*
10235 	 * For TCP, we should have no ancillary data sent down
10236 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10237 	 * has to be zero.
10238 	 */
10239 	ASSERT(thisdg_attrs == NULL);
10240 
10241 	/*
10242 	 * For fixed length options, no sanity check
10243 	 * of passed in length is done. It is assumed *_optcom_req()
10244 	 * routines do the right thing.
10245 	 */
10246 
10247 	switch (level) {
10248 	case SOL_SOCKET:
10249 		switch (name) {
10250 		case SO_LINGER: {
10251 			struct linger *lgr = (struct linger *)invalp;
10252 
10253 			if (!checkonly) {
10254 				if (lgr->l_onoff) {
10255 					tcp->tcp_linger = 1;
10256 					tcp->tcp_lingertime = lgr->l_linger;
10257 				} else {
10258 					tcp->tcp_linger = 0;
10259 					tcp->tcp_lingertime = 0;
10260 				}
10261 				/* struct copy */
10262 				*(struct linger *)outvalp = *lgr;
10263 			} else {
10264 				if (!lgr->l_onoff) {
10265 				    ((struct linger *)outvalp)->l_onoff = 0;
10266 				    ((struct linger *)outvalp)->l_linger = 0;
10267 				} else {
10268 				    /* struct copy */
10269 				    *(struct linger *)outvalp = *lgr;
10270 				}
10271 			}
10272 			*outlenp = sizeof (struct linger);
10273 			return (0);
10274 		}
10275 		case SO_DEBUG:
10276 			if (!checkonly)
10277 				tcp->tcp_debug = onoff;
10278 			break;
10279 		case SO_KEEPALIVE:
10280 			if (checkonly) {
10281 				/* T_CHECK case */
10282 				break;
10283 			}
10284 
10285 			if (!onoff) {
10286 				if (tcp->tcp_ka_enabled) {
10287 					if (tcp->tcp_ka_tid != 0) {
10288 						(void) TCP_TIMER_CANCEL(tcp,
10289 						    tcp->tcp_ka_tid);
10290 						tcp->tcp_ka_tid = 0;
10291 					}
10292 					tcp->tcp_ka_enabled = 0;
10293 				}
10294 				break;
10295 			}
10296 			if (!tcp->tcp_ka_enabled) {
10297 				/* Crank up the keepalive timer */
10298 				tcp->tcp_ka_last_intrvl = 0;
10299 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10300 				    tcp_keepalive_killer,
10301 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10302 				tcp->tcp_ka_enabled = 1;
10303 			}
10304 			break;
10305 		case SO_DONTROUTE:
10306 			/*
10307 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10308 			 * only of interest to IP.  We track them here only so
10309 			 * that we can report their current value.
10310 			 */
10311 			if (!checkonly) {
10312 				tcp->tcp_dontroute = onoff;
10313 				tcp->tcp_connp->conn_dontroute = onoff;
10314 			}
10315 			break;
10316 		case SO_USELOOPBACK:
10317 			if (!checkonly) {
10318 				tcp->tcp_useloopback = onoff;
10319 				tcp->tcp_connp->conn_loopback = onoff;
10320 			}
10321 			break;
10322 		case SO_BROADCAST:
10323 			if (!checkonly) {
10324 				tcp->tcp_broadcast = onoff;
10325 				tcp->tcp_connp->conn_broadcast = onoff;
10326 			}
10327 			break;
10328 		case SO_REUSEADDR:
10329 			if (!checkonly) {
10330 				tcp->tcp_reuseaddr = onoff;
10331 				tcp->tcp_connp->conn_reuseaddr = onoff;
10332 			}
10333 			break;
10334 		case SO_OOBINLINE:
10335 			if (!checkonly)
10336 				tcp->tcp_oobinline = onoff;
10337 			break;
10338 		case SO_DGRAM_ERRIND:
10339 			if (!checkonly)
10340 				tcp->tcp_dgram_errind = onoff;
10341 			break;
10342 		case SO_SNDBUF: {
10343 			if (*i1 > tcps->tcps_max_buf) {
10344 				*outlenp = 0;
10345 				return (ENOBUFS);
10346 			}
10347 			if (checkonly)
10348 				break;
10349 
10350 			tcp->tcp_xmit_hiwater = *i1;
10351 			if (tcps->tcps_snd_lowat_fraction != 0)
10352 				tcp->tcp_xmit_lowater =
10353 				    tcp->tcp_xmit_hiwater /
10354 				    tcps->tcps_snd_lowat_fraction;
10355 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10356 			/*
10357 			 * If we are flow-controlled, recheck the condition.
10358 			 * There are apps that increase SO_SNDBUF size when
10359 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10360 			 * control condition to be lifted right away.
10361 			 */
10362 			mutex_enter(&tcp->tcp_non_sq_lock);
10363 			if (tcp->tcp_flow_stopped &&
10364 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10365 				tcp_clrqfull(tcp);
10366 			}
10367 			mutex_exit(&tcp->tcp_non_sq_lock);
10368 			break;
10369 		}
10370 		case SO_RCVBUF:
10371 			if (*i1 > tcps->tcps_max_buf) {
10372 				*outlenp = 0;
10373 				return (ENOBUFS);
10374 			}
10375 			/* Silently ignore zero */
10376 			if (!checkonly && *i1 != 0) {
10377 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10378 				(void) tcp_rwnd_set(tcp, *i1);
10379 			}
10380 			/*
10381 			 * XXX should we return the rwnd here
10382 			 * and tcp_opt_get ?
10383 			 */
10384 			break;
10385 		case SO_SND_COPYAVOID:
10386 			if (!checkonly) {
10387 				/* we only allow enable at most once for now */
10388 				if (tcp->tcp_loopback ||
10389 				    (!tcp->tcp_snd_zcopy_aware &&
10390 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10391 					*outlenp = 0;
10392 					return (EOPNOTSUPP);
10393 				}
10394 				tcp->tcp_snd_zcopy_aware = 1;
10395 			}
10396 			break;
10397 		case SO_ALLZONES:
10398 			/* Handled at the IP level */
10399 			return (-EINVAL);
10400 		case SO_ANON_MLP:
10401 			if (!checkonly) {
10402 				mutex_enter(&connp->conn_lock);
10403 				connp->conn_anon_mlp = onoff;
10404 				mutex_exit(&connp->conn_lock);
10405 			}
10406 			break;
10407 		case SO_MAC_EXEMPT:
10408 			if (secpolicy_net_mac_aware(cr) != 0 ||
10409 			    IPCL_IS_BOUND(connp))
10410 				return (EACCES);
10411 			if (!checkonly) {
10412 				mutex_enter(&connp->conn_lock);
10413 				connp->conn_mac_exempt = onoff;
10414 				mutex_exit(&connp->conn_lock);
10415 			}
10416 			break;
10417 		case SO_EXCLBIND:
10418 			if (!checkonly)
10419 				tcp->tcp_exclbind = onoff;
10420 			break;
10421 		default:
10422 			*outlenp = 0;
10423 			return (EINVAL);
10424 		}
10425 		break;
10426 	case IPPROTO_TCP:
10427 		switch (name) {
10428 		case TCP_NODELAY:
10429 			if (!checkonly)
10430 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10431 			break;
10432 		case TCP_NOTIFY_THRESHOLD:
10433 			if (!checkonly)
10434 				tcp->tcp_first_timer_threshold = *i1;
10435 			break;
10436 		case TCP_ABORT_THRESHOLD:
10437 			if (!checkonly)
10438 				tcp->tcp_second_timer_threshold = *i1;
10439 			break;
10440 		case TCP_CONN_NOTIFY_THRESHOLD:
10441 			if (!checkonly)
10442 				tcp->tcp_first_ctimer_threshold = *i1;
10443 			break;
10444 		case TCP_CONN_ABORT_THRESHOLD:
10445 			if (!checkonly)
10446 				tcp->tcp_second_ctimer_threshold = *i1;
10447 			break;
10448 		case TCP_RECVDSTADDR:
10449 			if (tcp->tcp_state > TCPS_LISTEN)
10450 				return (EOPNOTSUPP);
10451 			if (!checkonly)
10452 				tcp->tcp_recvdstaddr = onoff;
10453 			break;
10454 		case TCP_ANONPRIVBIND:
10455 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10456 				*outlenp = 0;
10457 				return (reterr);
10458 			}
10459 			if (!checkonly) {
10460 				tcp->tcp_anon_priv_bind = onoff;
10461 			}
10462 			break;
10463 		case TCP_EXCLBIND:
10464 			if (!checkonly)
10465 				tcp->tcp_exclbind = onoff;
10466 			break;	/* goto sizeof (int) option return */
10467 		case TCP_INIT_CWND: {
10468 			uint32_t init_cwnd = *((uint32_t *)invalp);
10469 
10470 			if (checkonly)
10471 				break;
10472 
10473 			/*
10474 			 * Only allow socket with network configuration
10475 			 * privilege to set the initial cwnd to be larger
10476 			 * than allowed by RFC 3390.
10477 			 */
10478 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10479 				tcp->tcp_init_cwnd = init_cwnd;
10480 				break;
10481 			}
10482 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10483 				*outlenp = 0;
10484 				return (reterr);
10485 			}
10486 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10487 				*outlenp = 0;
10488 				return (EINVAL);
10489 			}
10490 			tcp->tcp_init_cwnd = init_cwnd;
10491 			break;
10492 		}
10493 		case TCP_KEEPALIVE_THRESHOLD:
10494 			if (checkonly)
10495 				break;
10496 
10497 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10498 			    *i1 > tcps->tcps_keepalive_interval_high) {
10499 				*outlenp = 0;
10500 				return (EINVAL);
10501 			}
10502 			if (*i1 != tcp->tcp_ka_interval) {
10503 				tcp->tcp_ka_interval = *i1;
10504 				/*
10505 				 * Check if we need to restart the
10506 				 * keepalive timer.
10507 				 */
10508 				if (tcp->tcp_ka_tid != 0) {
10509 					ASSERT(tcp->tcp_ka_enabled);
10510 					(void) TCP_TIMER_CANCEL(tcp,
10511 					    tcp->tcp_ka_tid);
10512 					tcp->tcp_ka_last_intrvl = 0;
10513 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10514 					    tcp_keepalive_killer,
10515 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10516 				}
10517 			}
10518 			break;
10519 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10520 			if (!checkonly) {
10521 				if (*i1 <
10522 				    tcps->tcps_keepalive_abort_interval_low ||
10523 				    *i1 >
10524 				    tcps->tcps_keepalive_abort_interval_high) {
10525 					*outlenp = 0;
10526 					return (EINVAL);
10527 				}
10528 				tcp->tcp_ka_abort_thres = *i1;
10529 			}
10530 			break;
10531 		case TCP_CORK:
10532 			if (!checkonly) {
10533 				/*
10534 				 * if tcp->tcp_cork was set and is now
10535 				 * being unset, we have to make sure that
10536 				 * the remaining data gets sent out. Also
10537 				 * unset tcp->tcp_cork so that tcp_wput_data()
10538 				 * can send data even if it is less than mss
10539 				 */
10540 				if (tcp->tcp_cork && onoff == 0 &&
10541 				    tcp->tcp_unsent > 0) {
10542 					tcp->tcp_cork = B_FALSE;
10543 					tcp_wput_data(tcp, NULL, B_FALSE);
10544 				}
10545 				tcp->tcp_cork = onoff;
10546 			}
10547 			break;
10548 		default:
10549 			*outlenp = 0;
10550 			return (EINVAL);
10551 		}
10552 		break;
10553 	case IPPROTO_IP:
10554 		if (tcp->tcp_family != AF_INET) {
10555 			*outlenp = 0;
10556 			return (ENOPROTOOPT);
10557 		}
10558 		switch (name) {
10559 		case IP_OPTIONS:
10560 		case T_IP_OPTIONS:
10561 			reterr = tcp_opt_set_header(tcp, checkonly,
10562 			    invalp, inlen);
10563 			if (reterr) {
10564 				*outlenp = 0;
10565 				return (reterr);
10566 			}
10567 			/* OK return - copy input buffer into output buffer */
10568 			if (invalp != outvalp) {
10569 				/* don't trust bcopy for identical src/dst */
10570 				bcopy(invalp, outvalp, inlen);
10571 			}
10572 			*outlenp = inlen;
10573 			return (0);
10574 		case IP_TOS:
10575 		case T_IP_TOS:
10576 			if (!checkonly) {
10577 				tcp->tcp_ipha->ipha_type_of_service =
10578 				    (uchar_t)*i1;
10579 				tcp->tcp_tos = (uchar_t)*i1;
10580 			}
10581 			break;
10582 		case IP_TTL:
10583 			if (!checkonly) {
10584 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10585 				tcp->tcp_ttl = (uchar_t)*i1;
10586 			}
10587 			break;
10588 		case IP_BOUND_IF:
10589 		case IP_NEXTHOP:
10590 			/* Handled at the IP level */
10591 			return (-EINVAL);
10592 		case IP_SEC_OPT:
10593 			/*
10594 			 * We should not allow policy setting after
10595 			 * we start listening for connections.
10596 			 */
10597 			if (tcp->tcp_state == TCPS_LISTEN) {
10598 				return (EINVAL);
10599 			} else {
10600 				/* Handled at the IP level */
10601 				return (-EINVAL);
10602 			}
10603 		default:
10604 			*outlenp = 0;
10605 			return (EINVAL);
10606 		}
10607 		break;
10608 	case IPPROTO_IPV6: {
10609 		ip6_pkt_t		*ipp;
10610 
10611 		/*
10612 		 * IPPROTO_IPV6 options are only supported for sockets
10613 		 * that are using IPv6 on the wire.
10614 		 */
10615 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10616 			*outlenp = 0;
10617 			return (ENOPROTOOPT);
10618 		}
10619 		/*
10620 		 * Only sticky options; no ancillary data
10621 		 */
10622 		ASSERT(thisdg_attrs == NULL);
10623 		ipp = &tcp->tcp_sticky_ipp;
10624 
10625 		switch (name) {
10626 		case IPV6_UNICAST_HOPS:
10627 			/* -1 means use default */
10628 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10629 				*outlenp = 0;
10630 				return (EINVAL);
10631 			}
10632 			if (!checkonly) {
10633 				if (*i1 == -1) {
10634 					tcp->tcp_ip6h->ip6_hops =
10635 					    ipp->ipp_unicast_hops =
10636 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10637 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10638 					/* Pass modified value to IP. */
10639 					*i1 = tcp->tcp_ip6h->ip6_hops;
10640 				} else {
10641 					tcp->tcp_ip6h->ip6_hops =
10642 					    ipp->ipp_unicast_hops =
10643 					    (uint8_t)*i1;
10644 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10645 				}
10646 				reterr = tcp_build_hdrs(q, tcp);
10647 				if (reterr != 0)
10648 					return (reterr);
10649 			}
10650 			break;
10651 		case IPV6_BOUND_IF:
10652 			if (!checkonly) {
10653 				int error = 0;
10654 
10655 				tcp->tcp_bound_if = *i1;
10656 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10657 				    B_TRUE, checkonly, level, name, mblk);
10658 				if (error != 0) {
10659 					*outlenp = 0;
10660 					return (error);
10661 				}
10662 			}
10663 			break;
10664 		/*
10665 		 * Set boolean switches for ancillary data delivery
10666 		 */
10667 		case IPV6_RECVPKTINFO:
10668 			if (!checkonly) {
10669 				if (onoff)
10670 					tcp->tcp_ipv6_recvancillary |=
10671 					    TCP_IPV6_RECVPKTINFO;
10672 				else
10673 					tcp->tcp_ipv6_recvancillary &=
10674 					    ~TCP_IPV6_RECVPKTINFO;
10675 				/* Force it to be sent up with the next msg */
10676 				tcp->tcp_recvifindex = 0;
10677 			}
10678 			break;
10679 		case IPV6_RECVTCLASS:
10680 			if (!checkonly) {
10681 				if (onoff)
10682 					tcp->tcp_ipv6_recvancillary |=
10683 					    TCP_IPV6_RECVTCLASS;
10684 				else
10685 					tcp->tcp_ipv6_recvancillary &=
10686 					    ~TCP_IPV6_RECVTCLASS;
10687 			}
10688 			break;
10689 		case IPV6_RECVHOPLIMIT:
10690 			if (!checkonly) {
10691 				if (onoff)
10692 					tcp->tcp_ipv6_recvancillary |=
10693 					    TCP_IPV6_RECVHOPLIMIT;
10694 				else
10695 					tcp->tcp_ipv6_recvancillary &=
10696 					    ~TCP_IPV6_RECVHOPLIMIT;
10697 				/* Force it to be sent up with the next msg */
10698 				tcp->tcp_recvhops = 0xffffffffU;
10699 			}
10700 			break;
10701 		case IPV6_RECVHOPOPTS:
10702 			if (!checkonly) {
10703 				if (onoff)
10704 					tcp->tcp_ipv6_recvancillary |=
10705 					    TCP_IPV6_RECVHOPOPTS;
10706 				else
10707 					tcp->tcp_ipv6_recvancillary &=
10708 					    ~TCP_IPV6_RECVHOPOPTS;
10709 			}
10710 			break;
10711 		case IPV6_RECVDSTOPTS:
10712 			if (!checkonly) {
10713 				if (onoff)
10714 					tcp->tcp_ipv6_recvancillary |=
10715 					    TCP_IPV6_RECVDSTOPTS;
10716 				else
10717 					tcp->tcp_ipv6_recvancillary &=
10718 					    ~TCP_IPV6_RECVDSTOPTS;
10719 			}
10720 			break;
10721 		case _OLD_IPV6_RECVDSTOPTS:
10722 			if (!checkonly) {
10723 				if (onoff)
10724 					tcp->tcp_ipv6_recvancillary |=
10725 					    TCP_OLD_IPV6_RECVDSTOPTS;
10726 				else
10727 					tcp->tcp_ipv6_recvancillary &=
10728 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10729 			}
10730 			break;
10731 		case IPV6_RECVRTHDR:
10732 			if (!checkonly) {
10733 				if (onoff)
10734 					tcp->tcp_ipv6_recvancillary |=
10735 					    TCP_IPV6_RECVRTHDR;
10736 				else
10737 					tcp->tcp_ipv6_recvancillary &=
10738 					    ~TCP_IPV6_RECVRTHDR;
10739 			}
10740 			break;
10741 		case IPV6_RECVRTHDRDSTOPTS:
10742 			if (!checkonly) {
10743 				if (onoff)
10744 					tcp->tcp_ipv6_recvancillary |=
10745 					    TCP_IPV6_RECVRTDSTOPTS;
10746 				else
10747 					tcp->tcp_ipv6_recvancillary &=
10748 					    ~TCP_IPV6_RECVRTDSTOPTS;
10749 			}
10750 			break;
10751 		case IPV6_PKTINFO:
10752 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10753 				return (EINVAL);
10754 			if (checkonly)
10755 				break;
10756 
10757 			if (inlen == 0) {
10758 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10759 			} else {
10760 				struct in6_pktinfo *pkti;
10761 
10762 				pkti = (struct in6_pktinfo *)invalp;
10763 				/*
10764 				 * RFC 3542 states that ipi6_addr must be
10765 				 * the unspecified address when setting the
10766 				 * IPV6_PKTINFO sticky socket option on a
10767 				 * TCP socket.
10768 				 */
10769 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10770 					return (EINVAL);
10771 				/*
10772 				 * ip6_set_pktinfo() validates the source
10773 				 * address and interface index.
10774 				 */
10775 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10776 				    pkti, mblk);
10777 				if (reterr != 0)
10778 					return (reterr);
10779 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10780 				ipp->ipp_addr = pkti->ipi6_addr;
10781 				if (ipp->ipp_ifindex != 0)
10782 					ipp->ipp_fields |= IPPF_IFINDEX;
10783 				else
10784 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10785 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10786 					ipp->ipp_fields |= IPPF_ADDR;
10787 				else
10788 					ipp->ipp_fields &= ~IPPF_ADDR;
10789 			}
10790 			reterr = tcp_build_hdrs(q, tcp);
10791 			if (reterr != 0)
10792 				return (reterr);
10793 			break;
10794 		case IPV6_TCLASS:
10795 			if (inlen != 0 && inlen != sizeof (int))
10796 				return (EINVAL);
10797 			if (checkonly)
10798 				break;
10799 
10800 			if (inlen == 0) {
10801 				ipp->ipp_fields &= ~IPPF_TCLASS;
10802 			} else {
10803 				if (*i1 > 255 || *i1 < -1)
10804 					return (EINVAL);
10805 				if (*i1 == -1) {
10806 					ipp->ipp_tclass = 0;
10807 					*i1 = 0;
10808 				} else {
10809 					ipp->ipp_tclass = *i1;
10810 				}
10811 				ipp->ipp_fields |= IPPF_TCLASS;
10812 			}
10813 			reterr = tcp_build_hdrs(q, tcp);
10814 			if (reterr != 0)
10815 				return (reterr);
10816 			break;
10817 		case IPV6_NEXTHOP:
10818 			/*
10819 			 * IP will verify that the nexthop is reachable
10820 			 * and fail for sticky options.
10821 			 */
10822 			if (inlen != 0 && inlen != sizeof (sin6_t))
10823 				return (EINVAL);
10824 			if (checkonly)
10825 				break;
10826 
10827 			if (inlen == 0) {
10828 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10829 			} else {
10830 				sin6_t *sin6 = (sin6_t *)invalp;
10831 
10832 				if (sin6->sin6_family != AF_INET6)
10833 					return (EAFNOSUPPORT);
10834 				if (IN6_IS_ADDR_V4MAPPED(
10835 				    &sin6->sin6_addr))
10836 					return (EADDRNOTAVAIL);
10837 				ipp->ipp_nexthop = sin6->sin6_addr;
10838 				if (!IN6_IS_ADDR_UNSPECIFIED(
10839 				    &ipp->ipp_nexthop))
10840 					ipp->ipp_fields |= IPPF_NEXTHOP;
10841 				else
10842 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10843 			}
10844 			reterr = tcp_build_hdrs(q, tcp);
10845 			if (reterr != 0)
10846 				return (reterr);
10847 			break;
10848 		case IPV6_HOPOPTS: {
10849 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10850 
10851 			/*
10852 			 * Sanity checks - minimum size, size a multiple of
10853 			 * eight bytes, and matching size passed in.
10854 			 */
10855 			if (inlen != 0 &&
10856 			    inlen != (8 * (hopts->ip6h_len + 1)))
10857 				return (EINVAL);
10858 
10859 			if (checkonly)
10860 				break;
10861 
10862 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10863 			    (uchar_t **)&ipp->ipp_hopopts,
10864 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10865 			if (reterr != 0)
10866 				return (reterr);
10867 			if (ipp->ipp_hopoptslen == 0)
10868 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10869 			else
10870 				ipp->ipp_fields |= IPPF_HOPOPTS;
10871 			reterr = tcp_build_hdrs(q, tcp);
10872 			if (reterr != 0)
10873 				return (reterr);
10874 			break;
10875 		}
10876 		case IPV6_RTHDRDSTOPTS: {
10877 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10878 
10879 			/*
10880 			 * Sanity checks - minimum size, size a multiple of
10881 			 * eight bytes, and matching size passed in.
10882 			 */
10883 			if (inlen != 0 &&
10884 			    inlen != (8 * (dopts->ip6d_len + 1)))
10885 				return (EINVAL);
10886 
10887 			if (checkonly)
10888 				break;
10889 
10890 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10891 			    (uchar_t **)&ipp->ipp_rtdstopts,
10892 			    &ipp->ipp_rtdstoptslen, 0);
10893 			if (reterr != 0)
10894 				return (reterr);
10895 			if (ipp->ipp_rtdstoptslen == 0)
10896 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10897 			else
10898 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10899 			reterr = tcp_build_hdrs(q, tcp);
10900 			if (reterr != 0)
10901 				return (reterr);
10902 			break;
10903 		}
10904 		case IPV6_DSTOPTS: {
10905 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10906 
10907 			/*
10908 			 * Sanity checks - minimum size, size a multiple of
10909 			 * eight bytes, and matching size passed in.
10910 			 */
10911 			if (inlen != 0 &&
10912 			    inlen != (8 * (dopts->ip6d_len + 1)))
10913 				return (EINVAL);
10914 
10915 			if (checkonly)
10916 				break;
10917 
10918 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10919 			    (uchar_t **)&ipp->ipp_dstopts,
10920 			    &ipp->ipp_dstoptslen, 0);
10921 			if (reterr != 0)
10922 				return (reterr);
10923 			if (ipp->ipp_dstoptslen == 0)
10924 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10925 			else
10926 				ipp->ipp_fields |= IPPF_DSTOPTS;
10927 			reterr = tcp_build_hdrs(q, tcp);
10928 			if (reterr != 0)
10929 				return (reterr);
10930 			break;
10931 		}
10932 		case IPV6_RTHDR: {
10933 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10934 
10935 			/*
10936 			 * Sanity checks - minimum size, size a multiple of
10937 			 * eight bytes, and matching size passed in.
10938 			 */
10939 			if (inlen != 0 &&
10940 			    inlen != (8 * (rt->ip6r_len + 1)))
10941 				return (EINVAL);
10942 
10943 			if (checkonly)
10944 				break;
10945 
10946 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10947 			    (uchar_t **)&ipp->ipp_rthdr,
10948 			    &ipp->ipp_rthdrlen, 0);
10949 			if (reterr != 0)
10950 				return (reterr);
10951 			if (ipp->ipp_rthdrlen == 0)
10952 				ipp->ipp_fields &= ~IPPF_RTHDR;
10953 			else
10954 				ipp->ipp_fields |= IPPF_RTHDR;
10955 			reterr = tcp_build_hdrs(q, tcp);
10956 			if (reterr != 0)
10957 				return (reterr);
10958 			break;
10959 		}
10960 		case IPV6_V6ONLY:
10961 			if (!checkonly)
10962 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10963 			break;
10964 		case IPV6_USE_MIN_MTU:
10965 			if (inlen != sizeof (int))
10966 				return (EINVAL);
10967 
10968 			if (*i1 < -1 || *i1 > 1)
10969 				return (EINVAL);
10970 
10971 			if (checkonly)
10972 				break;
10973 
10974 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10975 			ipp->ipp_use_min_mtu = *i1;
10976 			break;
10977 		case IPV6_BOUND_PIF:
10978 			/* Handled at the IP level */
10979 			return (-EINVAL);
10980 		case IPV6_SEC_OPT:
10981 			/*
10982 			 * We should not allow policy setting after
10983 			 * we start listening for connections.
10984 			 */
10985 			if (tcp->tcp_state == TCPS_LISTEN) {
10986 				return (EINVAL);
10987 			} else {
10988 				/* Handled at the IP level */
10989 				return (-EINVAL);
10990 			}
10991 		case IPV6_SRC_PREFERENCES:
10992 			if (inlen != sizeof (uint32_t))
10993 				return (EINVAL);
10994 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10995 			    *(uint32_t *)invalp);
10996 			if (reterr != 0) {
10997 				*outlenp = 0;
10998 				return (reterr);
10999 			}
11000 			break;
11001 		default:
11002 			*outlenp = 0;
11003 			return (EINVAL);
11004 		}
11005 		break;
11006 	}		/* end IPPROTO_IPV6 */
11007 	default:
11008 		*outlenp = 0;
11009 		return (EINVAL);
11010 	}
11011 	/*
11012 	 * Common case of OK return with outval same as inval
11013 	 */
11014 	if (invalp != outvalp) {
11015 		/* don't trust bcopy for identical src/dst */
11016 		(void) bcopy(invalp, outvalp, inlen);
11017 	}
11018 	*outlenp = inlen;
11019 	return (0);
11020 }
11021 
11022 /*
11023  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11024  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11025  * headers, and the maximum size tcp header (to avoid reallocation
11026  * on the fly for additional tcp options).
11027  * Returns failure if can't allocate memory.
11028  */
11029 static int
11030 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11031 {
11032 	char	*hdrs;
11033 	uint_t	hdrs_len;
11034 	ip6i_t	*ip6i;
11035 	char	buf[TCP_MAX_HDR_LENGTH];
11036 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11037 	in6_addr_t src, dst;
11038 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11039 
11040 	/*
11041 	 * save the existing tcp header and source/dest IP addresses
11042 	 */
11043 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11044 	src = tcp->tcp_ip6h->ip6_src;
11045 	dst = tcp->tcp_ip6h->ip6_dst;
11046 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11047 	ASSERT(hdrs_len != 0);
11048 	if (hdrs_len > tcp->tcp_iphc_len) {
11049 		/* Need to reallocate */
11050 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11051 		if (hdrs == NULL)
11052 			return (ENOMEM);
11053 		if (tcp->tcp_iphc != NULL) {
11054 			if (tcp->tcp_hdr_grown) {
11055 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11056 			} else {
11057 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11058 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11059 			}
11060 			tcp->tcp_iphc_len = 0;
11061 		}
11062 		ASSERT(tcp->tcp_iphc_len == 0);
11063 		tcp->tcp_iphc = hdrs;
11064 		tcp->tcp_iphc_len = hdrs_len;
11065 		tcp->tcp_hdr_grown = B_TRUE;
11066 	}
11067 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11068 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11069 
11070 	/* Set header fields not in ipp */
11071 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11072 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11073 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11074 	} else {
11075 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11076 	}
11077 	/*
11078 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11079 	 *
11080 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11081 	 */
11082 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11083 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11084 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11085 
11086 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11087 
11088 	tcp->tcp_ip6h->ip6_src = src;
11089 	tcp->tcp_ip6h->ip6_dst = dst;
11090 
11091 	/*
11092 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11093 	 * the default value for TCP.
11094 	 */
11095 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11096 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11097 
11098 	/*
11099 	 * If we're setting extension headers after a connection
11100 	 * has been established, and if we have a routing header
11101 	 * among the extension headers, call ip_massage_options_v6 to
11102 	 * manipulate the routing header/ip6_dst set the checksum
11103 	 * difference in the tcp header template.
11104 	 * (This happens in tcp_connect_ipv6 if the routing header
11105 	 * is set prior to the connect.)
11106 	 * Set the tcp_sum to zero first in case we've cleared a
11107 	 * routing header or don't have one at all.
11108 	 */
11109 	tcp->tcp_sum = 0;
11110 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11111 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11112 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11113 		    (uint8_t *)tcp->tcp_tcph);
11114 		if (rth != NULL) {
11115 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11116 			    rth, tcps->tcps_netstack);
11117 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11118 			    (tcp->tcp_sum >> 16));
11119 		}
11120 	}
11121 
11122 	/* Try to get everything in a single mblk */
11123 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11124 	return (0);
11125 }
11126 
11127 /*
11128  * Transfer any source route option from ipha to buf/dst in reversed form.
11129  */
11130 static int
11131 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11132 {
11133 	ipoptp_t	opts;
11134 	uchar_t		*opt;
11135 	uint8_t		optval;
11136 	uint8_t		optlen;
11137 	uint32_t	len = 0;
11138 
11139 	for (optval = ipoptp_first(&opts, ipha);
11140 	    optval != IPOPT_EOL;
11141 	    optval = ipoptp_next(&opts)) {
11142 		opt = opts.ipoptp_cur;
11143 		optlen = opts.ipoptp_len;
11144 		switch (optval) {
11145 			int	off1, off2;
11146 		case IPOPT_SSRR:
11147 		case IPOPT_LSRR:
11148 
11149 			/* Reverse source route */
11150 			/*
11151 			 * First entry should be the next to last one in the
11152 			 * current source route (the last entry is our
11153 			 * address.)
11154 			 * The last entry should be the final destination.
11155 			 */
11156 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11157 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11158 			off1 = IPOPT_MINOFF_SR - 1;
11159 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11160 			if (off2 < 0) {
11161 				/* No entries in source route */
11162 				break;
11163 			}
11164 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11165 			/*
11166 			 * Note: use src since ipha has not had its src
11167 			 * and dst reversed (it is in the state it was
11168 			 * received.
11169 			 */
11170 			bcopy(&ipha->ipha_src, buf + off2,
11171 			    IP_ADDR_LEN);
11172 			off2 -= IP_ADDR_LEN;
11173 
11174 			while (off2 > 0) {
11175 				bcopy(opt + off2, buf + off1,
11176 				    IP_ADDR_LEN);
11177 				off1 += IP_ADDR_LEN;
11178 				off2 -= IP_ADDR_LEN;
11179 			}
11180 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11181 			buf += optlen;
11182 			len += optlen;
11183 			break;
11184 		}
11185 	}
11186 done:
11187 	/* Pad the resulting options */
11188 	while (len & 0x3) {
11189 		*buf++ = IPOPT_EOL;
11190 		len++;
11191 	}
11192 	return (len);
11193 }
11194 
11195 
11196 /*
11197  * Extract and revert a source route from ipha (if any)
11198  * and then update the relevant fields in both tcp_t and the standard header.
11199  */
11200 static void
11201 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11202 {
11203 	char	buf[TCP_MAX_HDR_LENGTH];
11204 	uint_t	tcph_len;
11205 	int	len;
11206 
11207 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11208 	len = IPH_HDR_LENGTH(ipha);
11209 	if (len == IP_SIMPLE_HDR_LENGTH)
11210 		/* Nothing to do */
11211 		return;
11212 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11213 	    (len & 0x3))
11214 		return;
11215 
11216 	tcph_len = tcp->tcp_tcp_hdr_len;
11217 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11218 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11219 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11220 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11221 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11222 	len += IP_SIMPLE_HDR_LENGTH;
11223 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11224 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11225 	if ((int)tcp->tcp_sum < 0)
11226 		tcp->tcp_sum--;
11227 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11228 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11229 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11230 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11231 	tcp->tcp_ip_hdr_len = len;
11232 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11233 	    (IP_VERSION << 4) | (len >> 2);
11234 	len += tcph_len;
11235 	tcp->tcp_hdr_len = len;
11236 }
11237 
11238 /*
11239  * Copy the standard header into its new location,
11240  * lay in the new options and then update the relevant
11241  * fields in both tcp_t and the standard header.
11242  */
11243 static int
11244 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11245 {
11246 	uint_t	tcph_len;
11247 	uint8_t	*ip_optp;
11248 	tcph_t	*new_tcph;
11249 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11250 
11251 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11252 		return (EINVAL);
11253 
11254 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11255 		return (EINVAL);
11256 
11257 	if (checkonly) {
11258 		/*
11259 		 * do not really set, just pretend to - T_CHECK
11260 		 */
11261 		return (0);
11262 	}
11263 
11264 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11265 	if (tcp->tcp_label_len > 0) {
11266 		int padlen;
11267 		uint8_t opt;
11268 
11269 		/* convert list termination to no-ops */
11270 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11271 		ip_optp += ip_optp[IPOPT_OLEN];
11272 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11273 		while (--padlen >= 0)
11274 			*ip_optp++ = opt;
11275 	}
11276 	tcph_len = tcp->tcp_tcp_hdr_len;
11277 	new_tcph = (tcph_t *)(ip_optp + len);
11278 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11279 	tcp->tcp_tcph = new_tcph;
11280 	bcopy(ptr, ip_optp, len);
11281 
11282 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11283 
11284 	tcp->tcp_ip_hdr_len = len;
11285 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11286 	    (IP_VERSION << 4) | (len >> 2);
11287 	tcp->tcp_hdr_len = len + tcph_len;
11288 	if (!TCP_IS_DETACHED(tcp)) {
11289 		/* Always allocate room for all options. */
11290 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11291 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11292 	}
11293 	return (0);
11294 }
11295 
11296 /* Get callback routine passed to nd_load by tcp_param_register */
11297 /* ARGSUSED */
11298 static int
11299 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11300 {
11301 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11302 
11303 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11304 	return (0);
11305 }
11306 
11307 /*
11308  * Walk through the param array specified registering each element with the
11309  * named dispatch handler.
11310  */
11311 static boolean_t
11312 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11313 {
11314 	for (; cnt-- > 0; tcppa++) {
11315 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11316 			if (!nd_load(ndp, tcppa->tcp_param_name,
11317 			    tcp_param_get, tcp_param_set,
11318 			    (caddr_t)tcppa)) {
11319 				nd_free(ndp);
11320 				return (B_FALSE);
11321 			}
11322 		}
11323 	}
11324 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11325 	    KM_SLEEP);
11326 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11327 	    sizeof (tcpparam_t));
11328 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11329 	    tcp_param_get, tcp_param_set_aligned,
11330 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11331 		nd_free(ndp);
11332 		return (B_FALSE);
11333 	}
11334 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11335 	    KM_SLEEP);
11336 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11337 	    sizeof (tcpparam_t));
11338 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11339 	    tcp_param_get, tcp_param_set_aligned,
11340 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11341 		nd_free(ndp);
11342 		return (B_FALSE);
11343 	}
11344 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11345 	    KM_SLEEP);
11346 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11347 	    sizeof (tcpparam_t));
11348 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11349 	    tcp_param_get, tcp_param_set_aligned,
11350 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11351 		nd_free(ndp);
11352 		return (B_FALSE);
11353 	}
11354 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11355 	    KM_SLEEP);
11356 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11357 	    sizeof (tcpparam_t));
11358 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11359 	    tcp_param_get, tcp_param_set_aligned,
11360 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11361 		nd_free(ndp);
11362 		return (B_FALSE);
11363 	}
11364 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11365 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11366 		nd_free(ndp);
11367 		return (B_FALSE);
11368 	}
11369 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11370 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11371 		nd_free(ndp);
11372 		return (B_FALSE);
11373 	}
11374 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11375 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11376 		nd_free(ndp);
11377 		return (B_FALSE);
11378 	}
11379 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11380 	    NULL)) {
11381 		nd_free(ndp);
11382 		return (B_FALSE);
11383 	}
11384 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11385 	    NULL, NULL)) {
11386 		nd_free(ndp);
11387 		return (B_FALSE);
11388 	}
11389 	if (!nd_load(ndp, "tcp_listen_hash",
11390 	    tcp_listen_hash_report, NULL, NULL)) {
11391 		nd_free(ndp);
11392 		return (B_FALSE);
11393 	}
11394 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11395 	    NULL, NULL)) {
11396 		nd_free(ndp);
11397 		return (B_FALSE);
11398 	}
11399 	if (!nd_load(ndp, "tcp_acceptor_hash",
11400 	    tcp_acceptor_hash_report, NULL, NULL)) {
11401 		nd_free(ndp);
11402 		return (B_FALSE);
11403 	}
11404 	if (!nd_load(ndp, "tcp_host_param", tcp_host_param_report,
11405 	    tcp_host_param_set, NULL)) {
11406 		nd_free(ndp);
11407 		return (B_FALSE);
11408 	}
11409 	if (!nd_load(ndp, "tcp_host_param_ipv6",
11410 	    tcp_host_param_report, tcp_host_param_set_ipv6, NULL)) {
11411 		nd_free(ndp);
11412 		return (B_FALSE);
11413 	}
11414 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11415 	    tcp_1948_phrase_set, NULL)) {
11416 		nd_free(ndp);
11417 		return (B_FALSE);
11418 	}
11419 	if (!nd_load(ndp, "tcp_reserved_port_list",
11420 	    tcp_reserved_port_list, NULL, NULL)) {
11421 		nd_free(ndp);
11422 		return (B_FALSE);
11423 	}
11424 	/*
11425 	 * Dummy ndd variables - only to convey obsolescence information
11426 	 * through printing of their name (no get or set routines)
11427 	 * XXX Remove in future releases ?
11428 	 */
11429 	if (!nd_load(ndp,
11430 	    "tcp_close_wait_interval(obsoleted - "
11431 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11432 		nd_free(ndp);
11433 		return (B_FALSE);
11434 	}
11435 	return (B_TRUE);
11436 }
11437 
11438 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11439 /* ARGSUSED */
11440 static int
11441 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11442     cred_t *cr)
11443 {
11444 	long new_value;
11445 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11446 
11447 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11448 	    new_value < tcppa->tcp_param_min ||
11449 	    new_value > tcppa->tcp_param_max) {
11450 		return (EINVAL);
11451 	}
11452 	/*
11453 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11454 	 * round it up.  For future 64 bit requirement, we actually make it
11455 	 * a multiple of 8.
11456 	 */
11457 	if (new_value & 0x7) {
11458 		new_value = (new_value & ~0x7) + 0x8;
11459 	}
11460 	tcppa->tcp_param_val = new_value;
11461 	return (0);
11462 }
11463 
11464 /* Set callback routine passed to nd_load by tcp_param_register */
11465 /* ARGSUSED */
11466 static int
11467 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11468 {
11469 	long	new_value;
11470 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11471 
11472 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11473 	    new_value < tcppa->tcp_param_min ||
11474 	    new_value > tcppa->tcp_param_max) {
11475 		return (EINVAL);
11476 	}
11477 	tcppa->tcp_param_val = new_value;
11478 	return (0);
11479 }
11480 
11481 /*
11482  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11483  * is filled, return as much as we can.  The message passed in may be
11484  * multi-part, chained using b_cont.  "start" is the starting sequence
11485  * number for this piece.
11486  */
11487 static mblk_t *
11488 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11489 {
11490 	uint32_t	end;
11491 	mblk_t		*mp1;
11492 	mblk_t		*mp2;
11493 	mblk_t		*next_mp;
11494 	uint32_t	u1;
11495 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11496 
11497 	/* Walk through all the new pieces. */
11498 	do {
11499 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11500 		    (uintptr_t)INT_MAX);
11501 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11502 		next_mp = mp->b_cont;
11503 		if (start == end) {
11504 			/* Empty.  Blast it. */
11505 			freeb(mp);
11506 			continue;
11507 		}
11508 		mp->b_cont = NULL;
11509 		TCP_REASS_SET_SEQ(mp, start);
11510 		TCP_REASS_SET_END(mp, end);
11511 		mp1 = tcp->tcp_reass_tail;
11512 		if (!mp1) {
11513 			tcp->tcp_reass_tail = mp;
11514 			tcp->tcp_reass_head = mp;
11515 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11516 			UPDATE_MIB(&tcps->tcps_mib,
11517 			    tcpInDataUnorderBytes, end - start);
11518 			continue;
11519 		}
11520 		/* New stuff completely beyond tail? */
11521 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11522 			/* Link it on end. */
11523 			mp1->b_cont = mp;
11524 			tcp->tcp_reass_tail = mp;
11525 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11526 			UPDATE_MIB(&tcps->tcps_mib,
11527 			    tcpInDataUnorderBytes, end - start);
11528 			continue;
11529 		}
11530 		mp1 = tcp->tcp_reass_head;
11531 		u1 = TCP_REASS_SEQ(mp1);
11532 		/* New stuff at the front? */
11533 		if (SEQ_LT(start, u1)) {
11534 			/* Yes... Check for overlap. */
11535 			mp->b_cont = mp1;
11536 			tcp->tcp_reass_head = mp;
11537 			tcp_reass_elim_overlap(tcp, mp);
11538 			continue;
11539 		}
11540 		/*
11541 		 * The new piece fits somewhere between the head and tail.
11542 		 * We find our slot, where mp1 precedes us and mp2 trails.
11543 		 */
11544 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11545 			u1 = TCP_REASS_SEQ(mp2);
11546 			if (SEQ_LEQ(start, u1))
11547 				break;
11548 		}
11549 		/* Link ourselves in */
11550 		mp->b_cont = mp2;
11551 		mp1->b_cont = mp;
11552 
11553 		/* Trim overlap with following mblk(s) first */
11554 		tcp_reass_elim_overlap(tcp, mp);
11555 
11556 		/* Trim overlap with preceding mblk */
11557 		tcp_reass_elim_overlap(tcp, mp1);
11558 
11559 	} while (start = end, mp = next_mp);
11560 	mp1 = tcp->tcp_reass_head;
11561 	/* Anything ready to go? */
11562 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11563 		return (NULL);
11564 	/* Eat what we can off the queue */
11565 	for (;;) {
11566 		mp = mp1->b_cont;
11567 		end = TCP_REASS_END(mp1);
11568 		TCP_REASS_SET_SEQ(mp1, 0);
11569 		TCP_REASS_SET_END(mp1, 0);
11570 		if (!mp) {
11571 			tcp->tcp_reass_tail = NULL;
11572 			break;
11573 		}
11574 		if (end != TCP_REASS_SEQ(mp)) {
11575 			mp1->b_cont = NULL;
11576 			break;
11577 		}
11578 		mp1 = mp;
11579 	}
11580 	mp1 = tcp->tcp_reass_head;
11581 	tcp->tcp_reass_head = mp;
11582 	return (mp1);
11583 }
11584 
11585 /* Eliminate any overlap that mp may have over later mblks */
11586 static void
11587 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11588 {
11589 	uint32_t	end;
11590 	mblk_t		*mp1;
11591 	uint32_t	u1;
11592 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11593 
11594 	end = TCP_REASS_END(mp);
11595 	while ((mp1 = mp->b_cont) != NULL) {
11596 		u1 = TCP_REASS_SEQ(mp1);
11597 		if (!SEQ_GT(end, u1))
11598 			break;
11599 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11600 			mp->b_wptr -= end - u1;
11601 			TCP_REASS_SET_END(mp, u1);
11602 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11603 			UPDATE_MIB(&tcps->tcps_mib,
11604 			    tcpInDataPartDupBytes, end - u1);
11605 			break;
11606 		}
11607 		mp->b_cont = mp1->b_cont;
11608 		TCP_REASS_SET_SEQ(mp1, 0);
11609 		TCP_REASS_SET_END(mp1, 0);
11610 		freeb(mp1);
11611 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11612 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11613 	}
11614 	if (!mp1)
11615 		tcp->tcp_reass_tail = mp;
11616 }
11617 
11618 /*
11619  * Send up all messages queued on tcp_rcv_list.
11620  */
11621 static uint_t
11622 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11623 {
11624 	mblk_t *mp;
11625 	uint_t ret = 0;
11626 	uint_t thwin;
11627 #ifdef DEBUG
11628 	uint_t cnt = 0;
11629 #endif
11630 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11631 
11632 	/* Can't drain on an eager connection */
11633 	if (tcp->tcp_listener != NULL)
11634 		return (ret);
11635 
11636 	/*
11637 	 * Handle two cases here: we are currently fused or we were
11638 	 * previously fused and have some urgent data to be delivered
11639 	 * upstream.  The latter happens because we either ran out of
11640 	 * memory or were detached and therefore sending the SIGURG was
11641 	 * deferred until this point.  In either case we pass control
11642 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11643 	 * some work.
11644 	 */
11645 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11646 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11647 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11648 		    &tcp->tcp_fused_sigurg_mp))
11649 			return (ret);
11650 	}
11651 
11652 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11653 		tcp->tcp_rcv_list = mp->b_next;
11654 		mp->b_next = NULL;
11655 #ifdef DEBUG
11656 		cnt += msgdsize(mp);
11657 #endif
11658 		/* Does this need SSL processing first? */
11659 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11660 			tcp_kssl_input(tcp, mp);
11661 			continue;
11662 		}
11663 		putnext(q, mp);
11664 	}
11665 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11666 	tcp->tcp_rcv_last_head = NULL;
11667 	tcp->tcp_rcv_last_tail = NULL;
11668 	tcp->tcp_rcv_cnt = 0;
11669 
11670 	/* Learn the latest rwnd information that we sent to the other side. */
11671 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11672 	    << tcp->tcp_rcv_ws;
11673 	/* This is peer's calculated send window (our receive window). */
11674 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11675 	/*
11676 	 * Increase the receive window to max.  But we need to do receiver
11677 	 * SWS avoidance.  This means that we need to check the increase of
11678 	 * of receive window is at least 1 MSS.
11679 	 */
11680 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11681 		/*
11682 		 * If the window that the other side knows is less than max
11683 		 * deferred acks segments, send an update immediately.
11684 		 */
11685 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11686 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11687 			ret = TH_ACK_NEEDED;
11688 		}
11689 		tcp->tcp_rwnd = q->q_hiwat;
11690 	}
11691 	/* No need for the push timer now. */
11692 	if (tcp->tcp_push_tid != 0) {
11693 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11694 		tcp->tcp_push_tid = 0;
11695 	}
11696 	return (ret);
11697 }
11698 
11699 /*
11700  * Queue data on tcp_rcv_list which is a b_next chain.
11701  * tcp_rcv_last_head/tail is the last element of this chain.
11702  * Each element of the chain is a b_cont chain.
11703  *
11704  * M_DATA messages are added to the current element.
11705  * Other messages are added as new (b_next) elements.
11706  */
11707 void
11708 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11709 {
11710 	ASSERT(seg_len == msgdsize(mp));
11711 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11712 
11713 	if (tcp->tcp_rcv_list == NULL) {
11714 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11715 		tcp->tcp_rcv_list = mp;
11716 		tcp->tcp_rcv_last_head = mp;
11717 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11718 		tcp->tcp_rcv_last_tail->b_cont = mp;
11719 	} else {
11720 		tcp->tcp_rcv_last_head->b_next = mp;
11721 		tcp->tcp_rcv_last_head = mp;
11722 	}
11723 
11724 	while (mp->b_cont)
11725 		mp = mp->b_cont;
11726 
11727 	tcp->tcp_rcv_last_tail = mp;
11728 	tcp->tcp_rcv_cnt += seg_len;
11729 	tcp->tcp_rwnd -= seg_len;
11730 }
11731 
11732 /*
11733  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11734  *
11735  * This is the default entry function into TCP on the read side. TCP is
11736  * always entered via squeue i.e. using squeue's for mutual exclusion.
11737  * When classifier does a lookup to find the tcp, it also puts a reference
11738  * on the conn structure associated so the tcp is guaranteed to exist
11739  * when we come here. We still need to check the state because it might
11740  * as well has been closed. The squeue processing function i.e. squeue_enter,
11741  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11742  * CONN_DEC_REF.
11743  *
11744  * Apart from the default entry point, IP also sends packets directly to
11745  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11746  * connections.
11747  */
11748 void
11749 tcp_input(void *arg, mblk_t *mp, void *arg2)
11750 {
11751 	conn_t	*connp = (conn_t *)arg;
11752 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11753 
11754 	/* arg2 is the sqp */
11755 	ASSERT(arg2 != NULL);
11756 	ASSERT(mp != NULL);
11757 
11758 	/*
11759 	 * Don't accept any input on a closed tcp as this TCP logically does
11760 	 * not exist on the system. Don't proceed further with this TCP.
11761 	 * For eg. this packet could trigger another close of this tcp
11762 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11763 	 * tcp_clean_death / tcp_closei_local must be called at most once
11764 	 * on a TCP. In this case we need to refeed the packet into the
11765 	 * classifier and figure out where the packet should go. Need to
11766 	 * preserve the recv_ill somehow. Until we figure that out, for
11767 	 * now just drop the packet if we can't classify the packet.
11768 	 */
11769 	if (tcp->tcp_state == TCPS_CLOSED ||
11770 	    tcp->tcp_state == TCPS_BOUND) {
11771 		conn_t	*new_connp;
11772 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11773 
11774 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11775 		if (new_connp != NULL) {
11776 			tcp_reinput(new_connp, mp, arg2);
11777 			return;
11778 		}
11779 		/* We failed to classify. For now just drop the packet */
11780 		freemsg(mp);
11781 		return;
11782 	}
11783 
11784 	if (DB_TYPE(mp) == M_DATA)
11785 		tcp_rput_data(connp, mp, arg2);
11786 	else
11787 		tcp_rput_common(tcp, mp);
11788 }
11789 
11790 /*
11791  * The read side put procedure.
11792  * The packets passed up by ip are assume to be aligned according to
11793  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11794  */
11795 static void
11796 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11797 {
11798 	/*
11799 	 * tcp_rput_data() does not expect M_CTL except for the case
11800 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11801 	 * type. Need to make sure that any other M_CTLs don't make
11802 	 * it to tcp_rput_data since it is not expecting any and doesn't
11803 	 * check for it.
11804 	 */
11805 	if (DB_TYPE(mp) == M_CTL) {
11806 		switch (*(uint32_t *)(mp->b_rptr)) {
11807 		case TCP_IOC_ABORT_CONN:
11808 			/*
11809 			 * Handle connection abort request.
11810 			 */
11811 			tcp_ioctl_abort_handler(tcp, mp);
11812 			return;
11813 		case IPSEC_IN:
11814 			/*
11815 			 * Only secure icmp arrive in TCP and they
11816 			 * don't go through data path.
11817 			 */
11818 			tcp_icmp_error(tcp, mp);
11819 			return;
11820 		case IN_PKTINFO:
11821 			/*
11822 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11823 			 * sockets that are receiving IPv4 traffic. tcp
11824 			 */
11825 			ASSERT(tcp->tcp_family == AF_INET6);
11826 			ASSERT(tcp->tcp_ipv6_recvancillary &
11827 			    TCP_IPV6_RECVPKTINFO);
11828 			tcp_rput_data(tcp->tcp_connp, mp,
11829 			    tcp->tcp_connp->conn_sqp);
11830 			return;
11831 		case MDT_IOC_INFO_UPDATE:
11832 			/*
11833 			 * Handle Multidata information update; the
11834 			 * following routine will free the message.
11835 			 */
11836 			if (tcp->tcp_connp->conn_mdt_ok) {
11837 				tcp_mdt_update(tcp,
11838 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11839 				    B_FALSE);
11840 			}
11841 			freemsg(mp);
11842 			return;
11843 		case LSO_IOC_INFO_UPDATE:
11844 			/*
11845 			 * Handle LSO information update; the following
11846 			 * routine will free the message.
11847 			 */
11848 			if (tcp->tcp_connp->conn_lso_ok) {
11849 				tcp_lso_update(tcp,
11850 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11851 			}
11852 			freemsg(mp);
11853 			return;
11854 		default:
11855 			/*
11856 			 * tcp_icmp_err() will process the M_CTL packets.
11857 			 * Non-ICMP packets, if any, will be discarded in
11858 			 * tcp_icmp_err(). We will process the ICMP packet
11859 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11860 			 * incoming ICMP packet may result in changing
11861 			 * the tcp_mss, which we would need if we have
11862 			 * packets to retransmit.
11863 			 */
11864 			tcp_icmp_error(tcp, mp);
11865 			return;
11866 		}
11867 	}
11868 
11869 	/* No point processing the message if tcp is already closed */
11870 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11871 		freemsg(mp);
11872 		return;
11873 	}
11874 
11875 	tcp_rput_other(tcp, mp);
11876 }
11877 
11878 
11879 /* The minimum of smoothed mean deviation in RTO calculation. */
11880 #define	TCP_SD_MIN	400
11881 
11882 /*
11883  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11884  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11885  * are the same as those in Appendix A.2 of that paper.
11886  *
11887  * m = new measurement
11888  * sa = smoothed RTT average (8 * average estimates).
11889  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11890  */
11891 static void
11892 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11893 {
11894 	long m = TICK_TO_MSEC(rtt);
11895 	clock_t sa = tcp->tcp_rtt_sa;
11896 	clock_t sv = tcp->tcp_rtt_sd;
11897 	clock_t rto;
11898 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11899 
11900 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11901 	tcp->tcp_rtt_update++;
11902 
11903 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11904 	if (sa != 0) {
11905 		/*
11906 		 * Update average estimator:
11907 		 *	new rtt = 7/8 old rtt + 1/8 Error
11908 		 */
11909 
11910 		/* m is now Error in estimate. */
11911 		m -= sa >> 3;
11912 		if ((sa += m) <= 0) {
11913 			/*
11914 			 * Don't allow the smoothed average to be negative.
11915 			 * We use 0 to denote reinitialization of the
11916 			 * variables.
11917 			 */
11918 			sa = 1;
11919 		}
11920 
11921 		/*
11922 		 * Update deviation estimator:
11923 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11924 		 */
11925 		if (m < 0)
11926 			m = -m;
11927 		m -= sv >> 2;
11928 		sv += m;
11929 	} else {
11930 		/*
11931 		 * This follows BSD's implementation.  So the reinitialized
11932 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11933 		 * link is bandwidth dominated, doubling the window size
11934 		 * during slow start means doubling the RTT.  We want to be
11935 		 * more conservative when we reinitialize our estimates.  3
11936 		 * is just a convenient number.
11937 		 */
11938 		sa = m << 3;
11939 		sv = m << 1;
11940 	}
11941 	if (sv < TCP_SD_MIN) {
11942 		/*
11943 		 * We do not know that if sa captures the delay ACK
11944 		 * effect as in a long train of segments, a receiver
11945 		 * does not delay its ACKs.  So set the minimum of sv
11946 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11947 		 * of BSD DATO.  That means the minimum of mean
11948 		 * deviation is 100 ms.
11949 		 *
11950 		 */
11951 		sv = TCP_SD_MIN;
11952 	}
11953 	tcp->tcp_rtt_sa = sa;
11954 	tcp->tcp_rtt_sd = sv;
11955 	/*
11956 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11957 	 *
11958 	 * Add tcp_rexmit_interval extra in case of extreme environment
11959 	 * where the algorithm fails to work.  The default value of
11960 	 * tcp_rexmit_interval_extra should be 0.
11961 	 *
11962 	 * As we use a finer grained clock than BSD and update
11963 	 * RTO for every ACKs, add in another .25 of RTT to the
11964 	 * deviation of RTO to accomodate burstiness of 1/4 of
11965 	 * window size.
11966 	 */
11967 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11968 
11969 	if (rto > tcps->tcps_rexmit_interval_max) {
11970 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11971 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11972 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11973 	} else {
11974 		tcp->tcp_rto = rto;
11975 	}
11976 
11977 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11978 	tcp->tcp_timer_backoff = 0;
11979 }
11980 
11981 /*
11982  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11983  * send queue which starts at the given seq. no.
11984  *
11985  * Parameters:
11986  *	tcp_t *tcp: the tcp instance pointer.
11987  *	uint32_t seq: the starting seq. no of the requested segment.
11988  *	int32_t *off: after the execution, *off will be the offset to
11989  *		the returned mblk which points to the requested seq no.
11990  *		It is the caller's responsibility to send in a non-null off.
11991  *
11992  * Return:
11993  *	A mblk_t pointer pointing to the requested segment in send queue.
11994  */
11995 static mblk_t *
11996 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11997 {
11998 	int32_t	cnt;
11999 	mblk_t	*mp;
12000 
12001 	/* Defensive coding.  Make sure we don't send incorrect data. */
12002 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12003 		return (NULL);
12004 
12005 	cnt = seq - tcp->tcp_suna;
12006 	mp = tcp->tcp_xmit_head;
12007 	while (cnt > 0 && mp != NULL) {
12008 		cnt -= mp->b_wptr - mp->b_rptr;
12009 		if (cnt < 0) {
12010 			cnt += mp->b_wptr - mp->b_rptr;
12011 			break;
12012 		}
12013 		mp = mp->b_cont;
12014 	}
12015 	ASSERT(mp != NULL);
12016 	*off = cnt;
12017 	return (mp);
12018 }
12019 
12020 /*
12021  * This function handles all retransmissions if SACK is enabled for this
12022  * connection.  First it calculates how many segments can be retransmitted
12023  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12024  * segments.  A segment is eligible if sack_cnt for that segment is greater
12025  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12026  * all eligible segments, it checks to see if TCP can send some new segments
12027  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12028  *
12029  * Parameters:
12030  *	tcp_t *tcp: the tcp structure of the connection.
12031  *	uint_t *flags: in return, appropriate value will be set for
12032  *	tcp_rput_data().
12033  */
12034 static void
12035 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12036 {
12037 	notsack_blk_t	*notsack_blk;
12038 	int32_t		usable_swnd;
12039 	int32_t		mss;
12040 	uint32_t	seg_len;
12041 	mblk_t		*xmit_mp;
12042 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12043 
12044 	ASSERT(tcp->tcp_sack_info != NULL);
12045 	ASSERT(tcp->tcp_notsack_list != NULL);
12046 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12047 
12048 	/* Defensive coding in case there is a bug... */
12049 	if (tcp->tcp_notsack_list == NULL) {
12050 		return;
12051 	}
12052 	notsack_blk = tcp->tcp_notsack_list;
12053 	mss = tcp->tcp_mss;
12054 
12055 	/*
12056 	 * Limit the num of outstanding data in the network to be
12057 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12058 	 */
12059 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12060 
12061 	/* At least retransmit 1 MSS of data. */
12062 	if (usable_swnd <= 0) {
12063 		usable_swnd = mss;
12064 	}
12065 
12066 	/* Make sure no new RTT samples will be taken. */
12067 	tcp->tcp_csuna = tcp->tcp_snxt;
12068 
12069 	notsack_blk = tcp->tcp_notsack_list;
12070 	while (usable_swnd > 0) {
12071 		mblk_t		*snxt_mp, *tmp_mp;
12072 		tcp_seq		begin = tcp->tcp_sack_snxt;
12073 		tcp_seq		end;
12074 		int32_t		off;
12075 
12076 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12077 			if (SEQ_GT(notsack_blk->end, begin) &&
12078 			    (notsack_blk->sack_cnt >=
12079 			    tcps->tcps_dupack_fast_retransmit)) {
12080 				end = notsack_blk->end;
12081 				if (SEQ_LT(begin, notsack_blk->begin)) {
12082 					begin = notsack_blk->begin;
12083 				}
12084 				break;
12085 			}
12086 		}
12087 		/*
12088 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12089 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12090 		 * set to tcp_cwnd_ssthresh.
12091 		 */
12092 		if (notsack_blk == NULL) {
12093 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12094 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12095 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12096 				ASSERT(tcp->tcp_cwnd > 0);
12097 				return;
12098 			} else {
12099 				usable_swnd = usable_swnd / mss;
12100 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12101 				    MAX(usable_swnd * mss, mss);
12102 				*flags |= TH_XMIT_NEEDED;
12103 				return;
12104 			}
12105 		}
12106 
12107 		/*
12108 		 * Note that we may send more than usable_swnd allows here
12109 		 * because of round off, but no more than 1 MSS of data.
12110 		 */
12111 		seg_len = end - begin;
12112 		if (seg_len > mss)
12113 			seg_len = mss;
12114 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12115 		ASSERT(snxt_mp != NULL);
12116 		/* This should not happen.  Defensive coding again... */
12117 		if (snxt_mp == NULL) {
12118 			return;
12119 		}
12120 
12121 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12122 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12123 		if (xmit_mp == NULL)
12124 			return;
12125 
12126 		usable_swnd -= seg_len;
12127 		tcp->tcp_pipe += seg_len;
12128 		tcp->tcp_sack_snxt = begin + seg_len;
12129 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12130 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12131 
12132 		/*
12133 		 * Update the send timestamp to avoid false retransmission.
12134 		 */
12135 		snxt_mp->b_prev = (mblk_t *)lbolt;
12136 
12137 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12138 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12139 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12140 		/*
12141 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12142 		 * This happens when new data sent during fast recovery is
12143 		 * also lost.  If TCP retransmits those new data, it needs
12144 		 * to extend SACK recover phase to avoid starting another
12145 		 * fast retransmit/recovery unnecessarily.
12146 		 */
12147 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12148 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12149 		}
12150 	}
12151 }
12152 
12153 /*
12154  * This function handles policy checking at TCP level for non-hard_bound/
12155  * detached connections.
12156  */
12157 static boolean_t
12158 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12159     boolean_t secure, boolean_t mctl_present)
12160 {
12161 	ipsec_latch_t *ipl = NULL;
12162 	ipsec_action_t *act = NULL;
12163 	mblk_t *data_mp;
12164 	ipsec_in_t *ii;
12165 	const char *reason;
12166 	kstat_named_t *counter;
12167 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12168 	ipsec_stack_t	*ipss;
12169 	ip_stack_t	*ipst;
12170 
12171 	ASSERT(mctl_present || !secure);
12172 
12173 	ASSERT((ipha == NULL && ip6h != NULL) ||
12174 	    (ip6h == NULL && ipha != NULL));
12175 
12176 	/*
12177 	 * We don't necessarily have an ipsec_in_act action to verify
12178 	 * policy because of assymetrical policy where we have only
12179 	 * outbound policy and no inbound policy (possible with global
12180 	 * policy).
12181 	 */
12182 	if (!secure) {
12183 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12184 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12185 			return (B_TRUE);
12186 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12187 		    "tcp_check_policy", ipha, ip6h, secure,
12188 		    tcps->tcps_netstack);
12189 		ipss = tcps->tcps_netstack->netstack_ipsec;
12190 
12191 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12192 		    DROPPER(ipss, ipds_tcp_clear),
12193 		    &tcps->tcps_dropper);
12194 		return (B_FALSE);
12195 	}
12196 
12197 	/*
12198 	 * We have a secure packet.
12199 	 */
12200 	if (act == NULL) {
12201 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12202 		    "tcp_check_policy", ipha, ip6h, secure,
12203 		    tcps->tcps_netstack);
12204 		ipss = tcps->tcps_netstack->netstack_ipsec;
12205 
12206 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12207 		    DROPPER(ipss, ipds_tcp_secure),
12208 		    &tcps->tcps_dropper);
12209 		return (B_FALSE);
12210 	}
12211 
12212 	/*
12213 	 * XXX This whole routine is currently incorrect.  ipl should
12214 	 * be set to the latch pointer, but is currently not set, so
12215 	 * we initialize it to NULL to avoid picking up random garbage.
12216 	 */
12217 	if (ipl == NULL)
12218 		return (B_TRUE);
12219 
12220 	data_mp = first_mp->b_cont;
12221 
12222 	ii = (ipsec_in_t *)first_mp->b_rptr;
12223 
12224 	ipst = tcps->tcps_netstack->netstack_ip;
12225 
12226 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12227 	    &counter, tcp->tcp_connp)) {
12228 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12229 		return (B_TRUE);
12230 	}
12231 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12232 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12233 	    reason);
12234 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12235 
12236 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12237 	    &tcps->tcps_dropper);
12238 	return (B_FALSE);
12239 }
12240 
12241 /*
12242  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12243  * retransmission after a timeout.
12244  *
12245  * To limit the number of duplicate segments, we limit the number of segment
12246  * to be sent in one time to tcp_snd_burst, the burst variable.
12247  */
12248 static void
12249 tcp_ss_rexmit(tcp_t *tcp)
12250 {
12251 	uint32_t	snxt;
12252 	uint32_t	smax;
12253 	int32_t		win;
12254 	int32_t		mss;
12255 	int32_t		off;
12256 	int32_t		burst = tcp->tcp_snd_burst;
12257 	mblk_t		*snxt_mp;
12258 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12259 
12260 	/*
12261 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12262 	 * all unack'ed segments.
12263 	 */
12264 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12265 		smax = tcp->tcp_rexmit_max;
12266 		snxt = tcp->tcp_rexmit_nxt;
12267 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12268 			snxt = tcp->tcp_suna;
12269 		}
12270 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12271 		win -= snxt - tcp->tcp_suna;
12272 		mss = tcp->tcp_mss;
12273 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12274 
12275 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12276 		    (burst > 0) && (snxt_mp != NULL)) {
12277 			mblk_t	*xmit_mp;
12278 			mblk_t	*old_snxt_mp = snxt_mp;
12279 			uint32_t cnt = mss;
12280 
12281 			if (win < cnt) {
12282 				cnt = win;
12283 			}
12284 			if (SEQ_GT(snxt + cnt, smax)) {
12285 				cnt = smax - snxt;
12286 			}
12287 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12288 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12289 			if (xmit_mp == NULL)
12290 				return;
12291 
12292 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12293 
12294 			snxt += cnt;
12295 			win -= cnt;
12296 			/*
12297 			 * Update the send timestamp to avoid false
12298 			 * retransmission.
12299 			 */
12300 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12301 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12302 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12303 
12304 			tcp->tcp_rexmit_nxt = snxt;
12305 			burst--;
12306 		}
12307 		/*
12308 		 * If we have transmitted all we have at the time
12309 		 * we started the retranmission, we can leave
12310 		 * the rest of the job to tcp_wput_data().  But we
12311 		 * need to check the send window first.  If the
12312 		 * win is not 0, go on with tcp_wput_data().
12313 		 */
12314 		if (SEQ_LT(snxt, smax) || win == 0) {
12315 			return;
12316 		}
12317 	}
12318 	/* Only call tcp_wput_data() if there is data to be sent. */
12319 	if (tcp->tcp_unsent) {
12320 		tcp_wput_data(tcp, NULL, B_FALSE);
12321 	}
12322 }
12323 
12324 /*
12325  * Process all TCP option in SYN segment.  Note that this function should
12326  * be called after tcp_adapt_ire() is called so that the necessary info
12327  * from IRE is already set in the tcp structure.
12328  *
12329  * This function sets up the correct tcp_mss value according to the
12330  * MSS option value and our header size.  It also sets up the window scale
12331  * and timestamp values, and initialize SACK info blocks.  But it does not
12332  * change receive window size after setting the tcp_mss value.  The caller
12333  * should do the appropriate change.
12334  */
12335 void
12336 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12337 {
12338 	int options;
12339 	tcp_opt_t tcpopt;
12340 	uint32_t mss_max;
12341 	char *tmp_tcph;
12342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12343 
12344 	tcpopt.tcp = NULL;
12345 	options = tcp_parse_options(tcph, &tcpopt);
12346 
12347 	/*
12348 	 * Process MSS option.  Note that MSS option value does not account
12349 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12350 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12351 	 * IPv6.
12352 	 */
12353 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12354 		if (tcp->tcp_ipversion == IPV4_VERSION)
12355 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12356 		else
12357 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12358 	} else {
12359 		if (tcp->tcp_ipversion == IPV4_VERSION)
12360 			mss_max = tcps->tcps_mss_max_ipv4;
12361 		else
12362 			mss_max = tcps->tcps_mss_max_ipv6;
12363 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12364 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12365 		else if (tcpopt.tcp_opt_mss > mss_max)
12366 			tcpopt.tcp_opt_mss = mss_max;
12367 	}
12368 
12369 	/* Process Window Scale option. */
12370 	if (options & TCP_OPT_WSCALE_PRESENT) {
12371 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12372 		tcp->tcp_snd_ws_ok = B_TRUE;
12373 	} else {
12374 		tcp->tcp_snd_ws = B_FALSE;
12375 		tcp->tcp_snd_ws_ok = B_FALSE;
12376 		tcp->tcp_rcv_ws = B_FALSE;
12377 	}
12378 
12379 	/* Process Timestamp option. */
12380 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12381 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12382 		tmp_tcph = (char *)tcp->tcp_tcph;
12383 
12384 		tcp->tcp_snd_ts_ok = B_TRUE;
12385 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12386 		tcp->tcp_last_rcv_lbolt = lbolt64;
12387 		ASSERT(OK_32PTR(tmp_tcph));
12388 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12389 
12390 		/* Fill in our template header with basic timestamp option. */
12391 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12392 		tmp_tcph[0] = TCPOPT_NOP;
12393 		tmp_tcph[1] = TCPOPT_NOP;
12394 		tmp_tcph[2] = TCPOPT_TSTAMP;
12395 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12396 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12397 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12398 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12399 	} else {
12400 		tcp->tcp_snd_ts_ok = B_FALSE;
12401 	}
12402 
12403 	/*
12404 	 * Process SACK options.  If SACK is enabled for this connection,
12405 	 * then allocate the SACK info structure.  Note the following ways
12406 	 * when tcp_snd_sack_ok is set to true.
12407 	 *
12408 	 * For active connection: in tcp_adapt_ire() called in
12409 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12410 	 * is checked.
12411 	 *
12412 	 * For passive connection: in tcp_adapt_ire() called in
12413 	 * tcp_accept_comm().
12414 	 *
12415 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12416 	 * That check makes sure that if we did not send a SACK OK option,
12417 	 * we will not enable SACK for this connection even though the other
12418 	 * side sends us SACK OK option.  For active connection, the SACK
12419 	 * info structure has already been allocated.  So we need to free
12420 	 * it if SACK is disabled.
12421 	 */
12422 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12423 	    (tcp->tcp_snd_sack_ok ||
12424 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12425 		/* This should be true only in the passive case. */
12426 		if (tcp->tcp_sack_info == NULL) {
12427 			ASSERT(TCP_IS_DETACHED(tcp));
12428 			tcp->tcp_sack_info =
12429 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12430 		}
12431 		if (tcp->tcp_sack_info == NULL) {
12432 			tcp->tcp_snd_sack_ok = B_FALSE;
12433 		} else {
12434 			tcp->tcp_snd_sack_ok = B_TRUE;
12435 			if (tcp->tcp_snd_ts_ok) {
12436 				tcp->tcp_max_sack_blk = 3;
12437 			} else {
12438 				tcp->tcp_max_sack_blk = 4;
12439 			}
12440 		}
12441 	} else {
12442 		/*
12443 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12444 		 * no SACK info will be used for this
12445 		 * connection.  This assumes that SACK usage
12446 		 * permission is negotiated.  This may need
12447 		 * to be changed once this is clarified.
12448 		 */
12449 		if (tcp->tcp_sack_info != NULL) {
12450 			ASSERT(tcp->tcp_notsack_list == NULL);
12451 			kmem_cache_free(tcp_sack_info_cache,
12452 			    tcp->tcp_sack_info);
12453 			tcp->tcp_sack_info = NULL;
12454 		}
12455 		tcp->tcp_snd_sack_ok = B_FALSE;
12456 	}
12457 
12458 	/*
12459 	 * Now we know the exact TCP/IP header length, subtract
12460 	 * that from tcp_mss to get our side's MSS.
12461 	 */
12462 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12463 	/*
12464 	 * Here we assume that the other side's header size will be equal to
12465 	 * our header size.  We calculate the real MSS accordingly.  Need to
12466 	 * take into additional stuffs IPsec puts in.
12467 	 *
12468 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12469 	 */
12470 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12471 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12472 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12473 
12474 	/*
12475 	 * Set MSS to the smaller one of both ends of the connection.
12476 	 * We should not have called tcp_mss_set() before, but our
12477 	 * side of the MSS should have been set to a proper value
12478 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12479 	 * STREAM head parameters properly.
12480 	 *
12481 	 * If we have a larger-than-16-bit window but the other side
12482 	 * didn't want to do window scale, tcp_rwnd_set() will take
12483 	 * care of that.
12484 	 */
12485 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12486 }
12487 
12488 /*
12489  * Sends the T_CONN_IND to the listener. The caller calls this
12490  * functions via squeue to get inside the listener's perimeter
12491  * once the 3 way hand shake is done a T_CONN_IND needs to be
12492  * sent. As an optimization, the caller can call this directly
12493  * if listener's perimeter is same as eager's.
12494  */
12495 /* ARGSUSED */
12496 void
12497 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12498 {
12499 	conn_t			*lconnp = (conn_t *)arg;
12500 	tcp_t			*listener = lconnp->conn_tcp;
12501 	tcp_t			*tcp;
12502 	struct T_conn_ind	*conn_ind;
12503 	ipaddr_t 		*addr_cache;
12504 	boolean_t		need_send_conn_ind = B_FALSE;
12505 	tcp_stack_t		*tcps = listener->tcp_tcps;
12506 
12507 	/* retrieve the eager */
12508 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12509 	ASSERT(conn_ind->OPT_offset != 0 &&
12510 	    conn_ind->OPT_length == sizeof (intptr_t));
12511 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12512 		conn_ind->OPT_length);
12513 
12514 	/*
12515 	 * TLI/XTI applications will get confused by
12516 	 * sending eager as an option since it violates
12517 	 * the option semantics. So remove the eager as
12518 	 * option since TLI/XTI app doesn't need it anyway.
12519 	 */
12520 	if (!TCP_IS_SOCKET(listener)) {
12521 		conn_ind->OPT_length = 0;
12522 		conn_ind->OPT_offset = 0;
12523 	}
12524 	if (listener->tcp_state == TCPS_CLOSED ||
12525 	    TCP_IS_DETACHED(listener)) {
12526 		/*
12527 		 * If listener has closed, it would have caused a
12528 		 * a cleanup/blowoff to happen for the eager. We
12529 		 * just need to return.
12530 		 */
12531 		freemsg(mp);
12532 		return;
12533 	}
12534 
12535 
12536 	/*
12537 	 * if the conn_req_q is full defer passing up the
12538 	 * T_CONN_IND until space is availabe after t_accept()
12539 	 * processing
12540 	 */
12541 	mutex_enter(&listener->tcp_eager_lock);
12542 
12543 	/*
12544 	 * Take the eager out, if it is in the list of droppable eagers
12545 	 * as we are here because the 3W handshake is over.
12546 	 */
12547 	MAKE_UNDROPPABLE(tcp);
12548 
12549 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12550 		tcp_t *tail;
12551 
12552 		/*
12553 		 * The eager already has an extra ref put in tcp_rput_data
12554 		 * so that it stays till accept comes back even though it
12555 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12556 		 */
12557 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12558 		listener->tcp_conn_req_cnt_q0--;
12559 		listener->tcp_conn_req_cnt_q++;
12560 
12561 		/* Move from SYN_RCVD to ESTABLISHED list  */
12562 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12563 		    tcp->tcp_eager_prev_q0;
12564 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12565 		    tcp->tcp_eager_next_q0;
12566 		tcp->tcp_eager_prev_q0 = NULL;
12567 		tcp->tcp_eager_next_q0 = NULL;
12568 
12569 		/*
12570 		 * Insert at end of the queue because sockfs
12571 		 * sends down T_CONN_RES in chronological
12572 		 * order. Leaving the older conn indications
12573 		 * at front of the queue helps reducing search
12574 		 * time.
12575 		 */
12576 		tail = listener->tcp_eager_last_q;
12577 		if (tail != NULL)
12578 			tail->tcp_eager_next_q = tcp;
12579 		else
12580 			listener->tcp_eager_next_q = tcp;
12581 		listener->tcp_eager_last_q = tcp;
12582 		tcp->tcp_eager_next_q = NULL;
12583 		/*
12584 		 * Delay sending up the T_conn_ind until we are
12585 		 * done with the eager. Once we have have sent up
12586 		 * the T_conn_ind, the accept can potentially complete
12587 		 * any time and release the refhold we have on the eager.
12588 		 */
12589 		need_send_conn_ind = B_TRUE;
12590 	} else {
12591 		/*
12592 		 * Defer connection on q0 and set deferred
12593 		 * connection bit true
12594 		 */
12595 		tcp->tcp_conn_def_q0 = B_TRUE;
12596 
12597 		/* take tcp out of q0 ... */
12598 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12599 		    tcp->tcp_eager_next_q0;
12600 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12601 		    tcp->tcp_eager_prev_q0;
12602 
12603 		/* ... and place it at the end of q0 */
12604 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12605 		tcp->tcp_eager_next_q0 = listener;
12606 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12607 		listener->tcp_eager_prev_q0 = tcp;
12608 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12609 	}
12610 
12611 	/* we have timed out before */
12612 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12613 		tcp->tcp_syn_rcvd_timeout = 0;
12614 		listener->tcp_syn_rcvd_timeout--;
12615 		if (listener->tcp_syn_defense &&
12616 		    listener->tcp_syn_rcvd_timeout <=
12617 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12618 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12619 			listener->tcp_last_rcv_lbolt)) {
12620 			/*
12621 			 * Turn off the defense mode if we
12622 			 * believe the SYN attack is over.
12623 			 */
12624 			listener->tcp_syn_defense = B_FALSE;
12625 			if (listener->tcp_ip_addr_cache) {
12626 				kmem_free((void *)listener->tcp_ip_addr_cache,
12627 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12628 				listener->tcp_ip_addr_cache = NULL;
12629 			}
12630 		}
12631 	}
12632 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12633 	if (addr_cache != NULL) {
12634 		/*
12635 		 * We have finished a 3-way handshake with this
12636 		 * remote host. This proves the IP addr is good.
12637 		 * Cache it!
12638 		 */
12639 		addr_cache[IP_ADDR_CACHE_HASH(
12640 			tcp->tcp_remote)] = tcp->tcp_remote;
12641 	}
12642 	mutex_exit(&listener->tcp_eager_lock);
12643 	if (need_send_conn_ind)
12644 		putnext(listener->tcp_rq, mp);
12645 }
12646 
12647 mblk_t *
12648 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12649     uint_t *ifindexp, ip6_pkt_t *ippp)
12650 {
12651 	ip_pktinfo_t	*pinfo;
12652 	ip6_t		*ip6h;
12653 	uchar_t		*rptr;
12654 	mblk_t		*first_mp = mp;
12655 	boolean_t	mctl_present = B_FALSE;
12656 	uint_t 		ifindex = 0;
12657 	ip6_pkt_t	ipp;
12658 	uint_t		ipvers;
12659 	uint_t		ip_hdr_len;
12660 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12661 
12662 	rptr = mp->b_rptr;
12663 	ASSERT(OK_32PTR(rptr));
12664 	ASSERT(tcp != NULL);
12665 	ipp.ipp_fields = 0;
12666 
12667 	switch DB_TYPE(mp) {
12668 	case M_CTL:
12669 		mp = mp->b_cont;
12670 		if (mp == NULL) {
12671 			freemsg(first_mp);
12672 			return (NULL);
12673 		}
12674 		if (DB_TYPE(mp) != M_DATA) {
12675 			freemsg(first_mp);
12676 			return (NULL);
12677 		}
12678 		mctl_present = B_TRUE;
12679 		break;
12680 	case M_DATA:
12681 		break;
12682 	default:
12683 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12684 		freemsg(mp);
12685 		return (NULL);
12686 	}
12687 	ipvers = IPH_HDR_VERSION(rptr);
12688 	if (ipvers == IPV4_VERSION) {
12689 		if (tcp == NULL) {
12690 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12691 			goto done;
12692 		}
12693 
12694 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12695 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12696 
12697 		/*
12698 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12699 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12700 		 */
12701 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12702 		    mctl_present) {
12703 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12704 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12705 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12706 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12707 				ipp.ipp_fields |= IPPF_IFINDEX;
12708 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12709 				ifindex = pinfo->ip_pkt_ifindex;
12710 			}
12711 			freeb(first_mp);
12712 			mctl_present = B_FALSE;
12713 		}
12714 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12715 	} else {
12716 		ip6h = (ip6_t *)rptr;
12717 
12718 		ASSERT(ipvers == IPV6_VERSION);
12719 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12720 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12721 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12722 
12723 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12724 			uint8_t	nexthdrp;
12725 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12726 
12727 			/* Look for ifindex information */
12728 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12729 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12730 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12731 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12732 					freemsg(first_mp);
12733 					return (NULL);
12734 				}
12735 
12736 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12737 					ASSERT(ip6i->ip6i_ifindex != 0);
12738 					ipp.ipp_fields |= IPPF_IFINDEX;
12739 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12740 					ifindex = ip6i->ip6i_ifindex;
12741 				}
12742 				rptr = (uchar_t *)&ip6i[1];
12743 				mp->b_rptr = rptr;
12744 				if (rptr == mp->b_wptr) {
12745 					mblk_t *mp1;
12746 					mp1 = mp->b_cont;
12747 					freeb(mp);
12748 					mp = mp1;
12749 					rptr = mp->b_rptr;
12750 				}
12751 				if (MBLKL(mp) < IPV6_HDR_LEN +
12752 				    sizeof (tcph_t)) {
12753 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12754 					freemsg(first_mp);
12755 					return (NULL);
12756 				}
12757 				ip6h = (ip6_t *)rptr;
12758 			}
12759 
12760 			/*
12761 			 * Find any potentially interesting extension headers
12762 			 * as well as the length of the IPv6 + extension
12763 			 * headers.
12764 			 */
12765 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12766 			/* Verify if this is a TCP packet */
12767 			if (nexthdrp != IPPROTO_TCP) {
12768 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12769 				freemsg(first_mp);
12770 				return (NULL);
12771 			}
12772 		} else {
12773 			ip_hdr_len = IPV6_HDR_LEN;
12774 		}
12775 	}
12776 
12777 done:
12778 	if (ipversp != NULL)
12779 		*ipversp = ipvers;
12780 	if (ip_hdr_lenp != NULL)
12781 		*ip_hdr_lenp = ip_hdr_len;
12782 	if (ippp != NULL)
12783 		*ippp = ipp;
12784 	if (ifindexp != NULL)
12785 		*ifindexp = ifindex;
12786 	if (mctl_present) {
12787 		freeb(first_mp);
12788 	}
12789 	return (mp);
12790 }
12791 
12792 /*
12793  * Handle M_DATA messages from IP. Its called directly from IP via
12794  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12795  * in this path.
12796  *
12797  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12798  * v4 and v6), we are called through tcp_input() and a M_CTL can
12799  * be present for options but tcp_find_pktinfo() deals with it. We
12800  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12801  *
12802  * The first argument is always the connp/tcp to which the mp belongs.
12803  * There are no exceptions to this rule. The caller has already put
12804  * a reference on this connp/tcp and once tcp_rput_data() returns,
12805  * the squeue will do the refrele.
12806  *
12807  * The TH_SYN for the listener directly go to tcp_conn_request via
12808  * squeue.
12809  *
12810  * sqp: NULL = recursive, sqp != NULL means called from squeue
12811  */
12812 void
12813 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12814 {
12815 	int32_t		bytes_acked;
12816 	int32_t		gap;
12817 	mblk_t		*mp1;
12818 	uint_t		flags;
12819 	uint32_t	new_swnd = 0;
12820 	uchar_t		*iphdr;
12821 	uchar_t		*rptr;
12822 	int32_t		rgap;
12823 	uint32_t	seg_ack;
12824 	int		seg_len;
12825 	uint_t		ip_hdr_len;
12826 	uint32_t	seg_seq;
12827 	tcph_t		*tcph;
12828 	int		urp;
12829 	tcp_opt_t	tcpopt;
12830 	uint_t		ipvers;
12831 	ip6_pkt_t	ipp;
12832 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12833 	uint32_t	cwnd;
12834 	uint32_t	add;
12835 	int		npkt;
12836 	int		mss;
12837 	conn_t		*connp = (conn_t *)arg;
12838 	squeue_t	*sqp = (squeue_t *)arg2;
12839 	tcp_t		*tcp = connp->conn_tcp;
12840 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12841 
12842 	/*
12843 	 * RST from fused tcp loopback peer should trigger an unfuse.
12844 	 */
12845 	if (tcp->tcp_fused) {
12846 		TCP_STAT(tcps, tcp_fusion_aborted);
12847 		tcp_unfuse(tcp);
12848 	}
12849 
12850 	iphdr = mp->b_rptr;
12851 	rptr = mp->b_rptr;
12852 	ASSERT(OK_32PTR(rptr));
12853 
12854 	/*
12855 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12856 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12857 	 * necessary information.
12858 	 */
12859 	if (IPCL_IS_TCP4(connp)) {
12860 		ipvers = IPV4_VERSION;
12861 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12862 	} else {
12863 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12864 		    NULL, &ipp);
12865 		if (mp == NULL) {
12866 			TCP_STAT(tcps, tcp_rput_v6_error);
12867 			return;
12868 		}
12869 		iphdr = mp->b_rptr;
12870 		rptr = mp->b_rptr;
12871 	}
12872 	ASSERT(DB_TYPE(mp) == M_DATA);
12873 
12874 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12875 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12876 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12877 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12878 	seg_len = (int)(mp->b_wptr - rptr) -
12879 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12880 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12881 		do {
12882 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12883 			    (uintptr_t)INT_MAX);
12884 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12885 		} while ((mp1 = mp1->b_cont) != NULL &&
12886 		    mp1->b_datap->db_type == M_DATA);
12887 	}
12888 
12889 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12890 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12891 		    seg_len, tcph);
12892 		return;
12893 	}
12894 
12895 	if (sqp != NULL) {
12896 		/*
12897 		 * This is the correct place to update tcp_last_recv_time. Note
12898 		 * that it is also updated for tcp structure that belongs to
12899 		 * global and listener queues which do not really need updating.
12900 		 * But that should not cause any harm.  And it is updated for
12901 		 * all kinds of incoming segments, not only for data segments.
12902 		 */
12903 		tcp->tcp_last_recv_time = lbolt;
12904 	}
12905 
12906 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12907 
12908 	BUMP_LOCAL(tcp->tcp_ibsegs);
12909 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12910 
12911 	if ((flags & TH_URG) && sqp != NULL) {
12912 		/*
12913 		 * TCP can't handle urgent pointers that arrive before
12914 		 * the connection has been accept()ed since it can't
12915 		 * buffer OOB data.  Discard segment if this happens.
12916 		 *
12917 		 * Nor can it reassemble urgent pointers, so discard
12918 		 * if it's not the next segment expected.
12919 		 *
12920 		 * Otherwise, collapse chain into one mblk (discard if
12921 		 * that fails).  This makes sure the headers, retransmitted
12922 		 * data, and new data all are in the same mblk.
12923 		 */
12924 		ASSERT(mp != NULL);
12925 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12926 			freemsg(mp);
12927 			return;
12928 		}
12929 		/* Update pointers into message */
12930 		iphdr = rptr = mp->b_rptr;
12931 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12932 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12933 			/*
12934 			 * Since we can't handle any data with this urgent
12935 			 * pointer that is out of sequence, we expunge
12936 			 * the data.  This allows us to still register
12937 			 * the urgent mark and generate the M_PCSIG,
12938 			 * which we can do.
12939 			 */
12940 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12941 			seg_len = 0;
12942 		}
12943 	}
12944 
12945 	switch (tcp->tcp_state) {
12946 	case TCPS_SYN_SENT:
12947 		if (flags & TH_ACK) {
12948 			/*
12949 			 * Note that our stack cannot send data before a
12950 			 * connection is established, therefore the
12951 			 * following check is valid.  Otherwise, it has
12952 			 * to be changed.
12953 			 */
12954 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12955 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12956 				freemsg(mp);
12957 				if (flags & TH_RST)
12958 					return;
12959 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12960 				    tcp, seg_ack, 0, TH_RST);
12961 				return;
12962 			}
12963 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12964 		}
12965 		if (flags & TH_RST) {
12966 			freemsg(mp);
12967 			if (flags & TH_ACK)
12968 				(void) tcp_clean_death(tcp,
12969 				    ECONNREFUSED, 13);
12970 			return;
12971 		}
12972 		if (!(flags & TH_SYN)) {
12973 			freemsg(mp);
12974 			return;
12975 		}
12976 
12977 		/* Process all TCP options. */
12978 		tcp_process_options(tcp, tcph);
12979 		/*
12980 		 * The following changes our rwnd to be a multiple of the
12981 		 * MIN(peer MSS, our MSS) for performance reason.
12982 		 */
12983 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12984 		    tcp->tcp_mss));
12985 
12986 		/* Is the other end ECN capable? */
12987 		if (tcp->tcp_ecn_ok) {
12988 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12989 				tcp->tcp_ecn_ok = B_FALSE;
12990 			}
12991 		}
12992 		/*
12993 		 * Clear ECN flags because it may interfere with later
12994 		 * processing.
12995 		 */
12996 		flags &= ~(TH_ECE|TH_CWR);
12997 
12998 		tcp->tcp_irs = seg_seq;
12999 		tcp->tcp_rack = seg_seq;
13000 		tcp->tcp_rnxt = seg_seq + 1;
13001 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13002 		if (!TCP_IS_DETACHED(tcp)) {
13003 			/* Allocate room for SACK options if needed. */
13004 			if (tcp->tcp_snd_sack_ok) {
13005 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13006 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13007 				    (tcp->tcp_loopback ? 0 :
13008 				    tcps->tcps_wroff_xtra));
13009 			} else {
13010 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13011 				    tcp->tcp_hdr_len +
13012 				    (tcp->tcp_loopback ? 0 :
13013 				    tcps->tcps_wroff_xtra));
13014 			}
13015 		}
13016 		if (flags & TH_ACK) {
13017 			/*
13018 			 * If we can't get the confirmation upstream, pretend
13019 			 * we didn't even see this one.
13020 			 *
13021 			 * XXX: how can we pretend we didn't see it if we
13022 			 * have updated rnxt et. al.
13023 			 *
13024 			 * For loopback we defer sending up the T_CONN_CON
13025 			 * until after some checks below.
13026 			 */
13027 			mp1 = NULL;
13028 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13029 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13030 				freemsg(mp);
13031 				return;
13032 			}
13033 			/* SYN was acked - making progress */
13034 			if (tcp->tcp_ipversion == IPV6_VERSION)
13035 				tcp->tcp_ip_forward_progress = B_TRUE;
13036 
13037 			/* One for the SYN */
13038 			tcp->tcp_suna = tcp->tcp_iss + 1;
13039 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13040 			tcp->tcp_state = TCPS_ESTABLISHED;
13041 
13042 			/*
13043 			 * If SYN was retransmitted, need to reset all
13044 			 * retransmission info.  This is because this
13045 			 * segment will be treated as a dup ACK.
13046 			 */
13047 			if (tcp->tcp_rexmit) {
13048 				tcp->tcp_rexmit = B_FALSE;
13049 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13050 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13051 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13052 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13053 				tcp->tcp_ms_we_have_waited = 0;
13054 
13055 				/*
13056 				 * Set tcp_cwnd back to 1 MSS, per
13057 				 * recommendation from
13058 				 * draft-floyd-incr-init-win-01.txt,
13059 				 * Increasing TCP's Initial Window.
13060 				 */
13061 				tcp->tcp_cwnd = tcp->tcp_mss;
13062 			}
13063 
13064 			tcp->tcp_swl1 = seg_seq;
13065 			tcp->tcp_swl2 = seg_ack;
13066 
13067 			new_swnd = BE16_TO_U16(tcph->th_win);
13068 			tcp->tcp_swnd = new_swnd;
13069 			if (new_swnd > tcp->tcp_max_swnd)
13070 				tcp->tcp_max_swnd = new_swnd;
13071 
13072 			/*
13073 			 * Always send the three-way handshake ack immediately
13074 			 * in order to make the connection complete as soon as
13075 			 * possible on the accepting host.
13076 			 */
13077 			flags |= TH_ACK_NEEDED;
13078 
13079 			/*
13080 			 * Special case for loopback.  At this point we have
13081 			 * received SYN-ACK from the remote endpoint.  In
13082 			 * order to ensure that both endpoints reach the
13083 			 * fused state prior to any data exchange, the final
13084 			 * ACK needs to be sent before we indicate T_CONN_CON
13085 			 * to the module upstream.
13086 			 */
13087 			if (tcp->tcp_loopback) {
13088 				mblk_t *ack_mp;
13089 
13090 				ASSERT(!tcp->tcp_unfusable);
13091 				ASSERT(mp1 != NULL);
13092 				/*
13093 				 * For loopback, we always get a pure SYN-ACK
13094 				 * and only need to send back the final ACK
13095 				 * with no data (this is because the other
13096 				 * tcp is ours and we don't do T/TCP).  This
13097 				 * final ACK triggers the passive side to
13098 				 * perform fusion in ESTABLISHED state.
13099 				 */
13100 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13101 					if (tcp->tcp_ack_tid != 0) {
13102 						(void) TCP_TIMER_CANCEL(tcp,
13103 						    tcp->tcp_ack_tid);
13104 						tcp->tcp_ack_tid = 0;
13105 					}
13106 					TCP_RECORD_TRACE(tcp, ack_mp,
13107 					    TCP_TRACE_SEND_PKT);
13108 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13109 					BUMP_LOCAL(tcp->tcp_obsegs);
13110 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13111 
13112 					/* Send up T_CONN_CON */
13113 					putnext(tcp->tcp_rq, mp1);
13114 
13115 					freemsg(mp);
13116 					return;
13117 				}
13118 				/*
13119 				 * Forget fusion; we need to handle more
13120 				 * complex cases below.  Send the deferred
13121 				 * T_CONN_CON message upstream and proceed
13122 				 * as usual.  Mark this tcp as not capable
13123 				 * of fusion.
13124 				 */
13125 				TCP_STAT(tcps, tcp_fusion_unfusable);
13126 				tcp->tcp_unfusable = B_TRUE;
13127 				putnext(tcp->tcp_rq, mp1);
13128 			}
13129 
13130 			/*
13131 			 * Check to see if there is data to be sent.  If
13132 			 * yes, set the transmit flag.  Then check to see
13133 			 * if received data processing needs to be done.
13134 			 * If not, go straight to xmit_check.  This short
13135 			 * cut is OK as we don't support T/TCP.
13136 			 */
13137 			if (tcp->tcp_unsent)
13138 				flags |= TH_XMIT_NEEDED;
13139 
13140 			if (seg_len == 0 && !(flags & TH_URG)) {
13141 				freemsg(mp);
13142 				goto xmit_check;
13143 			}
13144 
13145 			flags &= ~TH_SYN;
13146 			seg_seq++;
13147 			break;
13148 		}
13149 		tcp->tcp_state = TCPS_SYN_RCVD;
13150 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13151 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13152 		if (mp1) {
13153 			DB_CPID(mp1) = tcp->tcp_cpid;
13154 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13155 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13156 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13157 		}
13158 		freemsg(mp);
13159 		return;
13160 	case TCPS_SYN_RCVD:
13161 		if (flags & TH_ACK) {
13162 			/*
13163 			 * In this state, a SYN|ACK packet is either bogus
13164 			 * because the other side must be ACKing our SYN which
13165 			 * indicates it has seen the ACK for their SYN and
13166 			 * shouldn't retransmit it or we're crossing SYNs
13167 			 * on active open.
13168 			 */
13169 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13170 				freemsg(mp);
13171 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13172 				    tcp, seg_ack, 0, TH_RST);
13173 				return;
13174 			}
13175 			/*
13176 			 * NOTE: RFC 793 pg. 72 says this should be
13177 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13178 			 * but that would mean we have an ack that ignored
13179 			 * our SYN.
13180 			 */
13181 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13182 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13183 				freemsg(mp);
13184 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13185 				    tcp, seg_ack, 0, TH_RST);
13186 				return;
13187 			}
13188 		}
13189 		break;
13190 	case TCPS_LISTEN:
13191 		/*
13192 		 * Only a TLI listener can come through this path when a
13193 		 * acceptor is going back to be a listener and a packet
13194 		 * for the acceptor hits the classifier. For a socket
13195 		 * listener, this can never happen because a listener
13196 		 * can never accept connection on itself and hence a
13197 		 * socket acceptor can not go back to being a listener.
13198 		 */
13199 		ASSERT(!TCP_IS_SOCKET(tcp));
13200 		/*FALLTHRU*/
13201 	case TCPS_CLOSED:
13202 	case TCPS_BOUND: {
13203 		conn_t	*new_connp;
13204 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13205 
13206 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13207 		if (new_connp != NULL) {
13208 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13209 			return;
13210 		}
13211 		/* We failed to classify. For now just drop the packet */
13212 		freemsg(mp);
13213 		return;
13214 	}
13215 	case TCPS_IDLE:
13216 		/*
13217 		 * Handle the case where the tcp_clean_death() has happened
13218 		 * on a connection (application hasn't closed yet) but a packet
13219 		 * was already queued on squeue before tcp_clean_death()
13220 		 * was processed. Calling tcp_clean_death() twice on same
13221 		 * connection can result in weird behaviour.
13222 		 */
13223 		freemsg(mp);
13224 		return;
13225 	default:
13226 		break;
13227 	}
13228 
13229 	/*
13230 	 * Already on the correct queue/perimeter.
13231 	 * If this is a detached connection and not an eager
13232 	 * connection hanging off a listener then new data
13233 	 * (past the FIN) will cause a reset.
13234 	 * We do a special check here where it
13235 	 * is out of the main line, rather than check
13236 	 * if we are detached every time we see new
13237 	 * data down below.
13238 	 */
13239 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13240 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13241 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13242 		TCP_RECORD_TRACE(tcp,
13243 		    mp, TCP_TRACE_RECV_PKT);
13244 
13245 		freemsg(mp);
13246 		/*
13247 		 * This could be an SSL closure alert. We're detached so just
13248 		 * acknowledge it this last time.
13249 		 */
13250 		if (tcp->tcp_kssl_ctx != NULL) {
13251 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13252 			tcp->tcp_kssl_ctx = NULL;
13253 
13254 			tcp->tcp_rnxt += seg_len;
13255 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13256 			flags |= TH_ACK_NEEDED;
13257 			goto ack_check;
13258 		}
13259 
13260 		tcp_xmit_ctl("new data when detached", tcp,
13261 		    tcp->tcp_snxt, 0, TH_RST);
13262 		(void) tcp_clean_death(tcp, EPROTO, 12);
13263 		return;
13264 	}
13265 
13266 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13267 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13268 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13269 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13270 
13271 	if (tcp->tcp_snd_ts_ok) {
13272 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13273 			/*
13274 			 * This segment is not acceptable.
13275 			 * Drop it and send back an ACK.
13276 			 */
13277 			freemsg(mp);
13278 			flags |= TH_ACK_NEEDED;
13279 			goto ack_check;
13280 		}
13281 	} else if (tcp->tcp_snd_sack_ok) {
13282 		ASSERT(tcp->tcp_sack_info != NULL);
13283 		tcpopt.tcp = tcp;
13284 		/*
13285 		 * SACK info in already updated in tcp_parse_options.  Ignore
13286 		 * all other TCP options...
13287 		 */
13288 		(void) tcp_parse_options(tcph, &tcpopt);
13289 	}
13290 try_again:;
13291 	mss = tcp->tcp_mss;
13292 	gap = seg_seq - tcp->tcp_rnxt;
13293 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13294 	/*
13295 	 * gap is the amount of sequence space between what we expect to see
13296 	 * and what we got for seg_seq.  A positive value for gap means
13297 	 * something got lost.  A negative value means we got some old stuff.
13298 	 */
13299 	if (gap < 0) {
13300 		/* Old stuff present.  Is the SYN in there? */
13301 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13302 		    (seg_len != 0)) {
13303 			flags &= ~TH_SYN;
13304 			seg_seq++;
13305 			urp--;
13306 			/* Recompute the gaps after noting the SYN. */
13307 			goto try_again;
13308 		}
13309 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13310 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13311 		    (seg_len > -gap ? -gap : seg_len));
13312 		/* Remove the old stuff from seg_len. */
13313 		seg_len += gap;
13314 		/*
13315 		 * Anything left?
13316 		 * Make sure to check for unack'd FIN when rest of data
13317 		 * has been previously ack'd.
13318 		 */
13319 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13320 			/*
13321 			 * Resets are only valid if they lie within our offered
13322 			 * window.  If the RST bit is set, we just ignore this
13323 			 * segment.
13324 			 */
13325 			if (flags & TH_RST) {
13326 				freemsg(mp);
13327 				return;
13328 			}
13329 
13330 			/*
13331 			 * The arriving of dup data packets indicate that we
13332 			 * may have postponed an ack for too long, or the other
13333 			 * side's RTT estimate is out of shape. Start acking
13334 			 * more often.
13335 			 */
13336 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13337 			    tcp->tcp_rack_cnt >= 1 &&
13338 			    tcp->tcp_rack_abs_max > 2) {
13339 				tcp->tcp_rack_abs_max--;
13340 			}
13341 			tcp->tcp_rack_cur_max = 1;
13342 
13343 			/*
13344 			 * This segment is "unacceptable".  None of its
13345 			 * sequence space lies within our advertized window.
13346 			 *
13347 			 * Adjust seg_len to the original value for tracing.
13348 			 */
13349 			seg_len -= gap;
13350 			if (tcp->tcp_debug) {
13351 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13352 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13353 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13354 				    "seg_len %d, rnxt %u, snxt %u, %s",
13355 				    gap, rgap, flags, seg_seq, seg_ack,
13356 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13357 				    tcp_display(tcp, NULL,
13358 				    DISP_ADDR_AND_PORT));
13359 			}
13360 
13361 			/*
13362 			 * Arrange to send an ACK in response to the
13363 			 * unacceptable segment per RFC 793 page 69. There
13364 			 * is only one small difference between ours and the
13365 			 * acceptability test in the RFC - we accept ACK-only
13366 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13367 			 * will be generated.
13368 			 *
13369 			 * Note that we have to ACK an ACK-only packet at least
13370 			 * for stacks that send 0-length keep-alives with
13371 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13372 			 * section 4.2.3.6. As long as we don't ever generate
13373 			 * an unacceptable packet in response to an incoming
13374 			 * packet that is unacceptable, it should not cause
13375 			 * "ACK wars".
13376 			 */
13377 			flags |=  TH_ACK_NEEDED;
13378 
13379 			/*
13380 			 * Continue processing this segment in order to use the
13381 			 * ACK information it contains, but skip all other
13382 			 * sequence-number processing.	Processing the ACK
13383 			 * information is necessary in order to
13384 			 * re-synchronize connections that may have lost
13385 			 * synchronization.
13386 			 *
13387 			 * We clear seg_len and flag fields related to
13388 			 * sequence number processing as they are not
13389 			 * to be trusted for an unacceptable segment.
13390 			 */
13391 			seg_len = 0;
13392 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13393 			goto process_ack;
13394 		}
13395 
13396 		/* Fix seg_seq, and chew the gap off the front. */
13397 		seg_seq = tcp->tcp_rnxt;
13398 		urp += gap;
13399 		do {
13400 			mblk_t	*mp2;
13401 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13402 			    (uintptr_t)UINT_MAX);
13403 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13404 			if (gap > 0) {
13405 				mp->b_rptr = mp->b_wptr - gap;
13406 				break;
13407 			}
13408 			mp2 = mp;
13409 			mp = mp->b_cont;
13410 			freeb(mp2);
13411 		} while (gap < 0);
13412 		/*
13413 		 * If the urgent data has already been acknowledged, we
13414 		 * should ignore TH_URG below
13415 		 */
13416 		if (urp < 0)
13417 			flags &= ~TH_URG;
13418 	}
13419 	/*
13420 	 * rgap is the amount of stuff received out of window.  A negative
13421 	 * value is the amount out of window.
13422 	 */
13423 	if (rgap < 0) {
13424 		mblk_t	*mp2;
13425 
13426 		if (tcp->tcp_rwnd == 0) {
13427 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13428 		} else {
13429 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13430 			UPDATE_MIB(&tcps->tcps_mib,
13431 			    tcpInDataPastWinBytes, -rgap);
13432 		}
13433 
13434 		/*
13435 		 * seg_len does not include the FIN, so if more than
13436 		 * just the FIN is out of window, we act like we don't
13437 		 * see it.  (If just the FIN is out of window, rgap
13438 		 * will be zero and we will go ahead and acknowledge
13439 		 * the FIN.)
13440 		 */
13441 		flags &= ~TH_FIN;
13442 
13443 		/* Fix seg_len and make sure there is something left. */
13444 		seg_len += rgap;
13445 		if (seg_len <= 0) {
13446 			/*
13447 			 * Resets are only valid if they lie within our offered
13448 			 * window.  If the RST bit is set, we just ignore this
13449 			 * segment.
13450 			 */
13451 			if (flags & TH_RST) {
13452 				freemsg(mp);
13453 				return;
13454 			}
13455 
13456 			/* Per RFC 793, we need to send back an ACK. */
13457 			flags |= TH_ACK_NEEDED;
13458 
13459 			/*
13460 			 * Send SIGURG as soon as possible i.e. even
13461 			 * if the TH_URG was delivered in a window probe
13462 			 * packet (which will be unacceptable).
13463 			 *
13464 			 * We generate a signal if none has been generated
13465 			 * for this connection or if this is a new urgent
13466 			 * byte. Also send a zero-length "unmarked" message
13467 			 * to inform SIOCATMARK that this is not the mark.
13468 			 *
13469 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13470 			 * is sent up. This plus the check for old data
13471 			 * (gap >= 0) handles the wraparound of the sequence
13472 			 * number space without having to always track the
13473 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13474 			 * this max in its rcv_up variable).
13475 			 *
13476 			 * This prevents duplicate SIGURGS due to a "late"
13477 			 * zero-window probe when the T_EXDATA_IND has already
13478 			 * been sent up.
13479 			 */
13480 			if ((flags & TH_URG) &&
13481 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13482 			    tcp->tcp_urp_last))) {
13483 				mp1 = allocb(0, BPRI_MED);
13484 				if (mp1 == NULL) {
13485 					freemsg(mp);
13486 					return;
13487 				}
13488 				if (!TCP_IS_DETACHED(tcp) &&
13489 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13490 				    SIGURG)) {
13491 					/* Try again on the rexmit. */
13492 					freemsg(mp1);
13493 					freemsg(mp);
13494 					return;
13495 				}
13496 				/*
13497 				 * If the next byte would be the mark
13498 				 * then mark with MARKNEXT else mark
13499 				 * with NOTMARKNEXT.
13500 				 */
13501 				if (gap == 0 && urp == 0)
13502 					mp1->b_flag |= MSGMARKNEXT;
13503 				else
13504 					mp1->b_flag |= MSGNOTMARKNEXT;
13505 				freemsg(tcp->tcp_urp_mark_mp);
13506 				tcp->tcp_urp_mark_mp = mp1;
13507 				flags |= TH_SEND_URP_MARK;
13508 				tcp->tcp_urp_last_valid = B_TRUE;
13509 				tcp->tcp_urp_last = urp + seg_seq;
13510 			}
13511 			/*
13512 			 * If this is a zero window probe, continue to
13513 			 * process the ACK part.  But we need to set seg_len
13514 			 * to 0 to avoid data processing.  Otherwise just
13515 			 * drop the segment and send back an ACK.
13516 			 */
13517 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13518 				flags &= ~(TH_SYN | TH_URG);
13519 				seg_len = 0;
13520 				goto process_ack;
13521 			} else {
13522 				freemsg(mp);
13523 				goto ack_check;
13524 			}
13525 		}
13526 		/* Pitch out of window stuff off the end. */
13527 		rgap = seg_len;
13528 		mp2 = mp;
13529 		do {
13530 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13531 			    (uintptr_t)INT_MAX);
13532 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13533 			if (rgap < 0) {
13534 				mp2->b_wptr += rgap;
13535 				if ((mp1 = mp2->b_cont) != NULL) {
13536 					mp2->b_cont = NULL;
13537 					freemsg(mp1);
13538 				}
13539 				break;
13540 			}
13541 		} while ((mp2 = mp2->b_cont) != NULL);
13542 	}
13543 ok:;
13544 	/*
13545 	 * TCP should check ECN info for segments inside the window only.
13546 	 * Therefore the check should be done here.
13547 	 */
13548 	if (tcp->tcp_ecn_ok) {
13549 		if (flags & TH_CWR) {
13550 			tcp->tcp_ecn_echo_on = B_FALSE;
13551 		}
13552 		/*
13553 		 * Note that both ECN_CE and CWR can be set in the
13554 		 * same segment.  In this case, we once again turn
13555 		 * on ECN_ECHO.
13556 		 */
13557 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13558 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13559 
13560 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13561 				tcp->tcp_ecn_echo_on = B_TRUE;
13562 			}
13563 		} else {
13564 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13565 
13566 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13567 			    htonl(IPH_ECN_CE << 20)) {
13568 				tcp->tcp_ecn_echo_on = B_TRUE;
13569 			}
13570 		}
13571 	}
13572 
13573 	/*
13574 	 * Check whether we can update tcp_ts_recent.  This test is
13575 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13576 	 * Extensions for High Performance: An Update", Internet Draft.
13577 	 */
13578 	if (tcp->tcp_snd_ts_ok &&
13579 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13580 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13581 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13582 		tcp->tcp_last_rcv_lbolt = lbolt64;
13583 	}
13584 
13585 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13586 		/*
13587 		 * FIN in an out of order segment.  We record this in
13588 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13589 		 * Clear the FIN so that any check on FIN flag will fail.
13590 		 * Remember that FIN also counts in the sequence number
13591 		 * space.  So we need to ack out of order FIN only segments.
13592 		 */
13593 		if (flags & TH_FIN) {
13594 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13595 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13596 			flags &= ~TH_FIN;
13597 			flags |= TH_ACK_NEEDED;
13598 		}
13599 		if (seg_len > 0) {
13600 			/* Fill in the SACK blk list. */
13601 			if (tcp->tcp_snd_sack_ok) {
13602 				ASSERT(tcp->tcp_sack_info != NULL);
13603 				tcp_sack_insert(tcp->tcp_sack_list,
13604 				    seg_seq, seg_seq + seg_len,
13605 				    &(tcp->tcp_num_sack_blk));
13606 			}
13607 
13608 			/*
13609 			 * Attempt reassembly and see if we have something
13610 			 * ready to go.
13611 			 */
13612 			mp = tcp_reass(tcp, mp, seg_seq);
13613 			/* Always ack out of order packets */
13614 			flags |= TH_ACK_NEEDED | TH_PUSH;
13615 			if (mp) {
13616 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13617 				    (uintptr_t)INT_MAX);
13618 				seg_len = mp->b_cont ? msgdsize(mp) :
13619 					(int)(mp->b_wptr - mp->b_rptr);
13620 				seg_seq = tcp->tcp_rnxt;
13621 				/*
13622 				 * A gap is filled and the seq num and len
13623 				 * of the gap match that of a previously
13624 				 * received FIN, put the FIN flag back in.
13625 				 */
13626 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13627 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13628 					flags |= TH_FIN;
13629 					tcp->tcp_valid_bits &=
13630 					    ~TCP_OFO_FIN_VALID;
13631 				}
13632 			} else {
13633 				/*
13634 				 * Keep going even with NULL mp.
13635 				 * There may be a useful ACK or something else
13636 				 * we don't want to miss.
13637 				 *
13638 				 * But TCP should not perform fast retransmit
13639 				 * because of the ack number.  TCP uses
13640 				 * seg_len == 0 to determine if it is a pure
13641 				 * ACK.  And this is not a pure ACK.
13642 				 */
13643 				seg_len = 0;
13644 				ofo_seg = B_TRUE;
13645 			}
13646 		}
13647 	} else if (seg_len > 0) {
13648 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13649 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13650 		/*
13651 		 * If an out of order FIN was received before, and the seq
13652 		 * num and len of the new segment match that of the FIN,
13653 		 * put the FIN flag back in.
13654 		 */
13655 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13656 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13657 			flags |= TH_FIN;
13658 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13659 		}
13660 	}
13661 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13662 	if (flags & TH_RST) {
13663 		freemsg(mp);
13664 		switch (tcp->tcp_state) {
13665 		case TCPS_SYN_RCVD:
13666 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13667 			break;
13668 		case TCPS_ESTABLISHED:
13669 		case TCPS_FIN_WAIT_1:
13670 		case TCPS_FIN_WAIT_2:
13671 		case TCPS_CLOSE_WAIT:
13672 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13673 			break;
13674 		case TCPS_CLOSING:
13675 		case TCPS_LAST_ACK:
13676 			(void) tcp_clean_death(tcp, 0, 16);
13677 			break;
13678 		default:
13679 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13680 			(void) tcp_clean_death(tcp, ENXIO, 17);
13681 			break;
13682 		}
13683 		return;
13684 	}
13685 	if (flags & TH_SYN) {
13686 		/*
13687 		 * See RFC 793, Page 71
13688 		 *
13689 		 * The seq number must be in the window as it should
13690 		 * be "fixed" above.  If it is outside window, it should
13691 		 * be already rejected.  Note that we allow seg_seq to be
13692 		 * rnxt + rwnd because we want to accept 0 window probe.
13693 		 */
13694 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13695 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13696 		freemsg(mp);
13697 		/*
13698 		 * If the ACK flag is not set, just use our snxt as the
13699 		 * seq number of the RST segment.
13700 		 */
13701 		if (!(flags & TH_ACK)) {
13702 			seg_ack = tcp->tcp_snxt;
13703 		}
13704 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13705 		    TH_RST|TH_ACK);
13706 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13707 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13708 		return;
13709 	}
13710 	/*
13711 	 * urp could be -1 when the urp field in the packet is 0
13712 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13713 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13714 	 */
13715 	if (flags & TH_URG && urp >= 0) {
13716 		if (!tcp->tcp_urp_last_valid ||
13717 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13718 			/*
13719 			 * If we haven't generated the signal yet for this
13720 			 * urgent pointer value, do it now.  Also, send up a
13721 			 * zero-length M_DATA indicating whether or not this is
13722 			 * the mark. The latter is not needed when a
13723 			 * T_EXDATA_IND is sent up. However, if there are
13724 			 * allocation failures this code relies on the sender
13725 			 * retransmitting and the socket code for determining
13726 			 * the mark should not block waiting for the peer to
13727 			 * transmit. Thus, for simplicity we always send up the
13728 			 * mark indication.
13729 			 */
13730 			mp1 = allocb(0, BPRI_MED);
13731 			if (mp1 == NULL) {
13732 				freemsg(mp);
13733 				return;
13734 			}
13735 			if (!TCP_IS_DETACHED(tcp) &&
13736 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13737 				/* Try again on the rexmit. */
13738 				freemsg(mp1);
13739 				freemsg(mp);
13740 				return;
13741 			}
13742 			/*
13743 			 * Mark with NOTMARKNEXT for now.
13744 			 * The code below will change this to MARKNEXT
13745 			 * if we are at the mark.
13746 			 *
13747 			 * If there are allocation failures (e.g. in dupmsg
13748 			 * below) the next time tcp_rput_data sees the urgent
13749 			 * segment it will send up the MSG*MARKNEXT message.
13750 			 */
13751 			mp1->b_flag |= MSGNOTMARKNEXT;
13752 			freemsg(tcp->tcp_urp_mark_mp);
13753 			tcp->tcp_urp_mark_mp = mp1;
13754 			flags |= TH_SEND_URP_MARK;
13755 #ifdef DEBUG
13756 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13757 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13758 			    "last %x, %s",
13759 			    seg_seq, urp, tcp->tcp_urp_last,
13760 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13761 #endif /* DEBUG */
13762 			tcp->tcp_urp_last_valid = B_TRUE;
13763 			tcp->tcp_urp_last = urp + seg_seq;
13764 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13765 			/*
13766 			 * An allocation failure prevented the previous
13767 			 * tcp_rput_data from sending up the allocated
13768 			 * MSG*MARKNEXT message - send it up this time
13769 			 * around.
13770 			 */
13771 			flags |= TH_SEND_URP_MARK;
13772 		}
13773 
13774 		/*
13775 		 * If the urgent byte is in this segment, make sure that it is
13776 		 * all by itself.  This makes it much easier to deal with the
13777 		 * possibility of an allocation failure on the T_exdata_ind.
13778 		 * Note that seg_len is the number of bytes in the segment, and
13779 		 * urp is the offset into the segment of the urgent byte.
13780 		 * urp < seg_len means that the urgent byte is in this segment.
13781 		 */
13782 		if (urp < seg_len) {
13783 			if (seg_len != 1) {
13784 				uint32_t  tmp_rnxt;
13785 				/*
13786 				 * Break it up and feed it back in.
13787 				 * Re-attach the IP header.
13788 				 */
13789 				mp->b_rptr = iphdr;
13790 				if (urp > 0) {
13791 					/*
13792 					 * There is stuff before the urgent
13793 					 * byte.
13794 					 */
13795 					mp1 = dupmsg(mp);
13796 					if (!mp1) {
13797 						/*
13798 						 * Trim from urgent byte on.
13799 						 * The rest will come back.
13800 						 */
13801 						(void) adjmsg(mp,
13802 						    urp - seg_len);
13803 						tcp_rput_data(connp,
13804 						    mp, NULL);
13805 						return;
13806 					}
13807 					(void) adjmsg(mp1, urp - seg_len);
13808 					/* Feed this piece back in. */
13809 					tmp_rnxt = tcp->tcp_rnxt;
13810 					tcp_rput_data(connp, mp1, NULL);
13811 					/*
13812 					 * If the data passed back in was not
13813 					 * processed (ie: bad ACK) sending
13814 					 * the remainder back in will cause a
13815 					 * loop. In this case, drop the
13816 					 * packet and let the sender try
13817 					 * sending a good packet.
13818 					 */
13819 					if (tmp_rnxt == tcp->tcp_rnxt) {
13820 						freemsg(mp);
13821 						return;
13822 					}
13823 				}
13824 				if (urp != seg_len - 1) {
13825 					uint32_t  tmp_rnxt;
13826 					/*
13827 					 * There is stuff after the urgent
13828 					 * byte.
13829 					 */
13830 					mp1 = dupmsg(mp);
13831 					if (!mp1) {
13832 						/*
13833 						 * Trim everything beyond the
13834 						 * urgent byte.  The rest will
13835 						 * come back.
13836 						 */
13837 						(void) adjmsg(mp,
13838 						    urp + 1 - seg_len);
13839 						tcp_rput_data(connp,
13840 						    mp, NULL);
13841 						return;
13842 					}
13843 					(void) adjmsg(mp1, urp + 1 - seg_len);
13844 					tmp_rnxt = tcp->tcp_rnxt;
13845 					tcp_rput_data(connp, mp1, NULL);
13846 					/*
13847 					 * If the data passed back in was not
13848 					 * processed (ie: bad ACK) sending
13849 					 * the remainder back in will cause a
13850 					 * loop. In this case, drop the
13851 					 * packet and let the sender try
13852 					 * sending a good packet.
13853 					 */
13854 					if (tmp_rnxt == tcp->tcp_rnxt) {
13855 						freemsg(mp);
13856 						return;
13857 					}
13858 				}
13859 				tcp_rput_data(connp, mp, NULL);
13860 				return;
13861 			}
13862 			/*
13863 			 * This segment contains only the urgent byte.  We
13864 			 * have to allocate the T_exdata_ind, if we can.
13865 			 */
13866 			if (!tcp->tcp_urp_mp) {
13867 				struct T_exdata_ind *tei;
13868 				mp1 = allocb(sizeof (struct T_exdata_ind),
13869 				    BPRI_MED);
13870 				if (!mp1) {
13871 					/*
13872 					 * Sigh... It'll be back.
13873 					 * Generate any MSG*MARK message now.
13874 					 */
13875 					freemsg(mp);
13876 					seg_len = 0;
13877 					if (flags & TH_SEND_URP_MARK) {
13878 
13879 
13880 						ASSERT(tcp->tcp_urp_mark_mp);
13881 						tcp->tcp_urp_mark_mp->b_flag &=
13882 							~MSGNOTMARKNEXT;
13883 						tcp->tcp_urp_mark_mp->b_flag |=
13884 							MSGMARKNEXT;
13885 					}
13886 					goto ack_check;
13887 				}
13888 				mp1->b_datap->db_type = M_PROTO;
13889 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13890 				tei->PRIM_type = T_EXDATA_IND;
13891 				tei->MORE_flag = 0;
13892 				mp1->b_wptr = (uchar_t *)&tei[1];
13893 				tcp->tcp_urp_mp = mp1;
13894 #ifdef DEBUG
13895 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13896 				    "tcp_rput: allocated exdata_ind %s",
13897 				    tcp_display(tcp, NULL,
13898 				    DISP_PORT_ONLY));
13899 #endif /* DEBUG */
13900 				/*
13901 				 * There is no need to send a separate MSG*MARK
13902 				 * message since the T_EXDATA_IND will be sent
13903 				 * now.
13904 				 */
13905 				flags &= ~TH_SEND_URP_MARK;
13906 				freemsg(tcp->tcp_urp_mark_mp);
13907 				tcp->tcp_urp_mark_mp = NULL;
13908 			}
13909 			/*
13910 			 * Now we are all set.  On the next putnext upstream,
13911 			 * tcp_urp_mp will be non-NULL and will get prepended
13912 			 * to what has to be this piece containing the urgent
13913 			 * byte.  If for any reason we abort this segment below,
13914 			 * if it comes back, we will have this ready, or it
13915 			 * will get blown off in close.
13916 			 */
13917 		} else if (urp == seg_len) {
13918 			/*
13919 			 * The urgent byte is the next byte after this sequence
13920 			 * number. If there is data it is marked with
13921 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13922 			 * since it is not needed. Otherwise, if the code
13923 			 * above just allocated a zero-length tcp_urp_mark_mp
13924 			 * message, that message is tagged with MSGMARKNEXT.
13925 			 * Sending up these MSGMARKNEXT messages makes
13926 			 * SIOCATMARK work correctly even though
13927 			 * the T_EXDATA_IND will not be sent up until the
13928 			 * urgent byte arrives.
13929 			 */
13930 			if (seg_len != 0) {
13931 				flags |= TH_MARKNEXT_NEEDED;
13932 				freemsg(tcp->tcp_urp_mark_mp);
13933 				tcp->tcp_urp_mark_mp = NULL;
13934 				flags &= ~TH_SEND_URP_MARK;
13935 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13936 				flags |= TH_SEND_URP_MARK;
13937 				tcp->tcp_urp_mark_mp->b_flag &=
13938 					~MSGNOTMARKNEXT;
13939 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13940 			}
13941 #ifdef DEBUG
13942 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13943 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13944 			    seg_len, flags,
13945 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13946 #endif /* DEBUG */
13947 		} else {
13948 			/* Data left until we hit mark */
13949 #ifdef DEBUG
13950 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13951 			    "tcp_rput: URP %d bytes left, %s",
13952 			    urp - seg_len, tcp_display(tcp, NULL,
13953 			    DISP_PORT_ONLY));
13954 #endif /* DEBUG */
13955 		}
13956 	}
13957 
13958 process_ack:
13959 	if (!(flags & TH_ACK)) {
13960 		freemsg(mp);
13961 		goto xmit_check;
13962 	}
13963 	}
13964 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13965 
13966 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13967 		tcp->tcp_ip_forward_progress = B_TRUE;
13968 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13969 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13970 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13971 			/* 3-way handshake complete - pass up the T_CONN_IND */
13972 			tcp_t	*listener = tcp->tcp_listener;
13973 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13974 
13975 			tcp->tcp_tconnind_started = B_TRUE;
13976 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13977 			/*
13978 			 * We are here means eager is fine but it can
13979 			 * get a TH_RST at any point between now and till
13980 			 * accept completes and disappear. We need to
13981 			 * ensure that reference to eager is valid after
13982 			 * we get out of eager's perimeter. So we do
13983 			 * an extra refhold.
13984 			 */
13985 			CONN_INC_REF(connp);
13986 
13987 			/*
13988 			 * The listener also exists because of the refhold
13989 			 * done in tcp_conn_request. Its possible that it
13990 			 * might have closed. We will check that once we
13991 			 * get inside listeners context.
13992 			 */
13993 			CONN_INC_REF(listener->tcp_connp);
13994 			if (listener->tcp_connp->conn_sqp ==
13995 			    connp->conn_sqp) {
13996 				tcp_send_conn_ind(listener->tcp_connp, mp,
13997 				    listener->tcp_connp->conn_sqp);
13998 				CONN_DEC_REF(listener->tcp_connp);
13999 			} else if (!tcp->tcp_loopback) {
14000 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14001 				    tcp_send_conn_ind,
14002 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14003 			} else {
14004 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14005 				    tcp_send_conn_ind, listener->tcp_connp,
14006 				    SQTAG_TCP_CONN_IND);
14007 			}
14008 		}
14009 
14010 		if (tcp->tcp_active_open) {
14011 			/*
14012 			 * We are seeing the final ack in the three way
14013 			 * hand shake of a active open'ed connection
14014 			 * so we must send up a T_CONN_CON
14015 			 */
14016 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14017 				freemsg(mp);
14018 				return;
14019 			}
14020 			/*
14021 			 * Don't fuse the loopback endpoints for
14022 			 * simultaneous active opens.
14023 			 */
14024 			if (tcp->tcp_loopback) {
14025 				TCP_STAT(tcps, tcp_fusion_unfusable);
14026 				tcp->tcp_unfusable = B_TRUE;
14027 			}
14028 		}
14029 
14030 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14031 		bytes_acked--;
14032 		/* SYN was acked - making progress */
14033 		if (tcp->tcp_ipversion == IPV6_VERSION)
14034 			tcp->tcp_ip_forward_progress = B_TRUE;
14035 
14036 		/*
14037 		 * If SYN was retransmitted, need to reset all
14038 		 * retransmission info as this segment will be
14039 		 * treated as a dup ACK.
14040 		 */
14041 		if (tcp->tcp_rexmit) {
14042 			tcp->tcp_rexmit = B_FALSE;
14043 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14044 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14045 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14046 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14047 			tcp->tcp_ms_we_have_waited = 0;
14048 			tcp->tcp_cwnd = mss;
14049 		}
14050 
14051 		/*
14052 		 * We set the send window to zero here.
14053 		 * This is needed if there is data to be
14054 		 * processed already on the queue.
14055 		 * Later (at swnd_update label), the
14056 		 * "new_swnd > tcp_swnd" condition is satisfied
14057 		 * the XMIT_NEEDED flag is set in the current
14058 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14059 		 * called if there is already data on queue in
14060 		 * this state.
14061 		 */
14062 		tcp->tcp_swnd = 0;
14063 
14064 		if (new_swnd > tcp->tcp_max_swnd)
14065 			tcp->tcp_max_swnd = new_swnd;
14066 		tcp->tcp_swl1 = seg_seq;
14067 		tcp->tcp_swl2 = seg_ack;
14068 		tcp->tcp_state = TCPS_ESTABLISHED;
14069 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14070 
14071 		/* Fuse when both sides are in ESTABLISHED state */
14072 		if (tcp->tcp_loopback && do_tcp_fusion)
14073 			tcp_fuse(tcp, iphdr, tcph);
14074 
14075 	}
14076 	/* This code follows 4.4BSD-Lite2 mostly. */
14077 	if (bytes_acked < 0)
14078 		goto est;
14079 
14080 	/*
14081 	 * If TCP is ECN capable and the congestion experience bit is
14082 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14083 	 * done once per window (or more loosely, per RTT).
14084 	 */
14085 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14086 		tcp->tcp_cwr = B_FALSE;
14087 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14088 		if (!tcp->tcp_cwr) {
14089 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14090 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14091 			tcp->tcp_cwnd = npkt * mss;
14092 			/*
14093 			 * If the cwnd is 0, use the timer to clock out
14094 			 * new segments.  This is required by the ECN spec.
14095 			 */
14096 			if (npkt == 0) {
14097 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14098 				/*
14099 				 * This makes sure that when the ACK comes
14100 				 * back, we will increase tcp_cwnd by 1 MSS.
14101 				 */
14102 				tcp->tcp_cwnd_cnt = 0;
14103 			}
14104 			tcp->tcp_cwr = B_TRUE;
14105 			/*
14106 			 * This marks the end of the current window of in
14107 			 * flight data.  That is why we don't use
14108 			 * tcp_suna + tcp_swnd.  Only data in flight can
14109 			 * provide ECN info.
14110 			 */
14111 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14112 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14113 		}
14114 	}
14115 
14116 	mp1 = tcp->tcp_xmit_head;
14117 	if (bytes_acked == 0) {
14118 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14119 			int dupack_cnt;
14120 
14121 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14122 			/*
14123 			 * Fast retransmit.  When we have seen exactly three
14124 			 * identical ACKs while we have unacked data
14125 			 * outstanding we take it as a hint that our peer
14126 			 * dropped something.
14127 			 *
14128 			 * If TCP is retransmitting, don't do fast retransmit.
14129 			 */
14130 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14131 			    ! tcp->tcp_rexmit) {
14132 				/* Do Limited Transmit */
14133 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14134 				    tcps->tcps_dupack_fast_retransmit) {
14135 					/*
14136 					 * RFC 3042
14137 					 *
14138 					 * What we need to do is temporarily
14139 					 * increase tcp_cwnd so that new
14140 					 * data can be sent if it is allowed
14141 					 * by the receive window (tcp_rwnd).
14142 					 * tcp_wput_data() will take care of
14143 					 * the rest.
14144 					 *
14145 					 * If the connection is SACK capable,
14146 					 * only do limited xmit when there
14147 					 * is SACK info.
14148 					 *
14149 					 * Note how tcp_cwnd is incremented.
14150 					 * The first dup ACK will increase
14151 					 * it by 1 MSS.  The second dup ACK
14152 					 * will increase it by 2 MSS.  This
14153 					 * means that only 1 new segment will
14154 					 * be sent for each dup ACK.
14155 					 */
14156 					if (tcp->tcp_unsent > 0 &&
14157 					    (!tcp->tcp_snd_sack_ok ||
14158 					    (tcp->tcp_snd_sack_ok &&
14159 					    tcp->tcp_notsack_list != NULL))) {
14160 						tcp->tcp_cwnd += mss <<
14161 						    (tcp->tcp_dupack_cnt - 1);
14162 						flags |= TH_LIMIT_XMIT;
14163 					}
14164 				} else if (dupack_cnt ==
14165 				    tcps->tcps_dupack_fast_retransmit) {
14166 
14167 				/*
14168 				 * If we have reduced tcp_ssthresh
14169 				 * because of ECN, do not reduce it again
14170 				 * unless it is already one window of data
14171 				 * away.  After one window of data, tcp_cwr
14172 				 * should then be cleared.  Note that
14173 				 * for non ECN capable connection, tcp_cwr
14174 				 * should always be false.
14175 				 *
14176 				 * Adjust cwnd since the duplicate
14177 				 * ack indicates that a packet was
14178 				 * dropped (due to congestion.)
14179 				 */
14180 				if (!tcp->tcp_cwr) {
14181 					npkt = ((tcp->tcp_snxt -
14182 					    tcp->tcp_suna) >> 1) / mss;
14183 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14184 					    mss;
14185 					tcp->tcp_cwnd = (npkt +
14186 					    tcp->tcp_dupack_cnt) * mss;
14187 				}
14188 				if (tcp->tcp_ecn_ok) {
14189 					tcp->tcp_cwr = B_TRUE;
14190 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14191 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14192 				}
14193 
14194 				/*
14195 				 * We do Hoe's algorithm.  Refer to her
14196 				 * paper "Improving the Start-up Behavior
14197 				 * of a Congestion Control Scheme for TCP,"
14198 				 * appeared in SIGCOMM'96.
14199 				 *
14200 				 * Save highest seq no we have sent so far.
14201 				 * Be careful about the invisible FIN byte.
14202 				 */
14203 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14204 				    (tcp->tcp_unsent == 0)) {
14205 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14206 				} else {
14207 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14208 				}
14209 
14210 				/*
14211 				 * Do not allow bursty traffic during.
14212 				 * fast recovery.  Refer to Fall and Floyd's
14213 				 * paper "Simulation-based Comparisons of
14214 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14215 				 * This is a best current practise.
14216 				 */
14217 				tcp->tcp_snd_burst = TCP_CWND_SS;
14218 
14219 				/*
14220 				 * For SACK:
14221 				 * Calculate tcp_pipe, which is the
14222 				 * estimated number of bytes in
14223 				 * network.
14224 				 *
14225 				 * tcp_fack is the highest sack'ed seq num
14226 				 * TCP has received.
14227 				 *
14228 				 * tcp_pipe is explained in the above quoted
14229 				 * Fall and Floyd's paper.  tcp_fack is
14230 				 * explained in Mathis and Mahdavi's
14231 				 * "Forward Acknowledgment: Refining TCP
14232 				 * Congestion Control" in SIGCOMM '96.
14233 				 */
14234 				if (tcp->tcp_snd_sack_ok) {
14235 					ASSERT(tcp->tcp_sack_info != NULL);
14236 					if (tcp->tcp_notsack_list != NULL) {
14237 						tcp->tcp_pipe = tcp->tcp_snxt -
14238 						    tcp->tcp_fack;
14239 						tcp->tcp_sack_snxt = seg_ack;
14240 						flags |= TH_NEED_SACK_REXMIT;
14241 					} else {
14242 						/*
14243 						 * Always initialize tcp_pipe
14244 						 * even though we don't have
14245 						 * any SACK info.  If later
14246 						 * we get SACK info and
14247 						 * tcp_pipe is not initialized,
14248 						 * funny things will happen.
14249 						 */
14250 						tcp->tcp_pipe =
14251 						    tcp->tcp_cwnd_ssthresh;
14252 					}
14253 				} else {
14254 					flags |= TH_REXMIT_NEEDED;
14255 				} /* tcp_snd_sack_ok */
14256 
14257 				} else {
14258 					/*
14259 					 * Here we perform congestion
14260 					 * avoidance, but NOT slow start.
14261 					 * This is known as the Fast
14262 					 * Recovery Algorithm.
14263 					 */
14264 					if (tcp->tcp_snd_sack_ok &&
14265 					    tcp->tcp_notsack_list != NULL) {
14266 						flags |= TH_NEED_SACK_REXMIT;
14267 						tcp->tcp_pipe -= mss;
14268 						if (tcp->tcp_pipe < 0)
14269 							tcp->tcp_pipe = 0;
14270 					} else {
14271 					/*
14272 					 * We know that one more packet has
14273 					 * left the pipe thus we can update
14274 					 * cwnd.
14275 					 */
14276 					cwnd = tcp->tcp_cwnd + mss;
14277 					if (cwnd > tcp->tcp_cwnd_max)
14278 						cwnd = tcp->tcp_cwnd_max;
14279 					tcp->tcp_cwnd = cwnd;
14280 					if (tcp->tcp_unsent > 0)
14281 						flags |= TH_XMIT_NEEDED;
14282 					}
14283 				}
14284 			}
14285 		} else if (tcp->tcp_zero_win_probe) {
14286 			/*
14287 			 * If the window has opened, need to arrange
14288 			 * to send additional data.
14289 			 */
14290 			if (new_swnd != 0) {
14291 				/* tcp_suna != tcp_snxt */
14292 				/* Packet contains a window update */
14293 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14294 				tcp->tcp_zero_win_probe = 0;
14295 				tcp->tcp_timer_backoff = 0;
14296 				tcp->tcp_ms_we_have_waited = 0;
14297 
14298 				/*
14299 				 * Transmit starting with tcp_suna since
14300 				 * the one byte probe is not ack'ed.
14301 				 * If TCP has sent more than one identical
14302 				 * probe, tcp_rexmit will be set.  That means
14303 				 * tcp_ss_rexmit() will send out the one
14304 				 * byte along with new data.  Otherwise,
14305 				 * fake the retransmission.
14306 				 */
14307 				flags |= TH_XMIT_NEEDED;
14308 				if (!tcp->tcp_rexmit) {
14309 					tcp->tcp_rexmit = B_TRUE;
14310 					tcp->tcp_dupack_cnt = 0;
14311 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14312 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14313 				}
14314 			}
14315 		}
14316 		goto swnd_update;
14317 	}
14318 
14319 	/*
14320 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14321 	 * If the ACK value acks something that we have not yet sent, it might
14322 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14323 	 * other side.
14324 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14325 	 * state is handled above, so we can always just drop the segment and
14326 	 * send an ACK here.
14327 	 *
14328 	 * Should we send ACKs in response to ACK only segments?
14329 	 */
14330 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14331 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14332 		/* drop the received segment */
14333 		freemsg(mp);
14334 
14335 		/*
14336 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14337 		 * greater than 0, check if the number of such
14338 		 * bogus ACks is greater than that count.  If yes,
14339 		 * don't send back any ACK.  This prevents TCP from
14340 		 * getting into an ACK storm if somehow an attacker
14341 		 * successfully spoofs an acceptable segment to our
14342 		 * peer.
14343 		 */
14344 		if (tcp_drop_ack_unsent_cnt > 0 &&
14345 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14346 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14347 			return;
14348 		}
14349 		mp = tcp_ack_mp(tcp);
14350 		if (mp != NULL) {
14351 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14352 			BUMP_LOCAL(tcp->tcp_obsegs);
14353 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14354 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14355 		}
14356 		return;
14357 	}
14358 
14359 	/*
14360 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14361 	 * blocks that are covered by this ACK.
14362 	 */
14363 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14364 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14365 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14366 	}
14367 
14368 	/*
14369 	 * If we got an ACK after fast retransmit, check to see
14370 	 * if it is a partial ACK.  If it is not and the congestion
14371 	 * window was inflated to account for the other side's
14372 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14373 	 */
14374 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14375 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14376 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14377 			tcp->tcp_dupack_cnt = 0;
14378 			/*
14379 			 * Restore the orig tcp_cwnd_ssthresh after
14380 			 * fast retransmit phase.
14381 			 */
14382 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14383 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14384 			}
14385 			tcp->tcp_rexmit_max = seg_ack;
14386 			tcp->tcp_cwnd_cnt = 0;
14387 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14388 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14389 
14390 			/*
14391 			 * Remove all notsack info to avoid confusion with
14392 			 * the next fast retrasnmit/recovery phase.
14393 			 */
14394 			if (tcp->tcp_snd_sack_ok &&
14395 			    tcp->tcp_notsack_list != NULL) {
14396 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14397 			}
14398 		} else {
14399 			if (tcp->tcp_snd_sack_ok &&
14400 			    tcp->tcp_notsack_list != NULL) {
14401 				flags |= TH_NEED_SACK_REXMIT;
14402 				tcp->tcp_pipe -= mss;
14403 				if (tcp->tcp_pipe < 0)
14404 					tcp->tcp_pipe = 0;
14405 			} else {
14406 				/*
14407 				 * Hoe's algorithm:
14408 				 *
14409 				 * Retransmit the unack'ed segment and
14410 				 * restart fast recovery.  Note that we
14411 				 * need to scale back tcp_cwnd to the
14412 				 * original value when we started fast
14413 				 * recovery.  This is to prevent overly
14414 				 * aggressive behaviour in sending new
14415 				 * segments.
14416 				 */
14417 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14418 				    tcps->tcps_dupack_fast_retransmit * mss;
14419 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14420 				flags |= TH_REXMIT_NEEDED;
14421 			}
14422 		}
14423 	} else {
14424 		tcp->tcp_dupack_cnt = 0;
14425 		if (tcp->tcp_rexmit) {
14426 			/*
14427 			 * TCP is retranmitting.  If the ACK ack's all
14428 			 * outstanding data, update tcp_rexmit_max and
14429 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14430 			 * to the correct value.
14431 			 *
14432 			 * Note that SEQ_LEQ() is used.  This is to avoid
14433 			 * unnecessary fast retransmit caused by dup ACKs
14434 			 * received when TCP does slow start retransmission
14435 			 * after a time out.  During this phase, TCP may
14436 			 * send out segments which are already received.
14437 			 * This causes dup ACKs to be sent back.
14438 			 */
14439 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14440 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14441 					tcp->tcp_rexmit_nxt = seg_ack;
14442 				}
14443 				if (seg_ack != tcp->tcp_rexmit_max) {
14444 					flags |= TH_XMIT_NEEDED;
14445 				}
14446 			} else {
14447 				tcp->tcp_rexmit = B_FALSE;
14448 				tcp->tcp_xmit_zc_clean = B_FALSE;
14449 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14450 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14451 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14452 			}
14453 			tcp->tcp_ms_we_have_waited = 0;
14454 		}
14455 	}
14456 
14457 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14458 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14459 	tcp->tcp_suna = seg_ack;
14460 	if (tcp->tcp_zero_win_probe != 0) {
14461 		tcp->tcp_zero_win_probe = 0;
14462 		tcp->tcp_timer_backoff = 0;
14463 	}
14464 
14465 	/*
14466 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14467 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14468 	 * will not reach here.
14469 	 */
14470 	if (mp1 == NULL) {
14471 		goto fin_acked;
14472 	}
14473 
14474 	/*
14475 	 * Update the congestion window.
14476 	 *
14477 	 * If TCP is not ECN capable or TCP is ECN capable but the
14478 	 * congestion experience bit is not set, increase the tcp_cwnd as
14479 	 * usual.
14480 	 */
14481 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14482 		cwnd = tcp->tcp_cwnd;
14483 		add = mss;
14484 
14485 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14486 			/*
14487 			 * This is to prevent an increase of less than 1 MSS of
14488 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14489 			 * may send out tinygrams in order to preserve mblk
14490 			 * boundaries.
14491 			 *
14492 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14493 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14494 			 * increased by 1 MSS for every RTTs.
14495 			 */
14496 			if (tcp->tcp_cwnd_cnt <= 0) {
14497 				tcp->tcp_cwnd_cnt = cwnd + add;
14498 			} else {
14499 				tcp->tcp_cwnd_cnt -= add;
14500 				add = 0;
14501 			}
14502 		}
14503 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14504 	}
14505 
14506 	/* See if the latest urgent data has been acknowledged */
14507 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14508 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14509 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14510 
14511 	/* Can we update the RTT estimates? */
14512 	if (tcp->tcp_snd_ts_ok) {
14513 		/* Ignore zero timestamp echo-reply. */
14514 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14515 			tcp_set_rto(tcp, (int32_t)lbolt -
14516 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14517 		}
14518 
14519 		/* If needed, restart the timer. */
14520 		if (tcp->tcp_set_timer == 1) {
14521 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14522 			tcp->tcp_set_timer = 0;
14523 		}
14524 		/*
14525 		 * Update tcp_csuna in case the other side stops sending
14526 		 * us timestamps.
14527 		 */
14528 		tcp->tcp_csuna = tcp->tcp_snxt;
14529 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14530 		/*
14531 		 * An ACK sequence we haven't seen before, so get the RTT
14532 		 * and update the RTO. But first check if the timestamp is
14533 		 * valid to use.
14534 		 */
14535 		if ((mp1->b_next != NULL) &&
14536 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14537 			tcp_set_rto(tcp, (int32_t)lbolt -
14538 			    (int32_t)(intptr_t)mp1->b_prev);
14539 		else
14540 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14541 
14542 		/* Remeber the last sequence to be ACKed */
14543 		tcp->tcp_csuna = seg_ack;
14544 		if (tcp->tcp_set_timer == 1) {
14545 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14546 			tcp->tcp_set_timer = 0;
14547 		}
14548 	} else {
14549 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14550 	}
14551 
14552 	/* Eat acknowledged bytes off the xmit queue. */
14553 	for (;;) {
14554 		mblk_t	*mp2;
14555 		uchar_t	*wptr;
14556 
14557 		wptr = mp1->b_wptr;
14558 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14559 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14560 		if (bytes_acked < 0) {
14561 			mp1->b_rptr = wptr + bytes_acked;
14562 			/*
14563 			 * Set a new timestamp if all the bytes timed by the
14564 			 * old timestamp have been ack'ed.
14565 			 */
14566 			if (SEQ_GT(seg_ack,
14567 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14568 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14569 				mp1->b_next = NULL;
14570 			}
14571 			break;
14572 		}
14573 		mp1->b_next = NULL;
14574 		mp1->b_prev = NULL;
14575 		mp2 = mp1;
14576 		mp1 = mp1->b_cont;
14577 
14578 		/*
14579 		 * This notification is required for some zero-copy
14580 		 * clients to maintain a copy semantic. After the data
14581 		 * is ack'ed, client is safe to modify or reuse the buffer.
14582 		 */
14583 		if (tcp->tcp_snd_zcopy_aware &&
14584 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14585 			tcp_zcopy_notify(tcp);
14586 		freeb(mp2);
14587 		if (bytes_acked == 0) {
14588 			if (mp1 == NULL) {
14589 				/* Everything is ack'ed, clear the tail. */
14590 				tcp->tcp_xmit_tail = NULL;
14591 				/*
14592 				 * Cancel the timer unless we are still
14593 				 * waiting for an ACK for the FIN packet.
14594 				 */
14595 				if (tcp->tcp_timer_tid != 0 &&
14596 				    tcp->tcp_snxt == tcp->tcp_suna) {
14597 					(void) TCP_TIMER_CANCEL(tcp,
14598 					    tcp->tcp_timer_tid);
14599 					tcp->tcp_timer_tid = 0;
14600 				}
14601 				goto pre_swnd_update;
14602 			}
14603 			if (mp2 != tcp->tcp_xmit_tail)
14604 				break;
14605 			tcp->tcp_xmit_tail = mp1;
14606 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14607 			    (uintptr_t)INT_MAX);
14608 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14609 			    mp1->b_rptr);
14610 			break;
14611 		}
14612 		if (mp1 == NULL) {
14613 			/*
14614 			 * More was acked but there is nothing more
14615 			 * outstanding.  This means that the FIN was
14616 			 * just acked or that we're talking to a clown.
14617 			 */
14618 fin_acked:
14619 			ASSERT(tcp->tcp_fin_sent);
14620 			tcp->tcp_xmit_tail = NULL;
14621 			if (tcp->tcp_fin_sent) {
14622 				/* FIN was acked - making progress */
14623 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14624 				    !tcp->tcp_fin_acked)
14625 					tcp->tcp_ip_forward_progress = B_TRUE;
14626 				tcp->tcp_fin_acked = B_TRUE;
14627 				if (tcp->tcp_linger_tid != 0 &&
14628 				    TCP_TIMER_CANCEL(tcp,
14629 					tcp->tcp_linger_tid) >= 0) {
14630 					tcp_stop_lingering(tcp);
14631 				}
14632 			} else {
14633 				/*
14634 				 * We should never get here because
14635 				 * we have already checked that the
14636 				 * number of bytes ack'ed should be
14637 				 * smaller than or equal to what we
14638 				 * have sent so far (it is the
14639 				 * acceptability check of the ACK).
14640 				 * We can only get here if the send
14641 				 * queue is corrupted.
14642 				 *
14643 				 * Terminate the connection and
14644 				 * panic the system.  It is better
14645 				 * for us to panic instead of
14646 				 * continuing to avoid other disaster.
14647 				 */
14648 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14649 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14650 				panic("Memory corruption "
14651 				    "detected for connection %s.",
14652 				    tcp_display(tcp, NULL,
14653 					DISP_ADDR_AND_PORT));
14654 				/*NOTREACHED*/
14655 			}
14656 			goto pre_swnd_update;
14657 		}
14658 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14659 	}
14660 	if (tcp->tcp_unsent) {
14661 		flags |= TH_XMIT_NEEDED;
14662 	}
14663 pre_swnd_update:
14664 	tcp->tcp_xmit_head = mp1;
14665 swnd_update:
14666 	/*
14667 	 * The following check is different from most other implementations.
14668 	 * For bi-directional transfer, when segments are dropped, the
14669 	 * "normal" check will not accept a window update in those
14670 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14671 	 * segments which are outside receiver's window.  As TCP accepts
14672 	 * the ack in those retransmitted segments, if the window update in
14673 	 * the same segment is not accepted, TCP will incorrectly calculates
14674 	 * that it can send more segments.  This can create a deadlock
14675 	 * with the receiver if its window becomes zero.
14676 	 */
14677 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14678 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14679 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14680 		/*
14681 		 * The criteria for update is:
14682 		 *
14683 		 * 1. the segment acknowledges some data.  Or
14684 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14685 		 * 3. the segment is not old and the advertised window is
14686 		 * larger than the previous advertised window.
14687 		 */
14688 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14689 			flags |= TH_XMIT_NEEDED;
14690 		tcp->tcp_swnd = new_swnd;
14691 		if (new_swnd > tcp->tcp_max_swnd)
14692 			tcp->tcp_max_swnd = new_swnd;
14693 		tcp->tcp_swl1 = seg_seq;
14694 		tcp->tcp_swl2 = seg_ack;
14695 	}
14696 est:
14697 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14698 
14699 		switch (tcp->tcp_state) {
14700 		case TCPS_FIN_WAIT_1:
14701 			if (tcp->tcp_fin_acked) {
14702 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14703 				/*
14704 				 * We implement the non-standard BSD/SunOS
14705 				 * FIN_WAIT_2 flushing algorithm.
14706 				 * If there is no user attached to this
14707 				 * TCP endpoint, then this TCP struct
14708 				 * could hang around forever in FIN_WAIT_2
14709 				 * state if the peer forgets to send us
14710 				 * a FIN.  To prevent this, we wait only
14711 				 * 2*MSL (a convenient time value) for
14712 				 * the FIN to arrive.  If it doesn't show up,
14713 				 * we flush the TCP endpoint.  This algorithm,
14714 				 * though a violation of RFC-793, has worked
14715 				 * for over 10 years in BSD systems.
14716 				 * Note: SunOS 4.x waits 675 seconds before
14717 				 * flushing the FIN_WAIT_2 connection.
14718 				 */
14719 				TCP_TIMER_RESTART(tcp,
14720 				    tcps->tcps_fin_wait_2_flush_interval);
14721 			}
14722 			break;
14723 		case TCPS_FIN_WAIT_2:
14724 			break;	/* Shutdown hook? */
14725 		case TCPS_LAST_ACK:
14726 			freemsg(mp);
14727 			if (tcp->tcp_fin_acked) {
14728 				(void) tcp_clean_death(tcp, 0, 19);
14729 				return;
14730 			}
14731 			goto xmit_check;
14732 		case TCPS_CLOSING:
14733 			if (tcp->tcp_fin_acked) {
14734 				tcp->tcp_state = TCPS_TIME_WAIT;
14735 				/*
14736 				 * Unconditionally clear the exclusive binding
14737 				 * bit so this TIME-WAIT connection won't
14738 				 * interfere with new ones.
14739 				 */
14740 				tcp->tcp_exclbind = 0;
14741 				if (!TCP_IS_DETACHED(tcp)) {
14742 					TCP_TIMER_RESTART(tcp,
14743 					    tcps->tcps_time_wait_interval);
14744 				} else {
14745 					tcp_time_wait_append(tcp);
14746 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14747 				}
14748 			}
14749 			/*FALLTHRU*/
14750 		case TCPS_CLOSE_WAIT:
14751 			freemsg(mp);
14752 			goto xmit_check;
14753 		default:
14754 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14755 			break;
14756 		}
14757 	}
14758 	if (flags & TH_FIN) {
14759 		/* Make sure we ack the fin */
14760 		flags |= TH_ACK_NEEDED;
14761 		if (!tcp->tcp_fin_rcvd) {
14762 			tcp->tcp_fin_rcvd = B_TRUE;
14763 			tcp->tcp_rnxt++;
14764 			tcph = tcp->tcp_tcph;
14765 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14766 
14767 			/*
14768 			 * Generate the ordrel_ind at the end unless we
14769 			 * are an eager guy.
14770 			 * In the eager case tcp_rsrv will do this when run
14771 			 * after tcp_accept is done.
14772 			 */
14773 			if (tcp->tcp_listener == NULL &&
14774 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14775 				flags |= TH_ORDREL_NEEDED;
14776 			switch (tcp->tcp_state) {
14777 			case TCPS_SYN_RCVD:
14778 			case TCPS_ESTABLISHED:
14779 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14780 				/* Keepalive? */
14781 				break;
14782 			case TCPS_FIN_WAIT_1:
14783 				if (!tcp->tcp_fin_acked) {
14784 					tcp->tcp_state = TCPS_CLOSING;
14785 					break;
14786 				}
14787 				/* FALLTHRU */
14788 			case TCPS_FIN_WAIT_2:
14789 				tcp->tcp_state = TCPS_TIME_WAIT;
14790 				/*
14791 				 * Unconditionally clear the exclusive binding
14792 				 * bit so this TIME-WAIT connection won't
14793 				 * interfere with new ones.
14794 				 */
14795 				tcp->tcp_exclbind = 0;
14796 				if (!TCP_IS_DETACHED(tcp)) {
14797 					TCP_TIMER_RESTART(tcp,
14798 					    tcps->tcps_time_wait_interval);
14799 				} else {
14800 					tcp_time_wait_append(tcp);
14801 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14802 				}
14803 				if (seg_len) {
14804 					/*
14805 					 * implies data piggybacked on FIN.
14806 					 * break to handle data.
14807 					 */
14808 					break;
14809 				}
14810 				freemsg(mp);
14811 				goto ack_check;
14812 			}
14813 		}
14814 	}
14815 	if (mp == NULL)
14816 		goto xmit_check;
14817 	if (seg_len == 0) {
14818 		freemsg(mp);
14819 		goto xmit_check;
14820 	}
14821 	if (mp->b_rptr == mp->b_wptr) {
14822 		/*
14823 		 * The header has been consumed, so we remove the
14824 		 * zero-length mblk here.
14825 		 */
14826 		mp1 = mp;
14827 		mp = mp->b_cont;
14828 		freeb(mp1);
14829 	}
14830 	tcph = tcp->tcp_tcph;
14831 	tcp->tcp_rack_cnt++;
14832 	{
14833 		uint32_t cur_max;
14834 
14835 		cur_max = tcp->tcp_rack_cur_max;
14836 		if (tcp->tcp_rack_cnt >= cur_max) {
14837 			/*
14838 			 * We have more unacked data than we should - send
14839 			 * an ACK now.
14840 			 */
14841 			flags |= TH_ACK_NEEDED;
14842 			cur_max++;
14843 			if (cur_max > tcp->tcp_rack_abs_max)
14844 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14845 			else
14846 				tcp->tcp_rack_cur_max = cur_max;
14847 		} else if (TCP_IS_DETACHED(tcp)) {
14848 			/* We don't have an ACK timer for detached TCP. */
14849 			flags |= TH_ACK_NEEDED;
14850 		} else if (seg_len < mss) {
14851 			/*
14852 			 * If we get a segment that is less than an mss, and we
14853 			 * already have unacknowledged data, and the amount
14854 			 * unacknowledged is not a multiple of mss, then we
14855 			 * better generate an ACK now.  Otherwise, this may be
14856 			 * the tail piece of a transaction, and we would rather
14857 			 * wait for the response.
14858 			 */
14859 			uint32_t udif;
14860 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14861 			    (uintptr_t)INT_MAX);
14862 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14863 			if (udif && (udif % mss))
14864 				flags |= TH_ACK_NEEDED;
14865 			else
14866 				flags |= TH_ACK_TIMER_NEEDED;
14867 		} else {
14868 			/* Start delayed ack timer */
14869 			flags |= TH_ACK_TIMER_NEEDED;
14870 		}
14871 	}
14872 	tcp->tcp_rnxt += seg_len;
14873 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14874 
14875 	/* Update SACK list */
14876 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14877 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14878 		    &(tcp->tcp_num_sack_blk));
14879 	}
14880 
14881 	if (tcp->tcp_urp_mp) {
14882 		tcp->tcp_urp_mp->b_cont = mp;
14883 		mp = tcp->tcp_urp_mp;
14884 		tcp->tcp_urp_mp = NULL;
14885 		/* Ready for a new signal. */
14886 		tcp->tcp_urp_last_valid = B_FALSE;
14887 #ifdef DEBUG
14888 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14889 		    "tcp_rput: sending exdata_ind %s",
14890 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14891 #endif /* DEBUG */
14892 	}
14893 
14894 	/*
14895 	 * Check for ancillary data changes compared to last segment.
14896 	 */
14897 	if (tcp->tcp_ipv6_recvancillary != 0) {
14898 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14899 		if (mp == NULL)
14900 			return;
14901 	}
14902 
14903 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14904 		/*
14905 		 * Side queue inbound data until the accept happens.
14906 		 * tcp_accept/tcp_rput drains this when the accept happens.
14907 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14908 		 * T_EXDATA_IND) it is queued on b_next.
14909 		 * XXX Make urgent data use this. Requires:
14910 		 *	Removing tcp_listener check for TH_URG
14911 		 *	Making M_PCPROTO and MARK messages skip the eager case
14912 		 */
14913 
14914 		if (tcp->tcp_kssl_pending) {
14915 			tcp_kssl_input(tcp, mp);
14916 		} else {
14917 			tcp_rcv_enqueue(tcp, mp, seg_len);
14918 		}
14919 	} else {
14920 		if (mp->b_datap->db_type != M_DATA ||
14921 		    (flags & TH_MARKNEXT_NEEDED)) {
14922 			if (tcp->tcp_rcv_list != NULL) {
14923 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14924 			}
14925 			ASSERT(tcp->tcp_rcv_list == NULL ||
14926 			    tcp->tcp_fused_sigurg);
14927 			if (flags & TH_MARKNEXT_NEEDED) {
14928 #ifdef DEBUG
14929 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14930 				    "tcp_rput: sending MSGMARKNEXT %s",
14931 				    tcp_display(tcp, NULL,
14932 				    DISP_PORT_ONLY));
14933 #endif /* DEBUG */
14934 				mp->b_flag |= MSGMARKNEXT;
14935 				flags &= ~TH_MARKNEXT_NEEDED;
14936 			}
14937 
14938 			/* Does this need SSL processing first? */
14939 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14940 			    (DB_TYPE(mp) == M_DATA)) {
14941 				tcp_kssl_input(tcp, mp);
14942 			} else {
14943 				putnext(tcp->tcp_rq, mp);
14944 				if (!canputnext(tcp->tcp_rq))
14945 					tcp->tcp_rwnd -= seg_len;
14946 			}
14947 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14948 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14949 			if (tcp->tcp_rcv_list != NULL) {
14950 				/*
14951 				 * Enqueue the new segment first and then
14952 				 * call tcp_rcv_drain() to send all data
14953 				 * up.  The other way to do this is to
14954 				 * send all queued data up and then call
14955 				 * putnext() to send the new segment up.
14956 				 * This way can remove the else part later
14957 				 * on.
14958 				 *
14959 				 * We don't this to avoid one more call to
14960 				 * canputnext() as tcp_rcv_drain() needs to
14961 				 * call canputnext().
14962 				 */
14963 				tcp_rcv_enqueue(tcp, mp, seg_len);
14964 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14965 			} else {
14966 				/* Does this need SSL processing first? */
14967 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14968 				    (DB_TYPE(mp) == M_DATA)) {
14969 					tcp_kssl_input(tcp, mp);
14970 				} else {
14971 					putnext(tcp->tcp_rq, mp);
14972 					if (!canputnext(tcp->tcp_rq))
14973 						tcp->tcp_rwnd -= seg_len;
14974 				}
14975 			}
14976 		} else {
14977 			/*
14978 			 * Enqueue all packets when processing an mblk
14979 			 * from the co queue and also enqueue normal packets.
14980 			 */
14981 			tcp_rcv_enqueue(tcp, mp, seg_len);
14982 		}
14983 		/*
14984 		 * Make sure the timer is running if we have data waiting
14985 		 * for a push bit. This provides resiliency against
14986 		 * implementations that do not correctly generate push bits.
14987 		 */
14988 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14989 			/*
14990 			 * The connection may be closed at this point, so don't
14991 			 * do anything for a detached tcp.
14992 			 */
14993 			if (!TCP_IS_DETACHED(tcp))
14994 			    tcp->tcp_push_tid = TCP_TIMER(tcp,
14995 				tcp_push_timer,
14996 				MSEC_TO_TICK(tcps->tcps_push_timer_interval));
14997 		}
14998 	}
14999 xmit_check:
15000 	/* Is there anything left to do? */
15001 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15002 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15003 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15004 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15005 		goto done;
15006 
15007 	/* Any transmit work to do and a non-zero window? */
15008 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15009 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15010 		if (flags & TH_REXMIT_NEEDED) {
15011 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15012 
15013 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15014 			if (snd_size > mss)
15015 				snd_size = mss;
15016 			if (snd_size > tcp->tcp_swnd)
15017 				snd_size = tcp->tcp_swnd;
15018 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15019 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15020 			    B_TRUE);
15021 
15022 			if (mp1 != NULL) {
15023 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15024 				tcp->tcp_csuna = tcp->tcp_snxt;
15025 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15026 				UPDATE_MIB(&tcps->tcps_mib,
15027 				    tcpRetransBytes, snd_size);
15028 				TCP_RECORD_TRACE(tcp, mp1,
15029 				    TCP_TRACE_SEND_PKT);
15030 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15031 			}
15032 		}
15033 		if (flags & TH_NEED_SACK_REXMIT) {
15034 			tcp_sack_rxmit(tcp, &flags);
15035 		}
15036 		/*
15037 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15038 		 * out new segment.  Note that tcp_rexmit should not be
15039 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15040 		 */
15041 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15042 			if (!tcp->tcp_rexmit) {
15043 				tcp_wput_data(tcp, NULL, B_FALSE);
15044 			} else {
15045 				tcp_ss_rexmit(tcp);
15046 			}
15047 		}
15048 		/*
15049 		 * Adjust tcp_cwnd back to normal value after sending
15050 		 * new data segments.
15051 		 */
15052 		if (flags & TH_LIMIT_XMIT) {
15053 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15054 			/*
15055 			 * This will restart the timer.  Restarting the
15056 			 * timer is used to avoid a timeout before the
15057 			 * limited transmitted segment's ACK gets back.
15058 			 */
15059 			if (tcp->tcp_xmit_head != NULL)
15060 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15061 		}
15062 
15063 		/* Anything more to do? */
15064 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15065 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15066 			goto done;
15067 	}
15068 ack_check:
15069 	if (flags & TH_SEND_URP_MARK) {
15070 		ASSERT(tcp->tcp_urp_mark_mp);
15071 		/*
15072 		 * Send up any queued data and then send the mark message
15073 		 */
15074 		if (tcp->tcp_rcv_list != NULL) {
15075 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15076 		}
15077 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15078 
15079 		mp1 = tcp->tcp_urp_mark_mp;
15080 		tcp->tcp_urp_mark_mp = NULL;
15081 #ifdef DEBUG
15082 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15083 		    "tcp_rput: sending zero-length %s %s",
15084 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15085 		    "MSGNOTMARKNEXT"),
15086 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15087 #endif /* DEBUG */
15088 		putnext(tcp->tcp_rq, mp1);
15089 		flags &= ~TH_SEND_URP_MARK;
15090 	}
15091 	if (flags & TH_ACK_NEEDED) {
15092 		/*
15093 		 * Time to send an ack for some reason.
15094 		 */
15095 		mp1 = tcp_ack_mp(tcp);
15096 
15097 		if (mp1 != NULL) {
15098 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15099 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15100 			BUMP_LOCAL(tcp->tcp_obsegs);
15101 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15102 		}
15103 		if (tcp->tcp_ack_tid != 0) {
15104 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15105 			tcp->tcp_ack_tid = 0;
15106 		}
15107 	}
15108 	if (flags & TH_ACK_TIMER_NEEDED) {
15109 		/*
15110 		 * Arrange for deferred ACK or push wait timeout.
15111 		 * Start timer if it is not already running.
15112 		 */
15113 		if (tcp->tcp_ack_tid == 0) {
15114 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15115 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15116 			    (clock_t)tcps->tcps_local_dack_interval :
15117 			    (clock_t)tcps->tcps_deferred_ack_interval));
15118 		}
15119 	}
15120 	if (flags & TH_ORDREL_NEEDED) {
15121 		/*
15122 		 * Send up the ordrel_ind unless we are an eager guy.
15123 		 * In the eager case tcp_rsrv will do this when run
15124 		 * after tcp_accept is done.
15125 		 */
15126 		ASSERT(tcp->tcp_listener == NULL);
15127 		if (tcp->tcp_rcv_list != NULL) {
15128 			/*
15129 			 * Push any mblk(s) enqueued from co processing.
15130 			 */
15131 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15132 		}
15133 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15134 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15135 			tcp->tcp_ordrel_done = B_TRUE;
15136 			putnext(tcp->tcp_rq, mp1);
15137 			if (tcp->tcp_deferred_clean_death) {
15138 				/*
15139 				 * tcp_clean_death was deferred
15140 				 * for T_ORDREL_IND - do it now
15141 				 */
15142 				(void) tcp_clean_death(tcp,
15143 				    tcp->tcp_client_errno, 20);
15144 				tcp->tcp_deferred_clean_death =	B_FALSE;
15145 			}
15146 		} else {
15147 			/*
15148 			 * Run the orderly release in the
15149 			 * service routine.
15150 			 */
15151 			qenable(tcp->tcp_rq);
15152 			/*
15153 			 * Caveat(XXX): The machine may be so
15154 			 * overloaded that tcp_rsrv() is not scheduled
15155 			 * until after the endpoint has transitioned
15156 			 * to TCPS_TIME_WAIT
15157 			 * and tcp_time_wait_interval expires. Then
15158 			 * tcp_timer() will blow away state in tcp_t
15159 			 * and T_ORDREL_IND will never be delivered
15160 			 * upstream. Unlikely but potentially
15161 			 * a problem.
15162 			 */
15163 		}
15164 	}
15165 done:
15166 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15167 }
15168 
15169 /*
15170  * This function does PAWS protection check. Returns B_TRUE if the
15171  * segment passes the PAWS test, else returns B_FALSE.
15172  */
15173 boolean_t
15174 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15175 {
15176 	uint8_t	flags;
15177 	int	options;
15178 	uint8_t *up;
15179 
15180 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15181 	/*
15182 	 * If timestamp option is aligned nicely, get values inline,
15183 	 * otherwise call general routine to parse.  Only do that
15184 	 * if timestamp is the only option.
15185 	 */
15186 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15187 	    TCPOPT_REAL_TS_LEN &&
15188 	    OK_32PTR((up = ((uint8_t *)tcph) +
15189 	    TCP_MIN_HEADER_LENGTH)) &&
15190 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15191 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15192 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15193 
15194 		options = TCP_OPT_TSTAMP_PRESENT;
15195 	} else {
15196 		if (tcp->tcp_snd_sack_ok) {
15197 			tcpoptp->tcp = tcp;
15198 		} else {
15199 			tcpoptp->tcp = NULL;
15200 		}
15201 		options = tcp_parse_options(tcph, tcpoptp);
15202 	}
15203 
15204 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15205 		/*
15206 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15207 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15208 		 */
15209 		if ((flags & TH_RST) == 0 &&
15210 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15211 		    tcp->tcp_ts_recent)) {
15212 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15213 			    PAWS_TIMEOUT)) {
15214 				/* This segment is not acceptable. */
15215 				return (B_FALSE);
15216 			} else {
15217 				/*
15218 				 * Connection has been idle for
15219 				 * too long.  Reset the timestamp
15220 				 * and assume the segment is valid.
15221 				 */
15222 				tcp->tcp_ts_recent =
15223 				    tcpoptp->tcp_opt_ts_val;
15224 			}
15225 		}
15226 	} else {
15227 		/*
15228 		 * If we don't get a timestamp on every packet, we
15229 		 * figure we can't really trust 'em, so we stop sending
15230 		 * and parsing them.
15231 		 */
15232 		tcp->tcp_snd_ts_ok = B_FALSE;
15233 
15234 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15235 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15236 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15237 		/*
15238 		 * Adjust the tcp_mss accordingly. We also need to
15239 		 * adjust tcp_cwnd here in accordance with the new mss.
15240 		 * But we avoid doing a slow start here so as to not
15241 		 * to lose on the transfer rate built up so far.
15242 		 */
15243 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15244 		if (tcp->tcp_snd_sack_ok) {
15245 			ASSERT(tcp->tcp_sack_info != NULL);
15246 			tcp->tcp_max_sack_blk = 4;
15247 		}
15248 	}
15249 	return (B_TRUE);
15250 }
15251 
15252 /*
15253  * Attach ancillary data to a received TCP segments for the
15254  * ancillary pieces requested by the application that are
15255  * different than they were in the previous data segment.
15256  *
15257  * Save the "current" values once memory allocation is ok so that
15258  * when memory allocation fails we can just wait for the next data segment.
15259  */
15260 static mblk_t *
15261 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15262 {
15263 	struct T_optdata_ind *todi;
15264 	int optlen;
15265 	uchar_t *optptr;
15266 	struct T_opthdr *toh;
15267 	uint_t addflag;	/* Which pieces to add */
15268 	mblk_t *mp1;
15269 
15270 	optlen = 0;
15271 	addflag = 0;
15272 	/* If app asked for pktinfo and the index has changed ... */
15273 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15274 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15275 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15276 		optlen += sizeof (struct T_opthdr) +
15277 		    sizeof (struct in6_pktinfo);
15278 		addflag |= TCP_IPV6_RECVPKTINFO;
15279 	}
15280 	/* If app asked for hoplimit and it has changed ... */
15281 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15282 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15283 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15284 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15285 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15286 	}
15287 	/* If app asked for tclass and it has changed ... */
15288 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15289 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15290 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15291 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15292 		addflag |= TCP_IPV6_RECVTCLASS;
15293 	}
15294 	/*
15295 	 * If app asked for hopbyhop headers and it has changed ...
15296 	 * For security labels, note that (1) security labels can't change on
15297 	 * a connected socket at all, (2) we're connected to at most one peer,
15298 	 * (3) if anything changes, then it must be some other extra option.
15299 	 */
15300 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15301 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15302 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15303 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15304 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15305 		    tcp->tcp_label_len;
15306 		addflag |= TCP_IPV6_RECVHOPOPTS;
15307 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15308 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15309 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15310 			return (mp);
15311 	}
15312 	/* If app asked for dst headers before routing headers ... */
15313 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15314 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15315 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15316 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15317 		optlen += sizeof (struct T_opthdr) +
15318 		    ipp->ipp_rtdstoptslen;
15319 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15320 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15321 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15322 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15323 			return (mp);
15324 	}
15325 	/* If app asked for routing headers and it has changed ... */
15326 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15327 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15328 	    (ipp->ipp_fields & IPPF_RTHDR),
15329 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15330 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15331 		addflag |= TCP_IPV6_RECVRTHDR;
15332 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15333 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15334 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15335 			return (mp);
15336 	}
15337 	/* If app asked for dest headers and it has changed ... */
15338 	if ((tcp->tcp_ipv6_recvancillary &
15339 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15340 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15341 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15342 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15343 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15344 		addflag |= TCP_IPV6_RECVDSTOPTS;
15345 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15346 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15347 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15348 			return (mp);
15349 	}
15350 
15351 	if (optlen == 0) {
15352 		/* Nothing to add */
15353 		return (mp);
15354 	}
15355 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15356 	if (mp1 == NULL) {
15357 		/*
15358 		 * Defer sending ancillary data until the next TCP segment
15359 		 * arrives.
15360 		 */
15361 		return (mp);
15362 	}
15363 	mp1->b_cont = mp;
15364 	mp = mp1;
15365 	mp->b_wptr += sizeof (*todi) + optlen;
15366 	mp->b_datap->db_type = M_PROTO;
15367 	todi = (struct T_optdata_ind *)mp->b_rptr;
15368 	todi->PRIM_type = T_OPTDATA_IND;
15369 	todi->DATA_flag = 1;	/* MORE data */
15370 	todi->OPT_length = optlen;
15371 	todi->OPT_offset = sizeof (*todi);
15372 	optptr = (uchar_t *)&todi[1];
15373 	/*
15374 	 * If app asked for pktinfo and the index has changed ...
15375 	 * Note that the local address never changes for the connection.
15376 	 */
15377 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15378 		struct in6_pktinfo *pkti;
15379 
15380 		toh = (struct T_opthdr *)optptr;
15381 		toh->level = IPPROTO_IPV6;
15382 		toh->name = IPV6_PKTINFO;
15383 		toh->len = sizeof (*toh) + sizeof (*pkti);
15384 		toh->status = 0;
15385 		optptr += sizeof (*toh);
15386 		pkti = (struct in6_pktinfo *)optptr;
15387 		if (tcp->tcp_ipversion == IPV6_VERSION)
15388 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15389 		else
15390 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15391 			    &pkti->ipi6_addr);
15392 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15393 		optptr += sizeof (*pkti);
15394 		ASSERT(OK_32PTR(optptr));
15395 		/* Save as "last" value */
15396 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15397 	}
15398 	/* If app asked for hoplimit and it has changed ... */
15399 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15400 		toh = (struct T_opthdr *)optptr;
15401 		toh->level = IPPROTO_IPV6;
15402 		toh->name = IPV6_HOPLIMIT;
15403 		toh->len = sizeof (*toh) + sizeof (uint_t);
15404 		toh->status = 0;
15405 		optptr += sizeof (*toh);
15406 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15407 		optptr += sizeof (uint_t);
15408 		ASSERT(OK_32PTR(optptr));
15409 		/* Save as "last" value */
15410 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15411 	}
15412 	/* If app asked for tclass and it has changed ... */
15413 	if (addflag & TCP_IPV6_RECVTCLASS) {
15414 		toh = (struct T_opthdr *)optptr;
15415 		toh->level = IPPROTO_IPV6;
15416 		toh->name = IPV6_TCLASS;
15417 		toh->len = sizeof (*toh) + sizeof (uint_t);
15418 		toh->status = 0;
15419 		optptr += sizeof (*toh);
15420 		*(uint_t *)optptr = ipp->ipp_tclass;
15421 		optptr += sizeof (uint_t);
15422 		ASSERT(OK_32PTR(optptr));
15423 		/* Save as "last" value */
15424 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15425 	}
15426 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15427 		toh = (struct T_opthdr *)optptr;
15428 		toh->level = IPPROTO_IPV6;
15429 		toh->name = IPV6_HOPOPTS;
15430 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15431 		    tcp->tcp_label_len;
15432 		toh->status = 0;
15433 		optptr += sizeof (*toh);
15434 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15435 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15436 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15437 		ASSERT(OK_32PTR(optptr));
15438 		/* Save as last value */
15439 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15440 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15441 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15442 	}
15443 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15444 		toh = (struct T_opthdr *)optptr;
15445 		toh->level = IPPROTO_IPV6;
15446 		toh->name = IPV6_RTHDRDSTOPTS;
15447 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15448 		toh->status = 0;
15449 		optptr += sizeof (*toh);
15450 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15451 		optptr += ipp->ipp_rtdstoptslen;
15452 		ASSERT(OK_32PTR(optptr));
15453 		/* Save as last value */
15454 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15455 		    &tcp->tcp_rtdstoptslen,
15456 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15457 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15458 	}
15459 	if (addflag & TCP_IPV6_RECVRTHDR) {
15460 		toh = (struct T_opthdr *)optptr;
15461 		toh->level = IPPROTO_IPV6;
15462 		toh->name = IPV6_RTHDR;
15463 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15464 		toh->status = 0;
15465 		optptr += sizeof (*toh);
15466 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15467 		optptr += ipp->ipp_rthdrlen;
15468 		ASSERT(OK_32PTR(optptr));
15469 		/* Save as last value */
15470 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15471 		    (ipp->ipp_fields & IPPF_RTHDR),
15472 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15473 	}
15474 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15475 		toh = (struct T_opthdr *)optptr;
15476 		toh->level = IPPROTO_IPV6;
15477 		toh->name = IPV6_DSTOPTS;
15478 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15479 		toh->status = 0;
15480 		optptr += sizeof (*toh);
15481 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15482 		optptr += ipp->ipp_dstoptslen;
15483 		ASSERT(OK_32PTR(optptr));
15484 		/* Save as last value */
15485 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15486 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15487 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15488 	}
15489 	ASSERT(optptr == mp->b_wptr);
15490 	return (mp);
15491 }
15492 
15493 
15494 /*
15495  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15496  * or a "bad" IRE detected by tcp_adapt_ire.
15497  * We can't tell if the failure was due to the laddr or the faddr
15498  * thus we clear out all addresses and ports.
15499  */
15500 static void
15501 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15502 {
15503 	queue_t	*q = tcp->tcp_rq;
15504 	tcph_t	*tcph;
15505 	struct T_error_ack *tea;
15506 	conn_t	*connp = tcp->tcp_connp;
15507 
15508 
15509 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15510 
15511 	if (mp->b_cont) {
15512 		freemsg(mp->b_cont);
15513 		mp->b_cont = NULL;
15514 	}
15515 	tea = (struct T_error_ack *)mp->b_rptr;
15516 	switch (tea->PRIM_type) {
15517 	case T_BIND_ACK:
15518 		/*
15519 		 * Need to unbind with classifier since we were just told that
15520 		 * our bind succeeded.
15521 		 */
15522 		tcp->tcp_hard_bound = B_FALSE;
15523 		tcp->tcp_hard_binding = B_FALSE;
15524 
15525 		ipcl_hash_remove(connp);
15526 		/* Reuse the mblk if possible */
15527 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15528 			sizeof (*tea));
15529 		mp->b_rptr = mp->b_datap->db_base;
15530 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15531 		tea = (struct T_error_ack *)mp->b_rptr;
15532 		tea->PRIM_type = T_ERROR_ACK;
15533 		tea->TLI_error = TSYSERR;
15534 		tea->UNIX_error = error;
15535 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15536 			tea->ERROR_prim = T_CONN_REQ;
15537 		} else {
15538 			tea->ERROR_prim = O_T_BIND_REQ;
15539 		}
15540 		break;
15541 
15542 	case T_ERROR_ACK:
15543 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15544 			tea->ERROR_prim = T_CONN_REQ;
15545 		break;
15546 	default:
15547 		panic("tcp_bind_failed: unexpected TPI type");
15548 		/*NOTREACHED*/
15549 	}
15550 
15551 	tcp->tcp_state = TCPS_IDLE;
15552 	if (tcp->tcp_ipversion == IPV4_VERSION)
15553 		tcp->tcp_ipha->ipha_src = 0;
15554 	else
15555 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15556 	/*
15557 	 * Copy of the src addr. in tcp_t is needed since
15558 	 * the lookup funcs. can only look at tcp_t
15559 	 */
15560 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15561 
15562 	tcph = tcp->tcp_tcph;
15563 	tcph->th_lport[0] = 0;
15564 	tcph->th_lport[1] = 0;
15565 	tcp_bind_hash_remove(tcp);
15566 	bzero(&connp->u_port, sizeof (connp->u_port));
15567 	/* blow away saved option results if any */
15568 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15569 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15570 
15571 	conn_delete_ire(tcp->tcp_connp, NULL);
15572 	putnext(q, mp);
15573 }
15574 
15575 /*
15576  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15577  * messages.
15578  */
15579 void
15580 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15581 {
15582 	mblk_t	*mp1;
15583 	uchar_t	*rptr = mp->b_rptr;
15584 	queue_t	*q = tcp->tcp_rq;
15585 	struct T_error_ack *tea;
15586 	uint32_t mss;
15587 	mblk_t *syn_mp;
15588 	mblk_t *mdti;
15589 	mblk_t *lsoi;
15590 	int	retval;
15591 	mblk_t *ire_mp;
15592 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15593 
15594 	switch (mp->b_datap->db_type) {
15595 	case M_PROTO:
15596 	case M_PCPROTO:
15597 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15598 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15599 			break;
15600 		tea = (struct T_error_ack *)rptr;
15601 		switch (tea->PRIM_type) {
15602 		case T_BIND_ACK:
15603 			/*
15604 			 * Adapt Multidata information, if any.  The
15605 			 * following tcp_mdt_update routine will free
15606 			 * the message.
15607 			 */
15608 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15609 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15610 				    b_rptr)->mdt_capab, B_TRUE);
15611 				freemsg(mdti);
15612 			}
15613 
15614 			/*
15615 			 * Check to update LSO information with tcp, and
15616 			 * tcp_lso_update routine will free the message.
15617 			 */
15618 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15619 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15620 				    b_rptr)->lso_capab);
15621 				freemsg(lsoi);
15622 			}
15623 
15624 			/* Get the IRE, if we had requested for it */
15625 			ire_mp = tcp_ire_mp(mp);
15626 
15627 			if (tcp->tcp_hard_binding) {
15628 				tcp->tcp_hard_binding = B_FALSE;
15629 				tcp->tcp_hard_bound = B_TRUE;
15630 				CL_INET_CONNECT(tcp);
15631 			} else {
15632 				if (ire_mp != NULL)
15633 					freeb(ire_mp);
15634 				goto after_syn_sent;
15635 			}
15636 
15637 			retval = tcp_adapt_ire(tcp, ire_mp);
15638 			if (ire_mp != NULL)
15639 				freeb(ire_mp);
15640 			if (retval == 0) {
15641 				tcp_bind_failed(tcp, mp,
15642 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15643 				    ENETUNREACH : EADDRNOTAVAIL));
15644 				return;
15645 			}
15646 			/*
15647 			 * Don't let an endpoint connect to itself.
15648 			 * Also checked in tcp_connect() but that
15649 			 * check can't handle the case when the
15650 			 * local IP address is INADDR_ANY.
15651 			 */
15652 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15653 				if ((tcp->tcp_ipha->ipha_dst ==
15654 				    tcp->tcp_ipha->ipha_src) &&
15655 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15656 				    tcp->tcp_tcph->th_fport))) {
15657 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15658 					return;
15659 				}
15660 			} else {
15661 				if (IN6_ARE_ADDR_EQUAL(
15662 				    &tcp->tcp_ip6h->ip6_dst,
15663 				    &tcp->tcp_ip6h->ip6_src) &&
15664 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15665 				    tcp->tcp_tcph->th_fport))) {
15666 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15667 					return;
15668 				}
15669 			}
15670 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15671 			/*
15672 			 * This should not be possible!  Just for
15673 			 * defensive coding...
15674 			 */
15675 			if (tcp->tcp_state != TCPS_SYN_SENT)
15676 				goto after_syn_sent;
15677 
15678 			if (is_system_labeled() &&
15679 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15680 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15681 				return;
15682 			}
15683 
15684 			ASSERT(q == tcp->tcp_rq);
15685 			/*
15686 			 * tcp_adapt_ire() does not adjust
15687 			 * for TCP/IP header length.
15688 			 */
15689 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15690 
15691 			/*
15692 			 * Just make sure our rwnd is at
15693 			 * least tcp_recv_hiwat_mss * MSS
15694 			 * large, and round up to the nearest
15695 			 * MSS.
15696 			 *
15697 			 * We do the round up here because
15698 			 * we need to get the interface
15699 			 * MTU first before we can do the
15700 			 * round up.
15701 			 */
15702 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15703 			    tcps->tcps_recv_hiwat_minmss * mss);
15704 			q->q_hiwat = tcp->tcp_rwnd;
15705 			tcp_set_ws_value(tcp);
15706 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15707 			    tcp->tcp_tcph->th_win);
15708 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
15709 				tcp->tcp_snd_ws_ok = B_TRUE;
15710 
15711 			/*
15712 			 * Set tcp_snd_ts_ok to true
15713 			 * so that tcp_xmit_mp will
15714 			 * include the timestamp
15715 			 * option in the SYN segment.
15716 			 */
15717 			if (tcps->tcps_tstamp_always ||
15718 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
15719 				tcp->tcp_snd_ts_ok = B_TRUE;
15720 			}
15721 
15722 			/*
15723 			 * tcp_snd_sack_ok can be set in
15724 			 * tcp_adapt_ire() if the sack metric
15725 			 * is set.  So check it here also.
15726 			 */
15727 			if (tcps->tcps_sack_permitted == 2 ||
15728 			    tcp->tcp_snd_sack_ok) {
15729 				if (tcp->tcp_sack_info == NULL) {
15730 					tcp->tcp_sack_info =
15731 					kmem_cache_alloc(tcp_sack_info_cache,
15732 					    KM_SLEEP);
15733 				}
15734 				tcp->tcp_snd_sack_ok = B_TRUE;
15735 			}
15736 
15737 			/*
15738 			 * Should we use ECN?  Note that the current
15739 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15740 			 * is 1.  The reason for doing this is that there
15741 			 * are equipments out there that will drop ECN
15742 			 * enabled IP packets.  Setting it to 1 avoids
15743 			 * compatibility problems.
15744 			 */
15745 			if (tcps->tcps_ecn_permitted == 2)
15746 				tcp->tcp_ecn_ok = B_TRUE;
15747 
15748 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15749 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15750 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15751 			if (syn_mp) {
15752 				cred_t *cr;
15753 				pid_t pid;
15754 
15755 				/*
15756 				 * Obtain the credential from the
15757 				 * thread calling connect(); the credential
15758 				 * lives on in the second mblk which
15759 				 * originated from T_CONN_REQ and is echoed
15760 				 * with the T_BIND_ACK from ip.  If none
15761 				 * can be found, default to the creator
15762 				 * of the socket.
15763 				 */
15764 				if (mp->b_cont == NULL ||
15765 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15766 					cr = tcp->tcp_cred;
15767 					pid = tcp->tcp_cpid;
15768 				} else {
15769 					pid = DB_CPID(mp->b_cont);
15770 				}
15771 
15772 				TCP_RECORD_TRACE(tcp, syn_mp,
15773 				    TCP_TRACE_SEND_PKT);
15774 				mblk_setcred(syn_mp, cr);
15775 				DB_CPID(syn_mp) = pid;
15776 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15777 			}
15778 		after_syn_sent:
15779 			/*
15780 			 * A trailer mblk indicates a waiting client upstream.
15781 			 * We complete here the processing begun in
15782 			 * either tcp_bind() or tcp_connect() by passing
15783 			 * upstream the reply message they supplied.
15784 			 */
15785 			mp1 = mp;
15786 			mp = mp->b_cont;
15787 			freeb(mp1);
15788 			if (mp)
15789 				break;
15790 			return;
15791 		case T_ERROR_ACK:
15792 			if (tcp->tcp_debug) {
15793 				(void) strlog(TCP_MOD_ID, 0, 1,
15794 				    SL_TRACE|SL_ERROR,
15795 				    "tcp_rput_other: case T_ERROR_ACK, "
15796 				    "ERROR_prim == %d",
15797 				    tea->ERROR_prim);
15798 			}
15799 			switch (tea->ERROR_prim) {
15800 			case O_T_BIND_REQ:
15801 			case T_BIND_REQ:
15802 				tcp_bind_failed(tcp, mp,
15803 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15804 				    ENETUNREACH : EADDRNOTAVAIL));
15805 				return;
15806 			case T_UNBIND_REQ:
15807 				tcp->tcp_hard_binding = B_FALSE;
15808 				tcp->tcp_hard_bound = B_FALSE;
15809 				if (mp->b_cont) {
15810 					freemsg(mp->b_cont);
15811 					mp->b_cont = NULL;
15812 				}
15813 				if (tcp->tcp_unbind_pending)
15814 					tcp->tcp_unbind_pending = 0;
15815 				else {
15816 					/* From tcp_ip_unbind() - free */
15817 					freemsg(mp);
15818 					return;
15819 				}
15820 				break;
15821 			case T_SVR4_OPTMGMT_REQ:
15822 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15823 					/* T_OPTMGMT_REQ generated by TCP */
15824 					printf("T_SVR4_OPTMGMT_REQ failed "
15825 					    "%d/%d - dropped (cnt %d)\n",
15826 					    tea->TLI_error, tea->UNIX_error,
15827 					    tcp->tcp_drop_opt_ack_cnt);
15828 					freemsg(mp);
15829 					tcp->tcp_drop_opt_ack_cnt--;
15830 					return;
15831 				}
15832 				break;
15833 			}
15834 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15835 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15836 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15837 				    "- dropped (cnt %d)\n",
15838 				    tea->TLI_error, tea->UNIX_error,
15839 				    tcp->tcp_drop_opt_ack_cnt);
15840 				freemsg(mp);
15841 				tcp->tcp_drop_opt_ack_cnt--;
15842 				return;
15843 			}
15844 			break;
15845 		case T_OPTMGMT_ACK:
15846 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15847 				/* T_OPTMGMT_REQ generated by TCP */
15848 				freemsg(mp);
15849 				tcp->tcp_drop_opt_ack_cnt--;
15850 				return;
15851 			}
15852 			break;
15853 		default:
15854 			break;
15855 		}
15856 		break;
15857 	case M_FLUSH:
15858 		if (*rptr & FLUSHR)
15859 			flushq(q, FLUSHDATA);
15860 		break;
15861 	default:
15862 		/* M_CTL will be directly sent to tcp_icmp_error() */
15863 		ASSERT(DB_TYPE(mp) != M_CTL);
15864 		break;
15865 	}
15866 	/*
15867 	 * Make sure we set this bit before sending the ACK for
15868 	 * bind. Otherwise accept could possibly run and free
15869 	 * this tcp struct.
15870 	 */
15871 	putnext(q, mp);
15872 }
15873 
15874 /*
15875  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15876  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15877  * tcp_rsrv() try again.
15878  */
15879 static void
15880 tcp_ordrel_kick(void *arg)
15881 {
15882 	conn_t 	*connp = (conn_t *)arg;
15883 	tcp_t	*tcp = connp->conn_tcp;
15884 
15885 	tcp->tcp_ordrelid = 0;
15886 	tcp->tcp_timeout = B_FALSE;
15887 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15888 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15889 		qenable(tcp->tcp_rq);
15890 	}
15891 }
15892 
15893 /* ARGSUSED */
15894 static void
15895 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15896 {
15897 	conn_t	*connp = (conn_t *)arg;
15898 	tcp_t	*tcp = connp->conn_tcp;
15899 	queue_t	*q = tcp->tcp_rq;
15900 	uint_t	thwin;
15901 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15902 
15903 	freeb(mp);
15904 
15905 	TCP_STAT(tcps, tcp_rsrv_calls);
15906 
15907 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15908 		return;
15909 	}
15910 
15911 	if (tcp->tcp_fused) {
15912 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15913 
15914 		ASSERT(tcp->tcp_fused);
15915 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15916 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15917 		ASSERT(!TCP_IS_DETACHED(tcp));
15918 		ASSERT(tcp->tcp_connp->conn_sqp ==
15919 		    peer_tcp->tcp_connp->conn_sqp);
15920 
15921 		/*
15922 		 * Normally we would not get backenabled in synchronous
15923 		 * streams mode, but in case this happens, we need to plug
15924 		 * synchronous streams during our drain to prevent a race
15925 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15926 		 */
15927 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15928 		if (tcp->tcp_rcv_list != NULL)
15929 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15930 
15931 		if (peer_tcp > tcp) {
15932 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15933 			mutex_enter(&tcp->tcp_non_sq_lock);
15934 		} else {
15935 			mutex_enter(&tcp->tcp_non_sq_lock);
15936 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15937 		}
15938 
15939 		if (peer_tcp->tcp_flow_stopped &&
15940 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15941 		    peer_tcp->tcp_xmit_lowater)) {
15942 			tcp_clrqfull(peer_tcp);
15943 		}
15944 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15945 		mutex_exit(&tcp->tcp_non_sq_lock);
15946 
15947 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15948 		TCP_STAT(tcps, tcp_fusion_backenabled);
15949 		return;
15950 	}
15951 
15952 	if (canputnext(q)) {
15953 		tcp->tcp_rwnd = q->q_hiwat;
15954 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15955 		    << tcp->tcp_rcv_ws;
15956 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15957 		/*
15958 		 * Send back a window update immediately if TCP is above
15959 		 * ESTABLISHED state and the increase of the rcv window
15960 		 * that the other side knows is at least 1 MSS after flow
15961 		 * control is lifted.
15962 		 */
15963 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15964 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15965 			tcp_xmit_ctl(NULL, tcp,
15966 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15967 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15968 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15969 		}
15970 	}
15971 	/* Handle a failure to allocate a T_ORDREL_IND here */
15972 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15973 		ASSERT(tcp->tcp_listener == NULL);
15974 		if (tcp->tcp_rcv_list != NULL) {
15975 			(void) tcp_rcv_drain(q, tcp);
15976 		}
15977 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15978 		mp = mi_tpi_ordrel_ind();
15979 		if (mp) {
15980 			tcp->tcp_ordrel_done = B_TRUE;
15981 			putnext(q, mp);
15982 			if (tcp->tcp_deferred_clean_death) {
15983 				/*
15984 				 * tcp_clean_death was deferred for
15985 				 * T_ORDREL_IND - do it now
15986 				 */
15987 				tcp->tcp_deferred_clean_death = B_FALSE;
15988 				(void) tcp_clean_death(tcp,
15989 				    tcp->tcp_client_errno, 22);
15990 			}
15991 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15992 			/*
15993 			 * If there isn't already a timer running
15994 			 * start one.  Use a 4 second
15995 			 * timer as a fallback since it can't fail.
15996 			 */
15997 			tcp->tcp_timeout = B_TRUE;
15998 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15999 			    MSEC_TO_TICK(4000));
16000 		}
16001 	}
16002 }
16003 
16004 /*
16005  * The read side service routine is called mostly when we get back-enabled as a
16006  * result of flow control relief.  Since we don't actually queue anything in
16007  * TCP, we have no data to send out of here.  What we do is clear the receive
16008  * window, and send out a window update.
16009  * This routine is also called to drive an orderly release message upstream
16010  * if the attempt in tcp_rput failed.
16011  */
16012 static void
16013 tcp_rsrv(queue_t *q)
16014 {
16015 	conn_t *connp = Q_TO_CONN(q);
16016 	tcp_t	*tcp = connp->conn_tcp;
16017 	mblk_t	*mp;
16018 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16019 
16020 	/* No code does a putq on the read side */
16021 	ASSERT(q->q_first == NULL);
16022 
16023 	/* Nothing to do for the default queue */
16024 	if (q == tcps->tcps_g_q) {
16025 		return;
16026 	}
16027 
16028 	mp = allocb(0, BPRI_HI);
16029 	if (mp == NULL) {
16030 		/*
16031 		 * We are under memory pressure. Return for now and we
16032 		 * we will be called again later.
16033 		 */
16034 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16035 			/*
16036 			 * If there isn't already a timer running
16037 			 * start one.  Use a 4 second
16038 			 * timer as a fallback since it can't fail.
16039 			 */
16040 			tcp->tcp_timeout = B_TRUE;
16041 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16042 			    MSEC_TO_TICK(4000));
16043 		}
16044 		return;
16045 	}
16046 	CONN_INC_REF(connp);
16047 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16048 	    SQTAG_TCP_RSRV);
16049 }
16050 
16051 /*
16052  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16053  * We do not allow the receive window to shrink.  After setting rwnd,
16054  * set the flow control hiwat of the stream.
16055  *
16056  * This function is called in 2 cases:
16057  *
16058  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16059  *    connection (passive open) and in tcp_rput_data() for active connect.
16060  *    This is called after tcp_mss_set() when the desired MSS value is known.
16061  *    This makes sure that our window size is a mutiple of the other side's
16062  *    MSS.
16063  * 2) Handling SO_RCVBUF option.
16064  *
16065  * It is ASSUMED that the requested size is a multiple of the current MSS.
16066  *
16067  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16068  * user requests so.
16069  */
16070 static int
16071 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16072 {
16073 	uint32_t	mss = tcp->tcp_mss;
16074 	uint32_t	old_max_rwnd;
16075 	uint32_t	max_transmittable_rwnd;
16076 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16077 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16078 
16079 	if (tcp->tcp_fused) {
16080 		size_t sth_hiwat;
16081 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16082 
16083 		ASSERT(peer_tcp != NULL);
16084 		/*
16085 		 * Record the stream head's high water mark for
16086 		 * this endpoint; this is used for flow-control
16087 		 * purposes in tcp_fuse_output().
16088 		 */
16089 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16090 		if (!tcp_detached)
16091 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16092 
16093 		/*
16094 		 * In the fusion case, the maxpsz stream head value of
16095 		 * our peer is set according to its send buffer size
16096 		 * and our receive buffer size; since the latter may
16097 		 * have changed we need to update the peer's maxpsz.
16098 		 */
16099 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16100 		return (rwnd);
16101 	}
16102 
16103 	if (tcp_detached)
16104 		old_max_rwnd = tcp->tcp_rwnd;
16105 	else
16106 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16107 
16108 	/*
16109 	 * Insist on a receive window that is at least
16110 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16111 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16112 	 * and delayed acknowledgement.
16113 	 */
16114 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16115 
16116 	/*
16117 	 * If window size info has already been exchanged, TCP should not
16118 	 * shrink the window.  Shrinking window is doable if done carefully.
16119 	 * We may add that support later.  But so far there is not a real
16120 	 * need to do that.
16121 	 */
16122 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16123 		/* MSS may have changed, do a round up again. */
16124 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16125 	}
16126 
16127 	/*
16128 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16129 	 * can be applied even before the window scale option is decided.
16130 	 */
16131 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16132 	if (rwnd > max_transmittable_rwnd) {
16133 		rwnd = max_transmittable_rwnd -
16134 		    (max_transmittable_rwnd % mss);
16135 		if (rwnd < mss)
16136 			rwnd = max_transmittable_rwnd;
16137 		/*
16138 		 * If we're over the limit we may have to back down tcp_rwnd.
16139 		 * The increment below won't work for us. So we set all three
16140 		 * here and the increment below will have no effect.
16141 		 */
16142 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16143 	}
16144 	if (tcp->tcp_localnet) {
16145 		tcp->tcp_rack_abs_max =
16146 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16147 	} else {
16148 		/*
16149 		 * For a remote host on a different subnet (through a router),
16150 		 * we ack every other packet to be conforming to RFC1122.
16151 		 * tcp_deferred_acks_max is default to 2.
16152 		 */
16153 		tcp->tcp_rack_abs_max =
16154 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16155 	}
16156 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16157 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16158 	else
16159 		tcp->tcp_rack_cur_max = 0;
16160 	/*
16161 	 * Increment the current rwnd by the amount the maximum grew (we
16162 	 * can not overwrite it since we might be in the middle of a
16163 	 * connection.)
16164 	 */
16165 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16166 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16167 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16168 		tcp->tcp_cwnd_max = rwnd;
16169 
16170 	if (tcp_detached)
16171 		return (rwnd);
16172 	/*
16173 	 * We set the maximum receive window into rq->q_hiwat.
16174 	 * This is not actually used for flow control.
16175 	 */
16176 	tcp->tcp_rq->q_hiwat = rwnd;
16177 	/*
16178 	 * Set the Stream head high water mark. This doesn't have to be
16179 	 * here, since we are simply using default values, but we would
16180 	 * prefer to choose these values algorithmically, with a likely
16181 	 * relationship to rwnd.
16182 	 */
16183 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16184 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16185 	return (rwnd);
16186 }
16187 
16188 /*
16189  * Return SNMP stuff in buffer in mpdata.
16190  */
16191 int
16192 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16193 {
16194 	mblk_t			*mpdata;
16195 	mblk_t			*mp_conn_ctl = NULL;
16196 	mblk_t			*mp_conn_tail;
16197 	mblk_t			*mp_attr_ctl = NULL;
16198 	mblk_t			*mp_attr_tail;
16199 	mblk_t			*mp6_conn_ctl = NULL;
16200 	mblk_t			*mp6_conn_tail;
16201 	mblk_t			*mp6_attr_ctl = NULL;
16202 	mblk_t			*mp6_attr_tail;
16203 	struct opthdr		*optp;
16204 	mib2_tcpConnEntry_t	tce;
16205 	mib2_tcp6ConnEntry_t	tce6;
16206 	mib2_transportMLPEntry_t mlp;
16207 	connf_t			*connfp;
16208 	conn_t			*connp;
16209 	int			i;
16210 	boolean_t 		ispriv;
16211 	zoneid_t 		zoneid;
16212 	int			v4_conn_idx;
16213 	int			v6_conn_idx;
16214 	tcp_stack_t		*tcps = Q_TO_TCP(q)->tcp_tcps;
16215 	ip_stack_t	*ipst;
16216 
16217 	if (mpctl == NULL ||
16218 	    (mpdata = mpctl->b_cont) == NULL ||
16219 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16220 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16221 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16222 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16223 		freemsg(mp_conn_ctl);
16224 		freemsg(mp_attr_ctl);
16225 		freemsg(mp6_conn_ctl);
16226 		freemsg(mp6_attr_ctl);
16227 		return (0);
16228 	}
16229 
16230 	/* build table of connections -- need count in fixed part */
16231 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16232 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16233 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16234 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16235 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16236 
16237 	ispriv =
16238 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16239 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16240 
16241 	v4_conn_idx = v6_conn_idx = 0;
16242 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16243 
16244 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16245 		ipst = tcps->tcps_netstack->netstack_ip;
16246 
16247 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16248 
16249 		connp = NULL;
16250 
16251 		while ((connp =
16252 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16253 			tcp_t *tcp;
16254 			boolean_t needattr;
16255 
16256 			if (connp->conn_zoneid != zoneid)
16257 				continue;	/* not in this zone */
16258 
16259 			tcp = connp->conn_tcp;
16260 			UPDATE_MIB(&tcps->tcps_mib,
16261 			    tcpHCInSegs, tcp->tcp_ibsegs);
16262 			tcp->tcp_ibsegs = 0;
16263 			UPDATE_MIB(&tcps->tcps_mib,
16264 			    tcpHCOutSegs, tcp->tcp_obsegs);
16265 			tcp->tcp_obsegs = 0;
16266 
16267 			tce6.tcp6ConnState = tce.tcpConnState =
16268 			    tcp_snmp_state(tcp);
16269 			if (tce.tcpConnState == MIB2_TCP_established ||
16270 			    tce.tcpConnState == MIB2_TCP_closeWait)
16271 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16272 
16273 			needattr = B_FALSE;
16274 			bzero(&mlp, sizeof (mlp));
16275 			if (connp->conn_mlp_type != mlptSingle) {
16276 				if (connp->conn_mlp_type == mlptShared ||
16277 				    connp->conn_mlp_type == mlptBoth)
16278 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16279 				if (connp->conn_mlp_type == mlptPrivate ||
16280 				    connp->conn_mlp_type == mlptBoth)
16281 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16282 				needattr = B_TRUE;
16283 			}
16284 			if (connp->conn_peercred != NULL) {
16285 				ts_label_t *tsl;
16286 
16287 				tsl = crgetlabel(connp->conn_peercred);
16288 				mlp.tme_doi = label2doi(tsl);
16289 				mlp.tme_label = *label2bslabel(tsl);
16290 				needattr = B_TRUE;
16291 			}
16292 
16293 			/* Create a message to report on IPv6 entries */
16294 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16295 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16296 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16297 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16298 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16299 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16300 			/* Don't want just anybody seeing these... */
16301 			if (ispriv) {
16302 				tce6.tcp6ConnEntryInfo.ce_snxt =
16303 				    tcp->tcp_snxt;
16304 				tce6.tcp6ConnEntryInfo.ce_suna =
16305 				    tcp->tcp_suna;
16306 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16307 				    tcp->tcp_rnxt;
16308 				tce6.tcp6ConnEntryInfo.ce_rack =
16309 				    tcp->tcp_rack;
16310 			} else {
16311 				/*
16312 				 * Netstat, unfortunately, uses this to
16313 				 * get send/receive queue sizes.  How to fix?
16314 				 * Why not compute the difference only?
16315 				 */
16316 				tce6.tcp6ConnEntryInfo.ce_snxt =
16317 				    tcp->tcp_snxt - tcp->tcp_suna;
16318 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16319 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16320 				    tcp->tcp_rnxt - tcp->tcp_rack;
16321 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16322 			}
16323 
16324 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16325 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16326 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16327 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16328 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16329 
16330 			tce6.tcp6ConnCreationProcess =
16331 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16332 			    tcp->tcp_cpid;
16333 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16334 
16335 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16336 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16337 
16338 			mlp.tme_connidx = v6_conn_idx++;
16339 			if (needattr)
16340 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16341 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16342 			}
16343 			/*
16344 			 * Create an IPv4 table entry for IPv4 entries and also
16345 			 * for IPv6 entries which are bound to in6addr_any
16346 			 * but don't have IPV6_V6ONLY set.
16347 			 * (i.e. anything an IPv4 peer could connect to)
16348 			 */
16349 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16350 			    (tcp->tcp_state <= TCPS_LISTEN &&
16351 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16352 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16353 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16354 					tce.tcpConnRemAddress = INADDR_ANY;
16355 					tce.tcpConnLocalAddress = INADDR_ANY;
16356 				} else {
16357 					tce.tcpConnRemAddress =
16358 					    tcp->tcp_remote;
16359 					tce.tcpConnLocalAddress =
16360 					    tcp->tcp_ip_src;
16361 				}
16362 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16363 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16364 				/* Don't want just anybody seeing these... */
16365 				if (ispriv) {
16366 					tce.tcpConnEntryInfo.ce_snxt =
16367 					    tcp->tcp_snxt;
16368 					tce.tcpConnEntryInfo.ce_suna =
16369 					    tcp->tcp_suna;
16370 					tce.tcpConnEntryInfo.ce_rnxt =
16371 					    tcp->tcp_rnxt;
16372 					tce.tcpConnEntryInfo.ce_rack =
16373 					    tcp->tcp_rack;
16374 				} else {
16375 					/*
16376 					 * Netstat, unfortunately, uses this to
16377 					 * get send/receive queue sizes.  How
16378 					 * to fix?
16379 					 * Why not compute the difference only?
16380 					 */
16381 					tce.tcpConnEntryInfo.ce_snxt =
16382 					    tcp->tcp_snxt - tcp->tcp_suna;
16383 					tce.tcpConnEntryInfo.ce_suna = 0;
16384 					tce.tcpConnEntryInfo.ce_rnxt =
16385 					    tcp->tcp_rnxt - tcp->tcp_rack;
16386 					tce.tcpConnEntryInfo.ce_rack = 0;
16387 				}
16388 
16389 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16390 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16391 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16392 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16393 				tce.tcpConnEntryInfo.ce_state =
16394 				    tcp->tcp_state;
16395 
16396 				tce.tcpConnCreationProcess =
16397 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16398 				    tcp->tcp_cpid;
16399 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16400 
16401 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16402 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16403 
16404 				mlp.tme_connidx = v4_conn_idx++;
16405 				if (needattr)
16406 					(void) snmp_append_data2(
16407 					    mp_attr_ctl->b_cont,
16408 					    &mp_attr_tail, (char *)&mlp,
16409 					    sizeof (mlp));
16410 			}
16411 		}
16412 	}
16413 
16414 	/* fixed length structure for IPv4 and IPv6 counters */
16415 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16416 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16417 	    sizeof (mib2_tcp6ConnEntry_t));
16418 	/* synchronize 32- and 64-bit counters */
16419 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16420 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16421 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16422 	optp->level = MIB2_TCP;
16423 	optp->name = 0;
16424 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16425 	    sizeof (tcps->tcps_mib));
16426 	optp->len = msgdsize(mpdata);
16427 	qreply(q, mpctl);
16428 
16429 	/* table of connections... */
16430 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16431 	    sizeof (struct T_optmgmt_ack)];
16432 	optp->level = MIB2_TCP;
16433 	optp->name = MIB2_TCP_CONN;
16434 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16435 	qreply(q, mp_conn_ctl);
16436 
16437 	/* table of MLP attributes... */
16438 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16439 	    sizeof (struct T_optmgmt_ack)];
16440 	optp->level = MIB2_TCP;
16441 	optp->name = EXPER_XPORT_MLP;
16442 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16443 	if (optp->len == 0)
16444 		freemsg(mp_attr_ctl);
16445 	else
16446 		qreply(q, mp_attr_ctl);
16447 
16448 	/* table of IPv6 connections... */
16449 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16450 	    sizeof (struct T_optmgmt_ack)];
16451 	optp->level = MIB2_TCP6;
16452 	optp->name = MIB2_TCP6_CONN;
16453 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16454 	qreply(q, mp6_conn_ctl);
16455 
16456 	/* table of IPv6 MLP attributes... */
16457 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16458 	    sizeof (struct T_optmgmt_ack)];
16459 	optp->level = MIB2_TCP6;
16460 	optp->name = EXPER_XPORT_MLP;
16461 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16462 	if (optp->len == 0)
16463 		freemsg(mp6_attr_ctl);
16464 	else
16465 		qreply(q, mp6_attr_ctl);
16466 	return (1);
16467 }
16468 
16469 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16470 /* ARGSUSED */
16471 int
16472 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16473 {
16474 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16475 
16476 	switch (level) {
16477 	case MIB2_TCP:
16478 		switch (name) {
16479 		case 13:
16480 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16481 				return (0);
16482 			/* TODO: delete entry defined by tce */
16483 			return (1);
16484 		default:
16485 			return (0);
16486 		}
16487 	default:
16488 		return (1);
16489 	}
16490 }
16491 
16492 /* Translate TCP state to MIB2 TCP state. */
16493 static int
16494 tcp_snmp_state(tcp_t *tcp)
16495 {
16496 	if (tcp == NULL)
16497 		return (0);
16498 
16499 	switch (tcp->tcp_state) {
16500 	case TCPS_CLOSED:
16501 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16502 	case TCPS_BOUND:
16503 		return (MIB2_TCP_closed);
16504 	case TCPS_LISTEN:
16505 		return (MIB2_TCP_listen);
16506 	case TCPS_SYN_SENT:
16507 		return (MIB2_TCP_synSent);
16508 	case TCPS_SYN_RCVD:
16509 		return (MIB2_TCP_synReceived);
16510 	case TCPS_ESTABLISHED:
16511 		return (MIB2_TCP_established);
16512 	case TCPS_CLOSE_WAIT:
16513 		return (MIB2_TCP_closeWait);
16514 	case TCPS_FIN_WAIT_1:
16515 		return (MIB2_TCP_finWait1);
16516 	case TCPS_CLOSING:
16517 		return (MIB2_TCP_closing);
16518 	case TCPS_LAST_ACK:
16519 		return (MIB2_TCP_lastAck);
16520 	case TCPS_FIN_WAIT_2:
16521 		return (MIB2_TCP_finWait2);
16522 	case TCPS_TIME_WAIT:
16523 		return (MIB2_TCP_timeWait);
16524 	default:
16525 		return (0);
16526 	}
16527 }
16528 
16529 static char tcp_report_header[] =
16530 	"TCP     " MI_COL_HDRPAD_STR
16531 	"zone dest            snxt     suna     "
16532 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16533 	"recent   [lport,fport] state";
16534 
16535 /*
16536  * TCP status report triggered via the Named Dispatch mechanism.
16537  */
16538 /* ARGSUSED */
16539 static void
16540 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16541     cred_t *cr)
16542 {
16543 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16544 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16545 	char cflag;
16546 	in6_addr_t	v6dst;
16547 	char buf[80];
16548 	uint_t print_len, buf_len;
16549 
16550 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16551 	if (buf_len <= 0)
16552 		return;
16553 
16554 	if (hashval >= 0)
16555 		(void) sprintf(hash, "%03d ", hashval);
16556 	else
16557 		hash[0] = '\0';
16558 
16559 	/*
16560 	 * Note that we use the remote address in the tcp_b  structure.
16561 	 * This means that it will print out the real destination address,
16562 	 * not the next hop's address if source routing is used.  This
16563 	 * avoid the confusion on the output because user may not
16564 	 * know that source routing is used for a connection.
16565 	 */
16566 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16567 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16568 	} else {
16569 		v6dst = tcp->tcp_remote_v6;
16570 	}
16571 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16572 	/*
16573 	 * the ispriv checks are so that normal users cannot determine
16574 	 * sequence number information using NDD.
16575 	 */
16576 
16577 	if (TCP_IS_DETACHED(tcp))
16578 		cflag = '*';
16579 	else
16580 		cflag = ' ';
16581 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16582 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16583 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16584 	    hash,
16585 	    (void *)tcp,
16586 	    tcp->tcp_connp->conn_zoneid,
16587 	    addrbuf,
16588 	    (ispriv) ? tcp->tcp_snxt : 0,
16589 	    (ispriv) ? tcp->tcp_suna : 0,
16590 	    tcp->tcp_swnd,
16591 	    (ispriv) ? tcp->tcp_rnxt : 0,
16592 	    (ispriv) ? tcp->tcp_rack : 0,
16593 	    tcp->tcp_rwnd,
16594 	    tcp->tcp_rto,
16595 	    tcp->tcp_mss,
16596 	    tcp->tcp_snd_ws_ok,
16597 	    tcp->tcp_snd_ws,
16598 	    tcp->tcp_rcv_ws,
16599 	    tcp->tcp_snd_ts_ok,
16600 	    tcp->tcp_ts_recent,
16601 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16602 	if (print_len < buf_len) {
16603 		((mblk_t *)mp)->b_wptr += print_len;
16604 	} else {
16605 		((mblk_t *)mp)->b_wptr += buf_len;
16606 	}
16607 }
16608 
16609 /*
16610  * TCP status report (for listeners only) triggered via the Named Dispatch
16611  * mechanism.
16612  */
16613 /* ARGSUSED */
16614 static void
16615 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16616 {
16617 	char addrbuf[INET6_ADDRSTRLEN];
16618 	in6_addr_t	v6dst;
16619 	uint_t print_len, buf_len;
16620 
16621 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16622 	if (buf_len <= 0)
16623 		return;
16624 
16625 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16626 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16627 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16628 	} else {
16629 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16630 		    addrbuf, sizeof (addrbuf));
16631 	}
16632 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16633 	    "%03d "
16634 	    MI_COL_PTRFMT_STR
16635 	    "%d %s %05u %08u %d/%d/%d%c\n",
16636 	    hashval, (void *)tcp,
16637 	    tcp->tcp_connp->conn_zoneid,
16638 	    addrbuf,
16639 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16640 	    tcp->tcp_conn_req_seqnum,
16641 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16642 	    tcp->tcp_conn_req_max,
16643 	    tcp->tcp_syn_defense ? '*' : ' ');
16644 	if (print_len < buf_len) {
16645 		((mblk_t *)mp)->b_wptr += print_len;
16646 	} else {
16647 		((mblk_t *)mp)->b_wptr += buf_len;
16648 	}
16649 }
16650 
16651 /* TCP status report triggered via the Named Dispatch mechanism. */
16652 /* ARGSUSED */
16653 static int
16654 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16655 {
16656 	tcp_t	*tcp;
16657 	int	i;
16658 	conn_t	*connp;
16659 	connf_t	*connfp;
16660 	zoneid_t zoneid;
16661 	tcp_stack_t *tcps;
16662 	ip_stack_t *ipst;
16663 
16664 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16665 	tcps = Q_TO_TCP(q)->tcp_tcps;
16666 
16667 	/*
16668 	 * Because of the ndd constraint, at most we can have 64K buffer
16669 	 * to put in all TCP info.  So to be more efficient, just
16670 	 * allocate a 64K buffer here, assuming we need that large buffer.
16671 	 * This may be a problem as any user can read tcp_status.  Therefore
16672 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16673 	 * This should be OK as normal users should not do this too often.
16674 	 */
16675 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16676 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16677 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16678 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16679 			return (0);
16680 		}
16681 	}
16682 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16683 		/* The following may work even if we cannot get a large buf. */
16684 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16685 		return (0);
16686 	}
16687 
16688 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16689 
16690 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16691 
16692 		ipst = tcps->tcps_netstack->netstack_ip;
16693 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16694 
16695 		connp = NULL;
16696 
16697 		while ((connp =
16698 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16699 			tcp = connp->conn_tcp;
16700 			if (zoneid != GLOBAL_ZONEID &&
16701 			    zoneid != connp->conn_zoneid)
16702 				continue;
16703 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16704 			    cr);
16705 		}
16706 
16707 	}
16708 
16709 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16710 	return (0);
16711 }
16712 
16713 /* TCP status report triggered via the Named Dispatch mechanism. */
16714 /* ARGSUSED */
16715 static int
16716 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16717 {
16718 	tf_t	*tbf;
16719 	tcp_t	*tcp;
16720 	int	i;
16721 	zoneid_t zoneid;
16722 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16723 
16724 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16725 
16726 	/* Refer to comments in tcp_status_report(). */
16727 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16728 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16729 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16730 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16731 			return (0);
16732 		}
16733 	}
16734 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16735 		/* The following may work even if we cannot get a large buf. */
16736 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16737 		return (0);
16738 	}
16739 
16740 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16741 
16742 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16743 		tbf = &tcps->tcps_bind_fanout[i];
16744 		mutex_enter(&tbf->tf_lock);
16745 		for (tcp = tbf->tf_tcp; tcp != NULL;
16746 		    tcp = tcp->tcp_bind_hash) {
16747 			if (zoneid != GLOBAL_ZONEID &&
16748 			    zoneid != tcp->tcp_connp->conn_zoneid)
16749 				continue;
16750 			CONN_INC_REF(tcp->tcp_connp);
16751 			tcp_report_item(mp->b_cont, tcp, i,
16752 			    Q_TO_TCP(q), cr);
16753 			CONN_DEC_REF(tcp->tcp_connp);
16754 		}
16755 		mutex_exit(&tbf->tf_lock);
16756 	}
16757 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16758 	return (0);
16759 }
16760 
16761 /* TCP status report triggered via the Named Dispatch mechanism. */
16762 /* ARGSUSED */
16763 static int
16764 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16765 {
16766 	connf_t	*connfp;
16767 	conn_t	*connp;
16768 	tcp_t	*tcp;
16769 	int	i;
16770 	zoneid_t zoneid;
16771 	tcp_stack_t *tcps;
16772 	ip_stack_t	*ipst;
16773 
16774 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16775 	tcps = Q_TO_TCP(q)->tcp_tcps;
16776 
16777 	/* Refer to comments in tcp_status_report(). */
16778 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16779 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16780 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16781 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16782 			return (0);
16783 		}
16784 	}
16785 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16786 		/* The following may work even if we cannot get a large buf. */
16787 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16788 		return (0);
16789 	}
16790 
16791 	(void) mi_mpprintf(mp,
16792 	    "    TCP    " MI_COL_HDRPAD_STR
16793 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16794 
16795 	ipst = tcps->tcps_netstack->netstack_ip;
16796 
16797 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16798 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16799 		connp = NULL;
16800 		while ((connp =
16801 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16802 			tcp = connp->conn_tcp;
16803 			if (zoneid != GLOBAL_ZONEID &&
16804 			    zoneid != connp->conn_zoneid)
16805 				continue;
16806 			tcp_report_listener(mp->b_cont, tcp, i);
16807 		}
16808 	}
16809 
16810 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16811 	return (0);
16812 }
16813 
16814 /* TCP status report triggered via the Named Dispatch mechanism. */
16815 /* ARGSUSED */
16816 static int
16817 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16818 {
16819 	connf_t	*connfp;
16820 	conn_t	*connp;
16821 	tcp_t	*tcp;
16822 	int	i;
16823 	zoneid_t zoneid;
16824 	tcp_stack_t *tcps;
16825 	ip_stack_t *ipst;
16826 
16827 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16828 	tcps = Q_TO_TCP(q)->tcp_tcps;
16829 	ipst = tcps->tcps_netstack->netstack_ip;
16830 
16831 	/* Refer to comments in tcp_status_report(). */
16832 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16833 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16834 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16835 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16836 			return (0);
16837 		}
16838 	}
16839 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16840 		/* The following may work even if we cannot get a large buf. */
16841 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16842 		return (0);
16843 	}
16844 
16845 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16846 	    ipst->ips_ipcl_conn_fanout_size);
16847 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16848 
16849 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16850 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16851 		connp = NULL;
16852 		while ((connp =
16853 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16854 			tcp = connp->conn_tcp;
16855 			if (zoneid != GLOBAL_ZONEID &&
16856 			    zoneid != connp->conn_zoneid)
16857 				continue;
16858 			tcp_report_item(mp->b_cont, tcp, i,
16859 			    Q_TO_TCP(q), cr);
16860 		}
16861 	}
16862 
16863 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16864 	return (0);
16865 }
16866 
16867 /* TCP status report triggered via the Named Dispatch mechanism. */
16868 /* ARGSUSED */
16869 static int
16870 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16871 {
16872 	tf_t	*tf;
16873 	tcp_t	*tcp;
16874 	int	i;
16875 	zoneid_t zoneid;
16876 	tcp_stack_t	*tcps;
16877 
16878 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16879 	tcps = Q_TO_TCP(q)->tcp_tcps;
16880 
16881 	/* Refer to comments in tcp_status_report(). */
16882 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16883 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16884 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16885 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16886 			return (0);
16887 		}
16888 	}
16889 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16890 		/* The following may work even if we cannot get a large buf. */
16891 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16892 		return (0);
16893 	}
16894 
16895 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16896 
16897 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16898 		tf = &tcps->tcps_acceptor_fanout[i];
16899 		mutex_enter(&tf->tf_lock);
16900 		for (tcp = tf->tf_tcp; tcp != NULL;
16901 		    tcp = tcp->tcp_acceptor_hash) {
16902 			if (zoneid != GLOBAL_ZONEID &&
16903 			    zoneid != tcp->tcp_connp->conn_zoneid)
16904 				continue;
16905 			tcp_report_item(mp->b_cont, tcp, i,
16906 			    Q_TO_TCP(q), cr);
16907 		}
16908 		mutex_exit(&tf->tf_lock);
16909 	}
16910 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16911 	return (0);
16912 }
16913 
16914 /*
16915  * tcp_timer is the timer service routine.  It handles the retransmission,
16916  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16917  * from the state of the tcp instance what kind of action needs to be done
16918  * at the time it is called.
16919  */
16920 static void
16921 tcp_timer(void *arg)
16922 {
16923 	mblk_t		*mp;
16924 	clock_t		first_threshold;
16925 	clock_t		second_threshold;
16926 	clock_t		ms;
16927 	uint32_t	mss;
16928 	conn_t		*connp = (conn_t *)arg;
16929 	tcp_t		*tcp = connp->conn_tcp;
16930 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16931 
16932 	tcp->tcp_timer_tid = 0;
16933 
16934 	if (tcp->tcp_fused)
16935 		return;
16936 
16937 	first_threshold =  tcp->tcp_first_timer_threshold;
16938 	second_threshold = tcp->tcp_second_timer_threshold;
16939 	switch (tcp->tcp_state) {
16940 	case TCPS_IDLE:
16941 	case TCPS_BOUND:
16942 	case TCPS_LISTEN:
16943 		return;
16944 	case TCPS_SYN_RCVD: {
16945 		tcp_t	*listener = tcp->tcp_listener;
16946 
16947 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16948 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16949 			/* it's our first timeout */
16950 			tcp->tcp_syn_rcvd_timeout = 1;
16951 			mutex_enter(&listener->tcp_eager_lock);
16952 			listener->tcp_syn_rcvd_timeout++;
16953 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16954 				/*
16955 				 * Make this eager available for drop if we
16956 				 * need to drop one to accomodate a new
16957 				 * incoming SYN request.
16958 				 */
16959 				MAKE_DROPPABLE(listener, tcp);
16960 			}
16961 			if (!listener->tcp_syn_defense &&
16962 			    (listener->tcp_syn_rcvd_timeout >
16963 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16964 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16965 				/* We may be under attack. Put on a defense. */
16966 				listener->tcp_syn_defense = B_TRUE;
16967 				cmn_err(CE_WARN, "High TCP connect timeout "
16968 				    "rate! System (port %d) may be under a "
16969 				    "SYN flood attack!",
16970 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16971 
16972 				listener->tcp_ip_addr_cache = kmem_zalloc(
16973 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16974 				    KM_NOSLEEP);
16975 			}
16976 			mutex_exit(&listener->tcp_eager_lock);
16977 		} else if (listener != NULL) {
16978 			mutex_enter(&listener->tcp_eager_lock);
16979 			tcp->tcp_syn_rcvd_timeout++;
16980 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16981 			    !tcp->tcp_closemp_used) {
16982 				/*
16983 				 * This is our second timeout. Put the tcp in
16984 				 * the list of droppable eagers to allow it to
16985 				 * be dropped, if needed. We don't check
16986 				 * whether tcp_dontdrop is set or not to
16987 				 * protect ourselve from a SYN attack where a
16988 				 * remote host can spoof itself as one of the
16989 				 * good IP source and continue to hold
16990 				 * resources too long.
16991 				 */
16992 				MAKE_DROPPABLE(listener, tcp);
16993 			}
16994 			mutex_exit(&listener->tcp_eager_lock);
16995 		}
16996 	}
16997 		/* FALLTHRU */
16998 	case TCPS_SYN_SENT:
16999 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17000 		second_threshold = tcp->tcp_second_ctimer_threshold;
17001 		break;
17002 	case TCPS_ESTABLISHED:
17003 	case TCPS_FIN_WAIT_1:
17004 	case TCPS_CLOSING:
17005 	case TCPS_CLOSE_WAIT:
17006 	case TCPS_LAST_ACK:
17007 		/* If we have data to rexmit */
17008 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17009 			clock_t	time_to_wait;
17010 
17011 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17012 			if (!tcp->tcp_xmit_head)
17013 				break;
17014 			time_to_wait = lbolt -
17015 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17016 			time_to_wait = tcp->tcp_rto -
17017 			    TICK_TO_MSEC(time_to_wait);
17018 			/*
17019 			 * If the timer fires too early, 1 clock tick earlier,
17020 			 * restart the timer.
17021 			 */
17022 			if (time_to_wait > msec_per_tick) {
17023 				TCP_STAT(tcps, tcp_timer_fire_early);
17024 				TCP_TIMER_RESTART(tcp, time_to_wait);
17025 				return;
17026 			}
17027 			/*
17028 			 * When we probe zero windows, we force the swnd open.
17029 			 * If our peer acks with a closed window swnd will be
17030 			 * set to zero by tcp_rput(). As long as we are
17031 			 * receiving acks tcp_rput will
17032 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17033 			 * first and second interval actions.  NOTE: the timer
17034 			 * interval is allowed to continue its exponential
17035 			 * backoff.
17036 			 */
17037 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17038 				if (tcp->tcp_debug) {
17039 					(void) strlog(TCP_MOD_ID, 0, 1,
17040 					    SL_TRACE, "tcp_timer: zero win");
17041 				}
17042 			} else {
17043 				/*
17044 				 * After retransmission, we need to do
17045 				 * slow start.  Set the ssthresh to one
17046 				 * half of current effective window and
17047 				 * cwnd to one MSS.  Also reset
17048 				 * tcp_cwnd_cnt.
17049 				 *
17050 				 * Note that if tcp_ssthresh is reduced because
17051 				 * of ECN, do not reduce it again unless it is
17052 				 * already one window of data away (tcp_cwr
17053 				 * should then be cleared) or this is a
17054 				 * timeout for a retransmitted segment.
17055 				 */
17056 				uint32_t npkt;
17057 
17058 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17059 					npkt = ((tcp->tcp_timer_backoff ?
17060 					    tcp->tcp_cwnd_ssthresh :
17061 					    tcp->tcp_snxt -
17062 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17063 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17064 					    tcp->tcp_mss;
17065 				}
17066 				tcp->tcp_cwnd = tcp->tcp_mss;
17067 				tcp->tcp_cwnd_cnt = 0;
17068 				if (tcp->tcp_ecn_ok) {
17069 					tcp->tcp_cwr = B_TRUE;
17070 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17071 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17072 				}
17073 			}
17074 			break;
17075 		}
17076 		/*
17077 		 * We have something to send yet we cannot send.  The
17078 		 * reason can be:
17079 		 *
17080 		 * 1. Zero send window: we need to do zero window probe.
17081 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17082 		 * segments.
17083 		 * 3. SWS avoidance: receiver may have shrunk window,
17084 		 * reset our knowledge.
17085 		 *
17086 		 * Note that condition 2 can happen with either 1 or
17087 		 * 3.  But 1 and 3 are exclusive.
17088 		 */
17089 		if (tcp->tcp_unsent != 0) {
17090 			if (tcp->tcp_cwnd == 0) {
17091 				/*
17092 				 * Set tcp_cwnd to 1 MSS so that a
17093 				 * new segment can be sent out.  We
17094 				 * are "clocking out" new data when
17095 				 * the network is really congested.
17096 				 */
17097 				ASSERT(tcp->tcp_ecn_ok);
17098 				tcp->tcp_cwnd = tcp->tcp_mss;
17099 			}
17100 			if (tcp->tcp_swnd == 0) {
17101 				/* Extend window for zero window probe */
17102 				tcp->tcp_swnd++;
17103 				tcp->tcp_zero_win_probe = B_TRUE;
17104 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17105 			} else {
17106 				/*
17107 				 * Handle timeout from sender SWS avoidance.
17108 				 * Reset our knowledge of the max send window
17109 				 * since the receiver might have reduced its
17110 				 * receive buffer.  Avoid setting tcp_max_swnd
17111 				 * to one since that will essentially disable
17112 				 * the SWS checks.
17113 				 *
17114 				 * Note that since we don't have a SWS
17115 				 * state variable, if the timeout is set
17116 				 * for ECN but not for SWS, this
17117 				 * code will also be executed.  This is
17118 				 * fine as tcp_max_swnd is updated
17119 				 * constantly and it will not affect
17120 				 * anything.
17121 				 */
17122 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17123 			}
17124 			tcp_wput_data(tcp, NULL, B_FALSE);
17125 			return;
17126 		}
17127 		/* Is there a FIN that needs to be to re retransmitted? */
17128 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17129 		    !tcp->tcp_fin_acked)
17130 			break;
17131 		/* Nothing to do, return without restarting timer. */
17132 		TCP_STAT(tcps, tcp_timer_fire_miss);
17133 		return;
17134 	case TCPS_FIN_WAIT_2:
17135 		/*
17136 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17137 		 * We waited some time for for peer's FIN, but it hasn't
17138 		 * arrived.  We flush the connection now to avoid
17139 		 * case where the peer has rebooted.
17140 		 */
17141 		if (TCP_IS_DETACHED(tcp)) {
17142 			(void) tcp_clean_death(tcp, 0, 23);
17143 		} else {
17144 			TCP_TIMER_RESTART(tcp,
17145 			    tcps->tcps_fin_wait_2_flush_interval);
17146 		}
17147 		return;
17148 	case TCPS_TIME_WAIT:
17149 		(void) tcp_clean_death(tcp, 0, 24);
17150 		return;
17151 	default:
17152 		if (tcp->tcp_debug) {
17153 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17154 			    "tcp_timer: strange state (%d) %s",
17155 			    tcp->tcp_state, tcp_display(tcp, NULL,
17156 			    DISP_PORT_ONLY));
17157 		}
17158 		return;
17159 	}
17160 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17161 		/*
17162 		 * For zero window probe, we need to send indefinitely,
17163 		 * unless we have not heard from the other side for some
17164 		 * time...
17165 		 */
17166 		if ((tcp->tcp_zero_win_probe == 0) ||
17167 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17168 		    second_threshold)) {
17169 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17170 			/*
17171 			 * If TCP is in SYN_RCVD state, send back a
17172 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17173 			 * should be zero in TCPS_SYN_RCVD state.
17174 			 */
17175 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17176 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17177 				    "in SYN_RCVD",
17178 				    tcp, tcp->tcp_snxt,
17179 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17180 			}
17181 			(void) tcp_clean_death(tcp,
17182 			    tcp->tcp_client_errno ?
17183 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17184 			return;
17185 		} else {
17186 			/*
17187 			 * Set tcp_ms_we_have_waited to second_threshold
17188 			 * so that in next timeout, we will do the above
17189 			 * check (lbolt - tcp_last_recv_time).  This is
17190 			 * also to avoid overflow.
17191 			 *
17192 			 * We don't need to decrement tcp_timer_backoff
17193 			 * to avoid overflow because it will be decremented
17194 			 * later if new timeout value is greater than
17195 			 * tcp_rexmit_interval_max.  In the case when
17196 			 * tcp_rexmit_interval_max is greater than
17197 			 * second_threshold, it means that we will wait
17198 			 * longer than second_threshold to send the next
17199 			 * window probe.
17200 			 */
17201 			tcp->tcp_ms_we_have_waited = second_threshold;
17202 		}
17203 	} else if (ms > first_threshold) {
17204 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17205 		    tcp->tcp_xmit_head != NULL) {
17206 			tcp->tcp_xmit_head =
17207 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17208 		}
17209 		/*
17210 		 * We have been retransmitting for too long...  The RTT
17211 		 * we calculated is probably incorrect.  Reinitialize it.
17212 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17213 		 * tcp_rtt_update so that we won't accidentally cache a
17214 		 * bad value.  But only do this if this is not a zero
17215 		 * window probe.
17216 		 */
17217 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17218 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17219 			    (tcp->tcp_rtt_sa >> 5);
17220 			tcp->tcp_rtt_sa = 0;
17221 			tcp_ip_notify(tcp);
17222 			tcp->tcp_rtt_update = 0;
17223 		}
17224 	}
17225 	tcp->tcp_timer_backoff++;
17226 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17227 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17228 	    tcps->tcps_rexmit_interval_min) {
17229 		/*
17230 		 * This means the original RTO is tcp_rexmit_interval_min.
17231 		 * So we will use tcp_rexmit_interval_min as the RTO value
17232 		 * and do the backoff.
17233 		 */
17234 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17235 	} else {
17236 		ms <<= tcp->tcp_timer_backoff;
17237 	}
17238 	if (ms > tcps->tcps_rexmit_interval_max) {
17239 		ms = tcps->tcps_rexmit_interval_max;
17240 		/*
17241 		 * ms is at max, decrement tcp_timer_backoff to avoid
17242 		 * overflow.
17243 		 */
17244 		tcp->tcp_timer_backoff--;
17245 	}
17246 	tcp->tcp_ms_we_have_waited += ms;
17247 	if (tcp->tcp_zero_win_probe == 0) {
17248 		tcp->tcp_rto = ms;
17249 	}
17250 	TCP_TIMER_RESTART(tcp, ms);
17251 	/*
17252 	 * This is after a timeout and tcp_rto is backed off.  Set
17253 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17254 	 * restart the timer with a correct value.
17255 	 */
17256 	tcp->tcp_set_timer = 1;
17257 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17258 	if (mss > tcp->tcp_mss)
17259 		mss = tcp->tcp_mss;
17260 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17261 		mss = tcp->tcp_swnd;
17262 
17263 	if ((mp = tcp->tcp_xmit_head) != NULL)
17264 		mp->b_prev = (mblk_t *)lbolt;
17265 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17266 	    B_TRUE);
17267 
17268 	/*
17269 	 * When slow start after retransmission begins, start with
17270 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17271 	 * start phase.  tcp_snd_burst controls how many segments
17272 	 * can be sent because of an ack.
17273 	 */
17274 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17275 	tcp->tcp_snd_burst = TCP_CWND_SS;
17276 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17277 	    (tcp->tcp_unsent == 0)) {
17278 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17279 	} else {
17280 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17281 	}
17282 	tcp->tcp_rexmit = B_TRUE;
17283 	tcp->tcp_dupack_cnt = 0;
17284 
17285 	/*
17286 	 * Remove all rexmit SACK blk to start from fresh.
17287 	 */
17288 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17289 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17290 		tcp->tcp_num_notsack_blk = 0;
17291 		tcp->tcp_cnt_notsack_list = 0;
17292 	}
17293 	if (mp == NULL) {
17294 		return;
17295 	}
17296 	/* Attach credentials to retransmitted initial SYNs. */
17297 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17298 		mblk_setcred(mp, tcp->tcp_cred);
17299 		DB_CPID(mp) = tcp->tcp_cpid;
17300 	}
17301 
17302 	tcp->tcp_csuna = tcp->tcp_snxt;
17303 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17304 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17305 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17306 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17307 
17308 }
17309 
17310 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17311 static void
17312 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17313 {
17314 	conn_t	*connp;
17315 
17316 	switch (tcp->tcp_state) {
17317 	case TCPS_BOUND:
17318 	case TCPS_LISTEN:
17319 		break;
17320 	default:
17321 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17322 		return;
17323 	}
17324 
17325 	/*
17326 	 * Need to clean up all the eagers since after the unbind, segments
17327 	 * will no longer be delivered to this listener stream.
17328 	 */
17329 	mutex_enter(&tcp->tcp_eager_lock);
17330 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17331 		tcp_eager_cleanup(tcp, 0);
17332 	}
17333 	mutex_exit(&tcp->tcp_eager_lock);
17334 
17335 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17336 		tcp->tcp_ipha->ipha_src = 0;
17337 	} else {
17338 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17339 	}
17340 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17341 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17342 	tcp_bind_hash_remove(tcp);
17343 	tcp->tcp_state = TCPS_IDLE;
17344 	tcp->tcp_mdt = B_FALSE;
17345 	/* Send M_FLUSH according to TPI */
17346 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17347 	connp = tcp->tcp_connp;
17348 	connp->conn_mdt_ok = B_FALSE;
17349 	ipcl_hash_remove(connp);
17350 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17351 	mp = mi_tpi_ok_ack_alloc(mp);
17352 	putnext(tcp->tcp_rq, mp);
17353 }
17354 
17355 /*
17356  * Don't let port fall into the privileged range.
17357  * Since the extra privileged ports can be arbitrary we also
17358  * ensure that we exclude those from consideration.
17359  * tcp_g_epriv_ports is not sorted thus we loop over it until
17360  * there are no changes.
17361  *
17362  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17363  * but instead the code relies on:
17364  * - the fact that the address of the array and its size never changes
17365  * - the atomic assignment of the elements of the array
17366  *
17367  * Returns 0 if there are no more ports available.
17368  *
17369  * TS note: skip multilevel ports.
17370  */
17371 static in_port_t
17372 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17373 {
17374 	int i;
17375 	boolean_t restart = B_FALSE;
17376 	tcp_stack_t *tcps = tcp->tcp_tcps;
17377 
17378 	if (random && tcp_random_anon_port != 0) {
17379 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17380 		    sizeof (in_port_t));
17381 		/*
17382 		 * Unless changed by a sys admin, the smallest anon port
17383 		 * is 32768 and the largest anon port is 65535.  It is
17384 		 * very likely (50%) for the random port to be smaller
17385 		 * than the smallest anon port.  When that happens,
17386 		 * add port % (anon port range) to the smallest anon
17387 		 * port to get the random port.  It should fall into the
17388 		 * valid anon port range.
17389 		 */
17390 		if (port < tcps->tcps_smallest_anon_port) {
17391 			port = tcps->tcps_smallest_anon_port +
17392 			    port % (tcps->tcps_largest_anon_port -
17393 			    tcps->tcps_smallest_anon_port);
17394 		}
17395 	}
17396 
17397 retry:
17398 	if (port < tcps->tcps_smallest_anon_port)
17399 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17400 
17401 	if (port > tcps->tcps_largest_anon_port) {
17402 		if (restart)
17403 			return (0);
17404 		restart = B_TRUE;
17405 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17406 	}
17407 
17408 	if (port < tcps->tcps_smallest_nonpriv_port)
17409 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17410 
17411 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17412 		if (port == tcps->tcps_g_epriv_ports[i]) {
17413 			port++;
17414 			/*
17415 			 * Make sure whether the port is in the
17416 			 * valid range.
17417 			 */
17418 			goto retry;
17419 		}
17420 	}
17421 	if (is_system_labeled() &&
17422 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17423 	    IPPROTO_TCP, B_TRUE)) != 0) {
17424 		port = i;
17425 		goto retry;
17426 	}
17427 	return (port);
17428 }
17429 
17430 /*
17431  * Return the next anonymous port in the privileged port range for
17432  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17433  * downwards.  This is the same behavior as documented in the userland
17434  * library call rresvport(3N).
17435  *
17436  * TS note: skip multilevel ports.
17437  */
17438 static in_port_t
17439 tcp_get_next_priv_port(const tcp_t *tcp)
17440 {
17441 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17442 	in_port_t nextport;
17443 	boolean_t restart = B_FALSE;
17444 	tcp_stack_t *tcps = tcp->tcp_tcps;
17445 retry:
17446 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17447 	    next_priv_port >= IPPORT_RESERVED) {
17448 		next_priv_port = IPPORT_RESERVED - 1;
17449 		if (restart)
17450 			return (0);
17451 		restart = B_TRUE;
17452 	}
17453 	if (is_system_labeled() &&
17454 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17455 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17456 		next_priv_port = nextport;
17457 		goto retry;
17458 	}
17459 	return (next_priv_port--);
17460 }
17461 
17462 /* The write side r/w procedure. */
17463 
17464 #if CCS_STATS
17465 struct {
17466 	struct {
17467 		int64_t count, bytes;
17468 	} tot, hit;
17469 } wrw_stats;
17470 #endif
17471 
17472 /*
17473  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17474  * messages.
17475  */
17476 /* ARGSUSED */
17477 static void
17478 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17479 {
17480 	conn_t	*connp = (conn_t *)arg;
17481 	tcp_t	*tcp = connp->conn_tcp;
17482 	queue_t	*q = tcp->tcp_wq;
17483 
17484 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17485 	/*
17486 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17487 	 * Once the close starts, streamhead and sockfs will not let any data
17488 	 * packets come down (close ensures that there are no threads using the
17489 	 * queue and no new threads will come down) but since qprocsoff()
17490 	 * hasn't happened yet, a M_FLUSH or some non data message might
17491 	 * get reflected back (in response to our own FLUSHRW) and get
17492 	 * processed after tcp_close() is done. The conn would still be valid
17493 	 * because a ref would have added but we need to check the state
17494 	 * before actually processing the packet.
17495 	 */
17496 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17497 		freemsg(mp);
17498 		return;
17499 	}
17500 
17501 	switch (DB_TYPE(mp)) {
17502 	case M_IOCDATA:
17503 		tcp_wput_iocdata(tcp, mp);
17504 		break;
17505 	case M_FLUSH:
17506 		tcp_wput_flush(tcp, mp);
17507 		break;
17508 	default:
17509 		CALL_IP_WPUT(connp, q, mp);
17510 		break;
17511 	}
17512 }
17513 
17514 /*
17515  * The TCP fast path write put procedure.
17516  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17517  */
17518 /* ARGSUSED */
17519 void
17520 tcp_output(void *arg, mblk_t *mp, void *arg2)
17521 {
17522 	int		len;
17523 	int		hdrlen;
17524 	int		plen;
17525 	mblk_t		*mp1;
17526 	uchar_t		*rptr;
17527 	uint32_t	snxt;
17528 	tcph_t		*tcph;
17529 	struct datab	*db;
17530 	uint32_t	suna;
17531 	uint32_t	mss;
17532 	ipaddr_t	*dst;
17533 	ipaddr_t	*src;
17534 	uint32_t	sum;
17535 	int		usable;
17536 	conn_t		*connp = (conn_t *)arg;
17537 	tcp_t		*tcp = connp->conn_tcp;
17538 	uint32_t	msize;
17539 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17540 
17541 	/*
17542 	 * Try and ASSERT the minimum possible references on the
17543 	 * conn early enough. Since we are executing on write side,
17544 	 * the connection is obviously not detached and that means
17545 	 * there is a ref each for TCP and IP. Since we are behind
17546 	 * the squeue, the minimum references needed are 3. If the
17547 	 * conn is in classifier hash list, there should be an
17548 	 * extra ref for that (we check both the possibilities).
17549 	 */
17550 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17551 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17552 
17553 	ASSERT(DB_TYPE(mp) == M_DATA);
17554 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17555 
17556 	mutex_enter(&tcp->tcp_non_sq_lock);
17557 	tcp->tcp_squeue_bytes -= msize;
17558 	mutex_exit(&tcp->tcp_non_sq_lock);
17559 
17560 	/* Bypass tcp protocol for fused tcp loopback */
17561 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17562 		return;
17563 
17564 	mss = tcp->tcp_mss;
17565 	if (tcp->tcp_xmit_zc_clean)
17566 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17567 
17568 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17569 	len = (int)(mp->b_wptr - mp->b_rptr);
17570 
17571 	/*
17572 	 * Criteria for fast path:
17573 	 *
17574 	 *   1. no unsent data
17575 	 *   2. single mblk in request
17576 	 *   3. connection established
17577 	 *   4. data in mblk
17578 	 *   5. len <= mss
17579 	 *   6. no tcp_valid bits
17580 	 */
17581 	if ((tcp->tcp_unsent != 0) ||
17582 	    (tcp->tcp_cork) ||
17583 	    (mp->b_cont != NULL) ||
17584 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17585 	    (len == 0) ||
17586 	    (len > mss) ||
17587 	    (tcp->tcp_valid_bits != 0)) {
17588 		tcp_wput_data(tcp, mp, B_FALSE);
17589 		return;
17590 	}
17591 
17592 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17593 	ASSERT(tcp->tcp_fin_sent == 0);
17594 
17595 	/* queue new packet onto retransmission queue */
17596 	if (tcp->tcp_xmit_head == NULL) {
17597 		tcp->tcp_xmit_head = mp;
17598 	} else {
17599 		tcp->tcp_xmit_last->b_cont = mp;
17600 	}
17601 	tcp->tcp_xmit_last = mp;
17602 	tcp->tcp_xmit_tail = mp;
17603 
17604 	/* find out how much we can send */
17605 	/* BEGIN CSTYLED */
17606 	/*
17607 	 *    un-acked           usable
17608 	 *  |--------------|-----------------|
17609 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17610 	 */
17611 	/* END CSTYLED */
17612 
17613 	/* start sending from tcp_snxt */
17614 	snxt = tcp->tcp_snxt;
17615 
17616 	/*
17617 	 * Check to see if this connection has been idled for some
17618 	 * time and no ACK is expected.  If it is, we need to slow
17619 	 * start again to get back the connection's "self-clock" as
17620 	 * described in VJ's paper.
17621 	 *
17622 	 * Refer to the comment in tcp_mss_set() for the calculation
17623 	 * of tcp_cwnd after idle.
17624 	 */
17625 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17626 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17627 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17628 	}
17629 
17630 	usable = tcp->tcp_swnd;		/* tcp window size */
17631 	if (usable > tcp->tcp_cwnd)
17632 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17633 	usable -= snxt;		/* subtract stuff already sent */
17634 	suna = tcp->tcp_suna;
17635 	usable += suna;
17636 	/* usable can be < 0 if the congestion window is smaller */
17637 	if (len > usable) {
17638 		/* Can't send complete M_DATA in one shot */
17639 		goto slow;
17640 	}
17641 
17642 	mutex_enter(&tcp->tcp_non_sq_lock);
17643 	if (tcp->tcp_flow_stopped &&
17644 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17645 		tcp_clrqfull(tcp);
17646 	}
17647 	mutex_exit(&tcp->tcp_non_sq_lock);
17648 
17649 	/*
17650 	 * determine if anything to send (Nagle).
17651 	 *
17652 	 *   1. len < tcp_mss (i.e. small)
17653 	 *   2. unacknowledged data present
17654 	 *   3. len < nagle limit
17655 	 *   4. last packet sent < nagle limit (previous packet sent)
17656 	 */
17657 	if ((len < mss) && (snxt != suna) &&
17658 	    (len < (int)tcp->tcp_naglim) &&
17659 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17660 		/*
17661 		 * This was the first unsent packet and normally
17662 		 * mss < xmit_hiwater so there is no need to worry
17663 		 * about flow control. The next packet will go
17664 		 * through the flow control check in tcp_wput_data().
17665 		 */
17666 		/* leftover work from above */
17667 		tcp->tcp_unsent = len;
17668 		tcp->tcp_xmit_tail_unsent = len;
17669 
17670 		return;
17671 	}
17672 
17673 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17674 
17675 	if (snxt == suna) {
17676 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17677 	}
17678 
17679 	/* we have always sent something */
17680 	tcp->tcp_rack_cnt = 0;
17681 
17682 	tcp->tcp_snxt = snxt + len;
17683 	tcp->tcp_rack = tcp->tcp_rnxt;
17684 
17685 	if ((mp1 = dupb(mp)) == 0)
17686 		goto no_memory;
17687 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17688 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17689 
17690 	/* adjust tcp header information */
17691 	tcph = tcp->tcp_tcph;
17692 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17693 
17694 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17695 	sum = (sum >> 16) + (sum & 0xFFFF);
17696 	U16_TO_ABE16(sum, tcph->th_sum);
17697 
17698 	U32_TO_ABE32(snxt, tcph->th_seq);
17699 
17700 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17701 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17702 	BUMP_LOCAL(tcp->tcp_obsegs);
17703 
17704 	/* Update the latest receive window size in TCP header. */
17705 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17706 	    tcph->th_win);
17707 
17708 	tcp->tcp_last_sent_len = (ushort_t)len;
17709 
17710 	plen = len + tcp->tcp_hdr_len;
17711 
17712 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17713 		tcp->tcp_ipha->ipha_length = htons(plen);
17714 	} else {
17715 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17716 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17717 	}
17718 
17719 	/* see if we need to allocate a mblk for the headers */
17720 	hdrlen = tcp->tcp_hdr_len;
17721 	rptr = mp1->b_rptr - hdrlen;
17722 	db = mp1->b_datap;
17723 	if ((db->db_ref != 2) || rptr < db->db_base ||
17724 	    (!OK_32PTR(rptr))) {
17725 		/* NOTE: we assume allocb returns an OK_32PTR */
17726 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17727 		    tcps->tcps_wroff_xtra, BPRI_MED);
17728 		if (!mp) {
17729 			freemsg(mp1);
17730 			goto no_memory;
17731 		}
17732 		mp->b_cont = mp1;
17733 		mp1 = mp;
17734 		/* Leave room for Link Level header */
17735 		/* hdrlen = tcp->tcp_hdr_len; */
17736 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17737 		mp1->b_wptr = &rptr[hdrlen];
17738 	}
17739 	mp1->b_rptr = rptr;
17740 
17741 	/* Fill in the timestamp option. */
17742 	if (tcp->tcp_snd_ts_ok) {
17743 		U32_TO_BE32((uint32_t)lbolt,
17744 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17745 		U32_TO_BE32(tcp->tcp_ts_recent,
17746 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17747 	} else {
17748 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17749 	}
17750 
17751 	/* copy header into outgoing packet */
17752 	dst = (ipaddr_t *)rptr;
17753 	src = (ipaddr_t *)tcp->tcp_iphc;
17754 	dst[0] = src[0];
17755 	dst[1] = src[1];
17756 	dst[2] = src[2];
17757 	dst[3] = src[3];
17758 	dst[4] = src[4];
17759 	dst[5] = src[5];
17760 	dst[6] = src[6];
17761 	dst[7] = src[7];
17762 	dst[8] = src[8];
17763 	dst[9] = src[9];
17764 	if (hdrlen -= 40) {
17765 		hdrlen >>= 2;
17766 		dst += 10;
17767 		src += 10;
17768 		do {
17769 			*dst++ = *src++;
17770 		} while (--hdrlen);
17771 	}
17772 
17773 	/*
17774 	 * Set the ECN info in the TCP header.  Note that this
17775 	 * is not the template header.
17776 	 */
17777 	if (tcp->tcp_ecn_ok) {
17778 		SET_ECT(tcp, rptr);
17779 
17780 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17781 		if (tcp->tcp_ecn_echo_on)
17782 			tcph->th_flags[0] |= TH_ECE;
17783 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17784 			tcph->th_flags[0] |= TH_CWR;
17785 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17786 		}
17787 	}
17788 
17789 	if (tcp->tcp_ip_forward_progress) {
17790 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17791 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17792 		tcp->tcp_ip_forward_progress = B_FALSE;
17793 	}
17794 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17795 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17796 	return;
17797 
17798 	/*
17799 	 * If we ran out of memory, we pretend to have sent the packet
17800 	 * and that it was lost on the wire.
17801 	 */
17802 no_memory:
17803 	return;
17804 
17805 slow:
17806 	/* leftover work from above */
17807 	tcp->tcp_unsent = len;
17808 	tcp->tcp_xmit_tail_unsent = len;
17809 	tcp_wput_data(tcp, NULL, B_FALSE);
17810 }
17811 
17812 /*
17813  * The function called through squeue to get behind eager's perimeter to
17814  * finish the accept processing.
17815  */
17816 /* ARGSUSED */
17817 void
17818 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17819 {
17820 	conn_t			*connp = (conn_t *)arg;
17821 	tcp_t			*tcp = connp->conn_tcp;
17822 	queue_t			*q = tcp->tcp_rq;
17823 	mblk_t			*mp1;
17824 	mblk_t			*stropt_mp = mp;
17825 	struct  stroptions	*stropt;
17826 	uint_t			thwin;
17827 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17828 
17829 	/*
17830 	 * Drop the eager's ref on the listener, that was placed when
17831 	 * this eager began life in tcp_conn_request.
17832 	 */
17833 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17834 
17835 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17836 		/*
17837 		 * Someone blewoff the eager before we could finish
17838 		 * the accept.
17839 		 *
17840 		 * The only reason eager exists it because we put in
17841 		 * a ref on it when conn ind went up. We need to send
17842 		 * a disconnect indication up while the last reference
17843 		 * on the eager will be dropped by the squeue when we
17844 		 * return.
17845 		 */
17846 		ASSERT(tcp->tcp_listener == NULL);
17847 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17848 			struct	T_discon_ind	*tdi;
17849 
17850 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17851 			/*
17852 			 * Let us reuse the incoming mblk to avoid memory
17853 			 * allocation failure problems. We know that the
17854 			 * size of the incoming mblk i.e. stroptions is greater
17855 			 * than sizeof T_discon_ind. So the reallocb below
17856 			 * can't fail.
17857 			 */
17858 			freemsg(mp->b_cont);
17859 			mp->b_cont = NULL;
17860 			ASSERT(DB_REF(mp) == 1);
17861 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17862 			    B_FALSE);
17863 			ASSERT(mp != NULL);
17864 			DB_TYPE(mp) = M_PROTO;
17865 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17866 			tdi = (struct T_discon_ind *)mp->b_rptr;
17867 			if (tcp->tcp_issocket) {
17868 				tdi->DISCON_reason = ECONNREFUSED;
17869 				tdi->SEQ_number = 0;
17870 			} else {
17871 				tdi->DISCON_reason = ENOPROTOOPT;
17872 				tdi->SEQ_number =
17873 				    tcp->tcp_conn_req_seqnum;
17874 			}
17875 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17876 			putnext(q, mp);
17877 		} else {
17878 			freemsg(mp);
17879 		}
17880 		if (tcp->tcp_hard_binding) {
17881 			tcp->tcp_hard_binding = B_FALSE;
17882 			tcp->tcp_hard_bound = B_TRUE;
17883 		}
17884 		tcp->tcp_detached = B_FALSE;
17885 		return;
17886 	}
17887 
17888 	mp1 = stropt_mp->b_cont;
17889 	stropt_mp->b_cont = NULL;
17890 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17891 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17892 
17893 	while (mp1 != NULL) {
17894 		mp = mp1;
17895 		mp1 = mp1->b_cont;
17896 		mp->b_cont = NULL;
17897 		tcp->tcp_drop_opt_ack_cnt++;
17898 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17899 	}
17900 	mp = NULL;
17901 
17902 	/*
17903 	 * For a loopback connection with tcp_direct_sockfs on, note that
17904 	 * we don't have to protect tcp_rcv_list yet because synchronous
17905 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17906 	 * possibly race with us.
17907 	 */
17908 
17909 	/*
17910 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17911 	 * properly.  This is the first time we know of the acceptor'
17912 	 * queue.  So we do it here.
17913 	 */
17914 	if (tcp->tcp_rcv_list == NULL) {
17915 		/*
17916 		 * Recv queue is empty, tcp_rwnd should not have changed.
17917 		 * That means it should be equal to the listener's tcp_rwnd.
17918 		 */
17919 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17920 	} else {
17921 #ifdef DEBUG
17922 		uint_t cnt = 0;
17923 
17924 		mp1 = tcp->tcp_rcv_list;
17925 		while ((mp = mp1) != NULL) {
17926 			mp1 = mp->b_next;
17927 			cnt += msgdsize(mp);
17928 		}
17929 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17930 #endif
17931 		/* There is some data, add them back to get the max. */
17932 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17933 	}
17934 
17935 	stropt->so_flags = SO_HIWAT;
17936 	stropt->so_hiwat = MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
17937 
17938 	stropt->so_flags |= SO_MAXBLK;
17939 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17940 
17941 	/*
17942 	 * This is the first time we run on the correct
17943 	 * queue after tcp_accept. So fix all the q parameters
17944 	 * here.
17945 	 */
17946 	/* Allocate room for SACK options if needed. */
17947 	stropt->so_flags |= SO_WROFF;
17948 	if (tcp->tcp_fused) {
17949 		ASSERT(tcp->tcp_loopback);
17950 		ASSERT(tcp->tcp_loopback_peer != NULL);
17951 		/*
17952 		 * For fused tcp loopback, set the stream head's write
17953 		 * offset value to zero since we won't be needing any room
17954 		 * for TCP/IP headers.  This would also improve performance
17955 		 * since it would reduce the amount of work done by kmem.
17956 		 * Non-fused tcp loopback case is handled separately below.
17957 		 */
17958 		stropt->so_wroff = 0;
17959 		/*
17960 		 * Record the stream head's high water mark for this endpoint;
17961 		 * this is used for flow-control purposes in tcp_fuse_output().
17962 		 */
17963 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17964 		/*
17965 		 * Update the peer's transmit parameters according to
17966 		 * our recently calculated high water mark value.
17967 		 */
17968 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17969 	} else if (tcp->tcp_snd_sack_ok) {
17970 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17971 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17972 	} else {
17973 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17974 		    tcps->tcps_wroff_xtra);
17975 	}
17976 
17977 	/*
17978 	 * If this is endpoint is handling SSL, then reserve extra
17979 	 * offset and space at the end.
17980 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17981 	 * overriding the previous setting. The extra cost of signing and
17982 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17983 	 * instead of a single contiguous one by the stream head
17984 	 * largely outweighs the statistical reduction of ACKs, when
17985 	 * applicable. The peer will also save on decyption and verification
17986 	 * costs.
17987 	 */
17988 	if (tcp->tcp_kssl_ctx != NULL) {
17989 		stropt->so_wroff += SSL3_WROFFSET;
17990 
17991 		stropt->so_flags |= SO_TAIL;
17992 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17993 
17994 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17995 	}
17996 
17997 	/* Send the options up */
17998 	putnext(q, stropt_mp);
17999 
18000 	/*
18001 	 * Pass up any data and/or a fin that has been received.
18002 	 *
18003 	 * Adjust receive window in case it had decreased
18004 	 * (because there is data <=> tcp_rcv_list != NULL)
18005 	 * while the connection was detached. Note that
18006 	 * in case the eager was flow-controlled, w/o this
18007 	 * code, the rwnd may never open up again!
18008 	 */
18009 	if (tcp->tcp_rcv_list != NULL) {
18010 		/* We drain directly in case of fused tcp loopback */
18011 		if (!tcp->tcp_fused && canputnext(q)) {
18012 			tcp->tcp_rwnd = q->q_hiwat;
18013 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18014 			    << tcp->tcp_rcv_ws;
18015 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18016 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18017 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18018 				tcp_xmit_ctl(NULL,
18019 				    tcp, (tcp->tcp_swnd == 0) ?
18020 				    tcp->tcp_suna : tcp->tcp_snxt,
18021 				    tcp->tcp_rnxt, TH_ACK);
18022 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18023 			}
18024 
18025 		}
18026 		(void) tcp_rcv_drain(q, tcp);
18027 
18028 		/*
18029 		 * For fused tcp loopback, back-enable peer endpoint
18030 		 * if it's currently flow-controlled.
18031 		 */
18032 		if (tcp->tcp_fused) {
18033 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18034 
18035 			ASSERT(peer_tcp != NULL);
18036 			ASSERT(peer_tcp->tcp_fused);
18037 			/*
18038 			 * In order to change the peer's tcp_flow_stopped,
18039 			 * we need to take locks for both end points. The
18040 			 * highest address is taken first.
18041 			 */
18042 			if (peer_tcp > tcp) {
18043 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18044 				mutex_enter(&tcp->tcp_non_sq_lock);
18045 			} else {
18046 				mutex_enter(&tcp->tcp_non_sq_lock);
18047 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18048 			}
18049 			if (peer_tcp->tcp_flow_stopped) {
18050 				tcp_clrqfull(peer_tcp);
18051 				TCP_STAT(tcps, tcp_fusion_backenabled);
18052 			}
18053 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18054 			mutex_exit(&tcp->tcp_non_sq_lock);
18055 		}
18056 	}
18057 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18058 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18059 		mp = mi_tpi_ordrel_ind();
18060 		if (mp) {
18061 			tcp->tcp_ordrel_done = B_TRUE;
18062 			putnext(q, mp);
18063 			if (tcp->tcp_deferred_clean_death) {
18064 				/*
18065 				 * tcp_clean_death was deferred
18066 				 * for T_ORDREL_IND - do it now
18067 				 */
18068 				(void) tcp_clean_death(tcp,
18069 				    tcp->tcp_client_errno, 21);
18070 				tcp->tcp_deferred_clean_death = B_FALSE;
18071 			}
18072 		} else {
18073 			/*
18074 			 * Run the orderly release in the
18075 			 * service routine.
18076 			 */
18077 			qenable(q);
18078 		}
18079 	}
18080 	if (tcp->tcp_hard_binding) {
18081 		tcp->tcp_hard_binding = B_FALSE;
18082 		tcp->tcp_hard_bound = B_TRUE;
18083 	}
18084 
18085 	tcp->tcp_detached = B_FALSE;
18086 
18087 	/* We can enable synchronous streams now */
18088 	if (tcp->tcp_fused) {
18089 		tcp_fuse_syncstr_enable_pair(tcp);
18090 	}
18091 
18092 	if (tcp->tcp_ka_enabled) {
18093 		tcp->tcp_ka_last_intrvl = 0;
18094 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18095 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18096 	}
18097 
18098 	/*
18099 	 * At this point, eager is fully established and will
18100 	 * have the following references -
18101 	 *
18102 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18103 	 * 1 reference for the squeue which will be dropped by the squeue as
18104 	 *	soon as this function returns.
18105 	 * There will be 1 additonal reference for being in classifier
18106 	 *	hash list provided something bad hasn't happened.
18107 	 */
18108 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18109 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18110 }
18111 
18112 /*
18113  * The function called through squeue to get behind listener's perimeter to
18114  * send a deffered conn_ind.
18115  */
18116 /* ARGSUSED */
18117 void
18118 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18119 {
18120 	conn_t	*connp = (conn_t *)arg;
18121 	tcp_t *listener = connp->conn_tcp;
18122 
18123 	if (listener->tcp_state == TCPS_CLOSED ||
18124 	    TCP_IS_DETACHED(listener)) {
18125 		/*
18126 		 * If listener has closed, it would have caused a
18127 		 * a cleanup/blowoff to happen for the eager.
18128 		 */
18129 		tcp_t *tcp;
18130 		struct T_conn_ind	*conn_ind;
18131 
18132 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18133 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18134 		    conn_ind->OPT_length);
18135 		/*
18136 		 * We need to drop the ref on eager that was put
18137 		 * tcp_rput_data() before trying to send the conn_ind
18138 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18139 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18140 		 * listener is closed so we drop the ref.
18141 		 */
18142 		CONN_DEC_REF(tcp->tcp_connp);
18143 		freemsg(mp);
18144 		return;
18145 	}
18146 	putnext(listener->tcp_rq, mp);
18147 }
18148 
18149 
18150 /*
18151  * This is the STREAMS entry point for T_CONN_RES coming down on
18152  * Acceptor STREAM when  sockfs listener does accept processing.
18153  * Read the block comment on top of tcp_conn_request().
18154  */
18155 void
18156 tcp_wput_accept(queue_t *q, mblk_t *mp)
18157 {
18158 	queue_t *rq = RD(q);
18159 	struct T_conn_res *conn_res;
18160 	tcp_t *eager;
18161 	tcp_t *listener;
18162 	struct T_ok_ack *ok;
18163 	t_scalar_t PRIM_type;
18164 	mblk_t *opt_mp;
18165 	conn_t *econnp;
18166 
18167 	ASSERT(DB_TYPE(mp) == M_PROTO);
18168 
18169 	conn_res = (struct T_conn_res *)mp->b_rptr;
18170 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18171 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18172 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18173 		if (mp != NULL)
18174 			putnext(rq, mp);
18175 		return;
18176 	}
18177 	switch (conn_res->PRIM_type) {
18178 	case O_T_CONN_RES:
18179 	case T_CONN_RES:
18180 		/*
18181 		 * We pass up an err ack if allocb fails. This will
18182 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18183 		 * tcp_eager_blowoff to be called. sockfs will then call
18184 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18185 		 * we need to do the allocb up here because we have to
18186 		 * make sure rq->q_qinfo->qi_qclose still points to the
18187 		 * correct function (tcpclose_accept) in case allocb
18188 		 * fails.
18189 		 */
18190 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18191 		if (opt_mp == NULL) {
18192 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18193 			if (mp != NULL)
18194 				putnext(rq, mp);
18195 			return;
18196 		}
18197 
18198 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18199 		    &eager, conn_res->OPT_length);
18200 		PRIM_type = conn_res->PRIM_type;
18201 		mp->b_datap->db_type = M_PCPROTO;
18202 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18203 		ok = (struct T_ok_ack *)mp->b_rptr;
18204 		ok->PRIM_type = T_OK_ACK;
18205 		ok->CORRECT_prim = PRIM_type;
18206 		econnp = eager->tcp_connp;
18207 		econnp->conn_dev = (dev_t)q->q_ptr;
18208 		eager->tcp_rq = rq;
18209 		eager->tcp_wq = q;
18210 		rq->q_ptr = econnp;
18211 		rq->q_qinfo = &tcp_rinit;
18212 		q->q_ptr = econnp;
18213 		q->q_qinfo = &tcp_winit;
18214 		listener = eager->tcp_listener;
18215 		eager->tcp_issocket = B_TRUE;
18216 
18217 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18218 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18219 		ASSERT(econnp->conn_netstack ==
18220 		    listener->tcp_connp->conn_netstack);
18221 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18222 
18223 		/* Put the ref for IP */
18224 		CONN_INC_REF(econnp);
18225 
18226 		/*
18227 		 * We should have minimum of 3 references on the conn
18228 		 * at this point. One each for TCP and IP and one for
18229 		 * the T_conn_ind that was sent up when the 3-way handshake
18230 		 * completed. In the normal case we would also have another
18231 		 * reference (making a total of 4) for the conn being in the
18232 		 * classifier hash list. However the eager could have received
18233 		 * an RST subsequently and tcp_closei_local could have removed
18234 		 * the eager from the classifier hash list, hence we can't
18235 		 * assert that reference.
18236 		 */
18237 		ASSERT(econnp->conn_ref >= 3);
18238 
18239 		/*
18240 		 * Send the new local address also up to sockfs. There
18241 		 * should already be enough space in the mp that came
18242 		 * down from soaccept().
18243 		 */
18244 		if (eager->tcp_family == AF_INET) {
18245 			sin_t *sin;
18246 
18247 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18248 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18249 			sin = (sin_t *)mp->b_wptr;
18250 			mp->b_wptr += sizeof (sin_t);
18251 			sin->sin_family = AF_INET;
18252 			sin->sin_port = eager->tcp_lport;
18253 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18254 		} else {
18255 			sin6_t *sin6;
18256 
18257 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18258 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18259 			sin6 = (sin6_t *)mp->b_wptr;
18260 			mp->b_wptr += sizeof (sin6_t);
18261 			sin6->sin6_family = AF_INET6;
18262 			sin6->sin6_port = eager->tcp_lport;
18263 			if (eager->tcp_ipversion == IPV4_VERSION) {
18264 				sin6->sin6_flowinfo = 0;
18265 				IN6_IPADDR_TO_V4MAPPED(
18266 					eager->tcp_ipha->ipha_src,
18267 					    &sin6->sin6_addr);
18268 			} else {
18269 				ASSERT(eager->tcp_ip6h != NULL);
18270 				sin6->sin6_flowinfo =
18271 				    eager->tcp_ip6h->ip6_vcf &
18272 				    ~IPV6_VERS_AND_FLOW_MASK;
18273 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18274 			}
18275 			sin6->sin6_scope_id = 0;
18276 			sin6->__sin6_src_id = 0;
18277 		}
18278 
18279 		putnext(rq, mp);
18280 
18281 		opt_mp->b_datap->db_type = M_SETOPTS;
18282 		opt_mp->b_wptr += sizeof (struct stroptions);
18283 
18284 		/*
18285 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18286 		 * from listener to acceptor. The message is chained on the
18287 		 * bind_mp which tcp_rput_other will send down to IP.
18288 		 */
18289 		if (listener->tcp_bound_if != 0) {
18290 			/* allocate optmgmt req */
18291 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18292 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18293 			    sizeof (int));
18294 			if (mp != NULL)
18295 				linkb(opt_mp, mp);
18296 		}
18297 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18298 			uint_t on = 1;
18299 
18300 			/* allocate optmgmt req */
18301 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18302 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18303 			if (mp != NULL)
18304 				linkb(opt_mp, mp);
18305 		}
18306 
18307 
18308 		mutex_enter(&listener->tcp_eager_lock);
18309 
18310 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18311 
18312 			tcp_t *tail;
18313 			tcp_t *tcp;
18314 			mblk_t *mp1;
18315 
18316 			tcp = listener->tcp_eager_prev_q0;
18317 			/*
18318 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18319 			 * deferred T_conn_ind queue. We need to get to the head
18320 			 * of the queue in order to send up T_conn_ind the same
18321 			 * order as how the 3WHS is completed.
18322 			 */
18323 			while (tcp != listener) {
18324 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18325 				    !tcp->tcp_kssl_pending)
18326 					break;
18327 				else
18328 					tcp = tcp->tcp_eager_prev_q0;
18329 			}
18330 			/* None of the pending eagers can be sent up now */
18331 			if (tcp == listener)
18332 				goto no_more_eagers;
18333 
18334 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18335 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18336 			/* Move from q0 to q */
18337 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18338 			listener->tcp_conn_req_cnt_q0--;
18339 			listener->tcp_conn_req_cnt_q++;
18340 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18341 			    tcp->tcp_eager_prev_q0;
18342 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18343 			    tcp->tcp_eager_next_q0;
18344 			tcp->tcp_eager_prev_q0 = NULL;
18345 			tcp->tcp_eager_next_q0 = NULL;
18346 			tcp->tcp_conn_def_q0 = B_FALSE;
18347 
18348 			/* Make sure the tcp isn't in the list of droppables */
18349 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18350 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18351 
18352 			/*
18353 			 * Insert at end of the queue because sockfs sends
18354 			 * down T_CONN_RES in chronological order. Leaving
18355 			 * the older conn indications at front of the queue
18356 			 * helps reducing search time.
18357 			 */
18358 			tail = listener->tcp_eager_last_q;
18359 			if (tail != NULL) {
18360 				tail->tcp_eager_next_q = tcp;
18361 			} else {
18362 				listener->tcp_eager_next_q = tcp;
18363 			}
18364 			listener->tcp_eager_last_q = tcp;
18365 			tcp->tcp_eager_next_q = NULL;
18366 
18367 			/* Need to get inside the listener perimeter */
18368 			CONN_INC_REF(listener->tcp_connp);
18369 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18370 			    tcp_send_pending, listener->tcp_connp,
18371 			    SQTAG_TCP_SEND_PENDING);
18372 		}
18373 no_more_eagers:
18374 		tcp_eager_unlink(eager);
18375 		mutex_exit(&listener->tcp_eager_lock);
18376 
18377 		/*
18378 		 * At this point, the eager is detached from the listener
18379 		 * but we still have an extra refs on eager (apart from the
18380 		 * usual tcp references). The ref was placed in tcp_rput_data
18381 		 * before sending the conn_ind in tcp_send_conn_ind.
18382 		 * The ref will be dropped in tcp_accept_finish().
18383 		 */
18384 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18385 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18386 		return;
18387 	default:
18388 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18389 		if (mp != NULL)
18390 			putnext(rq, mp);
18391 		return;
18392 	}
18393 }
18394 
18395 void
18396 tcp_wput(queue_t *q, mblk_t *mp)
18397 {
18398 	conn_t	*connp = Q_TO_CONN(q);
18399 	tcp_t	*tcp;
18400 	void (*output_proc)();
18401 	t_scalar_t type;
18402 	uchar_t *rptr;
18403 	struct iocblk	*iocp;
18404 	uint32_t	msize;
18405 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18406 
18407 	ASSERT(connp->conn_ref >= 2);
18408 
18409 	switch (DB_TYPE(mp)) {
18410 	case M_DATA:
18411 		tcp = connp->conn_tcp;
18412 		ASSERT(tcp != NULL);
18413 
18414 		msize = msgdsize(mp);
18415 
18416 		mutex_enter(&tcp->tcp_non_sq_lock);
18417 		tcp->tcp_squeue_bytes += msize;
18418 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18419 			tcp_setqfull(tcp);
18420 		}
18421 		mutex_exit(&tcp->tcp_non_sq_lock);
18422 
18423 		CONN_INC_REF(connp);
18424 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18425 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18426 		return;
18427 	case M_PROTO:
18428 	case M_PCPROTO:
18429 		/*
18430 		 * if it is a snmp message, don't get behind the squeue
18431 		 */
18432 		tcp = connp->conn_tcp;
18433 		rptr = mp->b_rptr;
18434 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18435 			type = ((union T_primitives *)rptr)->type;
18436 		} else {
18437 			if (tcp->tcp_debug) {
18438 				(void) strlog(TCP_MOD_ID, 0, 1,
18439 				    SL_ERROR|SL_TRACE,
18440 				    "tcp_wput_proto, dropping one...");
18441 			}
18442 			freemsg(mp);
18443 			return;
18444 		}
18445 		if (type == T_SVR4_OPTMGMT_REQ) {
18446 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18447 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18448 			    cr)) {
18449 				/*
18450 				 * This was a SNMP request
18451 				 */
18452 				return;
18453 			} else {
18454 				output_proc = tcp_wput_proto;
18455 			}
18456 		} else {
18457 			output_proc = tcp_wput_proto;
18458 		}
18459 		break;
18460 	case M_IOCTL:
18461 		/*
18462 		 * Most ioctls can be processed right away without going via
18463 		 * squeues - process them right here. Those that do require
18464 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18465 		 * are processed by tcp_wput_ioctl().
18466 		 */
18467 		iocp = (struct iocblk *)mp->b_rptr;
18468 		tcp = connp->conn_tcp;
18469 
18470 		switch (iocp->ioc_cmd) {
18471 		case TCP_IOC_ABORT_CONN:
18472 			tcp_ioctl_abort_conn(q, mp);
18473 			return;
18474 		case TI_GETPEERNAME:
18475 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18476 				iocp->ioc_error = ENOTCONN;
18477 				iocp->ioc_count = 0;
18478 				mp->b_datap->db_type = M_IOCACK;
18479 				qreply(q, mp);
18480 				return;
18481 			}
18482 			/* FALLTHRU */
18483 		case TI_GETMYNAME:
18484 			mi_copyin(q, mp, NULL,
18485 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18486 			return;
18487 		case ND_SET:
18488 			/* nd_getset does the necessary checks */
18489 		case ND_GET:
18490 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18491 				CALL_IP_WPUT(connp, q, mp);
18492 				return;
18493 			}
18494 			qreply(q, mp);
18495 			return;
18496 		case TCP_IOC_DEFAULT_Q:
18497 			/*
18498 			 * Wants to be the default wq. Check the credentials
18499 			 * first, the rest is executed via squeue.
18500 			 */
18501 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18502 				iocp->ioc_error = EPERM;
18503 				iocp->ioc_count = 0;
18504 				mp->b_datap->db_type = M_IOCACK;
18505 				qreply(q, mp);
18506 				return;
18507 			}
18508 			output_proc = tcp_wput_ioctl;
18509 			break;
18510 		default:
18511 			output_proc = tcp_wput_ioctl;
18512 			break;
18513 		}
18514 		break;
18515 	default:
18516 		output_proc = tcp_wput_nondata;
18517 		break;
18518 	}
18519 
18520 	CONN_INC_REF(connp);
18521 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18522 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18523 }
18524 
18525 /*
18526  * Initial STREAMS write side put() procedure for sockets. It tries to
18527  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18528  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18529  * are handled by tcp_wput() as usual.
18530  *
18531  * All further messages will also be handled by tcp_wput() because we cannot
18532  * be sure that the above short cut is safe later.
18533  */
18534 static void
18535 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18536 {
18537 	conn_t			*connp = Q_TO_CONN(wq);
18538 	tcp_t			*tcp = connp->conn_tcp;
18539 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18540 
18541 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18542 	wq->q_qinfo = &tcp_winit;
18543 
18544 	ASSERT(IPCL_IS_TCP(connp));
18545 	ASSERT(TCP_IS_SOCKET(tcp));
18546 
18547 	if (DB_TYPE(mp) == M_PCPROTO &&
18548 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18549 	    car->PRIM_type == T_CAPABILITY_REQ) {
18550 		tcp_capability_req(tcp, mp);
18551 		return;
18552 	}
18553 
18554 	tcp_wput(wq, mp);
18555 }
18556 
18557 static boolean_t
18558 tcp_zcopy_check(tcp_t *tcp)
18559 {
18560 	conn_t	*connp = tcp->tcp_connp;
18561 	ire_t	*ire;
18562 	boolean_t	zc_enabled = B_FALSE;
18563 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18564 
18565 	if (do_tcpzcopy == 2)
18566 		zc_enabled = B_TRUE;
18567 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18568 	    IPCL_IS_CONNECTED(connp) &&
18569 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18570 	    connp->conn_dontroute == 0 &&
18571 	    !connp->conn_nexthop_set &&
18572 	    connp->conn_xmit_if_ill == NULL &&
18573 	    connp->conn_nofailover_ill == NULL &&
18574 	    do_tcpzcopy == 1) {
18575 		/*
18576 		 * the checks above  closely resemble the fast path checks
18577 		 * in tcp_send_data().
18578 		 */
18579 		mutex_enter(&connp->conn_lock);
18580 		ire = connp->conn_ire_cache;
18581 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18582 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18583 			IRE_REFHOLD(ire);
18584 			if (ire->ire_stq != NULL) {
18585 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18586 
18587 				zc_enabled = ill && (ill->ill_capabilities &
18588 				    ILL_CAPAB_ZEROCOPY) &&
18589 				    (ill->ill_zerocopy_capab->
18590 				    ill_zerocopy_flags != 0);
18591 			}
18592 			IRE_REFRELE(ire);
18593 		}
18594 		mutex_exit(&connp->conn_lock);
18595 	}
18596 	tcp->tcp_snd_zcopy_on = zc_enabled;
18597 	if (!TCP_IS_DETACHED(tcp)) {
18598 		if (zc_enabled) {
18599 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18600 			TCP_STAT(tcps, tcp_zcopy_on);
18601 		} else {
18602 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18603 			TCP_STAT(tcps, tcp_zcopy_off);
18604 		}
18605 	}
18606 	return (zc_enabled);
18607 }
18608 
18609 static mblk_t *
18610 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18611 {
18612 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18613 
18614 	if (do_tcpzcopy == 2)
18615 		return (bp);
18616 	else if (tcp->tcp_snd_zcopy_on) {
18617 		tcp->tcp_snd_zcopy_on = B_FALSE;
18618 		if (!TCP_IS_DETACHED(tcp)) {
18619 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18620 			TCP_STAT(tcps, tcp_zcopy_disable);
18621 		}
18622 	}
18623 	return (tcp_zcopy_backoff(tcp, bp, 0));
18624 }
18625 
18626 /*
18627  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18628  * the original desballoca'ed segmapped mblk.
18629  */
18630 static mblk_t *
18631 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18632 {
18633 	mblk_t *head, *tail, *nbp;
18634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18635 
18636 	if (IS_VMLOANED_MBLK(bp)) {
18637 		TCP_STAT(tcps, tcp_zcopy_backoff);
18638 		if ((head = copyb(bp)) == NULL) {
18639 			/* fail to backoff; leave it for the next backoff */
18640 			tcp->tcp_xmit_zc_clean = B_FALSE;
18641 			return (bp);
18642 		}
18643 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18644 			if (fix_xmitlist)
18645 				tcp_zcopy_notify(tcp);
18646 			else
18647 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18648 		}
18649 		nbp = bp->b_cont;
18650 		if (fix_xmitlist) {
18651 			head->b_prev = bp->b_prev;
18652 			head->b_next = bp->b_next;
18653 			if (tcp->tcp_xmit_tail == bp)
18654 				tcp->tcp_xmit_tail = head;
18655 		}
18656 		bp->b_next = NULL;
18657 		bp->b_prev = NULL;
18658 		freeb(bp);
18659 	} else {
18660 		head = bp;
18661 		nbp = bp->b_cont;
18662 	}
18663 	tail = head;
18664 	while (nbp) {
18665 		if (IS_VMLOANED_MBLK(nbp)) {
18666 			TCP_STAT(tcps, tcp_zcopy_backoff);
18667 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18668 				tcp->tcp_xmit_zc_clean = B_FALSE;
18669 				tail->b_cont = nbp;
18670 				return (head);
18671 			}
18672 			tail = tail->b_cont;
18673 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18674 				if (fix_xmitlist)
18675 					tcp_zcopy_notify(tcp);
18676 				else
18677 					tail->b_datap->db_struioflag |=
18678 					    STRUIO_ZCNOTIFY;
18679 			}
18680 			bp = nbp;
18681 			nbp = nbp->b_cont;
18682 			if (fix_xmitlist) {
18683 				tail->b_prev = bp->b_prev;
18684 				tail->b_next = bp->b_next;
18685 				if (tcp->tcp_xmit_tail == bp)
18686 					tcp->tcp_xmit_tail = tail;
18687 			}
18688 			bp->b_next = NULL;
18689 			bp->b_prev = NULL;
18690 			freeb(bp);
18691 		} else {
18692 			tail->b_cont = nbp;
18693 			tail = nbp;
18694 			nbp = nbp->b_cont;
18695 		}
18696 	}
18697 	if (fix_xmitlist) {
18698 		tcp->tcp_xmit_last = tail;
18699 		tcp->tcp_xmit_zc_clean = B_TRUE;
18700 	}
18701 	return (head);
18702 }
18703 
18704 static void
18705 tcp_zcopy_notify(tcp_t *tcp)
18706 {
18707 	struct stdata	*stp;
18708 
18709 	if (tcp->tcp_detached)
18710 		return;
18711 	stp = STREAM(tcp->tcp_rq);
18712 	mutex_enter(&stp->sd_lock);
18713 	stp->sd_flag |= STZCNOTIFY;
18714 	cv_broadcast(&stp->sd_zcopy_wait);
18715 	mutex_exit(&stp->sd_lock);
18716 }
18717 
18718 static boolean_t
18719 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18720 {
18721 	ire_t	*ire;
18722 	conn_t	*connp = tcp->tcp_connp;
18723 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18724 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18725 
18726 	mutex_enter(&connp->conn_lock);
18727 	ire = connp->conn_ire_cache;
18728 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18729 
18730 	if ((ire != NULL) &&
18731 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18732 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18733 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18734 		IRE_REFHOLD(ire);
18735 		mutex_exit(&connp->conn_lock);
18736 	} else {
18737 		boolean_t cached = B_FALSE;
18738 		ts_label_t *tsl;
18739 
18740 		/* force a recheck later on */
18741 		tcp->tcp_ire_ill_check_done = B_FALSE;
18742 
18743 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18744 		connp->conn_ire_cache = NULL;
18745 		mutex_exit(&connp->conn_lock);
18746 
18747 		if (ire != NULL)
18748 			IRE_REFRELE_NOTR(ire);
18749 
18750 		tsl = crgetlabel(CONN_CRED(connp));
18751 		ire = (dst ?
18752 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18753 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18754 		    connp->conn_zoneid, tsl, ipst));
18755 
18756 		if (ire == NULL) {
18757 			TCP_STAT(tcps, tcp_ire_null);
18758 			return (B_FALSE);
18759 		}
18760 
18761 		IRE_REFHOLD_NOTR(ire);
18762 		/*
18763 		 * Since we are inside the squeue, there cannot be another
18764 		 * thread in TCP trying to set the conn_ire_cache now.  The
18765 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18766 		 * unplumb thread has not yet started cleaning up the conns.
18767 		 * Hence we don't need to grab the conn lock.
18768 		 */
18769 		if (CONN_CACHE_IRE(connp)) {
18770 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18771 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18772 				connp->conn_ire_cache = ire;
18773 				cached = B_TRUE;
18774 			}
18775 			rw_exit(&ire->ire_bucket->irb_lock);
18776 		}
18777 
18778 		/*
18779 		 * We can continue to use the ire but since it was
18780 		 * not cached, we should drop the extra reference.
18781 		 */
18782 		if (!cached)
18783 			IRE_REFRELE_NOTR(ire);
18784 
18785 		/*
18786 		 * Rampart note: no need to select a new label here, since
18787 		 * labels are not allowed to change during the life of a TCP
18788 		 * connection.
18789 		 */
18790 	}
18791 
18792 	*irep = ire;
18793 
18794 	return (B_TRUE);
18795 }
18796 
18797 /*
18798  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18799  *
18800  * 0 = success;
18801  * 1 = failed to find ire and ill.
18802  */
18803 static boolean_t
18804 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18805 {
18806 	ipha_t		*ipha;
18807 	ipaddr_t	dst;
18808 	ire_t		*ire;
18809 	ill_t		*ill;
18810 	conn_t		*connp = tcp->tcp_connp;
18811 	mblk_t		*ire_fp_mp;
18812 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18813 
18814 	if (mp != NULL)
18815 		ipha = (ipha_t *)mp->b_rptr;
18816 	else
18817 		ipha = tcp->tcp_ipha;
18818 	dst = ipha->ipha_dst;
18819 
18820 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18821 		return (B_FALSE);
18822 
18823 	if ((ire->ire_flags & RTF_MULTIRT) ||
18824 	    (ire->ire_stq == NULL) ||
18825 	    (ire->ire_nce == NULL) ||
18826 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18827 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18828 		MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18829 		TCP_STAT(tcps, tcp_ip_ire_send);
18830 		IRE_REFRELE(ire);
18831 		return (B_FALSE);
18832 	}
18833 
18834 	ill = ire_to_ill(ire);
18835 	if (connp->conn_outgoing_ill != NULL) {
18836 		ill_t *conn_outgoing_ill = NULL;
18837 		/*
18838 		 * Choose a good ill in the group to send the packets on.
18839 		 */
18840 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18841 		ill = ire_to_ill(ire);
18842 	}
18843 	ASSERT(ill != NULL);
18844 
18845 	if (!tcp->tcp_ire_ill_check_done) {
18846 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18847 		tcp->tcp_ire_ill_check_done = B_TRUE;
18848 	}
18849 
18850 	*irep = ire;
18851 	*illp = ill;
18852 
18853 	return (B_TRUE);
18854 }
18855 
18856 static void
18857 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18858 {
18859 	ipha_t		*ipha;
18860 	ipaddr_t	src;
18861 	ipaddr_t	dst;
18862 	uint32_t	cksum;
18863 	ire_t		*ire;
18864 	uint16_t	*up;
18865 	ill_t		*ill;
18866 	conn_t		*connp = tcp->tcp_connp;
18867 	uint32_t	hcksum_txflags = 0;
18868 	mblk_t		*ire_fp_mp;
18869 	uint_t		ire_fp_mp_len;
18870 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18871 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18872 
18873 	ASSERT(DB_TYPE(mp) == M_DATA);
18874 
18875 	if (DB_CRED(mp) == NULL)
18876 		mblk_setcred(mp, CONN_CRED(connp));
18877 
18878 	ipha = (ipha_t *)mp->b_rptr;
18879 	src = ipha->ipha_src;
18880 	dst = ipha->ipha_dst;
18881 
18882 	/*
18883 	 * Drop off fast path for IPv6 and also if options are present or
18884 	 * we need to resolve a TS label.
18885 	 */
18886 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18887 	    !IPCL_IS_CONNECTED(connp) ||
18888 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18889 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18890 	    !connp->conn_ulp_labeled ||
18891 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18892 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18893 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18894 		if (tcp->tcp_snd_zcopy_aware)
18895 			mp = tcp_zcopy_disable(tcp, mp);
18896 		TCP_STAT(tcps, tcp_ip_send);
18897 		CALL_IP_WPUT(connp, q, mp);
18898 		return;
18899 	}
18900 
18901 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18902 		if (tcp->tcp_snd_zcopy_aware)
18903 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18904 		CALL_IP_WPUT(connp, q, mp);
18905 		return;
18906 	}
18907 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18908 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18909 
18910 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18911 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18912 #ifndef _BIG_ENDIAN
18913 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18914 #endif
18915 
18916 	/*
18917 	 * Check to see if we need to re-enable LSO/MDT for this connection
18918 	 * because it was previously disabled due to changes in the ill;
18919 	 * note that by doing it here, this re-enabling only applies when
18920 	 * the packet is not dispatched through CALL_IP_WPUT().
18921 	 *
18922 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18923 	 * case, since that's how we ended up here.  For IPv6, we do the
18924 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18925 	 */
18926 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18927 		/*
18928 		 * Restore LSO for this connection, so that next time around
18929 		 * it is eligible to go through tcp_lsosend() path again.
18930 		 */
18931 		TCP_STAT(tcps, tcp_lso_enabled);
18932 		tcp->tcp_lso = B_TRUE;
18933 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18934 		    "interface %s\n", (void *)connp, ill->ill_name));
18935 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18936 		/*
18937 		 * Restore MDT for this connection, so that next time around
18938 		 * it is eligible to go through tcp_multisend() path again.
18939 		 */
18940 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18941 		tcp->tcp_mdt = B_TRUE;
18942 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18943 		    "interface %s\n", (void *)connp, ill->ill_name));
18944 	}
18945 
18946 	if (tcp->tcp_snd_zcopy_aware) {
18947 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18948 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18949 			mp = tcp_zcopy_disable(tcp, mp);
18950 		/*
18951 		 * we shouldn't need to reset ipha as the mp containing
18952 		 * ipha should never be a zero-copy mp.
18953 		 */
18954 	}
18955 
18956 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18957 		ASSERT(ill->ill_hcksum_capab != NULL);
18958 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18959 	}
18960 
18961 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18962 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18963 
18964 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18965 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18966 
18967 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18968 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18969 
18970 	/* Software checksum? */
18971 	if (DB_CKSUMFLAGS(mp) == 0) {
18972 		TCP_STAT(tcps, tcp_out_sw_cksum);
18973 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18974 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18975 	}
18976 
18977 	ipha->ipha_fragment_offset_and_flags |=
18978 	    (uint32_t)htons(ire->ire_frag_flag);
18979 
18980 	/* Calculate IP header checksum if hardware isn't capable */
18981 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18982 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18983 		    ((uint16_t *)ipha)[4]);
18984 	}
18985 
18986 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18987 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18988 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18989 
18990 	UPDATE_OB_PKT_COUNT(ire);
18991 	ire->ire_last_used_time = lbolt;
18992 
18993 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
18994 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
18995 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
18996 	    ntohs(ipha->ipha_length));
18997 
18998 	if (ILL_DLS_CAPABLE(ill)) {
18999 		/*
19000 		 * Send the packet directly to DLD, where it may be queued
19001 		 * depending on the availability of transmit resources at
19002 		 * the media layer.
19003 		 */
19004 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19005 	} else {
19006 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19007 		DTRACE_PROBE4(ip4__physical__out__start,
19008 		    ill_t *, NULL, ill_t *, out_ill,
19009 		    ipha_t *, ipha, mblk_t *, mp);
19010 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19011 		    ipst->ips_ipv4firewall_physical_out,
19012 		    NULL, out_ill, ipha, mp, mp, ipst);
19013 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19014 		if (mp != NULL)
19015 			putnext(ire->ire_stq, mp);
19016 	}
19017 	IRE_REFRELE(ire);
19018 }
19019 
19020 /*
19021  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19022  * if the receiver shrinks the window, i.e. moves the right window to the
19023  * left, the we should not send new data, but should retransmit normally the
19024  * old unacked data between suna and suna + swnd. We might has sent data
19025  * that is now outside the new window, pretend that we didn't send  it.
19026  */
19027 static void
19028 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19029 {
19030 	uint32_t	snxt = tcp->tcp_snxt;
19031 	mblk_t		*xmit_tail;
19032 	int32_t		offset;
19033 
19034 	ASSERT(shrunk_count > 0);
19035 
19036 	/* Pretend we didn't send the data outside the window */
19037 	snxt -= shrunk_count;
19038 
19039 	/* Get the mblk and the offset in it per the shrunk window */
19040 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19041 
19042 	ASSERT(xmit_tail != NULL);
19043 
19044 	/* Reset all the values per the now shrunk window */
19045 	tcp->tcp_snxt = snxt;
19046 	tcp->tcp_xmit_tail = xmit_tail;
19047 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19048 	    offset;
19049 	tcp->tcp_unsent += shrunk_count;
19050 
19051 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19052 		/*
19053 		 * Make sure the timer is running so that we will probe a zero
19054 		 * window.
19055 		 */
19056 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19057 }
19058 
19059 
19060 /*
19061  * The TCP normal data output path.
19062  * NOTE: the logic of the fast path is duplicated from this function.
19063  */
19064 static void
19065 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19066 {
19067 	int		len;
19068 	mblk_t		*local_time;
19069 	mblk_t		*mp1;
19070 	uint32_t	snxt;
19071 	int		tail_unsent;
19072 	int		tcpstate;
19073 	int		usable = 0;
19074 	mblk_t		*xmit_tail;
19075 	queue_t		*q = tcp->tcp_wq;
19076 	int32_t		mss;
19077 	int32_t		num_sack_blk = 0;
19078 	int32_t		tcp_hdr_len;
19079 	int32_t		tcp_tcp_hdr_len;
19080 	int		mdt_thres;
19081 	int		rc;
19082 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19083 	ip_stack_t	*ipst;
19084 
19085 	tcpstate = tcp->tcp_state;
19086 	if (mp == NULL) {
19087 		/*
19088 		 * tcp_wput_data() with NULL mp should only be called when
19089 		 * there is unsent data.
19090 		 */
19091 		ASSERT(tcp->tcp_unsent > 0);
19092 		/* Really tacky... but we need this for detached closes. */
19093 		len = tcp->tcp_unsent;
19094 		goto data_null;
19095 	}
19096 
19097 #if CCS_STATS
19098 	wrw_stats.tot.count++;
19099 	wrw_stats.tot.bytes += msgdsize(mp);
19100 #endif
19101 	ASSERT(mp->b_datap->db_type == M_DATA);
19102 	/*
19103 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19104 	 * or before a connection attempt has begun.
19105 	 */
19106 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19107 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19108 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19109 #ifdef DEBUG
19110 			cmn_err(CE_WARN,
19111 			    "tcp_wput_data: data after ordrel, %s",
19112 			    tcp_display(tcp, NULL,
19113 			    DISP_ADDR_AND_PORT));
19114 #else
19115 			if (tcp->tcp_debug) {
19116 				(void) strlog(TCP_MOD_ID, 0, 1,
19117 				    SL_TRACE|SL_ERROR,
19118 				    "tcp_wput_data: data after ordrel, %s\n",
19119 				    tcp_display(tcp, NULL,
19120 				    DISP_ADDR_AND_PORT));
19121 			}
19122 #endif /* DEBUG */
19123 		}
19124 		if (tcp->tcp_snd_zcopy_aware &&
19125 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19126 			tcp_zcopy_notify(tcp);
19127 		freemsg(mp);
19128 		mutex_enter(&tcp->tcp_non_sq_lock);
19129 		if (tcp->tcp_flow_stopped &&
19130 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19131 			tcp_clrqfull(tcp);
19132 		}
19133 		mutex_exit(&tcp->tcp_non_sq_lock);
19134 		return;
19135 	}
19136 
19137 	/* Strip empties */
19138 	for (;;) {
19139 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19140 		    (uintptr_t)INT_MAX);
19141 		len = (int)(mp->b_wptr - mp->b_rptr);
19142 		if (len > 0)
19143 			break;
19144 		mp1 = mp;
19145 		mp = mp->b_cont;
19146 		freeb(mp1);
19147 		if (!mp) {
19148 			return;
19149 		}
19150 	}
19151 
19152 	/* If we are the first on the list ... */
19153 	if (tcp->tcp_xmit_head == NULL) {
19154 		tcp->tcp_xmit_head = mp;
19155 		tcp->tcp_xmit_tail = mp;
19156 		tcp->tcp_xmit_tail_unsent = len;
19157 	} else {
19158 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19159 		struct datab *dp;
19160 
19161 		mp1 = tcp->tcp_xmit_last;
19162 		if (len < tcp_tx_pull_len &&
19163 		    (dp = mp1->b_datap)->db_ref == 1 &&
19164 		    dp->db_lim - mp1->b_wptr >= len) {
19165 			ASSERT(len > 0);
19166 			ASSERT(!mp1->b_cont);
19167 			if (len == 1) {
19168 				*mp1->b_wptr++ = *mp->b_rptr;
19169 			} else {
19170 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19171 				mp1->b_wptr += len;
19172 			}
19173 			if (mp1 == tcp->tcp_xmit_tail)
19174 				tcp->tcp_xmit_tail_unsent += len;
19175 			mp1->b_cont = mp->b_cont;
19176 			if (tcp->tcp_snd_zcopy_aware &&
19177 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19178 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19179 			freeb(mp);
19180 			mp = mp1;
19181 		} else {
19182 			tcp->tcp_xmit_last->b_cont = mp;
19183 		}
19184 		len += tcp->tcp_unsent;
19185 	}
19186 
19187 	/* Tack on however many more positive length mblks we have */
19188 	if ((mp1 = mp->b_cont) != NULL) {
19189 		do {
19190 			int tlen;
19191 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19192 			    (uintptr_t)INT_MAX);
19193 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19194 			if (tlen <= 0) {
19195 				mp->b_cont = mp1->b_cont;
19196 				freeb(mp1);
19197 			} else {
19198 				len += tlen;
19199 				mp = mp1;
19200 			}
19201 		} while ((mp1 = mp->b_cont) != NULL);
19202 	}
19203 	tcp->tcp_xmit_last = mp;
19204 	tcp->tcp_unsent = len;
19205 
19206 	if (urgent)
19207 		usable = 1;
19208 
19209 data_null:
19210 	snxt = tcp->tcp_snxt;
19211 	xmit_tail = tcp->tcp_xmit_tail;
19212 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19213 
19214 	/*
19215 	 * Note that tcp_mss has been adjusted to take into account the
19216 	 * timestamp option if applicable.  Because SACK options do not
19217 	 * appear in every TCP segments and they are of variable lengths,
19218 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19219 	 * the actual segment length when we need to send a segment which
19220 	 * includes SACK options.
19221 	 */
19222 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19223 		int32_t	opt_len;
19224 
19225 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19226 		    tcp->tcp_num_sack_blk);
19227 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19228 		    2 + TCPOPT_HEADER_LEN;
19229 		mss = tcp->tcp_mss - opt_len;
19230 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19231 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19232 	} else {
19233 		mss = tcp->tcp_mss;
19234 		tcp_hdr_len = tcp->tcp_hdr_len;
19235 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19236 	}
19237 
19238 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19239 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19240 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19241 	}
19242 	if (tcpstate == TCPS_SYN_RCVD) {
19243 		/*
19244 		 * The three-way connection establishment handshake is not
19245 		 * complete yet. We want to queue the data for transmission
19246 		 * after entering ESTABLISHED state (RFC793). A jump to
19247 		 * "done" label effectively leaves data on the queue.
19248 		 */
19249 		goto done;
19250 	} else {
19251 		int usable_r;
19252 
19253 		/*
19254 		 * In the special case when cwnd is zero, which can only
19255 		 * happen if the connection is ECN capable, return now.
19256 		 * New segments is sent using tcp_timer().  The timer
19257 		 * is set in tcp_rput_data().
19258 		 */
19259 		if (tcp->tcp_cwnd == 0) {
19260 			/*
19261 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19262 			 * finished.
19263 			 */
19264 			ASSERT(tcp->tcp_ecn_ok ||
19265 			    tcp->tcp_state < TCPS_ESTABLISHED);
19266 			return;
19267 		}
19268 
19269 		/* NOTE: trouble if xmitting while SYN not acked? */
19270 		usable_r = snxt - tcp->tcp_suna;
19271 		usable_r = tcp->tcp_swnd - usable_r;
19272 
19273 		/*
19274 		 * Check if the receiver has shrunk the window.  If
19275 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19276 		 * cannot be set as there is unsent data, so FIN cannot
19277 		 * be sent out.  Otherwise, we need to take into account
19278 		 * of FIN as it consumes an "invisible" sequence number.
19279 		 */
19280 		ASSERT(tcp->tcp_fin_sent == 0);
19281 		if (usable_r < 0) {
19282 			/*
19283 			 * The receiver has shrunk the window and we have sent
19284 			 * -usable_r date beyond the window, re-adjust.
19285 			 *
19286 			 * If TCP window scaling is enabled, there can be
19287 			 * round down error as the advertised receive window
19288 			 * is actually right shifted n bits.  This means that
19289 			 * the lower n bits info is wiped out.  It will look
19290 			 * like the window is shrunk.  Do a check here to
19291 			 * see if the shrunk amount is actually within the
19292 			 * error in window calculation.  If it is, just
19293 			 * return.  Note that this check is inside the
19294 			 * shrunk window check.  This makes sure that even
19295 			 * though tcp_process_shrunk_swnd() is not called,
19296 			 * we will stop further processing.
19297 			 */
19298 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19299 				tcp_process_shrunk_swnd(tcp, -usable_r);
19300 			}
19301 			return;
19302 		}
19303 
19304 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19305 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19306 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19307 
19308 		/* usable = MIN(usable, unsent) */
19309 		if (usable_r > len)
19310 			usable_r = len;
19311 
19312 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19313 		if (usable_r > 0) {
19314 			usable = usable_r;
19315 		} else {
19316 			/* Bypass all other unnecessary processing. */
19317 			goto done;
19318 		}
19319 	}
19320 
19321 	local_time = (mblk_t *)lbolt;
19322 
19323 	/*
19324 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19325 	 * BSD.  This is more in line with the true intent of Nagle.
19326 	 *
19327 	 * The conditions are:
19328 	 * 1. The amount of unsent data (or amount of data which can be
19329 	 *    sent, whichever is smaller) is less than Nagle limit.
19330 	 * 2. The last sent size is also less than Nagle limit.
19331 	 * 3. There is unack'ed data.
19332 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19333 	 *    Nagle algorithm.  This reduces the probability that urgent
19334 	 *    bytes get "merged" together.
19335 	 * 5. The app has not closed the connection.  This eliminates the
19336 	 *    wait time of the receiving side waiting for the last piece of
19337 	 *    (small) data.
19338 	 *
19339 	 * If all are satisified, exit without sending anything.  Note
19340 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19341 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19342 	 * 4095).
19343 	 */
19344 	if (usable < (int)tcp->tcp_naglim &&
19345 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19346 	    snxt != tcp->tcp_suna &&
19347 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19348 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19349 		goto done;
19350 	}
19351 
19352 	if (tcp->tcp_cork) {
19353 		/*
19354 		 * if the tcp->tcp_cork option is set, then we have to force
19355 		 * TCP not to send partial segment (smaller than MSS bytes).
19356 		 * We are calculating the usable now based on full mss and
19357 		 * will save the rest of remaining data for later.
19358 		 */
19359 		if (usable < mss)
19360 			goto done;
19361 		usable = (usable / mss) * mss;
19362 	}
19363 
19364 	/* Update the latest receive window size in TCP header. */
19365 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19366 	    tcp->tcp_tcph->th_win);
19367 
19368 	/*
19369 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19370 	 *
19371 	 * 1. Simple TCP/IP{v4,v6} (no options).
19372 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19373 	 * 3. If the TCP connection is in ESTABLISHED state.
19374 	 * 4. The TCP is not detached.
19375 	 *
19376 	 * If any of the above conditions have changed during the
19377 	 * connection, stop using LSO/MDT and restore the stream head
19378 	 * parameters accordingly.
19379 	 */
19380 	ipst = tcps->tcps_netstack->netstack_ip;
19381 
19382 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19383 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19384 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19385 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19386 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19387 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19388 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19389 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19390 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19391 		if (tcp->tcp_lso) {
19392 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19393 			tcp->tcp_lso = B_FALSE;
19394 		} else {
19395 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19396 			tcp->tcp_mdt = B_FALSE;
19397 		}
19398 
19399 		/* Anything other than detached is considered pathological */
19400 		if (!TCP_IS_DETACHED(tcp)) {
19401 			if (tcp->tcp_lso)
19402 				TCP_STAT(tcps, tcp_lso_disabled);
19403 			else
19404 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19405 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19406 		}
19407 	}
19408 
19409 	/* Use MDT if sendable amount is greater than the threshold */
19410 	if (tcp->tcp_mdt &&
19411 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19412 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19413 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19414 	    (tcp->tcp_valid_bits == 0 ||
19415 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19416 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19417 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19418 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19419 		    local_time, mdt_thres);
19420 	} else {
19421 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19422 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19423 		    local_time, INT_MAX);
19424 	}
19425 
19426 	/* Pretend that all we were trying to send really got sent */
19427 	if (rc < 0 && tail_unsent < 0) {
19428 		do {
19429 			xmit_tail = xmit_tail->b_cont;
19430 			xmit_tail->b_prev = local_time;
19431 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19432 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19433 			tail_unsent += (int)(xmit_tail->b_wptr -
19434 			    xmit_tail->b_rptr);
19435 		} while (tail_unsent < 0);
19436 	}
19437 done:;
19438 	tcp->tcp_xmit_tail = xmit_tail;
19439 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19440 	len = tcp->tcp_snxt - snxt;
19441 	if (len) {
19442 		/*
19443 		 * If new data was sent, need to update the notsack
19444 		 * list, which is, afterall, data blocks that have
19445 		 * not been sack'ed by the receiver.  New data is
19446 		 * not sack'ed.
19447 		 */
19448 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19449 			/* len is a negative value. */
19450 			tcp->tcp_pipe -= len;
19451 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19452 			    tcp->tcp_snxt, snxt,
19453 			    &(tcp->tcp_num_notsack_blk),
19454 			    &(tcp->tcp_cnt_notsack_list));
19455 		}
19456 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19457 		tcp->tcp_rack = tcp->tcp_rnxt;
19458 		tcp->tcp_rack_cnt = 0;
19459 		if ((snxt + len) == tcp->tcp_suna) {
19460 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19461 		}
19462 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19463 		/*
19464 		 * Didn't send anything. Make sure the timer is running
19465 		 * so that we will probe a zero window.
19466 		 */
19467 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19468 	}
19469 	/* Note that len is the amount we just sent but with a negative sign */
19470 	tcp->tcp_unsent += len;
19471 	mutex_enter(&tcp->tcp_non_sq_lock);
19472 	if (tcp->tcp_flow_stopped) {
19473 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19474 			tcp_clrqfull(tcp);
19475 		}
19476 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19477 		tcp_setqfull(tcp);
19478 	}
19479 	mutex_exit(&tcp->tcp_non_sq_lock);
19480 }
19481 
19482 /*
19483  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19484  * outgoing TCP header with the template header, as well as other
19485  * options such as time-stamp, ECN and/or SACK.
19486  */
19487 static void
19488 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19489 {
19490 	tcph_t *tcp_tmpl, *tcp_h;
19491 	uint32_t *dst, *src;
19492 	int hdrlen;
19493 
19494 	ASSERT(OK_32PTR(rptr));
19495 
19496 	/* Template header */
19497 	tcp_tmpl = tcp->tcp_tcph;
19498 
19499 	/* Header of outgoing packet */
19500 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19501 
19502 	/* dst and src are opaque 32-bit fields, used for copying */
19503 	dst = (uint32_t *)rptr;
19504 	src = (uint32_t *)tcp->tcp_iphc;
19505 	hdrlen = tcp->tcp_hdr_len;
19506 
19507 	/* Fill time-stamp option if needed */
19508 	if (tcp->tcp_snd_ts_ok) {
19509 		U32_TO_BE32((uint32_t)now,
19510 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19511 		U32_TO_BE32(tcp->tcp_ts_recent,
19512 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19513 	} else {
19514 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19515 	}
19516 
19517 	/*
19518 	 * Copy the template header; is this really more efficient than
19519 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19520 	 * but perhaps not for other scenarios.
19521 	 */
19522 	dst[0] = src[0];
19523 	dst[1] = src[1];
19524 	dst[2] = src[2];
19525 	dst[3] = src[3];
19526 	dst[4] = src[4];
19527 	dst[5] = src[5];
19528 	dst[6] = src[6];
19529 	dst[7] = src[7];
19530 	dst[8] = src[8];
19531 	dst[9] = src[9];
19532 	if (hdrlen -= 40) {
19533 		hdrlen >>= 2;
19534 		dst += 10;
19535 		src += 10;
19536 		do {
19537 			*dst++ = *src++;
19538 		} while (--hdrlen);
19539 	}
19540 
19541 	/*
19542 	 * Set the ECN info in the TCP header if it is not a zero
19543 	 * window probe.  Zero window probe is only sent in
19544 	 * tcp_wput_data() and tcp_timer().
19545 	 */
19546 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19547 		SET_ECT(tcp, rptr);
19548 
19549 		if (tcp->tcp_ecn_echo_on)
19550 			tcp_h->th_flags[0] |= TH_ECE;
19551 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19552 			tcp_h->th_flags[0] |= TH_CWR;
19553 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19554 		}
19555 	}
19556 
19557 	/* Fill in SACK options */
19558 	if (num_sack_blk > 0) {
19559 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19560 		sack_blk_t *tmp;
19561 		int32_t	i;
19562 
19563 		wptr[0] = TCPOPT_NOP;
19564 		wptr[1] = TCPOPT_NOP;
19565 		wptr[2] = TCPOPT_SACK;
19566 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19567 		    sizeof (sack_blk_t);
19568 		wptr += TCPOPT_REAL_SACK_LEN;
19569 
19570 		tmp = tcp->tcp_sack_list;
19571 		for (i = 0; i < num_sack_blk; i++) {
19572 			U32_TO_BE32(tmp[i].begin, wptr);
19573 			wptr += sizeof (tcp_seq);
19574 			U32_TO_BE32(tmp[i].end, wptr);
19575 			wptr += sizeof (tcp_seq);
19576 		}
19577 		tcp_h->th_offset_and_rsrvd[0] +=
19578 		    ((num_sack_blk * 2 + 1) << 4);
19579 	}
19580 }
19581 
19582 /*
19583  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19584  * the destination address and SAP attribute, and if necessary, the
19585  * hardware checksum offload attribute to a Multidata message.
19586  */
19587 static int
19588 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19589     const uint32_t start, const uint32_t stuff, const uint32_t end,
19590     const uint32_t flags, tcp_stack_t *tcps)
19591 {
19592 	/* Add global destination address & SAP attribute */
19593 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19594 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19595 		    "destination address+SAP\n"));
19596 
19597 		if (dlmp != NULL)
19598 			TCP_STAT(tcps, tcp_mdt_allocfail);
19599 		return (-1);
19600 	}
19601 
19602 	/* Add global hwcksum attribute */
19603 	if (hwcksum &&
19604 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19605 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19606 		    "checksum attribute\n"));
19607 
19608 		TCP_STAT(tcps, tcp_mdt_allocfail);
19609 		return (-1);
19610 	}
19611 
19612 	return (0);
19613 }
19614 
19615 /*
19616  * Smaller and private version of pdescinfo_t used specifically for TCP,
19617  * which allows for only two payload spans per packet.
19618  */
19619 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19620 
19621 /*
19622  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19623  * scheme, and returns one the following:
19624  *
19625  * -1 = failed allocation.
19626  *  0 = success; burst count reached, or usable send window is too small,
19627  *      and that we'd rather wait until later before sending again.
19628  */
19629 static int
19630 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19631     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19632     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19633     const int mdt_thres)
19634 {
19635 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19636 	multidata_t	*mmd;
19637 	uint_t		obsegs, obbytes, hdr_frag_sz;
19638 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19639 	int		num_burst_seg, max_pld;
19640 	pdesc_t		*pkt;
19641 	tcp_pdescinfo_t	tcp_pkt_info;
19642 	pdescinfo_t	*pkt_info;
19643 	int		pbuf_idx, pbuf_idx_nxt;
19644 	int		seg_len, len, spill, af;
19645 	boolean_t	add_buffer, zcopy, clusterwide;
19646 	boolean_t	buf_trunked = B_FALSE;
19647 	boolean_t	rconfirm = B_FALSE;
19648 	boolean_t	done = B_FALSE;
19649 	uint32_t	cksum;
19650 	uint32_t	hwcksum_flags;
19651 	ire_t		*ire = NULL;
19652 	ill_t		*ill;
19653 	ipha_t		*ipha;
19654 	ip6_t		*ip6h;
19655 	ipaddr_t	src, dst;
19656 	ill_zerocopy_capab_t *zc_cap = NULL;
19657 	uint16_t	*up;
19658 	int		err;
19659 	conn_t		*connp;
19660 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19661 	uchar_t		*pld_start;
19662 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19663 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19664 
19665 #ifdef	_BIG_ENDIAN
19666 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19667 #else
19668 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19669 #endif
19670 
19671 #define	PREP_NEW_MULTIDATA() {			\
19672 	mmd = NULL;				\
19673 	md_mp = md_hbuf = NULL;			\
19674 	cur_hdr_off = 0;			\
19675 	max_pld = tcp->tcp_mdt_max_pld;		\
19676 	pbuf_idx = pbuf_idx_nxt = -1;		\
19677 	add_buffer = B_TRUE;			\
19678 	zcopy = B_FALSE;			\
19679 }
19680 
19681 #define	PREP_NEW_PBUF() {			\
19682 	md_pbuf = md_pbuf_nxt = NULL;		\
19683 	pbuf_idx = pbuf_idx_nxt = -1;		\
19684 	cur_pld_off = 0;			\
19685 	first_snxt = *snxt;			\
19686 	ASSERT(*tail_unsent > 0);		\
19687 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19688 }
19689 
19690 	ASSERT(mdt_thres >= mss);
19691 	ASSERT(*usable > 0 && *usable > mdt_thres);
19692 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19693 	ASSERT(!TCP_IS_DETACHED(tcp));
19694 	ASSERT(tcp->tcp_valid_bits == 0 ||
19695 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19696 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19697 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19698 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19699 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19700 
19701 	connp = tcp->tcp_connp;
19702 	ASSERT(connp != NULL);
19703 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19704 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19705 
19706 	/*
19707 	 * Note that tcp will only declare at most 2 payload spans per
19708 	 * packet, which is much lower than the maximum allowable number
19709 	 * of packet spans per Multidata.  For this reason, we use the
19710 	 * privately declared and smaller descriptor info structure, in
19711 	 * order to save some stack space.
19712 	 */
19713 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19714 
19715 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19716 	if (af == AF_INET) {
19717 		dst = tcp->tcp_ipha->ipha_dst;
19718 		src = tcp->tcp_ipha->ipha_src;
19719 		ASSERT(!CLASSD(dst));
19720 	}
19721 	ASSERT(af == AF_INET ||
19722 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19723 
19724 	obsegs = obbytes = 0;
19725 	num_burst_seg = tcp->tcp_snd_burst;
19726 	md_mp_head = NULL;
19727 	PREP_NEW_MULTIDATA();
19728 
19729 	/*
19730 	 * Before we go on further, make sure there is an IRE that we can
19731 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19732 	 * in proceeding any further, and we should just hand everything
19733 	 * off to the legacy path.
19734 	 */
19735 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19736 		goto legacy_send_no_md;
19737 
19738 	ASSERT(ire != NULL);
19739 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19740 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19741 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19742 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19743 	/*
19744 	 * If we do support loopback for MDT (which requires modifications
19745 	 * to the receiving paths), the following assertions should go away,
19746 	 * and we would be sending the Multidata to loopback conn later on.
19747 	 */
19748 	ASSERT(!IRE_IS_LOCAL(ire));
19749 	ASSERT(ire->ire_stq != NULL);
19750 
19751 	ill = ire_to_ill(ire);
19752 	ASSERT(ill != NULL);
19753 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19754 
19755 	if (!tcp->tcp_ire_ill_check_done) {
19756 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19757 		tcp->tcp_ire_ill_check_done = B_TRUE;
19758 	}
19759 
19760 	/*
19761 	 * If the underlying interface conditions have changed, or if the
19762 	 * new interface does not support MDT, go back to legacy path.
19763 	 */
19764 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19765 		/* don't go through this path anymore for this connection */
19766 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19767 		tcp->tcp_mdt = B_FALSE;
19768 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19769 		    "interface %s\n", (void *)connp, ill->ill_name));
19770 		/* IRE will be released prior to returning */
19771 		goto legacy_send_no_md;
19772 	}
19773 
19774 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19775 		zc_cap = ill->ill_zerocopy_capab;
19776 
19777 	/*
19778 	 * Check if we can take tcp fast-path. Note that "incomplete"
19779 	 * ire's (where the link-layer for next hop is not resolved
19780 	 * or where the fast-path header in nce_fp_mp is not available
19781 	 * yet) are sent down the legacy (slow) path.
19782 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19783 	 */
19784 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19785 		/* IRE will be released prior to returning */
19786 		goto legacy_send_no_md;
19787 	}
19788 
19789 	/* go to legacy path if interface doesn't support zerocopy */
19790 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19791 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19792 		/* IRE will be released prior to returning */
19793 		goto legacy_send_no_md;
19794 	}
19795 
19796 	/* does the interface support hardware checksum offload? */
19797 	hwcksum_flags = 0;
19798 	if (ILL_HCKSUM_CAPABLE(ill) &&
19799 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19800 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19801 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19802 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19803 		    HCKSUM_IPHDRCKSUM)
19804 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19805 
19806 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19807 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19808 			hwcksum_flags |= HCK_FULLCKSUM;
19809 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19810 		    HCKSUM_INET_PARTIAL)
19811 			hwcksum_flags |= HCK_PARTIALCKSUM;
19812 	}
19813 
19814 	/*
19815 	 * Each header fragment consists of the leading extra space,
19816 	 * followed by the TCP/IP header, and the trailing extra space.
19817 	 * We make sure that each header fragment begins on a 32-bit
19818 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19819 	 * aligned in tcp_mdt_update).
19820 	 */
19821 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19822 	    tcp->tcp_mdt_hdr_tail), 4);
19823 
19824 	/* are we starting from the beginning of data block? */
19825 	if (*tail_unsent == 0) {
19826 		*xmit_tail = (*xmit_tail)->b_cont;
19827 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19828 		*tail_unsent = (int)MBLKL(*xmit_tail);
19829 	}
19830 
19831 	/*
19832 	 * Here we create one or more Multidata messages, each made up of
19833 	 * one header buffer and up to N payload buffers.  This entire
19834 	 * operation is done within two loops:
19835 	 *
19836 	 * The outer loop mostly deals with creating the Multidata message,
19837 	 * as well as the header buffer that gets added to it.  It also
19838 	 * links the Multidata messages together such that all of them can
19839 	 * be sent down to the lower layer in a single putnext call; this
19840 	 * linking behavior depends on the tcp_mdt_chain tunable.
19841 	 *
19842 	 * The inner loop takes an existing Multidata message, and adds
19843 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19844 	 * packetizes those buffers by filling up the corresponding header
19845 	 * buffer fragments with the proper IP and TCP headers, and by
19846 	 * describing the layout of each packet in the packet descriptors
19847 	 * that get added to the Multidata.
19848 	 */
19849 	do {
19850 		/*
19851 		 * If usable send window is too small, or data blocks in
19852 		 * transmit list are smaller than our threshold (i.e. app
19853 		 * performs large writes followed by small ones), we hand
19854 		 * off the control over to the legacy path.  Note that we'll
19855 		 * get back the control once it encounters a large block.
19856 		 */
19857 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19858 		    (*xmit_tail)->b_cont != NULL &&
19859 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19860 			/* send down what we've got so far */
19861 			if (md_mp_head != NULL) {
19862 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19863 				    obsegs, obbytes, &rconfirm);
19864 			}
19865 			/*
19866 			 * Pass control over to tcp_send(), but tell it to
19867 			 * return to us once a large-size transmission is
19868 			 * possible.
19869 			 */
19870 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19871 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19872 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19873 			    tail_unsent, xmit_tail, local_time,
19874 			    mdt_thres)) <= 0) {
19875 				/* burst count reached, or alloc failed */
19876 				IRE_REFRELE(ire);
19877 				return (err);
19878 			}
19879 
19880 			/* tcp_send() may have sent everything, so check */
19881 			if (*usable <= 0) {
19882 				IRE_REFRELE(ire);
19883 				return (0);
19884 			}
19885 
19886 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19887 			/*
19888 			 * We may have delivered the Multidata, so make sure
19889 			 * to re-initialize before the next round.
19890 			 */
19891 			md_mp_head = NULL;
19892 			obsegs = obbytes = 0;
19893 			num_burst_seg = tcp->tcp_snd_burst;
19894 			PREP_NEW_MULTIDATA();
19895 
19896 			/* are we starting from the beginning of data block? */
19897 			if (*tail_unsent == 0) {
19898 				*xmit_tail = (*xmit_tail)->b_cont;
19899 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19900 				    (uintptr_t)INT_MAX);
19901 				*tail_unsent = (int)MBLKL(*xmit_tail);
19902 			}
19903 		}
19904 
19905 		/*
19906 		 * max_pld limits the number of mblks in tcp's transmit
19907 		 * queue that can be added to a Multidata message.  Once
19908 		 * this counter reaches zero, no more additional mblks
19909 		 * can be added to it.  What happens afterwards depends
19910 		 * on whether or not we are set to chain the Multidata
19911 		 * messages.  If we are to link them together, reset
19912 		 * max_pld to its original value (tcp_mdt_max_pld) and
19913 		 * prepare to create a new Multidata message which will
19914 		 * get linked to md_mp_head.  Else, leave it alone and
19915 		 * let the inner loop break on its own.
19916 		 */
19917 		if (tcp_mdt_chain && max_pld == 0)
19918 			PREP_NEW_MULTIDATA();
19919 
19920 		/* adding a payload buffer; re-initialize values */
19921 		if (add_buffer)
19922 			PREP_NEW_PBUF();
19923 
19924 		/*
19925 		 * If we don't have a Multidata, either because we just
19926 		 * (re)entered this outer loop, or after we branched off
19927 		 * to tcp_send above, setup the Multidata and header
19928 		 * buffer to be used.
19929 		 */
19930 		if (md_mp == NULL) {
19931 			int md_hbuflen;
19932 			uint32_t start, stuff;
19933 
19934 			/*
19935 			 * Calculate Multidata header buffer size large enough
19936 			 * to hold all of the headers that can possibly be
19937 			 * sent at this moment.  We'd rather over-estimate
19938 			 * the size than running out of space; this is okay
19939 			 * since this buffer is small anyway.
19940 			 */
19941 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19942 
19943 			/*
19944 			 * Start and stuff offset for partial hardware
19945 			 * checksum offload; these are currently for IPv4.
19946 			 * For full checksum offload, they are set to zero.
19947 			 */
19948 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19949 				if (af == AF_INET) {
19950 					start = IP_SIMPLE_HDR_LENGTH;
19951 					stuff = IP_SIMPLE_HDR_LENGTH +
19952 					    TCP_CHECKSUM_OFFSET;
19953 				} else {
19954 					start = IPV6_HDR_LEN;
19955 					stuff = IPV6_HDR_LEN +
19956 					    TCP_CHECKSUM_OFFSET;
19957 				}
19958 			} else {
19959 				start = stuff = 0;
19960 			}
19961 
19962 			/*
19963 			 * Create the header buffer, Multidata, as well as
19964 			 * any necessary attributes (destination address,
19965 			 * SAP and hardware checksum offload) that should
19966 			 * be associated with the Multidata message.
19967 			 */
19968 			ASSERT(cur_hdr_off == 0);
19969 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19970 			    ((md_hbuf->b_wptr += md_hbuflen),
19971 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19972 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19973 			    /* fastpath mblk */
19974 			    ire->ire_nce->nce_res_mp,
19975 			    /* hardware checksum enabled */
19976 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19977 			    /* hardware checksum offsets */
19978 			    start, stuff, 0,
19979 			    /* hardware checksum flag */
19980 			    hwcksum_flags, tcps) != 0)) {
19981 legacy_send:
19982 				if (md_mp != NULL) {
19983 					/* Unlink message from the chain */
19984 					if (md_mp_head != NULL) {
19985 						err = (intptr_t)rmvb(md_mp_head,
19986 						    md_mp);
19987 						/*
19988 						 * We can't assert that rmvb
19989 						 * did not return -1, since we
19990 						 * may get here before linkb
19991 						 * happens.  We do, however,
19992 						 * check if we just removed the
19993 						 * only element in the list.
19994 						 */
19995 						if (err == 0)
19996 							md_mp_head = NULL;
19997 					}
19998 					/* md_hbuf gets freed automatically */
19999 					TCP_STAT(tcps, tcp_mdt_discarded);
20000 					freeb(md_mp);
20001 				} else {
20002 					/* Either allocb or mmd_alloc failed */
20003 					TCP_STAT(tcps, tcp_mdt_allocfail);
20004 					if (md_hbuf != NULL)
20005 						freeb(md_hbuf);
20006 				}
20007 
20008 				/* send down what we've got so far */
20009 				if (md_mp_head != NULL) {
20010 					tcp_multisend_data(tcp, ire, ill,
20011 					    md_mp_head, obsegs, obbytes,
20012 					    &rconfirm);
20013 				}
20014 legacy_send_no_md:
20015 				if (ire != NULL)
20016 					IRE_REFRELE(ire);
20017 				/*
20018 				 * Too bad; let the legacy path handle this.
20019 				 * We specify INT_MAX for the threshold, since
20020 				 * we gave up with the Multidata processings
20021 				 * and let the old path have it all.
20022 				 */
20023 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20024 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20025 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20026 				    snxt, tail_unsent, xmit_tail, local_time,
20027 				    INT_MAX));
20028 			}
20029 
20030 			/* link to any existing ones, if applicable */
20031 			TCP_STAT(tcps, tcp_mdt_allocd);
20032 			if (md_mp_head == NULL) {
20033 				md_mp_head = md_mp;
20034 			} else if (tcp_mdt_chain) {
20035 				TCP_STAT(tcps, tcp_mdt_linked);
20036 				linkb(md_mp_head, md_mp);
20037 			}
20038 		}
20039 
20040 		ASSERT(md_mp_head != NULL);
20041 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20042 		ASSERT(md_mp != NULL && mmd != NULL);
20043 		ASSERT(md_hbuf != NULL);
20044 
20045 		/*
20046 		 * Packetize the transmittable portion of the data block;
20047 		 * each data block is essentially added to the Multidata
20048 		 * as a payload buffer.  We also deal with adding more
20049 		 * than one payload buffers, which happens when the remaining
20050 		 * packetized portion of the current payload buffer is less
20051 		 * than MSS, while the next data block in transmit queue
20052 		 * has enough data to make up for one.  This "spillover"
20053 		 * case essentially creates a split-packet, where portions
20054 		 * of the packet's payload fragments may span across two
20055 		 * virtually discontiguous address blocks.
20056 		 */
20057 		seg_len = mss;
20058 		do {
20059 			len = seg_len;
20060 
20061 			ASSERT(len > 0);
20062 			ASSERT(max_pld >= 0);
20063 			ASSERT(!add_buffer || cur_pld_off == 0);
20064 
20065 			/*
20066 			 * First time around for this payload buffer; note
20067 			 * in the case of a spillover, the following has
20068 			 * been done prior to adding the split-packet
20069 			 * descriptor to Multidata, and we don't want to
20070 			 * repeat the process.
20071 			 */
20072 			if (add_buffer) {
20073 				ASSERT(mmd != NULL);
20074 				ASSERT(md_pbuf == NULL);
20075 				ASSERT(md_pbuf_nxt == NULL);
20076 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20077 
20078 				/*
20079 				 * Have we reached the limit?  We'd get to
20080 				 * this case when we're not chaining the
20081 				 * Multidata messages together, and since
20082 				 * we're done, terminate this loop.
20083 				 */
20084 				if (max_pld == 0)
20085 					break; /* done */
20086 
20087 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20088 					TCP_STAT(tcps, tcp_mdt_allocfail);
20089 					goto legacy_send; /* out_of_mem */
20090 				}
20091 
20092 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20093 				    zc_cap != NULL) {
20094 					if (!ip_md_zcopy_attr(mmd, NULL,
20095 					    zc_cap->ill_zerocopy_flags)) {
20096 						freeb(md_pbuf);
20097 						TCP_STAT(tcps,
20098 						    tcp_mdt_allocfail);
20099 						/* out_of_mem */
20100 						goto legacy_send;
20101 					}
20102 					zcopy = B_TRUE;
20103 				}
20104 
20105 				md_pbuf->b_rptr += base_pld_off;
20106 
20107 				/*
20108 				 * Add a payload buffer to the Multidata; this
20109 				 * operation must not fail, or otherwise our
20110 				 * logic in this routine is broken.  There
20111 				 * is no memory allocation done by the
20112 				 * routine, so any returned failure simply
20113 				 * tells us that we've done something wrong.
20114 				 *
20115 				 * A failure tells us that either we're adding
20116 				 * the same payload buffer more than once, or
20117 				 * we're trying to add more buffers than
20118 				 * allowed (max_pld calculation is wrong).
20119 				 * None of the above cases should happen, and
20120 				 * we panic because either there's horrible
20121 				 * heap corruption, and/or programming mistake.
20122 				 */
20123 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20124 				if (pbuf_idx < 0) {
20125 					cmn_err(CE_PANIC, "tcp_multisend: "
20126 					    "payload buffer logic error "
20127 					    "detected for tcp %p mmd %p "
20128 					    "pbuf %p (%d)\n",
20129 					    (void *)tcp, (void *)mmd,
20130 					    (void *)md_pbuf, pbuf_idx);
20131 				}
20132 
20133 				ASSERT(max_pld > 0);
20134 				--max_pld;
20135 				add_buffer = B_FALSE;
20136 			}
20137 
20138 			ASSERT(md_mp_head != NULL);
20139 			ASSERT(md_pbuf != NULL);
20140 			ASSERT(md_pbuf_nxt == NULL);
20141 			ASSERT(pbuf_idx != -1);
20142 			ASSERT(pbuf_idx_nxt == -1);
20143 			ASSERT(*usable > 0);
20144 
20145 			/*
20146 			 * We spillover to the next payload buffer only
20147 			 * if all of the following is true:
20148 			 *
20149 			 *   1. There is not enough data on the current
20150 			 *	payload buffer to make up `len',
20151 			 *   2. We are allowed to send `len',
20152 			 *   3. The next payload buffer length is large
20153 			 *	enough to accomodate `spill'.
20154 			 */
20155 			if ((spill = len - *tail_unsent) > 0 &&
20156 			    *usable >= len &&
20157 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20158 			    max_pld > 0) {
20159 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20160 				if (md_pbuf_nxt == NULL) {
20161 					TCP_STAT(tcps, tcp_mdt_allocfail);
20162 					goto legacy_send; /* out_of_mem */
20163 				}
20164 
20165 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20166 				    zc_cap != NULL) {
20167 					if (!ip_md_zcopy_attr(mmd, NULL,
20168 					    zc_cap->ill_zerocopy_flags)) {
20169 						freeb(md_pbuf_nxt);
20170 						TCP_STAT(tcps,
20171 						    tcp_mdt_allocfail);
20172 						/* out_of_mem */
20173 						goto legacy_send;
20174 					}
20175 					zcopy = B_TRUE;
20176 				}
20177 
20178 				/*
20179 				 * See comments above on the first call to
20180 				 * mmd_addpldbuf for explanation on the panic.
20181 				 */
20182 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20183 				if (pbuf_idx_nxt < 0) {
20184 					panic("tcp_multisend: "
20185 					    "next payload buffer logic error "
20186 					    "detected for tcp %p mmd %p "
20187 					    "pbuf %p (%d)\n",
20188 					    (void *)tcp, (void *)mmd,
20189 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20190 				}
20191 
20192 				ASSERT(max_pld > 0);
20193 				--max_pld;
20194 			} else if (spill > 0) {
20195 				/*
20196 				 * If there's a spillover, but the following
20197 				 * xmit_tail couldn't give us enough octets
20198 				 * to reach "len", then stop the current
20199 				 * Multidata creation and let the legacy
20200 				 * tcp_send() path take over.  We don't want
20201 				 * to send the tiny segment as part of this
20202 				 * Multidata for performance reasons; instead,
20203 				 * we let the legacy path deal with grouping
20204 				 * it with the subsequent small mblks.
20205 				 */
20206 				if (*usable >= len &&
20207 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20208 					max_pld = 0;
20209 					break;	/* done */
20210 				}
20211 
20212 				/*
20213 				 * We can't spillover, and we are near
20214 				 * the end of the current payload buffer,
20215 				 * so send what's left.
20216 				 */
20217 				ASSERT(*tail_unsent > 0);
20218 				len = *tail_unsent;
20219 			}
20220 
20221 			/* tail_unsent is negated if there is a spillover */
20222 			*tail_unsent -= len;
20223 			*usable -= len;
20224 			ASSERT(*usable >= 0);
20225 
20226 			if (*usable < mss)
20227 				seg_len = *usable;
20228 			/*
20229 			 * Sender SWS avoidance; see comments in tcp_send();
20230 			 * everything else is the same, except that we only
20231 			 * do this here if there is no more data to be sent
20232 			 * following the current xmit_tail.  We don't check
20233 			 * for 1-byte urgent data because we shouldn't get
20234 			 * here if TCP_URG_VALID is set.
20235 			 */
20236 			if (*usable > 0 && *usable < mss &&
20237 			    ((md_pbuf_nxt == NULL &&
20238 			    (*xmit_tail)->b_cont == NULL) ||
20239 			    (md_pbuf_nxt != NULL &&
20240 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20241 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20242 			    (tcp->tcp_unsent -
20243 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20244 			    !tcp->tcp_zero_win_probe) {
20245 				if ((*snxt + len) == tcp->tcp_snxt &&
20246 				    (*snxt + len) == tcp->tcp_suna) {
20247 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20248 				}
20249 				done = B_TRUE;
20250 			}
20251 
20252 			/*
20253 			 * Prime pump for IP's checksumming on our behalf;
20254 			 * include the adjustment for a source route if any.
20255 			 * Do this only for software/partial hardware checksum
20256 			 * offload, as this field gets zeroed out later for
20257 			 * the full hardware checksum offload case.
20258 			 */
20259 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20260 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20261 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20262 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20263 			}
20264 
20265 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20266 			*snxt += len;
20267 
20268 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20269 			/*
20270 			 * We set the PUSH bit only if TCP has no more buffered
20271 			 * data to be transmitted (or if sender SWS avoidance
20272 			 * takes place), as opposed to setting it for every
20273 			 * last packet in the burst.
20274 			 */
20275 			if (done ||
20276 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20277 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20278 
20279 			/*
20280 			 * Set FIN bit if this is our last segment; snxt
20281 			 * already includes its length, and it will not
20282 			 * be adjusted after this point.
20283 			 */
20284 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20285 			    *snxt == tcp->tcp_fss) {
20286 				if (!tcp->tcp_fin_acked) {
20287 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20288 					BUMP_MIB(&tcps->tcps_mib,
20289 					    tcpOutControl);
20290 				}
20291 				if (!tcp->tcp_fin_sent) {
20292 					tcp->tcp_fin_sent = B_TRUE;
20293 					/*
20294 					 * tcp state must be ESTABLISHED
20295 					 * in order for us to get here in
20296 					 * the first place.
20297 					 */
20298 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20299 
20300 					/*
20301 					 * Upon returning from this routine,
20302 					 * tcp_wput_data() will set tcp_snxt
20303 					 * to be equal to snxt + tcp_fin_sent.
20304 					 * This is essentially the same as
20305 					 * setting it to tcp_fss + 1.
20306 					 */
20307 				}
20308 			}
20309 
20310 			tcp->tcp_last_sent_len = (ushort_t)len;
20311 
20312 			len += tcp_hdr_len;
20313 			if (tcp->tcp_ipversion == IPV4_VERSION)
20314 				tcp->tcp_ipha->ipha_length = htons(len);
20315 			else
20316 				tcp->tcp_ip6h->ip6_plen = htons(len -
20317 				    ((char *)&tcp->tcp_ip6h[1] -
20318 				    tcp->tcp_iphc));
20319 
20320 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20321 
20322 			/* setup header fragment */
20323 			PDESC_HDR_ADD(pkt_info,
20324 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20325 			    tcp->tcp_mdt_hdr_head,		/* head room */
20326 			    tcp_hdr_len,			/* len */
20327 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20328 
20329 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20330 			    hdr_frag_sz);
20331 			ASSERT(MBLKIN(md_hbuf,
20332 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20333 			    PDESC_HDRSIZE(pkt_info)));
20334 
20335 			/* setup first payload fragment */
20336 			PDESC_PLD_INIT(pkt_info);
20337 			PDESC_PLD_SPAN_ADD(pkt_info,
20338 			    pbuf_idx,				/* index */
20339 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20340 			    tcp->tcp_last_sent_len);		/* len */
20341 
20342 			/* create a split-packet in case of a spillover */
20343 			if (md_pbuf_nxt != NULL) {
20344 				ASSERT(spill > 0);
20345 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20346 				ASSERT(!add_buffer);
20347 
20348 				md_pbuf = md_pbuf_nxt;
20349 				md_pbuf_nxt = NULL;
20350 				pbuf_idx = pbuf_idx_nxt;
20351 				pbuf_idx_nxt = -1;
20352 				cur_pld_off = spill;
20353 
20354 				/* trim out first payload fragment */
20355 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20356 
20357 				/* setup second payload fragment */
20358 				PDESC_PLD_SPAN_ADD(pkt_info,
20359 				    pbuf_idx,			/* index */
20360 				    md_pbuf->b_rptr,		/* start */
20361 				    spill);			/* len */
20362 
20363 				if ((*xmit_tail)->b_next == NULL) {
20364 					/*
20365 					 * Store the lbolt used for RTT
20366 					 * estimation. We can only record one
20367 					 * timestamp per mblk so we do it when
20368 					 * we reach the end of the payload
20369 					 * buffer.  Also we only take a new
20370 					 * timestamp sample when the previous
20371 					 * timed data from the same mblk has
20372 					 * been ack'ed.
20373 					 */
20374 					(*xmit_tail)->b_prev = local_time;
20375 					(*xmit_tail)->b_next =
20376 					    (mblk_t *)(uintptr_t)first_snxt;
20377 				}
20378 
20379 				first_snxt = *snxt - spill;
20380 
20381 				/*
20382 				 * Advance xmit_tail; usable could be 0 by
20383 				 * the time we got here, but we made sure
20384 				 * above that we would only spillover to
20385 				 * the next data block if usable includes
20386 				 * the spilled-over amount prior to the
20387 				 * subtraction.  Therefore, we are sure
20388 				 * that xmit_tail->b_cont can't be NULL.
20389 				 */
20390 				ASSERT((*xmit_tail)->b_cont != NULL);
20391 				*xmit_tail = (*xmit_tail)->b_cont;
20392 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20393 				    (uintptr_t)INT_MAX);
20394 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20395 			} else {
20396 				cur_pld_off += tcp->tcp_last_sent_len;
20397 			}
20398 
20399 			/*
20400 			 * Fill in the header using the template header, and
20401 			 * add options such as time-stamp, ECN and/or SACK,
20402 			 * as needed.
20403 			 */
20404 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20405 			    (clock_t)local_time, num_sack_blk);
20406 
20407 			/* take care of some IP header businesses */
20408 			if (af == AF_INET) {
20409 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20410 
20411 				ASSERT(OK_32PTR((uchar_t *)ipha));
20412 				ASSERT(PDESC_HDRL(pkt_info) >=
20413 				    IP_SIMPLE_HDR_LENGTH);
20414 				ASSERT(ipha->ipha_version_and_hdr_length ==
20415 				    IP_SIMPLE_HDR_VERSION);
20416 
20417 				/*
20418 				 * Assign ident value for current packet; see
20419 				 * related comments in ip_wput_ire() about the
20420 				 * contract private interface with clustering
20421 				 * group.
20422 				 */
20423 				clusterwide = B_FALSE;
20424 				if (cl_inet_ipident != NULL) {
20425 					ASSERT(cl_inet_isclusterwide != NULL);
20426 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20427 					    AF_INET,
20428 					    (uint8_t *)(uintptr_t)src)) {
20429 						ipha->ipha_ident =
20430 						    (*cl_inet_ipident)
20431 						    (IPPROTO_IP, AF_INET,
20432 						    (uint8_t *)(uintptr_t)src,
20433 						    (uint8_t *)(uintptr_t)dst);
20434 						clusterwide = B_TRUE;
20435 					}
20436 				}
20437 
20438 				if (!clusterwide) {
20439 					ipha->ipha_ident = (uint16_t)
20440 					    atomic_add_32_nv(
20441 						&ire->ire_ident, 1);
20442 				}
20443 #ifndef _BIG_ENDIAN
20444 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20445 				    (ipha->ipha_ident >> 8);
20446 #endif
20447 			} else {
20448 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20449 
20450 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20451 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20452 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20453 				ASSERT(PDESC_HDRL(pkt_info) >=
20454 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20455 				    TCP_CHECKSUM_SIZE));
20456 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20457 
20458 				if (tcp->tcp_ip_forward_progress) {
20459 					rconfirm = B_TRUE;
20460 					tcp->tcp_ip_forward_progress = B_FALSE;
20461 				}
20462 			}
20463 
20464 			/* at least one payload span, and at most two */
20465 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20466 
20467 			/* add the packet descriptor to Multidata */
20468 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20469 			    KM_NOSLEEP)) == NULL) {
20470 				/*
20471 				 * Any failure other than ENOMEM indicates
20472 				 * that we have passed in invalid pkt_info
20473 				 * or parameters to mmd_addpdesc, which must
20474 				 * not happen.
20475 				 *
20476 				 * EINVAL is a result of failure on boundary
20477 				 * checks against the pkt_info contents.  It
20478 				 * should not happen, and we panic because
20479 				 * either there's horrible heap corruption,
20480 				 * and/or programming mistake.
20481 				 */
20482 				if (err != ENOMEM) {
20483 					cmn_err(CE_PANIC, "tcp_multisend: "
20484 					    "pdesc logic error detected for "
20485 					    "tcp %p mmd %p pinfo %p (%d)\n",
20486 					    (void *)tcp, (void *)mmd,
20487 					    (void *)pkt_info, err);
20488 				}
20489 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20490 				goto legacy_send; /* out_of_mem */
20491 			}
20492 			ASSERT(pkt != NULL);
20493 
20494 			/* calculate IP header and TCP checksums */
20495 			if (af == AF_INET) {
20496 				/* calculate pseudo-header checksum */
20497 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20498 				    (src >> 16) + (src & 0xFFFF);
20499 
20500 				/* offset for TCP header checksum */
20501 				up = IPH_TCPH_CHECKSUMP(ipha,
20502 				    IP_SIMPLE_HDR_LENGTH);
20503 			} else {
20504 				up = (uint16_t *)&ip6h->ip6_src;
20505 
20506 				/* calculate pseudo-header checksum */
20507 				cksum = up[0] + up[1] + up[2] + up[3] +
20508 				    up[4] + up[5] + up[6] + up[7] +
20509 				    up[8] + up[9] + up[10] + up[11] +
20510 				    up[12] + up[13] + up[14] + up[15];
20511 
20512 				/* Fold the initial sum */
20513 				cksum = (cksum & 0xffff) + (cksum >> 16);
20514 
20515 				up = (uint16_t *)(((uchar_t *)ip6h) +
20516 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20517 			}
20518 
20519 			if (hwcksum_flags & HCK_FULLCKSUM) {
20520 				/* clear checksum field for hardware */
20521 				*up = 0;
20522 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20523 				uint32_t sum;
20524 
20525 				/* pseudo-header checksumming */
20526 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20527 				sum = (sum & 0xFFFF) + (sum >> 16);
20528 				*up = (sum & 0xFFFF) + (sum >> 16);
20529 			} else {
20530 				/* software checksumming */
20531 				TCP_STAT(tcps, tcp_out_sw_cksum);
20532 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20533 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20534 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20535 				    cksum + IP_TCP_CSUM_COMP);
20536 				if (*up == 0)
20537 					*up = 0xFFFF;
20538 			}
20539 
20540 			/* IPv4 header checksum */
20541 			if (af == AF_INET) {
20542 				ipha->ipha_fragment_offset_and_flags |=
20543 				    (uint32_t)htons(ire->ire_frag_flag);
20544 
20545 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20546 					ipha->ipha_hdr_checksum = 0;
20547 				} else {
20548 					IP_HDR_CKSUM(ipha, cksum,
20549 					    ((uint32_t *)ipha)[0],
20550 					    ((uint16_t *)ipha)[4]);
20551 				}
20552 			}
20553 
20554 			if (af == AF_INET &&
20555 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20556 			    af == AF_INET6 &&
20557 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20558 				/* build header(IP/TCP) mblk for this segment */
20559 				if ((mp = dupb(md_hbuf)) == NULL)
20560 					goto legacy_send;
20561 
20562 				mp->b_rptr = pkt_info->hdr_rptr;
20563 				mp->b_wptr = pkt_info->hdr_wptr;
20564 
20565 				/* build payload mblk for this segment */
20566 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20567 					freemsg(mp);
20568 					goto legacy_send;
20569 				}
20570 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20571 				mp1->b_rptr = mp1->b_wptr -
20572 				    tcp->tcp_last_sent_len;
20573 				linkb(mp, mp1);
20574 
20575 				pld_start = mp1->b_rptr;
20576 
20577 				if (af == AF_INET) {
20578 					DTRACE_PROBE4(
20579 					    ip4__physical__out__start,
20580 					    ill_t *, NULL,
20581 					    ill_t *, ill,
20582 					    ipha_t *, ipha,
20583 					    mblk_t *, mp);
20584 					FW_HOOKS(
20585 					    ipst->ips_ip4_physical_out_event,
20586 					    ipst->ips_ipv4firewall_physical_out,
20587 					    NULL, ill, ipha, mp, mp, ipst);
20588 					DTRACE_PROBE1(
20589 					    ip4__physical__out__end,
20590 					    mblk_t *, mp);
20591 				} else {
20592 					DTRACE_PROBE4(
20593 					    ip6__physical__out_start,
20594 					    ill_t *, NULL,
20595 					    ill_t *, ill,
20596 					    ip6_t *, ip6h,
20597 					    mblk_t *, mp);
20598 					FW_HOOKS6(
20599 					    ipst->ips_ip6_physical_out_event,
20600 					    ipst->ips_ipv6firewall_physical_out,
20601 					    NULL, ill, ip6h, mp, mp, ipst);
20602 					DTRACE_PROBE1(
20603 					    ip6__physical__out__end,
20604 					    mblk_t *, mp);
20605 				}
20606 
20607 				if (buf_trunked && mp != NULL) {
20608 					/*
20609 					 * Need to pass it to normal path.
20610 					 */
20611 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20612 				} else if (mp == NULL ||
20613 				    mp->b_rptr != pkt_info->hdr_rptr ||
20614 				    mp->b_wptr != pkt_info->hdr_wptr ||
20615 				    (mp1 = mp->b_cont) == NULL ||
20616 				    mp1->b_rptr != pld_start ||
20617 				    mp1->b_wptr != pld_start +
20618 				    tcp->tcp_last_sent_len ||
20619 				    mp1->b_cont != NULL) {
20620 					/*
20621 					 * Need to pass all packets of this
20622 					 * buffer to normal path, either when
20623 					 * packet is blocked, or when boundary
20624 					 * of header buffer or payload buffer
20625 					 * has been changed by FW_HOOKS[6].
20626 					 */
20627 					buf_trunked = B_TRUE;
20628 					if (md_mp_head != NULL) {
20629 						err = (intptr_t)rmvb(md_mp_head,
20630 						    md_mp);
20631 						if (err == 0)
20632 							md_mp_head = NULL;
20633 					}
20634 
20635 					/* send down what we've got so far */
20636 					if (md_mp_head != NULL) {
20637 						tcp_multisend_data(tcp, ire,
20638 						    ill, md_mp_head, obsegs,
20639 						    obbytes, &rconfirm);
20640 					}
20641 					md_mp_head = NULL;
20642 
20643 					if (mp != NULL)
20644 						CALL_IP_WPUT(tcp->tcp_connp,
20645 						    q, mp);
20646 
20647 					mp1 = fw_mp_head;
20648 					do {
20649 						mp = mp1;
20650 						mp1 = mp1->b_next;
20651 						mp->b_next = NULL;
20652 						mp->b_prev = NULL;
20653 						CALL_IP_WPUT(tcp->tcp_connp,
20654 						    q, mp);
20655 					} while (mp1 != NULL);
20656 
20657 					fw_mp_head = NULL;
20658 				} else {
20659 					if (fw_mp_head == NULL)
20660 						fw_mp_head = mp;
20661 					else
20662 						fw_mp_head->b_prev->b_next = mp;
20663 					fw_mp_head->b_prev = mp;
20664 				}
20665 			}
20666 
20667 			/* advance header offset */
20668 			cur_hdr_off += hdr_frag_sz;
20669 
20670 			obbytes += tcp->tcp_last_sent_len;
20671 			++obsegs;
20672 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20673 		    *tail_unsent > 0);
20674 
20675 		if ((*xmit_tail)->b_next == NULL) {
20676 			/*
20677 			 * Store the lbolt used for RTT estimation. We can only
20678 			 * record one timestamp per mblk so we do it when we
20679 			 * reach the end of the payload buffer. Also we only
20680 			 * take a new timestamp sample when the previous timed
20681 			 * data from the same mblk has been ack'ed.
20682 			 */
20683 			(*xmit_tail)->b_prev = local_time;
20684 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20685 		}
20686 
20687 		ASSERT(*tail_unsent >= 0);
20688 		if (*tail_unsent > 0) {
20689 			/*
20690 			 * We got here because we broke out of the above
20691 			 * loop due to of one of the following cases:
20692 			 *
20693 			 *   1. len < adjusted MSS (i.e. small),
20694 			 *   2. Sender SWS avoidance,
20695 			 *   3. max_pld is zero.
20696 			 *
20697 			 * We are done for this Multidata, so trim our
20698 			 * last payload buffer (if any) accordingly.
20699 			 */
20700 			if (md_pbuf != NULL)
20701 				md_pbuf->b_wptr -= *tail_unsent;
20702 		} else if (*usable > 0) {
20703 			*xmit_tail = (*xmit_tail)->b_cont;
20704 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20705 			    (uintptr_t)INT_MAX);
20706 			*tail_unsent = (int)MBLKL(*xmit_tail);
20707 			add_buffer = B_TRUE;
20708 		}
20709 
20710 		while (fw_mp_head) {
20711 			mp = fw_mp_head;
20712 			fw_mp_head = fw_mp_head->b_next;
20713 			mp->b_prev = mp->b_next = NULL;
20714 			freemsg(mp);
20715 		}
20716 		if (buf_trunked) {
20717 			TCP_STAT(tcps, tcp_mdt_discarded);
20718 			freeb(md_mp);
20719 			buf_trunked = B_FALSE;
20720 		}
20721 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20722 	    (tcp_mdt_chain || max_pld > 0));
20723 
20724 	if (md_mp_head != NULL) {
20725 		/* send everything down */
20726 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20727 		    &rconfirm);
20728 	}
20729 
20730 #undef PREP_NEW_MULTIDATA
20731 #undef PREP_NEW_PBUF
20732 #undef IPVER
20733 
20734 	IRE_REFRELE(ire);
20735 	return (0);
20736 }
20737 
20738 /*
20739  * A wrapper function for sending one or more Multidata messages down to
20740  * the module below ip; this routine does not release the reference of the
20741  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20742  */
20743 static void
20744 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20745     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20746 {
20747 	uint64_t delta;
20748 	nce_t *nce;
20749 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20750 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20751 
20752 	ASSERT(ire != NULL && ill != NULL);
20753 	ASSERT(ire->ire_stq != NULL);
20754 	ASSERT(md_mp_head != NULL);
20755 	ASSERT(rconfirm != NULL);
20756 
20757 	/* adjust MIBs and IRE timestamp */
20758 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20759 	tcp->tcp_obsegs += obsegs;
20760 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20761 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20762 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20763 
20764 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20765 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20766 	} else {
20767 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20768 	}
20769 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20770 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20771 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20772 
20773 	ire->ire_ob_pkt_count += obsegs;
20774 	if (ire->ire_ipif != NULL)
20775 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20776 	ire->ire_last_used_time = lbolt;
20777 
20778 	/* send it down */
20779 	putnext(ire->ire_stq, md_mp_head);
20780 
20781 	/* we're done for TCP/IPv4 */
20782 	if (tcp->tcp_ipversion == IPV4_VERSION)
20783 		return;
20784 
20785 	nce = ire->ire_nce;
20786 
20787 	ASSERT(nce != NULL);
20788 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20789 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20790 
20791 	/* reachability confirmation? */
20792 	if (*rconfirm) {
20793 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20794 		if (nce->nce_state != ND_REACHABLE) {
20795 			mutex_enter(&nce->nce_lock);
20796 			nce->nce_state = ND_REACHABLE;
20797 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20798 			mutex_exit(&nce->nce_lock);
20799 			(void) untimeout(nce->nce_timeout_id);
20800 			if (ip_debug > 2) {
20801 				/* ip1dbg */
20802 				pr_addr_dbg("tcp_multisend_data: state "
20803 				    "for %s changed to REACHABLE\n",
20804 				    AF_INET6, &ire->ire_addr_v6);
20805 			}
20806 		}
20807 		/* reset transport reachability confirmation */
20808 		*rconfirm = B_FALSE;
20809 	}
20810 
20811 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20812 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20813 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20814 
20815 	if (delta > (uint64_t)ill->ill_reachable_time) {
20816 		mutex_enter(&nce->nce_lock);
20817 		switch (nce->nce_state) {
20818 		case ND_REACHABLE:
20819 		case ND_STALE:
20820 			/*
20821 			 * ND_REACHABLE is identical to ND_STALE in this
20822 			 * specific case. If reachable time has expired for
20823 			 * this neighbor (delta is greater than reachable
20824 			 * time), conceptually, the neighbor cache is no
20825 			 * longer in REACHABLE state, but already in STALE
20826 			 * state.  So the correct transition here is to
20827 			 * ND_DELAY.
20828 			 */
20829 			nce->nce_state = ND_DELAY;
20830 			mutex_exit(&nce->nce_lock);
20831 			NDP_RESTART_TIMER(nce,
20832 			    ipst->ips_delay_first_probe_time);
20833 			if (ip_debug > 3) {
20834 				/* ip2dbg */
20835 				pr_addr_dbg("tcp_multisend_data: state "
20836 				    "for %s changed to DELAY\n",
20837 				    AF_INET6, &ire->ire_addr_v6);
20838 			}
20839 			break;
20840 		case ND_DELAY:
20841 		case ND_PROBE:
20842 			mutex_exit(&nce->nce_lock);
20843 			/* Timers have already started */
20844 			break;
20845 		case ND_UNREACHABLE:
20846 			/*
20847 			 * ndp timer has detected that this nce is
20848 			 * unreachable and initiated deleting this nce
20849 			 * and all its associated IREs. This is a race
20850 			 * where we found the ire before it was deleted
20851 			 * and have just sent out a packet using this
20852 			 * unreachable nce.
20853 			 */
20854 			mutex_exit(&nce->nce_lock);
20855 			break;
20856 		default:
20857 			ASSERT(0);
20858 		}
20859 	}
20860 }
20861 
20862 /*
20863  * Derived from tcp_send_data().
20864  */
20865 static void
20866 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20867     int num_lso_seg)
20868 {
20869 	ipha_t		*ipha;
20870 	mblk_t		*ire_fp_mp;
20871 	uint_t		ire_fp_mp_len;
20872 	uint32_t	hcksum_txflags = 0;
20873 	ipaddr_t	src;
20874 	ipaddr_t	dst;
20875 	uint32_t	cksum;
20876 	uint16_t	*up;
20877 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20878 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20879 
20880 	ASSERT(DB_TYPE(mp) == M_DATA);
20881 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20882 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20883 	ASSERT(tcp->tcp_connp != NULL);
20884 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20885 
20886 	ipha = (ipha_t *)mp->b_rptr;
20887 	src = ipha->ipha_src;
20888 	dst = ipha->ipha_dst;
20889 
20890 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20891 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20892 	    num_lso_seg);
20893 #ifndef _BIG_ENDIAN
20894 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20895 #endif
20896 	if (tcp->tcp_snd_zcopy_aware) {
20897 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20898 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20899 			mp = tcp_zcopy_disable(tcp, mp);
20900 	}
20901 
20902 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20903 		ASSERT(ill->ill_hcksum_capab != NULL);
20904 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20905 	}
20906 
20907 	/*
20908 	 * Since the TCP checksum should be recalculated by h/w, we can just
20909 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20910 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20911 	 * The partial pseudo-header excludes TCP length, that was calculated
20912 	 * in tcp_send(), so to zero *up before further processing.
20913 	 */
20914 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20915 
20916 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20917 	*up = 0;
20918 
20919 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20920 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20921 
20922 	/*
20923 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
20924 	 */
20925 	DB_LSOFLAGS(mp) |= HW_LSO;
20926 	DB_LSOMSS(mp) = mss;
20927 
20928 	ipha->ipha_fragment_offset_and_flags |=
20929 	    (uint32_t)htons(ire->ire_frag_flag);
20930 
20931 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20932 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20933 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20934 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20935 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20936 
20937 	UPDATE_OB_PKT_COUNT(ire);
20938 	ire->ire_last_used_time = lbolt;
20939 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20940 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20941 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20942 	    ntohs(ipha->ipha_length));
20943 
20944 	if (ILL_DLS_CAPABLE(ill)) {
20945 		/*
20946 		 * Send the packet directly to DLD, where it may be queued
20947 		 * depending on the availability of transmit resources at
20948 		 * the media layer.
20949 		 */
20950 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
20951 	} else {
20952 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
20953 		DTRACE_PROBE4(ip4__physical__out__start,
20954 		    ill_t *, NULL, ill_t *, out_ill,
20955 		    ipha_t *, ipha, mblk_t *, mp);
20956 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
20957 		    ipst->ips_ipv4firewall_physical_out,
20958 		    NULL, out_ill, ipha, mp, mp, ipst);
20959 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20960 		if (mp != NULL)
20961 			putnext(ire->ire_stq, mp);
20962 	}
20963 }
20964 
20965 /*
20966  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20967  * scheme, and returns one of the following:
20968  *
20969  * -1 = failed allocation.
20970  *  0 = success; burst count reached, or usable send window is too small,
20971  *      and that we'd rather wait until later before sending again.
20972  *  1 = success; we are called from tcp_multisend(), and both usable send
20973  *      window and tail_unsent are greater than the MDT threshold, and thus
20974  *      Multidata Transmit should be used instead.
20975  */
20976 static int
20977 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20978     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20979     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20980     const int mdt_thres)
20981 {
20982 	int num_burst_seg = tcp->tcp_snd_burst;
20983 	ire_t		*ire = NULL;
20984 	ill_t		*ill = NULL;
20985 	mblk_t		*ire_fp_mp = NULL;
20986 	uint_t		ire_fp_mp_len = 0;
20987 	int		num_lso_seg = 1;
20988 	uint_t		lso_usable;
20989 	boolean_t	do_lso_send = B_FALSE;
20990 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20991 
20992 	/*
20993 	 * Check LSO capability before any further work. And the similar check
20994 	 * need to be done in for(;;) loop.
20995 	 * LSO will be deployed when therer is more than one mss of available
20996 	 * data and a burst transmission is allowed.
20997 	 */
20998 	if (tcp->tcp_lso &&
20999 	    (tcp->tcp_valid_bits == 0 ||
21000 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21001 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21002 		/*
21003 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21004 		 */
21005 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21006 			/*
21007 			 * Enable LSO with this transmission.
21008 			 * Since IRE has been hold in
21009 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21010 			 * should be called before return.
21011 			 */
21012 			do_lso_send = B_TRUE;
21013 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21014 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21015 			/* Round up to multiple of 4 */
21016 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21017 		} else {
21018 			do_lso_send = B_FALSE;
21019 			ill = NULL;
21020 		}
21021 	}
21022 
21023 	for (;;) {
21024 		struct datab	*db;
21025 		tcph_t		*tcph;
21026 		uint32_t	sum;
21027 		mblk_t		*mp, *mp1;
21028 		uchar_t		*rptr;
21029 		int		len;
21030 
21031 		/*
21032 		 * If we're called by tcp_multisend(), and the amount of
21033 		 * sendable data as well as the size of current xmit_tail
21034 		 * is beyond the MDT threshold, return to the caller and
21035 		 * let the large data transmit be done using MDT.
21036 		 */
21037 		if (*usable > 0 && *usable > mdt_thres &&
21038 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21039 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21040 			ASSERT(tcp->tcp_mdt);
21041 			return (1);	/* success; do large send */
21042 		}
21043 
21044 		if (num_burst_seg == 0)
21045 			break;		/* success; burst count reached */
21046 
21047 		/*
21048 		 * Calculate the maximum payload length we can send in *one*
21049 		 * time.
21050 		 */
21051 		if (do_lso_send) {
21052 			/*
21053 			 * Check whether need to do LSO any more.
21054 			 */
21055 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21056 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21057 				lso_usable = MIN(lso_usable,
21058 				    num_burst_seg * mss);
21059 
21060 				num_lso_seg = lso_usable / mss;
21061 				if (lso_usable % mss) {
21062 					num_lso_seg++;
21063 					tcp->tcp_last_sent_len = (ushort_t)
21064 					    (lso_usable % mss);
21065 				} else {
21066 					tcp->tcp_last_sent_len = (ushort_t)mss;
21067 				}
21068 			} else {
21069 				do_lso_send = B_FALSE;
21070 				num_lso_seg = 1;
21071 				lso_usable = mss;
21072 			}
21073 		}
21074 
21075 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21076 
21077 		/*
21078 		 * Adjust num_burst_seg here.
21079 		 */
21080 		num_burst_seg -= num_lso_seg;
21081 
21082 		len = mss;
21083 		if (len > *usable) {
21084 			ASSERT(do_lso_send == B_FALSE);
21085 
21086 			len = *usable;
21087 			if (len <= 0) {
21088 				/* Terminate the loop */
21089 				break;	/* success; too small */
21090 			}
21091 			/*
21092 			 * Sender silly-window avoidance.
21093 			 * Ignore this if we are going to send a
21094 			 * zero window probe out.
21095 			 *
21096 			 * TODO: force data into microscopic window?
21097 			 *	==> (!pushed || (unsent > usable))
21098 			 */
21099 			if (len < (tcp->tcp_max_swnd >> 1) &&
21100 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21101 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21102 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21103 				/*
21104 				 * If the retransmit timer is not running
21105 				 * we start it so that we will retransmit
21106 				 * in the case when the the receiver has
21107 				 * decremented the window.
21108 				 */
21109 				if (*snxt == tcp->tcp_snxt &&
21110 				    *snxt == tcp->tcp_suna) {
21111 					/*
21112 					 * We are not supposed to send
21113 					 * anything.  So let's wait a little
21114 					 * bit longer before breaking SWS
21115 					 * avoidance.
21116 					 *
21117 					 * What should the value be?
21118 					 * Suggestion: MAX(init rexmit time,
21119 					 * tcp->tcp_rto)
21120 					 */
21121 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21122 				}
21123 				break;	/* success; too small */
21124 			}
21125 		}
21126 
21127 		tcph = tcp->tcp_tcph;
21128 
21129 		/*
21130 		 * The reason to adjust len here is that we need to set flags
21131 		 * and calculate checksum.
21132 		 */
21133 		if (do_lso_send)
21134 			len = lso_usable;
21135 
21136 		*usable -= len; /* Approximate - can be adjusted later */
21137 		if (*usable > 0)
21138 			tcph->th_flags[0] = TH_ACK;
21139 		else
21140 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21141 
21142 		/*
21143 		 * Prime pump for IP's checksumming on our behalf
21144 		 * Include the adjustment for a source route if any.
21145 		 */
21146 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21147 		sum = (sum >> 16) + (sum & 0xFFFF);
21148 		U16_TO_ABE16(sum, tcph->th_sum);
21149 
21150 		U32_TO_ABE32(*snxt, tcph->th_seq);
21151 
21152 		/*
21153 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21154 		 * set.  For the case when TCP_FSS_VALID is the only valid
21155 		 * bit (normal active close), branch off only when we think
21156 		 * that the FIN flag needs to be set.  Note for this case,
21157 		 * that (snxt + len) may not reflect the actual seg_len,
21158 		 * as len may be further reduced in tcp_xmit_mp().  If len
21159 		 * gets modified, we will end up here again.
21160 		 */
21161 		if (tcp->tcp_valid_bits != 0 &&
21162 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21163 		    ((*snxt + len) == tcp->tcp_fss))) {
21164 			uchar_t		*prev_rptr;
21165 			uint32_t	prev_snxt = tcp->tcp_snxt;
21166 
21167 			if (*tail_unsent == 0) {
21168 				ASSERT((*xmit_tail)->b_cont != NULL);
21169 				*xmit_tail = (*xmit_tail)->b_cont;
21170 				prev_rptr = (*xmit_tail)->b_rptr;
21171 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21172 				    (*xmit_tail)->b_rptr);
21173 			} else {
21174 				prev_rptr = (*xmit_tail)->b_rptr;
21175 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21176 				    *tail_unsent;
21177 			}
21178 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21179 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21180 			/* Restore tcp_snxt so we get amount sent right. */
21181 			tcp->tcp_snxt = prev_snxt;
21182 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21183 				/*
21184 				 * If the previous timestamp is still in use,
21185 				 * don't stomp on it.
21186 				 */
21187 				if ((*xmit_tail)->b_next == NULL) {
21188 					(*xmit_tail)->b_prev = local_time;
21189 					(*xmit_tail)->b_next =
21190 					    (mblk_t *)(uintptr_t)(*snxt);
21191 				}
21192 			} else
21193 				(*xmit_tail)->b_rptr = prev_rptr;
21194 
21195 			if (mp == NULL) {
21196 				if (ire != NULL)
21197 					IRE_REFRELE(ire);
21198 				return (-1);
21199 			}
21200 			mp1 = mp->b_cont;
21201 
21202 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21203 				tcp->tcp_last_sent_len = (ushort_t)len;
21204 			while (mp1->b_cont) {
21205 				*xmit_tail = (*xmit_tail)->b_cont;
21206 				(*xmit_tail)->b_prev = local_time;
21207 				(*xmit_tail)->b_next =
21208 				    (mblk_t *)(uintptr_t)(*snxt);
21209 				mp1 = mp1->b_cont;
21210 			}
21211 			*snxt += len;
21212 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21213 			BUMP_LOCAL(tcp->tcp_obsegs);
21214 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21215 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21216 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21217 			tcp_send_data(tcp, q, mp);
21218 			continue;
21219 		}
21220 
21221 		*snxt += len;	/* Adjust later if we don't send all of len */
21222 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21223 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21224 
21225 		if (*tail_unsent) {
21226 			/* Are the bytes above us in flight? */
21227 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21228 			if (rptr != (*xmit_tail)->b_rptr) {
21229 				*tail_unsent -= len;
21230 				if (len <= mss) /* LSO is unusable */
21231 					tcp->tcp_last_sent_len = (ushort_t)len;
21232 				len += tcp_hdr_len;
21233 				if (tcp->tcp_ipversion == IPV4_VERSION)
21234 					tcp->tcp_ipha->ipha_length = htons(len);
21235 				else
21236 					tcp->tcp_ip6h->ip6_plen =
21237 					    htons(len -
21238 					    ((char *)&tcp->tcp_ip6h[1] -
21239 					    tcp->tcp_iphc));
21240 				mp = dupb(*xmit_tail);
21241 				if (mp == NULL) {
21242 					if (ire != NULL)
21243 						IRE_REFRELE(ire);
21244 					return (-1);	/* out_of_mem */
21245 				}
21246 				mp->b_rptr = rptr;
21247 				/*
21248 				 * If the old timestamp is no longer in use,
21249 				 * sample a new timestamp now.
21250 				 */
21251 				if ((*xmit_tail)->b_next == NULL) {
21252 					(*xmit_tail)->b_prev = local_time;
21253 					(*xmit_tail)->b_next =
21254 					    (mblk_t *)(uintptr_t)(*snxt-len);
21255 				}
21256 				goto must_alloc;
21257 			}
21258 		} else {
21259 			*xmit_tail = (*xmit_tail)->b_cont;
21260 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21261 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21262 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21263 			    (*xmit_tail)->b_rptr);
21264 		}
21265 
21266 		(*xmit_tail)->b_prev = local_time;
21267 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21268 
21269 		*tail_unsent -= len;
21270 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21271 			tcp->tcp_last_sent_len = (ushort_t)len;
21272 
21273 		len += tcp_hdr_len;
21274 		if (tcp->tcp_ipversion == IPV4_VERSION)
21275 			tcp->tcp_ipha->ipha_length = htons(len);
21276 		else
21277 			tcp->tcp_ip6h->ip6_plen = htons(len -
21278 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21279 
21280 		mp = dupb(*xmit_tail);
21281 		if (mp == NULL) {
21282 			if (ire != NULL)
21283 				IRE_REFRELE(ire);
21284 			return (-1);	/* out_of_mem */
21285 		}
21286 
21287 		len = tcp_hdr_len;
21288 		/*
21289 		 * There are four reasons to allocate a new hdr mblk:
21290 		 *  1) The bytes above us are in use by another packet
21291 		 *  2) We don't have good alignment
21292 		 *  3) The mblk is being shared
21293 		 *  4) We don't have enough room for a header
21294 		 */
21295 		rptr = mp->b_rptr - len;
21296 		if (!OK_32PTR(rptr) ||
21297 		    ((db = mp->b_datap), db->db_ref != 2) ||
21298 		    rptr < db->db_base + ire_fp_mp_len) {
21299 			/* NOTE: we assume allocb returns an OK_32PTR */
21300 
21301 		must_alloc:;
21302 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21303 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21304 			if (mp1 == NULL) {
21305 				freemsg(mp);
21306 				if (ire != NULL)
21307 					IRE_REFRELE(ire);
21308 				return (-1);	/* out_of_mem */
21309 			}
21310 			mp1->b_cont = mp;
21311 			mp = mp1;
21312 			/* Leave room for Link Level header */
21313 			len = tcp_hdr_len;
21314 			rptr =
21315 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21316 			mp->b_wptr = &rptr[len];
21317 		}
21318 
21319 		/*
21320 		 * Fill in the header using the template header, and add
21321 		 * options such as time-stamp, ECN and/or SACK, as needed.
21322 		 */
21323 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21324 
21325 		mp->b_rptr = rptr;
21326 
21327 		if (*tail_unsent) {
21328 			int spill = *tail_unsent;
21329 
21330 			mp1 = mp->b_cont;
21331 			if (mp1 == NULL)
21332 				mp1 = mp;
21333 
21334 			/*
21335 			 * If we're a little short, tack on more mblks until
21336 			 * there is no more spillover.
21337 			 */
21338 			while (spill < 0) {
21339 				mblk_t *nmp;
21340 				int nmpsz;
21341 
21342 				nmp = (*xmit_tail)->b_cont;
21343 				nmpsz = MBLKL(nmp);
21344 
21345 				/*
21346 				 * Excess data in mblk; can we split it?
21347 				 * If MDT is enabled for the connection,
21348 				 * keep on splitting as this is a transient
21349 				 * send path.
21350 				 */
21351 				if (!do_lso_send && !tcp->tcp_mdt &&
21352 				    (spill + nmpsz > 0)) {
21353 					/*
21354 					 * Don't split if stream head was
21355 					 * told to break up larger writes
21356 					 * into smaller ones.
21357 					 */
21358 					if (tcp->tcp_maxpsz > 0)
21359 						break;
21360 
21361 					/*
21362 					 * Next mblk is less than SMSS/2
21363 					 * rounded up to nearest 64-byte;
21364 					 * let it get sent as part of the
21365 					 * next segment.
21366 					 */
21367 					if (tcp->tcp_localnet &&
21368 					    !tcp->tcp_cork &&
21369 					    (nmpsz < roundup((mss >> 1), 64)))
21370 						break;
21371 				}
21372 
21373 				*xmit_tail = nmp;
21374 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21375 				/* Stash for rtt use later */
21376 				(*xmit_tail)->b_prev = local_time;
21377 				(*xmit_tail)->b_next =
21378 				    (mblk_t *)(uintptr_t)(*snxt - len);
21379 				mp1->b_cont = dupb(*xmit_tail);
21380 				mp1 = mp1->b_cont;
21381 
21382 				spill += nmpsz;
21383 				if (mp1 == NULL) {
21384 					*tail_unsent = spill;
21385 					freemsg(mp);
21386 					if (ire != NULL)
21387 						IRE_REFRELE(ire);
21388 					return (-1);	/* out_of_mem */
21389 				}
21390 			}
21391 
21392 			/* Trim back any surplus on the last mblk */
21393 			if (spill >= 0) {
21394 				mp1->b_wptr -= spill;
21395 				*tail_unsent = spill;
21396 			} else {
21397 				/*
21398 				 * We did not send everything we could in
21399 				 * order to remain within the b_cont limit.
21400 				 */
21401 				*usable -= spill;
21402 				*snxt += spill;
21403 				tcp->tcp_last_sent_len += spill;
21404 				UPDATE_MIB(&tcps->tcps_mib,
21405 				    tcpOutDataBytes, spill);
21406 				/*
21407 				 * Adjust the checksum
21408 				 */
21409 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21410 				sum += spill;
21411 				sum = (sum >> 16) + (sum & 0xFFFF);
21412 				U16_TO_ABE16(sum, tcph->th_sum);
21413 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21414 					sum = ntohs(
21415 					    ((ipha_t *)rptr)->ipha_length) +
21416 					    spill;
21417 					((ipha_t *)rptr)->ipha_length =
21418 					    htons(sum);
21419 				} else {
21420 					sum = ntohs(
21421 					    ((ip6_t *)rptr)->ip6_plen) +
21422 					    spill;
21423 					((ip6_t *)rptr)->ip6_plen =
21424 					    htons(sum);
21425 				}
21426 				*tail_unsent = 0;
21427 			}
21428 		}
21429 		if (tcp->tcp_ip_forward_progress) {
21430 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21431 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21432 			tcp->tcp_ip_forward_progress = B_FALSE;
21433 		}
21434 
21435 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21436 		if (do_lso_send) {
21437 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21438 			    num_lso_seg);
21439 			tcp->tcp_obsegs += num_lso_seg;
21440 
21441 			TCP_STAT(tcps, tcp_lso_times);
21442 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21443 		} else {
21444 			tcp_send_data(tcp, q, mp);
21445 			BUMP_LOCAL(tcp->tcp_obsegs);
21446 		}
21447 	}
21448 
21449 	if (ire != NULL)
21450 		IRE_REFRELE(ire);
21451 	return (0);
21452 }
21453 
21454 /* Unlink and return any mblk that looks like it contains a MDT info */
21455 static mblk_t *
21456 tcp_mdt_info_mp(mblk_t *mp)
21457 {
21458 	mblk_t	*prev_mp;
21459 
21460 	for (;;) {
21461 		prev_mp = mp;
21462 		/* no more to process? */
21463 		if ((mp = mp->b_cont) == NULL)
21464 			break;
21465 
21466 		switch (DB_TYPE(mp)) {
21467 		case M_CTL:
21468 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21469 				continue;
21470 			ASSERT(prev_mp != NULL);
21471 			prev_mp->b_cont = mp->b_cont;
21472 			mp->b_cont = NULL;
21473 			return (mp);
21474 		default:
21475 			break;
21476 		}
21477 	}
21478 	return (mp);
21479 }
21480 
21481 /* MDT info update routine, called when IP notifies us about MDT */
21482 static void
21483 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21484 {
21485 	boolean_t prev_state;
21486 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21487 
21488 	/*
21489 	 * IP is telling us to abort MDT on this connection?  We know
21490 	 * this because the capability is only turned off when IP
21491 	 * encounters some pathological cases, e.g. link-layer change
21492 	 * where the new driver doesn't support MDT, or in situation
21493 	 * where MDT usage on the link-layer has been switched off.
21494 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21495 	 * if the link-layer doesn't support MDT, and if it does, it
21496 	 * will indicate that the feature is to be turned on.
21497 	 */
21498 	prev_state = tcp->tcp_mdt;
21499 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21500 	if (!tcp->tcp_mdt && !first) {
21501 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21502 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21503 		    (void *)tcp->tcp_connp));
21504 	}
21505 
21506 	/*
21507 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21508 	 * so disable MDT otherwise.  The checks are done here
21509 	 * and in tcp_wput_data().
21510 	 */
21511 	if (tcp->tcp_mdt &&
21512 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21513 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21514 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21515 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21516 		tcp->tcp_mdt = B_FALSE;
21517 
21518 	if (tcp->tcp_mdt) {
21519 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21520 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21521 			    "version (%d), expected version is %d",
21522 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21523 			tcp->tcp_mdt = B_FALSE;
21524 			return;
21525 		}
21526 
21527 		/*
21528 		 * We need the driver to be able to handle at least three
21529 		 * spans per packet in order for tcp MDT to be utilized.
21530 		 * The first is for the header portion, while the rest are
21531 		 * needed to handle a packet that straddles across two
21532 		 * virtually non-contiguous buffers; a typical tcp packet
21533 		 * therefore consists of only two spans.  Note that we take
21534 		 * a zero as "don't care".
21535 		 */
21536 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21537 		    mdt_capab->ill_mdt_span_limit < 3) {
21538 			tcp->tcp_mdt = B_FALSE;
21539 			return;
21540 		}
21541 
21542 		/* a zero means driver wants default value */
21543 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21544 		    tcps->tcps_mdt_max_pbufs);
21545 		if (tcp->tcp_mdt_max_pld == 0)
21546 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21547 
21548 		/* ensure 32-bit alignment */
21549 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21550 		    mdt_capab->ill_mdt_hdr_head), 4);
21551 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21552 		    mdt_capab->ill_mdt_hdr_tail), 4);
21553 
21554 		if (!first && !prev_state) {
21555 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21556 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21557 			    (void *)tcp->tcp_connp));
21558 		}
21559 	}
21560 }
21561 
21562 /* Unlink and return any mblk that looks like it contains a LSO info */
21563 static mblk_t *
21564 tcp_lso_info_mp(mblk_t *mp)
21565 {
21566 	mblk_t	*prev_mp;
21567 
21568 	for (;;) {
21569 		prev_mp = mp;
21570 		/* no more to process? */
21571 		if ((mp = mp->b_cont) == NULL)
21572 			break;
21573 
21574 		switch (DB_TYPE(mp)) {
21575 		case M_CTL:
21576 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21577 				continue;
21578 			ASSERT(prev_mp != NULL);
21579 			prev_mp->b_cont = mp->b_cont;
21580 			mp->b_cont = NULL;
21581 			return (mp);
21582 		default:
21583 			break;
21584 		}
21585 	}
21586 
21587 	return (mp);
21588 }
21589 
21590 /* LSO info update routine, called when IP notifies us about LSO */
21591 static void
21592 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21593 {
21594 	tcp_stack_t *tcps = tcp->tcp_tcps;
21595 
21596 	/*
21597 	 * IP is telling us to abort LSO on this connection?  We know
21598 	 * this because the capability is only turned off when IP
21599 	 * encounters some pathological cases, e.g. link-layer change
21600 	 * where the new NIC/driver doesn't support LSO, or in situation
21601 	 * where LSO usage on the link-layer has been switched off.
21602 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21603 	 * if the link-layer doesn't support LSO, and if it does, it
21604 	 * will indicate that the feature is to be turned on.
21605 	 */
21606 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21607 	TCP_STAT(tcps, tcp_lso_enabled);
21608 
21609 	/*
21610 	 * We currently only support LSO on simple TCP/IPv4,
21611 	 * so disable LSO otherwise.  The checks are done here
21612 	 * and in tcp_wput_data().
21613 	 */
21614 	if (tcp->tcp_lso &&
21615 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21616 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21617 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21618 		tcp->tcp_lso = B_FALSE;
21619 		TCP_STAT(tcps, tcp_lso_disabled);
21620 	} else {
21621 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21622 		    lso_capab->ill_lso_max);
21623 	}
21624 }
21625 
21626 static void
21627 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21628 {
21629 	conn_t *connp = tcp->tcp_connp;
21630 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21631 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21632 
21633 	ASSERT(ire != NULL);
21634 
21635 	/*
21636 	 * We may be in the fastpath here, and although we essentially do
21637 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21638 	 * we try to keep things as brief as possible.  After all, these
21639 	 * are only best-effort checks, and we do more thorough ones prior
21640 	 * to calling tcp_send()/tcp_multisend().
21641 	 */
21642 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21643 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21644 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21645 	    !(ire->ire_flags & RTF_MULTIRT) &&
21646 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21647 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21648 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21649 			/* Cache the result */
21650 			connp->conn_lso_ok = B_TRUE;
21651 
21652 			ASSERT(ill->ill_lso_capab != NULL);
21653 			if (!ill->ill_lso_capab->ill_lso_on) {
21654 				ill->ill_lso_capab->ill_lso_on = 1;
21655 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21656 				    "LSO for interface %s\n", (void *)connp,
21657 				    ill->ill_name));
21658 			}
21659 			tcp_lso_update(tcp, ill->ill_lso_capab);
21660 		} else if (ipst->ips_ip_multidata_outbound &&
21661 		    ILL_MDT_CAPABLE(ill)) {
21662 			/* Cache the result */
21663 			connp->conn_mdt_ok = B_TRUE;
21664 
21665 			ASSERT(ill->ill_mdt_capab != NULL);
21666 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21667 				ill->ill_mdt_capab->ill_mdt_on = 1;
21668 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21669 				    "MDT for interface %s\n", (void *)connp,
21670 				    ill->ill_name));
21671 			}
21672 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21673 		}
21674 	}
21675 
21676 	/*
21677 	 * The goal is to reduce the number of generated tcp segments by
21678 	 * setting the maxpsz multiplier to 0; this will have an affect on
21679 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21680 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21681 	 * of outbound segments and incoming ACKs, thus allowing for better
21682 	 * network and system performance.  In contrast the legacy behavior
21683 	 * may result in sending less than SMSS size, because the last mblk
21684 	 * for some packets may have more data than needed to make up SMSS,
21685 	 * and the legacy code refused to "split" it.
21686 	 *
21687 	 * We apply the new behavior on following situations:
21688 	 *
21689 	 *   1) Loopback connections,
21690 	 *   2) Connections in which the remote peer is not on local subnet,
21691 	 *   3) Local subnet connections over the bge interface (see below).
21692 	 *
21693 	 * Ideally, we would like this behavior to apply for interfaces other
21694 	 * than bge.  However, doing so would negatively impact drivers which
21695 	 * perform dynamic mapping and unmapping of DMA resources, which are
21696 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21697 	 * packet will be generated by tcp).  The bge driver does not suffer
21698 	 * from this, as it copies the mblks into pre-mapped buffers, and
21699 	 * therefore does not require more I/O resources than before.
21700 	 *
21701 	 * Otherwise, this behavior is present on all network interfaces when
21702 	 * the destination endpoint is non-local, since reducing the number
21703 	 * of packets in general is good for the network.
21704 	 *
21705 	 * TODO We need to remove this hard-coded conditional for bge once
21706 	 *	a better "self-tuning" mechanism, or a way to comprehend
21707 	 *	the driver transmit strategy is devised.  Until the solution
21708 	 *	is found and well understood, we live with this hack.
21709 	 */
21710 	if (!tcp_static_maxpsz &&
21711 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21712 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21713 		/* override the default value */
21714 		tcp->tcp_maxpsz = 0;
21715 
21716 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21717 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21718 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21719 	}
21720 
21721 	/* set the stream head parameters accordingly */
21722 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21723 }
21724 
21725 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21726 static void
21727 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21728 {
21729 	uchar_t	fval = *mp->b_rptr;
21730 	mblk_t	*tail;
21731 	queue_t	*q = tcp->tcp_wq;
21732 
21733 	/* TODO: How should flush interact with urgent data? */
21734 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21735 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21736 		/*
21737 		 * Flush only data that has not yet been put on the wire.  If
21738 		 * we flush data that we have already transmitted, life, as we
21739 		 * know it, may come to an end.
21740 		 */
21741 		tail = tcp->tcp_xmit_tail;
21742 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21743 		tcp->tcp_xmit_tail_unsent = 0;
21744 		tcp->tcp_unsent = 0;
21745 		if (tail->b_wptr != tail->b_rptr)
21746 			tail = tail->b_cont;
21747 		if (tail) {
21748 			mblk_t **excess = &tcp->tcp_xmit_head;
21749 			for (;;) {
21750 				mblk_t *mp1 = *excess;
21751 				if (mp1 == tail)
21752 					break;
21753 				tcp->tcp_xmit_tail = mp1;
21754 				tcp->tcp_xmit_last = mp1;
21755 				excess = &mp1->b_cont;
21756 			}
21757 			*excess = NULL;
21758 			tcp_close_mpp(&tail);
21759 			if (tcp->tcp_snd_zcopy_aware)
21760 				tcp_zcopy_notify(tcp);
21761 		}
21762 		/*
21763 		 * We have no unsent data, so unsent must be less than
21764 		 * tcp_xmit_lowater, so re-enable flow.
21765 		 */
21766 		mutex_enter(&tcp->tcp_non_sq_lock);
21767 		if (tcp->tcp_flow_stopped) {
21768 			tcp_clrqfull(tcp);
21769 		}
21770 		mutex_exit(&tcp->tcp_non_sq_lock);
21771 	}
21772 	/*
21773 	 * TODO: you can't just flush these, you have to increase rwnd for one
21774 	 * thing.  For another, how should urgent data interact?
21775 	 */
21776 	if (fval & FLUSHR) {
21777 		*mp->b_rptr = fval & ~FLUSHW;
21778 		/* XXX */
21779 		qreply(q, mp);
21780 		return;
21781 	}
21782 	freemsg(mp);
21783 }
21784 
21785 /*
21786  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21787  * messages.
21788  */
21789 static void
21790 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21791 {
21792 	mblk_t	*mp1;
21793 	STRUCT_HANDLE(strbuf, sb);
21794 	uint16_t port;
21795 	queue_t 	*q = tcp->tcp_wq;
21796 	in6_addr_t	v6addr;
21797 	ipaddr_t	v4addr;
21798 	uint32_t	flowinfo = 0;
21799 	int		addrlen;
21800 
21801 	/* Make sure it is one of ours. */
21802 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21803 	case TI_GETMYNAME:
21804 	case TI_GETPEERNAME:
21805 		break;
21806 	default:
21807 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21808 		return;
21809 	}
21810 	switch (mi_copy_state(q, mp, &mp1)) {
21811 	case -1:
21812 		return;
21813 	case MI_COPY_CASE(MI_COPY_IN, 1):
21814 		break;
21815 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21816 		/* Copy out the strbuf. */
21817 		mi_copyout(q, mp);
21818 		return;
21819 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21820 		/* All done. */
21821 		mi_copy_done(q, mp, 0);
21822 		return;
21823 	default:
21824 		mi_copy_done(q, mp, EPROTO);
21825 		return;
21826 	}
21827 	/* Check alignment of the strbuf */
21828 	if (!OK_32PTR(mp1->b_rptr)) {
21829 		mi_copy_done(q, mp, EINVAL);
21830 		return;
21831 	}
21832 
21833 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21834 	    (void *)mp1->b_rptr);
21835 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21836 
21837 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21838 		mi_copy_done(q, mp, EINVAL);
21839 		return;
21840 	}
21841 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21842 	case TI_GETMYNAME:
21843 		if (tcp->tcp_family == AF_INET) {
21844 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21845 				v4addr = tcp->tcp_ipha->ipha_src;
21846 			} else {
21847 				/* can't return an address in this case */
21848 				v4addr = 0;
21849 			}
21850 		} else {
21851 			/* tcp->tcp_family == AF_INET6 */
21852 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21853 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21854 				    &v6addr);
21855 			} else {
21856 				v6addr = tcp->tcp_ip6h->ip6_src;
21857 			}
21858 		}
21859 		port = tcp->tcp_lport;
21860 		break;
21861 	case TI_GETPEERNAME:
21862 		if (tcp->tcp_family == AF_INET) {
21863 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21864 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21865 				    v4addr);
21866 			} else {
21867 				/* can't return an address in this case */
21868 				v4addr = 0;
21869 			}
21870 		} else {
21871 			/* tcp->tcp_family == AF_INET6) */
21872 			v6addr = tcp->tcp_remote_v6;
21873 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21874 				/*
21875 				 * No flowinfo if tcp->tcp_ipversion is v4.
21876 				 *
21877 				 * flowinfo was already initialized to zero
21878 				 * where it was declared above, so only
21879 				 * set it if ipversion is v6.
21880 				 */
21881 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21882 				    ~IPV6_VERS_AND_FLOW_MASK;
21883 			}
21884 		}
21885 		port = tcp->tcp_fport;
21886 		break;
21887 	default:
21888 		mi_copy_done(q, mp, EPROTO);
21889 		return;
21890 	}
21891 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21892 	if (!mp1)
21893 		return;
21894 
21895 	if (tcp->tcp_family == AF_INET) {
21896 		sin_t *sin;
21897 
21898 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21899 		sin = (sin_t *)mp1->b_rptr;
21900 		mp1->b_wptr = (uchar_t *)&sin[1];
21901 		*sin = sin_null;
21902 		sin->sin_family = AF_INET;
21903 		sin->sin_addr.s_addr = v4addr;
21904 		sin->sin_port = port;
21905 	} else {
21906 		/* tcp->tcp_family == AF_INET6 */
21907 		sin6_t *sin6;
21908 
21909 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21910 		sin6 = (sin6_t *)mp1->b_rptr;
21911 		mp1->b_wptr = (uchar_t *)&sin6[1];
21912 		*sin6 = sin6_null;
21913 		sin6->sin6_family = AF_INET6;
21914 		sin6->sin6_flowinfo = flowinfo;
21915 		sin6->sin6_addr = v6addr;
21916 		sin6->sin6_port = port;
21917 	}
21918 	/* Copy out the address */
21919 	mi_copyout(q, mp);
21920 }
21921 
21922 /*
21923  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21924  * messages.
21925  */
21926 /* ARGSUSED */
21927 static void
21928 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21929 {
21930 	conn_t 	*connp = (conn_t *)arg;
21931 	tcp_t	*tcp = connp->conn_tcp;
21932 	queue_t	*q = tcp->tcp_wq;
21933 	struct iocblk	*iocp;
21934 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21935 
21936 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21937 	/*
21938 	 * Try and ASSERT the minimum possible references on the
21939 	 * conn early enough. Since we are executing on write side,
21940 	 * the connection is obviously not detached and that means
21941 	 * there is a ref each for TCP and IP. Since we are behind
21942 	 * the squeue, the minimum references needed are 3. If the
21943 	 * conn is in classifier hash list, there should be an
21944 	 * extra ref for that (we check both the possibilities).
21945 	 */
21946 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21947 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21948 
21949 	iocp = (struct iocblk *)mp->b_rptr;
21950 	switch (iocp->ioc_cmd) {
21951 	case TCP_IOC_DEFAULT_Q:
21952 		/* Wants to be the default wq. */
21953 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21954 			iocp->ioc_error = EPERM;
21955 			iocp->ioc_count = 0;
21956 			mp->b_datap->db_type = M_IOCACK;
21957 			qreply(q, mp);
21958 			return;
21959 		}
21960 		tcp_def_q_set(tcp, mp);
21961 		return;
21962 	case _SIOCSOCKFALLBACK:
21963 		/*
21964 		 * Either sockmod is about to be popped and the socket
21965 		 * would now be treated as a plain stream, or a module
21966 		 * is about to be pushed so we could no longer use read-
21967 		 * side synchronous streams for fused loopback tcp.
21968 		 * Drain any queued data and disable direct sockfs
21969 		 * interface from now on.
21970 		 */
21971 		if (!tcp->tcp_issocket) {
21972 			DB_TYPE(mp) = M_IOCNAK;
21973 			iocp->ioc_error = EINVAL;
21974 		} else {
21975 #ifdef	_ILP32
21976 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21977 #else
21978 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21979 #endif
21980 			/*
21981 			 * Insert this socket into the acceptor hash.
21982 			 * We might need it for T_CONN_RES message
21983 			 */
21984 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21985 
21986 			if (tcp->tcp_fused) {
21987 				/*
21988 				 * This is a fused loopback tcp; disable
21989 				 * read-side synchronous streams interface
21990 				 * and drain any queued data.  It is okay
21991 				 * to do this for non-synchronous streams
21992 				 * fused tcp as well.
21993 				 */
21994 				tcp_fuse_disable_pair(tcp, B_FALSE);
21995 			}
21996 			tcp->tcp_issocket = B_FALSE;
21997 			TCP_STAT(tcps, tcp_sock_fallback);
21998 
21999 			DB_TYPE(mp) = M_IOCACK;
22000 			iocp->ioc_error = 0;
22001 		}
22002 		iocp->ioc_count = 0;
22003 		iocp->ioc_rval = 0;
22004 		qreply(q, mp);
22005 		return;
22006 	}
22007 	CALL_IP_WPUT(connp, q, mp);
22008 }
22009 
22010 /*
22011  * This routine is called by tcp_wput() to handle all TPI requests.
22012  */
22013 /* ARGSUSED */
22014 static void
22015 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22016 {
22017 	conn_t 	*connp = (conn_t *)arg;
22018 	tcp_t	*tcp = connp->conn_tcp;
22019 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22020 	uchar_t *rptr;
22021 	t_scalar_t type;
22022 	int len;
22023 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22024 
22025 	/*
22026 	 * Try and ASSERT the minimum possible references on the
22027 	 * conn early enough. Since we are executing on write side,
22028 	 * the connection is obviously not detached and that means
22029 	 * there is a ref each for TCP and IP. Since we are behind
22030 	 * the squeue, the minimum references needed are 3. If the
22031 	 * conn is in classifier hash list, there should be an
22032 	 * extra ref for that (we check both the possibilities).
22033 	 */
22034 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22035 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22036 
22037 	rptr = mp->b_rptr;
22038 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22039 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22040 		type = ((union T_primitives *)rptr)->type;
22041 		if (type == T_EXDATA_REQ) {
22042 			uint32_t msize = msgdsize(mp->b_cont);
22043 
22044 			len = msize - 1;
22045 			if (len < 0) {
22046 				freemsg(mp);
22047 				return;
22048 			}
22049 			/*
22050 			 * Try to force urgent data out on the wire.
22051 			 * Even if we have unsent data this will
22052 			 * at least send the urgent flag.
22053 			 * XXX does not handle more flag correctly.
22054 			 */
22055 			len += tcp->tcp_unsent;
22056 			len += tcp->tcp_snxt;
22057 			tcp->tcp_urg = len;
22058 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22059 
22060 			/* Bypass tcp protocol for fused tcp loopback */
22061 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22062 				return;
22063 		} else if (type != T_DATA_REQ) {
22064 			goto non_urgent_data;
22065 		}
22066 		/* TODO: options, flags, ... from user */
22067 		/* Set length to zero for reclamation below */
22068 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22069 		freeb(mp);
22070 		return;
22071 	} else {
22072 		if (tcp->tcp_debug) {
22073 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22074 			    "tcp_wput_proto, dropping one...");
22075 		}
22076 		freemsg(mp);
22077 		return;
22078 	}
22079 
22080 non_urgent_data:
22081 
22082 	switch ((int)tprim->type) {
22083 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22084 		/*
22085 		 * save the kssl_ent_t from the next block, and convert this
22086 		 * back to a normal bind_req.
22087 		 */
22088 		if (mp->b_cont != NULL) {
22089 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22090 
22091 			if (tcp->tcp_kssl_ent != NULL) {
22092 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22093 				    KSSL_NO_PROXY);
22094 				tcp->tcp_kssl_ent = NULL;
22095 			}
22096 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22097 			    sizeof (kssl_ent_t));
22098 			kssl_hold_ent(tcp->tcp_kssl_ent);
22099 			freemsg(mp->b_cont);
22100 			mp->b_cont = NULL;
22101 		}
22102 		tprim->type = T_BIND_REQ;
22103 
22104 	/* FALLTHROUGH */
22105 	case O_T_BIND_REQ:	/* bind request */
22106 	case T_BIND_REQ:	/* new semantics bind request */
22107 		tcp_bind(tcp, mp);
22108 		break;
22109 	case T_UNBIND_REQ:	/* unbind request */
22110 		tcp_unbind(tcp, mp);
22111 		break;
22112 	case O_T_CONN_RES:	/* old connection response XXX */
22113 	case T_CONN_RES:	/* connection response */
22114 		tcp_accept(tcp, mp);
22115 		break;
22116 	case T_CONN_REQ:	/* connection request */
22117 		tcp_connect(tcp, mp);
22118 		break;
22119 	case T_DISCON_REQ:	/* disconnect request */
22120 		tcp_disconnect(tcp, mp);
22121 		break;
22122 	case T_CAPABILITY_REQ:
22123 		tcp_capability_req(tcp, mp);	/* capability request */
22124 		break;
22125 	case T_INFO_REQ:	/* information request */
22126 		tcp_info_req(tcp, mp);
22127 		break;
22128 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22129 		/* Only IP is allowed to return meaningful value */
22130 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22131 		break;
22132 	case T_OPTMGMT_REQ:
22133 		/*
22134 		 * Note:  no support for snmpcom_req() through new
22135 		 * T_OPTMGMT_REQ. See comments in ip.c
22136 		 */
22137 		/* Only IP is allowed to return meaningful value */
22138 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22139 		break;
22140 
22141 	case T_UNITDATA_REQ:	/* unitdata request */
22142 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22143 		break;
22144 	case T_ORDREL_REQ:	/* orderly release req */
22145 		freemsg(mp);
22146 
22147 		if (tcp->tcp_fused)
22148 			tcp_unfuse(tcp);
22149 
22150 		if (tcp_xmit_end(tcp) != 0) {
22151 			/*
22152 			 * We were crossing FINs and got a reset from
22153 			 * the other side. Just ignore it.
22154 			 */
22155 			if (tcp->tcp_debug) {
22156 				(void) strlog(TCP_MOD_ID, 0, 1,
22157 				    SL_ERROR|SL_TRACE,
22158 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22159 				    "state %s",
22160 				    tcp_display(tcp, NULL,
22161 				    DISP_ADDR_AND_PORT));
22162 			}
22163 		}
22164 		break;
22165 	case T_ADDR_REQ:
22166 		tcp_addr_req(tcp, mp);
22167 		break;
22168 	default:
22169 		if (tcp->tcp_debug) {
22170 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22171 			    "tcp_wput_proto, bogus TPI msg, type %d",
22172 			    tprim->type);
22173 		}
22174 		/*
22175 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22176 		 * to recover.
22177 		 */
22178 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22179 		break;
22180 	}
22181 }
22182 
22183 /*
22184  * The TCP write service routine should never be called...
22185  */
22186 /* ARGSUSED */
22187 static void
22188 tcp_wsrv(queue_t *q)
22189 {
22190 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22191 
22192 	TCP_STAT(tcps, tcp_wsrv_called);
22193 }
22194 
22195 /* Non overlapping byte exchanger */
22196 static void
22197 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22198 {
22199 	uchar_t	uch;
22200 
22201 	while (len-- > 0) {
22202 		uch = a[len];
22203 		a[len] = b[len];
22204 		b[len] = uch;
22205 	}
22206 }
22207 
22208 /*
22209  * Send out a control packet on the tcp connection specified.  This routine
22210  * is typically called where we need a simple ACK or RST generated.
22211  */
22212 static void
22213 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22214 {
22215 	uchar_t		*rptr;
22216 	tcph_t		*tcph;
22217 	ipha_t		*ipha = NULL;
22218 	ip6_t		*ip6h = NULL;
22219 	uint32_t	sum;
22220 	int		tcp_hdr_len;
22221 	int		tcp_ip_hdr_len;
22222 	mblk_t		*mp;
22223 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22224 
22225 	/*
22226 	 * Save sum for use in source route later.
22227 	 */
22228 	ASSERT(tcp != NULL);
22229 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22230 	tcp_hdr_len = tcp->tcp_hdr_len;
22231 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22232 
22233 	/* If a text string is passed in with the request, pass it to strlog. */
22234 	if (str != NULL && tcp->tcp_debug) {
22235 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22236 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22237 		    str, seq, ack, ctl);
22238 	}
22239 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22240 	    BPRI_MED);
22241 	if (mp == NULL) {
22242 		return;
22243 	}
22244 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22245 	mp->b_rptr = rptr;
22246 	mp->b_wptr = &rptr[tcp_hdr_len];
22247 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22248 
22249 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22250 		ipha = (ipha_t *)rptr;
22251 		ipha->ipha_length = htons(tcp_hdr_len);
22252 	} else {
22253 		ip6h = (ip6_t *)rptr;
22254 		ASSERT(tcp != NULL);
22255 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22256 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22257 	}
22258 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22259 	tcph->th_flags[0] = (uint8_t)ctl;
22260 	if (ctl & TH_RST) {
22261 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22262 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22263 		/*
22264 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22265 		 */
22266 		if (tcp->tcp_snd_ts_ok &&
22267 		    tcp->tcp_state > TCPS_SYN_SENT) {
22268 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22269 			*(mp->b_wptr) = TCPOPT_EOL;
22270 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22271 				ipha->ipha_length = htons(tcp_hdr_len -
22272 				    TCPOPT_REAL_TS_LEN);
22273 			} else {
22274 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22275 				    TCPOPT_REAL_TS_LEN);
22276 			}
22277 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22278 			sum -= TCPOPT_REAL_TS_LEN;
22279 		}
22280 	}
22281 	if (ctl & TH_ACK) {
22282 		if (tcp->tcp_snd_ts_ok) {
22283 			U32_TO_BE32(lbolt,
22284 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22285 			U32_TO_BE32(tcp->tcp_ts_recent,
22286 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22287 		}
22288 
22289 		/* Update the latest receive window size in TCP header. */
22290 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22291 		    tcph->th_win);
22292 		tcp->tcp_rack = ack;
22293 		tcp->tcp_rack_cnt = 0;
22294 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22295 	}
22296 	BUMP_LOCAL(tcp->tcp_obsegs);
22297 	U32_TO_BE32(seq, tcph->th_seq);
22298 	U32_TO_BE32(ack, tcph->th_ack);
22299 	/*
22300 	 * Include the adjustment for a source route if any.
22301 	 */
22302 	sum = (sum >> 16) + (sum & 0xFFFF);
22303 	U16_TO_BE16(sum, tcph->th_sum);
22304 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22305 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22306 }
22307 
22308 /*
22309  * If this routine returns B_TRUE, TCP can generate a RST in response
22310  * to a segment.  If it returns B_FALSE, TCP should not respond.
22311  */
22312 static boolean_t
22313 tcp_send_rst_chk(tcp_stack_t *tcps)
22314 {
22315 	clock_t	now;
22316 
22317 	/*
22318 	 * TCP needs to protect itself from generating too many RSTs.
22319 	 * This can be a DoS attack by sending us random segments
22320 	 * soliciting RSTs.
22321 	 *
22322 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22323 	 * in each 1 second interval.  In this way, TCP still generate
22324 	 * RSTs in normal cases but when under attack, the impact is
22325 	 * limited.
22326 	 */
22327 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22328 		now = lbolt;
22329 		/* lbolt can wrap around. */
22330 		if ((tcps->tcps_last_rst_intrvl > now) ||
22331 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22332 		    1*SECONDS)) {
22333 			tcps->tcps_last_rst_intrvl = now;
22334 			tcps->tcps_rst_cnt = 1;
22335 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22336 			return (B_FALSE);
22337 		}
22338 	}
22339 	return (B_TRUE);
22340 }
22341 
22342 /*
22343  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22344  */
22345 static void
22346 tcp_ip_ire_mark_advice(tcp_t *tcp)
22347 {
22348 	mblk_t *mp;
22349 	ipic_t *ipic;
22350 
22351 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22352 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22353 		    &ipic);
22354 	} else {
22355 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22356 		    &ipic);
22357 	}
22358 	if (mp == NULL)
22359 		return;
22360 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22361 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22362 }
22363 
22364 /*
22365  * Return an IP advice ioctl mblk and set ipic to be the pointer
22366  * to the advice structure.
22367  */
22368 static mblk_t *
22369 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22370 {
22371 	struct iocblk *ioc;
22372 	mblk_t *mp, *mp1;
22373 
22374 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22375 	if (mp == NULL)
22376 		return (NULL);
22377 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22378 	*ipic = (ipic_t *)mp->b_rptr;
22379 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22380 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22381 
22382 	bcopy(addr, *ipic + 1, addr_len);
22383 
22384 	(*ipic)->ipic_addr_length = addr_len;
22385 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22386 
22387 	mp1 = mkiocb(IP_IOCTL);
22388 	if (mp1 == NULL) {
22389 		freemsg(mp);
22390 		return (NULL);
22391 	}
22392 	mp1->b_cont = mp;
22393 	ioc = (struct iocblk *)mp1->b_rptr;
22394 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22395 
22396 	return (mp1);
22397 }
22398 
22399 /*
22400  * Generate a reset based on an inbound packet for which there is no active
22401  * tcp state that we can find.
22402  *
22403  * IPSEC NOTE : Try to send the reply with the same protection as it came
22404  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22405  * the packet will go out at the same level of protection as it came in by
22406  * converting the IPSEC_IN to IPSEC_OUT.
22407  */
22408 static void
22409 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22410     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22411     tcp_stack_t *tcps)
22412 {
22413 	ipha_t		*ipha = NULL;
22414 	ip6_t		*ip6h = NULL;
22415 	ushort_t	len;
22416 	tcph_t		*tcph;
22417 	int		i;
22418 	mblk_t		*ipsec_mp;
22419 	boolean_t	mctl_present;
22420 	ipic_t		*ipic;
22421 	ipaddr_t	v4addr;
22422 	in6_addr_t	v6addr;
22423 	int		addr_len;
22424 	void		*addr;
22425 	queue_t		*q = tcps->tcps_g_q;
22426 	tcp_t		*tcp;
22427 	cred_t		*cr;
22428 	mblk_t		*nmp;
22429 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22430 
22431 	if (tcps->tcps_g_q == NULL) {
22432 		/*
22433 		 * For non-zero stackids the default queue isn't created
22434 		 * until the first open, thus there can be a need to send
22435 		 * a reset before then. But we can't do that, hence we just
22436 		 * drop the packet. Later during boot, when the default queue
22437 		 * has been setup, a retransmitted packet from the peer
22438 		 * will result in a reset.
22439 		 */
22440 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22441 		    GLOBAL_NETSTACKID);
22442 		freemsg(mp);
22443 		return;
22444 	}
22445 
22446 	tcp = Q_TO_TCP(q);
22447 
22448 	if (!tcp_send_rst_chk(tcps)) {
22449 		tcps->tcps_rst_unsent++;
22450 		freemsg(mp);
22451 		return;
22452 	}
22453 
22454 	if (mp->b_datap->db_type == M_CTL) {
22455 		ipsec_mp = mp;
22456 		mp = mp->b_cont;
22457 		mctl_present = B_TRUE;
22458 	} else {
22459 		ipsec_mp = mp;
22460 		mctl_present = B_FALSE;
22461 	}
22462 
22463 	if (str && q && tcps->tcps_dbg) {
22464 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22465 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22466 		    "flags 0x%x",
22467 		    str, seq, ack, ctl);
22468 	}
22469 	if (mp->b_datap->db_ref != 1) {
22470 		mblk_t *mp1 = copyb(mp);
22471 		freemsg(mp);
22472 		mp = mp1;
22473 		if (!mp) {
22474 			if (mctl_present)
22475 				freeb(ipsec_mp);
22476 			return;
22477 		} else {
22478 			if (mctl_present) {
22479 				ipsec_mp->b_cont = mp;
22480 			} else {
22481 				ipsec_mp = mp;
22482 			}
22483 		}
22484 	} else if (mp->b_cont) {
22485 		freemsg(mp->b_cont);
22486 		mp->b_cont = NULL;
22487 	}
22488 	/*
22489 	 * We skip reversing source route here.
22490 	 * (for now we replace all IP options with EOL)
22491 	 */
22492 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22493 		ipha = (ipha_t *)mp->b_rptr;
22494 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22495 			mp->b_rptr[i] = IPOPT_EOL;
22496 		/*
22497 		 * Make sure that src address isn't flagrantly invalid.
22498 		 * Not all broadcast address checking for the src address
22499 		 * is possible, since we don't know the netmask of the src
22500 		 * addr.  No check for destination address is done, since
22501 		 * IP will not pass up a packet with a broadcast dest
22502 		 * address to TCP.  Similar checks are done below for IPv6.
22503 		 */
22504 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22505 		    CLASSD(ipha->ipha_src)) {
22506 			freemsg(ipsec_mp);
22507 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22508 			return;
22509 		}
22510 	} else {
22511 		ip6h = (ip6_t *)mp->b_rptr;
22512 
22513 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22514 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22515 			freemsg(ipsec_mp);
22516 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22517 			return;
22518 		}
22519 
22520 		/* Remove any extension headers assuming partial overlay */
22521 		if (ip_hdr_len > IPV6_HDR_LEN) {
22522 			uint8_t *to;
22523 
22524 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22525 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22526 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22527 			ip_hdr_len = IPV6_HDR_LEN;
22528 			ip6h = (ip6_t *)mp->b_rptr;
22529 			ip6h->ip6_nxt = IPPROTO_TCP;
22530 		}
22531 	}
22532 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22533 	if (tcph->th_flags[0] & TH_RST) {
22534 		freemsg(ipsec_mp);
22535 		return;
22536 	}
22537 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22538 	len = ip_hdr_len + sizeof (tcph_t);
22539 	mp->b_wptr = &mp->b_rptr[len];
22540 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22541 		ipha->ipha_length = htons(len);
22542 		/* Swap addresses */
22543 		v4addr = ipha->ipha_src;
22544 		ipha->ipha_src = ipha->ipha_dst;
22545 		ipha->ipha_dst = v4addr;
22546 		ipha->ipha_ident = 0;
22547 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22548 		addr_len = IP_ADDR_LEN;
22549 		addr = &v4addr;
22550 	} else {
22551 		/* No ip6i_t in this case */
22552 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22553 		/* Swap addresses */
22554 		v6addr = ip6h->ip6_src;
22555 		ip6h->ip6_src = ip6h->ip6_dst;
22556 		ip6h->ip6_dst = v6addr;
22557 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22558 		addr_len = IPV6_ADDR_LEN;
22559 		addr = &v6addr;
22560 	}
22561 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22562 	U32_TO_BE32(ack, tcph->th_ack);
22563 	U32_TO_BE32(seq, tcph->th_seq);
22564 	U16_TO_BE16(0, tcph->th_win);
22565 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22566 	tcph->th_flags[0] = (uint8_t)ctl;
22567 	if (ctl & TH_RST) {
22568 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22569 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22570 	}
22571 
22572 	/* IP trusts us to set up labels when required. */
22573 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22574 	    crgetlabel(cr) != NULL) {
22575 		int err, adjust;
22576 
22577 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22578 			err = tsol_check_label(cr, &mp, &adjust,
22579 			    tcp->tcp_connp->conn_mac_exempt,
22580 			    tcps->tcps_netstack->netstack_ip);
22581 		else
22582 			err = tsol_check_label_v6(cr, &mp, &adjust,
22583 			    tcp->tcp_connp->conn_mac_exempt,
22584 			    tcps->tcps_netstack->netstack_ip);
22585 		if (mctl_present)
22586 			ipsec_mp->b_cont = mp;
22587 		else
22588 			ipsec_mp = mp;
22589 		if (err != 0) {
22590 			freemsg(ipsec_mp);
22591 			return;
22592 		}
22593 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22594 			ipha = (ipha_t *)mp->b_rptr;
22595 			adjust += ntohs(ipha->ipha_length);
22596 			ipha->ipha_length = htons(adjust);
22597 		} else {
22598 			ip6h = (ip6_t *)mp->b_rptr;
22599 		}
22600 	}
22601 
22602 	if (mctl_present) {
22603 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22604 
22605 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22606 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22607 			return;
22608 		}
22609 	}
22610 	if (zoneid == ALL_ZONES)
22611 		zoneid = GLOBAL_ZONEID;
22612 
22613 	/* Add the zoneid so ip_output routes it properly */
22614 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22615 		freemsg(ipsec_mp);
22616 		return;
22617 	}
22618 	ipsec_mp = nmp;
22619 
22620 	/*
22621 	 * NOTE:  one might consider tracing a TCP packet here, but
22622 	 * this function has no active TCP state and no tcp structure
22623 	 * that has a trace buffer.  If we traced here, we would have
22624 	 * to keep a local trace buffer in tcp_record_trace().
22625 	 *
22626 	 * TSol note: The mblk that contains the incoming packet was
22627 	 * reused by tcp_xmit_listener_reset, so it already contains
22628 	 * the right credentials and we don't need to call mblk_setcred.
22629 	 * Also the conn's cred is not right since it is associated
22630 	 * with tcps_g_q.
22631 	 */
22632 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22633 
22634 	/*
22635 	 * Tell IP to mark the IRE used for this destination temporary.
22636 	 * This way, we can limit our exposure to DoS attack because IP
22637 	 * creates an IRE for each destination.  If there are too many,
22638 	 * the time to do any routing lookup will be extremely long.  And
22639 	 * the lookup can be in interrupt context.
22640 	 *
22641 	 * Note that in normal circumstances, this marking should not
22642 	 * affect anything.  It would be nice if only 1 message is
22643 	 * needed to inform IP that the IRE created for this RST should
22644 	 * not be added to the cache table.  But there is currently
22645 	 * not such communication mechanism between TCP and IP.  So
22646 	 * the best we can do now is to send the advice ioctl to IP
22647 	 * to mark the IRE temporary.
22648 	 */
22649 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22650 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22651 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22652 	}
22653 }
22654 
22655 /*
22656  * Initiate closedown sequence on an active connection.  (May be called as
22657  * writer.)  Return value zero for OK return, non-zero for error return.
22658  */
22659 static int
22660 tcp_xmit_end(tcp_t *tcp)
22661 {
22662 	ipic_t	*ipic;
22663 	mblk_t	*mp;
22664 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22665 
22666 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22667 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22668 		/*
22669 		 * Invalid state, only states TCPS_SYN_RCVD,
22670 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22671 		 */
22672 		return (-1);
22673 	}
22674 
22675 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22676 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22677 	/*
22678 	 * If there is nothing more unsent, send the FIN now.
22679 	 * Otherwise, it will go out with the last segment.
22680 	 */
22681 	if (tcp->tcp_unsent == 0) {
22682 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22683 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22684 
22685 		if (mp) {
22686 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22687 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22688 		} else {
22689 			/*
22690 			 * Couldn't allocate msg.  Pretend we got it out.
22691 			 * Wait for rexmit timeout.
22692 			 */
22693 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22694 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22695 		}
22696 
22697 		/*
22698 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22699 		 * changed.
22700 		 */
22701 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22702 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22703 		}
22704 	} else {
22705 		/*
22706 		 * If tcp->tcp_cork is set, then the data will not get sent,
22707 		 * so we have to check that and unset it first.
22708 		 */
22709 		if (tcp->tcp_cork)
22710 			tcp->tcp_cork = B_FALSE;
22711 		tcp_wput_data(tcp, NULL, B_FALSE);
22712 	}
22713 
22714 	/*
22715 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22716 	 * is 0, don't update the cache.
22717 	 */
22718 	if (tcps->tcps_rtt_updates == 0 ||
22719 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22720 		return (0);
22721 
22722 	/*
22723 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22724 	 * different from the destination.
22725 	 */
22726 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22727 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22728 			return (0);
22729 		}
22730 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22731 		    &ipic);
22732 	} else {
22733 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22734 		    &tcp->tcp_ip6h->ip6_dst))) {
22735 			return (0);
22736 		}
22737 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22738 		    &ipic);
22739 	}
22740 
22741 	/* Record route attributes in the IRE for use by future connections. */
22742 	if (mp == NULL)
22743 		return (0);
22744 
22745 	/*
22746 	 * We do not have a good algorithm to update ssthresh at this time.
22747 	 * So don't do any update.
22748 	 */
22749 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22750 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22751 
22752 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22753 	return (0);
22754 }
22755 
22756 /*
22757  * Generate a "no listener here" RST in response to an "unknown" segment.
22758  * Note that we are reusing the incoming mp to construct the outgoing
22759  * RST.
22760  */
22761 void
22762 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22763     tcp_stack_t *tcps)
22764 {
22765 	uchar_t		*rptr;
22766 	uint32_t	seg_len;
22767 	tcph_t		*tcph;
22768 	uint32_t	seg_seq;
22769 	uint32_t	seg_ack;
22770 	uint_t		flags;
22771 	mblk_t		*ipsec_mp;
22772 	ipha_t 		*ipha;
22773 	ip6_t 		*ip6h;
22774 	boolean_t	mctl_present = B_FALSE;
22775 	boolean_t	check = B_TRUE;
22776 	boolean_t	policy_present;
22777 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22778 
22779 	TCP_STAT(tcps, tcp_no_listener);
22780 
22781 	ipsec_mp = mp;
22782 
22783 	if (mp->b_datap->db_type == M_CTL) {
22784 		ipsec_in_t *ii;
22785 
22786 		mctl_present = B_TRUE;
22787 		mp = mp->b_cont;
22788 
22789 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22790 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22791 		if (ii->ipsec_in_dont_check) {
22792 			check = B_FALSE;
22793 			if (!ii->ipsec_in_secure) {
22794 				freeb(ipsec_mp);
22795 				mctl_present = B_FALSE;
22796 				ipsec_mp = mp;
22797 			}
22798 		}
22799 	}
22800 
22801 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22802 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22803 		ipha = (ipha_t *)mp->b_rptr;
22804 		ip6h = NULL;
22805 	} else {
22806 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22807 		ipha = NULL;
22808 		ip6h = (ip6_t *)mp->b_rptr;
22809 	}
22810 
22811 	if (check && policy_present) {
22812 		/*
22813 		 * The conn_t parameter is NULL because we already know
22814 		 * nobody's home.
22815 		 */
22816 		ipsec_mp = ipsec_check_global_policy(
22817 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22818 		    tcps->tcps_netstack);
22819 		if (ipsec_mp == NULL)
22820 			return;
22821 	}
22822 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22823 		DTRACE_PROBE2(
22824 		    tx__ip__log__error__nolistener__tcp,
22825 		    char *, "Could not reply with RST to mp(1)",
22826 		    mblk_t *, mp);
22827 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22828 		freemsg(ipsec_mp);
22829 		return;
22830 	}
22831 
22832 	rptr = mp->b_rptr;
22833 
22834 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22835 	seg_seq = BE32_TO_U32(tcph->th_seq);
22836 	seg_ack = BE32_TO_U32(tcph->th_ack);
22837 	flags = tcph->th_flags[0];
22838 
22839 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22840 	if (flags & TH_RST) {
22841 		freemsg(ipsec_mp);
22842 	} else if (flags & TH_ACK) {
22843 		tcp_xmit_early_reset("no tcp, reset",
22844 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps);
22845 	} else {
22846 		if (flags & TH_SYN) {
22847 			seg_len++;
22848 		} else {
22849 			/*
22850 			 * Here we violate the RFC.  Note that a normal
22851 			 * TCP will never send a segment without the ACK
22852 			 * flag, except for RST or SYN segment.  This
22853 			 * segment is neither.  Just drop it on the
22854 			 * floor.
22855 			 */
22856 			freemsg(ipsec_mp);
22857 			tcps->tcps_rst_unsent++;
22858 			return;
22859 		}
22860 
22861 		tcp_xmit_early_reset("no tcp, reset/ack",
22862 		    ipsec_mp, 0, seg_seq + seg_len,
22863 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps);
22864 	}
22865 }
22866 
22867 /*
22868  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22869  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22870  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22871  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22872  * otherwise it will dup partial mblks.)
22873  * Otherwise, an appropriate ACK packet will be generated.  This
22874  * routine is not usually called to send new data for the first time.  It
22875  * is mostly called out of the timer for retransmits, and to generate ACKs.
22876  *
22877  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22878  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22879  * of the original mblk chain will be returned in *offset and *end_mp.
22880  */
22881 mblk_t *
22882 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22883     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22884     boolean_t rexmit)
22885 {
22886 	int	data_length;
22887 	int32_t	off = 0;
22888 	uint_t	flags;
22889 	mblk_t	*mp1;
22890 	mblk_t	*mp2;
22891 	uchar_t	*rptr;
22892 	tcph_t	*tcph;
22893 	int32_t	num_sack_blk = 0;
22894 	int32_t	sack_opt_len = 0;
22895 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22896 
22897 	/* Allocate for our maximum TCP header + link-level */
22898 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22899 	    tcps->tcps_wroff_xtra, BPRI_MED);
22900 	if (!mp1)
22901 		return (NULL);
22902 	data_length = 0;
22903 
22904 	/*
22905 	 * Note that tcp_mss has been adjusted to take into account the
22906 	 * timestamp option if applicable.  Because SACK options do not
22907 	 * appear in every TCP segments and they are of variable lengths,
22908 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22909 	 * the actual segment length when we need to send a segment which
22910 	 * includes SACK options.
22911 	 */
22912 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22913 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22914 		    tcp->tcp_num_sack_blk);
22915 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22916 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22917 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22918 			max_to_send -= sack_opt_len;
22919 	}
22920 
22921 	if (offset != NULL) {
22922 		off = *offset;
22923 		/* We use offset as an indicator that end_mp is not NULL. */
22924 		*end_mp = NULL;
22925 	}
22926 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22927 		/* This could be faster with cooperation from downstream */
22928 		if (mp2 != mp1 && !sendall &&
22929 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22930 		    max_to_send)
22931 			/*
22932 			 * Don't send the next mblk since the whole mblk
22933 			 * does not fit.
22934 			 */
22935 			break;
22936 		mp2->b_cont = dupb(mp);
22937 		mp2 = mp2->b_cont;
22938 		if (!mp2) {
22939 			freemsg(mp1);
22940 			return (NULL);
22941 		}
22942 		mp2->b_rptr += off;
22943 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22944 		    (uintptr_t)INT_MAX);
22945 
22946 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22947 		if (data_length > max_to_send) {
22948 			mp2->b_wptr -= data_length - max_to_send;
22949 			data_length = max_to_send;
22950 			off = mp2->b_wptr - mp->b_rptr;
22951 			break;
22952 		} else {
22953 			off = 0;
22954 		}
22955 	}
22956 	if (offset != NULL) {
22957 		*offset = off;
22958 		*end_mp = mp;
22959 	}
22960 	if (seg_len != NULL) {
22961 		*seg_len = data_length;
22962 	}
22963 
22964 	/* Update the latest receive window size in TCP header. */
22965 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22966 	    tcp->tcp_tcph->th_win);
22967 
22968 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22969 	mp1->b_rptr = rptr;
22970 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22971 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22972 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22973 	U32_TO_ABE32(seq, tcph->th_seq);
22974 
22975 	/*
22976 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22977 	 * that this function was called from tcp_wput_data. Thus, when called
22978 	 * to retransmit data the setting of the PUSH bit may appear some
22979 	 * what random in that it might get set when it should not. This
22980 	 * should not pose any performance issues.
22981 	 */
22982 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22983 	    tcp->tcp_unsent == data_length)) {
22984 		flags = TH_ACK | TH_PUSH;
22985 	} else {
22986 		flags = TH_ACK;
22987 	}
22988 
22989 	if (tcp->tcp_ecn_ok) {
22990 		if (tcp->tcp_ecn_echo_on)
22991 			flags |= TH_ECE;
22992 
22993 		/*
22994 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22995 		 * There is no TCP flow control for non-data segments, and
22996 		 * only data segment is transmitted reliably.
22997 		 */
22998 		if (data_length > 0 && !rexmit) {
22999 			SET_ECT(tcp, rptr);
23000 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23001 				flags |= TH_CWR;
23002 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23003 			}
23004 		}
23005 	}
23006 
23007 	if (tcp->tcp_valid_bits) {
23008 		uint32_t u1;
23009 
23010 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23011 		    seq == tcp->tcp_iss) {
23012 			uchar_t	*wptr;
23013 
23014 			/*
23015 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23016 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23017 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23018 			 * our SYN is not ack'ed but the app closes this
23019 			 * TCP connection.
23020 			 */
23021 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23022 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23023 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23024 
23025 			/*
23026 			 * Tack on the MSS option.  It is always needed
23027 			 * for both active and passive open.
23028 			 *
23029 			 * MSS option value should be interface MTU - MIN
23030 			 * TCP/IP header according to RFC 793 as it means
23031 			 * the maximum segment size TCP can receive.  But
23032 			 * to get around some broken middle boxes/end hosts
23033 			 * out there, we allow the option value to be the
23034 			 * same as the MSS option size on the peer side.
23035 			 * In this way, the other side will not send
23036 			 * anything larger than they can receive.
23037 			 *
23038 			 * Note that for SYN_SENT state, the ndd param
23039 			 * tcp_use_smss_as_mss_opt has no effect as we
23040 			 * don't know the peer's MSS option value. So
23041 			 * the only case we need to take care of is in
23042 			 * SYN_RCVD state, which is done later.
23043 			 */
23044 			wptr = mp1->b_wptr;
23045 			wptr[0] = TCPOPT_MAXSEG;
23046 			wptr[1] = TCPOPT_MAXSEG_LEN;
23047 			wptr += 2;
23048 			u1 = tcp->tcp_if_mtu -
23049 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23050 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23051 			    TCP_MIN_HEADER_LENGTH;
23052 			U16_TO_BE16(u1, wptr);
23053 			mp1->b_wptr = wptr + 2;
23054 			/* Update the offset to cover the additional word */
23055 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23056 
23057 			/*
23058 			 * Note that the following way of filling in
23059 			 * TCP options are not optimal.  Some NOPs can
23060 			 * be saved.  But there is no need at this time
23061 			 * to optimize it.  When it is needed, we will
23062 			 * do it.
23063 			 */
23064 			switch (tcp->tcp_state) {
23065 			case TCPS_SYN_SENT:
23066 				flags = TH_SYN;
23067 
23068 				if (tcp->tcp_snd_ts_ok) {
23069 					uint32_t llbolt = (uint32_t)lbolt;
23070 
23071 					wptr = mp1->b_wptr;
23072 					wptr[0] = TCPOPT_NOP;
23073 					wptr[1] = TCPOPT_NOP;
23074 					wptr[2] = TCPOPT_TSTAMP;
23075 					wptr[3] = TCPOPT_TSTAMP_LEN;
23076 					wptr += 4;
23077 					U32_TO_BE32(llbolt, wptr);
23078 					wptr += 4;
23079 					ASSERT(tcp->tcp_ts_recent == 0);
23080 					U32_TO_BE32(0L, wptr);
23081 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23082 					tcph->th_offset_and_rsrvd[0] +=
23083 					    (3 << 4);
23084 				}
23085 
23086 				/*
23087 				 * Set up all the bits to tell other side
23088 				 * we are ECN capable.
23089 				 */
23090 				if (tcp->tcp_ecn_ok) {
23091 					flags |= (TH_ECE | TH_CWR);
23092 				}
23093 				break;
23094 			case TCPS_SYN_RCVD:
23095 				flags |= TH_SYN;
23096 
23097 				/*
23098 				 * Reset the MSS option value to be SMSS
23099 				 * We should probably add back the bytes
23100 				 * for timestamp option and IPsec.  We
23101 				 * don't do that as this is a workaround
23102 				 * for broken middle boxes/end hosts, it
23103 				 * is better for us to be more cautious.
23104 				 * They may not take these things into
23105 				 * account in their SMSS calculation.  Thus
23106 				 * the peer's calculated SMSS may be smaller
23107 				 * than what it can be.  This should be OK.
23108 				 */
23109 				if (tcps->tcps_use_smss_as_mss_opt) {
23110 					u1 = tcp->tcp_mss;
23111 					U16_TO_BE16(u1, wptr);
23112 				}
23113 
23114 				/*
23115 				 * If the other side is ECN capable, reply
23116 				 * that we are also ECN capable.
23117 				 */
23118 				if (tcp->tcp_ecn_ok)
23119 					flags |= TH_ECE;
23120 				break;
23121 			default:
23122 				/*
23123 				 * The above ASSERT() makes sure that this
23124 				 * must be FIN-WAIT-1 state.  Our SYN has
23125 				 * not been ack'ed so retransmit it.
23126 				 */
23127 				flags |= TH_SYN;
23128 				break;
23129 			}
23130 
23131 			if (tcp->tcp_snd_ws_ok) {
23132 				wptr = mp1->b_wptr;
23133 				wptr[0] =  TCPOPT_NOP;
23134 				wptr[1] =  TCPOPT_WSCALE;
23135 				wptr[2] =  TCPOPT_WS_LEN;
23136 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23137 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23138 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23139 			}
23140 
23141 			if (tcp->tcp_snd_sack_ok) {
23142 				wptr = mp1->b_wptr;
23143 				wptr[0] = TCPOPT_NOP;
23144 				wptr[1] = TCPOPT_NOP;
23145 				wptr[2] = TCPOPT_SACK_PERMITTED;
23146 				wptr[3] = TCPOPT_SACK_OK_LEN;
23147 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23148 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23149 			}
23150 
23151 			/* allocb() of adequate mblk assures space */
23152 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23153 			    (uintptr_t)INT_MAX);
23154 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23155 			/*
23156 			 * Get IP set to checksum on our behalf
23157 			 * Include the adjustment for a source route if any.
23158 			 */
23159 			u1 += tcp->tcp_sum;
23160 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23161 			U16_TO_BE16(u1, tcph->th_sum);
23162 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23163 		}
23164 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23165 		    (seq + data_length) == tcp->tcp_fss) {
23166 			if (!tcp->tcp_fin_acked) {
23167 				flags |= TH_FIN;
23168 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23169 			}
23170 			if (!tcp->tcp_fin_sent) {
23171 				tcp->tcp_fin_sent = B_TRUE;
23172 				switch (tcp->tcp_state) {
23173 				case TCPS_SYN_RCVD:
23174 				case TCPS_ESTABLISHED:
23175 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23176 					break;
23177 				case TCPS_CLOSE_WAIT:
23178 					tcp->tcp_state = TCPS_LAST_ACK;
23179 					break;
23180 				}
23181 				if (tcp->tcp_suna == tcp->tcp_snxt)
23182 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23183 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23184 			}
23185 		}
23186 		/*
23187 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23188 		 * is smaller than seq, u1 will become a very huge value.
23189 		 * So the comparison will fail.  Also note that tcp_urp
23190 		 * should be positive, see RFC 793 page 17.
23191 		 */
23192 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23193 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23194 		    u1 < (uint32_t)(64 * 1024)) {
23195 			flags |= TH_URG;
23196 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23197 			U32_TO_ABE16(u1, tcph->th_urp);
23198 		}
23199 	}
23200 	tcph->th_flags[0] = (uchar_t)flags;
23201 	tcp->tcp_rack = tcp->tcp_rnxt;
23202 	tcp->tcp_rack_cnt = 0;
23203 
23204 	if (tcp->tcp_snd_ts_ok) {
23205 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23206 			uint32_t llbolt = (uint32_t)lbolt;
23207 
23208 			U32_TO_BE32(llbolt,
23209 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23210 			U32_TO_BE32(tcp->tcp_ts_recent,
23211 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23212 		}
23213 	}
23214 
23215 	if (num_sack_blk > 0) {
23216 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23217 		sack_blk_t *tmp;
23218 		int32_t	i;
23219 
23220 		wptr[0] = TCPOPT_NOP;
23221 		wptr[1] = TCPOPT_NOP;
23222 		wptr[2] = TCPOPT_SACK;
23223 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23224 		    sizeof (sack_blk_t);
23225 		wptr += TCPOPT_REAL_SACK_LEN;
23226 
23227 		tmp = tcp->tcp_sack_list;
23228 		for (i = 0; i < num_sack_blk; i++) {
23229 			U32_TO_BE32(tmp[i].begin, wptr);
23230 			wptr += sizeof (tcp_seq);
23231 			U32_TO_BE32(tmp[i].end, wptr);
23232 			wptr += sizeof (tcp_seq);
23233 		}
23234 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23235 	}
23236 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23237 	data_length += (int)(mp1->b_wptr - rptr);
23238 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23239 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23240 	} else {
23241 		ip6_t *ip6 = (ip6_t *)(rptr +
23242 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23243 		    sizeof (ip6i_t) : 0));
23244 
23245 		ip6->ip6_plen = htons(data_length -
23246 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23247 	}
23248 
23249 	/*
23250 	 * Prime pump for IP
23251 	 * Include the adjustment for a source route if any.
23252 	 */
23253 	data_length -= tcp->tcp_ip_hdr_len;
23254 	data_length += tcp->tcp_sum;
23255 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23256 	U16_TO_ABE16(data_length, tcph->th_sum);
23257 	if (tcp->tcp_ip_forward_progress) {
23258 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23259 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23260 		tcp->tcp_ip_forward_progress = B_FALSE;
23261 	}
23262 	return (mp1);
23263 }
23264 
23265 /* This function handles the push timeout. */
23266 void
23267 tcp_push_timer(void *arg)
23268 {
23269 	conn_t	*connp = (conn_t *)arg;
23270 	tcp_t *tcp = connp->conn_tcp;
23271 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23272 
23273 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23274 
23275 	ASSERT(tcp->tcp_listener == NULL);
23276 
23277 	/*
23278 	 * We need to plug synchronous streams during our drain to prevent
23279 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23280 	 */
23281 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23282 	tcp->tcp_push_tid = 0;
23283 	if ((tcp->tcp_rcv_list != NULL) &&
23284 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
23285 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23286 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23287 }
23288 
23289 /*
23290  * This function handles delayed ACK timeout.
23291  */
23292 static void
23293 tcp_ack_timer(void *arg)
23294 {
23295 	conn_t	*connp = (conn_t *)arg;
23296 	tcp_t *tcp = connp->conn_tcp;
23297 	mblk_t *mp;
23298 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23299 
23300 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23301 
23302 	tcp->tcp_ack_tid = 0;
23303 
23304 	if (tcp->tcp_fused)
23305 		return;
23306 
23307 	/*
23308 	 * Do not send ACK if there is no outstanding unack'ed data.
23309 	 */
23310 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23311 		return;
23312 	}
23313 
23314 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23315 		/*
23316 		 * Make sure we don't allow deferred ACKs to result in
23317 		 * timer-based ACKing.  If we have held off an ACK
23318 		 * when there was more than an mss here, and the timer
23319 		 * goes off, we have to worry about the possibility
23320 		 * that the sender isn't doing slow-start, or is out
23321 		 * of step with us for some other reason.  We fall
23322 		 * permanently back in the direction of
23323 		 * ACK-every-other-packet as suggested in RFC 1122.
23324 		 */
23325 		if (tcp->tcp_rack_abs_max > 2)
23326 			tcp->tcp_rack_abs_max--;
23327 		tcp->tcp_rack_cur_max = 2;
23328 	}
23329 	mp = tcp_ack_mp(tcp);
23330 
23331 	if (mp != NULL) {
23332 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23333 		BUMP_LOCAL(tcp->tcp_obsegs);
23334 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23335 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23336 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23337 	}
23338 }
23339 
23340 
23341 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23342 static mblk_t *
23343 tcp_ack_mp(tcp_t *tcp)
23344 {
23345 	uint32_t	seq_no;
23346 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23347 
23348 	/*
23349 	 * There are a few cases to be considered while setting the sequence no.
23350 	 * Essentially, we can come here while processing an unacceptable pkt
23351 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23352 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23353 	 * If we are here for a zero window probe, stick with suna. In all
23354 	 * other cases, we check if suna + swnd encompasses snxt and set
23355 	 * the sequence number to snxt, if so. If snxt falls outside the
23356 	 * window (the receiver probably shrunk its window), we will go with
23357 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23358 	 * receiver.
23359 	 */
23360 	if (tcp->tcp_zero_win_probe) {
23361 		seq_no = tcp->tcp_suna;
23362 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23363 		ASSERT(tcp->tcp_swnd == 0);
23364 		seq_no = tcp->tcp_snxt;
23365 	} else {
23366 		seq_no = SEQ_GT(tcp->tcp_snxt,
23367 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23368 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23369 	}
23370 
23371 	if (tcp->tcp_valid_bits) {
23372 		/*
23373 		 * For the complex case where we have to send some
23374 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23375 		 */
23376 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23377 		    NULL, B_FALSE));
23378 	} else {
23379 		/* Generate a simple ACK */
23380 		int	data_length;
23381 		uchar_t	*rptr;
23382 		tcph_t	*tcph;
23383 		mblk_t	*mp1;
23384 		int32_t	tcp_hdr_len;
23385 		int32_t	tcp_tcp_hdr_len;
23386 		int32_t	num_sack_blk = 0;
23387 		int32_t sack_opt_len;
23388 
23389 		/*
23390 		 * Allocate space for TCP + IP headers
23391 		 * and link-level header
23392 		 */
23393 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23394 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23395 			    tcp->tcp_num_sack_blk);
23396 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23397 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23398 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23399 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23400 		} else {
23401 			tcp_hdr_len = tcp->tcp_hdr_len;
23402 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23403 		}
23404 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23405 		if (!mp1)
23406 			return (NULL);
23407 
23408 		/* Update the latest receive window size in TCP header. */
23409 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23410 		    tcp->tcp_tcph->th_win);
23411 		/* copy in prototype TCP + IP header */
23412 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23413 		mp1->b_rptr = rptr;
23414 		mp1->b_wptr = rptr + tcp_hdr_len;
23415 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23416 
23417 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23418 
23419 		/* Set the TCP sequence number. */
23420 		U32_TO_ABE32(seq_no, tcph->th_seq);
23421 
23422 		/* Set up the TCP flag field. */
23423 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23424 		if (tcp->tcp_ecn_echo_on)
23425 			tcph->th_flags[0] |= TH_ECE;
23426 
23427 		tcp->tcp_rack = tcp->tcp_rnxt;
23428 		tcp->tcp_rack_cnt = 0;
23429 
23430 		/* fill in timestamp option if in use */
23431 		if (tcp->tcp_snd_ts_ok) {
23432 			uint32_t llbolt = (uint32_t)lbolt;
23433 
23434 			U32_TO_BE32(llbolt,
23435 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23436 			U32_TO_BE32(tcp->tcp_ts_recent,
23437 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23438 		}
23439 
23440 		/* Fill in SACK options */
23441 		if (num_sack_blk > 0) {
23442 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23443 			sack_blk_t *tmp;
23444 			int32_t	i;
23445 
23446 			wptr[0] = TCPOPT_NOP;
23447 			wptr[1] = TCPOPT_NOP;
23448 			wptr[2] = TCPOPT_SACK;
23449 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23450 			    sizeof (sack_blk_t);
23451 			wptr += TCPOPT_REAL_SACK_LEN;
23452 
23453 			tmp = tcp->tcp_sack_list;
23454 			for (i = 0; i < num_sack_blk; i++) {
23455 				U32_TO_BE32(tmp[i].begin, wptr);
23456 				wptr += sizeof (tcp_seq);
23457 				U32_TO_BE32(tmp[i].end, wptr);
23458 				wptr += sizeof (tcp_seq);
23459 			}
23460 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23461 			    << 4);
23462 		}
23463 
23464 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23465 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23466 		} else {
23467 			/* Check for ip6i_t header in sticky hdrs */
23468 			ip6_t *ip6 = (ip6_t *)(rptr +
23469 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23470 			    sizeof (ip6i_t) : 0));
23471 
23472 			ip6->ip6_plen = htons(tcp_hdr_len -
23473 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23474 		}
23475 
23476 		/*
23477 		 * Prime pump for checksum calculation in IP.  Include the
23478 		 * adjustment for a source route if any.
23479 		 */
23480 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23481 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23482 		U16_TO_ABE16(data_length, tcph->th_sum);
23483 
23484 		if (tcp->tcp_ip_forward_progress) {
23485 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23486 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23487 			tcp->tcp_ip_forward_progress = B_FALSE;
23488 		}
23489 		return (mp1);
23490 	}
23491 }
23492 
23493 /*
23494  * To create a temporary tcp structure for inserting into bind hash list.
23495  * The parameter is assumed to be in network byte order, ready for use.
23496  */
23497 /* ARGSUSED */
23498 static tcp_t *
23499 tcp_alloc_temp_tcp(in_port_t port, tcp_stack_t *tcps)
23500 {
23501 	conn_t	*connp;
23502 	tcp_t	*tcp;
23503 
23504 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP, tcps->tcps_netstack);
23505 	if (connp == NULL)
23506 		return (NULL);
23507 
23508 	tcp = connp->conn_tcp;
23509 	tcp->tcp_tcps = tcps;
23510 	TCPS_REFHOLD(tcps);
23511 
23512 	/*
23513 	 * Only initialize the necessary info in those structures.  Note
23514 	 * that since INADDR_ANY is all 0, we do not need to set
23515 	 * tcp_bound_source to INADDR_ANY here.
23516 	 */
23517 	tcp->tcp_state = TCPS_BOUND;
23518 	tcp->tcp_lport = port;
23519 	tcp->tcp_exclbind = 1;
23520 	tcp->tcp_reserved_port = 1;
23521 
23522 	/* Just for place holding... */
23523 	tcp->tcp_ipversion = IPV4_VERSION;
23524 
23525 	return (tcp);
23526 }
23527 
23528 /*
23529  * To remove a port range specified by lo_port and hi_port from the
23530  * reserved port ranges.  This is one of the three public functions of
23531  * the reserved port interface.  Note that a port range has to be removed
23532  * as a whole.  Ports in a range cannot be removed individually.
23533  *
23534  * Params:
23535  *	in_port_t lo_port: the beginning port of the reserved port range to
23536  *		be deleted.
23537  *	in_port_t hi_port: the ending port of the reserved port range to
23538  *		be deleted.
23539  *
23540  * Return:
23541  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
23542  *
23543  * Assumes that nca is only for zoneid=0
23544  */
23545 boolean_t
23546 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
23547 {
23548 	int	i, j;
23549 	int	size;
23550 	tcp_t	**temp_tcp_array;
23551 	tcp_t	*tcp;
23552 	tcp_stack_t	*tcps;
23553 
23554 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23555 	ASSERT(tcps != NULL);
23556 
23557 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23558 
23559 	/* First make sure that the port ranage is indeed reserved. */
23560 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23561 		if (tcps->tcps_reserved_port[i].lo_port == lo_port) {
23562 			hi_port = tcps->tcps_reserved_port[i].hi_port;
23563 			temp_tcp_array =
23564 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23565 			break;
23566 		}
23567 	}
23568 	if (i == tcps->tcps_reserved_port_array_size) {
23569 		rw_exit(&tcps->tcps_reserved_port_lock);
23570 		netstack_rele(tcps->tcps_netstack);
23571 		return (B_FALSE);
23572 	}
23573 
23574 	/*
23575 	 * Remove the range from the array.  This simple loop is possible
23576 	 * because port ranges are inserted in ascending order.
23577 	 */
23578 	for (j = i; j < tcps->tcps_reserved_port_array_size - 1; j++) {
23579 		tcps->tcps_reserved_port[j].lo_port =
23580 		    tcps->tcps_reserved_port[j+1].lo_port;
23581 		tcps->tcps_reserved_port[j].hi_port =
23582 		    tcps->tcps_reserved_port[j+1].hi_port;
23583 		tcps->tcps_reserved_port[j].temp_tcp_array =
23584 		    tcps->tcps_reserved_port[j+1].temp_tcp_array;
23585 	}
23586 
23587 	/* Remove all the temporary tcp structures. */
23588 	size = hi_port - lo_port + 1;
23589 	while (size > 0) {
23590 		tcp = temp_tcp_array[size - 1];
23591 		ASSERT(tcp != NULL);
23592 		tcp_bind_hash_remove(tcp);
23593 		CONN_DEC_REF(tcp->tcp_connp);
23594 		size--;
23595 	}
23596 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
23597 	tcps->tcps_reserved_port_array_size--;
23598 	rw_exit(&tcps->tcps_reserved_port_lock);
23599 	netstack_rele(tcps->tcps_netstack);
23600 	return (B_TRUE);
23601 }
23602 
23603 /*
23604  * Macro to remove temporary tcp structure from the bind hash list.  The
23605  * first parameter is the list of tcp to be removed.  The second parameter
23606  * is the number of tcps in the array.
23607  */
23608 #define	TCP_TMP_TCP_REMOVE(tcp_array, num, tcps) \
23609 { \
23610 	while ((num) > 0) { \
23611 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
23612 		tf_t *tbf; \
23613 		tcp_t *tcpnext; \
23614 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
23615 		mutex_enter(&tbf->tf_lock); \
23616 		tcpnext = tcp->tcp_bind_hash; \
23617 		if (tcpnext) { \
23618 			tcpnext->tcp_ptpbhn = \
23619 				tcp->tcp_ptpbhn; \
23620 		} \
23621 		*tcp->tcp_ptpbhn = tcpnext; \
23622 		mutex_exit(&tbf->tf_lock); \
23623 		kmem_free(tcp, sizeof (tcp_t)); \
23624 		(tcp_array)[(num) - 1] = NULL; \
23625 		(num)--; \
23626 	} \
23627 }
23628 
23629 /*
23630  * The public interface for other modules to call to reserve a port range
23631  * in TCP.  The caller passes in how large a port range it wants.  TCP
23632  * will try to find a range and return it via lo_port and hi_port.  This is
23633  * used by NCA's nca_conn_init.
23634  * NCA can only be used in the global zone so this only affects the global
23635  * zone's ports.
23636  *
23637  * Params:
23638  *	int size: the size of the port range to be reserved.
23639  *	in_port_t *lo_port (referenced): returns the beginning port of the
23640  *		reserved port range added.
23641  *	in_port_t *hi_port (referenced): returns the ending port of the
23642  *		reserved port range added.
23643  *
23644  * Return:
23645  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
23646  *
23647  * Assumes that nca is only for zoneid=0
23648  */
23649 boolean_t
23650 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
23651 {
23652 	tcp_t		*tcp;
23653 	tcp_t		*tmp_tcp;
23654 	tcp_t		**temp_tcp_array;
23655 	tf_t		*tbf;
23656 	in_port_t	net_port;
23657 	in_port_t	port;
23658 	int32_t		cur_size;
23659 	int		i, j;
23660 	boolean_t	used;
23661 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
23662 	zoneid_t	zoneid = GLOBAL_ZONEID;
23663 	tcp_stack_t	*tcps;
23664 
23665 	/* Sanity check. */
23666 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
23667 		return (B_FALSE);
23668 	}
23669 
23670 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23671 	ASSERT(tcps != NULL);
23672 
23673 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23674 	if (tcps->tcps_reserved_port_array_size ==
23675 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
23676 		rw_exit(&tcps->tcps_reserved_port_lock);
23677 		netstack_rele(tcps->tcps_netstack);
23678 		return (B_FALSE);
23679 	}
23680 
23681 	/*
23682 	 * Find the starting port to try.  Since the port ranges are ordered
23683 	 * in the reserved port array, we can do a simple search here.
23684 	 */
23685 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
23686 	*hi_port = TCP_LARGEST_RESERVED_PORT;
23687 	for (i = 0; i < tcps->tcps_reserved_port_array_size;
23688 	    *lo_port = tcps->tcps_reserved_port[i].hi_port + 1, i++) {
23689 		if (tcps->tcps_reserved_port[i].lo_port - *lo_port >= size) {
23690 			*hi_port = tcps->tcps_reserved_port[i].lo_port - 1;
23691 			break;
23692 		}
23693 	}
23694 	/* No available port range. */
23695 	if (i == tcps->tcps_reserved_port_array_size &&
23696 	    *hi_port - *lo_port < size) {
23697 		rw_exit(&tcps->tcps_reserved_port_lock);
23698 		netstack_rele(tcps->tcps_netstack);
23699 		return (B_FALSE);
23700 	}
23701 
23702 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
23703 	if (temp_tcp_array == NULL) {
23704 		rw_exit(&tcps->tcps_reserved_port_lock);
23705 		netstack_rele(tcps->tcps_netstack);
23706 		return (B_FALSE);
23707 	}
23708 
23709 	/* Go thru the port range to see if some ports are already bound. */
23710 	for (port = *lo_port, cur_size = 0;
23711 	    cur_size < size && port <= *hi_port;
23712 	    cur_size++, port++) {
23713 		used = B_FALSE;
23714 		net_port = htons(port);
23715 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(net_port)];
23716 		mutex_enter(&tbf->tf_lock);
23717 		for (tcp = tbf->tf_tcp; tcp != NULL;
23718 		    tcp = tcp->tcp_bind_hash) {
23719 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
23720 			    net_port == tcp->tcp_lport) {
23721 				/*
23722 				 * A port is already bound.  Search again
23723 				 * starting from port + 1.  Release all
23724 				 * temporary tcps.
23725 				 */
23726 				mutex_exit(&tbf->tf_lock);
23727 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23728 				    tcps);
23729 				*lo_port = port + 1;
23730 				cur_size = -1;
23731 				used = B_TRUE;
23732 				break;
23733 			}
23734 		}
23735 		if (!used) {
23736 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port, tcps)) ==
23737 			    NULL) {
23738 				/*
23739 				 * Allocation failure.  Just fail the request.
23740 				 * Need to remove all those temporary tcp
23741 				 * structures.
23742 				 */
23743 				mutex_exit(&tbf->tf_lock);
23744 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23745 				    tcps);
23746 				rw_exit(&tcps->tcps_reserved_port_lock);
23747 				kmem_free(temp_tcp_array,
23748 				    (hi_port - lo_port + 1) *
23749 				    sizeof (tcp_t *));
23750 				netstack_rele(tcps->tcps_netstack);
23751 				return (B_FALSE);
23752 			}
23753 			temp_tcp_array[cur_size] = tmp_tcp;
23754 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
23755 			mutex_exit(&tbf->tf_lock);
23756 		}
23757 	}
23758 
23759 	/*
23760 	 * The current range is not large enough.  We can actually do another
23761 	 * search if this search is done between 2 reserved port ranges.  But
23762 	 * for first release, we just stop here and return saying that no port
23763 	 * range is available.
23764 	 */
23765 	if (cur_size < size) {
23766 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size, tcps);
23767 		rw_exit(&tcps->tcps_reserved_port_lock);
23768 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23769 		netstack_rele(tcps->tcps_netstack);
23770 		return (B_FALSE);
23771 	}
23772 	*hi_port = port - 1;
23773 
23774 	/*
23775 	 * Insert range into array in ascending order.  Since this function
23776 	 * must not be called often, we choose to use the simplest method.
23777 	 * The above array should not consume excessive stack space as
23778 	 * the size must be very small.  If in future releases, we find
23779 	 * that we should provide more reserved port ranges, this function
23780 	 * has to be modified to be more efficient.
23781 	 */
23782 	if (tcps->tcps_reserved_port_array_size == 0) {
23783 		tcps->tcps_reserved_port[0].lo_port = *lo_port;
23784 		tcps->tcps_reserved_port[0].hi_port = *hi_port;
23785 		tcps->tcps_reserved_port[0].temp_tcp_array = temp_tcp_array;
23786 	} else {
23787 		for (i = 0, j = 0; i < tcps->tcps_reserved_port_array_size;
23788 		    i++, j++) {
23789 			if (*lo_port < tcps->tcps_reserved_port[i].lo_port &&
23790 			    i == j) {
23791 				tmp_ports[j].lo_port = *lo_port;
23792 				tmp_ports[j].hi_port = *hi_port;
23793 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23794 				j++;
23795 			}
23796 			tmp_ports[j].lo_port =
23797 			    tcps->tcps_reserved_port[i].lo_port;
23798 			tmp_ports[j].hi_port =
23799 			    tcps->tcps_reserved_port[i].hi_port;
23800 			tmp_ports[j].temp_tcp_array =
23801 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23802 		}
23803 		if (j == i) {
23804 			tmp_ports[j].lo_port = *lo_port;
23805 			tmp_ports[j].hi_port = *hi_port;
23806 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23807 		}
23808 		bcopy(tmp_ports, tcps->tcps_reserved_port, sizeof (tmp_ports));
23809 	}
23810 	tcps->tcps_reserved_port_array_size++;
23811 	rw_exit(&tcps->tcps_reserved_port_lock);
23812 	netstack_rele(tcps->tcps_netstack);
23813 	return (B_TRUE);
23814 }
23815 
23816 /*
23817  * Check to see if a port is in any reserved port range.
23818  *
23819  * Params:
23820  *	in_port_t port: the port to be verified.
23821  *
23822  * Return:
23823  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23824  */
23825 boolean_t
23826 tcp_reserved_port_check(in_port_t port, tcp_stack_t *tcps)
23827 {
23828 	int i;
23829 
23830 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23831 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23832 		if (port >= tcps->tcps_reserved_port[i].lo_port ||
23833 		    port <= tcps->tcps_reserved_port[i].hi_port) {
23834 			rw_exit(&tcps->tcps_reserved_port_lock);
23835 			return (B_TRUE);
23836 		}
23837 	}
23838 	rw_exit(&tcps->tcps_reserved_port_lock);
23839 	return (B_FALSE);
23840 }
23841 
23842 /*
23843  * To list all reserved port ranges.  This is the function to handle
23844  * ndd tcp_reserved_port_list.
23845  */
23846 /* ARGSUSED */
23847 static int
23848 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23849 {
23850 	int i;
23851 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23852 
23853 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23854 	if (tcps->tcps_reserved_port_array_size > 0)
23855 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23856 	else
23857 		(void) mi_mpprintf(mp, "No port is reserved.");
23858 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23859 		(void) mi_mpprintf(mp, "%d-%d",
23860 		    tcps->tcps_reserved_port[i].lo_port,
23861 		    tcps->tcps_reserved_port[i].hi_port);
23862 	}
23863 	rw_exit(&tcps->tcps_reserved_port_lock);
23864 	return (0);
23865 }
23866 
23867 /*
23868  * Hash list insertion routine for tcp_t structures.
23869  * Inserts entries with the ones bound to a specific IP address first
23870  * followed by those bound to INADDR_ANY.
23871  */
23872 static void
23873 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23874 {
23875 	tcp_t	**tcpp;
23876 	tcp_t	*tcpnext;
23877 
23878 	if (tcp->tcp_ptpbhn != NULL) {
23879 		ASSERT(!caller_holds_lock);
23880 		tcp_bind_hash_remove(tcp);
23881 	}
23882 	tcpp = &tbf->tf_tcp;
23883 	if (!caller_holds_lock) {
23884 		mutex_enter(&tbf->tf_lock);
23885 	} else {
23886 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23887 	}
23888 	tcpnext = tcpp[0];
23889 	if (tcpnext) {
23890 		/*
23891 		 * If the new tcp bound to the INADDR_ANY address
23892 		 * and the first one in the list is not bound to
23893 		 * INADDR_ANY we skip all entries until we find the
23894 		 * first one bound to INADDR_ANY.
23895 		 * This makes sure that applications binding to a
23896 		 * specific address get preference over those binding to
23897 		 * INADDR_ANY.
23898 		 */
23899 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23900 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23901 			while ((tcpnext = tcpp[0]) != NULL &&
23902 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23903 				tcpp = &(tcpnext->tcp_bind_hash);
23904 			if (tcpnext)
23905 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23906 		} else
23907 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23908 	}
23909 	tcp->tcp_bind_hash = tcpnext;
23910 	tcp->tcp_ptpbhn = tcpp;
23911 	tcpp[0] = tcp;
23912 	if (!caller_holds_lock)
23913 		mutex_exit(&tbf->tf_lock);
23914 }
23915 
23916 /*
23917  * Hash list removal routine for tcp_t structures.
23918  */
23919 static void
23920 tcp_bind_hash_remove(tcp_t *tcp)
23921 {
23922 	tcp_t	*tcpnext;
23923 	kmutex_t *lockp;
23924 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23925 
23926 	if (tcp->tcp_ptpbhn == NULL)
23927 		return;
23928 
23929 	/*
23930 	 * Extract the lock pointer in case there are concurrent
23931 	 * hash_remove's for this instance.
23932 	 */
23933 	ASSERT(tcp->tcp_lport != 0);
23934 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23935 
23936 	ASSERT(lockp != NULL);
23937 	mutex_enter(lockp);
23938 	if (tcp->tcp_ptpbhn) {
23939 		tcpnext = tcp->tcp_bind_hash;
23940 		if (tcpnext) {
23941 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23942 			tcp->tcp_bind_hash = NULL;
23943 		}
23944 		*tcp->tcp_ptpbhn = tcpnext;
23945 		tcp->tcp_ptpbhn = NULL;
23946 	}
23947 	mutex_exit(lockp);
23948 }
23949 
23950 
23951 /*
23952  * Hash list lookup routine for tcp_t structures.
23953  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23954  */
23955 static tcp_t *
23956 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23957 {
23958 	tf_t	*tf;
23959 	tcp_t	*tcp;
23960 
23961 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23962 	mutex_enter(&tf->tf_lock);
23963 	for (tcp = tf->tf_tcp; tcp != NULL;
23964 	    tcp = tcp->tcp_acceptor_hash) {
23965 		if (tcp->tcp_acceptor_id == id) {
23966 			CONN_INC_REF(tcp->tcp_connp);
23967 			mutex_exit(&tf->tf_lock);
23968 			return (tcp);
23969 		}
23970 	}
23971 	mutex_exit(&tf->tf_lock);
23972 	return (NULL);
23973 }
23974 
23975 
23976 /*
23977  * Hash list insertion routine for tcp_t structures.
23978  */
23979 void
23980 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23981 {
23982 	tf_t	*tf;
23983 	tcp_t	**tcpp;
23984 	tcp_t	*tcpnext;
23985 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23986 
23987 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23988 
23989 	if (tcp->tcp_ptpahn != NULL)
23990 		tcp_acceptor_hash_remove(tcp);
23991 	tcpp = &tf->tf_tcp;
23992 	mutex_enter(&tf->tf_lock);
23993 	tcpnext = tcpp[0];
23994 	if (tcpnext)
23995 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23996 	tcp->tcp_acceptor_hash = tcpnext;
23997 	tcp->tcp_ptpahn = tcpp;
23998 	tcpp[0] = tcp;
23999 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24000 	mutex_exit(&tf->tf_lock);
24001 }
24002 
24003 /*
24004  * Hash list removal routine for tcp_t structures.
24005  */
24006 static void
24007 tcp_acceptor_hash_remove(tcp_t *tcp)
24008 {
24009 	tcp_t	*tcpnext;
24010 	kmutex_t *lockp;
24011 
24012 	/*
24013 	 * Extract the lock pointer in case there are concurrent
24014 	 * hash_remove's for this instance.
24015 	 */
24016 	lockp = tcp->tcp_acceptor_lockp;
24017 
24018 	if (tcp->tcp_ptpahn == NULL)
24019 		return;
24020 
24021 	ASSERT(lockp != NULL);
24022 	mutex_enter(lockp);
24023 	if (tcp->tcp_ptpahn) {
24024 		tcpnext = tcp->tcp_acceptor_hash;
24025 		if (tcpnext) {
24026 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24027 			tcp->tcp_acceptor_hash = NULL;
24028 		}
24029 		*tcp->tcp_ptpahn = tcpnext;
24030 		tcp->tcp_ptpahn = NULL;
24031 	}
24032 	mutex_exit(lockp);
24033 	tcp->tcp_acceptor_lockp = NULL;
24034 }
24035 
24036 /* ARGSUSED */
24037 static int
24038 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
24039 {
24040 	int error = 0;
24041 	int retval;
24042 	char *end;
24043 	tcp_hsp_t *hsp;
24044 	tcp_hsp_t *hspprev;
24045 	ipaddr_t addr = 0;		/* Address we're looking for */
24046 	in6_addr_t v6addr;		/* Address we're looking for */
24047 	uint32_t hash;			/* Hash of that address */
24048 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24049 
24050 	/*
24051 	 * If the following variables are still zero after parsing the input
24052 	 * string, the user didn't specify them and we don't change them in
24053 	 * the HSP.
24054 	 */
24055 
24056 	ipaddr_t mask = 0;		/* Subnet mask */
24057 	in6_addr_t v6mask;
24058 	long sendspace = 0;		/* Send buffer size */
24059 	long recvspace = 0;		/* Receive buffer size */
24060 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
24061 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
24062 
24063 	rw_enter(&tcps->tcps_hsp_lock, RW_WRITER);
24064 
24065 	/* Parse and validate address */
24066 	if (af == AF_INET) {
24067 		retval = inet_pton(af, value, &addr);
24068 		if (retval == 1)
24069 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
24070 	} else if (af == AF_INET6) {
24071 		retval = inet_pton(af, value, &v6addr);
24072 	} else {
24073 		error = EINVAL;
24074 		goto done;
24075 	}
24076 	if (retval == 0) {
24077 		error = EINVAL;
24078 		goto done;
24079 	}
24080 
24081 	while ((*value) && *value != ' ')
24082 		value++;
24083 
24084 	/* Parse individual keywords, set variables if found */
24085 	while (*value) {
24086 		/* Skip leading blanks */
24087 
24088 		while (*value == ' ' || *value == '\t')
24089 			value++;
24090 
24091 		/* If at end of string, we're done */
24092 
24093 		if (!*value)
24094 			break;
24095 
24096 		/* We have a word, figure out what it is */
24097 
24098 		if (strncmp("mask", value, 4) == 0) {
24099 			value += 4;
24100 			while (*value == ' ' || *value == '\t')
24101 				value++;
24102 			/* Parse subnet mask */
24103 			if (af == AF_INET) {
24104 				retval = inet_pton(af, value, &mask);
24105 				if (retval == 1) {
24106 					V4MASK_TO_V6(mask, v6mask);
24107 				}
24108 			} else if (af == AF_INET6) {
24109 				retval = inet_pton(af, value, &v6mask);
24110 			}
24111 			if (retval != 1) {
24112 				error = EINVAL;
24113 				goto done;
24114 			}
24115 			while ((*value) && *value != ' ')
24116 				value++;
24117 		} else if (strncmp("sendspace", value, 9) == 0) {
24118 			value += 9;
24119 
24120 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
24121 			    sendspace < TCP_XMIT_HIWATER ||
24122 			    sendspace >= (1L<<30)) {
24123 				error = EINVAL;
24124 				goto done;
24125 			}
24126 			value = end;
24127 		} else if (strncmp("recvspace", value, 9) == 0) {
24128 			value += 9;
24129 
24130 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
24131 			    recvspace < TCP_RECV_HIWATER ||
24132 			    recvspace >= (1L<<30)) {
24133 				error = EINVAL;
24134 				goto done;
24135 			}
24136 			value = end;
24137 		} else if (strncmp("timestamp", value, 9) == 0) {
24138 			value += 9;
24139 
24140 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
24141 			    timestamp < 0 || timestamp > 1) {
24142 				error = EINVAL;
24143 				goto done;
24144 			}
24145 
24146 			/*
24147 			 * We increment timestamp so we know it's been set;
24148 			 * this is undone when we put it in the HSP
24149 			 */
24150 			timestamp++;
24151 			value = end;
24152 		} else if (strncmp("delete", value, 6) == 0) {
24153 			value += 6;
24154 			delete = B_TRUE;
24155 		} else {
24156 			error = EINVAL;
24157 			goto done;
24158 		}
24159 	}
24160 
24161 	/* Hash address for lookup */
24162 
24163 	hash = TCP_HSP_HASH(addr);
24164 
24165 	if (delete) {
24166 		/*
24167 		 * Note that deletes don't return an error if the thing
24168 		 * we're trying to delete isn't there.
24169 		 */
24170 		if (tcps->tcps_hsp_hash == NULL)
24171 			goto done;
24172 		hsp = tcps->tcps_hsp_hash[hash];
24173 
24174 		if (hsp) {
24175 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24176 			    &v6addr)) {
24177 				tcps->tcps_hsp_hash[hash] = hsp->tcp_hsp_next;
24178 				mi_free((char *)hsp);
24179 			} else {
24180 				hspprev = hsp;
24181 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
24182 					if (IN6_ARE_ADDR_EQUAL(
24183 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
24184 						hspprev->tcp_hsp_next =
24185 						    hsp->tcp_hsp_next;
24186 						mi_free((char *)hsp);
24187 						break;
24188 					}
24189 					hspprev = hsp;
24190 				}
24191 			}
24192 		}
24193 	} else {
24194 		/*
24195 		 * We're adding/modifying an HSP.  If we haven't already done
24196 		 * so, allocate the hash table.
24197 		 */
24198 
24199 		if (!tcps->tcps_hsp_hash) {
24200 			tcps->tcps_hsp_hash = (tcp_hsp_t **)
24201 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
24202 			if (!tcps->tcps_hsp_hash) {
24203 				error = EINVAL;
24204 				goto done;
24205 			}
24206 		}
24207 
24208 		/* Get head of hash chain */
24209 
24210 		hsp = tcps->tcps_hsp_hash[hash];
24211 
24212 		/* Try to find pre-existing hsp on hash chain */
24213 		/* Doesn't handle CIDR prefixes. */
24214 		while (hsp) {
24215 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
24216 				break;
24217 			hsp = hsp->tcp_hsp_next;
24218 		}
24219 
24220 		/*
24221 		 * If we didn't, create one with default values and put it
24222 		 * at head of hash chain
24223 		 */
24224 
24225 		if (!hsp) {
24226 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
24227 			if (!hsp) {
24228 				error = EINVAL;
24229 				goto done;
24230 			}
24231 			hsp->tcp_hsp_next = tcps->tcps_hsp_hash[hash];
24232 			tcps->tcps_hsp_hash[hash] = hsp;
24233 		}
24234 
24235 		/* Set values that the user asked us to change */
24236 
24237 		hsp->tcp_hsp_addr_v6 = v6addr;
24238 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
24239 			hsp->tcp_hsp_vers = IPV4_VERSION;
24240 		else
24241 			hsp->tcp_hsp_vers = IPV6_VERSION;
24242 		hsp->tcp_hsp_subnet_v6 = v6mask;
24243 		if (sendspace > 0)
24244 			hsp->tcp_hsp_sendspace = sendspace;
24245 		if (recvspace > 0)
24246 			hsp->tcp_hsp_recvspace = recvspace;
24247 		if (timestamp > 0)
24248 			hsp->tcp_hsp_tstamp = timestamp - 1;
24249 	}
24250 
24251 done:
24252 	rw_exit(&tcps->tcps_hsp_lock);
24253 	return (error);
24254 }
24255 
24256 /* Set callback routine passed to nd_load by tcp_param_register. */
24257 /* ARGSUSED */
24258 static int
24259 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
24260 {
24261 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
24262 }
24263 /* ARGSUSED */
24264 static int
24265 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24266     cred_t *cr)
24267 {
24268 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
24269 }
24270 
24271 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
24272 /* ARGSUSED */
24273 static int
24274 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24275 {
24276 	tcp_hsp_t *hsp;
24277 	int i;
24278 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
24279 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24280 
24281 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24282 	(void) mi_mpprintf(mp,
24283 	    "Hash HSP     " MI_COL_HDRPAD_STR
24284 	    "Address         Subnet Mask     Send       Receive    TStamp");
24285 	if (tcps->tcps_hsp_hash) {
24286 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24287 			hsp = tcps->tcps_hsp_hash[i];
24288 			while (hsp) {
24289 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24290 					(void) inet_ntop(AF_INET,
24291 					    &hsp->tcp_hsp_addr,
24292 					    addrbuf, sizeof (addrbuf));
24293 					(void) inet_ntop(AF_INET,
24294 					    &hsp->tcp_hsp_subnet,
24295 					    subnetbuf, sizeof (subnetbuf));
24296 				} else {
24297 					(void) inet_ntop(AF_INET6,
24298 					    &hsp->tcp_hsp_addr_v6,
24299 					    addrbuf, sizeof (addrbuf));
24300 					(void) inet_ntop(AF_INET6,
24301 					    &hsp->tcp_hsp_subnet_v6,
24302 					    subnetbuf, sizeof (subnetbuf));
24303 				}
24304 				(void) mi_mpprintf(mp,
24305 				    " %03d " MI_COL_PTRFMT_STR
24306 				    "%s %s %010d %010d      %d",
24307 				    i,
24308 				    (void *)hsp,
24309 				    addrbuf,
24310 				    subnetbuf,
24311 				    hsp->tcp_hsp_sendspace,
24312 				    hsp->tcp_hsp_recvspace,
24313 				    hsp->tcp_hsp_tstamp);
24314 
24315 				hsp = hsp->tcp_hsp_next;
24316 			}
24317 		}
24318 	}
24319 	rw_exit(&tcps->tcps_hsp_lock);
24320 	return (0);
24321 }
24322 
24323 
24324 /* Data for fast netmask macro used by tcp_hsp_lookup */
24325 
24326 static ipaddr_t netmasks[] = {
24327 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24328 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24329 };
24330 
24331 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24332 
24333 /*
24334  * XXX This routine should go away and instead we should use the metrics
24335  * associated with the routes to determine the default sndspace and rcvspace.
24336  */
24337 static tcp_hsp_t *
24338 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24339 {
24340 	tcp_hsp_t *hsp = NULL;
24341 
24342 	/* Quick check without acquiring the lock. */
24343 	if (tcps->tcps_hsp_hash == NULL)
24344 		return (NULL);
24345 
24346 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24347 
24348 	/* This routine finds the best-matching HSP for address addr. */
24349 
24350 	if (tcps->tcps_hsp_hash) {
24351 		int i;
24352 		ipaddr_t srchaddr;
24353 		tcp_hsp_t *hsp_net;
24354 
24355 		/* We do three passes: host, network, and subnet. */
24356 
24357 		srchaddr = addr;
24358 
24359 		for (i = 1; i <= 3; i++) {
24360 			/* Look for exact match on srchaddr */
24361 
24362 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24363 			while (hsp) {
24364 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24365 				    hsp->tcp_hsp_addr == srchaddr)
24366 					break;
24367 				hsp = hsp->tcp_hsp_next;
24368 			}
24369 			ASSERT(hsp == NULL ||
24370 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24371 
24372 			/*
24373 			 * If this is the first pass:
24374 			 *   If we found a match, great, return it.
24375 			 *   If not, search for the network on the second pass.
24376 			 */
24377 
24378 			if (i == 1)
24379 				if (hsp)
24380 					break;
24381 				else
24382 				{
24383 					srchaddr = addr & netmask(addr);
24384 					continue;
24385 				}
24386 
24387 			/*
24388 			 * If this is the second pass:
24389 			 *   If we found a match, but there's a subnet mask,
24390 			 *    save the match but try again using the subnet
24391 			 *    mask on the third pass.
24392 			 *   Otherwise, return whatever we found.
24393 			 */
24394 
24395 			if (i == 2) {
24396 				if (hsp && hsp->tcp_hsp_subnet) {
24397 					hsp_net = hsp;
24398 					srchaddr = addr & hsp->tcp_hsp_subnet;
24399 					continue;
24400 				} else {
24401 					break;
24402 				}
24403 			}
24404 
24405 			/*
24406 			 * This must be the third pass.  If we didn't find
24407 			 * anything, return the saved network HSP instead.
24408 			 */
24409 
24410 			if (!hsp)
24411 				hsp = hsp_net;
24412 		}
24413 	}
24414 
24415 	rw_exit(&tcps->tcps_hsp_lock);
24416 	return (hsp);
24417 }
24418 
24419 /*
24420  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24421  * match lookup.
24422  */
24423 static tcp_hsp_t *
24424 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24425 {
24426 	tcp_hsp_t *hsp = NULL;
24427 
24428 	/* Quick check without acquiring the lock. */
24429 	if (tcps->tcps_hsp_hash == NULL)
24430 		return (NULL);
24431 
24432 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24433 
24434 	/* This routine finds the best-matching HSP for address addr. */
24435 
24436 	if (tcps->tcps_hsp_hash) {
24437 		int i;
24438 		in6_addr_t v6srchaddr;
24439 		tcp_hsp_t *hsp_net;
24440 
24441 		/* We do three passes: host, network, and subnet. */
24442 
24443 		v6srchaddr = *v6addr;
24444 
24445 		for (i = 1; i <= 3; i++) {
24446 			/* Look for exact match on srchaddr */
24447 
24448 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24449 			    V4_PART_OF_V6(v6srchaddr))];
24450 			while (hsp) {
24451 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24452 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24453 				    &v6srchaddr))
24454 					break;
24455 				hsp = hsp->tcp_hsp_next;
24456 			}
24457 
24458 			/*
24459 			 * If this is the first pass:
24460 			 *   If we found a match, great, return it.
24461 			 *   If not, search for the network on the second pass.
24462 			 */
24463 
24464 			if (i == 1)
24465 				if (hsp)
24466 					break;
24467 				else {
24468 					/* Assume a 64 bit mask */
24469 					v6srchaddr.s6_addr32[0] =
24470 					    v6addr->s6_addr32[0];
24471 					v6srchaddr.s6_addr32[1] =
24472 					    v6addr->s6_addr32[1];
24473 					v6srchaddr.s6_addr32[2] = 0;
24474 					v6srchaddr.s6_addr32[3] = 0;
24475 					continue;
24476 				}
24477 
24478 			/*
24479 			 * If this is the second pass:
24480 			 *   If we found a match, but there's a subnet mask,
24481 			 *    save the match but try again using the subnet
24482 			 *    mask on the third pass.
24483 			 *   Otherwise, return whatever we found.
24484 			 */
24485 
24486 			if (i == 2) {
24487 				ASSERT(hsp == NULL ||
24488 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24489 				if (hsp &&
24490 				    !IN6_IS_ADDR_UNSPECIFIED(
24491 				    &hsp->tcp_hsp_subnet_v6)) {
24492 					hsp_net = hsp;
24493 					V6_MASK_COPY(*v6addr,
24494 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24495 					continue;
24496 				} else {
24497 					break;
24498 				}
24499 			}
24500 
24501 			/*
24502 			 * This must be the third pass.  If we didn't find
24503 			 * anything, return the saved network HSP instead.
24504 			 */
24505 
24506 			if (!hsp)
24507 				hsp = hsp_net;
24508 		}
24509 	}
24510 
24511 	rw_exit(&tcps->tcps_hsp_lock);
24512 	return (hsp);
24513 }
24514 
24515 /*
24516  * Type three generator adapted from the random() function in 4.4 BSD:
24517  */
24518 
24519 /*
24520  * Copyright (c) 1983, 1993
24521  *	The Regents of the University of California.  All rights reserved.
24522  *
24523  * Redistribution and use in source and binary forms, with or without
24524  * modification, are permitted provided that the following conditions
24525  * are met:
24526  * 1. Redistributions of source code must retain the above copyright
24527  *    notice, this list of conditions and the following disclaimer.
24528  * 2. Redistributions in binary form must reproduce the above copyright
24529  *    notice, this list of conditions and the following disclaimer in the
24530  *    documentation and/or other materials provided with the distribution.
24531  * 3. All advertising materials mentioning features or use of this software
24532  *    must display the following acknowledgement:
24533  *	This product includes software developed by the University of
24534  *	California, Berkeley and its contributors.
24535  * 4. Neither the name of the University nor the names of its contributors
24536  *    may be used to endorse or promote products derived from this software
24537  *    without specific prior written permission.
24538  *
24539  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24540  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24541  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24542  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24543  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24544  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24545  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24546  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24547  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24548  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24549  * SUCH DAMAGE.
24550  */
24551 
24552 /* Type 3 -- x**31 + x**3 + 1 */
24553 #define	DEG_3		31
24554 #define	SEP_3		3
24555 
24556 
24557 /* Protected by tcp_random_lock */
24558 static int tcp_randtbl[DEG_3 + 1];
24559 
24560 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24561 static int *tcp_random_rptr = &tcp_randtbl[1];
24562 
24563 static int *tcp_random_state = &tcp_randtbl[1];
24564 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24565 
24566 kmutex_t tcp_random_lock;
24567 
24568 void
24569 tcp_random_init(void)
24570 {
24571 	int i;
24572 	hrtime_t hrt;
24573 	time_t wallclock;
24574 	uint64_t result;
24575 
24576 	/*
24577 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24578 	 * a longlong, which may contain resolution down to nanoseconds.
24579 	 * The current time will either be a 32-bit or a 64-bit quantity.
24580 	 * XOR the two together in a 64-bit result variable.
24581 	 * Convert the result to a 32-bit value by multiplying the high-order
24582 	 * 32-bits by the low-order 32-bits.
24583 	 */
24584 
24585 	hrt = gethrtime();
24586 	(void) drv_getparm(TIME, &wallclock);
24587 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24588 	mutex_enter(&tcp_random_lock);
24589 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24590 	    (result & 0xffffffff);
24591 
24592 	for (i = 1; i < DEG_3; i++)
24593 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24594 			+ 12345;
24595 	tcp_random_fptr = &tcp_random_state[SEP_3];
24596 	tcp_random_rptr = &tcp_random_state[0];
24597 	mutex_exit(&tcp_random_lock);
24598 	for (i = 0; i < 10 * DEG_3; i++)
24599 		(void) tcp_random();
24600 }
24601 
24602 /*
24603  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24604  * This range is selected to be approximately centered on TCP_ISS / 2,
24605  * and easy to compute. We get this value by generating a 32-bit random
24606  * number, selecting out the high-order 17 bits, and then adding one so
24607  * that we never return zero.
24608  */
24609 int
24610 tcp_random(void)
24611 {
24612 	int i;
24613 
24614 	mutex_enter(&tcp_random_lock);
24615 	*tcp_random_fptr += *tcp_random_rptr;
24616 
24617 	/*
24618 	 * The high-order bits are more random than the low-order bits,
24619 	 * so we select out the high-order 17 bits and add one so that
24620 	 * we never return zero.
24621 	 */
24622 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24623 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24624 		tcp_random_fptr = tcp_random_state;
24625 		++tcp_random_rptr;
24626 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24627 		tcp_random_rptr = tcp_random_state;
24628 
24629 	mutex_exit(&tcp_random_lock);
24630 	return (i);
24631 }
24632 
24633 /*
24634  * XXX This will go away when TPI is extended to send
24635  * info reqs to sockfs/timod .....
24636  * Given a queue, set the max packet size for the write
24637  * side of the queue below stream head.  This value is
24638  * cached on the stream head.
24639  * Returns 1 on success, 0 otherwise.
24640  */
24641 static int
24642 setmaxps(queue_t *q, int maxpsz)
24643 {
24644 	struct stdata	*stp;
24645 	queue_t		*wq;
24646 	stp = STREAM(q);
24647 
24648 	/*
24649 	 * At this point change of a queue parameter is not allowed
24650 	 * when a multiplexor is sitting on top.
24651 	 */
24652 	if (stp->sd_flag & STPLEX)
24653 		return (0);
24654 
24655 	claimstr(stp->sd_wrq);
24656 	wq = stp->sd_wrq->q_next;
24657 	ASSERT(wq != NULL);
24658 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24659 	releasestr(stp->sd_wrq);
24660 	return (1);
24661 }
24662 
24663 static int
24664 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24665     int *t_errorp, int *sys_errorp)
24666 {
24667 	int error;
24668 	int is_absreq_failure;
24669 	t_scalar_t *opt_lenp;
24670 	t_scalar_t opt_offset;
24671 	int prim_type;
24672 	struct T_conn_req *tcreqp;
24673 	struct T_conn_res *tcresp;
24674 	cred_t *cr;
24675 
24676 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24677 
24678 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24679 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24680 	    prim_type == T_CONN_RES);
24681 
24682 	switch (prim_type) {
24683 	case T_CONN_REQ:
24684 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24685 		opt_offset = tcreqp->OPT_offset;
24686 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24687 		break;
24688 	case O_T_CONN_RES:
24689 	case T_CONN_RES:
24690 		tcresp = (struct T_conn_res *)mp->b_rptr;
24691 		opt_offset = tcresp->OPT_offset;
24692 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24693 		break;
24694 	}
24695 
24696 	*t_errorp = 0;
24697 	*sys_errorp = 0;
24698 	*do_disconnectp = 0;
24699 
24700 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24701 	    opt_offset, cr, &tcp_opt_obj,
24702 	    NULL, &is_absreq_failure);
24703 
24704 	switch (error) {
24705 	case  0:		/* no error */
24706 		ASSERT(is_absreq_failure == 0);
24707 		return (0);
24708 	case ENOPROTOOPT:
24709 		*t_errorp = TBADOPT;
24710 		break;
24711 	case EACCES:
24712 		*t_errorp = TACCES;
24713 		break;
24714 	default:
24715 		*t_errorp = TSYSERR; *sys_errorp = error;
24716 		break;
24717 	}
24718 	if (is_absreq_failure != 0) {
24719 		/*
24720 		 * The connection request should get the local ack
24721 		 * T_OK_ACK and then a T_DISCON_IND.
24722 		 */
24723 		*do_disconnectp = 1;
24724 	}
24725 	return (-1);
24726 }
24727 
24728 /*
24729  * Split this function out so that if the secret changes, I'm okay.
24730  *
24731  * Initialize the tcp_iss_cookie and tcp_iss_key.
24732  */
24733 
24734 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24735 
24736 static void
24737 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24738 {
24739 	struct {
24740 		int32_t current_time;
24741 		uint32_t randnum;
24742 		uint16_t pad;
24743 		uint8_t ether[6];
24744 		uint8_t passwd[PASSWD_SIZE];
24745 	} tcp_iss_cookie;
24746 	time_t t;
24747 
24748 	/*
24749 	 * Start with the current absolute time.
24750 	 */
24751 	(void) drv_getparm(TIME, &t);
24752 	tcp_iss_cookie.current_time = t;
24753 
24754 	/*
24755 	 * XXX - Need a more random number per RFC 1750, not this crap.
24756 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24757 	 */
24758 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24759 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24760 
24761 	/*
24762 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24763 	 * as a good template.
24764 	 */
24765 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24766 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24767 
24768 	/*
24769 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24770 	 */
24771 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24772 
24773 	/*
24774 	 * See 4010593 if this section becomes a problem again,
24775 	 * but the local ethernet address is useful here.
24776 	 */
24777 	(void) localetheraddr(NULL,
24778 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24779 
24780 	/*
24781 	 * Hash 'em all together.  The MD5Final is called per-connection.
24782 	 */
24783 	mutex_enter(&tcps->tcps_iss_key_lock);
24784 	MD5Init(&tcps->tcps_iss_key);
24785 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24786 	    sizeof (tcp_iss_cookie));
24787 	mutex_exit(&tcps->tcps_iss_key_lock);
24788 }
24789 
24790 /*
24791  * Set the RFC 1948 pass phrase
24792  */
24793 /* ARGSUSED */
24794 static int
24795 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24796     cred_t *cr)
24797 {
24798 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24799 
24800 	/*
24801 	 * Basically, value contains a new pass phrase.  Pass it along!
24802 	 */
24803 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24804 	return (0);
24805 }
24806 
24807 /* ARGSUSED */
24808 static int
24809 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24810 {
24811 	bzero(buf, sizeof (tcp_sack_info_t));
24812 	return (0);
24813 }
24814 
24815 /* ARGSUSED */
24816 static int
24817 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24818 {
24819 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24820 	return (0);
24821 }
24822 
24823 /*
24824  * Make sure we wait until the default queue is setup, yet allow
24825  * tcp_g_q_create() to open a TCP stream.
24826  * We need to allow tcp_g_q_create() do do an open
24827  * of tcp, hence we compare curhread.
24828  * All others have to wait until the tcps_g_q has been
24829  * setup.
24830  */
24831 void
24832 tcp_g_q_setup(tcp_stack_t *tcps)
24833 {
24834 	mutex_enter(&tcps->tcps_g_q_lock);
24835 	if (tcps->tcps_g_q != NULL) {
24836 		mutex_exit(&tcps->tcps_g_q_lock);
24837 		return;
24838 	}
24839 	if (tcps->tcps_g_q_creator == NULL) {
24840 		/* This thread will set it up */
24841 		tcps->tcps_g_q_creator = curthread;
24842 		mutex_exit(&tcps->tcps_g_q_lock);
24843 		tcp_g_q_create(tcps);
24844 		mutex_enter(&tcps->tcps_g_q_lock);
24845 		ASSERT(tcps->tcps_g_q_creator == curthread);
24846 		tcps->tcps_g_q_creator = NULL;
24847 		cv_signal(&tcps->tcps_g_q_cv);
24848 		ASSERT(tcps->tcps_g_q != NULL);
24849 		mutex_exit(&tcps->tcps_g_q_lock);
24850 		return;
24851 	}
24852 	/* Everybody but the creator has to wait */
24853 	if (tcps->tcps_g_q_creator != curthread) {
24854 		while (tcps->tcps_g_q == NULL)
24855 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24856 	}
24857 	mutex_exit(&tcps->tcps_g_q_lock);
24858 }
24859 
24860 major_t IP_MAJ;
24861 #define	IP	"ip"
24862 
24863 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24864 
24865 /*
24866  * Create a default tcp queue here instead of in strplumb
24867  */
24868 void
24869 tcp_g_q_create(tcp_stack_t *tcps)
24870 {
24871 	int error;
24872 	ldi_handle_t	lh = NULL;
24873 	ldi_ident_t	li = NULL;
24874 	int		rval;
24875 	cred_t		*cr;
24876 
24877 #ifdef NS_DEBUG
24878 	(void) printf("tcp_g_q_create()\n");
24879 #endif
24880 
24881 	ASSERT(tcps->tcps_g_q_creator == curthread);
24882 
24883 	error = ldi_ident_from_major(IP_MAJ, &li);
24884 	if (error) {
24885 #ifdef DEBUG
24886 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24887 		    error);
24888 #endif
24889 		return;
24890 	}
24891 
24892 	cr = zone_get_kcred(netstackid_to_zoneid(
24893 				tcps->tcps_netstack->netstack_stackid));
24894 	ASSERT(cr != NULL);
24895 	/*
24896 	 * We set the tcp default queue to IPv6 because IPv4 falls
24897 	 * back to IPv6 when it can't find a client, but
24898 	 * IPv6 does not fall back to IPv4.
24899 	 */
24900 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24901 	if (error) {
24902 #ifdef DEBUG
24903 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24904 		    error);
24905 #endif
24906 		goto out;
24907 	}
24908 
24909 	/*
24910 	 * This ioctl causes the tcp framework to cache a pointer to
24911 	 * this stream, so we don't want to close the stream after
24912 	 * this operation.
24913 	 * Use the kernel credentials that are for the zone we're in.
24914 	 */
24915 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24916 	    (intptr_t)0, FKIOCTL, cr, &rval);
24917 	if (error) {
24918 #ifdef DEBUG
24919 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24920 		    "error %d\n", error);
24921 #endif
24922 		goto out;
24923 	}
24924 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24925 	lh = NULL;
24926 out:
24927 	/* Close layered handles */
24928 	if (li)
24929 		ldi_ident_release(li);
24930 	/* Keep cred around until _inactive needs it */
24931 	tcps->tcps_g_q_cr = cr;
24932 }
24933 
24934 /*
24935  * We keep tcp_g_q set until all other tcp_t's in the zone
24936  * has gone away, and then when tcp_g_q_inactive() is called
24937  * we clear it.
24938  */
24939 void
24940 tcp_g_q_destroy(tcp_stack_t *tcps)
24941 {
24942 #ifdef NS_DEBUG
24943 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24944 	    tcps->tcps_netstack->netstack_stackid);
24945 #endif
24946 
24947 	if (tcps->tcps_g_q == NULL) {
24948 		return;	/* Nothing to cleanup */
24949 	}
24950 	/*
24951 	 * Drop reference corresponding to the default queue.
24952 	 * This reference was added from tcp_open when the default queue
24953 	 * was created, hence we compensate for this extra drop in
24954 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24955 	 * the default queue was the last one to be open, in which
24956 	 * case, then tcp_g_q_inactive will be
24957 	 * called as a result of the refrele.
24958 	 */
24959 	TCPS_REFRELE(tcps);
24960 }
24961 
24962 /*
24963  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24964  * Run by tcp_q_q_inactive using a taskq.
24965  */
24966 static void
24967 tcp_g_q_close(void *arg)
24968 {
24969 	tcp_stack_t *tcps = arg;
24970 	int error;
24971 	ldi_handle_t	lh = NULL;
24972 	ldi_ident_t	li = NULL;
24973 	cred_t		*cr;
24974 
24975 #ifdef NS_DEBUG
24976 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24977 	    tcps->tcps_netstack->netstack_stackid,
24978 	    tcps->tcps_netstack->netstack_refcnt);
24979 #endif
24980 	lh = tcps->tcps_g_q_lh;
24981 	if (lh == NULL)
24982 		return;	/* Nothing to cleanup */
24983 
24984 	ASSERT(tcps->tcps_refcnt == 1);
24985 	ASSERT(tcps->tcps_g_q != NULL);
24986 
24987 	error = ldi_ident_from_major(IP_MAJ, &li);
24988 	if (error) {
24989 #ifdef DEBUG
24990 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24991 		    error);
24992 #endif
24993 		return;
24994 	}
24995 
24996 	cr = tcps->tcps_g_q_cr;
24997 	tcps->tcps_g_q_cr = NULL;
24998 	ASSERT(cr != NULL);
24999 
25000 	/*
25001 	 * Make sure we can break the recursion when tcp_close decrements
25002 	 * the reference count causing g_q_inactive to be called again.
25003 	 */
25004 	tcps->tcps_g_q_lh = NULL;
25005 
25006 	/* close the default queue */
25007 	(void) ldi_close(lh, FREAD|FWRITE, cr);
25008 	/*
25009 	 * At this point in time tcps and the rest of netstack_t might
25010 	 * have been deleted.
25011 	 */
25012 	tcps = NULL;
25013 
25014 	/* Close layered handles */
25015 	ldi_ident_release(li);
25016 	crfree(cr);
25017 }
25018 
25019 /*
25020  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25021  *
25022  * Have to ensure that the ldi routines are not used by an
25023  * interrupt thread by using a taskq.
25024  */
25025 void
25026 tcp_g_q_inactive(tcp_stack_t *tcps)
25027 {
25028 	if (tcps->tcps_g_q_lh == NULL)
25029 		return;	/* Nothing to cleanup */
25030 
25031 	ASSERT(tcps->tcps_refcnt == 0);
25032 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
25033 
25034 	if (servicing_interrupt()) {
25035 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
25036 			    (void *) tcps, TQ_SLEEP);
25037 	} else {
25038 		tcp_g_q_close(tcps);
25039 	}
25040 }
25041 
25042 /*
25043  * Called by IP when IP is loaded into the kernel
25044  */
25045 void
25046 tcp_ddi_g_init(void)
25047 {
25048 	IP_MAJ = ddi_name_to_major(IP);
25049 
25050 	tcp_timercache = kmem_cache_create("tcp_timercache",
25051 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
25052 	    NULL, NULL, NULL, NULL, NULL, 0);
25053 
25054 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
25055 	    sizeof (tcp_sack_info_t), 0,
25056 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
25057 
25058 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
25059 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
25060 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
25061 
25062 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
25063 
25064 	/* Initialize the random number generator */
25065 	tcp_random_init();
25066 
25067 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
25068 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
25069 
25070 	/* A single callback independently of how many netstacks we have */
25071 	ip_squeue_init(tcp_squeue_add);
25072 
25073 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
25074 
25075 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
25076 	    TASKQ_PREPOPULATE);
25077 
25078 	/*
25079 	 * We want to be informed each time a stack is created or
25080 	 * destroyed in the kernel, so we can maintain the
25081 	 * set of tcp_stack_t's.
25082 	 */
25083 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
25084 	    tcp_stack_fini);
25085 }
25086 
25087 
25088 /*
25089  * Initialize the TCP stack instance.
25090  */
25091 static void *
25092 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
25093 {
25094 	tcp_stack_t	*tcps;
25095 	tcpparam_t	*pa;
25096 	int		i;
25097 
25098 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
25099 	tcps->tcps_netstack = ns;
25100 
25101 	/* Initialize locks */
25102 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
25103 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
25104 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
25105 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
25106 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
25107 	rw_init(&tcps->tcps_reserved_port_lock, NULL, RW_DEFAULT, NULL);
25108 
25109 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
25110 	tcps->tcps_g_epriv_ports[0] = 2049;
25111 	tcps->tcps_g_epriv_ports[1] = 4045;
25112 	tcps->tcps_min_anonpriv_port = 512;
25113 
25114 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
25115 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
25116 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
25117 	    TCP_FANOUT_SIZE, KM_SLEEP);
25118 	tcps->tcps_reserved_port = kmem_zalloc(sizeof (tcp_rport_t) *
25119 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE, KM_SLEEP);
25120 
25121 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25122 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
25123 		    MUTEX_DEFAULT, NULL);
25124 	}
25125 
25126 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25127 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25128 		    MUTEX_DEFAULT, NULL);
25129 	}
25130 
25131 	/* TCP's IPsec code calls the packet dropper. */
25132 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25133 
25134 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25135 	tcps->tcps_params = pa;
25136 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25137 
25138 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25139 	    A_CNT(lcl_tcp_param_arr), tcps);
25140 
25141 	/*
25142 	 * Note: To really walk the device tree you need the devinfo
25143 	 * pointer to your device which is only available after probe/attach.
25144 	 * The following is safe only because it uses ddi_root_node()
25145 	 */
25146 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25147 	    tcp_opt_obj.odb_opt_arr_cnt);
25148 
25149 	/*
25150 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25151 	 * by the boot scripts.
25152 	 *
25153 	 * Use NULL name, as the name is caught by the new lockstats.
25154 	 *
25155 	 * Initialize with some random, non-guessable string, like the global
25156 	 * T_INFO_ACK.
25157 	 */
25158 
25159 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25160 	    sizeof (tcp_g_t_info_ack), tcps);
25161 
25162 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25163 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25164 
25165 	return (tcps);
25166 }
25167 
25168 /*
25169  * Called when the IP module is about to be unloaded.
25170  */
25171 void
25172 tcp_ddi_g_destroy(void)
25173 {
25174 	tcp_g_kstat_fini(tcp_g_kstat);
25175 	tcp_g_kstat = NULL;
25176 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25177 
25178 	mutex_destroy(&tcp_random_lock);
25179 
25180 	kmem_cache_destroy(tcp_timercache);
25181 	kmem_cache_destroy(tcp_sack_info_cache);
25182 	kmem_cache_destroy(tcp_iphc_cache);
25183 
25184 	netstack_unregister(NS_TCP);
25185 	taskq_destroy(tcp_taskq);
25186 }
25187 
25188 /*
25189  * Shut down the TCP stack instance.
25190  */
25191 /* ARGSUSED */
25192 static void
25193 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25194 {
25195 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25196 
25197 	tcp_g_q_destroy(tcps);
25198 }
25199 
25200 /*
25201  * Free the TCP stack instance.
25202  */
25203 static void
25204 tcp_stack_fini(netstackid_t stackid, void *arg)
25205 {
25206 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25207 	int i;
25208 
25209 	nd_free(&tcps->tcps_g_nd);
25210 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25211 	tcps->tcps_params = NULL;
25212 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25213 	tcps->tcps_wroff_xtra_param = NULL;
25214 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25215 	tcps->tcps_mdt_head_param = NULL;
25216 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25217 	tcps->tcps_mdt_tail_param = NULL;
25218 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25219 	tcps->tcps_mdt_max_pbufs_param = NULL;
25220 
25221 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25222 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25223 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25224 	}
25225 
25226 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25227 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25228 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25229 	}
25230 
25231 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25232 	tcps->tcps_bind_fanout = NULL;
25233 
25234 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25235 	tcps->tcps_acceptor_fanout = NULL;
25236 
25237 	kmem_free(tcps->tcps_reserved_port, sizeof (tcp_rport_t) *
25238 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE);
25239 	tcps->tcps_reserved_port = NULL;
25240 
25241 	mutex_destroy(&tcps->tcps_iss_key_lock);
25242 	rw_destroy(&tcps->tcps_hsp_lock);
25243 	mutex_destroy(&tcps->tcps_g_q_lock);
25244 	cv_destroy(&tcps->tcps_g_q_cv);
25245 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25246 	rw_destroy(&tcps->tcps_reserved_port_lock);
25247 
25248 	ip_drop_unregister(&tcps->tcps_dropper);
25249 
25250 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25251 	tcps->tcps_kstat = NULL;
25252 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25253 
25254 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25255 	tcps->tcps_mibkp = NULL;
25256 
25257 	kmem_free(tcps, sizeof (*tcps));
25258 }
25259 
25260 /*
25261  * Generate ISS, taking into account NDD changes may happen halfway through.
25262  * (If the iss is not zero, set it.)
25263  */
25264 
25265 static void
25266 tcp_iss_init(tcp_t *tcp)
25267 {
25268 	MD5_CTX context;
25269 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25270 	uint32_t answer[4];
25271 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25272 
25273 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25274 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25275 	switch (tcps->tcps_strong_iss) {
25276 	case 2:
25277 		mutex_enter(&tcps->tcps_iss_key_lock);
25278 		context = tcps->tcps_iss_key;
25279 		mutex_exit(&tcps->tcps_iss_key_lock);
25280 		arg.ports = tcp->tcp_ports;
25281 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25282 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25283 			    &arg.src);
25284 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25285 			    &arg.dst);
25286 		} else {
25287 			arg.src = tcp->tcp_ip6h->ip6_src;
25288 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25289 		}
25290 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25291 		MD5Final((uchar_t *)answer, &context);
25292 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25293 		/*
25294 		 * Now that we've hashed into a unique per-connection sequence
25295 		 * space, add a random increment per strong_iss == 1.  So I
25296 		 * guess we'll have to...
25297 		 */
25298 		/* FALLTHRU */
25299 	case 1:
25300 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25301 		break;
25302 	default:
25303 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25304 		break;
25305 	}
25306 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25307 	tcp->tcp_fss = tcp->tcp_iss - 1;
25308 	tcp->tcp_suna = tcp->tcp_iss;
25309 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25310 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25311 	tcp->tcp_csuna = tcp->tcp_snxt;
25312 }
25313 
25314 /*
25315  * Exported routine for extracting active tcp connection status.
25316  *
25317  * This is used by the Solaris Cluster Networking software to
25318  * gather a list of connections that need to be forwarded to
25319  * specific nodes in the cluster when configuration changes occur.
25320  *
25321  * The callback is invoked for each tcp_t structure. Returning
25322  * non-zero from the callback routine terminates the search.
25323  */
25324 int
25325 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25326     void *arg)
25327 {
25328 	netstack_handle_t nh;
25329 	netstack_t *ns;
25330 	int ret = 0;
25331 
25332 	netstack_next_init(&nh);
25333 	while ((ns = netstack_next(&nh)) != NULL) {
25334 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25335 		    ns->netstack_tcp);
25336 		netstack_rele(ns);
25337 	}
25338 	netstack_next_fini(&nh);
25339 	return (ret);
25340 }
25341 
25342 static int
25343 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25344     tcp_stack_t *tcps)
25345 {
25346 	tcp_t *tcp;
25347 	cl_tcp_info_t	cl_tcpi;
25348 	connf_t	*connfp;
25349 	conn_t	*connp;
25350 	int	i;
25351 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25352 
25353 	ASSERT(callback != NULL);
25354 
25355 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25356 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25357 		connp = NULL;
25358 
25359 		while ((connp =
25360 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25361 
25362 			tcp = connp->conn_tcp;
25363 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25364 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25365 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25366 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25367 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25368 			/*
25369 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25370 			 * addresses. They are copied implicitly below as
25371 			 * mapped addresses.
25372 			 */
25373 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25374 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25375 				cl_tcpi.cl_tcpi_faddr =
25376 				    tcp->tcp_ipha->ipha_dst;
25377 			} else {
25378 				cl_tcpi.cl_tcpi_faddr_v6 =
25379 				    tcp->tcp_ip6h->ip6_dst;
25380 			}
25381 
25382 			/*
25383 			 * If the callback returns non-zero
25384 			 * we terminate the traversal.
25385 			 */
25386 			if ((*callback)(&cl_tcpi, arg) != 0) {
25387 				CONN_DEC_REF(tcp->tcp_connp);
25388 				return (1);
25389 			}
25390 		}
25391 	}
25392 
25393 	return (0);
25394 }
25395 
25396 /*
25397  * Macros used for accessing the different types of sockaddr
25398  * structures inside a tcp_ioc_abort_conn_t.
25399  */
25400 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25401 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25402 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25403 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25404 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25405 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25406 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25407 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25408 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25409 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25410 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25411 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25412 
25413 /*
25414  * Return the correct error code to mimic the behavior
25415  * of a connection reset.
25416  */
25417 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25418 		switch ((state)) {		\
25419 		case TCPS_SYN_SENT:		\
25420 		case TCPS_SYN_RCVD:		\
25421 			(err) = ECONNREFUSED;	\
25422 			break;			\
25423 		case TCPS_ESTABLISHED:		\
25424 		case TCPS_FIN_WAIT_1:		\
25425 		case TCPS_FIN_WAIT_2:		\
25426 		case TCPS_CLOSE_WAIT:		\
25427 			(err) = ECONNRESET;	\
25428 			break;			\
25429 		case TCPS_CLOSING:		\
25430 		case TCPS_LAST_ACK:		\
25431 		case TCPS_TIME_WAIT:		\
25432 			(err) = 0;		\
25433 			break;			\
25434 		default:			\
25435 			(err) = ENXIO;		\
25436 		}				\
25437 	}
25438 
25439 /*
25440  * Check if a tcp structure matches the info in acp.
25441  */
25442 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25443 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25444 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25445 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25446 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25447 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25448 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25449 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25450 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25451 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25452 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25453 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25454 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25455 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25456 	&(tcp)->tcp_ip_src_v6)) &&				\
25457 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25458 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25459 	&(tcp)->tcp_remote_v6)) &&				\
25460 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25461 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25462 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25463 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25464 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25465 	(acp)->ac_end >= (tcp)->tcp_state))
25466 
25467 #define	TCP_AC_MATCH(acp, tcp)					\
25468 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25469 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25470 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25471 
25472 /*
25473  * Build a message containing a tcp_ioc_abort_conn_t structure
25474  * which is filled in with information from acp and tp.
25475  */
25476 static mblk_t *
25477 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25478 {
25479 	mblk_t *mp;
25480 	tcp_ioc_abort_conn_t *tacp;
25481 
25482 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25483 	if (mp == NULL)
25484 		return (NULL);
25485 
25486 	mp->b_datap->db_type = M_CTL;
25487 
25488 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25489 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25490 		sizeof (uint32_t));
25491 
25492 	tacp->ac_start = acp->ac_start;
25493 	tacp->ac_end = acp->ac_end;
25494 	tacp->ac_zoneid = acp->ac_zoneid;
25495 
25496 	if (acp->ac_local.ss_family == AF_INET) {
25497 		tacp->ac_local.ss_family = AF_INET;
25498 		tacp->ac_remote.ss_family = AF_INET;
25499 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25500 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25501 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25502 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25503 	} else {
25504 		tacp->ac_local.ss_family = AF_INET6;
25505 		tacp->ac_remote.ss_family = AF_INET6;
25506 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25507 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25508 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25509 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25510 	}
25511 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25512 	return (mp);
25513 }
25514 
25515 /*
25516  * Print a tcp_ioc_abort_conn_t structure.
25517  */
25518 static void
25519 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25520 {
25521 	char lbuf[128];
25522 	char rbuf[128];
25523 	sa_family_t af;
25524 	in_port_t lport, rport;
25525 	ushort_t logflags;
25526 
25527 	af = acp->ac_local.ss_family;
25528 
25529 	if (af == AF_INET) {
25530 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25531 				lbuf, 128);
25532 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25533 				rbuf, 128);
25534 		lport = ntohs(TCP_AC_V4LPORT(acp));
25535 		rport = ntohs(TCP_AC_V4RPORT(acp));
25536 	} else {
25537 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25538 				lbuf, 128);
25539 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25540 				rbuf, 128);
25541 		lport = ntohs(TCP_AC_V6LPORT(acp));
25542 		rport = ntohs(TCP_AC_V6RPORT(acp));
25543 	}
25544 
25545 	logflags = SL_TRACE | SL_NOTE;
25546 	/*
25547 	 * Don't print this message to the console if the operation was done
25548 	 * to a non-global zone.
25549 	 */
25550 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25551 		logflags |= SL_CONSOLE;
25552 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25553 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25554 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25555 		acp->ac_start, acp->ac_end);
25556 }
25557 
25558 /*
25559  * Called inside tcp_rput when a message built using
25560  * tcp_ioctl_abort_build_msg is put into a queue.
25561  * Note that when we get here there is no wildcard in acp any more.
25562  */
25563 static void
25564 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25565 {
25566 	tcp_ioc_abort_conn_t *acp;
25567 
25568 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25569 	if (tcp->tcp_state <= acp->ac_end) {
25570 		/*
25571 		 * If we get here, we are already on the correct
25572 		 * squeue. This ioctl follows the following path
25573 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25574 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25575 		 * different squeue)
25576 		 */
25577 		int errcode;
25578 
25579 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25580 		(void) tcp_clean_death(tcp, errcode, 26);
25581 	}
25582 	freemsg(mp);
25583 }
25584 
25585 /*
25586  * Abort all matching connections on a hash chain.
25587  */
25588 static int
25589 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25590     boolean_t exact, tcp_stack_t *tcps)
25591 {
25592 	int nmatch, err = 0;
25593 	tcp_t *tcp;
25594 	MBLKP mp, last, listhead = NULL;
25595 	conn_t	*tconnp;
25596 	connf_t	*connfp;
25597 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25598 
25599 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25600 
25601 startover:
25602 	nmatch = 0;
25603 
25604 	mutex_enter(&connfp->connf_lock);
25605 	for (tconnp = connfp->connf_head; tconnp != NULL;
25606 	    tconnp = tconnp->conn_next) {
25607 		tcp = tconnp->conn_tcp;
25608 		if (TCP_AC_MATCH(acp, tcp)) {
25609 			CONN_INC_REF(tcp->tcp_connp);
25610 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25611 			if (mp == NULL) {
25612 				err = ENOMEM;
25613 				CONN_DEC_REF(tcp->tcp_connp);
25614 				break;
25615 			}
25616 			mp->b_prev = (mblk_t *)tcp;
25617 
25618 			if (listhead == NULL) {
25619 				listhead = mp;
25620 				last = mp;
25621 			} else {
25622 				last->b_next = mp;
25623 				last = mp;
25624 			}
25625 			nmatch++;
25626 			if (exact)
25627 				break;
25628 		}
25629 
25630 		/* Avoid holding lock for too long. */
25631 		if (nmatch >= 500)
25632 			break;
25633 	}
25634 	mutex_exit(&connfp->connf_lock);
25635 
25636 	/* Pass mp into the correct tcp */
25637 	while ((mp = listhead) != NULL) {
25638 		listhead = listhead->b_next;
25639 		tcp = (tcp_t *)mp->b_prev;
25640 		mp->b_next = mp->b_prev = NULL;
25641 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25642 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25643 	}
25644 
25645 	*count += nmatch;
25646 	if (nmatch >= 500 && err == 0)
25647 		goto startover;
25648 	return (err);
25649 }
25650 
25651 /*
25652  * Abort all connections that matches the attributes specified in acp.
25653  */
25654 static int
25655 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25656 {
25657 	sa_family_t af;
25658 	uint32_t  ports;
25659 	uint16_t *pports;
25660 	int err = 0, count = 0;
25661 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25662 	int index = -1;
25663 	ushort_t logflags;
25664 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25665 
25666 	af = acp->ac_local.ss_family;
25667 
25668 	if (af == AF_INET) {
25669 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25670 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25671 			pports = (uint16_t *)&ports;
25672 			pports[1] = TCP_AC_V4LPORT(acp);
25673 			pports[0] = TCP_AC_V4RPORT(acp);
25674 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25675 		}
25676 	} else {
25677 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25678 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25679 			pports = (uint16_t *)&ports;
25680 			pports[1] = TCP_AC_V6LPORT(acp);
25681 			pports[0] = TCP_AC_V6RPORT(acp);
25682 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25683 		}
25684 	}
25685 
25686 	/*
25687 	 * For cases where remote addr, local port, and remote port are non-
25688 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25689 	 */
25690 	if (index != -1) {
25691 		err = tcp_ioctl_abort_bucket(acp, index,
25692 			    &count, exact, tcps);
25693 	} else {
25694 		/*
25695 		 * loop through all entries for wildcard case
25696 		 */
25697 		for (index = 0;
25698 		    index < ipst->ips_ipcl_conn_fanout_size;
25699 		    index++) {
25700 			err = tcp_ioctl_abort_bucket(acp, index,
25701 			    &count, exact, tcps);
25702 			if (err != 0)
25703 				break;
25704 		}
25705 	}
25706 
25707 	logflags = SL_TRACE | SL_NOTE;
25708 	/*
25709 	 * Don't print this message to the console if the operation was done
25710 	 * to a non-global zone.
25711 	 */
25712 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25713 		logflags |= SL_CONSOLE;
25714 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25715 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25716 	if (err == 0 && count == 0)
25717 		err = ENOENT;
25718 	return (err);
25719 }
25720 
25721 /*
25722  * Process the TCP_IOC_ABORT_CONN ioctl request.
25723  */
25724 static void
25725 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25726 {
25727 	int	err;
25728 	IOCP    iocp;
25729 	MBLKP   mp1;
25730 	sa_family_t laf, raf;
25731 	tcp_ioc_abort_conn_t *acp;
25732 	zone_t		*zptr;
25733 	conn_t		*connp = Q_TO_CONN(q);
25734 	zoneid_t	zoneid = connp->conn_zoneid;
25735 	tcp_t		*tcp = connp->conn_tcp;
25736 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25737 
25738 	iocp = (IOCP)mp->b_rptr;
25739 
25740 	if ((mp1 = mp->b_cont) == NULL ||
25741 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25742 		err = EINVAL;
25743 		goto out;
25744 	}
25745 
25746 	/* check permissions */
25747 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25748 		err = EPERM;
25749 		goto out;
25750 	}
25751 
25752 	if (mp1->b_cont != NULL) {
25753 		freemsg(mp1->b_cont);
25754 		mp1->b_cont = NULL;
25755 	}
25756 
25757 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25758 	laf = acp->ac_local.ss_family;
25759 	raf = acp->ac_remote.ss_family;
25760 
25761 	/* check that a zone with the supplied zoneid exists */
25762 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25763 		zptr = zone_find_by_id(zoneid);
25764 		if (zptr != NULL) {
25765 			zone_rele(zptr);
25766 		} else {
25767 			err = EINVAL;
25768 			goto out;
25769 		}
25770 	}
25771 
25772 	/*
25773 	 * For exclusive stacks we set the zoneid to zero
25774 	 * to make TCP operate as if in the global zone.
25775 	 */
25776 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25777 		acp->ac_zoneid = GLOBAL_ZONEID;
25778 
25779 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25780 	    acp->ac_start > acp->ac_end || laf != raf ||
25781 	    (laf != AF_INET && laf != AF_INET6)) {
25782 		err = EINVAL;
25783 		goto out;
25784 	}
25785 
25786 	tcp_ioctl_abort_dump(acp);
25787 	err = tcp_ioctl_abort(acp, tcps);
25788 
25789 out:
25790 	if (mp1 != NULL) {
25791 		freemsg(mp1);
25792 		mp->b_cont = NULL;
25793 	}
25794 
25795 	if (err != 0)
25796 		miocnak(q, mp, 0, err);
25797 	else
25798 		miocack(q, mp, 0, 0);
25799 }
25800 
25801 /*
25802  * tcp_time_wait_processing() handles processing of incoming packets when
25803  * the tcp is in the TIME_WAIT state.
25804  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25805  * on the time wait list.
25806  */
25807 void
25808 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25809     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25810 {
25811 	int32_t		bytes_acked;
25812 	int32_t		gap;
25813 	int32_t		rgap;
25814 	tcp_opt_t	tcpopt;
25815 	uint_t		flags;
25816 	uint32_t	new_swnd = 0;
25817 	conn_t		*connp;
25818 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25819 
25820 	BUMP_LOCAL(tcp->tcp_ibsegs);
25821 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
25822 
25823 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25824 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25825 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25826 	if (tcp->tcp_snd_ts_ok) {
25827 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25828 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25829 			    tcp->tcp_rnxt, TH_ACK);
25830 			goto done;
25831 		}
25832 	}
25833 	gap = seg_seq - tcp->tcp_rnxt;
25834 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25835 	if (gap < 0) {
25836 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25837 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25838 		    (seg_len > -gap ? -gap : seg_len));
25839 		seg_len += gap;
25840 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25841 			if (flags & TH_RST) {
25842 				goto done;
25843 			}
25844 			if ((flags & TH_FIN) && seg_len == -1) {
25845 				/*
25846 				 * When TCP receives a duplicate FIN in
25847 				 * TIME_WAIT state, restart the 2 MSL timer.
25848 				 * See page 73 in RFC 793. Make sure this TCP
25849 				 * is already on the TIME_WAIT list. If not,
25850 				 * just restart the timer.
25851 				 */
25852 				if (TCP_IS_DETACHED(tcp)) {
25853 					if (tcp_time_wait_remove(tcp, NULL) ==
25854 					    B_TRUE) {
25855 						tcp_time_wait_append(tcp);
25856 						TCP_DBGSTAT(tcps,
25857 						    tcp_rput_time_wait);
25858 					}
25859 				} else {
25860 					ASSERT(tcp != NULL);
25861 					TCP_TIMER_RESTART(tcp,
25862 					    tcps->tcps_time_wait_interval);
25863 				}
25864 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25865 				    tcp->tcp_rnxt, TH_ACK);
25866 				goto done;
25867 			}
25868 			flags |=  TH_ACK_NEEDED;
25869 			seg_len = 0;
25870 			goto process_ack;
25871 		}
25872 
25873 		/* Fix seg_seq, and chew the gap off the front. */
25874 		seg_seq = tcp->tcp_rnxt;
25875 	}
25876 
25877 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25878 		/*
25879 		 * Make sure that when we accept the connection, pick
25880 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25881 		 * old connection.
25882 		 *
25883 		 * The next ISS generated is equal to tcp_iss_incr_extra
25884 		 * + ISS_INCR/2 + other components depending on the
25885 		 * value of tcp_strong_iss.  We pre-calculate the new
25886 		 * ISS here and compare with tcp_snxt to determine if
25887 		 * we need to make adjustment to tcp_iss_incr_extra.
25888 		 *
25889 		 * The above calculation is ugly and is a
25890 		 * waste of CPU cycles...
25891 		 */
25892 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25893 		int32_t adj;
25894 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25895 
25896 		switch (tcps->tcps_strong_iss) {
25897 		case 2: {
25898 			/* Add time and MD5 components. */
25899 			uint32_t answer[4];
25900 			struct {
25901 				uint32_t ports;
25902 				in6_addr_t src;
25903 				in6_addr_t dst;
25904 			} arg;
25905 			MD5_CTX context;
25906 
25907 			mutex_enter(&tcps->tcps_iss_key_lock);
25908 			context = tcps->tcps_iss_key;
25909 			mutex_exit(&tcps->tcps_iss_key_lock);
25910 			arg.ports = tcp->tcp_ports;
25911 			/* We use MAPPED addresses in tcp_iss_init */
25912 			arg.src = tcp->tcp_ip_src_v6;
25913 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25914 				IN6_IPADDR_TO_V4MAPPED(
25915 					tcp->tcp_ipha->ipha_dst,
25916 					    &arg.dst);
25917 			} else {
25918 				arg.dst =
25919 				    tcp->tcp_ip6h->ip6_dst;
25920 			}
25921 			MD5Update(&context, (uchar_t *)&arg,
25922 			    sizeof (arg));
25923 			MD5Final((uchar_t *)answer, &context);
25924 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25925 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25926 			break;
25927 		}
25928 		case 1:
25929 			/* Add time component and min random (i.e. 1). */
25930 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25931 			break;
25932 		default:
25933 			/* Add only time component. */
25934 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25935 			break;
25936 		}
25937 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25938 			/*
25939 			 * New ISS not guaranteed to be ISS_INCR/2
25940 			 * ahead of the current tcp_snxt, so add the
25941 			 * difference to tcp_iss_incr_extra.
25942 			 */
25943 			tcps->tcps_iss_incr_extra += adj;
25944 		}
25945 		/*
25946 		 * If tcp_clean_death() can not perform the task now,
25947 		 * drop the SYN packet and let the other side re-xmit.
25948 		 * Otherwise pass the SYN packet back in, since the
25949 		 * old tcp state has been cleaned up or freed.
25950 		 */
25951 		if (tcp_clean_death(tcp, 0, 27) == -1)
25952 			goto done;
25953 		/*
25954 		 * We will come back to tcp_rput_data
25955 		 * on the global queue. Packets destined
25956 		 * for the global queue will be checked
25957 		 * with global policy. But the policy for
25958 		 * this packet has already been checked as
25959 		 * this was destined for the detached
25960 		 * connection. We need to bypass policy
25961 		 * check this time by attaching a dummy
25962 		 * ipsec_in with ipsec_in_dont_check set.
25963 		 */
25964 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25965 		if (connp != NULL) {
25966 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25967 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25968 			return;
25969 		}
25970 		goto done;
25971 	}
25972 
25973 	/*
25974 	 * rgap is the amount of stuff received out of window.  A negative
25975 	 * value is the amount out of window.
25976 	 */
25977 	if (rgap < 0) {
25978 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25979 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25980 		/* Fix seg_len and make sure there is something left. */
25981 		seg_len += rgap;
25982 		if (seg_len <= 0) {
25983 			if (flags & TH_RST) {
25984 				goto done;
25985 			}
25986 			flags |=  TH_ACK_NEEDED;
25987 			seg_len = 0;
25988 			goto process_ack;
25989 		}
25990 	}
25991 	/*
25992 	 * Check whether we can update tcp_ts_recent.  This test is
25993 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25994 	 * Extensions for High Performance: An Update", Internet Draft.
25995 	 */
25996 	if (tcp->tcp_snd_ts_ok &&
25997 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25998 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25999 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
26000 		tcp->tcp_last_rcv_lbolt = lbolt64;
26001 	}
26002 
26003 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
26004 		/* Always ack out of order packets */
26005 		flags |= TH_ACK_NEEDED;
26006 		seg_len = 0;
26007 	} else if (seg_len > 0) {
26008 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
26009 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
26010 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
26011 	}
26012 	if (flags & TH_RST) {
26013 		(void) tcp_clean_death(tcp, 0, 28);
26014 		goto done;
26015 	}
26016 	if (flags & TH_SYN) {
26017 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
26018 		    TH_RST|TH_ACK);
26019 		/*
26020 		 * Do not delete the TCP structure if it is in
26021 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
26022 		 */
26023 		goto done;
26024 	}
26025 process_ack:
26026 	if (flags & TH_ACK) {
26027 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
26028 		if (bytes_acked <= 0) {
26029 			if (bytes_acked == 0 && seg_len == 0 &&
26030 			    new_swnd == tcp->tcp_swnd)
26031 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
26032 		} else {
26033 			/* Acks something not sent */
26034 			flags |= TH_ACK_NEEDED;
26035 		}
26036 	}
26037 	if (flags & TH_ACK_NEEDED) {
26038 		/*
26039 		 * Time to send an ack for some reason.
26040 		 */
26041 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26042 		    tcp->tcp_rnxt, TH_ACK);
26043 	}
26044 done:
26045 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26046 		DB_CKSUMSTART(mp) = 0;
26047 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
26048 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
26049 	}
26050 	freemsg(mp);
26051 }
26052 
26053 /*
26054  * Allocate a T_SVR4_OPTMGMT_REQ.
26055  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
26056  * that tcp_rput_other can drop the acks.
26057  */
26058 static mblk_t *
26059 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
26060 {
26061 	mblk_t *mp;
26062 	struct T_optmgmt_req *tor;
26063 	struct opthdr *oh;
26064 	uint_t size;
26065 	char *optptr;
26066 
26067 	size = sizeof (*tor) + sizeof (*oh) + optlen;
26068 	mp = allocb(size, BPRI_MED);
26069 	if (mp == NULL)
26070 		return (NULL);
26071 
26072 	mp->b_wptr += size;
26073 	mp->b_datap->db_type = M_PROTO;
26074 	tor = (struct T_optmgmt_req *)mp->b_rptr;
26075 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
26076 	tor->MGMT_flags = T_NEGOTIATE;
26077 	tor->OPT_length = sizeof (*oh) + optlen;
26078 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
26079 
26080 	oh = (struct opthdr *)&tor[1];
26081 	oh->level = level;
26082 	oh->name = cmd;
26083 	oh->len = optlen;
26084 	if (optlen != 0) {
26085 		optptr = (char *)&oh[1];
26086 		bcopy(opt, optptr, optlen);
26087 	}
26088 	return (mp);
26089 }
26090 
26091 /*
26092  * TCP Timers Implementation.
26093  */
26094 timeout_id_t
26095 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
26096 {
26097 	mblk_t *mp;
26098 	tcp_timer_t *tcpt;
26099 	tcp_t *tcp = connp->conn_tcp;
26100 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26101 
26102 	ASSERT(connp->conn_sqp != NULL);
26103 
26104 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
26105 
26106 	if (tcp->tcp_timercache == NULL) {
26107 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
26108 	} else {
26109 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
26110 		mp = tcp->tcp_timercache;
26111 		tcp->tcp_timercache = mp->b_next;
26112 		mp->b_next = NULL;
26113 		ASSERT(mp->b_wptr == NULL);
26114 	}
26115 
26116 	CONN_INC_REF(connp);
26117 	tcpt = (tcp_timer_t *)mp->b_rptr;
26118 	tcpt->connp = connp;
26119 	tcpt->tcpt_proc = f;
26120 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
26121 	return ((timeout_id_t)mp);
26122 }
26123 
26124 static void
26125 tcp_timer_callback(void *arg)
26126 {
26127 	mblk_t *mp = (mblk_t *)arg;
26128 	tcp_timer_t *tcpt;
26129 	conn_t	*connp;
26130 
26131 	tcpt = (tcp_timer_t *)mp->b_rptr;
26132 	connp = tcpt->connp;
26133 	squeue_fill(connp->conn_sqp, mp,
26134 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26135 }
26136 
26137 static void
26138 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26139 {
26140 	tcp_timer_t *tcpt;
26141 	conn_t *connp = (conn_t *)arg;
26142 	tcp_t *tcp = connp->conn_tcp;
26143 
26144 	tcpt = (tcp_timer_t *)mp->b_rptr;
26145 	ASSERT(connp == tcpt->connp);
26146 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26147 
26148 	/*
26149 	 * If the TCP has reached the closed state, don't proceed any
26150 	 * further. This TCP logically does not exist on the system.
26151 	 * tcpt_proc could for example access queues, that have already
26152 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26153 	 */
26154 	if (tcp->tcp_state != TCPS_CLOSED) {
26155 		(*tcpt->tcpt_proc)(connp);
26156 	} else {
26157 		tcp->tcp_timer_tid = 0;
26158 	}
26159 	tcp_timer_free(connp->conn_tcp, mp);
26160 }
26161 
26162 /*
26163  * There is potential race with untimeout and the handler firing at the same
26164  * time. The mblock may be freed by the handler while we are trying to use
26165  * it. But since both should execute on the same squeue, this race should not
26166  * occur.
26167  */
26168 clock_t
26169 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26170 {
26171 	mblk_t	*mp = (mblk_t *)id;
26172 	tcp_timer_t *tcpt;
26173 	clock_t delta;
26174 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26175 
26176 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26177 
26178 	if (mp == NULL)
26179 		return (-1);
26180 
26181 	tcpt = (tcp_timer_t *)mp->b_rptr;
26182 	ASSERT(tcpt->connp == connp);
26183 
26184 	delta = untimeout(tcpt->tcpt_tid);
26185 
26186 	if (delta >= 0) {
26187 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26188 		tcp_timer_free(connp->conn_tcp, mp);
26189 		CONN_DEC_REF(connp);
26190 	}
26191 
26192 	return (delta);
26193 }
26194 
26195 /*
26196  * Allocate space for the timer event. The allocation looks like mblk, but it is
26197  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26198  *
26199  * Dealing with failures: If we can't allocate from the timer cache we try
26200  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26201  * points to b_rptr.
26202  * If we can't allocate anything using allocb_tryhard(), we perform a last
26203  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26204  * save the actual allocation size in b_datap.
26205  */
26206 mblk_t *
26207 tcp_timermp_alloc(int kmflags)
26208 {
26209 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26210 	    kmflags & ~KM_PANIC);
26211 
26212 	if (mp != NULL) {
26213 		mp->b_next = mp->b_prev = NULL;
26214 		mp->b_rptr = (uchar_t *)(&mp[1]);
26215 		mp->b_wptr = NULL;
26216 		mp->b_datap = NULL;
26217 		mp->b_queue = NULL;
26218 		mp->b_cont = NULL;
26219 	} else if (kmflags & KM_PANIC) {
26220 		/*
26221 		 * Failed to allocate memory for the timer. Try allocating from
26222 		 * dblock caches.
26223 		 */
26224 		/* ipclassifier calls this from a constructor - hence no tcps */
26225 		TCP_G_STAT(tcp_timermp_allocfail);
26226 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26227 		if (mp == NULL) {
26228 			size_t size = 0;
26229 			/*
26230 			 * Memory is really low. Try tryhard allocation.
26231 			 *
26232 			 * ipclassifier calls this from a constructor -
26233 			 * hence no tcps
26234 			 */
26235 			TCP_G_STAT(tcp_timermp_allocdblfail);
26236 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26237 			    sizeof (tcp_timer_t), &size, kmflags);
26238 			mp->b_rptr = (uchar_t *)(&mp[1]);
26239 			mp->b_next = mp->b_prev = NULL;
26240 			mp->b_wptr = (uchar_t *)-1;
26241 			mp->b_datap = (dblk_t *)size;
26242 			mp->b_queue = NULL;
26243 			mp->b_cont = NULL;
26244 		}
26245 		ASSERT(mp->b_wptr != NULL);
26246 	}
26247 	/* ipclassifier calls this from a constructor - hence no tcps */
26248 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26249 
26250 	return (mp);
26251 }
26252 
26253 /*
26254  * Free per-tcp timer cache.
26255  * It can only contain entries from tcp_timercache.
26256  */
26257 void
26258 tcp_timermp_free(tcp_t *tcp)
26259 {
26260 	mblk_t *mp;
26261 
26262 	while ((mp = tcp->tcp_timercache) != NULL) {
26263 		ASSERT(mp->b_wptr == NULL);
26264 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26265 		kmem_cache_free(tcp_timercache, mp);
26266 	}
26267 }
26268 
26269 /*
26270  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26271  * events there already (currently at most two events are cached).
26272  * If the event is not allocated from the timer cache, free it right away.
26273  */
26274 static void
26275 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26276 {
26277 	mblk_t *mp1 = tcp->tcp_timercache;
26278 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26279 
26280 	if (mp->b_wptr != NULL) {
26281 		/*
26282 		 * This allocation is not from a timer cache, free it right
26283 		 * away.
26284 		 */
26285 		if (mp->b_wptr != (uchar_t *)-1)
26286 			freeb(mp);
26287 		else
26288 			kmem_free(mp, (size_t)mp->b_datap);
26289 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26290 		/* Cache this timer block for future allocations */
26291 		mp->b_rptr = (uchar_t *)(&mp[1]);
26292 		mp->b_next = mp1;
26293 		tcp->tcp_timercache = mp;
26294 	} else {
26295 		kmem_cache_free(tcp_timercache, mp);
26296 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26297 	}
26298 }
26299 
26300 /*
26301  * End of TCP Timers implementation.
26302  */
26303 
26304 /*
26305  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26306  * on the specified backing STREAMS q. Note, the caller may make the
26307  * decision to call based on the tcp_t.tcp_flow_stopped value which
26308  * when check outside the q's lock is only an advisory check ...
26309  */
26310 
26311 void
26312 tcp_setqfull(tcp_t *tcp)
26313 {
26314 	queue_t *q = tcp->tcp_wq;
26315 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26316 
26317 	if (!(q->q_flag & QFULL)) {
26318 		mutex_enter(QLOCK(q));
26319 		if (!(q->q_flag & QFULL)) {
26320 			/* still need to set QFULL */
26321 			q->q_flag |= QFULL;
26322 			tcp->tcp_flow_stopped = B_TRUE;
26323 			mutex_exit(QLOCK(q));
26324 			TCP_STAT(tcps, tcp_flwctl_on);
26325 		} else {
26326 			mutex_exit(QLOCK(q));
26327 		}
26328 	}
26329 }
26330 
26331 void
26332 tcp_clrqfull(tcp_t *tcp)
26333 {
26334 	queue_t *q = tcp->tcp_wq;
26335 
26336 	if (q->q_flag & QFULL) {
26337 		mutex_enter(QLOCK(q));
26338 		if (q->q_flag & QFULL) {
26339 			q->q_flag &= ~QFULL;
26340 			tcp->tcp_flow_stopped = B_FALSE;
26341 			mutex_exit(QLOCK(q));
26342 			if (q->q_flag & QWANTW)
26343 				qbackenable(q, 0);
26344 		} else {
26345 			mutex_exit(QLOCK(q));
26346 		}
26347 	}
26348 }
26349 
26350 
26351 /*
26352  * kstats related to squeues i.e. not per IP instance
26353  */
26354 static void *
26355 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26356 {
26357 	kstat_t *ksp;
26358 
26359 	tcp_g_stat_t template = {
26360 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26361 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26362 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26363 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26364 	};
26365 
26366 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26367 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26368 	    KSTAT_FLAG_VIRTUAL);
26369 
26370 	if (ksp == NULL)
26371 		return (NULL);
26372 
26373 	bcopy(&template, tcp_g_statp, sizeof (template));
26374 	ksp->ks_data = (void *)tcp_g_statp;
26375 
26376 	kstat_install(ksp);
26377 	return (ksp);
26378 }
26379 
26380 static void
26381 tcp_g_kstat_fini(kstat_t *ksp)
26382 {
26383 	if (ksp != NULL) {
26384 		kstat_delete(ksp);
26385 	}
26386 }
26387 
26388 
26389 static void *
26390 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26391 {
26392 	kstat_t *ksp;
26393 
26394 	tcp_stat_t template = {
26395 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26396 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26397 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26398 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26399 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26400 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26401 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26402 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26403 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26404 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26405 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26406 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26407 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26408 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26409 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26410 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26411 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26412 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26413 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26414 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26415 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26416 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26417 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26418 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26419 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26420 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26421 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26422 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26423 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26424 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26425 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26426 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26427 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26428 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26429 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26430 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26431 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26432 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26433 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26434 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26435 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26436 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26437 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26438 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26439 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26440 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26441 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26442 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26443 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26444 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26445 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26446 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26447 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26448 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26449 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26450 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26451 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26452 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26453 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26454 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26455 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26456 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26457 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26458 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26459 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26460 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26461 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26462 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26463 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26464 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26465 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26466 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26467 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26468 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26469 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26470 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26471 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26472 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26473 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26474 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26475 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26476 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26477 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26478 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26479 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26480 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26481 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26482 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26483 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26484 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26485 	};
26486 
26487 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26488 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26489 	    KSTAT_FLAG_VIRTUAL, stackid);
26490 
26491 	if (ksp == NULL)
26492 		return (NULL);
26493 
26494 	bcopy(&template, tcps_statisticsp, sizeof (template));
26495 	ksp->ks_data = (void *)tcps_statisticsp;
26496 	ksp->ks_private = (void *)(uintptr_t)stackid;
26497 
26498 	kstat_install(ksp);
26499 	return (ksp);
26500 }
26501 
26502 static void
26503 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26504 {
26505 	if (ksp != NULL) {
26506 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26507 		kstat_delete_netstack(ksp, stackid);
26508 	}
26509 }
26510 
26511 /*
26512  * TCP Kstats implementation
26513  */
26514 static void *
26515 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26516 {
26517 	kstat_t	*ksp;
26518 
26519 	tcp_named_kstat_t template = {
26520 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26521 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26522 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26523 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26524 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26525 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26526 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26527 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26528 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26529 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26530 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26531 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26532 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26533 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26534 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26535 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26536 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26537 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26538 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26539 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26540 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26541 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26542 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26543 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26544 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26545 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26546 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26547 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26548 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26549 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26550 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26551 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26552 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26553 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26554 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26555 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26556 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26557 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26558 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26559 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26560 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26561 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26562 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26563 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26564 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26565 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26566 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26567 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26568 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26569 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26570 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26571 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26572 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26573 	};
26574 
26575 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26576 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26577 
26578 	if (ksp == NULL)
26579 		return (NULL);
26580 
26581 	template.rtoAlgorithm.value.ui32 = 4;
26582 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26583 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26584 	template.maxConn.value.i32 = -1;
26585 
26586 	bcopy(&template, ksp->ks_data, sizeof (template));
26587 	ksp->ks_update = tcp_kstat_update;
26588 	ksp->ks_private = (void *)(uintptr_t)stackid;
26589 
26590 	kstat_install(ksp);
26591 	return (ksp);
26592 }
26593 
26594 static void
26595 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26596 {
26597 	if (ksp != NULL) {
26598 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26599 		kstat_delete_netstack(ksp, stackid);
26600 	}
26601 }
26602 
26603 static int
26604 tcp_kstat_update(kstat_t *kp, int rw)
26605 {
26606 	tcp_named_kstat_t *tcpkp;
26607 	tcp_t		*tcp;
26608 	connf_t		*connfp;
26609 	conn_t		*connp;
26610 	int 		i;
26611 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26612 	netstack_t	*ns;
26613 	tcp_stack_t	*tcps;
26614 	ip_stack_t	*ipst;
26615 
26616 	if ((kp == NULL) || (kp->ks_data == NULL))
26617 		return (EIO);
26618 
26619 	if (rw == KSTAT_WRITE)
26620 		return (EACCES);
26621 
26622 	ns = netstack_find_by_stackid(stackid);
26623 	if (ns == NULL)
26624 		return (-1);
26625 	tcps = ns->netstack_tcp;
26626 	if (tcps == NULL) {
26627 		netstack_rele(ns);
26628 		return (-1);
26629 	}
26630 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26631 
26632 	tcpkp->currEstab.value.ui32 = 0;
26633 
26634 	ipst = ns->netstack_ip;
26635 
26636 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26637 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26638 		connp = NULL;
26639 		while ((connp =
26640 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26641 			tcp = connp->conn_tcp;
26642 			switch (tcp_snmp_state(tcp)) {
26643 			case MIB2_TCP_established:
26644 			case MIB2_TCP_closeWait:
26645 				tcpkp->currEstab.value.ui32++;
26646 				break;
26647 			}
26648 		}
26649 	}
26650 
26651 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26652 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26653 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26654 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26655 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26656 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26657 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26658 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26659 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26660 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26661 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26662 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26663 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26664 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26665 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26666 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26667 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26668 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26669 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26670 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26671 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26672 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26673 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26674 	tcpkp->inDataInorderSegs.value.ui32 =
26675 	    tcps->tcps_mib.tcpInDataInorderSegs;
26676 	tcpkp->inDataInorderBytes.value.ui32 =
26677 	    tcps->tcps_mib.tcpInDataInorderBytes;
26678 	tcpkp->inDataUnorderSegs.value.ui32 =
26679 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26680 	tcpkp->inDataUnorderBytes.value.ui32 =
26681 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26682 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26683 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26684 	tcpkp->inDataPartDupSegs.value.ui32 =
26685 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26686 	tcpkp->inDataPartDupBytes.value.ui32 =
26687 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26688 	tcpkp->inDataPastWinSegs.value.ui32 =
26689 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26690 	tcpkp->inDataPastWinBytes.value.ui32 =
26691 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26692 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26693 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26694 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26695 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26696 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26697 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26698 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26699 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26700 	tcpkp->timKeepaliveProbe.value.ui32 =
26701 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26702 	tcpkp->timKeepaliveDrop.value.ui32 =
26703 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26704 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26705 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26706 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26707 	tcpkp->outSackRetransSegs.value.ui32 =
26708 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26709 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26710 
26711 	netstack_rele(ns);
26712 	return (0);
26713 }
26714 
26715 void
26716 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26717 {
26718 	uint16_t	hdr_len;
26719 	ipha_t		*ipha;
26720 	uint8_t		*nexthdrp;
26721 	tcph_t		*tcph;
26722 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26723 
26724 	/* Already has an eager */
26725 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26726 		TCP_STAT(tcps, tcp_reinput_syn);
26727 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26728 		    connp, SQTAG_TCP_REINPUT_EAGER);
26729 		return;
26730 	}
26731 
26732 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26733 	case IPV4_VERSION:
26734 		ipha = (ipha_t *)mp->b_rptr;
26735 		hdr_len = IPH_HDR_LENGTH(ipha);
26736 		break;
26737 	case IPV6_VERSION:
26738 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26739 		    &hdr_len, &nexthdrp)) {
26740 			CONN_DEC_REF(connp);
26741 			freemsg(mp);
26742 			return;
26743 		}
26744 		break;
26745 	}
26746 
26747 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26748 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26749 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26750 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26751 	}
26752 
26753 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26754 	    SQTAG_TCP_REINPUT);
26755 }
26756 
26757 static squeue_func_t
26758 tcp_squeue_switch(int val)
26759 {
26760 	squeue_func_t rval = squeue_fill;
26761 
26762 	switch (val) {
26763 	case 1:
26764 		rval = squeue_enter_nodrain;
26765 		break;
26766 	case 2:
26767 		rval = squeue_enter;
26768 		break;
26769 	default:
26770 		break;
26771 	}
26772 	return (rval);
26773 }
26774 
26775 /*
26776  * This is called once for each squeue - globally for all stack
26777  * instances.
26778  */
26779 static void
26780 tcp_squeue_add(squeue_t *sqp)
26781 {
26782 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26783 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
26784 
26785 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26786 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
26787 	    sqp, TCP_TIME_WAIT_DELAY);
26788 	if (tcp_free_list_max_cnt == 0) {
26789 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26790 			max_ncpus : boot_max_ncpus);
26791 
26792 		/*
26793 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26794 		 */
26795 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26796 			(tcp_ncpus * sizeof (tcp_t) * 100);
26797 	}
26798 	tcp_time_wait->tcp_free_list_cnt = 0;
26799 }
26800