xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision c3bc9566581e85093f7711d6fe1e718d65de42c6)
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 		 * We can't just rely on a non-null tcp_listener to indicate
12918 		 * that the accept() has completed since unlinking of the
12919 		 * eager and completion of the accept are not atomic.
12920 		 * tcp_detached, when it is not set (B_FALSE) indicates
12921 		 * that the accept() has completed.
12922 		 *
12923 		 * Nor can it reassemble urgent pointers, so discard
12924 		 * if it's not the next segment expected.
12925 		 *
12926 		 * Otherwise, collapse chain into one mblk (discard if
12927 		 * that fails).  This makes sure the headers, retransmitted
12928 		 * data, and new data all are in the same mblk.
12929 		 */
12930 		ASSERT(mp != NULL);
12931 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12932 			freemsg(mp);
12933 			return;
12934 		}
12935 		/* Update pointers into message */
12936 		iphdr = rptr = mp->b_rptr;
12937 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12938 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12939 			/*
12940 			 * Since we can't handle any data with this urgent
12941 			 * pointer that is out of sequence, we expunge
12942 			 * the data.  This allows us to still register
12943 			 * the urgent mark and generate the M_PCSIG,
12944 			 * which we can do.
12945 			 */
12946 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12947 			seg_len = 0;
12948 		}
12949 	}
12950 
12951 	switch (tcp->tcp_state) {
12952 	case TCPS_SYN_SENT:
12953 		if (flags & TH_ACK) {
12954 			/*
12955 			 * Note that our stack cannot send data before a
12956 			 * connection is established, therefore the
12957 			 * following check is valid.  Otherwise, it has
12958 			 * to be changed.
12959 			 */
12960 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12961 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12962 				freemsg(mp);
12963 				if (flags & TH_RST)
12964 					return;
12965 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12966 				    tcp, seg_ack, 0, TH_RST);
12967 				return;
12968 			}
12969 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12970 		}
12971 		if (flags & TH_RST) {
12972 			freemsg(mp);
12973 			if (flags & TH_ACK)
12974 				(void) tcp_clean_death(tcp,
12975 				    ECONNREFUSED, 13);
12976 			return;
12977 		}
12978 		if (!(flags & TH_SYN)) {
12979 			freemsg(mp);
12980 			return;
12981 		}
12982 
12983 		/* Process all TCP options. */
12984 		tcp_process_options(tcp, tcph);
12985 		/*
12986 		 * The following changes our rwnd to be a multiple of the
12987 		 * MIN(peer MSS, our MSS) for performance reason.
12988 		 */
12989 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12990 		    tcp->tcp_mss));
12991 
12992 		/* Is the other end ECN capable? */
12993 		if (tcp->tcp_ecn_ok) {
12994 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12995 				tcp->tcp_ecn_ok = B_FALSE;
12996 			}
12997 		}
12998 		/*
12999 		 * Clear ECN flags because it may interfere with later
13000 		 * processing.
13001 		 */
13002 		flags &= ~(TH_ECE|TH_CWR);
13003 
13004 		tcp->tcp_irs = seg_seq;
13005 		tcp->tcp_rack = seg_seq;
13006 		tcp->tcp_rnxt = seg_seq + 1;
13007 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13008 		if (!TCP_IS_DETACHED(tcp)) {
13009 			/* Allocate room for SACK options if needed. */
13010 			if (tcp->tcp_snd_sack_ok) {
13011 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13012 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13013 				    (tcp->tcp_loopback ? 0 :
13014 				    tcps->tcps_wroff_xtra));
13015 			} else {
13016 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13017 				    tcp->tcp_hdr_len +
13018 				    (tcp->tcp_loopback ? 0 :
13019 				    tcps->tcps_wroff_xtra));
13020 			}
13021 		}
13022 		if (flags & TH_ACK) {
13023 			/*
13024 			 * If we can't get the confirmation upstream, pretend
13025 			 * we didn't even see this one.
13026 			 *
13027 			 * XXX: how can we pretend we didn't see it if we
13028 			 * have updated rnxt et. al.
13029 			 *
13030 			 * For loopback we defer sending up the T_CONN_CON
13031 			 * until after some checks below.
13032 			 */
13033 			mp1 = NULL;
13034 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13035 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13036 				freemsg(mp);
13037 				return;
13038 			}
13039 			/* SYN was acked - making progress */
13040 			if (tcp->tcp_ipversion == IPV6_VERSION)
13041 				tcp->tcp_ip_forward_progress = B_TRUE;
13042 
13043 			/* One for the SYN */
13044 			tcp->tcp_suna = tcp->tcp_iss + 1;
13045 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13046 			tcp->tcp_state = TCPS_ESTABLISHED;
13047 
13048 			/*
13049 			 * If SYN was retransmitted, need to reset all
13050 			 * retransmission info.  This is because this
13051 			 * segment will be treated as a dup ACK.
13052 			 */
13053 			if (tcp->tcp_rexmit) {
13054 				tcp->tcp_rexmit = B_FALSE;
13055 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13056 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13057 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13058 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13059 				tcp->tcp_ms_we_have_waited = 0;
13060 
13061 				/*
13062 				 * Set tcp_cwnd back to 1 MSS, per
13063 				 * recommendation from
13064 				 * draft-floyd-incr-init-win-01.txt,
13065 				 * Increasing TCP's Initial Window.
13066 				 */
13067 				tcp->tcp_cwnd = tcp->tcp_mss;
13068 			}
13069 
13070 			tcp->tcp_swl1 = seg_seq;
13071 			tcp->tcp_swl2 = seg_ack;
13072 
13073 			new_swnd = BE16_TO_U16(tcph->th_win);
13074 			tcp->tcp_swnd = new_swnd;
13075 			if (new_swnd > tcp->tcp_max_swnd)
13076 				tcp->tcp_max_swnd = new_swnd;
13077 
13078 			/*
13079 			 * Always send the three-way handshake ack immediately
13080 			 * in order to make the connection complete as soon as
13081 			 * possible on the accepting host.
13082 			 */
13083 			flags |= TH_ACK_NEEDED;
13084 
13085 			/*
13086 			 * Special case for loopback.  At this point we have
13087 			 * received SYN-ACK from the remote endpoint.  In
13088 			 * order to ensure that both endpoints reach the
13089 			 * fused state prior to any data exchange, the final
13090 			 * ACK needs to be sent before we indicate T_CONN_CON
13091 			 * to the module upstream.
13092 			 */
13093 			if (tcp->tcp_loopback) {
13094 				mblk_t *ack_mp;
13095 
13096 				ASSERT(!tcp->tcp_unfusable);
13097 				ASSERT(mp1 != NULL);
13098 				/*
13099 				 * For loopback, we always get a pure SYN-ACK
13100 				 * and only need to send back the final ACK
13101 				 * with no data (this is because the other
13102 				 * tcp is ours and we don't do T/TCP).  This
13103 				 * final ACK triggers the passive side to
13104 				 * perform fusion in ESTABLISHED state.
13105 				 */
13106 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13107 					if (tcp->tcp_ack_tid != 0) {
13108 						(void) TCP_TIMER_CANCEL(tcp,
13109 						    tcp->tcp_ack_tid);
13110 						tcp->tcp_ack_tid = 0;
13111 					}
13112 					TCP_RECORD_TRACE(tcp, ack_mp,
13113 					    TCP_TRACE_SEND_PKT);
13114 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13115 					BUMP_LOCAL(tcp->tcp_obsegs);
13116 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13117 
13118 					/* Send up T_CONN_CON */
13119 					putnext(tcp->tcp_rq, mp1);
13120 
13121 					freemsg(mp);
13122 					return;
13123 				}
13124 				/*
13125 				 * Forget fusion; we need to handle more
13126 				 * complex cases below.  Send the deferred
13127 				 * T_CONN_CON message upstream and proceed
13128 				 * as usual.  Mark this tcp as not capable
13129 				 * of fusion.
13130 				 */
13131 				TCP_STAT(tcps, tcp_fusion_unfusable);
13132 				tcp->tcp_unfusable = B_TRUE;
13133 				putnext(tcp->tcp_rq, mp1);
13134 			}
13135 
13136 			/*
13137 			 * Check to see if there is data to be sent.  If
13138 			 * yes, set the transmit flag.  Then check to see
13139 			 * if received data processing needs to be done.
13140 			 * If not, go straight to xmit_check.  This short
13141 			 * cut is OK as we don't support T/TCP.
13142 			 */
13143 			if (tcp->tcp_unsent)
13144 				flags |= TH_XMIT_NEEDED;
13145 
13146 			if (seg_len == 0 && !(flags & TH_URG)) {
13147 				freemsg(mp);
13148 				goto xmit_check;
13149 			}
13150 
13151 			flags &= ~TH_SYN;
13152 			seg_seq++;
13153 			break;
13154 		}
13155 		tcp->tcp_state = TCPS_SYN_RCVD;
13156 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13157 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13158 		if (mp1) {
13159 			DB_CPID(mp1) = tcp->tcp_cpid;
13160 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13161 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13162 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13163 		}
13164 		freemsg(mp);
13165 		return;
13166 	case TCPS_SYN_RCVD:
13167 		if (flags & TH_ACK) {
13168 			/*
13169 			 * In this state, a SYN|ACK packet is either bogus
13170 			 * because the other side must be ACKing our SYN which
13171 			 * indicates it has seen the ACK for their SYN and
13172 			 * shouldn't retransmit it or we're crossing SYNs
13173 			 * on active open.
13174 			 */
13175 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13176 				freemsg(mp);
13177 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13178 				    tcp, seg_ack, 0, TH_RST);
13179 				return;
13180 			}
13181 			/*
13182 			 * NOTE: RFC 793 pg. 72 says this should be
13183 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13184 			 * but that would mean we have an ack that ignored
13185 			 * our SYN.
13186 			 */
13187 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13188 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13189 				freemsg(mp);
13190 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13191 				    tcp, seg_ack, 0, TH_RST);
13192 				return;
13193 			}
13194 		}
13195 		break;
13196 	case TCPS_LISTEN:
13197 		/*
13198 		 * Only a TLI listener can come through this path when a
13199 		 * acceptor is going back to be a listener and a packet
13200 		 * for the acceptor hits the classifier. For a socket
13201 		 * listener, this can never happen because a listener
13202 		 * can never accept connection on itself and hence a
13203 		 * socket acceptor can not go back to being a listener.
13204 		 */
13205 		ASSERT(!TCP_IS_SOCKET(tcp));
13206 		/*FALLTHRU*/
13207 	case TCPS_CLOSED:
13208 	case TCPS_BOUND: {
13209 		conn_t	*new_connp;
13210 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13211 
13212 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13213 		if (new_connp != NULL) {
13214 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13215 			return;
13216 		}
13217 		/* We failed to classify. For now just drop the packet */
13218 		freemsg(mp);
13219 		return;
13220 	}
13221 	case TCPS_IDLE:
13222 		/*
13223 		 * Handle the case where the tcp_clean_death() has happened
13224 		 * on a connection (application hasn't closed yet) but a packet
13225 		 * was already queued on squeue before tcp_clean_death()
13226 		 * was processed. Calling tcp_clean_death() twice on same
13227 		 * connection can result in weird behaviour.
13228 		 */
13229 		freemsg(mp);
13230 		return;
13231 	default:
13232 		break;
13233 	}
13234 
13235 	/*
13236 	 * Already on the correct queue/perimeter.
13237 	 * If this is a detached connection and not an eager
13238 	 * connection hanging off a listener then new data
13239 	 * (past the FIN) will cause a reset.
13240 	 * We do a special check here where it
13241 	 * is out of the main line, rather than check
13242 	 * if we are detached every time we see new
13243 	 * data down below.
13244 	 */
13245 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13246 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13247 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13248 		TCP_RECORD_TRACE(tcp,
13249 		    mp, TCP_TRACE_RECV_PKT);
13250 
13251 		freemsg(mp);
13252 		/*
13253 		 * This could be an SSL closure alert. We're detached so just
13254 		 * acknowledge it this last time.
13255 		 */
13256 		if (tcp->tcp_kssl_ctx != NULL) {
13257 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13258 			tcp->tcp_kssl_ctx = NULL;
13259 
13260 			tcp->tcp_rnxt += seg_len;
13261 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13262 			flags |= TH_ACK_NEEDED;
13263 			goto ack_check;
13264 		}
13265 
13266 		tcp_xmit_ctl("new data when detached", tcp,
13267 		    tcp->tcp_snxt, 0, TH_RST);
13268 		(void) tcp_clean_death(tcp, EPROTO, 12);
13269 		return;
13270 	}
13271 
13272 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13273 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13274 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13275 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13276 
13277 	if (tcp->tcp_snd_ts_ok) {
13278 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13279 			/*
13280 			 * This segment is not acceptable.
13281 			 * Drop it and send back an ACK.
13282 			 */
13283 			freemsg(mp);
13284 			flags |= TH_ACK_NEEDED;
13285 			goto ack_check;
13286 		}
13287 	} else if (tcp->tcp_snd_sack_ok) {
13288 		ASSERT(tcp->tcp_sack_info != NULL);
13289 		tcpopt.tcp = tcp;
13290 		/*
13291 		 * SACK info in already updated in tcp_parse_options.  Ignore
13292 		 * all other TCP options...
13293 		 */
13294 		(void) tcp_parse_options(tcph, &tcpopt);
13295 	}
13296 try_again:;
13297 	mss = tcp->tcp_mss;
13298 	gap = seg_seq - tcp->tcp_rnxt;
13299 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13300 	/*
13301 	 * gap is the amount of sequence space between what we expect to see
13302 	 * and what we got for seg_seq.  A positive value for gap means
13303 	 * something got lost.  A negative value means we got some old stuff.
13304 	 */
13305 	if (gap < 0) {
13306 		/* Old stuff present.  Is the SYN in there? */
13307 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13308 		    (seg_len != 0)) {
13309 			flags &= ~TH_SYN;
13310 			seg_seq++;
13311 			urp--;
13312 			/* Recompute the gaps after noting the SYN. */
13313 			goto try_again;
13314 		}
13315 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13316 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13317 		    (seg_len > -gap ? -gap : seg_len));
13318 		/* Remove the old stuff from seg_len. */
13319 		seg_len += gap;
13320 		/*
13321 		 * Anything left?
13322 		 * Make sure to check for unack'd FIN when rest of data
13323 		 * has been previously ack'd.
13324 		 */
13325 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13326 			/*
13327 			 * Resets are only valid if they lie within our offered
13328 			 * window.  If the RST bit is set, we just ignore this
13329 			 * segment.
13330 			 */
13331 			if (flags & TH_RST) {
13332 				freemsg(mp);
13333 				return;
13334 			}
13335 
13336 			/*
13337 			 * The arriving of dup data packets indicate that we
13338 			 * may have postponed an ack for too long, or the other
13339 			 * side's RTT estimate is out of shape. Start acking
13340 			 * more often.
13341 			 */
13342 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13343 			    tcp->tcp_rack_cnt >= 1 &&
13344 			    tcp->tcp_rack_abs_max > 2) {
13345 				tcp->tcp_rack_abs_max--;
13346 			}
13347 			tcp->tcp_rack_cur_max = 1;
13348 
13349 			/*
13350 			 * This segment is "unacceptable".  None of its
13351 			 * sequence space lies within our advertized window.
13352 			 *
13353 			 * Adjust seg_len to the original value for tracing.
13354 			 */
13355 			seg_len -= gap;
13356 			if (tcp->tcp_debug) {
13357 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13358 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13359 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13360 				    "seg_len %d, rnxt %u, snxt %u, %s",
13361 				    gap, rgap, flags, seg_seq, seg_ack,
13362 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13363 				    tcp_display(tcp, NULL,
13364 				    DISP_ADDR_AND_PORT));
13365 			}
13366 
13367 			/*
13368 			 * Arrange to send an ACK in response to the
13369 			 * unacceptable segment per RFC 793 page 69. There
13370 			 * is only one small difference between ours and the
13371 			 * acceptability test in the RFC - we accept ACK-only
13372 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13373 			 * will be generated.
13374 			 *
13375 			 * Note that we have to ACK an ACK-only packet at least
13376 			 * for stacks that send 0-length keep-alives with
13377 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13378 			 * section 4.2.3.6. As long as we don't ever generate
13379 			 * an unacceptable packet in response to an incoming
13380 			 * packet that is unacceptable, it should not cause
13381 			 * "ACK wars".
13382 			 */
13383 			flags |=  TH_ACK_NEEDED;
13384 
13385 			/*
13386 			 * Continue processing this segment in order to use the
13387 			 * ACK information it contains, but skip all other
13388 			 * sequence-number processing.	Processing the ACK
13389 			 * information is necessary in order to
13390 			 * re-synchronize connections that may have lost
13391 			 * synchronization.
13392 			 *
13393 			 * We clear seg_len and flag fields related to
13394 			 * sequence number processing as they are not
13395 			 * to be trusted for an unacceptable segment.
13396 			 */
13397 			seg_len = 0;
13398 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13399 			goto process_ack;
13400 		}
13401 
13402 		/* Fix seg_seq, and chew the gap off the front. */
13403 		seg_seq = tcp->tcp_rnxt;
13404 		urp += gap;
13405 		do {
13406 			mblk_t	*mp2;
13407 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13408 			    (uintptr_t)UINT_MAX);
13409 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13410 			if (gap > 0) {
13411 				mp->b_rptr = mp->b_wptr - gap;
13412 				break;
13413 			}
13414 			mp2 = mp;
13415 			mp = mp->b_cont;
13416 			freeb(mp2);
13417 		} while (gap < 0);
13418 		/*
13419 		 * If the urgent data has already been acknowledged, we
13420 		 * should ignore TH_URG below
13421 		 */
13422 		if (urp < 0)
13423 			flags &= ~TH_URG;
13424 	}
13425 	/*
13426 	 * rgap is the amount of stuff received out of window.  A negative
13427 	 * value is the amount out of window.
13428 	 */
13429 	if (rgap < 0) {
13430 		mblk_t	*mp2;
13431 
13432 		if (tcp->tcp_rwnd == 0) {
13433 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13434 		} else {
13435 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13436 			UPDATE_MIB(&tcps->tcps_mib,
13437 			    tcpInDataPastWinBytes, -rgap);
13438 		}
13439 
13440 		/*
13441 		 * seg_len does not include the FIN, so if more than
13442 		 * just the FIN is out of window, we act like we don't
13443 		 * see it.  (If just the FIN is out of window, rgap
13444 		 * will be zero and we will go ahead and acknowledge
13445 		 * the FIN.)
13446 		 */
13447 		flags &= ~TH_FIN;
13448 
13449 		/* Fix seg_len and make sure there is something left. */
13450 		seg_len += rgap;
13451 		if (seg_len <= 0) {
13452 			/*
13453 			 * Resets are only valid if they lie within our offered
13454 			 * window.  If the RST bit is set, we just ignore this
13455 			 * segment.
13456 			 */
13457 			if (flags & TH_RST) {
13458 				freemsg(mp);
13459 				return;
13460 			}
13461 
13462 			/* Per RFC 793, we need to send back an ACK. */
13463 			flags |= TH_ACK_NEEDED;
13464 
13465 			/*
13466 			 * Send SIGURG as soon as possible i.e. even
13467 			 * if the TH_URG was delivered in a window probe
13468 			 * packet (which will be unacceptable).
13469 			 *
13470 			 * We generate a signal if none has been generated
13471 			 * for this connection or if this is a new urgent
13472 			 * byte. Also send a zero-length "unmarked" message
13473 			 * to inform SIOCATMARK that this is not the mark.
13474 			 *
13475 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13476 			 * is sent up. This plus the check for old data
13477 			 * (gap >= 0) handles the wraparound of the sequence
13478 			 * number space without having to always track the
13479 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13480 			 * this max in its rcv_up variable).
13481 			 *
13482 			 * This prevents duplicate SIGURGS due to a "late"
13483 			 * zero-window probe when the T_EXDATA_IND has already
13484 			 * been sent up.
13485 			 */
13486 			if ((flags & TH_URG) &&
13487 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13488 			    tcp->tcp_urp_last))) {
13489 				mp1 = allocb(0, BPRI_MED);
13490 				if (mp1 == NULL) {
13491 					freemsg(mp);
13492 					return;
13493 				}
13494 				if (!TCP_IS_DETACHED(tcp) &&
13495 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13496 				    SIGURG)) {
13497 					/* Try again on the rexmit. */
13498 					freemsg(mp1);
13499 					freemsg(mp);
13500 					return;
13501 				}
13502 				/*
13503 				 * If the next byte would be the mark
13504 				 * then mark with MARKNEXT else mark
13505 				 * with NOTMARKNEXT.
13506 				 */
13507 				if (gap == 0 && urp == 0)
13508 					mp1->b_flag |= MSGMARKNEXT;
13509 				else
13510 					mp1->b_flag |= MSGNOTMARKNEXT;
13511 				freemsg(tcp->tcp_urp_mark_mp);
13512 				tcp->tcp_urp_mark_mp = mp1;
13513 				flags |= TH_SEND_URP_MARK;
13514 				tcp->tcp_urp_last_valid = B_TRUE;
13515 				tcp->tcp_urp_last = urp + seg_seq;
13516 			}
13517 			/*
13518 			 * If this is a zero window probe, continue to
13519 			 * process the ACK part.  But we need to set seg_len
13520 			 * to 0 to avoid data processing.  Otherwise just
13521 			 * drop the segment and send back an ACK.
13522 			 */
13523 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13524 				flags &= ~(TH_SYN | TH_URG);
13525 				seg_len = 0;
13526 				goto process_ack;
13527 			} else {
13528 				freemsg(mp);
13529 				goto ack_check;
13530 			}
13531 		}
13532 		/* Pitch out of window stuff off the end. */
13533 		rgap = seg_len;
13534 		mp2 = mp;
13535 		do {
13536 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13537 			    (uintptr_t)INT_MAX);
13538 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13539 			if (rgap < 0) {
13540 				mp2->b_wptr += rgap;
13541 				if ((mp1 = mp2->b_cont) != NULL) {
13542 					mp2->b_cont = NULL;
13543 					freemsg(mp1);
13544 				}
13545 				break;
13546 			}
13547 		} while ((mp2 = mp2->b_cont) != NULL);
13548 	}
13549 ok:;
13550 	/*
13551 	 * TCP should check ECN info for segments inside the window only.
13552 	 * Therefore the check should be done here.
13553 	 */
13554 	if (tcp->tcp_ecn_ok) {
13555 		if (flags & TH_CWR) {
13556 			tcp->tcp_ecn_echo_on = B_FALSE;
13557 		}
13558 		/*
13559 		 * Note that both ECN_CE and CWR can be set in the
13560 		 * same segment.  In this case, we once again turn
13561 		 * on ECN_ECHO.
13562 		 */
13563 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13564 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13565 
13566 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13567 				tcp->tcp_ecn_echo_on = B_TRUE;
13568 			}
13569 		} else {
13570 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13571 
13572 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13573 			    htonl(IPH_ECN_CE << 20)) {
13574 				tcp->tcp_ecn_echo_on = B_TRUE;
13575 			}
13576 		}
13577 	}
13578 
13579 	/*
13580 	 * Check whether we can update tcp_ts_recent.  This test is
13581 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13582 	 * Extensions for High Performance: An Update", Internet Draft.
13583 	 */
13584 	if (tcp->tcp_snd_ts_ok &&
13585 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13586 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13587 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13588 		tcp->tcp_last_rcv_lbolt = lbolt64;
13589 	}
13590 
13591 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13592 		/*
13593 		 * FIN in an out of order segment.  We record this in
13594 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13595 		 * Clear the FIN so that any check on FIN flag will fail.
13596 		 * Remember that FIN also counts in the sequence number
13597 		 * space.  So we need to ack out of order FIN only segments.
13598 		 */
13599 		if (flags & TH_FIN) {
13600 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13601 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13602 			flags &= ~TH_FIN;
13603 			flags |= TH_ACK_NEEDED;
13604 		}
13605 		if (seg_len > 0) {
13606 			/* Fill in the SACK blk list. */
13607 			if (tcp->tcp_snd_sack_ok) {
13608 				ASSERT(tcp->tcp_sack_info != NULL);
13609 				tcp_sack_insert(tcp->tcp_sack_list,
13610 				    seg_seq, seg_seq + seg_len,
13611 				    &(tcp->tcp_num_sack_blk));
13612 			}
13613 
13614 			/*
13615 			 * Attempt reassembly and see if we have something
13616 			 * ready to go.
13617 			 */
13618 			mp = tcp_reass(tcp, mp, seg_seq);
13619 			/* Always ack out of order packets */
13620 			flags |= TH_ACK_NEEDED | TH_PUSH;
13621 			if (mp) {
13622 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13623 				    (uintptr_t)INT_MAX);
13624 				seg_len = mp->b_cont ? msgdsize(mp) :
13625 					(int)(mp->b_wptr - mp->b_rptr);
13626 				seg_seq = tcp->tcp_rnxt;
13627 				/*
13628 				 * A gap is filled and the seq num and len
13629 				 * of the gap match that of a previously
13630 				 * received FIN, put the FIN flag back in.
13631 				 */
13632 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13633 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13634 					flags |= TH_FIN;
13635 					tcp->tcp_valid_bits &=
13636 					    ~TCP_OFO_FIN_VALID;
13637 				}
13638 			} else {
13639 				/*
13640 				 * Keep going even with NULL mp.
13641 				 * There may be a useful ACK or something else
13642 				 * we don't want to miss.
13643 				 *
13644 				 * But TCP should not perform fast retransmit
13645 				 * because of the ack number.  TCP uses
13646 				 * seg_len == 0 to determine if it is a pure
13647 				 * ACK.  And this is not a pure ACK.
13648 				 */
13649 				seg_len = 0;
13650 				ofo_seg = B_TRUE;
13651 			}
13652 		}
13653 	} else if (seg_len > 0) {
13654 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13655 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13656 		/*
13657 		 * If an out of order FIN was received before, and the seq
13658 		 * num and len of the new segment match that of the FIN,
13659 		 * put the FIN flag back in.
13660 		 */
13661 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13662 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13663 			flags |= TH_FIN;
13664 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13665 		}
13666 	}
13667 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13668 	if (flags & TH_RST) {
13669 		freemsg(mp);
13670 		switch (tcp->tcp_state) {
13671 		case TCPS_SYN_RCVD:
13672 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13673 			break;
13674 		case TCPS_ESTABLISHED:
13675 		case TCPS_FIN_WAIT_1:
13676 		case TCPS_FIN_WAIT_2:
13677 		case TCPS_CLOSE_WAIT:
13678 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13679 			break;
13680 		case TCPS_CLOSING:
13681 		case TCPS_LAST_ACK:
13682 			(void) tcp_clean_death(tcp, 0, 16);
13683 			break;
13684 		default:
13685 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13686 			(void) tcp_clean_death(tcp, ENXIO, 17);
13687 			break;
13688 		}
13689 		return;
13690 	}
13691 	if (flags & TH_SYN) {
13692 		/*
13693 		 * See RFC 793, Page 71
13694 		 *
13695 		 * The seq number must be in the window as it should
13696 		 * be "fixed" above.  If it is outside window, it should
13697 		 * be already rejected.  Note that we allow seg_seq to be
13698 		 * rnxt + rwnd because we want to accept 0 window probe.
13699 		 */
13700 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13701 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13702 		freemsg(mp);
13703 		/*
13704 		 * If the ACK flag is not set, just use our snxt as the
13705 		 * seq number of the RST segment.
13706 		 */
13707 		if (!(flags & TH_ACK)) {
13708 			seg_ack = tcp->tcp_snxt;
13709 		}
13710 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13711 		    TH_RST|TH_ACK);
13712 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13713 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13714 		return;
13715 	}
13716 	/*
13717 	 * urp could be -1 when the urp field in the packet is 0
13718 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13719 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13720 	 */
13721 	if (flags & TH_URG && urp >= 0) {
13722 		if (!tcp->tcp_urp_last_valid ||
13723 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13724 			/*
13725 			 * If we haven't generated the signal yet for this
13726 			 * urgent pointer value, do it now.  Also, send up a
13727 			 * zero-length M_DATA indicating whether or not this is
13728 			 * the mark. The latter is not needed when a
13729 			 * T_EXDATA_IND is sent up. However, if there are
13730 			 * allocation failures this code relies on the sender
13731 			 * retransmitting and the socket code for determining
13732 			 * the mark should not block waiting for the peer to
13733 			 * transmit. Thus, for simplicity we always send up the
13734 			 * mark indication.
13735 			 */
13736 			mp1 = allocb(0, BPRI_MED);
13737 			if (mp1 == NULL) {
13738 				freemsg(mp);
13739 				return;
13740 			}
13741 			if (!TCP_IS_DETACHED(tcp) &&
13742 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13743 				/* Try again on the rexmit. */
13744 				freemsg(mp1);
13745 				freemsg(mp);
13746 				return;
13747 			}
13748 			/*
13749 			 * Mark with NOTMARKNEXT for now.
13750 			 * The code below will change this to MARKNEXT
13751 			 * if we are at the mark.
13752 			 *
13753 			 * If there are allocation failures (e.g. in dupmsg
13754 			 * below) the next time tcp_rput_data sees the urgent
13755 			 * segment it will send up the MSG*MARKNEXT message.
13756 			 */
13757 			mp1->b_flag |= MSGNOTMARKNEXT;
13758 			freemsg(tcp->tcp_urp_mark_mp);
13759 			tcp->tcp_urp_mark_mp = mp1;
13760 			flags |= TH_SEND_URP_MARK;
13761 #ifdef DEBUG
13762 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13763 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13764 			    "last %x, %s",
13765 			    seg_seq, urp, tcp->tcp_urp_last,
13766 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13767 #endif /* DEBUG */
13768 			tcp->tcp_urp_last_valid = B_TRUE;
13769 			tcp->tcp_urp_last = urp + seg_seq;
13770 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13771 			/*
13772 			 * An allocation failure prevented the previous
13773 			 * tcp_rput_data from sending up the allocated
13774 			 * MSG*MARKNEXT message - send it up this time
13775 			 * around.
13776 			 */
13777 			flags |= TH_SEND_URP_MARK;
13778 		}
13779 
13780 		/*
13781 		 * If the urgent byte is in this segment, make sure that it is
13782 		 * all by itself.  This makes it much easier to deal with the
13783 		 * possibility of an allocation failure on the T_exdata_ind.
13784 		 * Note that seg_len is the number of bytes in the segment, and
13785 		 * urp is the offset into the segment of the urgent byte.
13786 		 * urp < seg_len means that the urgent byte is in this segment.
13787 		 */
13788 		if (urp < seg_len) {
13789 			if (seg_len != 1) {
13790 				uint32_t  tmp_rnxt;
13791 				/*
13792 				 * Break it up and feed it back in.
13793 				 * Re-attach the IP header.
13794 				 */
13795 				mp->b_rptr = iphdr;
13796 				if (urp > 0) {
13797 					/*
13798 					 * There is stuff before the urgent
13799 					 * byte.
13800 					 */
13801 					mp1 = dupmsg(mp);
13802 					if (!mp1) {
13803 						/*
13804 						 * Trim from urgent byte on.
13805 						 * The rest will come back.
13806 						 */
13807 						(void) adjmsg(mp,
13808 						    urp - seg_len);
13809 						tcp_rput_data(connp,
13810 						    mp, NULL);
13811 						return;
13812 					}
13813 					(void) adjmsg(mp1, urp - seg_len);
13814 					/* Feed this piece back in. */
13815 					tmp_rnxt = tcp->tcp_rnxt;
13816 					tcp_rput_data(connp, mp1, NULL);
13817 					/*
13818 					 * If the data passed back in was not
13819 					 * processed (ie: bad ACK) sending
13820 					 * the remainder back in will cause a
13821 					 * loop. In this case, drop the
13822 					 * packet and let the sender try
13823 					 * sending a good packet.
13824 					 */
13825 					if (tmp_rnxt == tcp->tcp_rnxt) {
13826 						freemsg(mp);
13827 						return;
13828 					}
13829 				}
13830 				if (urp != seg_len - 1) {
13831 					uint32_t  tmp_rnxt;
13832 					/*
13833 					 * There is stuff after the urgent
13834 					 * byte.
13835 					 */
13836 					mp1 = dupmsg(mp);
13837 					if (!mp1) {
13838 						/*
13839 						 * Trim everything beyond the
13840 						 * urgent byte.  The rest will
13841 						 * come back.
13842 						 */
13843 						(void) adjmsg(mp,
13844 						    urp + 1 - seg_len);
13845 						tcp_rput_data(connp,
13846 						    mp, NULL);
13847 						return;
13848 					}
13849 					(void) adjmsg(mp1, urp + 1 - seg_len);
13850 					tmp_rnxt = tcp->tcp_rnxt;
13851 					tcp_rput_data(connp, mp1, NULL);
13852 					/*
13853 					 * If the data passed back in was not
13854 					 * processed (ie: bad ACK) sending
13855 					 * the remainder back in will cause a
13856 					 * loop. In this case, drop the
13857 					 * packet and let the sender try
13858 					 * sending a good packet.
13859 					 */
13860 					if (tmp_rnxt == tcp->tcp_rnxt) {
13861 						freemsg(mp);
13862 						return;
13863 					}
13864 				}
13865 				tcp_rput_data(connp, mp, NULL);
13866 				return;
13867 			}
13868 			/*
13869 			 * This segment contains only the urgent byte.  We
13870 			 * have to allocate the T_exdata_ind, if we can.
13871 			 */
13872 			if (!tcp->tcp_urp_mp) {
13873 				struct T_exdata_ind *tei;
13874 				mp1 = allocb(sizeof (struct T_exdata_ind),
13875 				    BPRI_MED);
13876 				if (!mp1) {
13877 					/*
13878 					 * Sigh... It'll be back.
13879 					 * Generate any MSG*MARK message now.
13880 					 */
13881 					freemsg(mp);
13882 					seg_len = 0;
13883 					if (flags & TH_SEND_URP_MARK) {
13884 
13885 
13886 						ASSERT(tcp->tcp_urp_mark_mp);
13887 						tcp->tcp_urp_mark_mp->b_flag &=
13888 							~MSGNOTMARKNEXT;
13889 						tcp->tcp_urp_mark_mp->b_flag |=
13890 							MSGMARKNEXT;
13891 					}
13892 					goto ack_check;
13893 				}
13894 				mp1->b_datap->db_type = M_PROTO;
13895 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13896 				tei->PRIM_type = T_EXDATA_IND;
13897 				tei->MORE_flag = 0;
13898 				mp1->b_wptr = (uchar_t *)&tei[1];
13899 				tcp->tcp_urp_mp = mp1;
13900 #ifdef DEBUG
13901 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13902 				    "tcp_rput: allocated exdata_ind %s",
13903 				    tcp_display(tcp, NULL,
13904 				    DISP_PORT_ONLY));
13905 #endif /* DEBUG */
13906 				/*
13907 				 * There is no need to send a separate MSG*MARK
13908 				 * message since the T_EXDATA_IND will be sent
13909 				 * now.
13910 				 */
13911 				flags &= ~TH_SEND_URP_MARK;
13912 				freemsg(tcp->tcp_urp_mark_mp);
13913 				tcp->tcp_urp_mark_mp = NULL;
13914 			}
13915 			/*
13916 			 * Now we are all set.  On the next putnext upstream,
13917 			 * tcp_urp_mp will be non-NULL and will get prepended
13918 			 * to what has to be this piece containing the urgent
13919 			 * byte.  If for any reason we abort this segment below,
13920 			 * if it comes back, we will have this ready, or it
13921 			 * will get blown off in close.
13922 			 */
13923 		} else if (urp == seg_len) {
13924 			/*
13925 			 * The urgent byte is the next byte after this sequence
13926 			 * number. If there is data it is marked with
13927 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13928 			 * since it is not needed. Otherwise, if the code
13929 			 * above just allocated a zero-length tcp_urp_mark_mp
13930 			 * message, that message is tagged with MSGMARKNEXT.
13931 			 * Sending up these MSGMARKNEXT messages makes
13932 			 * SIOCATMARK work correctly even though
13933 			 * the T_EXDATA_IND will not be sent up until the
13934 			 * urgent byte arrives.
13935 			 */
13936 			if (seg_len != 0) {
13937 				flags |= TH_MARKNEXT_NEEDED;
13938 				freemsg(tcp->tcp_urp_mark_mp);
13939 				tcp->tcp_urp_mark_mp = NULL;
13940 				flags &= ~TH_SEND_URP_MARK;
13941 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13942 				flags |= TH_SEND_URP_MARK;
13943 				tcp->tcp_urp_mark_mp->b_flag &=
13944 					~MSGNOTMARKNEXT;
13945 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13946 			}
13947 #ifdef DEBUG
13948 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13949 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13950 			    seg_len, flags,
13951 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13952 #endif /* DEBUG */
13953 		} else {
13954 			/* Data left until we hit mark */
13955 #ifdef DEBUG
13956 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13957 			    "tcp_rput: URP %d bytes left, %s",
13958 			    urp - seg_len, tcp_display(tcp, NULL,
13959 			    DISP_PORT_ONLY));
13960 #endif /* DEBUG */
13961 		}
13962 	}
13963 
13964 process_ack:
13965 	if (!(flags & TH_ACK)) {
13966 		freemsg(mp);
13967 		goto xmit_check;
13968 	}
13969 	}
13970 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13971 
13972 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13973 		tcp->tcp_ip_forward_progress = B_TRUE;
13974 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13975 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13976 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13977 			/* 3-way handshake complete - pass up the T_CONN_IND */
13978 			tcp_t	*listener = tcp->tcp_listener;
13979 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13980 
13981 			tcp->tcp_tconnind_started = B_TRUE;
13982 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13983 			/*
13984 			 * We are here means eager is fine but it can
13985 			 * get a TH_RST at any point between now and till
13986 			 * accept completes and disappear. We need to
13987 			 * ensure that reference to eager is valid after
13988 			 * we get out of eager's perimeter. So we do
13989 			 * an extra refhold.
13990 			 */
13991 			CONN_INC_REF(connp);
13992 
13993 			/*
13994 			 * The listener also exists because of the refhold
13995 			 * done in tcp_conn_request. Its possible that it
13996 			 * might have closed. We will check that once we
13997 			 * get inside listeners context.
13998 			 */
13999 			CONN_INC_REF(listener->tcp_connp);
14000 			if (listener->tcp_connp->conn_sqp ==
14001 			    connp->conn_sqp) {
14002 				tcp_send_conn_ind(listener->tcp_connp, mp,
14003 				    listener->tcp_connp->conn_sqp);
14004 				CONN_DEC_REF(listener->tcp_connp);
14005 			} else if (!tcp->tcp_loopback) {
14006 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14007 				    tcp_send_conn_ind,
14008 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14009 			} else {
14010 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14011 				    tcp_send_conn_ind, listener->tcp_connp,
14012 				    SQTAG_TCP_CONN_IND);
14013 			}
14014 		}
14015 
14016 		if (tcp->tcp_active_open) {
14017 			/*
14018 			 * We are seeing the final ack in the three way
14019 			 * hand shake of a active open'ed connection
14020 			 * so we must send up a T_CONN_CON
14021 			 */
14022 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14023 				freemsg(mp);
14024 				return;
14025 			}
14026 			/*
14027 			 * Don't fuse the loopback endpoints for
14028 			 * simultaneous active opens.
14029 			 */
14030 			if (tcp->tcp_loopback) {
14031 				TCP_STAT(tcps, tcp_fusion_unfusable);
14032 				tcp->tcp_unfusable = B_TRUE;
14033 			}
14034 		}
14035 
14036 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14037 		bytes_acked--;
14038 		/* SYN was acked - making progress */
14039 		if (tcp->tcp_ipversion == IPV6_VERSION)
14040 			tcp->tcp_ip_forward_progress = B_TRUE;
14041 
14042 		/*
14043 		 * If SYN was retransmitted, need to reset all
14044 		 * retransmission info as this segment will be
14045 		 * treated as a dup ACK.
14046 		 */
14047 		if (tcp->tcp_rexmit) {
14048 			tcp->tcp_rexmit = B_FALSE;
14049 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14050 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14051 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14052 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14053 			tcp->tcp_ms_we_have_waited = 0;
14054 			tcp->tcp_cwnd = mss;
14055 		}
14056 
14057 		/*
14058 		 * We set the send window to zero here.
14059 		 * This is needed if there is data to be
14060 		 * processed already on the queue.
14061 		 * Later (at swnd_update label), the
14062 		 * "new_swnd > tcp_swnd" condition is satisfied
14063 		 * the XMIT_NEEDED flag is set in the current
14064 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14065 		 * called if there is already data on queue in
14066 		 * this state.
14067 		 */
14068 		tcp->tcp_swnd = 0;
14069 
14070 		if (new_swnd > tcp->tcp_max_swnd)
14071 			tcp->tcp_max_swnd = new_swnd;
14072 		tcp->tcp_swl1 = seg_seq;
14073 		tcp->tcp_swl2 = seg_ack;
14074 		tcp->tcp_state = TCPS_ESTABLISHED;
14075 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14076 
14077 		/* Fuse when both sides are in ESTABLISHED state */
14078 		if (tcp->tcp_loopback && do_tcp_fusion)
14079 			tcp_fuse(tcp, iphdr, tcph);
14080 
14081 	}
14082 	/* This code follows 4.4BSD-Lite2 mostly. */
14083 	if (bytes_acked < 0)
14084 		goto est;
14085 
14086 	/*
14087 	 * If TCP is ECN capable and the congestion experience bit is
14088 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14089 	 * done once per window (or more loosely, per RTT).
14090 	 */
14091 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14092 		tcp->tcp_cwr = B_FALSE;
14093 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14094 		if (!tcp->tcp_cwr) {
14095 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14096 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14097 			tcp->tcp_cwnd = npkt * mss;
14098 			/*
14099 			 * If the cwnd is 0, use the timer to clock out
14100 			 * new segments.  This is required by the ECN spec.
14101 			 */
14102 			if (npkt == 0) {
14103 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14104 				/*
14105 				 * This makes sure that when the ACK comes
14106 				 * back, we will increase tcp_cwnd by 1 MSS.
14107 				 */
14108 				tcp->tcp_cwnd_cnt = 0;
14109 			}
14110 			tcp->tcp_cwr = B_TRUE;
14111 			/*
14112 			 * This marks the end of the current window of in
14113 			 * flight data.  That is why we don't use
14114 			 * tcp_suna + tcp_swnd.  Only data in flight can
14115 			 * provide ECN info.
14116 			 */
14117 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14118 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14119 		}
14120 	}
14121 
14122 	mp1 = tcp->tcp_xmit_head;
14123 	if (bytes_acked == 0) {
14124 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14125 			int dupack_cnt;
14126 
14127 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14128 			/*
14129 			 * Fast retransmit.  When we have seen exactly three
14130 			 * identical ACKs while we have unacked data
14131 			 * outstanding we take it as a hint that our peer
14132 			 * dropped something.
14133 			 *
14134 			 * If TCP is retransmitting, don't do fast retransmit.
14135 			 */
14136 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14137 			    ! tcp->tcp_rexmit) {
14138 				/* Do Limited Transmit */
14139 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14140 				    tcps->tcps_dupack_fast_retransmit) {
14141 					/*
14142 					 * RFC 3042
14143 					 *
14144 					 * What we need to do is temporarily
14145 					 * increase tcp_cwnd so that new
14146 					 * data can be sent if it is allowed
14147 					 * by the receive window (tcp_rwnd).
14148 					 * tcp_wput_data() will take care of
14149 					 * the rest.
14150 					 *
14151 					 * If the connection is SACK capable,
14152 					 * only do limited xmit when there
14153 					 * is SACK info.
14154 					 *
14155 					 * Note how tcp_cwnd is incremented.
14156 					 * The first dup ACK will increase
14157 					 * it by 1 MSS.  The second dup ACK
14158 					 * will increase it by 2 MSS.  This
14159 					 * means that only 1 new segment will
14160 					 * be sent for each dup ACK.
14161 					 */
14162 					if (tcp->tcp_unsent > 0 &&
14163 					    (!tcp->tcp_snd_sack_ok ||
14164 					    (tcp->tcp_snd_sack_ok &&
14165 					    tcp->tcp_notsack_list != NULL))) {
14166 						tcp->tcp_cwnd += mss <<
14167 						    (tcp->tcp_dupack_cnt - 1);
14168 						flags |= TH_LIMIT_XMIT;
14169 					}
14170 				} else if (dupack_cnt ==
14171 				    tcps->tcps_dupack_fast_retransmit) {
14172 
14173 				/*
14174 				 * If we have reduced tcp_ssthresh
14175 				 * because of ECN, do not reduce it again
14176 				 * unless it is already one window of data
14177 				 * away.  After one window of data, tcp_cwr
14178 				 * should then be cleared.  Note that
14179 				 * for non ECN capable connection, tcp_cwr
14180 				 * should always be false.
14181 				 *
14182 				 * Adjust cwnd since the duplicate
14183 				 * ack indicates that a packet was
14184 				 * dropped (due to congestion.)
14185 				 */
14186 				if (!tcp->tcp_cwr) {
14187 					npkt = ((tcp->tcp_snxt -
14188 					    tcp->tcp_suna) >> 1) / mss;
14189 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14190 					    mss;
14191 					tcp->tcp_cwnd = (npkt +
14192 					    tcp->tcp_dupack_cnt) * mss;
14193 				}
14194 				if (tcp->tcp_ecn_ok) {
14195 					tcp->tcp_cwr = B_TRUE;
14196 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14197 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14198 				}
14199 
14200 				/*
14201 				 * We do Hoe's algorithm.  Refer to her
14202 				 * paper "Improving the Start-up Behavior
14203 				 * of a Congestion Control Scheme for TCP,"
14204 				 * appeared in SIGCOMM'96.
14205 				 *
14206 				 * Save highest seq no we have sent so far.
14207 				 * Be careful about the invisible FIN byte.
14208 				 */
14209 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14210 				    (tcp->tcp_unsent == 0)) {
14211 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14212 				} else {
14213 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14214 				}
14215 
14216 				/*
14217 				 * Do not allow bursty traffic during.
14218 				 * fast recovery.  Refer to Fall and Floyd's
14219 				 * paper "Simulation-based Comparisons of
14220 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14221 				 * This is a best current practise.
14222 				 */
14223 				tcp->tcp_snd_burst = TCP_CWND_SS;
14224 
14225 				/*
14226 				 * For SACK:
14227 				 * Calculate tcp_pipe, which is the
14228 				 * estimated number of bytes in
14229 				 * network.
14230 				 *
14231 				 * tcp_fack is the highest sack'ed seq num
14232 				 * TCP has received.
14233 				 *
14234 				 * tcp_pipe is explained in the above quoted
14235 				 * Fall and Floyd's paper.  tcp_fack is
14236 				 * explained in Mathis and Mahdavi's
14237 				 * "Forward Acknowledgment: Refining TCP
14238 				 * Congestion Control" in SIGCOMM '96.
14239 				 */
14240 				if (tcp->tcp_snd_sack_ok) {
14241 					ASSERT(tcp->tcp_sack_info != NULL);
14242 					if (tcp->tcp_notsack_list != NULL) {
14243 						tcp->tcp_pipe = tcp->tcp_snxt -
14244 						    tcp->tcp_fack;
14245 						tcp->tcp_sack_snxt = seg_ack;
14246 						flags |= TH_NEED_SACK_REXMIT;
14247 					} else {
14248 						/*
14249 						 * Always initialize tcp_pipe
14250 						 * even though we don't have
14251 						 * any SACK info.  If later
14252 						 * we get SACK info and
14253 						 * tcp_pipe is not initialized,
14254 						 * funny things will happen.
14255 						 */
14256 						tcp->tcp_pipe =
14257 						    tcp->tcp_cwnd_ssthresh;
14258 					}
14259 				} else {
14260 					flags |= TH_REXMIT_NEEDED;
14261 				} /* tcp_snd_sack_ok */
14262 
14263 				} else {
14264 					/*
14265 					 * Here we perform congestion
14266 					 * avoidance, but NOT slow start.
14267 					 * This is known as the Fast
14268 					 * Recovery Algorithm.
14269 					 */
14270 					if (tcp->tcp_snd_sack_ok &&
14271 					    tcp->tcp_notsack_list != NULL) {
14272 						flags |= TH_NEED_SACK_REXMIT;
14273 						tcp->tcp_pipe -= mss;
14274 						if (tcp->tcp_pipe < 0)
14275 							tcp->tcp_pipe = 0;
14276 					} else {
14277 					/*
14278 					 * We know that one more packet has
14279 					 * left the pipe thus we can update
14280 					 * cwnd.
14281 					 */
14282 					cwnd = tcp->tcp_cwnd + mss;
14283 					if (cwnd > tcp->tcp_cwnd_max)
14284 						cwnd = tcp->tcp_cwnd_max;
14285 					tcp->tcp_cwnd = cwnd;
14286 					if (tcp->tcp_unsent > 0)
14287 						flags |= TH_XMIT_NEEDED;
14288 					}
14289 				}
14290 			}
14291 		} else if (tcp->tcp_zero_win_probe) {
14292 			/*
14293 			 * If the window has opened, need to arrange
14294 			 * to send additional data.
14295 			 */
14296 			if (new_swnd != 0) {
14297 				/* tcp_suna != tcp_snxt */
14298 				/* Packet contains a window update */
14299 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14300 				tcp->tcp_zero_win_probe = 0;
14301 				tcp->tcp_timer_backoff = 0;
14302 				tcp->tcp_ms_we_have_waited = 0;
14303 
14304 				/*
14305 				 * Transmit starting with tcp_suna since
14306 				 * the one byte probe is not ack'ed.
14307 				 * If TCP has sent more than one identical
14308 				 * probe, tcp_rexmit will be set.  That means
14309 				 * tcp_ss_rexmit() will send out the one
14310 				 * byte along with new data.  Otherwise,
14311 				 * fake the retransmission.
14312 				 */
14313 				flags |= TH_XMIT_NEEDED;
14314 				if (!tcp->tcp_rexmit) {
14315 					tcp->tcp_rexmit = B_TRUE;
14316 					tcp->tcp_dupack_cnt = 0;
14317 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14318 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14319 				}
14320 			}
14321 		}
14322 		goto swnd_update;
14323 	}
14324 
14325 	/*
14326 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14327 	 * If the ACK value acks something that we have not yet sent, it might
14328 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14329 	 * other side.
14330 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14331 	 * state is handled above, so we can always just drop the segment and
14332 	 * send an ACK here.
14333 	 *
14334 	 * Should we send ACKs in response to ACK only segments?
14335 	 */
14336 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14337 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14338 		/* drop the received segment */
14339 		freemsg(mp);
14340 
14341 		/*
14342 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14343 		 * greater than 0, check if the number of such
14344 		 * bogus ACks is greater than that count.  If yes,
14345 		 * don't send back any ACK.  This prevents TCP from
14346 		 * getting into an ACK storm if somehow an attacker
14347 		 * successfully spoofs an acceptable segment to our
14348 		 * peer.
14349 		 */
14350 		if (tcp_drop_ack_unsent_cnt > 0 &&
14351 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14352 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14353 			return;
14354 		}
14355 		mp = tcp_ack_mp(tcp);
14356 		if (mp != NULL) {
14357 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14358 			BUMP_LOCAL(tcp->tcp_obsegs);
14359 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14360 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14361 		}
14362 		return;
14363 	}
14364 
14365 	/*
14366 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14367 	 * blocks that are covered by this ACK.
14368 	 */
14369 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14370 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14371 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14372 	}
14373 
14374 	/*
14375 	 * If we got an ACK after fast retransmit, check to see
14376 	 * if it is a partial ACK.  If it is not and the congestion
14377 	 * window was inflated to account for the other side's
14378 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14379 	 */
14380 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14381 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14382 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14383 			tcp->tcp_dupack_cnt = 0;
14384 			/*
14385 			 * Restore the orig tcp_cwnd_ssthresh after
14386 			 * fast retransmit phase.
14387 			 */
14388 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14389 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14390 			}
14391 			tcp->tcp_rexmit_max = seg_ack;
14392 			tcp->tcp_cwnd_cnt = 0;
14393 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14394 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14395 
14396 			/*
14397 			 * Remove all notsack info to avoid confusion with
14398 			 * the next fast retrasnmit/recovery phase.
14399 			 */
14400 			if (tcp->tcp_snd_sack_ok &&
14401 			    tcp->tcp_notsack_list != NULL) {
14402 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14403 			}
14404 		} else {
14405 			if (tcp->tcp_snd_sack_ok &&
14406 			    tcp->tcp_notsack_list != NULL) {
14407 				flags |= TH_NEED_SACK_REXMIT;
14408 				tcp->tcp_pipe -= mss;
14409 				if (tcp->tcp_pipe < 0)
14410 					tcp->tcp_pipe = 0;
14411 			} else {
14412 				/*
14413 				 * Hoe's algorithm:
14414 				 *
14415 				 * Retransmit the unack'ed segment and
14416 				 * restart fast recovery.  Note that we
14417 				 * need to scale back tcp_cwnd to the
14418 				 * original value when we started fast
14419 				 * recovery.  This is to prevent overly
14420 				 * aggressive behaviour in sending new
14421 				 * segments.
14422 				 */
14423 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14424 				    tcps->tcps_dupack_fast_retransmit * mss;
14425 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14426 				flags |= TH_REXMIT_NEEDED;
14427 			}
14428 		}
14429 	} else {
14430 		tcp->tcp_dupack_cnt = 0;
14431 		if (tcp->tcp_rexmit) {
14432 			/*
14433 			 * TCP is retranmitting.  If the ACK ack's all
14434 			 * outstanding data, update tcp_rexmit_max and
14435 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14436 			 * to the correct value.
14437 			 *
14438 			 * Note that SEQ_LEQ() is used.  This is to avoid
14439 			 * unnecessary fast retransmit caused by dup ACKs
14440 			 * received when TCP does slow start retransmission
14441 			 * after a time out.  During this phase, TCP may
14442 			 * send out segments which are already received.
14443 			 * This causes dup ACKs to be sent back.
14444 			 */
14445 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14446 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14447 					tcp->tcp_rexmit_nxt = seg_ack;
14448 				}
14449 				if (seg_ack != tcp->tcp_rexmit_max) {
14450 					flags |= TH_XMIT_NEEDED;
14451 				}
14452 			} else {
14453 				tcp->tcp_rexmit = B_FALSE;
14454 				tcp->tcp_xmit_zc_clean = B_FALSE;
14455 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14456 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14457 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14458 			}
14459 			tcp->tcp_ms_we_have_waited = 0;
14460 		}
14461 	}
14462 
14463 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14464 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14465 	tcp->tcp_suna = seg_ack;
14466 	if (tcp->tcp_zero_win_probe != 0) {
14467 		tcp->tcp_zero_win_probe = 0;
14468 		tcp->tcp_timer_backoff = 0;
14469 	}
14470 
14471 	/*
14472 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14473 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14474 	 * will not reach here.
14475 	 */
14476 	if (mp1 == NULL) {
14477 		goto fin_acked;
14478 	}
14479 
14480 	/*
14481 	 * Update the congestion window.
14482 	 *
14483 	 * If TCP is not ECN capable or TCP is ECN capable but the
14484 	 * congestion experience bit is not set, increase the tcp_cwnd as
14485 	 * usual.
14486 	 */
14487 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14488 		cwnd = tcp->tcp_cwnd;
14489 		add = mss;
14490 
14491 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14492 			/*
14493 			 * This is to prevent an increase of less than 1 MSS of
14494 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14495 			 * may send out tinygrams in order to preserve mblk
14496 			 * boundaries.
14497 			 *
14498 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14499 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14500 			 * increased by 1 MSS for every RTTs.
14501 			 */
14502 			if (tcp->tcp_cwnd_cnt <= 0) {
14503 				tcp->tcp_cwnd_cnt = cwnd + add;
14504 			} else {
14505 				tcp->tcp_cwnd_cnt -= add;
14506 				add = 0;
14507 			}
14508 		}
14509 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14510 	}
14511 
14512 	/* See if the latest urgent data has been acknowledged */
14513 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14514 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14515 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14516 
14517 	/* Can we update the RTT estimates? */
14518 	if (tcp->tcp_snd_ts_ok) {
14519 		/* Ignore zero timestamp echo-reply. */
14520 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14521 			tcp_set_rto(tcp, (int32_t)lbolt -
14522 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14523 		}
14524 
14525 		/* If needed, restart the timer. */
14526 		if (tcp->tcp_set_timer == 1) {
14527 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14528 			tcp->tcp_set_timer = 0;
14529 		}
14530 		/*
14531 		 * Update tcp_csuna in case the other side stops sending
14532 		 * us timestamps.
14533 		 */
14534 		tcp->tcp_csuna = tcp->tcp_snxt;
14535 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14536 		/*
14537 		 * An ACK sequence we haven't seen before, so get the RTT
14538 		 * and update the RTO. But first check if the timestamp is
14539 		 * valid to use.
14540 		 */
14541 		if ((mp1->b_next != NULL) &&
14542 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14543 			tcp_set_rto(tcp, (int32_t)lbolt -
14544 			    (int32_t)(intptr_t)mp1->b_prev);
14545 		else
14546 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14547 
14548 		/* Remeber the last sequence to be ACKed */
14549 		tcp->tcp_csuna = seg_ack;
14550 		if (tcp->tcp_set_timer == 1) {
14551 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14552 			tcp->tcp_set_timer = 0;
14553 		}
14554 	} else {
14555 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14556 	}
14557 
14558 	/* Eat acknowledged bytes off the xmit queue. */
14559 	for (;;) {
14560 		mblk_t	*mp2;
14561 		uchar_t	*wptr;
14562 
14563 		wptr = mp1->b_wptr;
14564 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14565 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14566 		if (bytes_acked < 0) {
14567 			mp1->b_rptr = wptr + bytes_acked;
14568 			/*
14569 			 * Set a new timestamp if all the bytes timed by the
14570 			 * old timestamp have been ack'ed.
14571 			 */
14572 			if (SEQ_GT(seg_ack,
14573 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14574 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14575 				mp1->b_next = NULL;
14576 			}
14577 			break;
14578 		}
14579 		mp1->b_next = NULL;
14580 		mp1->b_prev = NULL;
14581 		mp2 = mp1;
14582 		mp1 = mp1->b_cont;
14583 
14584 		/*
14585 		 * This notification is required for some zero-copy
14586 		 * clients to maintain a copy semantic. After the data
14587 		 * is ack'ed, client is safe to modify or reuse the buffer.
14588 		 */
14589 		if (tcp->tcp_snd_zcopy_aware &&
14590 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14591 			tcp_zcopy_notify(tcp);
14592 		freeb(mp2);
14593 		if (bytes_acked == 0) {
14594 			if (mp1 == NULL) {
14595 				/* Everything is ack'ed, clear the tail. */
14596 				tcp->tcp_xmit_tail = NULL;
14597 				/*
14598 				 * Cancel the timer unless we are still
14599 				 * waiting for an ACK for the FIN packet.
14600 				 */
14601 				if (tcp->tcp_timer_tid != 0 &&
14602 				    tcp->tcp_snxt == tcp->tcp_suna) {
14603 					(void) TCP_TIMER_CANCEL(tcp,
14604 					    tcp->tcp_timer_tid);
14605 					tcp->tcp_timer_tid = 0;
14606 				}
14607 				goto pre_swnd_update;
14608 			}
14609 			if (mp2 != tcp->tcp_xmit_tail)
14610 				break;
14611 			tcp->tcp_xmit_tail = mp1;
14612 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14613 			    (uintptr_t)INT_MAX);
14614 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14615 			    mp1->b_rptr);
14616 			break;
14617 		}
14618 		if (mp1 == NULL) {
14619 			/*
14620 			 * More was acked but there is nothing more
14621 			 * outstanding.  This means that the FIN was
14622 			 * just acked or that we're talking to a clown.
14623 			 */
14624 fin_acked:
14625 			ASSERT(tcp->tcp_fin_sent);
14626 			tcp->tcp_xmit_tail = NULL;
14627 			if (tcp->tcp_fin_sent) {
14628 				/* FIN was acked - making progress */
14629 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14630 				    !tcp->tcp_fin_acked)
14631 					tcp->tcp_ip_forward_progress = B_TRUE;
14632 				tcp->tcp_fin_acked = B_TRUE;
14633 				if (tcp->tcp_linger_tid != 0 &&
14634 				    TCP_TIMER_CANCEL(tcp,
14635 					tcp->tcp_linger_tid) >= 0) {
14636 					tcp_stop_lingering(tcp);
14637 				}
14638 			} else {
14639 				/*
14640 				 * We should never get here because
14641 				 * we have already checked that the
14642 				 * number of bytes ack'ed should be
14643 				 * smaller than or equal to what we
14644 				 * have sent so far (it is the
14645 				 * acceptability check of the ACK).
14646 				 * We can only get here if the send
14647 				 * queue is corrupted.
14648 				 *
14649 				 * Terminate the connection and
14650 				 * panic the system.  It is better
14651 				 * for us to panic instead of
14652 				 * continuing to avoid other disaster.
14653 				 */
14654 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14655 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14656 				panic("Memory corruption "
14657 				    "detected for connection %s.",
14658 				    tcp_display(tcp, NULL,
14659 					DISP_ADDR_AND_PORT));
14660 				/*NOTREACHED*/
14661 			}
14662 			goto pre_swnd_update;
14663 		}
14664 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14665 	}
14666 	if (tcp->tcp_unsent) {
14667 		flags |= TH_XMIT_NEEDED;
14668 	}
14669 pre_swnd_update:
14670 	tcp->tcp_xmit_head = mp1;
14671 swnd_update:
14672 	/*
14673 	 * The following check is different from most other implementations.
14674 	 * For bi-directional transfer, when segments are dropped, the
14675 	 * "normal" check will not accept a window update in those
14676 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14677 	 * segments which are outside receiver's window.  As TCP accepts
14678 	 * the ack in those retransmitted segments, if the window update in
14679 	 * the same segment is not accepted, TCP will incorrectly calculates
14680 	 * that it can send more segments.  This can create a deadlock
14681 	 * with the receiver if its window becomes zero.
14682 	 */
14683 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14684 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14685 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14686 		/*
14687 		 * The criteria for update is:
14688 		 *
14689 		 * 1. the segment acknowledges some data.  Or
14690 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14691 		 * 3. the segment is not old and the advertised window is
14692 		 * larger than the previous advertised window.
14693 		 */
14694 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14695 			flags |= TH_XMIT_NEEDED;
14696 		tcp->tcp_swnd = new_swnd;
14697 		if (new_swnd > tcp->tcp_max_swnd)
14698 			tcp->tcp_max_swnd = new_swnd;
14699 		tcp->tcp_swl1 = seg_seq;
14700 		tcp->tcp_swl2 = seg_ack;
14701 	}
14702 est:
14703 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14704 
14705 		switch (tcp->tcp_state) {
14706 		case TCPS_FIN_WAIT_1:
14707 			if (tcp->tcp_fin_acked) {
14708 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14709 				/*
14710 				 * We implement the non-standard BSD/SunOS
14711 				 * FIN_WAIT_2 flushing algorithm.
14712 				 * If there is no user attached to this
14713 				 * TCP endpoint, then this TCP struct
14714 				 * could hang around forever in FIN_WAIT_2
14715 				 * state if the peer forgets to send us
14716 				 * a FIN.  To prevent this, we wait only
14717 				 * 2*MSL (a convenient time value) for
14718 				 * the FIN to arrive.  If it doesn't show up,
14719 				 * we flush the TCP endpoint.  This algorithm,
14720 				 * though a violation of RFC-793, has worked
14721 				 * for over 10 years in BSD systems.
14722 				 * Note: SunOS 4.x waits 675 seconds before
14723 				 * flushing the FIN_WAIT_2 connection.
14724 				 */
14725 				TCP_TIMER_RESTART(tcp,
14726 				    tcps->tcps_fin_wait_2_flush_interval);
14727 			}
14728 			break;
14729 		case TCPS_FIN_WAIT_2:
14730 			break;	/* Shutdown hook? */
14731 		case TCPS_LAST_ACK:
14732 			freemsg(mp);
14733 			if (tcp->tcp_fin_acked) {
14734 				(void) tcp_clean_death(tcp, 0, 19);
14735 				return;
14736 			}
14737 			goto xmit_check;
14738 		case TCPS_CLOSING:
14739 			if (tcp->tcp_fin_acked) {
14740 				tcp->tcp_state = TCPS_TIME_WAIT;
14741 				/*
14742 				 * Unconditionally clear the exclusive binding
14743 				 * bit so this TIME-WAIT connection won't
14744 				 * interfere with new ones.
14745 				 */
14746 				tcp->tcp_exclbind = 0;
14747 				if (!TCP_IS_DETACHED(tcp)) {
14748 					TCP_TIMER_RESTART(tcp,
14749 					    tcps->tcps_time_wait_interval);
14750 				} else {
14751 					tcp_time_wait_append(tcp);
14752 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14753 				}
14754 			}
14755 			/*FALLTHRU*/
14756 		case TCPS_CLOSE_WAIT:
14757 			freemsg(mp);
14758 			goto xmit_check;
14759 		default:
14760 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14761 			break;
14762 		}
14763 	}
14764 	if (flags & TH_FIN) {
14765 		/* Make sure we ack the fin */
14766 		flags |= TH_ACK_NEEDED;
14767 		if (!tcp->tcp_fin_rcvd) {
14768 			tcp->tcp_fin_rcvd = B_TRUE;
14769 			tcp->tcp_rnxt++;
14770 			tcph = tcp->tcp_tcph;
14771 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14772 
14773 			/*
14774 			 * Generate the ordrel_ind at the end unless we
14775 			 * are an eager guy.
14776 			 * In the eager case tcp_rsrv will do this when run
14777 			 * after tcp_accept is done.
14778 			 */
14779 			if (tcp->tcp_listener == NULL &&
14780 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14781 				flags |= TH_ORDREL_NEEDED;
14782 			switch (tcp->tcp_state) {
14783 			case TCPS_SYN_RCVD:
14784 			case TCPS_ESTABLISHED:
14785 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14786 				/* Keepalive? */
14787 				break;
14788 			case TCPS_FIN_WAIT_1:
14789 				if (!tcp->tcp_fin_acked) {
14790 					tcp->tcp_state = TCPS_CLOSING;
14791 					break;
14792 				}
14793 				/* FALLTHRU */
14794 			case TCPS_FIN_WAIT_2:
14795 				tcp->tcp_state = TCPS_TIME_WAIT;
14796 				/*
14797 				 * Unconditionally clear the exclusive binding
14798 				 * bit so this TIME-WAIT connection won't
14799 				 * interfere with new ones.
14800 				 */
14801 				tcp->tcp_exclbind = 0;
14802 				if (!TCP_IS_DETACHED(tcp)) {
14803 					TCP_TIMER_RESTART(tcp,
14804 					    tcps->tcps_time_wait_interval);
14805 				} else {
14806 					tcp_time_wait_append(tcp);
14807 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14808 				}
14809 				if (seg_len) {
14810 					/*
14811 					 * implies data piggybacked on FIN.
14812 					 * break to handle data.
14813 					 */
14814 					break;
14815 				}
14816 				freemsg(mp);
14817 				goto ack_check;
14818 			}
14819 		}
14820 	}
14821 	if (mp == NULL)
14822 		goto xmit_check;
14823 	if (seg_len == 0) {
14824 		freemsg(mp);
14825 		goto xmit_check;
14826 	}
14827 	if (mp->b_rptr == mp->b_wptr) {
14828 		/*
14829 		 * The header has been consumed, so we remove the
14830 		 * zero-length mblk here.
14831 		 */
14832 		mp1 = mp;
14833 		mp = mp->b_cont;
14834 		freeb(mp1);
14835 	}
14836 	tcph = tcp->tcp_tcph;
14837 	tcp->tcp_rack_cnt++;
14838 	{
14839 		uint32_t cur_max;
14840 
14841 		cur_max = tcp->tcp_rack_cur_max;
14842 		if (tcp->tcp_rack_cnt >= cur_max) {
14843 			/*
14844 			 * We have more unacked data than we should - send
14845 			 * an ACK now.
14846 			 */
14847 			flags |= TH_ACK_NEEDED;
14848 			cur_max++;
14849 			if (cur_max > tcp->tcp_rack_abs_max)
14850 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14851 			else
14852 				tcp->tcp_rack_cur_max = cur_max;
14853 		} else if (TCP_IS_DETACHED(tcp)) {
14854 			/* We don't have an ACK timer for detached TCP. */
14855 			flags |= TH_ACK_NEEDED;
14856 		} else if (seg_len < mss) {
14857 			/*
14858 			 * If we get a segment that is less than an mss, and we
14859 			 * already have unacknowledged data, and the amount
14860 			 * unacknowledged is not a multiple of mss, then we
14861 			 * better generate an ACK now.  Otherwise, this may be
14862 			 * the tail piece of a transaction, and we would rather
14863 			 * wait for the response.
14864 			 */
14865 			uint32_t udif;
14866 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14867 			    (uintptr_t)INT_MAX);
14868 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14869 			if (udif && (udif % mss))
14870 				flags |= TH_ACK_NEEDED;
14871 			else
14872 				flags |= TH_ACK_TIMER_NEEDED;
14873 		} else {
14874 			/* Start delayed ack timer */
14875 			flags |= TH_ACK_TIMER_NEEDED;
14876 		}
14877 	}
14878 	tcp->tcp_rnxt += seg_len;
14879 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14880 
14881 	/* Update SACK list */
14882 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14883 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14884 		    &(tcp->tcp_num_sack_blk));
14885 	}
14886 
14887 	if (tcp->tcp_urp_mp) {
14888 		tcp->tcp_urp_mp->b_cont = mp;
14889 		mp = tcp->tcp_urp_mp;
14890 		tcp->tcp_urp_mp = NULL;
14891 		/* Ready for a new signal. */
14892 		tcp->tcp_urp_last_valid = B_FALSE;
14893 #ifdef DEBUG
14894 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14895 		    "tcp_rput: sending exdata_ind %s",
14896 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14897 #endif /* DEBUG */
14898 	}
14899 
14900 	/*
14901 	 * Check for ancillary data changes compared to last segment.
14902 	 */
14903 	if (tcp->tcp_ipv6_recvancillary != 0) {
14904 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14905 		if (mp == NULL)
14906 			return;
14907 	}
14908 
14909 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14910 		/*
14911 		 * Side queue inbound data until the accept happens.
14912 		 * tcp_accept/tcp_rput drains this when the accept happens.
14913 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14914 		 * T_EXDATA_IND) it is queued on b_next.
14915 		 * XXX Make urgent data use this. Requires:
14916 		 *	Removing tcp_listener check for TH_URG
14917 		 *	Making M_PCPROTO and MARK messages skip the eager case
14918 		 */
14919 
14920 		if (tcp->tcp_kssl_pending) {
14921 			tcp_kssl_input(tcp, mp);
14922 		} else {
14923 			tcp_rcv_enqueue(tcp, mp, seg_len);
14924 		}
14925 	} else {
14926 		if (mp->b_datap->db_type != M_DATA ||
14927 		    (flags & TH_MARKNEXT_NEEDED)) {
14928 			if (tcp->tcp_rcv_list != NULL) {
14929 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14930 			}
14931 			ASSERT(tcp->tcp_rcv_list == NULL ||
14932 			    tcp->tcp_fused_sigurg);
14933 			if (flags & TH_MARKNEXT_NEEDED) {
14934 #ifdef DEBUG
14935 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14936 				    "tcp_rput: sending MSGMARKNEXT %s",
14937 				    tcp_display(tcp, NULL,
14938 				    DISP_PORT_ONLY));
14939 #endif /* DEBUG */
14940 				mp->b_flag |= MSGMARKNEXT;
14941 				flags &= ~TH_MARKNEXT_NEEDED;
14942 			}
14943 
14944 			/* Does this need SSL processing first? */
14945 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14946 			    (DB_TYPE(mp) == M_DATA)) {
14947 				tcp_kssl_input(tcp, mp);
14948 			} else {
14949 				putnext(tcp->tcp_rq, mp);
14950 				if (!canputnext(tcp->tcp_rq))
14951 					tcp->tcp_rwnd -= seg_len;
14952 			}
14953 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14954 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14955 			if (tcp->tcp_rcv_list != NULL) {
14956 				/*
14957 				 * Enqueue the new segment first and then
14958 				 * call tcp_rcv_drain() to send all data
14959 				 * up.  The other way to do this is to
14960 				 * send all queued data up and then call
14961 				 * putnext() to send the new segment up.
14962 				 * This way can remove the else part later
14963 				 * on.
14964 				 *
14965 				 * We don't this to avoid one more call to
14966 				 * canputnext() as tcp_rcv_drain() needs to
14967 				 * call canputnext().
14968 				 */
14969 				tcp_rcv_enqueue(tcp, mp, seg_len);
14970 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14971 			} else {
14972 				/* Does this need SSL processing first? */
14973 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14974 				    (DB_TYPE(mp) == M_DATA)) {
14975 					tcp_kssl_input(tcp, mp);
14976 				} else {
14977 					putnext(tcp->tcp_rq, mp);
14978 					if (!canputnext(tcp->tcp_rq))
14979 						tcp->tcp_rwnd -= seg_len;
14980 				}
14981 			}
14982 		} else {
14983 			/*
14984 			 * Enqueue all packets when processing an mblk
14985 			 * from the co queue and also enqueue normal packets.
14986 			 */
14987 			tcp_rcv_enqueue(tcp, mp, seg_len);
14988 		}
14989 		/*
14990 		 * Make sure the timer is running if we have data waiting
14991 		 * for a push bit. This provides resiliency against
14992 		 * implementations that do not correctly generate push bits.
14993 		 */
14994 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14995 			/*
14996 			 * The connection may be closed at this point, so don't
14997 			 * do anything for a detached tcp.
14998 			 */
14999 			if (!TCP_IS_DETACHED(tcp))
15000 			    tcp->tcp_push_tid = TCP_TIMER(tcp,
15001 				tcp_push_timer,
15002 				MSEC_TO_TICK(tcps->tcps_push_timer_interval));
15003 		}
15004 	}
15005 xmit_check:
15006 	/* Is there anything left to do? */
15007 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15008 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15009 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15010 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15011 		goto done;
15012 
15013 	/* Any transmit work to do and a non-zero window? */
15014 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15015 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15016 		if (flags & TH_REXMIT_NEEDED) {
15017 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15018 
15019 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15020 			if (snd_size > mss)
15021 				snd_size = mss;
15022 			if (snd_size > tcp->tcp_swnd)
15023 				snd_size = tcp->tcp_swnd;
15024 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15025 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15026 			    B_TRUE);
15027 
15028 			if (mp1 != NULL) {
15029 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15030 				tcp->tcp_csuna = tcp->tcp_snxt;
15031 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15032 				UPDATE_MIB(&tcps->tcps_mib,
15033 				    tcpRetransBytes, snd_size);
15034 				TCP_RECORD_TRACE(tcp, mp1,
15035 				    TCP_TRACE_SEND_PKT);
15036 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15037 			}
15038 		}
15039 		if (flags & TH_NEED_SACK_REXMIT) {
15040 			tcp_sack_rxmit(tcp, &flags);
15041 		}
15042 		/*
15043 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15044 		 * out new segment.  Note that tcp_rexmit should not be
15045 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15046 		 */
15047 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15048 			if (!tcp->tcp_rexmit) {
15049 				tcp_wput_data(tcp, NULL, B_FALSE);
15050 			} else {
15051 				tcp_ss_rexmit(tcp);
15052 			}
15053 		}
15054 		/*
15055 		 * Adjust tcp_cwnd back to normal value after sending
15056 		 * new data segments.
15057 		 */
15058 		if (flags & TH_LIMIT_XMIT) {
15059 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15060 			/*
15061 			 * This will restart the timer.  Restarting the
15062 			 * timer is used to avoid a timeout before the
15063 			 * limited transmitted segment's ACK gets back.
15064 			 */
15065 			if (tcp->tcp_xmit_head != NULL)
15066 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15067 		}
15068 
15069 		/* Anything more to do? */
15070 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15071 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15072 			goto done;
15073 	}
15074 ack_check:
15075 	if (flags & TH_SEND_URP_MARK) {
15076 		ASSERT(tcp->tcp_urp_mark_mp);
15077 		/*
15078 		 * Send up any queued data and then send the mark message
15079 		 */
15080 		if (tcp->tcp_rcv_list != NULL) {
15081 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15082 		}
15083 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15084 
15085 		mp1 = tcp->tcp_urp_mark_mp;
15086 		tcp->tcp_urp_mark_mp = NULL;
15087 #ifdef DEBUG
15088 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15089 		    "tcp_rput: sending zero-length %s %s",
15090 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15091 		    "MSGNOTMARKNEXT"),
15092 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15093 #endif /* DEBUG */
15094 		putnext(tcp->tcp_rq, mp1);
15095 		flags &= ~TH_SEND_URP_MARK;
15096 	}
15097 	if (flags & TH_ACK_NEEDED) {
15098 		/*
15099 		 * Time to send an ack for some reason.
15100 		 */
15101 		mp1 = tcp_ack_mp(tcp);
15102 
15103 		if (mp1 != NULL) {
15104 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15105 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15106 			BUMP_LOCAL(tcp->tcp_obsegs);
15107 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15108 		}
15109 		if (tcp->tcp_ack_tid != 0) {
15110 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15111 			tcp->tcp_ack_tid = 0;
15112 		}
15113 	}
15114 	if (flags & TH_ACK_TIMER_NEEDED) {
15115 		/*
15116 		 * Arrange for deferred ACK or push wait timeout.
15117 		 * Start timer if it is not already running.
15118 		 */
15119 		if (tcp->tcp_ack_tid == 0) {
15120 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15121 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15122 			    (clock_t)tcps->tcps_local_dack_interval :
15123 			    (clock_t)tcps->tcps_deferred_ack_interval));
15124 		}
15125 	}
15126 	if (flags & TH_ORDREL_NEEDED) {
15127 		/*
15128 		 * Send up the ordrel_ind unless we are an eager guy.
15129 		 * In the eager case tcp_rsrv will do this when run
15130 		 * after tcp_accept is done.
15131 		 */
15132 		ASSERT(tcp->tcp_listener == NULL);
15133 		if (tcp->tcp_rcv_list != NULL) {
15134 			/*
15135 			 * Push any mblk(s) enqueued from co processing.
15136 			 */
15137 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15138 		}
15139 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15140 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15141 			tcp->tcp_ordrel_done = B_TRUE;
15142 			putnext(tcp->tcp_rq, mp1);
15143 			if (tcp->tcp_deferred_clean_death) {
15144 				/*
15145 				 * tcp_clean_death was deferred
15146 				 * for T_ORDREL_IND - do it now
15147 				 */
15148 				(void) tcp_clean_death(tcp,
15149 				    tcp->tcp_client_errno, 20);
15150 				tcp->tcp_deferred_clean_death =	B_FALSE;
15151 			}
15152 		} else {
15153 			/*
15154 			 * Run the orderly release in the
15155 			 * service routine.
15156 			 */
15157 			qenable(tcp->tcp_rq);
15158 			/*
15159 			 * Caveat(XXX): The machine may be so
15160 			 * overloaded that tcp_rsrv() is not scheduled
15161 			 * until after the endpoint has transitioned
15162 			 * to TCPS_TIME_WAIT
15163 			 * and tcp_time_wait_interval expires. Then
15164 			 * tcp_timer() will blow away state in tcp_t
15165 			 * and T_ORDREL_IND will never be delivered
15166 			 * upstream. Unlikely but potentially
15167 			 * a problem.
15168 			 */
15169 		}
15170 	}
15171 done:
15172 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15173 }
15174 
15175 /*
15176  * This function does PAWS protection check. Returns B_TRUE if the
15177  * segment passes the PAWS test, else returns B_FALSE.
15178  */
15179 boolean_t
15180 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15181 {
15182 	uint8_t	flags;
15183 	int	options;
15184 	uint8_t *up;
15185 
15186 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15187 	/*
15188 	 * If timestamp option is aligned nicely, get values inline,
15189 	 * otherwise call general routine to parse.  Only do that
15190 	 * if timestamp is the only option.
15191 	 */
15192 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15193 	    TCPOPT_REAL_TS_LEN &&
15194 	    OK_32PTR((up = ((uint8_t *)tcph) +
15195 	    TCP_MIN_HEADER_LENGTH)) &&
15196 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15197 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15198 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15199 
15200 		options = TCP_OPT_TSTAMP_PRESENT;
15201 	} else {
15202 		if (tcp->tcp_snd_sack_ok) {
15203 			tcpoptp->tcp = tcp;
15204 		} else {
15205 			tcpoptp->tcp = NULL;
15206 		}
15207 		options = tcp_parse_options(tcph, tcpoptp);
15208 	}
15209 
15210 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15211 		/*
15212 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15213 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15214 		 */
15215 		if ((flags & TH_RST) == 0 &&
15216 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15217 		    tcp->tcp_ts_recent)) {
15218 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15219 			    PAWS_TIMEOUT)) {
15220 				/* This segment is not acceptable. */
15221 				return (B_FALSE);
15222 			} else {
15223 				/*
15224 				 * Connection has been idle for
15225 				 * too long.  Reset the timestamp
15226 				 * and assume the segment is valid.
15227 				 */
15228 				tcp->tcp_ts_recent =
15229 				    tcpoptp->tcp_opt_ts_val;
15230 			}
15231 		}
15232 	} else {
15233 		/*
15234 		 * If we don't get a timestamp on every packet, we
15235 		 * figure we can't really trust 'em, so we stop sending
15236 		 * and parsing them.
15237 		 */
15238 		tcp->tcp_snd_ts_ok = B_FALSE;
15239 
15240 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15241 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15242 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15243 		/*
15244 		 * Adjust the tcp_mss accordingly. We also need to
15245 		 * adjust tcp_cwnd here in accordance with the new mss.
15246 		 * But we avoid doing a slow start here so as to not
15247 		 * to lose on the transfer rate built up so far.
15248 		 */
15249 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15250 		if (tcp->tcp_snd_sack_ok) {
15251 			ASSERT(tcp->tcp_sack_info != NULL);
15252 			tcp->tcp_max_sack_blk = 4;
15253 		}
15254 	}
15255 	return (B_TRUE);
15256 }
15257 
15258 /*
15259  * Attach ancillary data to a received TCP segments for the
15260  * ancillary pieces requested by the application that are
15261  * different than they were in the previous data segment.
15262  *
15263  * Save the "current" values once memory allocation is ok so that
15264  * when memory allocation fails we can just wait for the next data segment.
15265  */
15266 static mblk_t *
15267 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15268 {
15269 	struct T_optdata_ind *todi;
15270 	int optlen;
15271 	uchar_t *optptr;
15272 	struct T_opthdr *toh;
15273 	uint_t addflag;	/* Which pieces to add */
15274 	mblk_t *mp1;
15275 
15276 	optlen = 0;
15277 	addflag = 0;
15278 	/* If app asked for pktinfo and the index has changed ... */
15279 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15280 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15281 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15282 		optlen += sizeof (struct T_opthdr) +
15283 		    sizeof (struct in6_pktinfo);
15284 		addflag |= TCP_IPV6_RECVPKTINFO;
15285 	}
15286 	/* If app asked for hoplimit and it has changed ... */
15287 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15288 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15289 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15290 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15291 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15292 	}
15293 	/* If app asked for tclass and it has changed ... */
15294 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15295 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15296 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15297 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15298 		addflag |= TCP_IPV6_RECVTCLASS;
15299 	}
15300 	/*
15301 	 * If app asked for hopbyhop headers and it has changed ...
15302 	 * For security labels, note that (1) security labels can't change on
15303 	 * a connected socket at all, (2) we're connected to at most one peer,
15304 	 * (3) if anything changes, then it must be some other extra option.
15305 	 */
15306 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15307 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15308 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15309 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15310 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15311 		    tcp->tcp_label_len;
15312 		addflag |= TCP_IPV6_RECVHOPOPTS;
15313 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15314 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15315 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15316 			return (mp);
15317 	}
15318 	/* If app asked for dst headers before routing headers ... */
15319 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15320 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15321 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15322 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15323 		optlen += sizeof (struct T_opthdr) +
15324 		    ipp->ipp_rtdstoptslen;
15325 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15326 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15327 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15328 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15329 			return (mp);
15330 	}
15331 	/* If app asked for routing headers and it has changed ... */
15332 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15333 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15334 	    (ipp->ipp_fields & IPPF_RTHDR),
15335 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15336 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15337 		addflag |= TCP_IPV6_RECVRTHDR;
15338 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15339 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15340 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15341 			return (mp);
15342 	}
15343 	/* If app asked for dest headers and it has changed ... */
15344 	if ((tcp->tcp_ipv6_recvancillary &
15345 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15346 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15347 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15348 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15349 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15350 		addflag |= TCP_IPV6_RECVDSTOPTS;
15351 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15352 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15353 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15354 			return (mp);
15355 	}
15356 
15357 	if (optlen == 0) {
15358 		/* Nothing to add */
15359 		return (mp);
15360 	}
15361 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15362 	if (mp1 == NULL) {
15363 		/*
15364 		 * Defer sending ancillary data until the next TCP segment
15365 		 * arrives.
15366 		 */
15367 		return (mp);
15368 	}
15369 	mp1->b_cont = mp;
15370 	mp = mp1;
15371 	mp->b_wptr += sizeof (*todi) + optlen;
15372 	mp->b_datap->db_type = M_PROTO;
15373 	todi = (struct T_optdata_ind *)mp->b_rptr;
15374 	todi->PRIM_type = T_OPTDATA_IND;
15375 	todi->DATA_flag = 1;	/* MORE data */
15376 	todi->OPT_length = optlen;
15377 	todi->OPT_offset = sizeof (*todi);
15378 	optptr = (uchar_t *)&todi[1];
15379 	/*
15380 	 * If app asked for pktinfo and the index has changed ...
15381 	 * Note that the local address never changes for the connection.
15382 	 */
15383 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15384 		struct in6_pktinfo *pkti;
15385 
15386 		toh = (struct T_opthdr *)optptr;
15387 		toh->level = IPPROTO_IPV6;
15388 		toh->name = IPV6_PKTINFO;
15389 		toh->len = sizeof (*toh) + sizeof (*pkti);
15390 		toh->status = 0;
15391 		optptr += sizeof (*toh);
15392 		pkti = (struct in6_pktinfo *)optptr;
15393 		if (tcp->tcp_ipversion == IPV6_VERSION)
15394 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15395 		else
15396 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15397 			    &pkti->ipi6_addr);
15398 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15399 		optptr += sizeof (*pkti);
15400 		ASSERT(OK_32PTR(optptr));
15401 		/* Save as "last" value */
15402 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15403 	}
15404 	/* If app asked for hoplimit and it has changed ... */
15405 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15406 		toh = (struct T_opthdr *)optptr;
15407 		toh->level = IPPROTO_IPV6;
15408 		toh->name = IPV6_HOPLIMIT;
15409 		toh->len = sizeof (*toh) + sizeof (uint_t);
15410 		toh->status = 0;
15411 		optptr += sizeof (*toh);
15412 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15413 		optptr += sizeof (uint_t);
15414 		ASSERT(OK_32PTR(optptr));
15415 		/* Save as "last" value */
15416 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15417 	}
15418 	/* If app asked for tclass and it has changed ... */
15419 	if (addflag & TCP_IPV6_RECVTCLASS) {
15420 		toh = (struct T_opthdr *)optptr;
15421 		toh->level = IPPROTO_IPV6;
15422 		toh->name = IPV6_TCLASS;
15423 		toh->len = sizeof (*toh) + sizeof (uint_t);
15424 		toh->status = 0;
15425 		optptr += sizeof (*toh);
15426 		*(uint_t *)optptr = ipp->ipp_tclass;
15427 		optptr += sizeof (uint_t);
15428 		ASSERT(OK_32PTR(optptr));
15429 		/* Save as "last" value */
15430 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15431 	}
15432 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15433 		toh = (struct T_opthdr *)optptr;
15434 		toh->level = IPPROTO_IPV6;
15435 		toh->name = IPV6_HOPOPTS;
15436 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15437 		    tcp->tcp_label_len;
15438 		toh->status = 0;
15439 		optptr += sizeof (*toh);
15440 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15441 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15442 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15443 		ASSERT(OK_32PTR(optptr));
15444 		/* Save as last value */
15445 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15446 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15447 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15448 	}
15449 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15450 		toh = (struct T_opthdr *)optptr;
15451 		toh->level = IPPROTO_IPV6;
15452 		toh->name = IPV6_RTHDRDSTOPTS;
15453 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15454 		toh->status = 0;
15455 		optptr += sizeof (*toh);
15456 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15457 		optptr += ipp->ipp_rtdstoptslen;
15458 		ASSERT(OK_32PTR(optptr));
15459 		/* Save as last value */
15460 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15461 		    &tcp->tcp_rtdstoptslen,
15462 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15463 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15464 	}
15465 	if (addflag & TCP_IPV6_RECVRTHDR) {
15466 		toh = (struct T_opthdr *)optptr;
15467 		toh->level = IPPROTO_IPV6;
15468 		toh->name = IPV6_RTHDR;
15469 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15470 		toh->status = 0;
15471 		optptr += sizeof (*toh);
15472 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15473 		optptr += ipp->ipp_rthdrlen;
15474 		ASSERT(OK_32PTR(optptr));
15475 		/* Save as last value */
15476 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15477 		    (ipp->ipp_fields & IPPF_RTHDR),
15478 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15479 	}
15480 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15481 		toh = (struct T_opthdr *)optptr;
15482 		toh->level = IPPROTO_IPV6;
15483 		toh->name = IPV6_DSTOPTS;
15484 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15485 		toh->status = 0;
15486 		optptr += sizeof (*toh);
15487 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15488 		optptr += ipp->ipp_dstoptslen;
15489 		ASSERT(OK_32PTR(optptr));
15490 		/* Save as last value */
15491 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15492 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15493 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15494 	}
15495 	ASSERT(optptr == mp->b_wptr);
15496 	return (mp);
15497 }
15498 
15499 
15500 /*
15501  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15502  * or a "bad" IRE detected by tcp_adapt_ire.
15503  * We can't tell if the failure was due to the laddr or the faddr
15504  * thus we clear out all addresses and ports.
15505  */
15506 static void
15507 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15508 {
15509 	queue_t	*q = tcp->tcp_rq;
15510 	tcph_t	*tcph;
15511 	struct T_error_ack *tea;
15512 	conn_t	*connp = tcp->tcp_connp;
15513 
15514 
15515 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15516 
15517 	if (mp->b_cont) {
15518 		freemsg(mp->b_cont);
15519 		mp->b_cont = NULL;
15520 	}
15521 	tea = (struct T_error_ack *)mp->b_rptr;
15522 	switch (tea->PRIM_type) {
15523 	case T_BIND_ACK:
15524 		/*
15525 		 * Need to unbind with classifier since we were just told that
15526 		 * our bind succeeded.
15527 		 */
15528 		tcp->tcp_hard_bound = B_FALSE;
15529 		tcp->tcp_hard_binding = B_FALSE;
15530 
15531 		ipcl_hash_remove(connp);
15532 		/* Reuse the mblk if possible */
15533 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15534 			sizeof (*tea));
15535 		mp->b_rptr = mp->b_datap->db_base;
15536 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15537 		tea = (struct T_error_ack *)mp->b_rptr;
15538 		tea->PRIM_type = T_ERROR_ACK;
15539 		tea->TLI_error = TSYSERR;
15540 		tea->UNIX_error = error;
15541 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15542 			tea->ERROR_prim = T_CONN_REQ;
15543 		} else {
15544 			tea->ERROR_prim = O_T_BIND_REQ;
15545 		}
15546 		break;
15547 
15548 	case T_ERROR_ACK:
15549 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15550 			tea->ERROR_prim = T_CONN_REQ;
15551 		break;
15552 	default:
15553 		panic("tcp_bind_failed: unexpected TPI type");
15554 		/*NOTREACHED*/
15555 	}
15556 
15557 	tcp->tcp_state = TCPS_IDLE;
15558 	if (tcp->tcp_ipversion == IPV4_VERSION)
15559 		tcp->tcp_ipha->ipha_src = 0;
15560 	else
15561 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15562 	/*
15563 	 * Copy of the src addr. in tcp_t is needed since
15564 	 * the lookup funcs. can only look at tcp_t
15565 	 */
15566 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15567 
15568 	tcph = tcp->tcp_tcph;
15569 	tcph->th_lport[0] = 0;
15570 	tcph->th_lport[1] = 0;
15571 	tcp_bind_hash_remove(tcp);
15572 	bzero(&connp->u_port, sizeof (connp->u_port));
15573 	/* blow away saved option results if any */
15574 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15575 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15576 
15577 	conn_delete_ire(tcp->tcp_connp, NULL);
15578 	putnext(q, mp);
15579 }
15580 
15581 /*
15582  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15583  * messages.
15584  */
15585 void
15586 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15587 {
15588 	mblk_t	*mp1;
15589 	uchar_t	*rptr = mp->b_rptr;
15590 	queue_t	*q = tcp->tcp_rq;
15591 	struct T_error_ack *tea;
15592 	uint32_t mss;
15593 	mblk_t *syn_mp;
15594 	mblk_t *mdti;
15595 	mblk_t *lsoi;
15596 	int	retval;
15597 	mblk_t *ire_mp;
15598 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15599 
15600 	switch (mp->b_datap->db_type) {
15601 	case M_PROTO:
15602 	case M_PCPROTO:
15603 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15604 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15605 			break;
15606 		tea = (struct T_error_ack *)rptr;
15607 		switch (tea->PRIM_type) {
15608 		case T_BIND_ACK:
15609 			/*
15610 			 * Adapt Multidata information, if any.  The
15611 			 * following tcp_mdt_update routine will free
15612 			 * the message.
15613 			 */
15614 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15615 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15616 				    b_rptr)->mdt_capab, B_TRUE);
15617 				freemsg(mdti);
15618 			}
15619 
15620 			/*
15621 			 * Check to update LSO information with tcp, and
15622 			 * tcp_lso_update routine will free the message.
15623 			 */
15624 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15625 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15626 				    b_rptr)->lso_capab);
15627 				freemsg(lsoi);
15628 			}
15629 
15630 			/* Get the IRE, if we had requested for it */
15631 			ire_mp = tcp_ire_mp(mp);
15632 
15633 			if (tcp->tcp_hard_binding) {
15634 				tcp->tcp_hard_binding = B_FALSE;
15635 				tcp->tcp_hard_bound = B_TRUE;
15636 				CL_INET_CONNECT(tcp);
15637 			} else {
15638 				if (ire_mp != NULL)
15639 					freeb(ire_mp);
15640 				goto after_syn_sent;
15641 			}
15642 
15643 			retval = tcp_adapt_ire(tcp, ire_mp);
15644 			if (ire_mp != NULL)
15645 				freeb(ire_mp);
15646 			if (retval == 0) {
15647 				tcp_bind_failed(tcp, mp,
15648 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15649 				    ENETUNREACH : EADDRNOTAVAIL));
15650 				return;
15651 			}
15652 			/*
15653 			 * Don't let an endpoint connect to itself.
15654 			 * Also checked in tcp_connect() but that
15655 			 * check can't handle the case when the
15656 			 * local IP address is INADDR_ANY.
15657 			 */
15658 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15659 				if ((tcp->tcp_ipha->ipha_dst ==
15660 				    tcp->tcp_ipha->ipha_src) &&
15661 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15662 				    tcp->tcp_tcph->th_fport))) {
15663 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15664 					return;
15665 				}
15666 			} else {
15667 				if (IN6_ARE_ADDR_EQUAL(
15668 				    &tcp->tcp_ip6h->ip6_dst,
15669 				    &tcp->tcp_ip6h->ip6_src) &&
15670 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15671 				    tcp->tcp_tcph->th_fport))) {
15672 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15673 					return;
15674 				}
15675 			}
15676 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15677 			/*
15678 			 * This should not be possible!  Just for
15679 			 * defensive coding...
15680 			 */
15681 			if (tcp->tcp_state != TCPS_SYN_SENT)
15682 				goto after_syn_sent;
15683 
15684 			if (is_system_labeled() &&
15685 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15686 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15687 				return;
15688 			}
15689 
15690 			ASSERT(q == tcp->tcp_rq);
15691 			/*
15692 			 * tcp_adapt_ire() does not adjust
15693 			 * for TCP/IP header length.
15694 			 */
15695 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15696 
15697 			/*
15698 			 * Just make sure our rwnd is at
15699 			 * least tcp_recv_hiwat_mss * MSS
15700 			 * large, and round up to the nearest
15701 			 * MSS.
15702 			 *
15703 			 * We do the round up here because
15704 			 * we need to get the interface
15705 			 * MTU first before we can do the
15706 			 * round up.
15707 			 */
15708 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15709 			    tcps->tcps_recv_hiwat_minmss * mss);
15710 			q->q_hiwat = tcp->tcp_rwnd;
15711 			tcp_set_ws_value(tcp);
15712 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15713 			    tcp->tcp_tcph->th_win);
15714 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
15715 				tcp->tcp_snd_ws_ok = B_TRUE;
15716 
15717 			/*
15718 			 * Set tcp_snd_ts_ok to true
15719 			 * so that tcp_xmit_mp will
15720 			 * include the timestamp
15721 			 * option in the SYN segment.
15722 			 */
15723 			if (tcps->tcps_tstamp_always ||
15724 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
15725 				tcp->tcp_snd_ts_ok = B_TRUE;
15726 			}
15727 
15728 			/*
15729 			 * tcp_snd_sack_ok can be set in
15730 			 * tcp_adapt_ire() if the sack metric
15731 			 * is set.  So check it here also.
15732 			 */
15733 			if (tcps->tcps_sack_permitted == 2 ||
15734 			    tcp->tcp_snd_sack_ok) {
15735 				if (tcp->tcp_sack_info == NULL) {
15736 					tcp->tcp_sack_info =
15737 					kmem_cache_alloc(tcp_sack_info_cache,
15738 					    KM_SLEEP);
15739 				}
15740 				tcp->tcp_snd_sack_ok = B_TRUE;
15741 			}
15742 
15743 			/*
15744 			 * Should we use ECN?  Note that the current
15745 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15746 			 * is 1.  The reason for doing this is that there
15747 			 * are equipments out there that will drop ECN
15748 			 * enabled IP packets.  Setting it to 1 avoids
15749 			 * compatibility problems.
15750 			 */
15751 			if (tcps->tcps_ecn_permitted == 2)
15752 				tcp->tcp_ecn_ok = B_TRUE;
15753 
15754 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15755 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15756 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15757 			if (syn_mp) {
15758 				cred_t *cr;
15759 				pid_t pid;
15760 
15761 				/*
15762 				 * Obtain the credential from the
15763 				 * thread calling connect(); the credential
15764 				 * lives on in the second mblk which
15765 				 * originated from T_CONN_REQ and is echoed
15766 				 * with the T_BIND_ACK from ip.  If none
15767 				 * can be found, default to the creator
15768 				 * of the socket.
15769 				 */
15770 				if (mp->b_cont == NULL ||
15771 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15772 					cr = tcp->tcp_cred;
15773 					pid = tcp->tcp_cpid;
15774 				} else {
15775 					pid = DB_CPID(mp->b_cont);
15776 				}
15777 
15778 				TCP_RECORD_TRACE(tcp, syn_mp,
15779 				    TCP_TRACE_SEND_PKT);
15780 				mblk_setcred(syn_mp, cr);
15781 				DB_CPID(syn_mp) = pid;
15782 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15783 			}
15784 		after_syn_sent:
15785 			/*
15786 			 * A trailer mblk indicates a waiting client upstream.
15787 			 * We complete here the processing begun in
15788 			 * either tcp_bind() or tcp_connect() by passing
15789 			 * upstream the reply message they supplied.
15790 			 */
15791 			mp1 = mp;
15792 			mp = mp->b_cont;
15793 			freeb(mp1);
15794 			if (mp)
15795 				break;
15796 			return;
15797 		case T_ERROR_ACK:
15798 			if (tcp->tcp_debug) {
15799 				(void) strlog(TCP_MOD_ID, 0, 1,
15800 				    SL_TRACE|SL_ERROR,
15801 				    "tcp_rput_other: case T_ERROR_ACK, "
15802 				    "ERROR_prim == %d",
15803 				    tea->ERROR_prim);
15804 			}
15805 			switch (tea->ERROR_prim) {
15806 			case O_T_BIND_REQ:
15807 			case T_BIND_REQ:
15808 				tcp_bind_failed(tcp, mp,
15809 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15810 				    ENETUNREACH : EADDRNOTAVAIL));
15811 				return;
15812 			case T_UNBIND_REQ:
15813 				tcp->tcp_hard_binding = B_FALSE;
15814 				tcp->tcp_hard_bound = B_FALSE;
15815 				if (mp->b_cont) {
15816 					freemsg(mp->b_cont);
15817 					mp->b_cont = NULL;
15818 				}
15819 				if (tcp->tcp_unbind_pending)
15820 					tcp->tcp_unbind_pending = 0;
15821 				else {
15822 					/* From tcp_ip_unbind() - free */
15823 					freemsg(mp);
15824 					return;
15825 				}
15826 				break;
15827 			case T_SVR4_OPTMGMT_REQ:
15828 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15829 					/* T_OPTMGMT_REQ generated by TCP */
15830 					printf("T_SVR4_OPTMGMT_REQ failed "
15831 					    "%d/%d - dropped (cnt %d)\n",
15832 					    tea->TLI_error, tea->UNIX_error,
15833 					    tcp->tcp_drop_opt_ack_cnt);
15834 					freemsg(mp);
15835 					tcp->tcp_drop_opt_ack_cnt--;
15836 					return;
15837 				}
15838 				break;
15839 			}
15840 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15841 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15842 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15843 				    "- dropped (cnt %d)\n",
15844 				    tea->TLI_error, tea->UNIX_error,
15845 				    tcp->tcp_drop_opt_ack_cnt);
15846 				freemsg(mp);
15847 				tcp->tcp_drop_opt_ack_cnt--;
15848 				return;
15849 			}
15850 			break;
15851 		case T_OPTMGMT_ACK:
15852 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15853 				/* T_OPTMGMT_REQ generated by TCP */
15854 				freemsg(mp);
15855 				tcp->tcp_drop_opt_ack_cnt--;
15856 				return;
15857 			}
15858 			break;
15859 		default:
15860 			break;
15861 		}
15862 		break;
15863 	case M_FLUSH:
15864 		if (*rptr & FLUSHR)
15865 			flushq(q, FLUSHDATA);
15866 		break;
15867 	default:
15868 		/* M_CTL will be directly sent to tcp_icmp_error() */
15869 		ASSERT(DB_TYPE(mp) != M_CTL);
15870 		break;
15871 	}
15872 	/*
15873 	 * Make sure we set this bit before sending the ACK for
15874 	 * bind. Otherwise accept could possibly run and free
15875 	 * this tcp struct.
15876 	 */
15877 	putnext(q, mp);
15878 }
15879 
15880 /*
15881  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15882  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15883  * tcp_rsrv() try again.
15884  */
15885 static void
15886 tcp_ordrel_kick(void *arg)
15887 {
15888 	conn_t 	*connp = (conn_t *)arg;
15889 	tcp_t	*tcp = connp->conn_tcp;
15890 
15891 	tcp->tcp_ordrelid = 0;
15892 	tcp->tcp_timeout = B_FALSE;
15893 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15894 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15895 		qenable(tcp->tcp_rq);
15896 	}
15897 }
15898 
15899 /* ARGSUSED */
15900 static void
15901 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15902 {
15903 	conn_t	*connp = (conn_t *)arg;
15904 	tcp_t	*tcp = connp->conn_tcp;
15905 	queue_t	*q = tcp->tcp_rq;
15906 	uint_t	thwin;
15907 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15908 
15909 	freeb(mp);
15910 
15911 	TCP_STAT(tcps, tcp_rsrv_calls);
15912 
15913 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15914 		return;
15915 	}
15916 
15917 	if (tcp->tcp_fused) {
15918 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15919 
15920 		ASSERT(tcp->tcp_fused);
15921 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15922 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15923 		ASSERT(!TCP_IS_DETACHED(tcp));
15924 		ASSERT(tcp->tcp_connp->conn_sqp ==
15925 		    peer_tcp->tcp_connp->conn_sqp);
15926 
15927 		/*
15928 		 * Normally we would not get backenabled in synchronous
15929 		 * streams mode, but in case this happens, we need to plug
15930 		 * synchronous streams during our drain to prevent a race
15931 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15932 		 */
15933 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15934 		if (tcp->tcp_rcv_list != NULL)
15935 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15936 
15937 		if (peer_tcp > tcp) {
15938 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15939 			mutex_enter(&tcp->tcp_non_sq_lock);
15940 		} else {
15941 			mutex_enter(&tcp->tcp_non_sq_lock);
15942 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15943 		}
15944 
15945 		if (peer_tcp->tcp_flow_stopped &&
15946 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15947 		    peer_tcp->tcp_xmit_lowater)) {
15948 			tcp_clrqfull(peer_tcp);
15949 		}
15950 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15951 		mutex_exit(&tcp->tcp_non_sq_lock);
15952 
15953 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15954 		TCP_STAT(tcps, tcp_fusion_backenabled);
15955 		return;
15956 	}
15957 
15958 	if (canputnext(q)) {
15959 		tcp->tcp_rwnd = q->q_hiwat;
15960 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15961 		    << tcp->tcp_rcv_ws;
15962 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15963 		/*
15964 		 * Send back a window update immediately if TCP is above
15965 		 * ESTABLISHED state and the increase of the rcv window
15966 		 * that the other side knows is at least 1 MSS after flow
15967 		 * control is lifted.
15968 		 */
15969 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15970 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15971 			tcp_xmit_ctl(NULL, tcp,
15972 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15973 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15974 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15975 		}
15976 	}
15977 	/* Handle a failure to allocate a T_ORDREL_IND here */
15978 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15979 		ASSERT(tcp->tcp_listener == NULL);
15980 		if (tcp->tcp_rcv_list != NULL) {
15981 			(void) tcp_rcv_drain(q, tcp);
15982 		}
15983 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15984 		mp = mi_tpi_ordrel_ind();
15985 		if (mp) {
15986 			tcp->tcp_ordrel_done = B_TRUE;
15987 			putnext(q, mp);
15988 			if (tcp->tcp_deferred_clean_death) {
15989 				/*
15990 				 * tcp_clean_death was deferred for
15991 				 * T_ORDREL_IND - do it now
15992 				 */
15993 				tcp->tcp_deferred_clean_death = B_FALSE;
15994 				(void) tcp_clean_death(tcp,
15995 				    tcp->tcp_client_errno, 22);
15996 			}
15997 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15998 			/*
15999 			 * If there isn't already a timer running
16000 			 * start one.  Use a 4 second
16001 			 * timer as a fallback since it can't fail.
16002 			 */
16003 			tcp->tcp_timeout = B_TRUE;
16004 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16005 			    MSEC_TO_TICK(4000));
16006 		}
16007 	}
16008 }
16009 
16010 /*
16011  * The read side service routine is called mostly when we get back-enabled as a
16012  * result of flow control relief.  Since we don't actually queue anything in
16013  * TCP, we have no data to send out of here.  What we do is clear the receive
16014  * window, and send out a window update.
16015  * This routine is also called to drive an orderly release message upstream
16016  * if the attempt in tcp_rput failed.
16017  */
16018 static void
16019 tcp_rsrv(queue_t *q)
16020 {
16021 	conn_t *connp = Q_TO_CONN(q);
16022 	tcp_t	*tcp = connp->conn_tcp;
16023 	mblk_t	*mp;
16024 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16025 
16026 	/* No code does a putq on the read side */
16027 	ASSERT(q->q_first == NULL);
16028 
16029 	/* Nothing to do for the default queue */
16030 	if (q == tcps->tcps_g_q) {
16031 		return;
16032 	}
16033 
16034 	mp = allocb(0, BPRI_HI);
16035 	if (mp == NULL) {
16036 		/*
16037 		 * We are under memory pressure. Return for now and we
16038 		 * we will be called again later.
16039 		 */
16040 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16041 			/*
16042 			 * If there isn't already a timer running
16043 			 * start one.  Use a 4 second
16044 			 * timer as a fallback since it can't fail.
16045 			 */
16046 			tcp->tcp_timeout = B_TRUE;
16047 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16048 			    MSEC_TO_TICK(4000));
16049 		}
16050 		return;
16051 	}
16052 	CONN_INC_REF(connp);
16053 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16054 	    SQTAG_TCP_RSRV);
16055 }
16056 
16057 /*
16058  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16059  * We do not allow the receive window to shrink.  After setting rwnd,
16060  * set the flow control hiwat of the stream.
16061  *
16062  * This function is called in 2 cases:
16063  *
16064  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16065  *    connection (passive open) and in tcp_rput_data() for active connect.
16066  *    This is called after tcp_mss_set() when the desired MSS value is known.
16067  *    This makes sure that our window size is a mutiple of the other side's
16068  *    MSS.
16069  * 2) Handling SO_RCVBUF option.
16070  *
16071  * It is ASSUMED that the requested size is a multiple of the current MSS.
16072  *
16073  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16074  * user requests so.
16075  */
16076 static int
16077 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16078 {
16079 	uint32_t	mss = tcp->tcp_mss;
16080 	uint32_t	old_max_rwnd;
16081 	uint32_t	max_transmittable_rwnd;
16082 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16083 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16084 
16085 	if (tcp->tcp_fused) {
16086 		size_t sth_hiwat;
16087 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16088 
16089 		ASSERT(peer_tcp != NULL);
16090 		/*
16091 		 * Record the stream head's high water mark for
16092 		 * this endpoint; this is used for flow-control
16093 		 * purposes in tcp_fuse_output().
16094 		 */
16095 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16096 		if (!tcp_detached)
16097 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16098 
16099 		/*
16100 		 * In the fusion case, the maxpsz stream head value of
16101 		 * our peer is set according to its send buffer size
16102 		 * and our receive buffer size; since the latter may
16103 		 * have changed we need to update the peer's maxpsz.
16104 		 */
16105 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16106 		return (rwnd);
16107 	}
16108 
16109 	if (tcp_detached)
16110 		old_max_rwnd = tcp->tcp_rwnd;
16111 	else
16112 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16113 
16114 	/*
16115 	 * Insist on a receive window that is at least
16116 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16117 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16118 	 * and delayed acknowledgement.
16119 	 */
16120 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16121 
16122 	/*
16123 	 * If window size info has already been exchanged, TCP should not
16124 	 * shrink the window.  Shrinking window is doable if done carefully.
16125 	 * We may add that support later.  But so far there is not a real
16126 	 * need to do that.
16127 	 */
16128 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16129 		/* MSS may have changed, do a round up again. */
16130 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16131 	}
16132 
16133 	/*
16134 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16135 	 * can be applied even before the window scale option is decided.
16136 	 */
16137 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16138 	if (rwnd > max_transmittable_rwnd) {
16139 		rwnd = max_transmittable_rwnd -
16140 		    (max_transmittable_rwnd % mss);
16141 		if (rwnd < mss)
16142 			rwnd = max_transmittable_rwnd;
16143 		/*
16144 		 * If we're over the limit we may have to back down tcp_rwnd.
16145 		 * The increment below won't work for us. So we set all three
16146 		 * here and the increment below will have no effect.
16147 		 */
16148 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16149 	}
16150 	if (tcp->tcp_localnet) {
16151 		tcp->tcp_rack_abs_max =
16152 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16153 	} else {
16154 		/*
16155 		 * For a remote host on a different subnet (through a router),
16156 		 * we ack every other packet to be conforming to RFC1122.
16157 		 * tcp_deferred_acks_max is default to 2.
16158 		 */
16159 		tcp->tcp_rack_abs_max =
16160 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16161 	}
16162 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16163 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16164 	else
16165 		tcp->tcp_rack_cur_max = 0;
16166 	/*
16167 	 * Increment the current rwnd by the amount the maximum grew (we
16168 	 * can not overwrite it since we might be in the middle of a
16169 	 * connection.)
16170 	 */
16171 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16172 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16173 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16174 		tcp->tcp_cwnd_max = rwnd;
16175 
16176 	if (tcp_detached)
16177 		return (rwnd);
16178 	/*
16179 	 * We set the maximum receive window into rq->q_hiwat.
16180 	 * This is not actually used for flow control.
16181 	 */
16182 	tcp->tcp_rq->q_hiwat = rwnd;
16183 	/*
16184 	 * Set the Stream head high water mark. This doesn't have to be
16185 	 * here, since we are simply using default values, but we would
16186 	 * prefer to choose these values algorithmically, with a likely
16187 	 * relationship to rwnd.
16188 	 */
16189 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16190 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16191 	return (rwnd);
16192 }
16193 
16194 /*
16195  * Return SNMP stuff in buffer in mpdata.
16196  */
16197 int
16198 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16199 {
16200 	mblk_t			*mpdata;
16201 	mblk_t			*mp_conn_ctl = NULL;
16202 	mblk_t			*mp_conn_tail;
16203 	mblk_t			*mp_attr_ctl = NULL;
16204 	mblk_t			*mp_attr_tail;
16205 	mblk_t			*mp6_conn_ctl = NULL;
16206 	mblk_t			*mp6_conn_tail;
16207 	mblk_t			*mp6_attr_ctl = NULL;
16208 	mblk_t			*mp6_attr_tail;
16209 	struct opthdr		*optp;
16210 	mib2_tcpConnEntry_t	tce;
16211 	mib2_tcp6ConnEntry_t	tce6;
16212 	mib2_transportMLPEntry_t mlp;
16213 	connf_t			*connfp;
16214 	conn_t			*connp;
16215 	int			i;
16216 	boolean_t 		ispriv;
16217 	zoneid_t 		zoneid;
16218 	int			v4_conn_idx;
16219 	int			v6_conn_idx;
16220 	tcp_stack_t		*tcps = Q_TO_TCP(q)->tcp_tcps;
16221 	ip_stack_t	*ipst;
16222 
16223 	if (mpctl == NULL ||
16224 	    (mpdata = mpctl->b_cont) == NULL ||
16225 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16226 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16227 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16228 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16229 		freemsg(mp_conn_ctl);
16230 		freemsg(mp_attr_ctl);
16231 		freemsg(mp6_conn_ctl);
16232 		freemsg(mp6_attr_ctl);
16233 		return (0);
16234 	}
16235 
16236 	/* build table of connections -- need count in fixed part */
16237 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16238 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16239 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16240 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16241 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16242 
16243 	ispriv =
16244 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16245 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16246 
16247 	v4_conn_idx = v6_conn_idx = 0;
16248 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16249 
16250 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16251 		ipst = tcps->tcps_netstack->netstack_ip;
16252 
16253 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16254 
16255 		connp = NULL;
16256 
16257 		while ((connp =
16258 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16259 			tcp_t *tcp;
16260 			boolean_t needattr;
16261 
16262 			if (connp->conn_zoneid != zoneid)
16263 				continue;	/* not in this zone */
16264 
16265 			tcp = connp->conn_tcp;
16266 			UPDATE_MIB(&tcps->tcps_mib,
16267 			    tcpHCInSegs, tcp->tcp_ibsegs);
16268 			tcp->tcp_ibsegs = 0;
16269 			UPDATE_MIB(&tcps->tcps_mib,
16270 			    tcpHCOutSegs, tcp->tcp_obsegs);
16271 			tcp->tcp_obsegs = 0;
16272 
16273 			tce6.tcp6ConnState = tce.tcpConnState =
16274 			    tcp_snmp_state(tcp);
16275 			if (tce.tcpConnState == MIB2_TCP_established ||
16276 			    tce.tcpConnState == MIB2_TCP_closeWait)
16277 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16278 
16279 			needattr = B_FALSE;
16280 			bzero(&mlp, sizeof (mlp));
16281 			if (connp->conn_mlp_type != mlptSingle) {
16282 				if (connp->conn_mlp_type == mlptShared ||
16283 				    connp->conn_mlp_type == mlptBoth)
16284 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16285 				if (connp->conn_mlp_type == mlptPrivate ||
16286 				    connp->conn_mlp_type == mlptBoth)
16287 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16288 				needattr = B_TRUE;
16289 			}
16290 			if (connp->conn_peercred != NULL) {
16291 				ts_label_t *tsl;
16292 
16293 				tsl = crgetlabel(connp->conn_peercred);
16294 				mlp.tme_doi = label2doi(tsl);
16295 				mlp.tme_label = *label2bslabel(tsl);
16296 				needattr = B_TRUE;
16297 			}
16298 
16299 			/* Create a message to report on IPv6 entries */
16300 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16301 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16302 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16303 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16304 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16305 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16306 			/* Don't want just anybody seeing these... */
16307 			if (ispriv) {
16308 				tce6.tcp6ConnEntryInfo.ce_snxt =
16309 				    tcp->tcp_snxt;
16310 				tce6.tcp6ConnEntryInfo.ce_suna =
16311 				    tcp->tcp_suna;
16312 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16313 				    tcp->tcp_rnxt;
16314 				tce6.tcp6ConnEntryInfo.ce_rack =
16315 				    tcp->tcp_rack;
16316 			} else {
16317 				/*
16318 				 * Netstat, unfortunately, uses this to
16319 				 * get send/receive queue sizes.  How to fix?
16320 				 * Why not compute the difference only?
16321 				 */
16322 				tce6.tcp6ConnEntryInfo.ce_snxt =
16323 				    tcp->tcp_snxt - tcp->tcp_suna;
16324 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16325 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16326 				    tcp->tcp_rnxt - tcp->tcp_rack;
16327 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16328 			}
16329 
16330 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16331 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16332 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16333 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16334 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16335 
16336 			tce6.tcp6ConnCreationProcess =
16337 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16338 			    tcp->tcp_cpid;
16339 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16340 
16341 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16342 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16343 
16344 			mlp.tme_connidx = v6_conn_idx++;
16345 			if (needattr)
16346 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16347 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16348 			}
16349 			/*
16350 			 * Create an IPv4 table entry for IPv4 entries and also
16351 			 * for IPv6 entries which are bound to in6addr_any
16352 			 * but don't have IPV6_V6ONLY set.
16353 			 * (i.e. anything an IPv4 peer could connect to)
16354 			 */
16355 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16356 			    (tcp->tcp_state <= TCPS_LISTEN &&
16357 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16358 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16359 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16360 					tce.tcpConnRemAddress = INADDR_ANY;
16361 					tce.tcpConnLocalAddress = INADDR_ANY;
16362 				} else {
16363 					tce.tcpConnRemAddress =
16364 					    tcp->tcp_remote;
16365 					tce.tcpConnLocalAddress =
16366 					    tcp->tcp_ip_src;
16367 				}
16368 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16369 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16370 				/* Don't want just anybody seeing these... */
16371 				if (ispriv) {
16372 					tce.tcpConnEntryInfo.ce_snxt =
16373 					    tcp->tcp_snxt;
16374 					tce.tcpConnEntryInfo.ce_suna =
16375 					    tcp->tcp_suna;
16376 					tce.tcpConnEntryInfo.ce_rnxt =
16377 					    tcp->tcp_rnxt;
16378 					tce.tcpConnEntryInfo.ce_rack =
16379 					    tcp->tcp_rack;
16380 				} else {
16381 					/*
16382 					 * Netstat, unfortunately, uses this to
16383 					 * get send/receive queue sizes.  How
16384 					 * to fix?
16385 					 * Why not compute the difference only?
16386 					 */
16387 					tce.tcpConnEntryInfo.ce_snxt =
16388 					    tcp->tcp_snxt - tcp->tcp_suna;
16389 					tce.tcpConnEntryInfo.ce_suna = 0;
16390 					tce.tcpConnEntryInfo.ce_rnxt =
16391 					    tcp->tcp_rnxt - tcp->tcp_rack;
16392 					tce.tcpConnEntryInfo.ce_rack = 0;
16393 				}
16394 
16395 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16396 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16397 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16398 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16399 				tce.tcpConnEntryInfo.ce_state =
16400 				    tcp->tcp_state;
16401 
16402 				tce.tcpConnCreationProcess =
16403 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16404 				    tcp->tcp_cpid;
16405 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16406 
16407 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16408 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16409 
16410 				mlp.tme_connidx = v4_conn_idx++;
16411 				if (needattr)
16412 					(void) snmp_append_data2(
16413 					    mp_attr_ctl->b_cont,
16414 					    &mp_attr_tail, (char *)&mlp,
16415 					    sizeof (mlp));
16416 			}
16417 		}
16418 	}
16419 
16420 	/* fixed length structure for IPv4 and IPv6 counters */
16421 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16422 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16423 	    sizeof (mib2_tcp6ConnEntry_t));
16424 	/* synchronize 32- and 64-bit counters */
16425 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16426 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16427 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16428 	optp->level = MIB2_TCP;
16429 	optp->name = 0;
16430 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16431 	    sizeof (tcps->tcps_mib));
16432 	optp->len = msgdsize(mpdata);
16433 	qreply(q, mpctl);
16434 
16435 	/* table of connections... */
16436 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16437 	    sizeof (struct T_optmgmt_ack)];
16438 	optp->level = MIB2_TCP;
16439 	optp->name = MIB2_TCP_CONN;
16440 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16441 	qreply(q, mp_conn_ctl);
16442 
16443 	/* table of MLP attributes... */
16444 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16445 	    sizeof (struct T_optmgmt_ack)];
16446 	optp->level = MIB2_TCP;
16447 	optp->name = EXPER_XPORT_MLP;
16448 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16449 	if (optp->len == 0)
16450 		freemsg(mp_attr_ctl);
16451 	else
16452 		qreply(q, mp_attr_ctl);
16453 
16454 	/* table of IPv6 connections... */
16455 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16456 	    sizeof (struct T_optmgmt_ack)];
16457 	optp->level = MIB2_TCP6;
16458 	optp->name = MIB2_TCP6_CONN;
16459 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16460 	qreply(q, mp6_conn_ctl);
16461 
16462 	/* table of IPv6 MLP attributes... */
16463 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16464 	    sizeof (struct T_optmgmt_ack)];
16465 	optp->level = MIB2_TCP6;
16466 	optp->name = EXPER_XPORT_MLP;
16467 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16468 	if (optp->len == 0)
16469 		freemsg(mp6_attr_ctl);
16470 	else
16471 		qreply(q, mp6_attr_ctl);
16472 	return (1);
16473 }
16474 
16475 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16476 /* ARGSUSED */
16477 int
16478 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16479 {
16480 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16481 
16482 	switch (level) {
16483 	case MIB2_TCP:
16484 		switch (name) {
16485 		case 13:
16486 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16487 				return (0);
16488 			/* TODO: delete entry defined by tce */
16489 			return (1);
16490 		default:
16491 			return (0);
16492 		}
16493 	default:
16494 		return (1);
16495 	}
16496 }
16497 
16498 /* Translate TCP state to MIB2 TCP state. */
16499 static int
16500 tcp_snmp_state(tcp_t *tcp)
16501 {
16502 	if (tcp == NULL)
16503 		return (0);
16504 
16505 	switch (tcp->tcp_state) {
16506 	case TCPS_CLOSED:
16507 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16508 	case TCPS_BOUND:
16509 		return (MIB2_TCP_closed);
16510 	case TCPS_LISTEN:
16511 		return (MIB2_TCP_listen);
16512 	case TCPS_SYN_SENT:
16513 		return (MIB2_TCP_synSent);
16514 	case TCPS_SYN_RCVD:
16515 		return (MIB2_TCP_synReceived);
16516 	case TCPS_ESTABLISHED:
16517 		return (MIB2_TCP_established);
16518 	case TCPS_CLOSE_WAIT:
16519 		return (MIB2_TCP_closeWait);
16520 	case TCPS_FIN_WAIT_1:
16521 		return (MIB2_TCP_finWait1);
16522 	case TCPS_CLOSING:
16523 		return (MIB2_TCP_closing);
16524 	case TCPS_LAST_ACK:
16525 		return (MIB2_TCP_lastAck);
16526 	case TCPS_FIN_WAIT_2:
16527 		return (MIB2_TCP_finWait2);
16528 	case TCPS_TIME_WAIT:
16529 		return (MIB2_TCP_timeWait);
16530 	default:
16531 		return (0);
16532 	}
16533 }
16534 
16535 static char tcp_report_header[] =
16536 	"TCP     " MI_COL_HDRPAD_STR
16537 	"zone dest            snxt     suna     "
16538 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16539 	"recent   [lport,fport] state";
16540 
16541 /*
16542  * TCP status report triggered via the Named Dispatch mechanism.
16543  */
16544 /* ARGSUSED */
16545 static void
16546 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16547     cred_t *cr)
16548 {
16549 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16550 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16551 	char cflag;
16552 	in6_addr_t	v6dst;
16553 	char buf[80];
16554 	uint_t print_len, buf_len;
16555 
16556 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16557 	if (buf_len <= 0)
16558 		return;
16559 
16560 	if (hashval >= 0)
16561 		(void) sprintf(hash, "%03d ", hashval);
16562 	else
16563 		hash[0] = '\0';
16564 
16565 	/*
16566 	 * Note that we use the remote address in the tcp_b  structure.
16567 	 * This means that it will print out the real destination address,
16568 	 * not the next hop's address if source routing is used.  This
16569 	 * avoid the confusion on the output because user may not
16570 	 * know that source routing is used for a connection.
16571 	 */
16572 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16573 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16574 	} else {
16575 		v6dst = tcp->tcp_remote_v6;
16576 	}
16577 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16578 	/*
16579 	 * the ispriv checks are so that normal users cannot determine
16580 	 * sequence number information using NDD.
16581 	 */
16582 
16583 	if (TCP_IS_DETACHED(tcp))
16584 		cflag = '*';
16585 	else
16586 		cflag = ' ';
16587 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16588 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16589 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16590 	    hash,
16591 	    (void *)tcp,
16592 	    tcp->tcp_connp->conn_zoneid,
16593 	    addrbuf,
16594 	    (ispriv) ? tcp->tcp_snxt : 0,
16595 	    (ispriv) ? tcp->tcp_suna : 0,
16596 	    tcp->tcp_swnd,
16597 	    (ispriv) ? tcp->tcp_rnxt : 0,
16598 	    (ispriv) ? tcp->tcp_rack : 0,
16599 	    tcp->tcp_rwnd,
16600 	    tcp->tcp_rto,
16601 	    tcp->tcp_mss,
16602 	    tcp->tcp_snd_ws_ok,
16603 	    tcp->tcp_snd_ws,
16604 	    tcp->tcp_rcv_ws,
16605 	    tcp->tcp_snd_ts_ok,
16606 	    tcp->tcp_ts_recent,
16607 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16608 	if (print_len < buf_len) {
16609 		((mblk_t *)mp)->b_wptr += print_len;
16610 	} else {
16611 		((mblk_t *)mp)->b_wptr += buf_len;
16612 	}
16613 }
16614 
16615 /*
16616  * TCP status report (for listeners only) triggered via the Named Dispatch
16617  * mechanism.
16618  */
16619 /* ARGSUSED */
16620 static void
16621 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16622 {
16623 	char addrbuf[INET6_ADDRSTRLEN];
16624 	in6_addr_t	v6dst;
16625 	uint_t print_len, buf_len;
16626 
16627 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16628 	if (buf_len <= 0)
16629 		return;
16630 
16631 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16632 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16633 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16634 	} else {
16635 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16636 		    addrbuf, sizeof (addrbuf));
16637 	}
16638 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16639 	    "%03d "
16640 	    MI_COL_PTRFMT_STR
16641 	    "%d %s %05u %08u %d/%d/%d%c\n",
16642 	    hashval, (void *)tcp,
16643 	    tcp->tcp_connp->conn_zoneid,
16644 	    addrbuf,
16645 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16646 	    tcp->tcp_conn_req_seqnum,
16647 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16648 	    tcp->tcp_conn_req_max,
16649 	    tcp->tcp_syn_defense ? '*' : ' ');
16650 	if (print_len < buf_len) {
16651 		((mblk_t *)mp)->b_wptr += print_len;
16652 	} else {
16653 		((mblk_t *)mp)->b_wptr += buf_len;
16654 	}
16655 }
16656 
16657 /* TCP status report triggered via the Named Dispatch mechanism. */
16658 /* ARGSUSED */
16659 static int
16660 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16661 {
16662 	tcp_t	*tcp;
16663 	int	i;
16664 	conn_t	*connp;
16665 	connf_t	*connfp;
16666 	zoneid_t zoneid;
16667 	tcp_stack_t *tcps;
16668 	ip_stack_t *ipst;
16669 
16670 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16671 	tcps = Q_TO_TCP(q)->tcp_tcps;
16672 
16673 	/*
16674 	 * Because of the ndd constraint, at most we can have 64K buffer
16675 	 * to put in all TCP info.  So to be more efficient, just
16676 	 * allocate a 64K buffer here, assuming we need that large buffer.
16677 	 * This may be a problem as any user can read tcp_status.  Therefore
16678 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16679 	 * This should be OK as normal users should not do this too often.
16680 	 */
16681 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16682 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16683 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16684 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16685 			return (0);
16686 		}
16687 	}
16688 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16689 		/* The following may work even if we cannot get a large buf. */
16690 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16691 		return (0);
16692 	}
16693 
16694 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16695 
16696 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16697 
16698 		ipst = tcps->tcps_netstack->netstack_ip;
16699 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16700 
16701 		connp = NULL;
16702 
16703 		while ((connp =
16704 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16705 			tcp = connp->conn_tcp;
16706 			if (zoneid != GLOBAL_ZONEID &&
16707 			    zoneid != connp->conn_zoneid)
16708 				continue;
16709 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16710 			    cr);
16711 		}
16712 
16713 	}
16714 
16715 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16716 	return (0);
16717 }
16718 
16719 /* TCP status report triggered via the Named Dispatch mechanism. */
16720 /* ARGSUSED */
16721 static int
16722 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16723 {
16724 	tf_t	*tbf;
16725 	tcp_t	*tcp;
16726 	int	i;
16727 	zoneid_t zoneid;
16728 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16729 
16730 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16731 
16732 	/* Refer to comments in tcp_status_report(). */
16733 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16734 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16735 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16736 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16737 			return (0);
16738 		}
16739 	}
16740 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16741 		/* The following may work even if we cannot get a large buf. */
16742 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16743 		return (0);
16744 	}
16745 
16746 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16747 
16748 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16749 		tbf = &tcps->tcps_bind_fanout[i];
16750 		mutex_enter(&tbf->tf_lock);
16751 		for (tcp = tbf->tf_tcp; tcp != NULL;
16752 		    tcp = tcp->tcp_bind_hash) {
16753 			if (zoneid != GLOBAL_ZONEID &&
16754 			    zoneid != tcp->tcp_connp->conn_zoneid)
16755 				continue;
16756 			CONN_INC_REF(tcp->tcp_connp);
16757 			tcp_report_item(mp->b_cont, tcp, i,
16758 			    Q_TO_TCP(q), cr);
16759 			CONN_DEC_REF(tcp->tcp_connp);
16760 		}
16761 		mutex_exit(&tbf->tf_lock);
16762 	}
16763 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16764 	return (0);
16765 }
16766 
16767 /* TCP status report triggered via the Named Dispatch mechanism. */
16768 /* ARGSUSED */
16769 static int
16770 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16771 {
16772 	connf_t	*connfp;
16773 	conn_t	*connp;
16774 	tcp_t	*tcp;
16775 	int	i;
16776 	zoneid_t zoneid;
16777 	tcp_stack_t *tcps;
16778 	ip_stack_t	*ipst;
16779 
16780 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16781 	tcps = Q_TO_TCP(q)->tcp_tcps;
16782 
16783 	/* Refer to comments in tcp_status_report(). */
16784 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16785 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16786 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16787 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16788 			return (0);
16789 		}
16790 	}
16791 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16792 		/* The following may work even if we cannot get a large buf. */
16793 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16794 		return (0);
16795 	}
16796 
16797 	(void) mi_mpprintf(mp,
16798 	    "    TCP    " MI_COL_HDRPAD_STR
16799 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16800 
16801 	ipst = tcps->tcps_netstack->netstack_ip;
16802 
16803 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16804 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16805 		connp = NULL;
16806 		while ((connp =
16807 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16808 			tcp = connp->conn_tcp;
16809 			if (zoneid != GLOBAL_ZONEID &&
16810 			    zoneid != connp->conn_zoneid)
16811 				continue;
16812 			tcp_report_listener(mp->b_cont, tcp, i);
16813 		}
16814 	}
16815 
16816 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16817 	return (0);
16818 }
16819 
16820 /* TCP status report triggered via the Named Dispatch mechanism. */
16821 /* ARGSUSED */
16822 static int
16823 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16824 {
16825 	connf_t	*connfp;
16826 	conn_t	*connp;
16827 	tcp_t	*tcp;
16828 	int	i;
16829 	zoneid_t zoneid;
16830 	tcp_stack_t *tcps;
16831 	ip_stack_t *ipst;
16832 
16833 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16834 	tcps = Q_TO_TCP(q)->tcp_tcps;
16835 	ipst = tcps->tcps_netstack->netstack_ip;
16836 
16837 	/* Refer to comments in tcp_status_report(). */
16838 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16839 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16840 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16841 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16842 			return (0);
16843 		}
16844 	}
16845 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16846 		/* The following may work even if we cannot get a large buf. */
16847 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16848 		return (0);
16849 	}
16850 
16851 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16852 	    ipst->ips_ipcl_conn_fanout_size);
16853 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16854 
16855 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16856 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16857 		connp = NULL;
16858 		while ((connp =
16859 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16860 			tcp = connp->conn_tcp;
16861 			if (zoneid != GLOBAL_ZONEID &&
16862 			    zoneid != connp->conn_zoneid)
16863 				continue;
16864 			tcp_report_item(mp->b_cont, tcp, i,
16865 			    Q_TO_TCP(q), cr);
16866 		}
16867 	}
16868 
16869 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16870 	return (0);
16871 }
16872 
16873 /* TCP status report triggered via the Named Dispatch mechanism. */
16874 /* ARGSUSED */
16875 static int
16876 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16877 {
16878 	tf_t	*tf;
16879 	tcp_t	*tcp;
16880 	int	i;
16881 	zoneid_t zoneid;
16882 	tcp_stack_t	*tcps;
16883 
16884 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16885 	tcps = Q_TO_TCP(q)->tcp_tcps;
16886 
16887 	/* Refer to comments in tcp_status_report(). */
16888 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16889 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16890 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16891 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16892 			return (0);
16893 		}
16894 	}
16895 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16896 		/* The following may work even if we cannot get a large buf. */
16897 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16898 		return (0);
16899 	}
16900 
16901 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16902 
16903 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16904 		tf = &tcps->tcps_acceptor_fanout[i];
16905 		mutex_enter(&tf->tf_lock);
16906 		for (tcp = tf->tf_tcp; tcp != NULL;
16907 		    tcp = tcp->tcp_acceptor_hash) {
16908 			if (zoneid != GLOBAL_ZONEID &&
16909 			    zoneid != tcp->tcp_connp->conn_zoneid)
16910 				continue;
16911 			tcp_report_item(mp->b_cont, tcp, i,
16912 			    Q_TO_TCP(q), cr);
16913 		}
16914 		mutex_exit(&tf->tf_lock);
16915 	}
16916 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16917 	return (0);
16918 }
16919 
16920 /*
16921  * tcp_timer is the timer service routine.  It handles the retransmission,
16922  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16923  * from the state of the tcp instance what kind of action needs to be done
16924  * at the time it is called.
16925  */
16926 static void
16927 tcp_timer(void *arg)
16928 {
16929 	mblk_t		*mp;
16930 	clock_t		first_threshold;
16931 	clock_t		second_threshold;
16932 	clock_t		ms;
16933 	uint32_t	mss;
16934 	conn_t		*connp = (conn_t *)arg;
16935 	tcp_t		*tcp = connp->conn_tcp;
16936 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16937 
16938 	tcp->tcp_timer_tid = 0;
16939 
16940 	if (tcp->tcp_fused)
16941 		return;
16942 
16943 	first_threshold =  tcp->tcp_first_timer_threshold;
16944 	second_threshold = tcp->tcp_second_timer_threshold;
16945 	switch (tcp->tcp_state) {
16946 	case TCPS_IDLE:
16947 	case TCPS_BOUND:
16948 	case TCPS_LISTEN:
16949 		return;
16950 	case TCPS_SYN_RCVD: {
16951 		tcp_t	*listener = tcp->tcp_listener;
16952 
16953 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16954 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16955 			/* it's our first timeout */
16956 			tcp->tcp_syn_rcvd_timeout = 1;
16957 			mutex_enter(&listener->tcp_eager_lock);
16958 			listener->tcp_syn_rcvd_timeout++;
16959 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16960 				/*
16961 				 * Make this eager available for drop if we
16962 				 * need to drop one to accomodate a new
16963 				 * incoming SYN request.
16964 				 */
16965 				MAKE_DROPPABLE(listener, tcp);
16966 			}
16967 			if (!listener->tcp_syn_defense &&
16968 			    (listener->tcp_syn_rcvd_timeout >
16969 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16970 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16971 				/* We may be under attack. Put on a defense. */
16972 				listener->tcp_syn_defense = B_TRUE;
16973 				cmn_err(CE_WARN, "High TCP connect timeout "
16974 				    "rate! System (port %d) may be under a "
16975 				    "SYN flood attack!",
16976 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16977 
16978 				listener->tcp_ip_addr_cache = kmem_zalloc(
16979 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16980 				    KM_NOSLEEP);
16981 			}
16982 			mutex_exit(&listener->tcp_eager_lock);
16983 		} else if (listener != NULL) {
16984 			mutex_enter(&listener->tcp_eager_lock);
16985 			tcp->tcp_syn_rcvd_timeout++;
16986 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
16987 			    !tcp->tcp_closemp_used) {
16988 				/*
16989 				 * This is our second timeout. Put the tcp in
16990 				 * the list of droppable eagers to allow it to
16991 				 * be dropped, if needed. We don't check
16992 				 * whether tcp_dontdrop is set or not to
16993 				 * protect ourselve from a SYN attack where a
16994 				 * remote host can spoof itself as one of the
16995 				 * good IP source and continue to hold
16996 				 * resources too long.
16997 				 */
16998 				MAKE_DROPPABLE(listener, tcp);
16999 			}
17000 			mutex_exit(&listener->tcp_eager_lock);
17001 		}
17002 	}
17003 		/* FALLTHRU */
17004 	case TCPS_SYN_SENT:
17005 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17006 		second_threshold = tcp->tcp_second_ctimer_threshold;
17007 		break;
17008 	case TCPS_ESTABLISHED:
17009 	case TCPS_FIN_WAIT_1:
17010 	case TCPS_CLOSING:
17011 	case TCPS_CLOSE_WAIT:
17012 	case TCPS_LAST_ACK:
17013 		/* If we have data to rexmit */
17014 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17015 			clock_t	time_to_wait;
17016 
17017 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17018 			if (!tcp->tcp_xmit_head)
17019 				break;
17020 			time_to_wait = lbolt -
17021 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17022 			time_to_wait = tcp->tcp_rto -
17023 			    TICK_TO_MSEC(time_to_wait);
17024 			/*
17025 			 * If the timer fires too early, 1 clock tick earlier,
17026 			 * restart the timer.
17027 			 */
17028 			if (time_to_wait > msec_per_tick) {
17029 				TCP_STAT(tcps, tcp_timer_fire_early);
17030 				TCP_TIMER_RESTART(tcp, time_to_wait);
17031 				return;
17032 			}
17033 			/*
17034 			 * When we probe zero windows, we force the swnd open.
17035 			 * If our peer acks with a closed window swnd will be
17036 			 * set to zero by tcp_rput(). As long as we are
17037 			 * receiving acks tcp_rput will
17038 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17039 			 * first and second interval actions.  NOTE: the timer
17040 			 * interval is allowed to continue its exponential
17041 			 * backoff.
17042 			 */
17043 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17044 				if (tcp->tcp_debug) {
17045 					(void) strlog(TCP_MOD_ID, 0, 1,
17046 					    SL_TRACE, "tcp_timer: zero win");
17047 				}
17048 			} else {
17049 				/*
17050 				 * After retransmission, we need to do
17051 				 * slow start.  Set the ssthresh to one
17052 				 * half of current effective window and
17053 				 * cwnd to one MSS.  Also reset
17054 				 * tcp_cwnd_cnt.
17055 				 *
17056 				 * Note that if tcp_ssthresh is reduced because
17057 				 * of ECN, do not reduce it again unless it is
17058 				 * already one window of data away (tcp_cwr
17059 				 * should then be cleared) or this is a
17060 				 * timeout for a retransmitted segment.
17061 				 */
17062 				uint32_t npkt;
17063 
17064 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17065 					npkt = ((tcp->tcp_timer_backoff ?
17066 					    tcp->tcp_cwnd_ssthresh :
17067 					    tcp->tcp_snxt -
17068 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17069 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17070 					    tcp->tcp_mss;
17071 				}
17072 				tcp->tcp_cwnd = tcp->tcp_mss;
17073 				tcp->tcp_cwnd_cnt = 0;
17074 				if (tcp->tcp_ecn_ok) {
17075 					tcp->tcp_cwr = B_TRUE;
17076 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17077 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17078 				}
17079 			}
17080 			break;
17081 		}
17082 		/*
17083 		 * We have something to send yet we cannot send.  The
17084 		 * reason can be:
17085 		 *
17086 		 * 1. Zero send window: we need to do zero window probe.
17087 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17088 		 * segments.
17089 		 * 3. SWS avoidance: receiver may have shrunk window,
17090 		 * reset our knowledge.
17091 		 *
17092 		 * Note that condition 2 can happen with either 1 or
17093 		 * 3.  But 1 and 3 are exclusive.
17094 		 */
17095 		if (tcp->tcp_unsent != 0) {
17096 			if (tcp->tcp_cwnd == 0) {
17097 				/*
17098 				 * Set tcp_cwnd to 1 MSS so that a
17099 				 * new segment can be sent out.  We
17100 				 * are "clocking out" new data when
17101 				 * the network is really congested.
17102 				 */
17103 				ASSERT(tcp->tcp_ecn_ok);
17104 				tcp->tcp_cwnd = tcp->tcp_mss;
17105 			}
17106 			if (tcp->tcp_swnd == 0) {
17107 				/* Extend window for zero window probe */
17108 				tcp->tcp_swnd++;
17109 				tcp->tcp_zero_win_probe = B_TRUE;
17110 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17111 			} else {
17112 				/*
17113 				 * Handle timeout from sender SWS avoidance.
17114 				 * Reset our knowledge of the max send window
17115 				 * since the receiver might have reduced its
17116 				 * receive buffer.  Avoid setting tcp_max_swnd
17117 				 * to one since that will essentially disable
17118 				 * the SWS checks.
17119 				 *
17120 				 * Note that since we don't have a SWS
17121 				 * state variable, if the timeout is set
17122 				 * for ECN but not for SWS, this
17123 				 * code will also be executed.  This is
17124 				 * fine as tcp_max_swnd is updated
17125 				 * constantly and it will not affect
17126 				 * anything.
17127 				 */
17128 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17129 			}
17130 			tcp_wput_data(tcp, NULL, B_FALSE);
17131 			return;
17132 		}
17133 		/* Is there a FIN that needs to be to re retransmitted? */
17134 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17135 		    !tcp->tcp_fin_acked)
17136 			break;
17137 		/* Nothing to do, return without restarting timer. */
17138 		TCP_STAT(tcps, tcp_timer_fire_miss);
17139 		return;
17140 	case TCPS_FIN_WAIT_2:
17141 		/*
17142 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17143 		 * We waited some time for for peer's FIN, but it hasn't
17144 		 * arrived.  We flush the connection now to avoid
17145 		 * case where the peer has rebooted.
17146 		 */
17147 		if (TCP_IS_DETACHED(tcp)) {
17148 			(void) tcp_clean_death(tcp, 0, 23);
17149 		} else {
17150 			TCP_TIMER_RESTART(tcp,
17151 			    tcps->tcps_fin_wait_2_flush_interval);
17152 		}
17153 		return;
17154 	case TCPS_TIME_WAIT:
17155 		(void) tcp_clean_death(tcp, 0, 24);
17156 		return;
17157 	default:
17158 		if (tcp->tcp_debug) {
17159 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17160 			    "tcp_timer: strange state (%d) %s",
17161 			    tcp->tcp_state, tcp_display(tcp, NULL,
17162 			    DISP_PORT_ONLY));
17163 		}
17164 		return;
17165 	}
17166 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17167 		/*
17168 		 * For zero window probe, we need to send indefinitely,
17169 		 * unless we have not heard from the other side for some
17170 		 * time...
17171 		 */
17172 		if ((tcp->tcp_zero_win_probe == 0) ||
17173 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17174 		    second_threshold)) {
17175 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17176 			/*
17177 			 * If TCP is in SYN_RCVD state, send back a
17178 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17179 			 * should be zero in TCPS_SYN_RCVD state.
17180 			 */
17181 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17182 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17183 				    "in SYN_RCVD",
17184 				    tcp, tcp->tcp_snxt,
17185 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17186 			}
17187 			(void) tcp_clean_death(tcp,
17188 			    tcp->tcp_client_errno ?
17189 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17190 			return;
17191 		} else {
17192 			/*
17193 			 * Set tcp_ms_we_have_waited to second_threshold
17194 			 * so that in next timeout, we will do the above
17195 			 * check (lbolt - tcp_last_recv_time).  This is
17196 			 * also to avoid overflow.
17197 			 *
17198 			 * We don't need to decrement tcp_timer_backoff
17199 			 * to avoid overflow because it will be decremented
17200 			 * later if new timeout value is greater than
17201 			 * tcp_rexmit_interval_max.  In the case when
17202 			 * tcp_rexmit_interval_max is greater than
17203 			 * second_threshold, it means that we will wait
17204 			 * longer than second_threshold to send the next
17205 			 * window probe.
17206 			 */
17207 			tcp->tcp_ms_we_have_waited = second_threshold;
17208 		}
17209 	} else if (ms > first_threshold) {
17210 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17211 		    tcp->tcp_xmit_head != NULL) {
17212 			tcp->tcp_xmit_head =
17213 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17214 		}
17215 		/*
17216 		 * We have been retransmitting for too long...  The RTT
17217 		 * we calculated is probably incorrect.  Reinitialize it.
17218 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17219 		 * tcp_rtt_update so that we won't accidentally cache a
17220 		 * bad value.  But only do this if this is not a zero
17221 		 * window probe.
17222 		 */
17223 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17224 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17225 			    (tcp->tcp_rtt_sa >> 5);
17226 			tcp->tcp_rtt_sa = 0;
17227 			tcp_ip_notify(tcp);
17228 			tcp->tcp_rtt_update = 0;
17229 		}
17230 	}
17231 	tcp->tcp_timer_backoff++;
17232 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17233 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17234 	    tcps->tcps_rexmit_interval_min) {
17235 		/*
17236 		 * This means the original RTO is tcp_rexmit_interval_min.
17237 		 * So we will use tcp_rexmit_interval_min as the RTO value
17238 		 * and do the backoff.
17239 		 */
17240 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17241 	} else {
17242 		ms <<= tcp->tcp_timer_backoff;
17243 	}
17244 	if (ms > tcps->tcps_rexmit_interval_max) {
17245 		ms = tcps->tcps_rexmit_interval_max;
17246 		/*
17247 		 * ms is at max, decrement tcp_timer_backoff to avoid
17248 		 * overflow.
17249 		 */
17250 		tcp->tcp_timer_backoff--;
17251 	}
17252 	tcp->tcp_ms_we_have_waited += ms;
17253 	if (tcp->tcp_zero_win_probe == 0) {
17254 		tcp->tcp_rto = ms;
17255 	}
17256 	TCP_TIMER_RESTART(tcp, ms);
17257 	/*
17258 	 * This is after a timeout and tcp_rto is backed off.  Set
17259 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17260 	 * restart the timer with a correct value.
17261 	 */
17262 	tcp->tcp_set_timer = 1;
17263 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17264 	if (mss > tcp->tcp_mss)
17265 		mss = tcp->tcp_mss;
17266 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17267 		mss = tcp->tcp_swnd;
17268 
17269 	if ((mp = tcp->tcp_xmit_head) != NULL)
17270 		mp->b_prev = (mblk_t *)lbolt;
17271 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17272 	    B_TRUE);
17273 
17274 	/*
17275 	 * When slow start after retransmission begins, start with
17276 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17277 	 * start phase.  tcp_snd_burst controls how many segments
17278 	 * can be sent because of an ack.
17279 	 */
17280 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17281 	tcp->tcp_snd_burst = TCP_CWND_SS;
17282 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17283 	    (tcp->tcp_unsent == 0)) {
17284 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17285 	} else {
17286 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17287 	}
17288 	tcp->tcp_rexmit = B_TRUE;
17289 	tcp->tcp_dupack_cnt = 0;
17290 
17291 	/*
17292 	 * Remove all rexmit SACK blk to start from fresh.
17293 	 */
17294 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17295 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17296 		tcp->tcp_num_notsack_blk = 0;
17297 		tcp->tcp_cnt_notsack_list = 0;
17298 	}
17299 	if (mp == NULL) {
17300 		return;
17301 	}
17302 	/* Attach credentials to retransmitted initial SYNs. */
17303 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17304 		mblk_setcred(mp, tcp->tcp_cred);
17305 		DB_CPID(mp) = tcp->tcp_cpid;
17306 	}
17307 
17308 	tcp->tcp_csuna = tcp->tcp_snxt;
17309 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17310 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17311 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17312 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17313 
17314 }
17315 
17316 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17317 static void
17318 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17319 {
17320 	conn_t	*connp;
17321 
17322 	switch (tcp->tcp_state) {
17323 	case TCPS_BOUND:
17324 	case TCPS_LISTEN:
17325 		break;
17326 	default:
17327 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17328 		return;
17329 	}
17330 
17331 	/*
17332 	 * Need to clean up all the eagers since after the unbind, segments
17333 	 * will no longer be delivered to this listener stream.
17334 	 */
17335 	mutex_enter(&tcp->tcp_eager_lock);
17336 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17337 		tcp_eager_cleanup(tcp, 0);
17338 	}
17339 	mutex_exit(&tcp->tcp_eager_lock);
17340 
17341 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17342 		tcp->tcp_ipha->ipha_src = 0;
17343 	} else {
17344 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17345 	}
17346 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17347 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17348 	tcp_bind_hash_remove(tcp);
17349 	tcp->tcp_state = TCPS_IDLE;
17350 	tcp->tcp_mdt = B_FALSE;
17351 	/* Send M_FLUSH according to TPI */
17352 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17353 	connp = tcp->tcp_connp;
17354 	connp->conn_mdt_ok = B_FALSE;
17355 	ipcl_hash_remove(connp);
17356 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17357 	mp = mi_tpi_ok_ack_alloc(mp);
17358 	putnext(tcp->tcp_rq, mp);
17359 }
17360 
17361 /*
17362  * Don't let port fall into the privileged range.
17363  * Since the extra privileged ports can be arbitrary we also
17364  * ensure that we exclude those from consideration.
17365  * tcp_g_epriv_ports is not sorted thus we loop over it until
17366  * there are no changes.
17367  *
17368  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17369  * but instead the code relies on:
17370  * - the fact that the address of the array and its size never changes
17371  * - the atomic assignment of the elements of the array
17372  *
17373  * Returns 0 if there are no more ports available.
17374  *
17375  * TS note: skip multilevel ports.
17376  */
17377 static in_port_t
17378 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17379 {
17380 	int i;
17381 	boolean_t restart = B_FALSE;
17382 	tcp_stack_t *tcps = tcp->tcp_tcps;
17383 
17384 	if (random && tcp_random_anon_port != 0) {
17385 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17386 		    sizeof (in_port_t));
17387 		/*
17388 		 * Unless changed by a sys admin, the smallest anon port
17389 		 * is 32768 and the largest anon port is 65535.  It is
17390 		 * very likely (50%) for the random port to be smaller
17391 		 * than the smallest anon port.  When that happens,
17392 		 * add port % (anon port range) to the smallest anon
17393 		 * port to get the random port.  It should fall into the
17394 		 * valid anon port range.
17395 		 */
17396 		if (port < tcps->tcps_smallest_anon_port) {
17397 			port = tcps->tcps_smallest_anon_port +
17398 			    port % (tcps->tcps_largest_anon_port -
17399 			    tcps->tcps_smallest_anon_port);
17400 		}
17401 	}
17402 
17403 retry:
17404 	if (port < tcps->tcps_smallest_anon_port)
17405 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17406 
17407 	if (port > tcps->tcps_largest_anon_port) {
17408 		if (restart)
17409 			return (0);
17410 		restart = B_TRUE;
17411 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17412 	}
17413 
17414 	if (port < tcps->tcps_smallest_nonpriv_port)
17415 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17416 
17417 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17418 		if (port == tcps->tcps_g_epriv_ports[i]) {
17419 			port++;
17420 			/*
17421 			 * Make sure whether the port is in the
17422 			 * valid range.
17423 			 */
17424 			goto retry;
17425 		}
17426 	}
17427 	if (is_system_labeled() &&
17428 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17429 	    IPPROTO_TCP, B_TRUE)) != 0) {
17430 		port = i;
17431 		goto retry;
17432 	}
17433 	return (port);
17434 }
17435 
17436 /*
17437  * Return the next anonymous port in the privileged port range for
17438  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17439  * downwards.  This is the same behavior as documented in the userland
17440  * library call rresvport(3N).
17441  *
17442  * TS note: skip multilevel ports.
17443  */
17444 static in_port_t
17445 tcp_get_next_priv_port(const tcp_t *tcp)
17446 {
17447 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17448 	in_port_t nextport;
17449 	boolean_t restart = B_FALSE;
17450 	tcp_stack_t *tcps = tcp->tcp_tcps;
17451 retry:
17452 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17453 	    next_priv_port >= IPPORT_RESERVED) {
17454 		next_priv_port = IPPORT_RESERVED - 1;
17455 		if (restart)
17456 			return (0);
17457 		restart = B_TRUE;
17458 	}
17459 	if (is_system_labeled() &&
17460 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17461 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17462 		next_priv_port = nextport;
17463 		goto retry;
17464 	}
17465 	return (next_priv_port--);
17466 }
17467 
17468 /* The write side r/w procedure. */
17469 
17470 #if CCS_STATS
17471 struct {
17472 	struct {
17473 		int64_t count, bytes;
17474 	} tot, hit;
17475 } wrw_stats;
17476 #endif
17477 
17478 /*
17479  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17480  * messages.
17481  */
17482 /* ARGSUSED */
17483 static void
17484 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17485 {
17486 	conn_t	*connp = (conn_t *)arg;
17487 	tcp_t	*tcp = connp->conn_tcp;
17488 	queue_t	*q = tcp->tcp_wq;
17489 
17490 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17491 	/*
17492 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17493 	 * Once the close starts, streamhead and sockfs will not let any data
17494 	 * packets come down (close ensures that there are no threads using the
17495 	 * queue and no new threads will come down) but since qprocsoff()
17496 	 * hasn't happened yet, a M_FLUSH or some non data message might
17497 	 * get reflected back (in response to our own FLUSHRW) and get
17498 	 * processed after tcp_close() is done. The conn would still be valid
17499 	 * because a ref would have added but we need to check the state
17500 	 * before actually processing the packet.
17501 	 */
17502 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17503 		freemsg(mp);
17504 		return;
17505 	}
17506 
17507 	switch (DB_TYPE(mp)) {
17508 	case M_IOCDATA:
17509 		tcp_wput_iocdata(tcp, mp);
17510 		break;
17511 	case M_FLUSH:
17512 		tcp_wput_flush(tcp, mp);
17513 		break;
17514 	default:
17515 		CALL_IP_WPUT(connp, q, mp);
17516 		break;
17517 	}
17518 }
17519 
17520 /*
17521  * The TCP fast path write put procedure.
17522  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17523  */
17524 /* ARGSUSED */
17525 void
17526 tcp_output(void *arg, mblk_t *mp, void *arg2)
17527 {
17528 	int		len;
17529 	int		hdrlen;
17530 	int		plen;
17531 	mblk_t		*mp1;
17532 	uchar_t		*rptr;
17533 	uint32_t	snxt;
17534 	tcph_t		*tcph;
17535 	struct datab	*db;
17536 	uint32_t	suna;
17537 	uint32_t	mss;
17538 	ipaddr_t	*dst;
17539 	ipaddr_t	*src;
17540 	uint32_t	sum;
17541 	int		usable;
17542 	conn_t		*connp = (conn_t *)arg;
17543 	tcp_t		*tcp = connp->conn_tcp;
17544 	uint32_t	msize;
17545 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17546 
17547 	/*
17548 	 * Try and ASSERT the minimum possible references on the
17549 	 * conn early enough. Since we are executing on write side,
17550 	 * the connection is obviously not detached and that means
17551 	 * there is a ref each for TCP and IP. Since we are behind
17552 	 * the squeue, the minimum references needed are 3. If the
17553 	 * conn is in classifier hash list, there should be an
17554 	 * extra ref for that (we check both the possibilities).
17555 	 */
17556 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17557 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17558 
17559 	ASSERT(DB_TYPE(mp) == M_DATA);
17560 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17561 
17562 	mutex_enter(&tcp->tcp_non_sq_lock);
17563 	tcp->tcp_squeue_bytes -= msize;
17564 	mutex_exit(&tcp->tcp_non_sq_lock);
17565 
17566 	/* Bypass tcp protocol for fused tcp loopback */
17567 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17568 		return;
17569 
17570 	mss = tcp->tcp_mss;
17571 	if (tcp->tcp_xmit_zc_clean)
17572 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17573 
17574 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17575 	len = (int)(mp->b_wptr - mp->b_rptr);
17576 
17577 	/*
17578 	 * Criteria for fast path:
17579 	 *
17580 	 *   1. no unsent data
17581 	 *   2. single mblk in request
17582 	 *   3. connection established
17583 	 *   4. data in mblk
17584 	 *   5. len <= mss
17585 	 *   6. no tcp_valid bits
17586 	 */
17587 	if ((tcp->tcp_unsent != 0) ||
17588 	    (tcp->tcp_cork) ||
17589 	    (mp->b_cont != NULL) ||
17590 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17591 	    (len == 0) ||
17592 	    (len > mss) ||
17593 	    (tcp->tcp_valid_bits != 0)) {
17594 		tcp_wput_data(tcp, mp, B_FALSE);
17595 		return;
17596 	}
17597 
17598 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17599 	ASSERT(tcp->tcp_fin_sent == 0);
17600 
17601 	/* queue new packet onto retransmission queue */
17602 	if (tcp->tcp_xmit_head == NULL) {
17603 		tcp->tcp_xmit_head = mp;
17604 	} else {
17605 		tcp->tcp_xmit_last->b_cont = mp;
17606 	}
17607 	tcp->tcp_xmit_last = mp;
17608 	tcp->tcp_xmit_tail = mp;
17609 
17610 	/* find out how much we can send */
17611 	/* BEGIN CSTYLED */
17612 	/*
17613 	 *    un-acked           usable
17614 	 *  |--------------|-----------------|
17615 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17616 	 */
17617 	/* END CSTYLED */
17618 
17619 	/* start sending from tcp_snxt */
17620 	snxt = tcp->tcp_snxt;
17621 
17622 	/*
17623 	 * Check to see if this connection has been idled for some
17624 	 * time and no ACK is expected.  If it is, we need to slow
17625 	 * start again to get back the connection's "self-clock" as
17626 	 * described in VJ's paper.
17627 	 *
17628 	 * Refer to the comment in tcp_mss_set() for the calculation
17629 	 * of tcp_cwnd after idle.
17630 	 */
17631 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17632 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17633 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17634 	}
17635 
17636 	usable = tcp->tcp_swnd;		/* tcp window size */
17637 	if (usable > tcp->tcp_cwnd)
17638 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17639 	usable -= snxt;		/* subtract stuff already sent */
17640 	suna = tcp->tcp_suna;
17641 	usable += suna;
17642 	/* usable can be < 0 if the congestion window is smaller */
17643 	if (len > usable) {
17644 		/* Can't send complete M_DATA in one shot */
17645 		goto slow;
17646 	}
17647 
17648 	mutex_enter(&tcp->tcp_non_sq_lock);
17649 	if (tcp->tcp_flow_stopped &&
17650 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17651 		tcp_clrqfull(tcp);
17652 	}
17653 	mutex_exit(&tcp->tcp_non_sq_lock);
17654 
17655 	/*
17656 	 * determine if anything to send (Nagle).
17657 	 *
17658 	 *   1. len < tcp_mss (i.e. small)
17659 	 *   2. unacknowledged data present
17660 	 *   3. len < nagle limit
17661 	 *   4. last packet sent < nagle limit (previous packet sent)
17662 	 */
17663 	if ((len < mss) && (snxt != suna) &&
17664 	    (len < (int)tcp->tcp_naglim) &&
17665 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17666 		/*
17667 		 * This was the first unsent packet and normally
17668 		 * mss < xmit_hiwater so there is no need to worry
17669 		 * about flow control. The next packet will go
17670 		 * through the flow control check in tcp_wput_data().
17671 		 */
17672 		/* leftover work from above */
17673 		tcp->tcp_unsent = len;
17674 		tcp->tcp_xmit_tail_unsent = len;
17675 
17676 		return;
17677 	}
17678 
17679 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17680 
17681 	if (snxt == suna) {
17682 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17683 	}
17684 
17685 	/* we have always sent something */
17686 	tcp->tcp_rack_cnt = 0;
17687 
17688 	tcp->tcp_snxt = snxt + len;
17689 	tcp->tcp_rack = tcp->tcp_rnxt;
17690 
17691 	if ((mp1 = dupb(mp)) == 0)
17692 		goto no_memory;
17693 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17694 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17695 
17696 	/* adjust tcp header information */
17697 	tcph = tcp->tcp_tcph;
17698 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17699 
17700 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17701 	sum = (sum >> 16) + (sum & 0xFFFF);
17702 	U16_TO_ABE16(sum, tcph->th_sum);
17703 
17704 	U32_TO_ABE32(snxt, tcph->th_seq);
17705 
17706 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17707 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17708 	BUMP_LOCAL(tcp->tcp_obsegs);
17709 
17710 	/* Update the latest receive window size in TCP header. */
17711 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17712 	    tcph->th_win);
17713 
17714 	tcp->tcp_last_sent_len = (ushort_t)len;
17715 
17716 	plen = len + tcp->tcp_hdr_len;
17717 
17718 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17719 		tcp->tcp_ipha->ipha_length = htons(plen);
17720 	} else {
17721 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17722 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17723 	}
17724 
17725 	/* see if we need to allocate a mblk for the headers */
17726 	hdrlen = tcp->tcp_hdr_len;
17727 	rptr = mp1->b_rptr - hdrlen;
17728 	db = mp1->b_datap;
17729 	if ((db->db_ref != 2) || rptr < db->db_base ||
17730 	    (!OK_32PTR(rptr))) {
17731 		/* NOTE: we assume allocb returns an OK_32PTR */
17732 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17733 		    tcps->tcps_wroff_xtra, BPRI_MED);
17734 		if (!mp) {
17735 			freemsg(mp1);
17736 			goto no_memory;
17737 		}
17738 		mp->b_cont = mp1;
17739 		mp1 = mp;
17740 		/* Leave room for Link Level header */
17741 		/* hdrlen = tcp->tcp_hdr_len; */
17742 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17743 		mp1->b_wptr = &rptr[hdrlen];
17744 	}
17745 	mp1->b_rptr = rptr;
17746 
17747 	/* Fill in the timestamp option. */
17748 	if (tcp->tcp_snd_ts_ok) {
17749 		U32_TO_BE32((uint32_t)lbolt,
17750 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17751 		U32_TO_BE32(tcp->tcp_ts_recent,
17752 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17753 	} else {
17754 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17755 	}
17756 
17757 	/* copy header into outgoing packet */
17758 	dst = (ipaddr_t *)rptr;
17759 	src = (ipaddr_t *)tcp->tcp_iphc;
17760 	dst[0] = src[0];
17761 	dst[1] = src[1];
17762 	dst[2] = src[2];
17763 	dst[3] = src[3];
17764 	dst[4] = src[4];
17765 	dst[5] = src[5];
17766 	dst[6] = src[6];
17767 	dst[7] = src[7];
17768 	dst[8] = src[8];
17769 	dst[9] = src[9];
17770 	if (hdrlen -= 40) {
17771 		hdrlen >>= 2;
17772 		dst += 10;
17773 		src += 10;
17774 		do {
17775 			*dst++ = *src++;
17776 		} while (--hdrlen);
17777 	}
17778 
17779 	/*
17780 	 * Set the ECN info in the TCP header.  Note that this
17781 	 * is not the template header.
17782 	 */
17783 	if (tcp->tcp_ecn_ok) {
17784 		SET_ECT(tcp, rptr);
17785 
17786 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17787 		if (tcp->tcp_ecn_echo_on)
17788 			tcph->th_flags[0] |= TH_ECE;
17789 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17790 			tcph->th_flags[0] |= TH_CWR;
17791 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17792 		}
17793 	}
17794 
17795 	if (tcp->tcp_ip_forward_progress) {
17796 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17797 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17798 		tcp->tcp_ip_forward_progress = B_FALSE;
17799 	}
17800 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17801 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17802 	return;
17803 
17804 	/*
17805 	 * If we ran out of memory, we pretend to have sent the packet
17806 	 * and that it was lost on the wire.
17807 	 */
17808 no_memory:
17809 	return;
17810 
17811 slow:
17812 	/* leftover work from above */
17813 	tcp->tcp_unsent = len;
17814 	tcp->tcp_xmit_tail_unsent = len;
17815 	tcp_wput_data(tcp, NULL, B_FALSE);
17816 }
17817 
17818 /*
17819  * The function called through squeue to get behind eager's perimeter to
17820  * finish the accept processing.
17821  */
17822 /* ARGSUSED */
17823 void
17824 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17825 {
17826 	conn_t			*connp = (conn_t *)arg;
17827 	tcp_t			*tcp = connp->conn_tcp;
17828 	queue_t			*q = tcp->tcp_rq;
17829 	mblk_t			*mp1;
17830 	mblk_t			*stropt_mp = mp;
17831 	struct  stroptions	*stropt;
17832 	uint_t			thwin;
17833 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17834 
17835 	/*
17836 	 * Drop the eager's ref on the listener, that was placed when
17837 	 * this eager began life in tcp_conn_request.
17838 	 */
17839 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17840 
17841 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17842 		/*
17843 		 * Someone blewoff the eager before we could finish
17844 		 * the accept.
17845 		 *
17846 		 * The only reason eager exists it because we put in
17847 		 * a ref on it when conn ind went up. We need to send
17848 		 * a disconnect indication up while the last reference
17849 		 * on the eager will be dropped by the squeue when we
17850 		 * return.
17851 		 */
17852 		ASSERT(tcp->tcp_listener == NULL);
17853 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17854 			struct	T_discon_ind	*tdi;
17855 
17856 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17857 			/*
17858 			 * Let us reuse the incoming mblk to avoid memory
17859 			 * allocation failure problems. We know that the
17860 			 * size of the incoming mblk i.e. stroptions is greater
17861 			 * than sizeof T_discon_ind. So the reallocb below
17862 			 * can't fail.
17863 			 */
17864 			freemsg(mp->b_cont);
17865 			mp->b_cont = NULL;
17866 			ASSERT(DB_REF(mp) == 1);
17867 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17868 			    B_FALSE);
17869 			ASSERT(mp != NULL);
17870 			DB_TYPE(mp) = M_PROTO;
17871 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17872 			tdi = (struct T_discon_ind *)mp->b_rptr;
17873 			if (tcp->tcp_issocket) {
17874 				tdi->DISCON_reason = ECONNREFUSED;
17875 				tdi->SEQ_number = 0;
17876 			} else {
17877 				tdi->DISCON_reason = ENOPROTOOPT;
17878 				tdi->SEQ_number =
17879 				    tcp->tcp_conn_req_seqnum;
17880 			}
17881 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17882 			putnext(q, mp);
17883 		} else {
17884 			freemsg(mp);
17885 		}
17886 		if (tcp->tcp_hard_binding) {
17887 			tcp->tcp_hard_binding = B_FALSE;
17888 			tcp->tcp_hard_bound = B_TRUE;
17889 		}
17890 		tcp->tcp_detached = B_FALSE;
17891 		return;
17892 	}
17893 
17894 	mp1 = stropt_mp->b_cont;
17895 	stropt_mp->b_cont = NULL;
17896 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17897 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17898 
17899 	while (mp1 != NULL) {
17900 		mp = mp1;
17901 		mp1 = mp1->b_cont;
17902 		mp->b_cont = NULL;
17903 		tcp->tcp_drop_opt_ack_cnt++;
17904 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17905 	}
17906 	mp = NULL;
17907 
17908 	/*
17909 	 * For a loopback connection with tcp_direct_sockfs on, note that
17910 	 * we don't have to protect tcp_rcv_list yet because synchronous
17911 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17912 	 * possibly race with us.
17913 	 */
17914 
17915 	/*
17916 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17917 	 * properly.  This is the first time we know of the acceptor'
17918 	 * queue.  So we do it here.
17919 	 */
17920 	if (tcp->tcp_rcv_list == NULL) {
17921 		/*
17922 		 * Recv queue is empty, tcp_rwnd should not have changed.
17923 		 * That means it should be equal to the listener's tcp_rwnd.
17924 		 */
17925 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17926 	} else {
17927 #ifdef DEBUG
17928 		uint_t cnt = 0;
17929 
17930 		mp1 = tcp->tcp_rcv_list;
17931 		while ((mp = mp1) != NULL) {
17932 			mp1 = mp->b_next;
17933 			cnt += msgdsize(mp);
17934 		}
17935 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17936 #endif
17937 		/* There is some data, add them back to get the max. */
17938 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17939 	}
17940 
17941 	stropt->so_flags = SO_HIWAT;
17942 	stropt->so_hiwat = MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
17943 
17944 	stropt->so_flags |= SO_MAXBLK;
17945 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17946 
17947 	/*
17948 	 * This is the first time we run on the correct
17949 	 * queue after tcp_accept. So fix all the q parameters
17950 	 * here.
17951 	 */
17952 	/* Allocate room for SACK options if needed. */
17953 	stropt->so_flags |= SO_WROFF;
17954 	if (tcp->tcp_fused) {
17955 		ASSERT(tcp->tcp_loopback);
17956 		ASSERT(tcp->tcp_loopback_peer != NULL);
17957 		/*
17958 		 * For fused tcp loopback, set the stream head's write
17959 		 * offset value to zero since we won't be needing any room
17960 		 * for TCP/IP headers.  This would also improve performance
17961 		 * since it would reduce the amount of work done by kmem.
17962 		 * Non-fused tcp loopback case is handled separately below.
17963 		 */
17964 		stropt->so_wroff = 0;
17965 		/*
17966 		 * Record the stream head's high water mark for this endpoint;
17967 		 * this is used for flow-control purposes in tcp_fuse_output().
17968 		 */
17969 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17970 		/*
17971 		 * Update the peer's transmit parameters according to
17972 		 * our recently calculated high water mark value.
17973 		 */
17974 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17975 	} else if (tcp->tcp_snd_sack_ok) {
17976 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17977 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17978 	} else {
17979 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17980 		    tcps->tcps_wroff_xtra);
17981 	}
17982 
17983 	/*
17984 	 * If this is endpoint is handling SSL, then reserve extra
17985 	 * offset and space at the end.
17986 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17987 	 * overriding the previous setting. The extra cost of signing and
17988 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17989 	 * instead of a single contiguous one by the stream head
17990 	 * largely outweighs the statistical reduction of ACKs, when
17991 	 * applicable. The peer will also save on decyption and verification
17992 	 * costs.
17993 	 */
17994 	if (tcp->tcp_kssl_ctx != NULL) {
17995 		stropt->so_wroff += SSL3_WROFFSET;
17996 
17997 		stropt->so_flags |= SO_TAIL;
17998 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17999 
18000 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18001 	}
18002 
18003 	/* Send the options up */
18004 	putnext(q, stropt_mp);
18005 
18006 	/*
18007 	 * Pass up any data and/or a fin that has been received.
18008 	 *
18009 	 * Adjust receive window in case it had decreased
18010 	 * (because there is data <=> tcp_rcv_list != NULL)
18011 	 * while the connection was detached. Note that
18012 	 * in case the eager was flow-controlled, w/o this
18013 	 * code, the rwnd may never open up again!
18014 	 */
18015 	if (tcp->tcp_rcv_list != NULL) {
18016 		/* We drain directly in case of fused tcp loopback */
18017 		if (!tcp->tcp_fused && canputnext(q)) {
18018 			tcp->tcp_rwnd = q->q_hiwat;
18019 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18020 			    << tcp->tcp_rcv_ws;
18021 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18022 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18023 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18024 				tcp_xmit_ctl(NULL,
18025 				    tcp, (tcp->tcp_swnd == 0) ?
18026 				    tcp->tcp_suna : tcp->tcp_snxt,
18027 				    tcp->tcp_rnxt, TH_ACK);
18028 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18029 			}
18030 
18031 		}
18032 		(void) tcp_rcv_drain(q, tcp);
18033 
18034 		/*
18035 		 * For fused tcp loopback, back-enable peer endpoint
18036 		 * if it's currently flow-controlled.
18037 		 */
18038 		if (tcp->tcp_fused) {
18039 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18040 
18041 			ASSERT(peer_tcp != NULL);
18042 			ASSERT(peer_tcp->tcp_fused);
18043 			/*
18044 			 * In order to change the peer's tcp_flow_stopped,
18045 			 * we need to take locks for both end points. The
18046 			 * highest address is taken first.
18047 			 */
18048 			if (peer_tcp > tcp) {
18049 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18050 				mutex_enter(&tcp->tcp_non_sq_lock);
18051 			} else {
18052 				mutex_enter(&tcp->tcp_non_sq_lock);
18053 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18054 			}
18055 			if (peer_tcp->tcp_flow_stopped) {
18056 				tcp_clrqfull(peer_tcp);
18057 				TCP_STAT(tcps, tcp_fusion_backenabled);
18058 			}
18059 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18060 			mutex_exit(&tcp->tcp_non_sq_lock);
18061 		}
18062 	}
18063 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18064 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18065 		mp = mi_tpi_ordrel_ind();
18066 		if (mp) {
18067 			tcp->tcp_ordrel_done = B_TRUE;
18068 			putnext(q, mp);
18069 			if (tcp->tcp_deferred_clean_death) {
18070 				/*
18071 				 * tcp_clean_death was deferred
18072 				 * for T_ORDREL_IND - do it now
18073 				 */
18074 				(void) tcp_clean_death(tcp,
18075 				    tcp->tcp_client_errno, 21);
18076 				tcp->tcp_deferred_clean_death = B_FALSE;
18077 			}
18078 		} else {
18079 			/*
18080 			 * Run the orderly release in the
18081 			 * service routine.
18082 			 */
18083 			qenable(q);
18084 		}
18085 	}
18086 	if (tcp->tcp_hard_binding) {
18087 		tcp->tcp_hard_binding = B_FALSE;
18088 		tcp->tcp_hard_bound = B_TRUE;
18089 	}
18090 
18091 	tcp->tcp_detached = B_FALSE;
18092 
18093 	/* We can enable synchronous streams now */
18094 	if (tcp->tcp_fused) {
18095 		tcp_fuse_syncstr_enable_pair(tcp);
18096 	}
18097 
18098 	if (tcp->tcp_ka_enabled) {
18099 		tcp->tcp_ka_last_intrvl = 0;
18100 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18101 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18102 	}
18103 
18104 	/*
18105 	 * At this point, eager is fully established and will
18106 	 * have the following references -
18107 	 *
18108 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18109 	 * 1 reference for the squeue which will be dropped by the squeue as
18110 	 *	soon as this function returns.
18111 	 * There will be 1 additonal reference for being in classifier
18112 	 *	hash list provided something bad hasn't happened.
18113 	 */
18114 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18115 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18116 }
18117 
18118 /*
18119  * The function called through squeue to get behind listener's perimeter to
18120  * send a deffered conn_ind.
18121  */
18122 /* ARGSUSED */
18123 void
18124 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18125 {
18126 	conn_t	*connp = (conn_t *)arg;
18127 	tcp_t *listener = connp->conn_tcp;
18128 
18129 	if (listener->tcp_state == TCPS_CLOSED ||
18130 	    TCP_IS_DETACHED(listener)) {
18131 		/*
18132 		 * If listener has closed, it would have caused a
18133 		 * a cleanup/blowoff to happen for the eager.
18134 		 */
18135 		tcp_t *tcp;
18136 		struct T_conn_ind	*conn_ind;
18137 
18138 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18139 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18140 		    conn_ind->OPT_length);
18141 		/*
18142 		 * We need to drop the ref on eager that was put
18143 		 * tcp_rput_data() before trying to send the conn_ind
18144 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18145 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18146 		 * listener is closed so we drop the ref.
18147 		 */
18148 		CONN_DEC_REF(tcp->tcp_connp);
18149 		freemsg(mp);
18150 		return;
18151 	}
18152 	putnext(listener->tcp_rq, mp);
18153 }
18154 
18155 
18156 /*
18157  * This is the STREAMS entry point for T_CONN_RES coming down on
18158  * Acceptor STREAM when  sockfs listener does accept processing.
18159  * Read the block comment on top of tcp_conn_request().
18160  */
18161 void
18162 tcp_wput_accept(queue_t *q, mblk_t *mp)
18163 {
18164 	queue_t *rq = RD(q);
18165 	struct T_conn_res *conn_res;
18166 	tcp_t *eager;
18167 	tcp_t *listener;
18168 	struct T_ok_ack *ok;
18169 	t_scalar_t PRIM_type;
18170 	mblk_t *opt_mp;
18171 	conn_t *econnp;
18172 
18173 	ASSERT(DB_TYPE(mp) == M_PROTO);
18174 
18175 	conn_res = (struct T_conn_res *)mp->b_rptr;
18176 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18177 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18178 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18179 		if (mp != NULL)
18180 			putnext(rq, mp);
18181 		return;
18182 	}
18183 	switch (conn_res->PRIM_type) {
18184 	case O_T_CONN_RES:
18185 	case T_CONN_RES:
18186 		/*
18187 		 * We pass up an err ack if allocb fails. This will
18188 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18189 		 * tcp_eager_blowoff to be called. sockfs will then call
18190 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18191 		 * we need to do the allocb up here because we have to
18192 		 * make sure rq->q_qinfo->qi_qclose still points to the
18193 		 * correct function (tcpclose_accept) in case allocb
18194 		 * fails.
18195 		 */
18196 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18197 		if (opt_mp == NULL) {
18198 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18199 			if (mp != NULL)
18200 				putnext(rq, mp);
18201 			return;
18202 		}
18203 
18204 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18205 		    &eager, conn_res->OPT_length);
18206 		PRIM_type = conn_res->PRIM_type;
18207 		mp->b_datap->db_type = M_PCPROTO;
18208 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18209 		ok = (struct T_ok_ack *)mp->b_rptr;
18210 		ok->PRIM_type = T_OK_ACK;
18211 		ok->CORRECT_prim = PRIM_type;
18212 		econnp = eager->tcp_connp;
18213 		econnp->conn_dev = (dev_t)q->q_ptr;
18214 		eager->tcp_rq = rq;
18215 		eager->tcp_wq = q;
18216 		rq->q_ptr = econnp;
18217 		rq->q_qinfo = &tcp_rinit;
18218 		q->q_ptr = econnp;
18219 		q->q_qinfo = &tcp_winit;
18220 		listener = eager->tcp_listener;
18221 		eager->tcp_issocket = B_TRUE;
18222 
18223 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18224 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18225 		ASSERT(econnp->conn_netstack ==
18226 		    listener->tcp_connp->conn_netstack);
18227 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18228 
18229 		/* Put the ref for IP */
18230 		CONN_INC_REF(econnp);
18231 
18232 		/*
18233 		 * We should have minimum of 3 references on the conn
18234 		 * at this point. One each for TCP and IP and one for
18235 		 * the T_conn_ind that was sent up when the 3-way handshake
18236 		 * completed. In the normal case we would also have another
18237 		 * reference (making a total of 4) for the conn being in the
18238 		 * classifier hash list. However the eager could have received
18239 		 * an RST subsequently and tcp_closei_local could have removed
18240 		 * the eager from the classifier hash list, hence we can't
18241 		 * assert that reference.
18242 		 */
18243 		ASSERT(econnp->conn_ref >= 3);
18244 
18245 		/*
18246 		 * Send the new local address also up to sockfs. There
18247 		 * should already be enough space in the mp that came
18248 		 * down from soaccept().
18249 		 */
18250 		if (eager->tcp_family == AF_INET) {
18251 			sin_t *sin;
18252 
18253 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18254 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18255 			sin = (sin_t *)mp->b_wptr;
18256 			mp->b_wptr += sizeof (sin_t);
18257 			sin->sin_family = AF_INET;
18258 			sin->sin_port = eager->tcp_lport;
18259 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18260 		} else {
18261 			sin6_t *sin6;
18262 
18263 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18264 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18265 			sin6 = (sin6_t *)mp->b_wptr;
18266 			mp->b_wptr += sizeof (sin6_t);
18267 			sin6->sin6_family = AF_INET6;
18268 			sin6->sin6_port = eager->tcp_lport;
18269 			if (eager->tcp_ipversion == IPV4_VERSION) {
18270 				sin6->sin6_flowinfo = 0;
18271 				IN6_IPADDR_TO_V4MAPPED(
18272 					eager->tcp_ipha->ipha_src,
18273 					    &sin6->sin6_addr);
18274 			} else {
18275 				ASSERT(eager->tcp_ip6h != NULL);
18276 				sin6->sin6_flowinfo =
18277 				    eager->tcp_ip6h->ip6_vcf &
18278 				    ~IPV6_VERS_AND_FLOW_MASK;
18279 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18280 			}
18281 			sin6->sin6_scope_id = 0;
18282 			sin6->__sin6_src_id = 0;
18283 		}
18284 
18285 		putnext(rq, mp);
18286 
18287 		opt_mp->b_datap->db_type = M_SETOPTS;
18288 		opt_mp->b_wptr += sizeof (struct stroptions);
18289 
18290 		/*
18291 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18292 		 * from listener to acceptor. The message is chained on the
18293 		 * bind_mp which tcp_rput_other will send down to IP.
18294 		 */
18295 		if (listener->tcp_bound_if != 0) {
18296 			/* allocate optmgmt req */
18297 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18298 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18299 			    sizeof (int));
18300 			if (mp != NULL)
18301 				linkb(opt_mp, mp);
18302 		}
18303 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18304 			uint_t on = 1;
18305 
18306 			/* allocate optmgmt req */
18307 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18308 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18309 			if (mp != NULL)
18310 				linkb(opt_mp, mp);
18311 		}
18312 
18313 
18314 		mutex_enter(&listener->tcp_eager_lock);
18315 
18316 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18317 
18318 			tcp_t *tail;
18319 			tcp_t *tcp;
18320 			mblk_t *mp1;
18321 
18322 			tcp = listener->tcp_eager_prev_q0;
18323 			/*
18324 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18325 			 * deferred T_conn_ind queue. We need to get to the head
18326 			 * of the queue in order to send up T_conn_ind the same
18327 			 * order as how the 3WHS is completed.
18328 			 */
18329 			while (tcp != listener) {
18330 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18331 				    !tcp->tcp_kssl_pending)
18332 					break;
18333 				else
18334 					tcp = tcp->tcp_eager_prev_q0;
18335 			}
18336 			/* None of the pending eagers can be sent up now */
18337 			if (tcp == listener)
18338 				goto no_more_eagers;
18339 
18340 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18341 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18342 			/* Move from q0 to q */
18343 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18344 			listener->tcp_conn_req_cnt_q0--;
18345 			listener->tcp_conn_req_cnt_q++;
18346 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18347 			    tcp->tcp_eager_prev_q0;
18348 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18349 			    tcp->tcp_eager_next_q0;
18350 			tcp->tcp_eager_prev_q0 = NULL;
18351 			tcp->tcp_eager_next_q0 = NULL;
18352 			tcp->tcp_conn_def_q0 = B_FALSE;
18353 
18354 			/* Make sure the tcp isn't in the list of droppables */
18355 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18356 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18357 
18358 			/*
18359 			 * Insert at end of the queue because sockfs sends
18360 			 * down T_CONN_RES in chronological order. Leaving
18361 			 * the older conn indications at front of the queue
18362 			 * helps reducing search time.
18363 			 */
18364 			tail = listener->tcp_eager_last_q;
18365 			if (tail != NULL) {
18366 				tail->tcp_eager_next_q = tcp;
18367 			} else {
18368 				listener->tcp_eager_next_q = tcp;
18369 			}
18370 			listener->tcp_eager_last_q = tcp;
18371 			tcp->tcp_eager_next_q = NULL;
18372 
18373 			/* Need to get inside the listener perimeter */
18374 			CONN_INC_REF(listener->tcp_connp);
18375 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18376 			    tcp_send_pending, listener->tcp_connp,
18377 			    SQTAG_TCP_SEND_PENDING);
18378 		}
18379 no_more_eagers:
18380 		tcp_eager_unlink(eager);
18381 		mutex_exit(&listener->tcp_eager_lock);
18382 
18383 		/*
18384 		 * At this point, the eager is detached from the listener
18385 		 * but we still have an extra refs on eager (apart from the
18386 		 * usual tcp references). The ref was placed in tcp_rput_data
18387 		 * before sending the conn_ind in tcp_send_conn_ind.
18388 		 * The ref will be dropped in tcp_accept_finish().
18389 		 */
18390 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18391 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18392 		return;
18393 	default:
18394 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18395 		if (mp != NULL)
18396 			putnext(rq, mp);
18397 		return;
18398 	}
18399 }
18400 
18401 void
18402 tcp_wput(queue_t *q, mblk_t *mp)
18403 {
18404 	conn_t	*connp = Q_TO_CONN(q);
18405 	tcp_t	*tcp;
18406 	void (*output_proc)();
18407 	t_scalar_t type;
18408 	uchar_t *rptr;
18409 	struct iocblk	*iocp;
18410 	uint32_t	msize;
18411 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18412 
18413 	ASSERT(connp->conn_ref >= 2);
18414 
18415 	switch (DB_TYPE(mp)) {
18416 	case M_DATA:
18417 		tcp = connp->conn_tcp;
18418 		ASSERT(tcp != NULL);
18419 
18420 		msize = msgdsize(mp);
18421 
18422 		mutex_enter(&tcp->tcp_non_sq_lock);
18423 		tcp->tcp_squeue_bytes += msize;
18424 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18425 			tcp_setqfull(tcp);
18426 		}
18427 		mutex_exit(&tcp->tcp_non_sq_lock);
18428 
18429 		CONN_INC_REF(connp);
18430 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18431 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18432 		return;
18433 	case M_PROTO:
18434 	case M_PCPROTO:
18435 		/*
18436 		 * if it is a snmp message, don't get behind the squeue
18437 		 */
18438 		tcp = connp->conn_tcp;
18439 		rptr = mp->b_rptr;
18440 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18441 			type = ((union T_primitives *)rptr)->type;
18442 		} else {
18443 			if (tcp->tcp_debug) {
18444 				(void) strlog(TCP_MOD_ID, 0, 1,
18445 				    SL_ERROR|SL_TRACE,
18446 				    "tcp_wput_proto, dropping one...");
18447 			}
18448 			freemsg(mp);
18449 			return;
18450 		}
18451 		if (type == T_SVR4_OPTMGMT_REQ) {
18452 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18453 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18454 			    cr)) {
18455 				/*
18456 				 * This was a SNMP request
18457 				 */
18458 				return;
18459 			} else {
18460 				output_proc = tcp_wput_proto;
18461 			}
18462 		} else {
18463 			output_proc = tcp_wput_proto;
18464 		}
18465 		break;
18466 	case M_IOCTL:
18467 		/*
18468 		 * Most ioctls can be processed right away without going via
18469 		 * squeues - process them right here. Those that do require
18470 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18471 		 * are processed by tcp_wput_ioctl().
18472 		 */
18473 		iocp = (struct iocblk *)mp->b_rptr;
18474 		tcp = connp->conn_tcp;
18475 
18476 		switch (iocp->ioc_cmd) {
18477 		case TCP_IOC_ABORT_CONN:
18478 			tcp_ioctl_abort_conn(q, mp);
18479 			return;
18480 		case TI_GETPEERNAME:
18481 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18482 				iocp->ioc_error = ENOTCONN;
18483 				iocp->ioc_count = 0;
18484 				mp->b_datap->db_type = M_IOCACK;
18485 				qreply(q, mp);
18486 				return;
18487 			}
18488 			/* FALLTHRU */
18489 		case TI_GETMYNAME:
18490 			mi_copyin(q, mp, NULL,
18491 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18492 			return;
18493 		case ND_SET:
18494 			/* nd_getset does the necessary checks */
18495 		case ND_GET:
18496 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18497 				CALL_IP_WPUT(connp, q, mp);
18498 				return;
18499 			}
18500 			qreply(q, mp);
18501 			return;
18502 		case TCP_IOC_DEFAULT_Q:
18503 			/*
18504 			 * Wants to be the default wq. Check the credentials
18505 			 * first, the rest is executed via squeue.
18506 			 */
18507 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18508 				iocp->ioc_error = EPERM;
18509 				iocp->ioc_count = 0;
18510 				mp->b_datap->db_type = M_IOCACK;
18511 				qreply(q, mp);
18512 				return;
18513 			}
18514 			output_proc = tcp_wput_ioctl;
18515 			break;
18516 		default:
18517 			output_proc = tcp_wput_ioctl;
18518 			break;
18519 		}
18520 		break;
18521 	default:
18522 		output_proc = tcp_wput_nondata;
18523 		break;
18524 	}
18525 
18526 	CONN_INC_REF(connp);
18527 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18528 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18529 }
18530 
18531 /*
18532  * Initial STREAMS write side put() procedure for sockets. It tries to
18533  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18534  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18535  * are handled by tcp_wput() as usual.
18536  *
18537  * All further messages will also be handled by tcp_wput() because we cannot
18538  * be sure that the above short cut is safe later.
18539  */
18540 static void
18541 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18542 {
18543 	conn_t			*connp = Q_TO_CONN(wq);
18544 	tcp_t			*tcp = connp->conn_tcp;
18545 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18546 
18547 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18548 	wq->q_qinfo = &tcp_winit;
18549 
18550 	ASSERT(IPCL_IS_TCP(connp));
18551 	ASSERT(TCP_IS_SOCKET(tcp));
18552 
18553 	if (DB_TYPE(mp) == M_PCPROTO &&
18554 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18555 	    car->PRIM_type == T_CAPABILITY_REQ) {
18556 		tcp_capability_req(tcp, mp);
18557 		return;
18558 	}
18559 
18560 	tcp_wput(wq, mp);
18561 }
18562 
18563 static boolean_t
18564 tcp_zcopy_check(tcp_t *tcp)
18565 {
18566 	conn_t	*connp = tcp->tcp_connp;
18567 	ire_t	*ire;
18568 	boolean_t	zc_enabled = B_FALSE;
18569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18570 
18571 	if (do_tcpzcopy == 2)
18572 		zc_enabled = B_TRUE;
18573 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18574 	    IPCL_IS_CONNECTED(connp) &&
18575 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18576 	    connp->conn_dontroute == 0 &&
18577 	    !connp->conn_nexthop_set &&
18578 	    connp->conn_xmit_if_ill == NULL &&
18579 	    connp->conn_nofailover_ill == NULL &&
18580 	    do_tcpzcopy == 1) {
18581 		/*
18582 		 * the checks above  closely resemble the fast path checks
18583 		 * in tcp_send_data().
18584 		 */
18585 		mutex_enter(&connp->conn_lock);
18586 		ire = connp->conn_ire_cache;
18587 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18588 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18589 			IRE_REFHOLD(ire);
18590 			if (ire->ire_stq != NULL) {
18591 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18592 
18593 				zc_enabled = ill && (ill->ill_capabilities &
18594 				    ILL_CAPAB_ZEROCOPY) &&
18595 				    (ill->ill_zerocopy_capab->
18596 				    ill_zerocopy_flags != 0);
18597 			}
18598 			IRE_REFRELE(ire);
18599 		}
18600 		mutex_exit(&connp->conn_lock);
18601 	}
18602 	tcp->tcp_snd_zcopy_on = zc_enabled;
18603 	if (!TCP_IS_DETACHED(tcp)) {
18604 		if (zc_enabled) {
18605 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18606 			TCP_STAT(tcps, tcp_zcopy_on);
18607 		} else {
18608 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18609 			TCP_STAT(tcps, tcp_zcopy_off);
18610 		}
18611 	}
18612 	return (zc_enabled);
18613 }
18614 
18615 static mblk_t *
18616 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18617 {
18618 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18619 
18620 	if (do_tcpzcopy == 2)
18621 		return (bp);
18622 	else if (tcp->tcp_snd_zcopy_on) {
18623 		tcp->tcp_snd_zcopy_on = B_FALSE;
18624 		if (!TCP_IS_DETACHED(tcp)) {
18625 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18626 			TCP_STAT(tcps, tcp_zcopy_disable);
18627 		}
18628 	}
18629 	return (tcp_zcopy_backoff(tcp, bp, 0));
18630 }
18631 
18632 /*
18633  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18634  * the original desballoca'ed segmapped mblk.
18635  */
18636 static mblk_t *
18637 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18638 {
18639 	mblk_t *head, *tail, *nbp;
18640 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18641 
18642 	if (IS_VMLOANED_MBLK(bp)) {
18643 		TCP_STAT(tcps, tcp_zcopy_backoff);
18644 		if ((head = copyb(bp)) == NULL) {
18645 			/* fail to backoff; leave it for the next backoff */
18646 			tcp->tcp_xmit_zc_clean = B_FALSE;
18647 			return (bp);
18648 		}
18649 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18650 			if (fix_xmitlist)
18651 				tcp_zcopy_notify(tcp);
18652 			else
18653 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18654 		}
18655 		nbp = bp->b_cont;
18656 		if (fix_xmitlist) {
18657 			head->b_prev = bp->b_prev;
18658 			head->b_next = bp->b_next;
18659 			if (tcp->tcp_xmit_tail == bp)
18660 				tcp->tcp_xmit_tail = head;
18661 		}
18662 		bp->b_next = NULL;
18663 		bp->b_prev = NULL;
18664 		freeb(bp);
18665 	} else {
18666 		head = bp;
18667 		nbp = bp->b_cont;
18668 	}
18669 	tail = head;
18670 	while (nbp) {
18671 		if (IS_VMLOANED_MBLK(nbp)) {
18672 			TCP_STAT(tcps, tcp_zcopy_backoff);
18673 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18674 				tcp->tcp_xmit_zc_clean = B_FALSE;
18675 				tail->b_cont = nbp;
18676 				return (head);
18677 			}
18678 			tail = tail->b_cont;
18679 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18680 				if (fix_xmitlist)
18681 					tcp_zcopy_notify(tcp);
18682 				else
18683 					tail->b_datap->db_struioflag |=
18684 					    STRUIO_ZCNOTIFY;
18685 			}
18686 			bp = nbp;
18687 			nbp = nbp->b_cont;
18688 			if (fix_xmitlist) {
18689 				tail->b_prev = bp->b_prev;
18690 				tail->b_next = bp->b_next;
18691 				if (tcp->tcp_xmit_tail == bp)
18692 					tcp->tcp_xmit_tail = tail;
18693 			}
18694 			bp->b_next = NULL;
18695 			bp->b_prev = NULL;
18696 			freeb(bp);
18697 		} else {
18698 			tail->b_cont = nbp;
18699 			tail = nbp;
18700 			nbp = nbp->b_cont;
18701 		}
18702 	}
18703 	if (fix_xmitlist) {
18704 		tcp->tcp_xmit_last = tail;
18705 		tcp->tcp_xmit_zc_clean = B_TRUE;
18706 	}
18707 	return (head);
18708 }
18709 
18710 static void
18711 tcp_zcopy_notify(tcp_t *tcp)
18712 {
18713 	struct stdata	*stp;
18714 
18715 	if (tcp->tcp_detached)
18716 		return;
18717 	stp = STREAM(tcp->tcp_rq);
18718 	mutex_enter(&stp->sd_lock);
18719 	stp->sd_flag |= STZCNOTIFY;
18720 	cv_broadcast(&stp->sd_zcopy_wait);
18721 	mutex_exit(&stp->sd_lock);
18722 }
18723 
18724 static boolean_t
18725 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18726 {
18727 	ire_t	*ire;
18728 	conn_t	*connp = tcp->tcp_connp;
18729 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18730 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18731 
18732 	mutex_enter(&connp->conn_lock);
18733 	ire = connp->conn_ire_cache;
18734 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18735 
18736 	if ((ire != NULL) &&
18737 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18738 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18739 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18740 		IRE_REFHOLD(ire);
18741 		mutex_exit(&connp->conn_lock);
18742 	} else {
18743 		boolean_t cached = B_FALSE;
18744 		ts_label_t *tsl;
18745 
18746 		/* force a recheck later on */
18747 		tcp->tcp_ire_ill_check_done = B_FALSE;
18748 
18749 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18750 		connp->conn_ire_cache = NULL;
18751 		mutex_exit(&connp->conn_lock);
18752 
18753 		if (ire != NULL)
18754 			IRE_REFRELE_NOTR(ire);
18755 
18756 		tsl = crgetlabel(CONN_CRED(connp));
18757 		ire = (dst ?
18758 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18759 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18760 		    connp->conn_zoneid, tsl, ipst));
18761 
18762 		if (ire == NULL) {
18763 			TCP_STAT(tcps, tcp_ire_null);
18764 			return (B_FALSE);
18765 		}
18766 
18767 		IRE_REFHOLD_NOTR(ire);
18768 		/*
18769 		 * Since we are inside the squeue, there cannot be another
18770 		 * thread in TCP trying to set the conn_ire_cache now.  The
18771 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18772 		 * unplumb thread has not yet started cleaning up the conns.
18773 		 * Hence we don't need to grab the conn lock.
18774 		 */
18775 		if (CONN_CACHE_IRE(connp)) {
18776 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18777 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18778 				TCP_CHECK_IREINFO(tcp, ire);
18779 				connp->conn_ire_cache = ire;
18780 				cached = B_TRUE;
18781 			}
18782 			rw_exit(&ire->ire_bucket->irb_lock);
18783 		}
18784 
18785 		/*
18786 		 * We can continue to use the ire but since it was
18787 		 * not cached, we should drop the extra reference.
18788 		 */
18789 		if (!cached)
18790 			IRE_REFRELE_NOTR(ire);
18791 
18792 		/*
18793 		 * Rampart note: no need to select a new label here, since
18794 		 * labels are not allowed to change during the life of a TCP
18795 		 * connection.
18796 		 */
18797 	}
18798 
18799 	*irep = ire;
18800 
18801 	return (B_TRUE);
18802 }
18803 
18804 /*
18805  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18806  *
18807  * 0 = success;
18808  * 1 = failed to find ire and ill.
18809  */
18810 static boolean_t
18811 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18812 {
18813 	ipha_t		*ipha;
18814 	ipaddr_t	dst;
18815 	ire_t		*ire;
18816 	ill_t		*ill;
18817 	conn_t		*connp = tcp->tcp_connp;
18818 	mblk_t		*ire_fp_mp;
18819 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18820 
18821 	if (mp != NULL)
18822 		ipha = (ipha_t *)mp->b_rptr;
18823 	else
18824 		ipha = tcp->tcp_ipha;
18825 	dst = ipha->ipha_dst;
18826 
18827 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18828 		return (B_FALSE);
18829 
18830 	if ((ire->ire_flags & RTF_MULTIRT) ||
18831 	    (ire->ire_stq == NULL) ||
18832 	    (ire->ire_nce == NULL) ||
18833 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18834 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18835 		MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18836 		TCP_STAT(tcps, tcp_ip_ire_send);
18837 		IRE_REFRELE(ire);
18838 		return (B_FALSE);
18839 	}
18840 
18841 	ill = ire_to_ill(ire);
18842 	if (connp->conn_outgoing_ill != NULL) {
18843 		ill_t *conn_outgoing_ill = NULL;
18844 		/*
18845 		 * Choose a good ill in the group to send the packets on.
18846 		 */
18847 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18848 		ill = ire_to_ill(ire);
18849 	}
18850 	ASSERT(ill != NULL);
18851 
18852 	if (!tcp->tcp_ire_ill_check_done) {
18853 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18854 		tcp->tcp_ire_ill_check_done = B_TRUE;
18855 	}
18856 
18857 	*irep = ire;
18858 	*illp = ill;
18859 
18860 	return (B_TRUE);
18861 }
18862 
18863 static void
18864 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18865 {
18866 	ipha_t		*ipha;
18867 	ipaddr_t	src;
18868 	ipaddr_t	dst;
18869 	uint32_t	cksum;
18870 	ire_t		*ire;
18871 	uint16_t	*up;
18872 	ill_t		*ill;
18873 	conn_t		*connp = tcp->tcp_connp;
18874 	uint32_t	hcksum_txflags = 0;
18875 	mblk_t		*ire_fp_mp;
18876 	uint_t		ire_fp_mp_len;
18877 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18878 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18879 
18880 	ASSERT(DB_TYPE(mp) == M_DATA);
18881 
18882 	if (DB_CRED(mp) == NULL)
18883 		mblk_setcred(mp, CONN_CRED(connp));
18884 
18885 	ipha = (ipha_t *)mp->b_rptr;
18886 	src = ipha->ipha_src;
18887 	dst = ipha->ipha_dst;
18888 
18889 	/*
18890 	 * Drop off fast path for IPv6 and also if options are present or
18891 	 * we need to resolve a TS label.
18892 	 */
18893 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18894 	    !IPCL_IS_CONNECTED(connp) ||
18895 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18896 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18897 	    !connp->conn_ulp_labeled ||
18898 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18899 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18900 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18901 		if (tcp->tcp_snd_zcopy_aware)
18902 			mp = tcp_zcopy_disable(tcp, mp);
18903 		TCP_STAT(tcps, tcp_ip_send);
18904 		CALL_IP_WPUT(connp, q, mp);
18905 		return;
18906 	}
18907 
18908 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18909 		if (tcp->tcp_snd_zcopy_aware)
18910 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18911 		CALL_IP_WPUT(connp, q, mp);
18912 		return;
18913 	}
18914 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18915 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18916 
18917 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18918 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18919 #ifndef _BIG_ENDIAN
18920 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18921 #endif
18922 
18923 	/*
18924 	 * Check to see if we need to re-enable LSO/MDT for this connection
18925 	 * because it was previously disabled due to changes in the ill;
18926 	 * note that by doing it here, this re-enabling only applies when
18927 	 * the packet is not dispatched through CALL_IP_WPUT().
18928 	 *
18929 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18930 	 * case, since that's how we ended up here.  For IPv6, we do the
18931 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18932 	 */
18933 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18934 		/*
18935 		 * Restore LSO for this connection, so that next time around
18936 		 * it is eligible to go through tcp_lsosend() path again.
18937 		 */
18938 		TCP_STAT(tcps, tcp_lso_enabled);
18939 		tcp->tcp_lso = B_TRUE;
18940 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18941 		    "interface %s\n", (void *)connp, ill->ill_name));
18942 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18943 		/*
18944 		 * Restore MDT for this connection, so that next time around
18945 		 * it is eligible to go through tcp_multisend() path again.
18946 		 */
18947 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18948 		tcp->tcp_mdt = B_TRUE;
18949 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18950 		    "interface %s\n", (void *)connp, ill->ill_name));
18951 	}
18952 
18953 	if (tcp->tcp_snd_zcopy_aware) {
18954 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18955 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18956 			mp = tcp_zcopy_disable(tcp, mp);
18957 		/*
18958 		 * we shouldn't need to reset ipha as the mp containing
18959 		 * ipha should never be a zero-copy mp.
18960 		 */
18961 	}
18962 
18963 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18964 		ASSERT(ill->ill_hcksum_capab != NULL);
18965 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18966 	}
18967 
18968 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18969 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18970 
18971 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18972 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18973 
18974 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18975 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18976 
18977 	/* Software checksum? */
18978 	if (DB_CKSUMFLAGS(mp) == 0) {
18979 		TCP_STAT(tcps, tcp_out_sw_cksum);
18980 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18981 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18982 	}
18983 
18984 	ipha->ipha_fragment_offset_and_flags |=
18985 	    (uint32_t)htons(ire->ire_frag_flag);
18986 
18987 	/* Calculate IP header checksum if hardware isn't capable */
18988 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18989 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18990 		    ((uint16_t *)ipha)[4]);
18991 	}
18992 
18993 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18994 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18995 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18996 
18997 	UPDATE_OB_PKT_COUNT(ire);
18998 	ire->ire_last_used_time = lbolt;
18999 
19000 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19001 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19002 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19003 	    ntohs(ipha->ipha_length));
19004 
19005 	if (ILL_DLS_CAPABLE(ill)) {
19006 		/*
19007 		 * Send the packet directly to DLD, where it may be queued
19008 		 * depending on the availability of transmit resources at
19009 		 * the media layer.
19010 		 */
19011 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19012 	} else {
19013 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19014 		DTRACE_PROBE4(ip4__physical__out__start,
19015 		    ill_t *, NULL, ill_t *, out_ill,
19016 		    ipha_t *, ipha, mblk_t *, mp);
19017 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19018 		    ipst->ips_ipv4firewall_physical_out,
19019 		    NULL, out_ill, ipha, mp, mp, ipst);
19020 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19021 		if (mp != NULL)
19022 			putnext(ire->ire_stq, mp);
19023 	}
19024 	IRE_REFRELE(ire);
19025 }
19026 
19027 /*
19028  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19029  * if the receiver shrinks the window, i.e. moves the right window to the
19030  * left, the we should not send new data, but should retransmit normally the
19031  * old unacked data between suna and suna + swnd. We might has sent data
19032  * that is now outside the new window, pretend that we didn't send  it.
19033  */
19034 static void
19035 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19036 {
19037 	uint32_t	snxt = tcp->tcp_snxt;
19038 	mblk_t		*xmit_tail;
19039 	int32_t		offset;
19040 
19041 	ASSERT(shrunk_count > 0);
19042 
19043 	/* Pretend we didn't send the data outside the window */
19044 	snxt -= shrunk_count;
19045 
19046 	/* Get the mblk and the offset in it per the shrunk window */
19047 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19048 
19049 	ASSERT(xmit_tail != NULL);
19050 
19051 	/* Reset all the values per the now shrunk window */
19052 	tcp->tcp_snxt = snxt;
19053 	tcp->tcp_xmit_tail = xmit_tail;
19054 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19055 	    offset;
19056 	tcp->tcp_unsent += shrunk_count;
19057 
19058 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19059 		/*
19060 		 * Make sure the timer is running so that we will probe a zero
19061 		 * window.
19062 		 */
19063 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19064 }
19065 
19066 
19067 /*
19068  * The TCP normal data output path.
19069  * NOTE: the logic of the fast path is duplicated from this function.
19070  */
19071 static void
19072 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19073 {
19074 	int		len;
19075 	mblk_t		*local_time;
19076 	mblk_t		*mp1;
19077 	uint32_t	snxt;
19078 	int		tail_unsent;
19079 	int		tcpstate;
19080 	int		usable = 0;
19081 	mblk_t		*xmit_tail;
19082 	queue_t		*q = tcp->tcp_wq;
19083 	int32_t		mss;
19084 	int32_t		num_sack_blk = 0;
19085 	int32_t		tcp_hdr_len;
19086 	int32_t		tcp_tcp_hdr_len;
19087 	int		mdt_thres;
19088 	int		rc;
19089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19090 	ip_stack_t	*ipst;
19091 
19092 	tcpstate = tcp->tcp_state;
19093 	if (mp == NULL) {
19094 		/*
19095 		 * tcp_wput_data() with NULL mp should only be called when
19096 		 * there is unsent data.
19097 		 */
19098 		ASSERT(tcp->tcp_unsent > 0);
19099 		/* Really tacky... but we need this for detached closes. */
19100 		len = tcp->tcp_unsent;
19101 		goto data_null;
19102 	}
19103 
19104 #if CCS_STATS
19105 	wrw_stats.tot.count++;
19106 	wrw_stats.tot.bytes += msgdsize(mp);
19107 #endif
19108 	ASSERT(mp->b_datap->db_type == M_DATA);
19109 	/*
19110 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19111 	 * or before a connection attempt has begun.
19112 	 */
19113 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19114 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19115 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19116 #ifdef DEBUG
19117 			cmn_err(CE_WARN,
19118 			    "tcp_wput_data: data after ordrel, %s",
19119 			    tcp_display(tcp, NULL,
19120 			    DISP_ADDR_AND_PORT));
19121 #else
19122 			if (tcp->tcp_debug) {
19123 				(void) strlog(TCP_MOD_ID, 0, 1,
19124 				    SL_TRACE|SL_ERROR,
19125 				    "tcp_wput_data: data after ordrel, %s\n",
19126 				    tcp_display(tcp, NULL,
19127 				    DISP_ADDR_AND_PORT));
19128 			}
19129 #endif /* DEBUG */
19130 		}
19131 		if (tcp->tcp_snd_zcopy_aware &&
19132 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19133 			tcp_zcopy_notify(tcp);
19134 		freemsg(mp);
19135 		mutex_enter(&tcp->tcp_non_sq_lock);
19136 		if (tcp->tcp_flow_stopped &&
19137 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19138 			tcp_clrqfull(tcp);
19139 		}
19140 		mutex_exit(&tcp->tcp_non_sq_lock);
19141 		return;
19142 	}
19143 
19144 	/* Strip empties */
19145 	for (;;) {
19146 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19147 		    (uintptr_t)INT_MAX);
19148 		len = (int)(mp->b_wptr - mp->b_rptr);
19149 		if (len > 0)
19150 			break;
19151 		mp1 = mp;
19152 		mp = mp->b_cont;
19153 		freeb(mp1);
19154 		if (!mp) {
19155 			return;
19156 		}
19157 	}
19158 
19159 	/* If we are the first on the list ... */
19160 	if (tcp->tcp_xmit_head == NULL) {
19161 		tcp->tcp_xmit_head = mp;
19162 		tcp->tcp_xmit_tail = mp;
19163 		tcp->tcp_xmit_tail_unsent = len;
19164 	} else {
19165 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19166 		struct datab *dp;
19167 
19168 		mp1 = tcp->tcp_xmit_last;
19169 		if (len < tcp_tx_pull_len &&
19170 		    (dp = mp1->b_datap)->db_ref == 1 &&
19171 		    dp->db_lim - mp1->b_wptr >= len) {
19172 			ASSERT(len > 0);
19173 			ASSERT(!mp1->b_cont);
19174 			if (len == 1) {
19175 				*mp1->b_wptr++ = *mp->b_rptr;
19176 			} else {
19177 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19178 				mp1->b_wptr += len;
19179 			}
19180 			if (mp1 == tcp->tcp_xmit_tail)
19181 				tcp->tcp_xmit_tail_unsent += len;
19182 			mp1->b_cont = mp->b_cont;
19183 			if (tcp->tcp_snd_zcopy_aware &&
19184 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19185 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19186 			freeb(mp);
19187 			mp = mp1;
19188 		} else {
19189 			tcp->tcp_xmit_last->b_cont = mp;
19190 		}
19191 		len += tcp->tcp_unsent;
19192 	}
19193 
19194 	/* Tack on however many more positive length mblks we have */
19195 	if ((mp1 = mp->b_cont) != NULL) {
19196 		do {
19197 			int tlen;
19198 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19199 			    (uintptr_t)INT_MAX);
19200 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19201 			if (tlen <= 0) {
19202 				mp->b_cont = mp1->b_cont;
19203 				freeb(mp1);
19204 			} else {
19205 				len += tlen;
19206 				mp = mp1;
19207 			}
19208 		} while ((mp1 = mp->b_cont) != NULL);
19209 	}
19210 	tcp->tcp_xmit_last = mp;
19211 	tcp->tcp_unsent = len;
19212 
19213 	if (urgent)
19214 		usable = 1;
19215 
19216 data_null:
19217 	snxt = tcp->tcp_snxt;
19218 	xmit_tail = tcp->tcp_xmit_tail;
19219 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19220 
19221 	/*
19222 	 * Note that tcp_mss has been adjusted to take into account the
19223 	 * timestamp option if applicable.  Because SACK options do not
19224 	 * appear in every TCP segments and they are of variable lengths,
19225 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19226 	 * the actual segment length when we need to send a segment which
19227 	 * includes SACK options.
19228 	 */
19229 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19230 		int32_t	opt_len;
19231 
19232 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19233 		    tcp->tcp_num_sack_blk);
19234 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19235 		    2 + TCPOPT_HEADER_LEN;
19236 		mss = tcp->tcp_mss - opt_len;
19237 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19238 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19239 	} else {
19240 		mss = tcp->tcp_mss;
19241 		tcp_hdr_len = tcp->tcp_hdr_len;
19242 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19243 	}
19244 
19245 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19246 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19247 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19248 	}
19249 	if (tcpstate == TCPS_SYN_RCVD) {
19250 		/*
19251 		 * The three-way connection establishment handshake is not
19252 		 * complete yet. We want to queue the data for transmission
19253 		 * after entering ESTABLISHED state (RFC793). A jump to
19254 		 * "done" label effectively leaves data on the queue.
19255 		 */
19256 		goto done;
19257 	} else {
19258 		int usable_r;
19259 
19260 		/*
19261 		 * In the special case when cwnd is zero, which can only
19262 		 * happen if the connection is ECN capable, return now.
19263 		 * New segments is sent using tcp_timer().  The timer
19264 		 * is set in tcp_rput_data().
19265 		 */
19266 		if (tcp->tcp_cwnd == 0) {
19267 			/*
19268 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19269 			 * finished.
19270 			 */
19271 			ASSERT(tcp->tcp_ecn_ok ||
19272 			    tcp->tcp_state < TCPS_ESTABLISHED);
19273 			return;
19274 		}
19275 
19276 		/* NOTE: trouble if xmitting while SYN not acked? */
19277 		usable_r = snxt - tcp->tcp_suna;
19278 		usable_r = tcp->tcp_swnd - usable_r;
19279 
19280 		/*
19281 		 * Check if the receiver has shrunk the window.  If
19282 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19283 		 * cannot be set as there is unsent data, so FIN cannot
19284 		 * be sent out.  Otherwise, we need to take into account
19285 		 * of FIN as it consumes an "invisible" sequence number.
19286 		 */
19287 		ASSERT(tcp->tcp_fin_sent == 0);
19288 		if (usable_r < 0) {
19289 			/*
19290 			 * The receiver has shrunk the window and we have sent
19291 			 * -usable_r date beyond the window, re-adjust.
19292 			 *
19293 			 * If TCP window scaling is enabled, there can be
19294 			 * round down error as the advertised receive window
19295 			 * is actually right shifted n bits.  This means that
19296 			 * the lower n bits info is wiped out.  It will look
19297 			 * like the window is shrunk.  Do a check here to
19298 			 * see if the shrunk amount is actually within the
19299 			 * error in window calculation.  If it is, just
19300 			 * return.  Note that this check is inside the
19301 			 * shrunk window check.  This makes sure that even
19302 			 * though tcp_process_shrunk_swnd() is not called,
19303 			 * we will stop further processing.
19304 			 */
19305 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19306 				tcp_process_shrunk_swnd(tcp, -usable_r);
19307 			}
19308 			return;
19309 		}
19310 
19311 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19312 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19313 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19314 
19315 		/* usable = MIN(usable, unsent) */
19316 		if (usable_r > len)
19317 			usable_r = len;
19318 
19319 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19320 		if (usable_r > 0) {
19321 			usable = usable_r;
19322 		} else {
19323 			/* Bypass all other unnecessary processing. */
19324 			goto done;
19325 		}
19326 	}
19327 
19328 	local_time = (mblk_t *)lbolt;
19329 
19330 	/*
19331 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19332 	 * BSD.  This is more in line with the true intent of Nagle.
19333 	 *
19334 	 * The conditions are:
19335 	 * 1. The amount of unsent data (or amount of data which can be
19336 	 *    sent, whichever is smaller) is less than Nagle limit.
19337 	 * 2. The last sent size is also less than Nagle limit.
19338 	 * 3. There is unack'ed data.
19339 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19340 	 *    Nagle algorithm.  This reduces the probability that urgent
19341 	 *    bytes get "merged" together.
19342 	 * 5. The app has not closed the connection.  This eliminates the
19343 	 *    wait time of the receiving side waiting for the last piece of
19344 	 *    (small) data.
19345 	 *
19346 	 * If all are satisified, exit without sending anything.  Note
19347 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19348 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19349 	 * 4095).
19350 	 */
19351 	if (usable < (int)tcp->tcp_naglim &&
19352 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19353 	    snxt != tcp->tcp_suna &&
19354 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19355 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19356 		goto done;
19357 	}
19358 
19359 	if (tcp->tcp_cork) {
19360 		/*
19361 		 * if the tcp->tcp_cork option is set, then we have to force
19362 		 * TCP not to send partial segment (smaller than MSS bytes).
19363 		 * We are calculating the usable now based on full mss and
19364 		 * will save the rest of remaining data for later.
19365 		 */
19366 		if (usable < mss)
19367 			goto done;
19368 		usable = (usable / mss) * mss;
19369 	}
19370 
19371 	/* Update the latest receive window size in TCP header. */
19372 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19373 	    tcp->tcp_tcph->th_win);
19374 
19375 	/*
19376 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19377 	 *
19378 	 * 1. Simple TCP/IP{v4,v6} (no options).
19379 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19380 	 * 3. If the TCP connection is in ESTABLISHED state.
19381 	 * 4. The TCP is not detached.
19382 	 *
19383 	 * If any of the above conditions have changed during the
19384 	 * connection, stop using LSO/MDT and restore the stream head
19385 	 * parameters accordingly.
19386 	 */
19387 	ipst = tcps->tcps_netstack->netstack_ip;
19388 
19389 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19390 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19391 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19392 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19393 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19394 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19395 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19396 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19397 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19398 		if (tcp->tcp_lso) {
19399 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19400 			tcp->tcp_lso = B_FALSE;
19401 		} else {
19402 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19403 			tcp->tcp_mdt = B_FALSE;
19404 		}
19405 
19406 		/* Anything other than detached is considered pathological */
19407 		if (!TCP_IS_DETACHED(tcp)) {
19408 			if (tcp->tcp_lso)
19409 				TCP_STAT(tcps, tcp_lso_disabled);
19410 			else
19411 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19412 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19413 		}
19414 	}
19415 
19416 	/* Use MDT if sendable amount is greater than the threshold */
19417 	if (tcp->tcp_mdt &&
19418 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19419 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19420 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19421 	    (tcp->tcp_valid_bits == 0 ||
19422 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19423 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19424 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19425 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19426 		    local_time, mdt_thres);
19427 	} else {
19428 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19429 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19430 		    local_time, INT_MAX);
19431 	}
19432 
19433 	/* Pretend that all we were trying to send really got sent */
19434 	if (rc < 0 && tail_unsent < 0) {
19435 		do {
19436 			xmit_tail = xmit_tail->b_cont;
19437 			xmit_tail->b_prev = local_time;
19438 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19439 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19440 			tail_unsent += (int)(xmit_tail->b_wptr -
19441 			    xmit_tail->b_rptr);
19442 		} while (tail_unsent < 0);
19443 	}
19444 done:;
19445 	tcp->tcp_xmit_tail = xmit_tail;
19446 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19447 	len = tcp->tcp_snxt - snxt;
19448 	if (len) {
19449 		/*
19450 		 * If new data was sent, need to update the notsack
19451 		 * list, which is, afterall, data blocks that have
19452 		 * not been sack'ed by the receiver.  New data is
19453 		 * not sack'ed.
19454 		 */
19455 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19456 			/* len is a negative value. */
19457 			tcp->tcp_pipe -= len;
19458 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19459 			    tcp->tcp_snxt, snxt,
19460 			    &(tcp->tcp_num_notsack_blk),
19461 			    &(tcp->tcp_cnt_notsack_list));
19462 		}
19463 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19464 		tcp->tcp_rack = tcp->tcp_rnxt;
19465 		tcp->tcp_rack_cnt = 0;
19466 		if ((snxt + len) == tcp->tcp_suna) {
19467 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19468 		}
19469 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19470 		/*
19471 		 * Didn't send anything. Make sure the timer is running
19472 		 * so that we will probe a zero window.
19473 		 */
19474 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19475 	}
19476 	/* Note that len is the amount we just sent but with a negative sign */
19477 	tcp->tcp_unsent += len;
19478 	mutex_enter(&tcp->tcp_non_sq_lock);
19479 	if (tcp->tcp_flow_stopped) {
19480 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19481 			tcp_clrqfull(tcp);
19482 		}
19483 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19484 		tcp_setqfull(tcp);
19485 	}
19486 	mutex_exit(&tcp->tcp_non_sq_lock);
19487 }
19488 
19489 /*
19490  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19491  * outgoing TCP header with the template header, as well as other
19492  * options such as time-stamp, ECN and/or SACK.
19493  */
19494 static void
19495 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19496 {
19497 	tcph_t *tcp_tmpl, *tcp_h;
19498 	uint32_t *dst, *src;
19499 	int hdrlen;
19500 
19501 	ASSERT(OK_32PTR(rptr));
19502 
19503 	/* Template header */
19504 	tcp_tmpl = tcp->tcp_tcph;
19505 
19506 	/* Header of outgoing packet */
19507 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19508 
19509 	/* dst and src are opaque 32-bit fields, used for copying */
19510 	dst = (uint32_t *)rptr;
19511 	src = (uint32_t *)tcp->tcp_iphc;
19512 	hdrlen = tcp->tcp_hdr_len;
19513 
19514 	/* Fill time-stamp option if needed */
19515 	if (tcp->tcp_snd_ts_ok) {
19516 		U32_TO_BE32((uint32_t)now,
19517 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19518 		U32_TO_BE32(tcp->tcp_ts_recent,
19519 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19520 	} else {
19521 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19522 	}
19523 
19524 	/*
19525 	 * Copy the template header; is this really more efficient than
19526 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19527 	 * but perhaps not for other scenarios.
19528 	 */
19529 	dst[0] = src[0];
19530 	dst[1] = src[1];
19531 	dst[2] = src[2];
19532 	dst[3] = src[3];
19533 	dst[4] = src[4];
19534 	dst[5] = src[5];
19535 	dst[6] = src[6];
19536 	dst[7] = src[7];
19537 	dst[8] = src[8];
19538 	dst[9] = src[9];
19539 	if (hdrlen -= 40) {
19540 		hdrlen >>= 2;
19541 		dst += 10;
19542 		src += 10;
19543 		do {
19544 			*dst++ = *src++;
19545 		} while (--hdrlen);
19546 	}
19547 
19548 	/*
19549 	 * Set the ECN info in the TCP header if it is not a zero
19550 	 * window probe.  Zero window probe is only sent in
19551 	 * tcp_wput_data() and tcp_timer().
19552 	 */
19553 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19554 		SET_ECT(tcp, rptr);
19555 
19556 		if (tcp->tcp_ecn_echo_on)
19557 			tcp_h->th_flags[0] |= TH_ECE;
19558 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19559 			tcp_h->th_flags[0] |= TH_CWR;
19560 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19561 		}
19562 	}
19563 
19564 	/* Fill in SACK options */
19565 	if (num_sack_blk > 0) {
19566 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19567 		sack_blk_t *tmp;
19568 		int32_t	i;
19569 
19570 		wptr[0] = TCPOPT_NOP;
19571 		wptr[1] = TCPOPT_NOP;
19572 		wptr[2] = TCPOPT_SACK;
19573 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19574 		    sizeof (sack_blk_t);
19575 		wptr += TCPOPT_REAL_SACK_LEN;
19576 
19577 		tmp = tcp->tcp_sack_list;
19578 		for (i = 0; i < num_sack_blk; i++) {
19579 			U32_TO_BE32(tmp[i].begin, wptr);
19580 			wptr += sizeof (tcp_seq);
19581 			U32_TO_BE32(tmp[i].end, wptr);
19582 			wptr += sizeof (tcp_seq);
19583 		}
19584 		tcp_h->th_offset_and_rsrvd[0] +=
19585 		    ((num_sack_blk * 2 + 1) << 4);
19586 	}
19587 }
19588 
19589 /*
19590  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19591  * the destination address and SAP attribute, and if necessary, the
19592  * hardware checksum offload attribute to a Multidata message.
19593  */
19594 static int
19595 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19596     const uint32_t start, const uint32_t stuff, const uint32_t end,
19597     const uint32_t flags, tcp_stack_t *tcps)
19598 {
19599 	/* Add global destination address & SAP attribute */
19600 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19601 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19602 		    "destination address+SAP\n"));
19603 
19604 		if (dlmp != NULL)
19605 			TCP_STAT(tcps, tcp_mdt_allocfail);
19606 		return (-1);
19607 	}
19608 
19609 	/* Add global hwcksum attribute */
19610 	if (hwcksum &&
19611 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19612 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19613 		    "checksum attribute\n"));
19614 
19615 		TCP_STAT(tcps, tcp_mdt_allocfail);
19616 		return (-1);
19617 	}
19618 
19619 	return (0);
19620 }
19621 
19622 /*
19623  * Smaller and private version of pdescinfo_t used specifically for TCP,
19624  * which allows for only two payload spans per packet.
19625  */
19626 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19627 
19628 /*
19629  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19630  * scheme, and returns one the following:
19631  *
19632  * -1 = failed allocation.
19633  *  0 = success; burst count reached, or usable send window is too small,
19634  *      and that we'd rather wait until later before sending again.
19635  */
19636 static int
19637 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19638     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19639     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19640     const int mdt_thres)
19641 {
19642 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19643 	multidata_t	*mmd;
19644 	uint_t		obsegs, obbytes, hdr_frag_sz;
19645 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19646 	int		num_burst_seg, max_pld;
19647 	pdesc_t		*pkt;
19648 	tcp_pdescinfo_t	tcp_pkt_info;
19649 	pdescinfo_t	*pkt_info;
19650 	int		pbuf_idx, pbuf_idx_nxt;
19651 	int		seg_len, len, spill, af;
19652 	boolean_t	add_buffer, zcopy, clusterwide;
19653 	boolean_t	buf_trunked = B_FALSE;
19654 	boolean_t	rconfirm = B_FALSE;
19655 	boolean_t	done = B_FALSE;
19656 	uint32_t	cksum;
19657 	uint32_t	hwcksum_flags;
19658 	ire_t		*ire = NULL;
19659 	ill_t		*ill;
19660 	ipha_t		*ipha;
19661 	ip6_t		*ip6h;
19662 	ipaddr_t	src, dst;
19663 	ill_zerocopy_capab_t *zc_cap = NULL;
19664 	uint16_t	*up;
19665 	int		err;
19666 	conn_t		*connp;
19667 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19668 	uchar_t		*pld_start;
19669 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19670 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19671 
19672 #ifdef	_BIG_ENDIAN
19673 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19674 #else
19675 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19676 #endif
19677 
19678 #define	PREP_NEW_MULTIDATA() {			\
19679 	mmd = NULL;				\
19680 	md_mp = md_hbuf = NULL;			\
19681 	cur_hdr_off = 0;			\
19682 	max_pld = tcp->tcp_mdt_max_pld;		\
19683 	pbuf_idx = pbuf_idx_nxt = -1;		\
19684 	add_buffer = B_TRUE;			\
19685 	zcopy = B_FALSE;			\
19686 }
19687 
19688 #define	PREP_NEW_PBUF() {			\
19689 	md_pbuf = md_pbuf_nxt = NULL;		\
19690 	pbuf_idx = pbuf_idx_nxt = -1;		\
19691 	cur_pld_off = 0;			\
19692 	first_snxt = *snxt;			\
19693 	ASSERT(*tail_unsent > 0);		\
19694 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19695 }
19696 
19697 	ASSERT(mdt_thres >= mss);
19698 	ASSERT(*usable > 0 && *usable > mdt_thres);
19699 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19700 	ASSERT(!TCP_IS_DETACHED(tcp));
19701 	ASSERT(tcp->tcp_valid_bits == 0 ||
19702 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19703 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19704 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19705 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19706 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19707 
19708 	connp = tcp->tcp_connp;
19709 	ASSERT(connp != NULL);
19710 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19711 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19712 
19713 	/*
19714 	 * Note that tcp will only declare at most 2 payload spans per
19715 	 * packet, which is much lower than the maximum allowable number
19716 	 * of packet spans per Multidata.  For this reason, we use the
19717 	 * privately declared and smaller descriptor info structure, in
19718 	 * order to save some stack space.
19719 	 */
19720 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19721 
19722 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19723 	if (af == AF_INET) {
19724 		dst = tcp->tcp_ipha->ipha_dst;
19725 		src = tcp->tcp_ipha->ipha_src;
19726 		ASSERT(!CLASSD(dst));
19727 	}
19728 	ASSERT(af == AF_INET ||
19729 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19730 
19731 	obsegs = obbytes = 0;
19732 	num_burst_seg = tcp->tcp_snd_burst;
19733 	md_mp_head = NULL;
19734 	PREP_NEW_MULTIDATA();
19735 
19736 	/*
19737 	 * Before we go on further, make sure there is an IRE that we can
19738 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19739 	 * in proceeding any further, and we should just hand everything
19740 	 * off to the legacy path.
19741 	 */
19742 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19743 		goto legacy_send_no_md;
19744 
19745 	ASSERT(ire != NULL);
19746 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19747 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19748 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19749 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19750 	/*
19751 	 * If we do support loopback for MDT (which requires modifications
19752 	 * to the receiving paths), the following assertions should go away,
19753 	 * and we would be sending the Multidata to loopback conn later on.
19754 	 */
19755 	ASSERT(!IRE_IS_LOCAL(ire));
19756 	ASSERT(ire->ire_stq != NULL);
19757 
19758 	ill = ire_to_ill(ire);
19759 	ASSERT(ill != NULL);
19760 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19761 
19762 	if (!tcp->tcp_ire_ill_check_done) {
19763 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19764 		tcp->tcp_ire_ill_check_done = B_TRUE;
19765 	}
19766 
19767 	/*
19768 	 * If the underlying interface conditions have changed, or if the
19769 	 * new interface does not support MDT, go back to legacy path.
19770 	 */
19771 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19772 		/* don't go through this path anymore for this connection */
19773 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19774 		tcp->tcp_mdt = B_FALSE;
19775 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19776 		    "interface %s\n", (void *)connp, ill->ill_name));
19777 		/* IRE will be released prior to returning */
19778 		goto legacy_send_no_md;
19779 	}
19780 
19781 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19782 		zc_cap = ill->ill_zerocopy_capab;
19783 
19784 	/*
19785 	 * Check if we can take tcp fast-path. Note that "incomplete"
19786 	 * ire's (where the link-layer for next hop is not resolved
19787 	 * or where the fast-path header in nce_fp_mp is not available
19788 	 * yet) are sent down the legacy (slow) path.
19789 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19790 	 */
19791 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19792 		/* IRE will be released prior to returning */
19793 		goto legacy_send_no_md;
19794 	}
19795 
19796 	/* go to legacy path if interface doesn't support zerocopy */
19797 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19798 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19799 		/* IRE will be released prior to returning */
19800 		goto legacy_send_no_md;
19801 	}
19802 
19803 	/* does the interface support hardware checksum offload? */
19804 	hwcksum_flags = 0;
19805 	if (ILL_HCKSUM_CAPABLE(ill) &&
19806 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19807 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19808 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19809 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19810 		    HCKSUM_IPHDRCKSUM)
19811 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19812 
19813 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19814 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19815 			hwcksum_flags |= HCK_FULLCKSUM;
19816 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19817 		    HCKSUM_INET_PARTIAL)
19818 			hwcksum_flags |= HCK_PARTIALCKSUM;
19819 	}
19820 
19821 	/*
19822 	 * Each header fragment consists of the leading extra space,
19823 	 * followed by the TCP/IP header, and the trailing extra space.
19824 	 * We make sure that each header fragment begins on a 32-bit
19825 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19826 	 * aligned in tcp_mdt_update).
19827 	 */
19828 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19829 	    tcp->tcp_mdt_hdr_tail), 4);
19830 
19831 	/* are we starting from the beginning of data block? */
19832 	if (*tail_unsent == 0) {
19833 		*xmit_tail = (*xmit_tail)->b_cont;
19834 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19835 		*tail_unsent = (int)MBLKL(*xmit_tail);
19836 	}
19837 
19838 	/*
19839 	 * Here we create one or more Multidata messages, each made up of
19840 	 * one header buffer and up to N payload buffers.  This entire
19841 	 * operation is done within two loops:
19842 	 *
19843 	 * The outer loop mostly deals with creating the Multidata message,
19844 	 * as well as the header buffer that gets added to it.  It also
19845 	 * links the Multidata messages together such that all of them can
19846 	 * be sent down to the lower layer in a single putnext call; this
19847 	 * linking behavior depends on the tcp_mdt_chain tunable.
19848 	 *
19849 	 * The inner loop takes an existing Multidata message, and adds
19850 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19851 	 * packetizes those buffers by filling up the corresponding header
19852 	 * buffer fragments with the proper IP and TCP headers, and by
19853 	 * describing the layout of each packet in the packet descriptors
19854 	 * that get added to the Multidata.
19855 	 */
19856 	do {
19857 		/*
19858 		 * If usable send window is too small, or data blocks in
19859 		 * transmit list are smaller than our threshold (i.e. app
19860 		 * performs large writes followed by small ones), we hand
19861 		 * off the control over to the legacy path.  Note that we'll
19862 		 * get back the control once it encounters a large block.
19863 		 */
19864 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19865 		    (*xmit_tail)->b_cont != NULL &&
19866 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19867 			/* send down what we've got so far */
19868 			if (md_mp_head != NULL) {
19869 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19870 				    obsegs, obbytes, &rconfirm);
19871 			}
19872 			/*
19873 			 * Pass control over to tcp_send(), but tell it to
19874 			 * return to us once a large-size transmission is
19875 			 * possible.
19876 			 */
19877 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19878 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19879 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19880 			    tail_unsent, xmit_tail, local_time,
19881 			    mdt_thres)) <= 0) {
19882 				/* burst count reached, or alloc failed */
19883 				IRE_REFRELE(ire);
19884 				return (err);
19885 			}
19886 
19887 			/* tcp_send() may have sent everything, so check */
19888 			if (*usable <= 0) {
19889 				IRE_REFRELE(ire);
19890 				return (0);
19891 			}
19892 
19893 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19894 			/*
19895 			 * We may have delivered the Multidata, so make sure
19896 			 * to re-initialize before the next round.
19897 			 */
19898 			md_mp_head = NULL;
19899 			obsegs = obbytes = 0;
19900 			num_burst_seg = tcp->tcp_snd_burst;
19901 			PREP_NEW_MULTIDATA();
19902 
19903 			/* are we starting from the beginning of data block? */
19904 			if (*tail_unsent == 0) {
19905 				*xmit_tail = (*xmit_tail)->b_cont;
19906 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19907 				    (uintptr_t)INT_MAX);
19908 				*tail_unsent = (int)MBLKL(*xmit_tail);
19909 			}
19910 		}
19911 
19912 		/*
19913 		 * max_pld limits the number of mblks in tcp's transmit
19914 		 * queue that can be added to a Multidata message.  Once
19915 		 * this counter reaches zero, no more additional mblks
19916 		 * can be added to it.  What happens afterwards depends
19917 		 * on whether or not we are set to chain the Multidata
19918 		 * messages.  If we are to link them together, reset
19919 		 * max_pld to its original value (tcp_mdt_max_pld) and
19920 		 * prepare to create a new Multidata message which will
19921 		 * get linked to md_mp_head.  Else, leave it alone and
19922 		 * let the inner loop break on its own.
19923 		 */
19924 		if (tcp_mdt_chain && max_pld == 0)
19925 			PREP_NEW_MULTIDATA();
19926 
19927 		/* adding a payload buffer; re-initialize values */
19928 		if (add_buffer)
19929 			PREP_NEW_PBUF();
19930 
19931 		/*
19932 		 * If we don't have a Multidata, either because we just
19933 		 * (re)entered this outer loop, or after we branched off
19934 		 * to tcp_send above, setup the Multidata and header
19935 		 * buffer to be used.
19936 		 */
19937 		if (md_mp == NULL) {
19938 			int md_hbuflen;
19939 			uint32_t start, stuff;
19940 
19941 			/*
19942 			 * Calculate Multidata header buffer size large enough
19943 			 * to hold all of the headers that can possibly be
19944 			 * sent at this moment.  We'd rather over-estimate
19945 			 * the size than running out of space; this is okay
19946 			 * since this buffer is small anyway.
19947 			 */
19948 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19949 
19950 			/*
19951 			 * Start and stuff offset for partial hardware
19952 			 * checksum offload; these are currently for IPv4.
19953 			 * For full checksum offload, they are set to zero.
19954 			 */
19955 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19956 				if (af == AF_INET) {
19957 					start = IP_SIMPLE_HDR_LENGTH;
19958 					stuff = IP_SIMPLE_HDR_LENGTH +
19959 					    TCP_CHECKSUM_OFFSET;
19960 				} else {
19961 					start = IPV6_HDR_LEN;
19962 					stuff = IPV6_HDR_LEN +
19963 					    TCP_CHECKSUM_OFFSET;
19964 				}
19965 			} else {
19966 				start = stuff = 0;
19967 			}
19968 
19969 			/*
19970 			 * Create the header buffer, Multidata, as well as
19971 			 * any necessary attributes (destination address,
19972 			 * SAP and hardware checksum offload) that should
19973 			 * be associated with the Multidata message.
19974 			 */
19975 			ASSERT(cur_hdr_off == 0);
19976 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19977 			    ((md_hbuf->b_wptr += md_hbuflen),
19978 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19979 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19980 			    /* fastpath mblk */
19981 			    ire->ire_nce->nce_res_mp,
19982 			    /* hardware checksum enabled */
19983 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19984 			    /* hardware checksum offsets */
19985 			    start, stuff, 0,
19986 			    /* hardware checksum flag */
19987 			    hwcksum_flags, tcps) != 0)) {
19988 legacy_send:
19989 				if (md_mp != NULL) {
19990 					/* Unlink message from the chain */
19991 					if (md_mp_head != NULL) {
19992 						err = (intptr_t)rmvb(md_mp_head,
19993 						    md_mp);
19994 						/*
19995 						 * We can't assert that rmvb
19996 						 * did not return -1, since we
19997 						 * may get here before linkb
19998 						 * happens.  We do, however,
19999 						 * check if we just removed the
20000 						 * only element in the list.
20001 						 */
20002 						if (err == 0)
20003 							md_mp_head = NULL;
20004 					}
20005 					/* md_hbuf gets freed automatically */
20006 					TCP_STAT(tcps, tcp_mdt_discarded);
20007 					freeb(md_mp);
20008 				} else {
20009 					/* Either allocb or mmd_alloc failed */
20010 					TCP_STAT(tcps, tcp_mdt_allocfail);
20011 					if (md_hbuf != NULL)
20012 						freeb(md_hbuf);
20013 				}
20014 
20015 				/* send down what we've got so far */
20016 				if (md_mp_head != NULL) {
20017 					tcp_multisend_data(tcp, ire, ill,
20018 					    md_mp_head, obsegs, obbytes,
20019 					    &rconfirm);
20020 				}
20021 legacy_send_no_md:
20022 				if (ire != NULL)
20023 					IRE_REFRELE(ire);
20024 				/*
20025 				 * Too bad; let the legacy path handle this.
20026 				 * We specify INT_MAX for the threshold, since
20027 				 * we gave up with the Multidata processings
20028 				 * and let the old path have it all.
20029 				 */
20030 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20031 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20032 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20033 				    snxt, tail_unsent, xmit_tail, local_time,
20034 				    INT_MAX));
20035 			}
20036 
20037 			/* link to any existing ones, if applicable */
20038 			TCP_STAT(tcps, tcp_mdt_allocd);
20039 			if (md_mp_head == NULL) {
20040 				md_mp_head = md_mp;
20041 			} else if (tcp_mdt_chain) {
20042 				TCP_STAT(tcps, tcp_mdt_linked);
20043 				linkb(md_mp_head, md_mp);
20044 			}
20045 		}
20046 
20047 		ASSERT(md_mp_head != NULL);
20048 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20049 		ASSERT(md_mp != NULL && mmd != NULL);
20050 		ASSERT(md_hbuf != NULL);
20051 
20052 		/*
20053 		 * Packetize the transmittable portion of the data block;
20054 		 * each data block is essentially added to the Multidata
20055 		 * as a payload buffer.  We also deal with adding more
20056 		 * than one payload buffers, which happens when the remaining
20057 		 * packetized portion of the current payload buffer is less
20058 		 * than MSS, while the next data block in transmit queue
20059 		 * has enough data to make up for one.  This "spillover"
20060 		 * case essentially creates a split-packet, where portions
20061 		 * of the packet's payload fragments may span across two
20062 		 * virtually discontiguous address blocks.
20063 		 */
20064 		seg_len = mss;
20065 		do {
20066 			len = seg_len;
20067 
20068 			ASSERT(len > 0);
20069 			ASSERT(max_pld >= 0);
20070 			ASSERT(!add_buffer || cur_pld_off == 0);
20071 
20072 			/*
20073 			 * First time around for this payload buffer; note
20074 			 * in the case of a spillover, the following has
20075 			 * been done prior to adding the split-packet
20076 			 * descriptor to Multidata, and we don't want to
20077 			 * repeat the process.
20078 			 */
20079 			if (add_buffer) {
20080 				ASSERT(mmd != NULL);
20081 				ASSERT(md_pbuf == NULL);
20082 				ASSERT(md_pbuf_nxt == NULL);
20083 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20084 
20085 				/*
20086 				 * Have we reached the limit?  We'd get to
20087 				 * this case when we're not chaining the
20088 				 * Multidata messages together, and since
20089 				 * we're done, terminate this loop.
20090 				 */
20091 				if (max_pld == 0)
20092 					break; /* done */
20093 
20094 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20095 					TCP_STAT(tcps, tcp_mdt_allocfail);
20096 					goto legacy_send; /* out_of_mem */
20097 				}
20098 
20099 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20100 				    zc_cap != NULL) {
20101 					if (!ip_md_zcopy_attr(mmd, NULL,
20102 					    zc_cap->ill_zerocopy_flags)) {
20103 						freeb(md_pbuf);
20104 						TCP_STAT(tcps,
20105 						    tcp_mdt_allocfail);
20106 						/* out_of_mem */
20107 						goto legacy_send;
20108 					}
20109 					zcopy = B_TRUE;
20110 				}
20111 
20112 				md_pbuf->b_rptr += base_pld_off;
20113 
20114 				/*
20115 				 * Add a payload buffer to the Multidata; this
20116 				 * operation must not fail, or otherwise our
20117 				 * logic in this routine is broken.  There
20118 				 * is no memory allocation done by the
20119 				 * routine, so any returned failure simply
20120 				 * tells us that we've done something wrong.
20121 				 *
20122 				 * A failure tells us that either we're adding
20123 				 * the same payload buffer more than once, or
20124 				 * we're trying to add more buffers than
20125 				 * allowed (max_pld calculation is wrong).
20126 				 * None of the above cases should happen, and
20127 				 * we panic because either there's horrible
20128 				 * heap corruption, and/or programming mistake.
20129 				 */
20130 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20131 				if (pbuf_idx < 0) {
20132 					cmn_err(CE_PANIC, "tcp_multisend: "
20133 					    "payload buffer logic error "
20134 					    "detected for tcp %p mmd %p "
20135 					    "pbuf %p (%d)\n",
20136 					    (void *)tcp, (void *)mmd,
20137 					    (void *)md_pbuf, pbuf_idx);
20138 				}
20139 
20140 				ASSERT(max_pld > 0);
20141 				--max_pld;
20142 				add_buffer = B_FALSE;
20143 			}
20144 
20145 			ASSERT(md_mp_head != NULL);
20146 			ASSERT(md_pbuf != NULL);
20147 			ASSERT(md_pbuf_nxt == NULL);
20148 			ASSERT(pbuf_idx != -1);
20149 			ASSERT(pbuf_idx_nxt == -1);
20150 			ASSERT(*usable > 0);
20151 
20152 			/*
20153 			 * We spillover to the next payload buffer only
20154 			 * if all of the following is true:
20155 			 *
20156 			 *   1. There is not enough data on the current
20157 			 *	payload buffer to make up `len',
20158 			 *   2. We are allowed to send `len',
20159 			 *   3. The next payload buffer length is large
20160 			 *	enough to accomodate `spill'.
20161 			 */
20162 			if ((spill = len - *tail_unsent) > 0 &&
20163 			    *usable >= len &&
20164 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20165 			    max_pld > 0) {
20166 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20167 				if (md_pbuf_nxt == NULL) {
20168 					TCP_STAT(tcps, tcp_mdt_allocfail);
20169 					goto legacy_send; /* out_of_mem */
20170 				}
20171 
20172 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20173 				    zc_cap != NULL) {
20174 					if (!ip_md_zcopy_attr(mmd, NULL,
20175 					    zc_cap->ill_zerocopy_flags)) {
20176 						freeb(md_pbuf_nxt);
20177 						TCP_STAT(tcps,
20178 						    tcp_mdt_allocfail);
20179 						/* out_of_mem */
20180 						goto legacy_send;
20181 					}
20182 					zcopy = B_TRUE;
20183 				}
20184 
20185 				/*
20186 				 * See comments above on the first call to
20187 				 * mmd_addpldbuf for explanation on the panic.
20188 				 */
20189 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20190 				if (pbuf_idx_nxt < 0) {
20191 					panic("tcp_multisend: "
20192 					    "next payload buffer logic error "
20193 					    "detected for tcp %p mmd %p "
20194 					    "pbuf %p (%d)\n",
20195 					    (void *)tcp, (void *)mmd,
20196 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20197 				}
20198 
20199 				ASSERT(max_pld > 0);
20200 				--max_pld;
20201 			} else if (spill > 0) {
20202 				/*
20203 				 * If there's a spillover, but the following
20204 				 * xmit_tail couldn't give us enough octets
20205 				 * to reach "len", then stop the current
20206 				 * Multidata creation and let the legacy
20207 				 * tcp_send() path take over.  We don't want
20208 				 * to send the tiny segment as part of this
20209 				 * Multidata for performance reasons; instead,
20210 				 * we let the legacy path deal with grouping
20211 				 * it with the subsequent small mblks.
20212 				 */
20213 				if (*usable >= len &&
20214 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20215 					max_pld = 0;
20216 					break;	/* done */
20217 				}
20218 
20219 				/*
20220 				 * We can't spillover, and we are near
20221 				 * the end of the current payload buffer,
20222 				 * so send what's left.
20223 				 */
20224 				ASSERT(*tail_unsent > 0);
20225 				len = *tail_unsent;
20226 			}
20227 
20228 			/* tail_unsent is negated if there is a spillover */
20229 			*tail_unsent -= len;
20230 			*usable -= len;
20231 			ASSERT(*usable >= 0);
20232 
20233 			if (*usable < mss)
20234 				seg_len = *usable;
20235 			/*
20236 			 * Sender SWS avoidance; see comments in tcp_send();
20237 			 * everything else is the same, except that we only
20238 			 * do this here if there is no more data to be sent
20239 			 * following the current xmit_tail.  We don't check
20240 			 * for 1-byte urgent data because we shouldn't get
20241 			 * here if TCP_URG_VALID is set.
20242 			 */
20243 			if (*usable > 0 && *usable < mss &&
20244 			    ((md_pbuf_nxt == NULL &&
20245 			    (*xmit_tail)->b_cont == NULL) ||
20246 			    (md_pbuf_nxt != NULL &&
20247 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20248 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20249 			    (tcp->tcp_unsent -
20250 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20251 			    !tcp->tcp_zero_win_probe) {
20252 				if ((*snxt + len) == tcp->tcp_snxt &&
20253 				    (*snxt + len) == tcp->tcp_suna) {
20254 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20255 				}
20256 				done = B_TRUE;
20257 			}
20258 
20259 			/*
20260 			 * Prime pump for IP's checksumming on our behalf;
20261 			 * include the adjustment for a source route if any.
20262 			 * Do this only for software/partial hardware checksum
20263 			 * offload, as this field gets zeroed out later for
20264 			 * the full hardware checksum offload case.
20265 			 */
20266 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20267 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20268 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20269 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20270 			}
20271 
20272 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20273 			*snxt += len;
20274 
20275 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20276 			/*
20277 			 * We set the PUSH bit only if TCP has no more buffered
20278 			 * data to be transmitted (or if sender SWS avoidance
20279 			 * takes place), as opposed to setting it for every
20280 			 * last packet in the burst.
20281 			 */
20282 			if (done ||
20283 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20284 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20285 
20286 			/*
20287 			 * Set FIN bit if this is our last segment; snxt
20288 			 * already includes its length, and it will not
20289 			 * be adjusted after this point.
20290 			 */
20291 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20292 			    *snxt == tcp->tcp_fss) {
20293 				if (!tcp->tcp_fin_acked) {
20294 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20295 					BUMP_MIB(&tcps->tcps_mib,
20296 					    tcpOutControl);
20297 				}
20298 				if (!tcp->tcp_fin_sent) {
20299 					tcp->tcp_fin_sent = B_TRUE;
20300 					/*
20301 					 * tcp state must be ESTABLISHED
20302 					 * in order for us to get here in
20303 					 * the first place.
20304 					 */
20305 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20306 
20307 					/*
20308 					 * Upon returning from this routine,
20309 					 * tcp_wput_data() will set tcp_snxt
20310 					 * to be equal to snxt + tcp_fin_sent.
20311 					 * This is essentially the same as
20312 					 * setting it to tcp_fss + 1.
20313 					 */
20314 				}
20315 			}
20316 
20317 			tcp->tcp_last_sent_len = (ushort_t)len;
20318 
20319 			len += tcp_hdr_len;
20320 			if (tcp->tcp_ipversion == IPV4_VERSION)
20321 				tcp->tcp_ipha->ipha_length = htons(len);
20322 			else
20323 				tcp->tcp_ip6h->ip6_plen = htons(len -
20324 				    ((char *)&tcp->tcp_ip6h[1] -
20325 				    tcp->tcp_iphc));
20326 
20327 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20328 
20329 			/* setup header fragment */
20330 			PDESC_HDR_ADD(pkt_info,
20331 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20332 			    tcp->tcp_mdt_hdr_head,		/* head room */
20333 			    tcp_hdr_len,			/* len */
20334 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20335 
20336 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20337 			    hdr_frag_sz);
20338 			ASSERT(MBLKIN(md_hbuf,
20339 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20340 			    PDESC_HDRSIZE(pkt_info)));
20341 
20342 			/* setup first payload fragment */
20343 			PDESC_PLD_INIT(pkt_info);
20344 			PDESC_PLD_SPAN_ADD(pkt_info,
20345 			    pbuf_idx,				/* index */
20346 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20347 			    tcp->tcp_last_sent_len);		/* len */
20348 
20349 			/* create a split-packet in case of a spillover */
20350 			if (md_pbuf_nxt != NULL) {
20351 				ASSERT(spill > 0);
20352 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20353 				ASSERT(!add_buffer);
20354 
20355 				md_pbuf = md_pbuf_nxt;
20356 				md_pbuf_nxt = NULL;
20357 				pbuf_idx = pbuf_idx_nxt;
20358 				pbuf_idx_nxt = -1;
20359 				cur_pld_off = spill;
20360 
20361 				/* trim out first payload fragment */
20362 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20363 
20364 				/* setup second payload fragment */
20365 				PDESC_PLD_SPAN_ADD(pkt_info,
20366 				    pbuf_idx,			/* index */
20367 				    md_pbuf->b_rptr,		/* start */
20368 				    spill);			/* len */
20369 
20370 				if ((*xmit_tail)->b_next == NULL) {
20371 					/*
20372 					 * Store the lbolt used for RTT
20373 					 * estimation. We can only record one
20374 					 * timestamp per mblk so we do it when
20375 					 * we reach the end of the payload
20376 					 * buffer.  Also we only take a new
20377 					 * timestamp sample when the previous
20378 					 * timed data from the same mblk has
20379 					 * been ack'ed.
20380 					 */
20381 					(*xmit_tail)->b_prev = local_time;
20382 					(*xmit_tail)->b_next =
20383 					    (mblk_t *)(uintptr_t)first_snxt;
20384 				}
20385 
20386 				first_snxt = *snxt - spill;
20387 
20388 				/*
20389 				 * Advance xmit_tail; usable could be 0 by
20390 				 * the time we got here, but we made sure
20391 				 * above that we would only spillover to
20392 				 * the next data block if usable includes
20393 				 * the spilled-over amount prior to the
20394 				 * subtraction.  Therefore, we are sure
20395 				 * that xmit_tail->b_cont can't be NULL.
20396 				 */
20397 				ASSERT((*xmit_tail)->b_cont != NULL);
20398 				*xmit_tail = (*xmit_tail)->b_cont;
20399 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20400 				    (uintptr_t)INT_MAX);
20401 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20402 			} else {
20403 				cur_pld_off += tcp->tcp_last_sent_len;
20404 			}
20405 
20406 			/*
20407 			 * Fill in the header using the template header, and
20408 			 * add options such as time-stamp, ECN and/or SACK,
20409 			 * as needed.
20410 			 */
20411 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20412 			    (clock_t)local_time, num_sack_blk);
20413 
20414 			/* take care of some IP header businesses */
20415 			if (af == AF_INET) {
20416 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20417 
20418 				ASSERT(OK_32PTR((uchar_t *)ipha));
20419 				ASSERT(PDESC_HDRL(pkt_info) >=
20420 				    IP_SIMPLE_HDR_LENGTH);
20421 				ASSERT(ipha->ipha_version_and_hdr_length ==
20422 				    IP_SIMPLE_HDR_VERSION);
20423 
20424 				/*
20425 				 * Assign ident value for current packet; see
20426 				 * related comments in ip_wput_ire() about the
20427 				 * contract private interface with clustering
20428 				 * group.
20429 				 */
20430 				clusterwide = B_FALSE;
20431 				if (cl_inet_ipident != NULL) {
20432 					ASSERT(cl_inet_isclusterwide != NULL);
20433 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20434 					    AF_INET,
20435 					    (uint8_t *)(uintptr_t)src)) {
20436 						ipha->ipha_ident =
20437 						    (*cl_inet_ipident)
20438 						    (IPPROTO_IP, AF_INET,
20439 						    (uint8_t *)(uintptr_t)src,
20440 						    (uint8_t *)(uintptr_t)dst);
20441 						clusterwide = B_TRUE;
20442 					}
20443 				}
20444 
20445 				if (!clusterwide) {
20446 					ipha->ipha_ident = (uint16_t)
20447 					    atomic_add_32_nv(
20448 						&ire->ire_ident, 1);
20449 				}
20450 #ifndef _BIG_ENDIAN
20451 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20452 				    (ipha->ipha_ident >> 8);
20453 #endif
20454 			} else {
20455 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20456 
20457 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20458 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20459 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20460 				ASSERT(PDESC_HDRL(pkt_info) >=
20461 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20462 				    TCP_CHECKSUM_SIZE));
20463 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20464 
20465 				if (tcp->tcp_ip_forward_progress) {
20466 					rconfirm = B_TRUE;
20467 					tcp->tcp_ip_forward_progress = B_FALSE;
20468 				}
20469 			}
20470 
20471 			/* at least one payload span, and at most two */
20472 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20473 
20474 			/* add the packet descriptor to Multidata */
20475 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20476 			    KM_NOSLEEP)) == NULL) {
20477 				/*
20478 				 * Any failure other than ENOMEM indicates
20479 				 * that we have passed in invalid pkt_info
20480 				 * or parameters to mmd_addpdesc, which must
20481 				 * not happen.
20482 				 *
20483 				 * EINVAL is a result of failure on boundary
20484 				 * checks against the pkt_info contents.  It
20485 				 * should not happen, and we panic because
20486 				 * either there's horrible heap corruption,
20487 				 * and/or programming mistake.
20488 				 */
20489 				if (err != ENOMEM) {
20490 					cmn_err(CE_PANIC, "tcp_multisend: "
20491 					    "pdesc logic error detected for "
20492 					    "tcp %p mmd %p pinfo %p (%d)\n",
20493 					    (void *)tcp, (void *)mmd,
20494 					    (void *)pkt_info, err);
20495 				}
20496 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20497 				goto legacy_send; /* out_of_mem */
20498 			}
20499 			ASSERT(pkt != NULL);
20500 
20501 			/* calculate IP header and TCP checksums */
20502 			if (af == AF_INET) {
20503 				/* calculate pseudo-header checksum */
20504 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20505 				    (src >> 16) + (src & 0xFFFF);
20506 
20507 				/* offset for TCP header checksum */
20508 				up = IPH_TCPH_CHECKSUMP(ipha,
20509 				    IP_SIMPLE_HDR_LENGTH);
20510 			} else {
20511 				up = (uint16_t *)&ip6h->ip6_src;
20512 
20513 				/* calculate pseudo-header checksum */
20514 				cksum = up[0] + up[1] + up[2] + up[3] +
20515 				    up[4] + up[5] + up[6] + up[7] +
20516 				    up[8] + up[9] + up[10] + up[11] +
20517 				    up[12] + up[13] + up[14] + up[15];
20518 
20519 				/* Fold the initial sum */
20520 				cksum = (cksum & 0xffff) + (cksum >> 16);
20521 
20522 				up = (uint16_t *)(((uchar_t *)ip6h) +
20523 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20524 			}
20525 
20526 			if (hwcksum_flags & HCK_FULLCKSUM) {
20527 				/* clear checksum field for hardware */
20528 				*up = 0;
20529 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20530 				uint32_t sum;
20531 
20532 				/* pseudo-header checksumming */
20533 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20534 				sum = (sum & 0xFFFF) + (sum >> 16);
20535 				*up = (sum & 0xFFFF) + (sum >> 16);
20536 			} else {
20537 				/* software checksumming */
20538 				TCP_STAT(tcps, tcp_out_sw_cksum);
20539 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20540 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20541 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20542 				    cksum + IP_TCP_CSUM_COMP);
20543 				if (*up == 0)
20544 					*up = 0xFFFF;
20545 			}
20546 
20547 			/* IPv4 header checksum */
20548 			if (af == AF_INET) {
20549 				ipha->ipha_fragment_offset_and_flags |=
20550 				    (uint32_t)htons(ire->ire_frag_flag);
20551 
20552 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20553 					ipha->ipha_hdr_checksum = 0;
20554 				} else {
20555 					IP_HDR_CKSUM(ipha, cksum,
20556 					    ((uint32_t *)ipha)[0],
20557 					    ((uint16_t *)ipha)[4]);
20558 				}
20559 			}
20560 
20561 			if (af == AF_INET &&
20562 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20563 			    af == AF_INET6 &&
20564 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20565 				/* build header(IP/TCP) mblk for this segment */
20566 				if ((mp = dupb(md_hbuf)) == NULL)
20567 					goto legacy_send;
20568 
20569 				mp->b_rptr = pkt_info->hdr_rptr;
20570 				mp->b_wptr = pkt_info->hdr_wptr;
20571 
20572 				/* build payload mblk for this segment */
20573 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20574 					freemsg(mp);
20575 					goto legacy_send;
20576 				}
20577 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20578 				mp1->b_rptr = mp1->b_wptr -
20579 				    tcp->tcp_last_sent_len;
20580 				linkb(mp, mp1);
20581 
20582 				pld_start = mp1->b_rptr;
20583 
20584 				if (af == AF_INET) {
20585 					DTRACE_PROBE4(
20586 					    ip4__physical__out__start,
20587 					    ill_t *, NULL,
20588 					    ill_t *, ill,
20589 					    ipha_t *, ipha,
20590 					    mblk_t *, mp);
20591 					FW_HOOKS(
20592 					    ipst->ips_ip4_physical_out_event,
20593 					    ipst->ips_ipv4firewall_physical_out,
20594 					    NULL, ill, ipha, mp, mp, ipst);
20595 					DTRACE_PROBE1(
20596 					    ip4__physical__out__end,
20597 					    mblk_t *, mp);
20598 				} else {
20599 					DTRACE_PROBE4(
20600 					    ip6__physical__out_start,
20601 					    ill_t *, NULL,
20602 					    ill_t *, ill,
20603 					    ip6_t *, ip6h,
20604 					    mblk_t *, mp);
20605 					FW_HOOKS6(
20606 					    ipst->ips_ip6_physical_out_event,
20607 					    ipst->ips_ipv6firewall_physical_out,
20608 					    NULL, ill, ip6h, mp, mp, ipst);
20609 					DTRACE_PROBE1(
20610 					    ip6__physical__out__end,
20611 					    mblk_t *, mp);
20612 				}
20613 
20614 				if (buf_trunked && mp != NULL) {
20615 					/*
20616 					 * Need to pass it to normal path.
20617 					 */
20618 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20619 				} else if (mp == NULL ||
20620 				    mp->b_rptr != pkt_info->hdr_rptr ||
20621 				    mp->b_wptr != pkt_info->hdr_wptr ||
20622 				    (mp1 = mp->b_cont) == NULL ||
20623 				    mp1->b_rptr != pld_start ||
20624 				    mp1->b_wptr != pld_start +
20625 				    tcp->tcp_last_sent_len ||
20626 				    mp1->b_cont != NULL) {
20627 					/*
20628 					 * Need to pass all packets of this
20629 					 * buffer to normal path, either when
20630 					 * packet is blocked, or when boundary
20631 					 * of header buffer or payload buffer
20632 					 * has been changed by FW_HOOKS[6].
20633 					 */
20634 					buf_trunked = B_TRUE;
20635 					if (md_mp_head != NULL) {
20636 						err = (intptr_t)rmvb(md_mp_head,
20637 						    md_mp);
20638 						if (err == 0)
20639 							md_mp_head = NULL;
20640 					}
20641 
20642 					/* send down what we've got so far */
20643 					if (md_mp_head != NULL) {
20644 						tcp_multisend_data(tcp, ire,
20645 						    ill, md_mp_head, obsegs,
20646 						    obbytes, &rconfirm);
20647 					}
20648 					md_mp_head = NULL;
20649 
20650 					if (mp != NULL)
20651 						CALL_IP_WPUT(tcp->tcp_connp,
20652 						    q, mp);
20653 
20654 					mp1 = fw_mp_head;
20655 					do {
20656 						mp = mp1;
20657 						mp1 = mp1->b_next;
20658 						mp->b_next = NULL;
20659 						mp->b_prev = NULL;
20660 						CALL_IP_WPUT(tcp->tcp_connp,
20661 						    q, mp);
20662 					} while (mp1 != NULL);
20663 
20664 					fw_mp_head = NULL;
20665 				} else {
20666 					if (fw_mp_head == NULL)
20667 						fw_mp_head = mp;
20668 					else
20669 						fw_mp_head->b_prev->b_next = mp;
20670 					fw_mp_head->b_prev = mp;
20671 				}
20672 			}
20673 
20674 			/* advance header offset */
20675 			cur_hdr_off += hdr_frag_sz;
20676 
20677 			obbytes += tcp->tcp_last_sent_len;
20678 			++obsegs;
20679 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20680 		    *tail_unsent > 0);
20681 
20682 		if ((*xmit_tail)->b_next == NULL) {
20683 			/*
20684 			 * Store the lbolt used for RTT estimation. We can only
20685 			 * record one timestamp per mblk so we do it when we
20686 			 * reach the end of the payload buffer. Also we only
20687 			 * take a new timestamp sample when the previous timed
20688 			 * data from the same mblk has been ack'ed.
20689 			 */
20690 			(*xmit_tail)->b_prev = local_time;
20691 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20692 		}
20693 
20694 		ASSERT(*tail_unsent >= 0);
20695 		if (*tail_unsent > 0) {
20696 			/*
20697 			 * We got here because we broke out of the above
20698 			 * loop due to of one of the following cases:
20699 			 *
20700 			 *   1. len < adjusted MSS (i.e. small),
20701 			 *   2. Sender SWS avoidance,
20702 			 *   3. max_pld is zero.
20703 			 *
20704 			 * We are done for this Multidata, so trim our
20705 			 * last payload buffer (if any) accordingly.
20706 			 */
20707 			if (md_pbuf != NULL)
20708 				md_pbuf->b_wptr -= *tail_unsent;
20709 		} else if (*usable > 0) {
20710 			*xmit_tail = (*xmit_tail)->b_cont;
20711 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20712 			    (uintptr_t)INT_MAX);
20713 			*tail_unsent = (int)MBLKL(*xmit_tail);
20714 			add_buffer = B_TRUE;
20715 		}
20716 
20717 		while (fw_mp_head) {
20718 			mp = fw_mp_head;
20719 			fw_mp_head = fw_mp_head->b_next;
20720 			mp->b_prev = mp->b_next = NULL;
20721 			freemsg(mp);
20722 		}
20723 		if (buf_trunked) {
20724 			TCP_STAT(tcps, tcp_mdt_discarded);
20725 			freeb(md_mp);
20726 			buf_trunked = B_FALSE;
20727 		}
20728 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20729 	    (tcp_mdt_chain || max_pld > 0));
20730 
20731 	if (md_mp_head != NULL) {
20732 		/* send everything down */
20733 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20734 		    &rconfirm);
20735 	}
20736 
20737 #undef PREP_NEW_MULTIDATA
20738 #undef PREP_NEW_PBUF
20739 #undef IPVER
20740 
20741 	IRE_REFRELE(ire);
20742 	return (0);
20743 }
20744 
20745 /*
20746  * A wrapper function for sending one or more Multidata messages down to
20747  * the module below ip; this routine does not release the reference of the
20748  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20749  */
20750 static void
20751 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20752     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20753 {
20754 	uint64_t delta;
20755 	nce_t *nce;
20756 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20757 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20758 
20759 	ASSERT(ire != NULL && ill != NULL);
20760 	ASSERT(ire->ire_stq != NULL);
20761 	ASSERT(md_mp_head != NULL);
20762 	ASSERT(rconfirm != NULL);
20763 
20764 	/* adjust MIBs and IRE timestamp */
20765 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20766 	tcp->tcp_obsegs += obsegs;
20767 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20768 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20769 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20770 
20771 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20772 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20773 	} else {
20774 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20775 	}
20776 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20777 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20778 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20779 
20780 	ire->ire_ob_pkt_count += obsegs;
20781 	if (ire->ire_ipif != NULL)
20782 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20783 	ire->ire_last_used_time = lbolt;
20784 
20785 	/* send it down */
20786 	putnext(ire->ire_stq, md_mp_head);
20787 
20788 	/* we're done for TCP/IPv4 */
20789 	if (tcp->tcp_ipversion == IPV4_VERSION)
20790 		return;
20791 
20792 	nce = ire->ire_nce;
20793 
20794 	ASSERT(nce != NULL);
20795 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20796 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20797 
20798 	/* reachability confirmation? */
20799 	if (*rconfirm) {
20800 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20801 		if (nce->nce_state != ND_REACHABLE) {
20802 			mutex_enter(&nce->nce_lock);
20803 			nce->nce_state = ND_REACHABLE;
20804 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20805 			mutex_exit(&nce->nce_lock);
20806 			(void) untimeout(nce->nce_timeout_id);
20807 			if (ip_debug > 2) {
20808 				/* ip1dbg */
20809 				pr_addr_dbg("tcp_multisend_data: state "
20810 				    "for %s changed to REACHABLE\n",
20811 				    AF_INET6, &ire->ire_addr_v6);
20812 			}
20813 		}
20814 		/* reset transport reachability confirmation */
20815 		*rconfirm = B_FALSE;
20816 	}
20817 
20818 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20819 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20820 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20821 
20822 	if (delta > (uint64_t)ill->ill_reachable_time) {
20823 		mutex_enter(&nce->nce_lock);
20824 		switch (nce->nce_state) {
20825 		case ND_REACHABLE:
20826 		case ND_STALE:
20827 			/*
20828 			 * ND_REACHABLE is identical to ND_STALE in this
20829 			 * specific case. If reachable time has expired for
20830 			 * this neighbor (delta is greater than reachable
20831 			 * time), conceptually, the neighbor cache is no
20832 			 * longer in REACHABLE state, but already in STALE
20833 			 * state.  So the correct transition here is to
20834 			 * ND_DELAY.
20835 			 */
20836 			nce->nce_state = ND_DELAY;
20837 			mutex_exit(&nce->nce_lock);
20838 			NDP_RESTART_TIMER(nce,
20839 			    ipst->ips_delay_first_probe_time);
20840 			if (ip_debug > 3) {
20841 				/* ip2dbg */
20842 				pr_addr_dbg("tcp_multisend_data: state "
20843 				    "for %s changed to DELAY\n",
20844 				    AF_INET6, &ire->ire_addr_v6);
20845 			}
20846 			break;
20847 		case ND_DELAY:
20848 		case ND_PROBE:
20849 			mutex_exit(&nce->nce_lock);
20850 			/* Timers have already started */
20851 			break;
20852 		case ND_UNREACHABLE:
20853 			/*
20854 			 * ndp timer has detected that this nce is
20855 			 * unreachable and initiated deleting this nce
20856 			 * and all its associated IREs. This is a race
20857 			 * where we found the ire before it was deleted
20858 			 * and have just sent out a packet using this
20859 			 * unreachable nce.
20860 			 */
20861 			mutex_exit(&nce->nce_lock);
20862 			break;
20863 		default:
20864 			ASSERT(0);
20865 		}
20866 	}
20867 }
20868 
20869 /*
20870  * Derived from tcp_send_data().
20871  */
20872 static void
20873 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20874     int num_lso_seg)
20875 {
20876 	ipha_t		*ipha;
20877 	mblk_t		*ire_fp_mp;
20878 	uint_t		ire_fp_mp_len;
20879 	uint32_t	hcksum_txflags = 0;
20880 	ipaddr_t	src;
20881 	ipaddr_t	dst;
20882 	uint32_t	cksum;
20883 	uint16_t	*up;
20884 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20885 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20886 
20887 	ASSERT(DB_TYPE(mp) == M_DATA);
20888 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20889 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20890 	ASSERT(tcp->tcp_connp != NULL);
20891 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20892 
20893 	ipha = (ipha_t *)mp->b_rptr;
20894 	src = ipha->ipha_src;
20895 	dst = ipha->ipha_dst;
20896 
20897 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20898 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20899 	    num_lso_seg);
20900 #ifndef _BIG_ENDIAN
20901 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20902 #endif
20903 	if (tcp->tcp_snd_zcopy_aware) {
20904 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20905 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20906 			mp = tcp_zcopy_disable(tcp, mp);
20907 	}
20908 
20909 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20910 		ASSERT(ill->ill_hcksum_capab != NULL);
20911 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20912 	}
20913 
20914 	/*
20915 	 * Since the TCP checksum should be recalculated by h/w, we can just
20916 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20917 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20918 	 * The partial pseudo-header excludes TCP length, that was calculated
20919 	 * in tcp_send(), so to zero *up before further processing.
20920 	 */
20921 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20922 
20923 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20924 	*up = 0;
20925 
20926 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20927 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20928 
20929 	/*
20930 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
20931 	 */
20932 	DB_LSOFLAGS(mp) |= HW_LSO;
20933 	DB_LSOMSS(mp) = mss;
20934 
20935 	ipha->ipha_fragment_offset_and_flags |=
20936 	    (uint32_t)htons(ire->ire_frag_flag);
20937 
20938 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20939 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20940 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20941 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20942 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20943 
20944 	UPDATE_OB_PKT_COUNT(ire);
20945 	ire->ire_last_used_time = lbolt;
20946 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20947 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20948 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20949 	    ntohs(ipha->ipha_length));
20950 
20951 	if (ILL_DLS_CAPABLE(ill)) {
20952 		/*
20953 		 * Send the packet directly to DLD, where it may be queued
20954 		 * depending on the availability of transmit resources at
20955 		 * the media layer.
20956 		 */
20957 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
20958 	} else {
20959 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
20960 		DTRACE_PROBE4(ip4__physical__out__start,
20961 		    ill_t *, NULL, ill_t *, out_ill,
20962 		    ipha_t *, ipha, mblk_t *, mp);
20963 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
20964 		    ipst->ips_ipv4firewall_physical_out,
20965 		    NULL, out_ill, ipha, mp, mp, ipst);
20966 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20967 		if (mp != NULL)
20968 			putnext(ire->ire_stq, mp);
20969 	}
20970 }
20971 
20972 /*
20973  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20974  * scheme, and returns one of the following:
20975  *
20976  * -1 = failed allocation.
20977  *  0 = success; burst count reached, or usable send window is too small,
20978  *      and that we'd rather wait until later before sending again.
20979  *  1 = success; we are called from tcp_multisend(), and both usable send
20980  *      window and tail_unsent are greater than the MDT threshold, and thus
20981  *      Multidata Transmit should be used instead.
20982  */
20983 static int
20984 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20985     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20986     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20987     const int mdt_thres)
20988 {
20989 	int num_burst_seg = tcp->tcp_snd_burst;
20990 	ire_t		*ire = NULL;
20991 	ill_t		*ill = NULL;
20992 	mblk_t		*ire_fp_mp = NULL;
20993 	uint_t		ire_fp_mp_len = 0;
20994 	int		num_lso_seg = 1;
20995 	uint_t		lso_usable;
20996 	boolean_t	do_lso_send = B_FALSE;
20997 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20998 
20999 	/*
21000 	 * Check LSO capability before any further work. And the similar check
21001 	 * need to be done in for(;;) loop.
21002 	 * LSO will be deployed when therer is more than one mss of available
21003 	 * data and a burst transmission is allowed.
21004 	 */
21005 	if (tcp->tcp_lso &&
21006 	    (tcp->tcp_valid_bits == 0 ||
21007 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21008 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21009 		/*
21010 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21011 		 */
21012 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21013 			/*
21014 			 * Enable LSO with this transmission.
21015 			 * Since IRE has been hold in
21016 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21017 			 * should be called before return.
21018 			 */
21019 			do_lso_send = B_TRUE;
21020 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21021 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21022 			/* Round up to multiple of 4 */
21023 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21024 		} else {
21025 			do_lso_send = B_FALSE;
21026 			ill = NULL;
21027 		}
21028 	}
21029 
21030 	for (;;) {
21031 		struct datab	*db;
21032 		tcph_t		*tcph;
21033 		uint32_t	sum;
21034 		mblk_t		*mp, *mp1;
21035 		uchar_t		*rptr;
21036 		int		len;
21037 
21038 		/*
21039 		 * If we're called by tcp_multisend(), and the amount of
21040 		 * sendable data as well as the size of current xmit_tail
21041 		 * is beyond the MDT threshold, return to the caller and
21042 		 * let the large data transmit be done using MDT.
21043 		 */
21044 		if (*usable > 0 && *usable > mdt_thres &&
21045 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21046 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21047 			ASSERT(tcp->tcp_mdt);
21048 			return (1);	/* success; do large send */
21049 		}
21050 
21051 		if (num_burst_seg == 0)
21052 			break;		/* success; burst count reached */
21053 
21054 		/*
21055 		 * Calculate the maximum payload length we can send in *one*
21056 		 * time.
21057 		 */
21058 		if (do_lso_send) {
21059 			/*
21060 			 * Check whether need to do LSO any more.
21061 			 */
21062 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21063 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21064 				lso_usable = MIN(lso_usable,
21065 				    num_burst_seg * mss);
21066 
21067 				num_lso_seg = lso_usable / mss;
21068 				if (lso_usable % mss) {
21069 					num_lso_seg++;
21070 					tcp->tcp_last_sent_len = (ushort_t)
21071 					    (lso_usable % mss);
21072 				} else {
21073 					tcp->tcp_last_sent_len = (ushort_t)mss;
21074 				}
21075 			} else {
21076 				do_lso_send = B_FALSE;
21077 				num_lso_seg = 1;
21078 				lso_usable = mss;
21079 			}
21080 		}
21081 
21082 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21083 
21084 		/*
21085 		 * Adjust num_burst_seg here.
21086 		 */
21087 		num_burst_seg -= num_lso_seg;
21088 
21089 		len = mss;
21090 		if (len > *usable) {
21091 			ASSERT(do_lso_send == B_FALSE);
21092 
21093 			len = *usable;
21094 			if (len <= 0) {
21095 				/* Terminate the loop */
21096 				break;	/* success; too small */
21097 			}
21098 			/*
21099 			 * Sender silly-window avoidance.
21100 			 * Ignore this if we are going to send a
21101 			 * zero window probe out.
21102 			 *
21103 			 * TODO: force data into microscopic window?
21104 			 *	==> (!pushed || (unsent > usable))
21105 			 */
21106 			if (len < (tcp->tcp_max_swnd >> 1) &&
21107 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21108 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21109 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21110 				/*
21111 				 * If the retransmit timer is not running
21112 				 * we start it so that we will retransmit
21113 				 * in the case when the the receiver has
21114 				 * decremented the window.
21115 				 */
21116 				if (*snxt == tcp->tcp_snxt &&
21117 				    *snxt == tcp->tcp_suna) {
21118 					/*
21119 					 * We are not supposed to send
21120 					 * anything.  So let's wait a little
21121 					 * bit longer before breaking SWS
21122 					 * avoidance.
21123 					 *
21124 					 * What should the value be?
21125 					 * Suggestion: MAX(init rexmit time,
21126 					 * tcp->tcp_rto)
21127 					 */
21128 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21129 				}
21130 				break;	/* success; too small */
21131 			}
21132 		}
21133 
21134 		tcph = tcp->tcp_tcph;
21135 
21136 		/*
21137 		 * The reason to adjust len here is that we need to set flags
21138 		 * and calculate checksum.
21139 		 */
21140 		if (do_lso_send)
21141 			len = lso_usable;
21142 
21143 		*usable -= len; /* Approximate - can be adjusted later */
21144 		if (*usable > 0)
21145 			tcph->th_flags[0] = TH_ACK;
21146 		else
21147 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21148 
21149 		/*
21150 		 * Prime pump for IP's checksumming on our behalf
21151 		 * Include the adjustment for a source route if any.
21152 		 */
21153 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21154 		sum = (sum >> 16) + (sum & 0xFFFF);
21155 		U16_TO_ABE16(sum, tcph->th_sum);
21156 
21157 		U32_TO_ABE32(*snxt, tcph->th_seq);
21158 
21159 		/*
21160 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21161 		 * set.  For the case when TCP_FSS_VALID is the only valid
21162 		 * bit (normal active close), branch off only when we think
21163 		 * that the FIN flag needs to be set.  Note for this case,
21164 		 * that (snxt + len) may not reflect the actual seg_len,
21165 		 * as len may be further reduced in tcp_xmit_mp().  If len
21166 		 * gets modified, we will end up here again.
21167 		 */
21168 		if (tcp->tcp_valid_bits != 0 &&
21169 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21170 		    ((*snxt + len) == tcp->tcp_fss))) {
21171 			uchar_t		*prev_rptr;
21172 			uint32_t	prev_snxt = tcp->tcp_snxt;
21173 
21174 			if (*tail_unsent == 0) {
21175 				ASSERT((*xmit_tail)->b_cont != NULL);
21176 				*xmit_tail = (*xmit_tail)->b_cont;
21177 				prev_rptr = (*xmit_tail)->b_rptr;
21178 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21179 				    (*xmit_tail)->b_rptr);
21180 			} else {
21181 				prev_rptr = (*xmit_tail)->b_rptr;
21182 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21183 				    *tail_unsent;
21184 			}
21185 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21186 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21187 			/* Restore tcp_snxt so we get amount sent right. */
21188 			tcp->tcp_snxt = prev_snxt;
21189 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21190 				/*
21191 				 * If the previous timestamp is still in use,
21192 				 * don't stomp on it.
21193 				 */
21194 				if ((*xmit_tail)->b_next == NULL) {
21195 					(*xmit_tail)->b_prev = local_time;
21196 					(*xmit_tail)->b_next =
21197 					    (mblk_t *)(uintptr_t)(*snxt);
21198 				}
21199 			} else
21200 				(*xmit_tail)->b_rptr = prev_rptr;
21201 
21202 			if (mp == NULL) {
21203 				if (ire != NULL)
21204 					IRE_REFRELE(ire);
21205 				return (-1);
21206 			}
21207 			mp1 = mp->b_cont;
21208 
21209 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21210 				tcp->tcp_last_sent_len = (ushort_t)len;
21211 			while (mp1->b_cont) {
21212 				*xmit_tail = (*xmit_tail)->b_cont;
21213 				(*xmit_tail)->b_prev = local_time;
21214 				(*xmit_tail)->b_next =
21215 				    (mblk_t *)(uintptr_t)(*snxt);
21216 				mp1 = mp1->b_cont;
21217 			}
21218 			*snxt += len;
21219 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21220 			BUMP_LOCAL(tcp->tcp_obsegs);
21221 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21222 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21223 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21224 			tcp_send_data(tcp, q, mp);
21225 			continue;
21226 		}
21227 
21228 		*snxt += len;	/* Adjust later if we don't send all of len */
21229 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21230 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21231 
21232 		if (*tail_unsent) {
21233 			/* Are the bytes above us in flight? */
21234 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21235 			if (rptr != (*xmit_tail)->b_rptr) {
21236 				*tail_unsent -= len;
21237 				if (len <= mss) /* LSO is unusable */
21238 					tcp->tcp_last_sent_len = (ushort_t)len;
21239 				len += tcp_hdr_len;
21240 				if (tcp->tcp_ipversion == IPV4_VERSION)
21241 					tcp->tcp_ipha->ipha_length = htons(len);
21242 				else
21243 					tcp->tcp_ip6h->ip6_plen =
21244 					    htons(len -
21245 					    ((char *)&tcp->tcp_ip6h[1] -
21246 					    tcp->tcp_iphc));
21247 				mp = dupb(*xmit_tail);
21248 				if (mp == NULL) {
21249 					if (ire != NULL)
21250 						IRE_REFRELE(ire);
21251 					return (-1);	/* out_of_mem */
21252 				}
21253 				mp->b_rptr = rptr;
21254 				/*
21255 				 * If the old timestamp is no longer in use,
21256 				 * sample a new timestamp now.
21257 				 */
21258 				if ((*xmit_tail)->b_next == NULL) {
21259 					(*xmit_tail)->b_prev = local_time;
21260 					(*xmit_tail)->b_next =
21261 					    (mblk_t *)(uintptr_t)(*snxt-len);
21262 				}
21263 				goto must_alloc;
21264 			}
21265 		} else {
21266 			*xmit_tail = (*xmit_tail)->b_cont;
21267 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21268 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21269 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21270 			    (*xmit_tail)->b_rptr);
21271 		}
21272 
21273 		(*xmit_tail)->b_prev = local_time;
21274 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21275 
21276 		*tail_unsent -= len;
21277 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21278 			tcp->tcp_last_sent_len = (ushort_t)len;
21279 
21280 		len += tcp_hdr_len;
21281 		if (tcp->tcp_ipversion == IPV4_VERSION)
21282 			tcp->tcp_ipha->ipha_length = htons(len);
21283 		else
21284 			tcp->tcp_ip6h->ip6_plen = htons(len -
21285 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21286 
21287 		mp = dupb(*xmit_tail);
21288 		if (mp == NULL) {
21289 			if (ire != NULL)
21290 				IRE_REFRELE(ire);
21291 			return (-1);	/* out_of_mem */
21292 		}
21293 
21294 		len = tcp_hdr_len;
21295 		/*
21296 		 * There are four reasons to allocate a new hdr mblk:
21297 		 *  1) The bytes above us are in use by another packet
21298 		 *  2) We don't have good alignment
21299 		 *  3) The mblk is being shared
21300 		 *  4) We don't have enough room for a header
21301 		 */
21302 		rptr = mp->b_rptr - len;
21303 		if (!OK_32PTR(rptr) ||
21304 		    ((db = mp->b_datap), db->db_ref != 2) ||
21305 		    rptr < db->db_base + ire_fp_mp_len) {
21306 			/* NOTE: we assume allocb returns an OK_32PTR */
21307 
21308 		must_alloc:;
21309 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21310 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21311 			if (mp1 == NULL) {
21312 				freemsg(mp);
21313 				if (ire != NULL)
21314 					IRE_REFRELE(ire);
21315 				return (-1);	/* out_of_mem */
21316 			}
21317 			mp1->b_cont = mp;
21318 			mp = mp1;
21319 			/* Leave room for Link Level header */
21320 			len = tcp_hdr_len;
21321 			rptr =
21322 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21323 			mp->b_wptr = &rptr[len];
21324 		}
21325 
21326 		/*
21327 		 * Fill in the header using the template header, and add
21328 		 * options such as time-stamp, ECN and/or SACK, as needed.
21329 		 */
21330 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21331 
21332 		mp->b_rptr = rptr;
21333 
21334 		if (*tail_unsent) {
21335 			int spill = *tail_unsent;
21336 
21337 			mp1 = mp->b_cont;
21338 			if (mp1 == NULL)
21339 				mp1 = mp;
21340 
21341 			/*
21342 			 * If we're a little short, tack on more mblks until
21343 			 * there is no more spillover.
21344 			 */
21345 			while (spill < 0) {
21346 				mblk_t *nmp;
21347 				int nmpsz;
21348 
21349 				nmp = (*xmit_tail)->b_cont;
21350 				nmpsz = MBLKL(nmp);
21351 
21352 				/*
21353 				 * Excess data in mblk; can we split it?
21354 				 * If MDT is enabled for the connection,
21355 				 * keep on splitting as this is a transient
21356 				 * send path.
21357 				 */
21358 				if (!do_lso_send && !tcp->tcp_mdt &&
21359 				    (spill + nmpsz > 0)) {
21360 					/*
21361 					 * Don't split if stream head was
21362 					 * told to break up larger writes
21363 					 * into smaller ones.
21364 					 */
21365 					if (tcp->tcp_maxpsz > 0)
21366 						break;
21367 
21368 					/*
21369 					 * Next mblk is less than SMSS/2
21370 					 * rounded up to nearest 64-byte;
21371 					 * let it get sent as part of the
21372 					 * next segment.
21373 					 */
21374 					if (tcp->tcp_localnet &&
21375 					    !tcp->tcp_cork &&
21376 					    (nmpsz < roundup((mss >> 1), 64)))
21377 						break;
21378 				}
21379 
21380 				*xmit_tail = nmp;
21381 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21382 				/* Stash for rtt use later */
21383 				(*xmit_tail)->b_prev = local_time;
21384 				(*xmit_tail)->b_next =
21385 				    (mblk_t *)(uintptr_t)(*snxt - len);
21386 				mp1->b_cont = dupb(*xmit_tail);
21387 				mp1 = mp1->b_cont;
21388 
21389 				spill += nmpsz;
21390 				if (mp1 == NULL) {
21391 					*tail_unsent = spill;
21392 					freemsg(mp);
21393 					if (ire != NULL)
21394 						IRE_REFRELE(ire);
21395 					return (-1);	/* out_of_mem */
21396 				}
21397 			}
21398 
21399 			/* Trim back any surplus on the last mblk */
21400 			if (spill >= 0) {
21401 				mp1->b_wptr -= spill;
21402 				*tail_unsent = spill;
21403 			} else {
21404 				/*
21405 				 * We did not send everything we could in
21406 				 * order to remain within the b_cont limit.
21407 				 */
21408 				*usable -= spill;
21409 				*snxt += spill;
21410 				tcp->tcp_last_sent_len += spill;
21411 				UPDATE_MIB(&tcps->tcps_mib,
21412 				    tcpOutDataBytes, spill);
21413 				/*
21414 				 * Adjust the checksum
21415 				 */
21416 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21417 				sum += spill;
21418 				sum = (sum >> 16) + (sum & 0xFFFF);
21419 				U16_TO_ABE16(sum, tcph->th_sum);
21420 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21421 					sum = ntohs(
21422 					    ((ipha_t *)rptr)->ipha_length) +
21423 					    spill;
21424 					((ipha_t *)rptr)->ipha_length =
21425 					    htons(sum);
21426 				} else {
21427 					sum = ntohs(
21428 					    ((ip6_t *)rptr)->ip6_plen) +
21429 					    spill;
21430 					((ip6_t *)rptr)->ip6_plen =
21431 					    htons(sum);
21432 				}
21433 				*tail_unsent = 0;
21434 			}
21435 		}
21436 		if (tcp->tcp_ip_forward_progress) {
21437 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21438 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21439 			tcp->tcp_ip_forward_progress = B_FALSE;
21440 		}
21441 
21442 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21443 		if (do_lso_send) {
21444 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21445 			    num_lso_seg);
21446 			tcp->tcp_obsegs += num_lso_seg;
21447 
21448 			TCP_STAT(tcps, tcp_lso_times);
21449 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21450 		} else {
21451 			tcp_send_data(tcp, q, mp);
21452 			BUMP_LOCAL(tcp->tcp_obsegs);
21453 		}
21454 	}
21455 
21456 	if (ire != NULL)
21457 		IRE_REFRELE(ire);
21458 	return (0);
21459 }
21460 
21461 /* Unlink and return any mblk that looks like it contains a MDT info */
21462 static mblk_t *
21463 tcp_mdt_info_mp(mblk_t *mp)
21464 {
21465 	mblk_t	*prev_mp;
21466 
21467 	for (;;) {
21468 		prev_mp = mp;
21469 		/* no more to process? */
21470 		if ((mp = mp->b_cont) == NULL)
21471 			break;
21472 
21473 		switch (DB_TYPE(mp)) {
21474 		case M_CTL:
21475 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21476 				continue;
21477 			ASSERT(prev_mp != NULL);
21478 			prev_mp->b_cont = mp->b_cont;
21479 			mp->b_cont = NULL;
21480 			return (mp);
21481 		default:
21482 			break;
21483 		}
21484 	}
21485 	return (mp);
21486 }
21487 
21488 /* MDT info update routine, called when IP notifies us about MDT */
21489 static void
21490 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21491 {
21492 	boolean_t prev_state;
21493 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21494 
21495 	/*
21496 	 * IP is telling us to abort MDT on this connection?  We know
21497 	 * this because the capability is only turned off when IP
21498 	 * encounters some pathological cases, e.g. link-layer change
21499 	 * where the new driver doesn't support MDT, or in situation
21500 	 * where MDT usage on the link-layer has been switched off.
21501 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21502 	 * if the link-layer doesn't support MDT, and if it does, it
21503 	 * will indicate that the feature is to be turned on.
21504 	 */
21505 	prev_state = tcp->tcp_mdt;
21506 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21507 	if (!tcp->tcp_mdt && !first) {
21508 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21509 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21510 		    (void *)tcp->tcp_connp));
21511 	}
21512 
21513 	/*
21514 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21515 	 * so disable MDT otherwise.  The checks are done here
21516 	 * and in tcp_wput_data().
21517 	 */
21518 	if (tcp->tcp_mdt &&
21519 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21520 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21521 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21522 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21523 		tcp->tcp_mdt = B_FALSE;
21524 
21525 	if (tcp->tcp_mdt) {
21526 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21527 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21528 			    "version (%d), expected version is %d",
21529 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21530 			tcp->tcp_mdt = B_FALSE;
21531 			return;
21532 		}
21533 
21534 		/*
21535 		 * We need the driver to be able to handle at least three
21536 		 * spans per packet in order for tcp MDT to be utilized.
21537 		 * The first is for the header portion, while the rest are
21538 		 * needed to handle a packet that straddles across two
21539 		 * virtually non-contiguous buffers; a typical tcp packet
21540 		 * therefore consists of only two spans.  Note that we take
21541 		 * a zero as "don't care".
21542 		 */
21543 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21544 		    mdt_capab->ill_mdt_span_limit < 3) {
21545 			tcp->tcp_mdt = B_FALSE;
21546 			return;
21547 		}
21548 
21549 		/* a zero means driver wants default value */
21550 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21551 		    tcps->tcps_mdt_max_pbufs);
21552 		if (tcp->tcp_mdt_max_pld == 0)
21553 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21554 
21555 		/* ensure 32-bit alignment */
21556 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21557 		    mdt_capab->ill_mdt_hdr_head), 4);
21558 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21559 		    mdt_capab->ill_mdt_hdr_tail), 4);
21560 
21561 		if (!first && !prev_state) {
21562 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21563 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21564 			    (void *)tcp->tcp_connp));
21565 		}
21566 	}
21567 }
21568 
21569 /* Unlink and return any mblk that looks like it contains a LSO info */
21570 static mblk_t *
21571 tcp_lso_info_mp(mblk_t *mp)
21572 {
21573 	mblk_t	*prev_mp;
21574 
21575 	for (;;) {
21576 		prev_mp = mp;
21577 		/* no more to process? */
21578 		if ((mp = mp->b_cont) == NULL)
21579 			break;
21580 
21581 		switch (DB_TYPE(mp)) {
21582 		case M_CTL:
21583 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21584 				continue;
21585 			ASSERT(prev_mp != NULL);
21586 			prev_mp->b_cont = mp->b_cont;
21587 			mp->b_cont = NULL;
21588 			return (mp);
21589 		default:
21590 			break;
21591 		}
21592 	}
21593 
21594 	return (mp);
21595 }
21596 
21597 /* LSO info update routine, called when IP notifies us about LSO */
21598 static void
21599 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21600 {
21601 	tcp_stack_t *tcps = tcp->tcp_tcps;
21602 
21603 	/*
21604 	 * IP is telling us to abort LSO on this connection?  We know
21605 	 * this because the capability is only turned off when IP
21606 	 * encounters some pathological cases, e.g. link-layer change
21607 	 * where the new NIC/driver doesn't support LSO, or in situation
21608 	 * where LSO usage on the link-layer has been switched off.
21609 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21610 	 * if the link-layer doesn't support LSO, and if it does, it
21611 	 * will indicate that the feature is to be turned on.
21612 	 */
21613 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21614 	TCP_STAT(tcps, tcp_lso_enabled);
21615 
21616 	/*
21617 	 * We currently only support LSO on simple TCP/IPv4,
21618 	 * so disable LSO otherwise.  The checks are done here
21619 	 * and in tcp_wput_data().
21620 	 */
21621 	if (tcp->tcp_lso &&
21622 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21623 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21624 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21625 		tcp->tcp_lso = B_FALSE;
21626 		TCP_STAT(tcps, tcp_lso_disabled);
21627 	} else {
21628 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21629 		    lso_capab->ill_lso_max);
21630 	}
21631 }
21632 
21633 static void
21634 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21635 {
21636 	conn_t *connp = tcp->tcp_connp;
21637 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21638 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21639 
21640 	ASSERT(ire != NULL);
21641 
21642 	/*
21643 	 * We may be in the fastpath here, and although we essentially do
21644 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21645 	 * we try to keep things as brief as possible.  After all, these
21646 	 * are only best-effort checks, and we do more thorough ones prior
21647 	 * to calling tcp_send()/tcp_multisend().
21648 	 */
21649 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21650 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21651 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21652 	    !(ire->ire_flags & RTF_MULTIRT) &&
21653 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21654 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21655 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21656 			/* Cache the result */
21657 			connp->conn_lso_ok = B_TRUE;
21658 
21659 			ASSERT(ill->ill_lso_capab != NULL);
21660 			if (!ill->ill_lso_capab->ill_lso_on) {
21661 				ill->ill_lso_capab->ill_lso_on = 1;
21662 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21663 				    "LSO for interface %s\n", (void *)connp,
21664 				    ill->ill_name));
21665 			}
21666 			tcp_lso_update(tcp, ill->ill_lso_capab);
21667 		} else if (ipst->ips_ip_multidata_outbound &&
21668 		    ILL_MDT_CAPABLE(ill)) {
21669 			/* Cache the result */
21670 			connp->conn_mdt_ok = B_TRUE;
21671 
21672 			ASSERT(ill->ill_mdt_capab != NULL);
21673 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21674 				ill->ill_mdt_capab->ill_mdt_on = 1;
21675 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21676 				    "MDT for interface %s\n", (void *)connp,
21677 				    ill->ill_name));
21678 			}
21679 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21680 		}
21681 	}
21682 
21683 	/*
21684 	 * The goal is to reduce the number of generated tcp segments by
21685 	 * setting the maxpsz multiplier to 0; this will have an affect on
21686 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21687 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21688 	 * of outbound segments and incoming ACKs, thus allowing for better
21689 	 * network and system performance.  In contrast the legacy behavior
21690 	 * may result in sending less than SMSS size, because the last mblk
21691 	 * for some packets may have more data than needed to make up SMSS,
21692 	 * and the legacy code refused to "split" it.
21693 	 *
21694 	 * We apply the new behavior on following situations:
21695 	 *
21696 	 *   1) Loopback connections,
21697 	 *   2) Connections in which the remote peer is not on local subnet,
21698 	 *   3) Local subnet connections over the bge interface (see below).
21699 	 *
21700 	 * Ideally, we would like this behavior to apply for interfaces other
21701 	 * than bge.  However, doing so would negatively impact drivers which
21702 	 * perform dynamic mapping and unmapping of DMA resources, which are
21703 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21704 	 * packet will be generated by tcp).  The bge driver does not suffer
21705 	 * from this, as it copies the mblks into pre-mapped buffers, and
21706 	 * therefore does not require more I/O resources than before.
21707 	 *
21708 	 * Otherwise, this behavior is present on all network interfaces when
21709 	 * the destination endpoint is non-local, since reducing the number
21710 	 * of packets in general is good for the network.
21711 	 *
21712 	 * TODO We need to remove this hard-coded conditional for bge once
21713 	 *	a better "self-tuning" mechanism, or a way to comprehend
21714 	 *	the driver transmit strategy is devised.  Until the solution
21715 	 *	is found and well understood, we live with this hack.
21716 	 */
21717 	if (!tcp_static_maxpsz &&
21718 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21719 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21720 		/* override the default value */
21721 		tcp->tcp_maxpsz = 0;
21722 
21723 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21724 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21725 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21726 	}
21727 
21728 	/* set the stream head parameters accordingly */
21729 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21730 }
21731 
21732 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21733 static void
21734 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21735 {
21736 	uchar_t	fval = *mp->b_rptr;
21737 	mblk_t	*tail;
21738 	queue_t	*q = tcp->tcp_wq;
21739 
21740 	/* TODO: How should flush interact with urgent data? */
21741 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21742 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21743 		/*
21744 		 * Flush only data that has not yet been put on the wire.  If
21745 		 * we flush data that we have already transmitted, life, as we
21746 		 * know it, may come to an end.
21747 		 */
21748 		tail = tcp->tcp_xmit_tail;
21749 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21750 		tcp->tcp_xmit_tail_unsent = 0;
21751 		tcp->tcp_unsent = 0;
21752 		if (tail->b_wptr != tail->b_rptr)
21753 			tail = tail->b_cont;
21754 		if (tail) {
21755 			mblk_t **excess = &tcp->tcp_xmit_head;
21756 			for (;;) {
21757 				mblk_t *mp1 = *excess;
21758 				if (mp1 == tail)
21759 					break;
21760 				tcp->tcp_xmit_tail = mp1;
21761 				tcp->tcp_xmit_last = mp1;
21762 				excess = &mp1->b_cont;
21763 			}
21764 			*excess = NULL;
21765 			tcp_close_mpp(&tail);
21766 			if (tcp->tcp_snd_zcopy_aware)
21767 				tcp_zcopy_notify(tcp);
21768 		}
21769 		/*
21770 		 * We have no unsent data, so unsent must be less than
21771 		 * tcp_xmit_lowater, so re-enable flow.
21772 		 */
21773 		mutex_enter(&tcp->tcp_non_sq_lock);
21774 		if (tcp->tcp_flow_stopped) {
21775 			tcp_clrqfull(tcp);
21776 		}
21777 		mutex_exit(&tcp->tcp_non_sq_lock);
21778 	}
21779 	/*
21780 	 * TODO: you can't just flush these, you have to increase rwnd for one
21781 	 * thing.  For another, how should urgent data interact?
21782 	 */
21783 	if (fval & FLUSHR) {
21784 		*mp->b_rptr = fval & ~FLUSHW;
21785 		/* XXX */
21786 		qreply(q, mp);
21787 		return;
21788 	}
21789 	freemsg(mp);
21790 }
21791 
21792 /*
21793  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21794  * messages.
21795  */
21796 static void
21797 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21798 {
21799 	mblk_t	*mp1;
21800 	STRUCT_HANDLE(strbuf, sb);
21801 	uint16_t port;
21802 	queue_t 	*q = tcp->tcp_wq;
21803 	in6_addr_t	v6addr;
21804 	ipaddr_t	v4addr;
21805 	uint32_t	flowinfo = 0;
21806 	int		addrlen;
21807 
21808 	/* Make sure it is one of ours. */
21809 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21810 	case TI_GETMYNAME:
21811 	case TI_GETPEERNAME:
21812 		break;
21813 	default:
21814 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21815 		return;
21816 	}
21817 	switch (mi_copy_state(q, mp, &mp1)) {
21818 	case -1:
21819 		return;
21820 	case MI_COPY_CASE(MI_COPY_IN, 1):
21821 		break;
21822 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21823 		/* Copy out the strbuf. */
21824 		mi_copyout(q, mp);
21825 		return;
21826 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21827 		/* All done. */
21828 		mi_copy_done(q, mp, 0);
21829 		return;
21830 	default:
21831 		mi_copy_done(q, mp, EPROTO);
21832 		return;
21833 	}
21834 	/* Check alignment of the strbuf */
21835 	if (!OK_32PTR(mp1->b_rptr)) {
21836 		mi_copy_done(q, mp, EINVAL);
21837 		return;
21838 	}
21839 
21840 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21841 	    (void *)mp1->b_rptr);
21842 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21843 
21844 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21845 		mi_copy_done(q, mp, EINVAL);
21846 		return;
21847 	}
21848 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21849 	case TI_GETMYNAME:
21850 		if (tcp->tcp_family == AF_INET) {
21851 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21852 				v4addr = tcp->tcp_ipha->ipha_src;
21853 			} else {
21854 				/* can't return an address in this case */
21855 				v4addr = 0;
21856 			}
21857 		} else {
21858 			/* tcp->tcp_family == AF_INET6 */
21859 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21860 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21861 				    &v6addr);
21862 			} else {
21863 				v6addr = tcp->tcp_ip6h->ip6_src;
21864 			}
21865 		}
21866 		port = tcp->tcp_lport;
21867 		break;
21868 	case TI_GETPEERNAME:
21869 		if (tcp->tcp_family == AF_INET) {
21870 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21871 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21872 				    v4addr);
21873 			} else {
21874 				/* can't return an address in this case */
21875 				v4addr = 0;
21876 			}
21877 		} else {
21878 			/* tcp->tcp_family == AF_INET6) */
21879 			v6addr = tcp->tcp_remote_v6;
21880 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21881 				/*
21882 				 * No flowinfo if tcp->tcp_ipversion is v4.
21883 				 *
21884 				 * flowinfo was already initialized to zero
21885 				 * where it was declared above, so only
21886 				 * set it if ipversion is v6.
21887 				 */
21888 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21889 				    ~IPV6_VERS_AND_FLOW_MASK;
21890 			}
21891 		}
21892 		port = tcp->tcp_fport;
21893 		break;
21894 	default:
21895 		mi_copy_done(q, mp, EPROTO);
21896 		return;
21897 	}
21898 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21899 	if (!mp1)
21900 		return;
21901 
21902 	if (tcp->tcp_family == AF_INET) {
21903 		sin_t *sin;
21904 
21905 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21906 		sin = (sin_t *)mp1->b_rptr;
21907 		mp1->b_wptr = (uchar_t *)&sin[1];
21908 		*sin = sin_null;
21909 		sin->sin_family = AF_INET;
21910 		sin->sin_addr.s_addr = v4addr;
21911 		sin->sin_port = port;
21912 	} else {
21913 		/* tcp->tcp_family == AF_INET6 */
21914 		sin6_t *sin6;
21915 
21916 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21917 		sin6 = (sin6_t *)mp1->b_rptr;
21918 		mp1->b_wptr = (uchar_t *)&sin6[1];
21919 		*sin6 = sin6_null;
21920 		sin6->sin6_family = AF_INET6;
21921 		sin6->sin6_flowinfo = flowinfo;
21922 		sin6->sin6_addr = v6addr;
21923 		sin6->sin6_port = port;
21924 	}
21925 	/* Copy out the address */
21926 	mi_copyout(q, mp);
21927 }
21928 
21929 /*
21930  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21931  * messages.
21932  */
21933 /* ARGSUSED */
21934 static void
21935 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21936 {
21937 	conn_t 	*connp = (conn_t *)arg;
21938 	tcp_t	*tcp = connp->conn_tcp;
21939 	queue_t	*q = tcp->tcp_wq;
21940 	struct iocblk	*iocp;
21941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21942 
21943 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21944 	/*
21945 	 * Try and ASSERT the minimum possible references on the
21946 	 * conn early enough. Since we are executing on write side,
21947 	 * the connection is obviously not detached and that means
21948 	 * there is a ref each for TCP and IP. Since we are behind
21949 	 * the squeue, the minimum references needed are 3. If the
21950 	 * conn is in classifier hash list, there should be an
21951 	 * extra ref for that (we check both the possibilities).
21952 	 */
21953 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21954 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21955 
21956 	iocp = (struct iocblk *)mp->b_rptr;
21957 	switch (iocp->ioc_cmd) {
21958 	case TCP_IOC_DEFAULT_Q:
21959 		/* Wants to be the default wq. */
21960 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21961 			iocp->ioc_error = EPERM;
21962 			iocp->ioc_count = 0;
21963 			mp->b_datap->db_type = M_IOCACK;
21964 			qreply(q, mp);
21965 			return;
21966 		}
21967 		tcp_def_q_set(tcp, mp);
21968 		return;
21969 	case _SIOCSOCKFALLBACK:
21970 		/*
21971 		 * Either sockmod is about to be popped and the socket
21972 		 * would now be treated as a plain stream, or a module
21973 		 * is about to be pushed so we could no longer use read-
21974 		 * side synchronous streams for fused loopback tcp.
21975 		 * Drain any queued data and disable direct sockfs
21976 		 * interface from now on.
21977 		 */
21978 		if (!tcp->tcp_issocket) {
21979 			DB_TYPE(mp) = M_IOCNAK;
21980 			iocp->ioc_error = EINVAL;
21981 		} else {
21982 #ifdef	_ILP32
21983 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21984 #else
21985 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21986 #endif
21987 			/*
21988 			 * Insert this socket into the acceptor hash.
21989 			 * We might need it for T_CONN_RES message
21990 			 */
21991 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21992 
21993 			if (tcp->tcp_fused) {
21994 				/*
21995 				 * This is a fused loopback tcp; disable
21996 				 * read-side synchronous streams interface
21997 				 * and drain any queued data.  It is okay
21998 				 * to do this for non-synchronous streams
21999 				 * fused tcp as well.
22000 				 */
22001 				tcp_fuse_disable_pair(tcp, B_FALSE);
22002 			}
22003 			tcp->tcp_issocket = B_FALSE;
22004 			TCP_STAT(tcps, tcp_sock_fallback);
22005 
22006 			DB_TYPE(mp) = M_IOCACK;
22007 			iocp->ioc_error = 0;
22008 		}
22009 		iocp->ioc_count = 0;
22010 		iocp->ioc_rval = 0;
22011 		qreply(q, mp);
22012 		return;
22013 	}
22014 	CALL_IP_WPUT(connp, q, mp);
22015 }
22016 
22017 /*
22018  * This routine is called by tcp_wput() to handle all TPI requests.
22019  */
22020 /* ARGSUSED */
22021 static void
22022 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22023 {
22024 	conn_t 	*connp = (conn_t *)arg;
22025 	tcp_t	*tcp = connp->conn_tcp;
22026 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22027 	uchar_t *rptr;
22028 	t_scalar_t type;
22029 	int len;
22030 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22031 
22032 	/*
22033 	 * Try and ASSERT the minimum possible references on the
22034 	 * conn early enough. Since we are executing on write side,
22035 	 * the connection is obviously not detached and that means
22036 	 * there is a ref each for TCP and IP. Since we are behind
22037 	 * the squeue, the minimum references needed are 3. If the
22038 	 * conn is in classifier hash list, there should be an
22039 	 * extra ref for that (we check both the possibilities).
22040 	 */
22041 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22042 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22043 
22044 	rptr = mp->b_rptr;
22045 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22046 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22047 		type = ((union T_primitives *)rptr)->type;
22048 		if (type == T_EXDATA_REQ) {
22049 			uint32_t msize = msgdsize(mp->b_cont);
22050 
22051 			len = msize - 1;
22052 			if (len < 0) {
22053 				freemsg(mp);
22054 				return;
22055 			}
22056 			/*
22057 			 * Try to force urgent data out on the wire.
22058 			 * Even if we have unsent data this will
22059 			 * at least send the urgent flag.
22060 			 * XXX does not handle more flag correctly.
22061 			 */
22062 			len += tcp->tcp_unsent;
22063 			len += tcp->tcp_snxt;
22064 			tcp->tcp_urg = len;
22065 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22066 
22067 			/* Bypass tcp protocol for fused tcp loopback */
22068 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22069 				return;
22070 		} else if (type != T_DATA_REQ) {
22071 			goto non_urgent_data;
22072 		}
22073 		/* TODO: options, flags, ... from user */
22074 		/* Set length to zero for reclamation below */
22075 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22076 		freeb(mp);
22077 		return;
22078 	} else {
22079 		if (tcp->tcp_debug) {
22080 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22081 			    "tcp_wput_proto, dropping one...");
22082 		}
22083 		freemsg(mp);
22084 		return;
22085 	}
22086 
22087 non_urgent_data:
22088 
22089 	switch ((int)tprim->type) {
22090 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22091 		/*
22092 		 * save the kssl_ent_t from the next block, and convert this
22093 		 * back to a normal bind_req.
22094 		 */
22095 		if (mp->b_cont != NULL) {
22096 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22097 
22098 			if (tcp->tcp_kssl_ent != NULL) {
22099 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22100 				    KSSL_NO_PROXY);
22101 				tcp->tcp_kssl_ent = NULL;
22102 			}
22103 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22104 			    sizeof (kssl_ent_t));
22105 			kssl_hold_ent(tcp->tcp_kssl_ent);
22106 			freemsg(mp->b_cont);
22107 			mp->b_cont = NULL;
22108 		}
22109 		tprim->type = T_BIND_REQ;
22110 
22111 	/* FALLTHROUGH */
22112 	case O_T_BIND_REQ:	/* bind request */
22113 	case T_BIND_REQ:	/* new semantics bind request */
22114 		tcp_bind(tcp, mp);
22115 		break;
22116 	case T_UNBIND_REQ:	/* unbind request */
22117 		tcp_unbind(tcp, mp);
22118 		break;
22119 	case O_T_CONN_RES:	/* old connection response XXX */
22120 	case T_CONN_RES:	/* connection response */
22121 		tcp_accept(tcp, mp);
22122 		break;
22123 	case T_CONN_REQ:	/* connection request */
22124 		tcp_connect(tcp, mp);
22125 		break;
22126 	case T_DISCON_REQ:	/* disconnect request */
22127 		tcp_disconnect(tcp, mp);
22128 		break;
22129 	case T_CAPABILITY_REQ:
22130 		tcp_capability_req(tcp, mp);	/* capability request */
22131 		break;
22132 	case T_INFO_REQ:	/* information request */
22133 		tcp_info_req(tcp, mp);
22134 		break;
22135 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22136 		/* Only IP is allowed to return meaningful value */
22137 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22138 		break;
22139 	case T_OPTMGMT_REQ:
22140 		/*
22141 		 * Note:  no support for snmpcom_req() through new
22142 		 * T_OPTMGMT_REQ. See comments in ip.c
22143 		 */
22144 		/* Only IP is allowed to return meaningful value */
22145 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22146 		break;
22147 
22148 	case T_UNITDATA_REQ:	/* unitdata request */
22149 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22150 		break;
22151 	case T_ORDREL_REQ:	/* orderly release req */
22152 		freemsg(mp);
22153 
22154 		if (tcp->tcp_fused)
22155 			tcp_unfuse(tcp);
22156 
22157 		if (tcp_xmit_end(tcp) != 0) {
22158 			/*
22159 			 * We were crossing FINs and got a reset from
22160 			 * the other side. Just ignore it.
22161 			 */
22162 			if (tcp->tcp_debug) {
22163 				(void) strlog(TCP_MOD_ID, 0, 1,
22164 				    SL_ERROR|SL_TRACE,
22165 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22166 				    "state %s",
22167 				    tcp_display(tcp, NULL,
22168 				    DISP_ADDR_AND_PORT));
22169 			}
22170 		}
22171 		break;
22172 	case T_ADDR_REQ:
22173 		tcp_addr_req(tcp, mp);
22174 		break;
22175 	default:
22176 		if (tcp->tcp_debug) {
22177 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22178 			    "tcp_wput_proto, bogus TPI msg, type %d",
22179 			    tprim->type);
22180 		}
22181 		/*
22182 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22183 		 * to recover.
22184 		 */
22185 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22186 		break;
22187 	}
22188 }
22189 
22190 /*
22191  * The TCP write service routine should never be called...
22192  */
22193 /* ARGSUSED */
22194 static void
22195 tcp_wsrv(queue_t *q)
22196 {
22197 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22198 
22199 	TCP_STAT(tcps, tcp_wsrv_called);
22200 }
22201 
22202 /* Non overlapping byte exchanger */
22203 static void
22204 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22205 {
22206 	uchar_t	uch;
22207 
22208 	while (len-- > 0) {
22209 		uch = a[len];
22210 		a[len] = b[len];
22211 		b[len] = uch;
22212 	}
22213 }
22214 
22215 /*
22216  * Send out a control packet on the tcp connection specified.  This routine
22217  * is typically called where we need a simple ACK or RST generated.
22218  */
22219 static void
22220 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22221 {
22222 	uchar_t		*rptr;
22223 	tcph_t		*tcph;
22224 	ipha_t		*ipha = NULL;
22225 	ip6_t		*ip6h = NULL;
22226 	uint32_t	sum;
22227 	int		tcp_hdr_len;
22228 	int		tcp_ip_hdr_len;
22229 	mblk_t		*mp;
22230 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22231 
22232 	/*
22233 	 * Save sum for use in source route later.
22234 	 */
22235 	ASSERT(tcp != NULL);
22236 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22237 	tcp_hdr_len = tcp->tcp_hdr_len;
22238 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22239 
22240 	/* If a text string is passed in with the request, pass it to strlog. */
22241 	if (str != NULL && tcp->tcp_debug) {
22242 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22243 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22244 		    str, seq, ack, ctl);
22245 	}
22246 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22247 	    BPRI_MED);
22248 	if (mp == NULL) {
22249 		return;
22250 	}
22251 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22252 	mp->b_rptr = rptr;
22253 	mp->b_wptr = &rptr[tcp_hdr_len];
22254 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22255 
22256 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22257 		ipha = (ipha_t *)rptr;
22258 		ipha->ipha_length = htons(tcp_hdr_len);
22259 	} else {
22260 		ip6h = (ip6_t *)rptr;
22261 		ASSERT(tcp != NULL);
22262 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22263 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22264 	}
22265 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22266 	tcph->th_flags[0] = (uint8_t)ctl;
22267 	if (ctl & TH_RST) {
22268 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22269 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22270 		/*
22271 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22272 		 */
22273 		if (tcp->tcp_snd_ts_ok &&
22274 		    tcp->tcp_state > TCPS_SYN_SENT) {
22275 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22276 			*(mp->b_wptr) = TCPOPT_EOL;
22277 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22278 				ipha->ipha_length = htons(tcp_hdr_len -
22279 				    TCPOPT_REAL_TS_LEN);
22280 			} else {
22281 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22282 				    TCPOPT_REAL_TS_LEN);
22283 			}
22284 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22285 			sum -= TCPOPT_REAL_TS_LEN;
22286 		}
22287 	}
22288 	if (ctl & TH_ACK) {
22289 		if (tcp->tcp_snd_ts_ok) {
22290 			U32_TO_BE32(lbolt,
22291 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22292 			U32_TO_BE32(tcp->tcp_ts_recent,
22293 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22294 		}
22295 
22296 		/* Update the latest receive window size in TCP header. */
22297 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22298 		    tcph->th_win);
22299 		tcp->tcp_rack = ack;
22300 		tcp->tcp_rack_cnt = 0;
22301 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22302 	}
22303 	BUMP_LOCAL(tcp->tcp_obsegs);
22304 	U32_TO_BE32(seq, tcph->th_seq);
22305 	U32_TO_BE32(ack, tcph->th_ack);
22306 	/*
22307 	 * Include the adjustment for a source route if any.
22308 	 */
22309 	sum = (sum >> 16) + (sum & 0xFFFF);
22310 	U16_TO_BE16(sum, tcph->th_sum);
22311 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22312 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22313 }
22314 
22315 /*
22316  * If this routine returns B_TRUE, TCP can generate a RST in response
22317  * to a segment.  If it returns B_FALSE, TCP should not respond.
22318  */
22319 static boolean_t
22320 tcp_send_rst_chk(tcp_stack_t *tcps)
22321 {
22322 	clock_t	now;
22323 
22324 	/*
22325 	 * TCP needs to protect itself from generating too many RSTs.
22326 	 * This can be a DoS attack by sending us random segments
22327 	 * soliciting RSTs.
22328 	 *
22329 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22330 	 * in each 1 second interval.  In this way, TCP still generate
22331 	 * RSTs in normal cases but when under attack, the impact is
22332 	 * limited.
22333 	 */
22334 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22335 		now = lbolt;
22336 		/* lbolt can wrap around. */
22337 		if ((tcps->tcps_last_rst_intrvl > now) ||
22338 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22339 		    1*SECONDS)) {
22340 			tcps->tcps_last_rst_intrvl = now;
22341 			tcps->tcps_rst_cnt = 1;
22342 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22343 			return (B_FALSE);
22344 		}
22345 	}
22346 	return (B_TRUE);
22347 }
22348 
22349 /*
22350  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22351  */
22352 static void
22353 tcp_ip_ire_mark_advice(tcp_t *tcp)
22354 {
22355 	mblk_t *mp;
22356 	ipic_t *ipic;
22357 
22358 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22359 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22360 		    &ipic);
22361 	} else {
22362 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22363 		    &ipic);
22364 	}
22365 	if (mp == NULL)
22366 		return;
22367 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22368 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22369 }
22370 
22371 /*
22372  * Return an IP advice ioctl mblk and set ipic to be the pointer
22373  * to the advice structure.
22374  */
22375 static mblk_t *
22376 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22377 {
22378 	struct iocblk *ioc;
22379 	mblk_t *mp, *mp1;
22380 
22381 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22382 	if (mp == NULL)
22383 		return (NULL);
22384 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22385 	*ipic = (ipic_t *)mp->b_rptr;
22386 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22387 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22388 
22389 	bcopy(addr, *ipic + 1, addr_len);
22390 
22391 	(*ipic)->ipic_addr_length = addr_len;
22392 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22393 
22394 	mp1 = mkiocb(IP_IOCTL);
22395 	if (mp1 == NULL) {
22396 		freemsg(mp);
22397 		return (NULL);
22398 	}
22399 	mp1->b_cont = mp;
22400 	ioc = (struct iocblk *)mp1->b_rptr;
22401 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22402 
22403 	return (mp1);
22404 }
22405 
22406 /*
22407  * Generate a reset based on an inbound packet for which there is no active
22408  * tcp state that we can find.
22409  *
22410  * IPSEC NOTE : Try to send the reply with the same protection as it came
22411  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22412  * the packet will go out at the same level of protection as it came in by
22413  * converting the IPSEC_IN to IPSEC_OUT.
22414  */
22415 static void
22416 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22417     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22418     tcp_stack_t *tcps)
22419 {
22420 	ipha_t		*ipha = NULL;
22421 	ip6_t		*ip6h = NULL;
22422 	ushort_t	len;
22423 	tcph_t		*tcph;
22424 	int		i;
22425 	mblk_t		*ipsec_mp;
22426 	boolean_t	mctl_present;
22427 	ipic_t		*ipic;
22428 	ipaddr_t	v4addr;
22429 	in6_addr_t	v6addr;
22430 	int		addr_len;
22431 	void		*addr;
22432 	queue_t		*q = tcps->tcps_g_q;
22433 	tcp_t		*tcp;
22434 	cred_t		*cr;
22435 	mblk_t		*nmp;
22436 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22437 
22438 	if (tcps->tcps_g_q == NULL) {
22439 		/*
22440 		 * For non-zero stackids the default queue isn't created
22441 		 * until the first open, thus there can be a need to send
22442 		 * a reset before then. But we can't do that, hence we just
22443 		 * drop the packet. Later during boot, when the default queue
22444 		 * has been setup, a retransmitted packet from the peer
22445 		 * will result in a reset.
22446 		 */
22447 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22448 		    GLOBAL_NETSTACKID);
22449 		freemsg(mp);
22450 		return;
22451 	}
22452 
22453 	tcp = Q_TO_TCP(q);
22454 
22455 	if (!tcp_send_rst_chk(tcps)) {
22456 		tcps->tcps_rst_unsent++;
22457 		freemsg(mp);
22458 		return;
22459 	}
22460 
22461 	if (mp->b_datap->db_type == M_CTL) {
22462 		ipsec_mp = mp;
22463 		mp = mp->b_cont;
22464 		mctl_present = B_TRUE;
22465 	} else {
22466 		ipsec_mp = mp;
22467 		mctl_present = B_FALSE;
22468 	}
22469 
22470 	if (str && q && tcps->tcps_dbg) {
22471 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22472 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22473 		    "flags 0x%x",
22474 		    str, seq, ack, ctl);
22475 	}
22476 	if (mp->b_datap->db_ref != 1) {
22477 		mblk_t *mp1 = copyb(mp);
22478 		freemsg(mp);
22479 		mp = mp1;
22480 		if (!mp) {
22481 			if (mctl_present)
22482 				freeb(ipsec_mp);
22483 			return;
22484 		} else {
22485 			if (mctl_present) {
22486 				ipsec_mp->b_cont = mp;
22487 			} else {
22488 				ipsec_mp = mp;
22489 			}
22490 		}
22491 	} else if (mp->b_cont) {
22492 		freemsg(mp->b_cont);
22493 		mp->b_cont = NULL;
22494 	}
22495 	/*
22496 	 * We skip reversing source route here.
22497 	 * (for now we replace all IP options with EOL)
22498 	 */
22499 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22500 		ipha = (ipha_t *)mp->b_rptr;
22501 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22502 			mp->b_rptr[i] = IPOPT_EOL;
22503 		/*
22504 		 * Make sure that src address isn't flagrantly invalid.
22505 		 * Not all broadcast address checking for the src address
22506 		 * is possible, since we don't know the netmask of the src
22507 		 * addr.  No check for destination address is done, since
22508 		 * IP will not pass up a packet with a broadcast dest
22509 		 * address to TCP.  Similar checks are done below for IPv6.
22510 		 */
22511 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22512 		    CLASSD(ipha->ipha_src)) {
22513 			freemsg(ipsec_mp);
22514 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22515 			return;
22516 		}
22517 	} else {
22518 		ip6h = (ip6_t *)mp->b_rptr;
22519 
22520 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22521 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22522 			freemsg(ipsec_mp);
22523 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22524 			return;
22525 		}
22526 
22527 		/* Remove any extension headers assuming partial overlay */
22528 		if (ip_hdr_len > IPV6_HDR_LEN) {
22529 			uint8_t *to;
22530 
22531 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22532 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22533 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22534 			ip_hdr_len = IPV6_HDR_LEN;
22535 			ip6h = (ip6_t *)mp->b_rptr;
22536 			ip6h->ip6_nxt = IPPROTO_TCP;
22537 		}
22538 	}
22539 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22540 	if (tcph->th_flags[0] & TH_RST) {
22541 		freemsg(ipsec_mp);
22542 		return;
22543 	}
22544 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22545 	len = ip_hdr_len + sizeof (tcph_t);
22546 	mp->b_wptr = &mp->b_rptr[len];
22547 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22548 		ipha->ipha_length = htons(len);
22549 		/* Swap addresses */
22550 		v4addr = ipha->ipha_src;
22551 		ipha->ipha_src = ipha->ipha_dst;
22552 		ipha->ipha_dst = v4addr;
22553 		ipha->ipha_ident = 0;
22554 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22555 		addr_len = IP_ADDR_LEN;
22556 		addr = &v4addr;
22557 	} else {
22558 		/* No ip6i_t in this case */
22559 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22560 		/* Swap addresses */
22561 		v6addr = ip6h->ip6_src;
22562 		ip6h->ip6_src = ip6h->ip6_dst;
22563 		ip6h->ip6_dst = v6addr;
22564 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22565 		addr_len = IPV6_ADDR_LEN;
22566 		addr = &v6addr;
22567 	}
22568 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22569 	U32_TO_BE32(ack, tcph->th_ack);
22570 	U32_TO_BE32(seq, tcph->th_seq);
22571 	U16_TO_BE16(0, tcph->th_win);
22572 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22573 	tcph->th_flags[0] = (uint8_t)ctl;
22574 	if (ctl & TH_RST) {
22575 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22576 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22577 	}
22578 
22579 	/* IP trusts us to set up labels when required. */
22580 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22581 	    crgetlabel(cr) != NULL) {
22582 		int err, adjust;
22583 
22584 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22585 			err = tsol_check_label(cr, &mp, &adjust,
22586 			    tcp->tcp_connp->conn_mac_exempt,
22587 			    tcps->tcps_netstack->netstack_ip);
22588 		else
22589 			err = tsol_check_label_v6(cr, &mp, &adjust,
22590 			    tcp->tcp_connp->conn_mac_exempt,
22591 			    tcps->tcps_netstack->netstack_ip);
22592 		if (mctl_present)
22593 			ipsec_mp->b_cont = mp;
22594 		else
22595 			ipsec_mp = mp;
22596 		if (err != 0) {
22597 			freemsg(ipsec_mp);
22598 			return;
22599 		}
22600 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22601 			ipha = (ipha_t *)mp->b_rptr;
22602 			adjust += ntohs(ipha->ipha_length);
22603 			ipha->ipha_length = htons(adjust);
22604 		} else {
22605 			ip6h = (ip6_t *)mp->b_rptr;
22606 		}
22607 	}
22608 
22609 	if (mctl_present) {
22610 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22611 
22612 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22613 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22614 			return;
22615 		}
22616 	}
22617 	if (zoneid == ALL_ZONES)
22618 		zoneid = GLOBAL_ZONEID;
22619 
22620 	/* Add the zoneid so ip_output routes it properly */
22621 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22622 		freemsg(ipsec_mp);
22623 		return;
22624 	}
22625 	ipsec_mp = nmp;
22626 
22627 	/*
22628 	 * NOTE:  one might consider tracing a TCP packet here, but
22629 	 * this function has no active TCP state and no tcp structure
22630 	 * that has a trace buffer.  If we traced here, we would have
22631 	 * to keep a local trace buffer in tcp_record_trace().
22632 	 *
22633 	 * TSol note: The mblk that contains the incoming packet was
22634 	 * reused by tcp_xmit_listener_reset, so it already contains
22635 	 * the right credentials and we don't need to call mblk_setcred.
22636 	 * Also the conn's cred is not right since it is associated
22637 	 * with tcps_g_q.
22638 	 */
22639 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22640 
22641 	/*
22642 	 * Tell IP to mark the IRE used for this destination temporary.
22643 	 * This way, we can limit our exposure to DoS attack because IP
22644 	 * creates an IRE for each destination.  If there are too many,
22645 	 * the time to do any routing lookup will be extremely long.  And
22646 	 * the lookup can be in interrupt context.
22647 	 *
22648 	 * Note that in normal circumstances, this marking should not
22649 	 * affect anything.  It would be nice if only 1 message is
22650 	 * needed to inform IP that the IRE created for this RST should
22651 	 * not be added to the cache table.  But there is currently
22652 	 * not such communication mechanism between TCP and IP.  So
22653 	 * the best we can do now is to send the advice ioctl to IP
22654 	 * to mark the IRE temporary.
22655 	 */
22656 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22657 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22658 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22659 	}
22660 }
22661 
22662 /*
22663  * Initiate closedown sequence on an active connection.  (May be called as
22664  * writer.)  Return value zero for OK return, non-zero for error return.
22665  */
22666 static int
22667 tcp_xmit_end(tcp_t *tcp)
22668 {
22669 	ipic_t	*ipic;
22670 	mblk_t	*mp;
22671 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22672 
22673 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22674 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22675 		/*
22676 		 * Invalid state, only states TCPS_SYN_RCVD,
22677 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22678 		 */
22679 		return (-1);
22680 	}
22681 
22682 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22683 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22684 	/*
22685 	 * If there is nothing more unsent, send the FIN now.
22686 	 * Otherwise, it will go out with the last segment.
22687 	 */
22688 	if (tcp->tcp_unsent == 0) {
22689 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22690 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22691 
22692 		if (mp) {
22693 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22694 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22695 		} else {
22696 			/*
22697 			 * Couldn't allocate msg.  Pretend we got it out.
22698 			 * Wait for rexmit timeout.
22699 			 */
22700 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22701 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22702 		}
22703 
22704 		/*
22705 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22706 		 * changed.
22707 		 */
22708 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22709 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22710 		}
22711 	} else {
22712 		/*
22713 		 * If tcp->tcp_cork is set, then the data will not get sent,
22714 		 * so we have to check that and unset it first.
22715 		 */
22716 		if (tcp->tcp_cork)
22717 			tcp->tcp_cork = B_FALSE;
22718 		tcp_wput_data(tcp, NULL, B_FALSE);
22719 	}
22720 
22721 	/*
22722 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22723 	 * is 0, don't update the cache.
22724 	 */
22725 	if (tcps->tcps_rtt_updates == 0 ||
22726 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22727 		return (0);
22728 
22729 	/*
22730 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22731 	 * different from the destination.
22732 	 */
22733 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22734 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22735 			return (0);
22736 		}
22737 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22738 		    &ipic);
22739 	} else {
22740 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22741 		    &tcp->tcp_ip6h->ip6_dst))) {
22742 			return (0);
22743 		}
22744 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22745 		    &ipic);
22746 	}
22747 
22748 	/* Record route attributes in the IRE for use by future connections. */
22749 	if (mp == NULL)
22750 		return (0);
22751 
22752 	/*
22753 	 * We do not have a good algorithm to update ssthresh at this time.
22754 	 * So don't do any update.
22755 	 */
22756 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22757 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22758 
22759 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22760 	return (0);
22761 }
22762 
22763 /*
22764  * Generate a "no listener here" RST in response to an "unknown" segment.
22765  * Note that we are reusing the incoming mp to construct the outgoing
22766  * RST.
22767  */
22768 void
22769 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22770     tcp_stack_t *tcps)
22771 {
22772 	uchar_t		*rptr;
22773 	uint32_t	seg_len;
22774 	tcph_t		*tcph;
22775 	uint32_t	seg_seq;
22776 	uint32_t	seg_ack;
22777 	uint_t		flags;
22778 	mblk_t		*ipsec_mp;
22779 	ipha_t 		*ipha;
22780 	ip6_t 		*ip6h;
22781 	boolean_t	mctl_present = B_FALSE;
22782 	boolean_t	check = B_TRUE;
22783 	boolean_t	policy_present;
22784 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22785 
22786 	TCP_STAT(tcps, tcp_no_listener);
22787 
22788 	ipsec_mp = mp;
22789 
22790 	if (mp->b_datap->db_type == M_CTL) {
22791 		ipsec_in_t *ii;
22792 
22793 		mctl_present = B_TRUE;
22794 		mp = mp->b_cont;
22795 
22796 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22797 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22798 		if (ii->ipsec_in_dont_check) {
22799 			check = B_FALSE;
22800 			if (!ii->ipsec_in_secure) {
22801 				freeb(ipsec_mp);
22802 				mctl_present = B_FALSE;
22803 				ipsec_mp = mp;
22804 			}
22805 		}
22806 	}
22807 
22808 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22809 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22810 		ipha = (ipha_t *)mp->b_rptr;
22811 		ip6h = NULL;
22812 	} else {
22813 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22814 		ipha = NULL;
22815 		ip6h = (ip6_t *)mp->b_rptr;
22816 	}
22817 
22818 	if (check && policy_present) {
22819 		/*
22820 		 * The conn_t parameter is NULL because we already know
22821 		 * nobody's home.
22822 		 */
22823 		ipsec_mp = ipsec_check_global_policy(
22824 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22825 		    tcps->tcps_netstack);
22826 		if (ipsec_mp == NULL)
22827 			return;
22828 	}
22829 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22830 		DTRACE_PROBE2(
22831 		    tx__ip__log__error__nolistener__tcp,
22832 		    char *, "Could not reply with RST to mp(1)",
22833 		    mblk_t *, mp);
22834 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22835 		freemsg(ipsec_mp);
22836 		return;
22837 	}
22838 
22839 	rptr = mp->b_rptr;
22840 
22841 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22842 	seg_seq = BE32_TO_U32(tcph->th_seq);
22843 	seg_ack = BE32_TO_U32(tcph->th_ack);
22844 	flags = tcph->th_flags[0];
22845 
22846 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22847 	if (flags & TH_RST) {
22848 		freemsg(ipsec_mp);
22849 	} else if (flags & TH_ACK) {
22850 		tcp_xmit_early_reset("no tcp, reset",
22851 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps);
22852 	} else {
22853 		if (flags & TH_SYN) {
22854 			seg_len++;
22855 		} else {
22856 			/*
22857 			 * Here we violate the RFC.  Note that a normal
22858 			 * TCP will never send a segment without the ACK
22859 			 * flag, except for RST or SYN segment.  This
22860 			 * segment is neither.  Just drop it on the
22861 			 * floor.
22862 			 */
22863 			freemsg(ipsec_mp);
22864 			tcps->tcps_rst_unsent++;
22865 			return;
22866 		}
22867 
22868 		tcp_xmit_early_reset("no tcp, reset/ack",
22869 		    ipsec_mp, 0, seg_seq + seg_len,
22870 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps);
22871 	}
22872 }
22873 
22874 /*
22875  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22876  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22877  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22878  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22879  * otherwise it will dup partial mblks.)
22880  * Otherwise, an appropriate ACK packet will be generated.  This
22881  * routine is not usually called to send new data for the first time.  It
22882  * is mostly called out of the timer for retransmits, and to generate ACKs.
22883  *
22884  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22885  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22886  * of the original mblk chain will be returned in *offset and *end_mp.
22887  */
22888 mblk_t *
22889 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22890     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22891     boolean_t rexmit)
22892 {
22893 	int	data_length;
22894 	int32_t	off = 0;
22895 	uint_t	flags;
22896 	mblk_t	*mp1;
22897 	mblk_t	*mp2;
22898 	uchar_t	*rptr;
22899 	tcph_t	*tcph;
22900 	int32_t	num_sack_blk = 0;
22901 	int32_t	sack_opt_len = 0;
22902 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22903 
22904 	/* Allocate for our maximum TCP header + link-level */
22905 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22906 	    tcps->tcps_wroff_xtra, BPRI_MED);
22907 	if (!mp1)
22908 		return (NULL);
22909 	data_length = 0;
22910 
22911 	/*
22912 	 * Note that tcp_mss has been adjusted to take into account the
22913 	 * timestamp option if applicable.  Because SACK options do not
22914 	 * appear in every TCP segments and they are of variable lengths,
22915 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22916 	 * the actual segment length when we need to send a segment which
22917 	 * includes SACK options.
22918 	 */
22919 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22920 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22921 		    tcp->tcp_num_sack_blk);
22922 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22923 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22924 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22925 			max_to_send -= sack_opt_len;
22926 	}
22927 
22928 	if (offset != NULL) {
22929 		off = *offset;
22930 		/* We use offset as an indicator that end_mp is not NULL. */
22931 		*end_mp = NULL;
22932 	}
22933 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22934 		/* This could be faster with cooperation from downstream */
22935 		if (mp2 != mp1 && !sendall &&
22936 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22937 		    max_to_send)
22938 			/*
22939 			 * Don't send the next mblk since the whole mblk
22940 			 * does not fit.
22941 			 */
22942 			break;
22943 		mp2->b_cont = dupb(mp);
22944 		mp2 = mp2->b_cont;
22945 		if (!mp2) {
22946 			freemsg(mp1);
22947 			return (NULL);
22948 		}
22949 		mp2->b_rptr += off;
22950 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22951 		    (uintptr_t)INT_MAX);
22952 
22953 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22954 		if (data_length > max_to_send) {
22955 			mp2->b_wptr -= data_length - max_to_send;
22956 			data_length = max_to_send;
22957 			off = mp2->b_wptr - mp->b_rptr;
22958 			break;
22959 		} else {
22960 			off = 0;
22961 		}
22962 	}
22963 	if (offset != NULL) {
22964 		*offset = off;
22965 		*end_mp = mp;
22966 	}
22967 	if (seg_len != NULL) {
22968 		*seg_len = data_length;
22969 	}
22970 
22971 	/* Update the latest receive window size in TCP header. */
22972 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22973 	    tcp->tcp_tcph->th_win);
22974 
22975 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22976 	mp1->b_rptr = rptr;
22977 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22978 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22979 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22980 	U32_TO_ABE32(seq, tcph->th_seq);
22981 
22982 	/*
22983 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22984 	 * that this function was called from tcp_wput_data. Thus, when called
22985 	 * to retransmit data the setting of the PUSH bit may appear some
22986 	 * what random in that it might get set when it should not. This
22987 	 * should not pose any performance issues.
22988 	 */
22989 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22990 	    tcp->tcp_unsent == data_length)) {
22991 		flags = TH_ACK | TH_PUSH;
22992 	} else {
22993 		flags = TH_ACK;
22994 	}
22995 
22996 	if (tcp->tcp_ecn_ok) {
22997 		if (tcp->tcp_ecn_echo_on)
22998 			flags |= TH_ECE;
22999 
23000 		/*
23001 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23002 		 * There is no TCP flow control for non-data segments, and
23003 		 * only data segment is transmitted reliably.
23004 		 */
23005 		if (data_length > 0 && !rexmit) {
23006 			SET_ECT(tcp, rptr);
23007 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23008 				flags |= TH_CWR;
23009 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23010 			}
23011 		}
23012 	}
23013 
23014 	if (tcp->tcp_valid_bits) {
23015 		uint32_t u1;
23016 
23017 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23018 		    seq == tcp->tcp_iss) {
23019 			uchar_t	*wptr;
23020 
23021 			/*
23022 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23023 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23024 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23025 			 * our SYN is not ack'ed but the app closes this
23026 			 * TCP connection.
23027 			 */
23028 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23029 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23030 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23031 
23032 			/*
23033 			 * Tack on the MSS option.  It is always needed
23034 			 * for both active and passive open.
23035 			 *
23036 			 * MSS option value should be interface MTU - MIN
23037 			 * TCP/IP header according to RFC 793 as it means
23038 			 * the maximum segment size TCP can receive.  But
23039 			 * to get around some broken middle boxes/end hosts
23040 			 * out there, we allow the option value to be the
23041 			 * same as the MSS option size on the peer side.
23042 			 * In this way, the other side will not send
23043 			 * anything larger than they can receive.
23044 			 *
23045 			 * Note that for SYN_SENT state, the ndd param
23046 			 * tcp_use_smss_as_mss_opt has no effect as we
23047 			 * don't know the peer's MSS option value. So
23048 			 * the only case we need to take care of is in
23049 			 * SYN_RCVD state, which is done later.
23050 			 */
23051 			wptr = mp1->b_wptr;
23052 			wptr[0] = TCPOPT_MAXSEG;
23053 			wptr[1] = TCPOPT_MAXSEG_LEN;
23054 			wptr += 2;
23055 			u1 = tcp->tcp_if_mtu -
23056 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23057 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23058 			    TCP_MIN_HEADER_LENGTH;
23059 			U16_TO_BE16(u1, wptr);
23060 			mp1->b_wptr = wptr + 2;
23061 			/* Update the offset to cover the additional word */
23062 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23063 
23064 			/*
23065 			 * Note that the following way of filling in
23066 			 * TCP options are not optimal.  Some NOPs can
23067 			 * be saved.  But there is no need at this time
23068 			 * to optimize it.  When it is needed, we will
23069 			 * do it.
23070 			 */
23071 			switch (tcp->tcp_state) {
23072 			case TCPS_SYN_SENT:
23073 				flags = TH_SYN;
23074 
23075 				if (tcp->tcp_snd_ts_ok) {
23076 					uint32_t llbolt = (uint32_t)lbolt;
23077 
23078 					wptr = mp1->b_wptr;
23079 					wptr[0] = TCPOPT_NOP;
23080 					wptr[1] = TCPOPT_NOP;
23081 					wptr[2] = TCPOPT_TSTAMP;
23082 					wptr[3] = TCPOPT_TSTAMP_LEN;
23083 					wptr += 4;
23084 					U32_TO_BE32(llbolt, wptr);
23085 					wptr += 4;
23086 					ASSERT(tcp->tcp_ts_recent == 0);
23087 					U32_TO_BE32(0L, wptr);
23088 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23089 					tcph->th_offset_and_rsrvd[0] +=
23090 					    (3 << 4);
23091 				}
23092 
23093 				/*
23094 				 * Set up all the bits to tell other side
23095 				 * we are ECN capable.
23096 				 */
23097 				if (tcp->tcp_ecn_ok) {
23098 					flags |= (TH_ECE | TH_CWR);
23099 				}
23100 				break;
23101 			case TCPS_SYN_RCVD:
23102 				flags |= TH_SYN;
23103 
23104 				/*
23105 				 * Reset the MSS option value to be SMSS
23106 				 * We should probably add back the bytes
23107 				 * for timestamp option and IPsec.  We
23108 				 * don't do that as this is a workaround
23109 				 * for broken middle boxes/end hosts, it
23110 				 * is better for us to be more cautious.
23111 				 * They may not take these things into
23112 				 * account in their SMSS calculation.  Thus
23113 				 * the peer's calculated SMSS may be smaller
23114 				 * than what it can be.  This should be OK.
23115 				 */
23116 				if (tcps->tcps_use_smss_as_mss_opt) {
23117 					u1 = tcp->tcp_mss;
23118 					U16_TO_BE16(u1, wptr);
23119 				}
23120 
23121 				/*
23122 				 * If the other side is ECN capable, reply
23123 				 * that we are also ECN capable.
23124 				 */
23125 				if (tcp->tcp_ecn_ok)
23126 					flags |= TH_ECE;
23127 				break;
23128 			default:
23129 				/*
23130 				 * The above ASSERT() makes sure that this
23131 				 * must be FIN-WAIT-1 state.  Our SYN has
23132 				 * not been ack'ed so retransmit it.
23133 				 */
23134 				flags |= TH_SYN;
23135 				break;
23136 			}
23137 
23138 			if (tcp->tcp_snd_ws_ok) {
23139 				wptr = mp1->b_wptr;
23140 				wptr[0] =  TCPOPT_NOP;
23141 				wptr[1] =  TCPOPT_WSCALE;
23142 				wptr[2] =  TCPOPT_WS_LEN;
23143 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23144 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23145 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23146 			}
23147 
23148 			if (tcp->tcp_snd_sack_ok) {
23149 				wptr = mp1->b_wptr;
23150 				wptr[0] = TCPOPT_NOP;
23151 				wptr[1] = TCPOPT_NOP;
23152 				wptr[2] = TCPOPT_SACK_PERMITTED;
23153 				wptr[3] = TCPOPT_SACK_OK_LEN;
23154 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23155 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23156 			}
23157 
23158 			/* allocb() of adequate mblk assures space */
23159 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23160 			    (uintptr_t)INT_MAX);
23161 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23162 			/*
23163 			 * Get IP set to checksum on our behalf
23164 			 * Include the adjustment for a source route if any.
23165 			 */
23166 			u1 += tcp->tcp_sum;
23167 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23168 			U16_TO_BE16(u1, tcph->th_sum);
23169 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23170 		}
23171 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23172 		    (seq + data_length) == tcp->tcp_fss) {
23173 			if (!tcp->tcp_fin_acked) {
23174 				flags |= TH_FIN;
23175 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23176 			}
23177 			if (!tcp->tcp_fin_sent) {
23178 				tcp->tcp_fin_sent = B_TRUE;
23179 				switch (tcp->tcp_state) {
23180 				case TCPS_SYN_RCVD:
23181 				case TCPS_ESTABLISHED:
23182 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23183 					break;
23184 				case TCPS_CLOSE_WAIT:
23185 					tcp->tcp_state = TCPS_LAST_ACK;
23186 					break;
23187 				}
23188 				if (tcp->tcp_suna == tcp->tcp_snxt)
23189 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23190 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23191 			}
23192 		}
23193 		/*
23194 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23195 		 * is smaller than seq, u1 will become a very huge value.
23196 		 * So the comparison will fail.  Also note that tcp_urp
23197 		 * should be positive, see RFC 793 page 17.
23198 		 */
23199 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23200 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23201 		    u1 < (uint32_t)(64 * 1024)) {
23202 			flags |= TH_URG;
23203 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23204 			U32_TO_ABE16(u1, tcph->th_urp);
23205 		}
23206 	}
23207 	tcph->th_flags[0] = (uchar_t)flags;
23208 	tcp->tcp_rack = tcp->tcp_rnxt;
23209 	tcp->tcp_rack_cnt = 0;
23210 
23211 	if (tcp->tcp_snd_ts_ok) {
23212 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23213 			uint32_t llbolt = (uint32_t)lbolt;
23214 
23215 			U32_TO_BE32(llbolt,
23216 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23217 			U32_TO_BE32(tcp->tcp_ts_recent,
23218 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23219 		}
23220 	}
23221 
23222 	if (num_sack_blk > 0) {
23223 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23224 		sack_blk_t *tmp;
23225 		int32_t	i;
23226 
23227 		wptr[0] = TCPOPT_NOP;
23228 		wptr[1] = TCPOPT_NOP;
23229 		wptr[2] = TCPOPT_SACK;
23230 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23231 		    sizeof (sack_blk_t);
23232 		wptr += TCPOPT_REAL_SACK_LEN;
23233 
23234 		tmp = tcp->tcp_sack_list;
23235 		for (i = 0; i < num_sack_blk; i++) {
23236 			U32_TO_BE32(tmp[i].begin, wptr);
23237 			wptr += sizeof (tcp_seq);
23238 			U32_TO_BE32(tmp[i].end, wptr);
23239 			wptr += sizeof (tcp_seq);
23240 		}
23241 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23242 	}
23243 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23244 	data_length += (int)(mp1->b_wptr - rptr);
23245 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23246 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23247 	} else {
23248 		ip6_t *ip6 = (ip6_t *)(rptr +
23249 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23250 		    sizeof (ip6i_t) : 0));
23251 
23252 		ip6->ip6_plen = htons(data_length -
23253 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23254 	}
23255 
23256 	/*
23257 	 * Prime pump for IP
23258 	 * Include the adjustment for a source route if any.
23259 	 */
23260 	data_length -= tcp->tcp_ip_hdr_len;
23261 	data_length += tcp->tcp_sum;
23262 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23263 	U16_TO_ABE16(data_length, tcph->th_sum);
23264 	if (tcp->tcp_ip_forward_progress) {
23265 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23266 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23267 		tcp->tcp_ip_forward_progress = B_FALSE;
23268 	}
23269 	return (mp1);
23270 }
23271 
23272 /* This function handles the push timeout. */
23273 void
23274 tcp_push_timer(void *arg)
23275 {
23276 	conn_t	*connp = (conn_t *)arg;
23277 	tcp_t *tcp = connp->conn_tcp;
23278 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23279 
23280 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23281 
23282 	ASSERT(tcp->tcp_listener == NULL);
23283 
23284 	/*
23285 	 * We need to plug synchronous streams during our drain to prevent
23286 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23287 	 */
23288 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23289 	tcp->tcp_push_tid = 0;
23290 	if ((tcp->tcp_rcv_list != NULL) &&
23291 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
23292 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23293 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23294 }
23295 
23296 /*
23297  * This function handles delayed ACK timeout.
23298  */
23299 static void
23300 tcp_ack_timer(void *arg)
23301 {
23302 	conn_t	*connp = (conn_t *)arg;
23303 	tcp_t *tcp = connp->conn_tcp;
23304 	mblk_t *mp;
23305 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23306 
23307 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23308 
23309 	tcp->tcp_ack_tid = 0;
23310 
23311 	if (tcp->tcp_fused)
23312 		return;
23313 
23314 	/*
23315 	 * Do not send ACK if there is no outstanding unack'ed data.
23316 	 */
23317 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23318 		return;
23319 	}
23320 
23321 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23322 		/*
23323 		 * Make sure we don't allow deferred ACKs to result in
23324 		 * timer-based ACKing.  If we have held off an ACK
23325 		 * when there was more than an mss here, and the timer
23326 		 * goes off, we have to worry about the possibility
23327 		 * that the sender isn't doing slow-start, or is out
23328 		 * of step with us for some other reason.  We fall
23329 		 * permanently back in the direction of
23330 		 * ACK-every-other-packet as suggested in RFC 1122.
23331 		 */
23332 		if (tcp->tcp_rack_abs_max > 2)
23333 			tcp->tcp_rack_abs_max--;
23334 		tcp->tcp_rack_cur_max = 2;
23335 	}
23336 	mp = tcp_ack_mp(tcp);
23337 
23338 	if (mp != NULL) {
23339 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23340 		BUMP_LOCAL(tcp->tcp_obsegs);
23341 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23342 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23343 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23344 	}
23345 }
23346 
23347 
23348 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23349 static mblk_t *
23350 tcp_ack_mp(tcp_t *tcp)
23351 {
23352 	uint32_t	seq_no;
23353 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23354 
23355 	/*
23356 	 * There are a few cases to be considered while setting the sequence no.
23357 	 * Essentially, we can come here while processing an unacceptable pkt
23358 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23359 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23360 	 * If we are here for a zero window probe, stick with suna. In all
23361 	 * other cases, we check if suna + swnd encompasses snxt and set
23362 	 * the sequence number to snxt, if so. If snxt falls outside the
23363 	 * window (the receiver probably shrunk its window), we will go with
23364 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23365 	 * receiver.
23366 	 */
23367 	if (tcp->tcp_zero_win_probe) {
23368 		seq_no = tcp->tcp_suna;
23369 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23370 		ASSERT(tcp->tcp_swnd == 0);
23371 		seq_no = tcp->tcp_snxt;
23372 	} else {
23373 		seq_no = SEQ_GT(tcp->tcp_snxt,
23374 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23375 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23376 	}
23377 
23378 	if (tcp->tcp_valid_bits) {
23379 		/*
23380 		 * For the complex case where we have to send some
23381 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23382 		 */
23383 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23384 		    NULL, B_FALSE));
23385 	} else {
23386 		/* Generate a simple ACK */
23387 		int	data_length;
23388 		uchar_t	*rptr;
23389 		tcph_t	*tcph;
23390 		mblk_t	*mp1;
23391 		int32_t	tcp_hdr_len;
23392 		int32_t	tcp_tcp_hdr_len;
23393 		int32_t	num_sack_blk = 0;
23394 		int32_t sack_opt_len;
23395 
23396 		/*
23397 		 * Allocate space for TCP + IP headers
23398 		 * and link-level header
23399 		 */
23400 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23401 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23402 			    tcp->tcp_num_sack_blk);
23403 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23404 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23405 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23406 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23407 		} else {
23408 			tcp_hdr_len = tcp->tcp_hdr_len;
23409 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23410 		}
23411 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23412 		if (!mp1)
23413 			return (NULL);
23414 
23415 		/* Update the latest receive window size in TCP header. */
23416 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23417 		    tcp->tcp_tcph->th_win);
23418 		/* copy in prototype TCP + IP header */
23419 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23420 		mp1->b_rptr = rptr;
23421 		mp1->b_wptr = rptr + tcp_hdr_len;
23422 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23423 
23424 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23425 
23426 		/* Set the TCP sequence number. */
23427 		U32_TO_ABE32(seq_no, tcph->th_seq);
23428 
23429 		/* Set up the TCP flag field. */
23430 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23431 		if (tcp->tcp_ecn_echo_on)
23432 			tcph->th_flags[0] |= TH_ECE;
23433 
23434 		tcp->tcp_rack = tcp->tcp_rnxt;
23435 		tcp->tcp_rack_cnt = 0;
23436 
23437 		/* fill in timestamp option if in use */
23438 		if (tcp->tcp_snd_ts_ok) {
23439 			uint32_t llbolt = (uint32_t)lbolt;
23440 
23441 			U32_TO_BE32(llbolt,
23442 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23443 			U32_TO_BE32(tcp->tcp_ts_recent,
23444 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23445 		}
23446 
23447 		/* Fill in SACK options */
23448 		if (num_sack_blk > 0) {
23449 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23450 			sack_blk_t *tmp;
23451 			int32_t	i;
23452 
23453 			wptr[0] = TCPOPT_NOP;
23454 			wptr[1] = TCPOPT_NOP;
23455 			wptr[2] = TCPOPT_SACK;
23456 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23457 			    sizeof (sack_blk_t);
23458 			wptr += TCPOPT_REAL_SACK_LEN;
23459 
23460 			tmp = tcp->tcp_sack_list;
23461 			for (i = 0; i < num_sack_blk; i++) {
23462 				U32_TO_BE32(tmp[i].begin, wptr);
23463 				wptr += sizeof (tcp_seq);
23464 				U32_TO_BE32(tmp[i].end, wptr);
23465 				wptr += sizeof (tcp_seq);
23466 			}
23467 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23468 			    << 4);
23469 		}
23470 
23471 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23472 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23473 		} else {
23474 			/* Check for ip6i_t header in sticky hdrs */
23475 			ip6_t *ip6 = (ip6_t *)(rptr +
23476 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23477 			    sizeof (ip6i_t) : 0));
23478 
23479 			ip6->ip6_plen = htons(tcp_hdr_len -
23480 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23481 		}
23482 
23483 		/*
23484 		 * Prime pump for checksum calculation in IP.  Include the
23485 		 * adjustment for a source route if any.
23486 		 */
23487 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23488 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23489 		U16_TO_ABE16(data_length, tcph->th_sum);
23490 
23491 		if (tcp->tcp_ip_forward_progress) {
23492 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23493 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23494 			tcp->tcp_ip_forward_progress = B_FALSE;
23495 		}
23496 		return (mp1);
23497 	}
23498 }
23499 
23500 /*
23501  * To create a temporary tcp structure for inserting into bind hash list.
23502  * The parameter is assumed to be in network byte order, ready for use.
23503  */
23504 /* ARGSUSED */
23505 static tcp_t *
23506 tcp_alloc_temp_tcp(in_port_t port, tcp_stack_t *tcps)
23507 {
23508 	conn_t	*connp;
23509 	tcp_t	*tcp;
23510 
23511 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP, tcps->tcps_netstack);
23512 	if (connp == NULL)
23513 		return (NULL);
23514 
23515 	tcp = connp->conn_tcp;
23516 	tcp->tcp_tcps = tcps;
23517 	TCPS_REFHOLD(tcps);
23518 
23519 	/*
23520 	 * Only initialize the necessary info in those structures.  Note
23521 	 * that since INADDR_ANY is all 0, we do not need to set
23522 	 * tcp_bound_source to INADDR_ANY here.
23523 	 */
23524 	tcp->tcp_state = TCPS_BOUND;
23525 	tcp->tcp_lport = port;
23526 	tcp->tcp_exclbind = 1;
23527 	tcp->tcp_reserved_port = 1;
23528 
23529 	/* Just for place holding... */
23530 	tcp->tcp_ipversion = IPV4_VERSION;
23531 
23532 	return (tcp);
23533 }
23534 
23535 /*
23536  * To remove a port range specified by lo_port and hi_port from the
23537  * reserved port ranges.  This is one of the three public functions of
23538  * the reserved port interface.  Note that a port range has to be removed
23539  * as a whole.  Ports in a range cannot be removed individually.
23540  *
23541  * Params:
23542  *	in_port_t lo_port: the beginning port of the reserved port range to
23543  *		be deleted.
23544  *	in_port_t hi_port: the ending port of the reserved port range to
23545  *		be deleted.
23546  *
23547  * Return:
23548  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
23549  *
23550  * Assumes that nca is only for zoneid=0
23551  */
23552 boolean_t
23553 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
23554 {
23555 	int	i, j;
23556 	int	size;
23557 	tcp_t	**temp_tcp_array;
23558 	tcp_t	*tcp;
23559 	tcp_stack_t	*tcps;
23560 
23561 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23562 	ASSERT(tcps != NULL);
23563 
23564 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23565 
23566 	/* First make sure that the port ranage is indeed reserved. */
23567 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23568 		if (tcps->tcps_reserved_port[i].lo_port == lo_port) {
23569 			hi_port = tcps->tcps_reserved_port[i].hi_port;
23570 			temp_tcp_array =
23571 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23572 			break;
23573 		}
23574 	}
23575 	if (i == tcps->tcps_reserved_port_array_size) {
23576 		rw_exit(&tcps->tcps_reserved_port_lock);
23577 		netstack_rele(tcps->tcps_netstack);
23578 		return (B_FALSE);
23579 	}
23580 
23581 	/*
23582 	 * Remove the range from the array.  This simple loop is possible
23583 	 * because port ranges are inserted in ascending order.
23584 	 */
23585 	for (j = i; j < tcps->tcps_reserved_port_array_size - 1; j++) {
23586 		tcps->tcps_reserved_port[j].lo_port =
23587 		    tcps->tcps_reserved_port[j+1].lo_port;
23588 		tcps->tcps_reserved_port[j].hi_port =
23589 		    tcps->tcps_reserved_port[j+1].hi_port;
23590 		tcps->tcps_reserved_port[j].temp_tcp_array =
23591 		    tcps->tcps_reserved_port[j+1].temp_tcp_array;
23592 	}
23593 
23594 	/* Remove all the temporary tcp structures. */
23595 	size = hi_port - lo_port + 1;
23596 	while (size > 0) {
23597 		tcp = temp_tcp_array[size - 1];
23598 		ASSERT(tcp != NULL);
23599 		tcp_bind_hash_remove(tcp);
23600 		CONN_DEC_REF(tcp->tcp_connp);
23601 		size--;
23602 	}
23603 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
23604 	tcps->tcps_reserved_port_array_size--;
23605 	rw_exit(&tcps->tcps_reserved_port_lock);
23606 	netstack_rele(tcps->tcps_netstack);
23607 	return (B_TRUE);
23608 }
23609 
23610 /*
23611  * Macro to remove temporary tcp structure from the bind hash list.  The
23612  * first parameter is the list of tcp to be removed.  The second parameter
23613  * is the number of tcps in the array.
23614  */
23615 #define	TCP_TMP_TCP_REMOVE(tcp_array, num, tcps) \
23616 { \
23617 	while ((num) > 0) { \
23618 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
23619 		tf_t *tbf; \
23620 		tcp_t *tcpnext; \
23621 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
23622 		mutex_enter(&tbf->tf_lock); \
23623 		tcpnext = tcp->tcp_bind_hash; \
23624 		if (tcpnext) { \
23625 			tcpnext->tcp_ptpbhn = \
23626 				tcp->tcp_ptpbhn; \
23627 		} \
23628 		*tcp->tcp_ptpbhn = tcpnext; \
23629 		mutex_exit(&tbf->tf_lock); \
23630 		kmem_free(tcp, sizeof (tcp_t)); \
23631 		(tcp_array)[(num) - 1] = NULL; \
23632 		(num)--; \
23633 	} \
23634 }
23635 
23636 /*
23637  * The public interface for other modules to call to reserve a port range
23638  * in TCP.  The caller passes in how large a port range it wants.  TCP
23639  * will try to find a range and return it via lo_port and hi_port.  This is
23640  * used by NCA's nca_conn_init.
23641  * NCA can only be used in the global zone so this only affects the global
23642  * zone's ports.
23643  *
23644  * Params:
23645  *	int size: the size of the port range to be reserved.
23646  *	in_port_t *lo_port (referenced): returns the beginning port of the
23647  *		reserved port range added.
23648  *	in_port_t *hi_port (referenced): returns the ending port of the
23649  *		reserved port range added.
23650  *
23651  * Return:
23652  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
23653  *
23654  * Assumes that nca is only for zoneid=0
23655  */
23656 boolean_t
23657 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
23658 {
23659 	tcp_t		*tcp;
23660 	tcp_t		*tmp_tcp;
23661 	tcp_t		**temp_tcp_array;
23662 	tf_t		*tbf;
23663 	in_port_t	net_port;
23664 	in_port_t	port;
23665 	int32_t		cur_size;
23666 	int		i, j;
23667 	boolean_t	used;
23668 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
23669 	zoneid_t	zoneid = GLOBAL_ZONEID;
23670 	tcp_stack_t	*tcps;
23671 
23672 	/* Sanity check. */
23673 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
23674 		return (B_FALSE);
23675 	}
23676 
23677 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23678 	ASSERT(tcps != NULL);
23679 
23680 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23681 	if (tcps->tcps_reserved_port_array_size ==
23682 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
23683 		rw_exit(&tcps->tcps_reserved_port_lock);
23684 		netstack_rele(tcps->tcps_netstack);
23685 		return (B_FALSE);
23686 	}
23687 
23688 	/*
23689 	 * Find the starting port to try.  Since the port ranges are ordered
23690 	 * in the reserved port array, we can do a simple search here.
23691 	 */
23692 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
23693 	*hi_port = TCP_LARGEST_RESERVED_PORT;
23694 	for (i = 0; i < tcps->tcps_reserved_port_array_size;
23695 	    *lo_port = tcps->tcps_reserved_port[i].hi_port + 1, i++) {
23696 		if (tcps->tcps_reserved_port[i].lo_port - *lo_port >= size) {
23697 			*hi_port = tcps->tcps_reserved_port[i].lo_port - 1;
23698 			break;
23699 		}
23700 	}
23701 	/* No available port range. */
23702 	if (i == tcps->tcps_reserved_port_array_size &&
23703 	    *hi_port - *lo_port < size) {
23704 		rw_exit(&tcps->tcps_reserved_port_lock);
23705 		netstack_rele(tcps->tcps_netstack);
23706 		return (B_FALSE);
23707 	}
23708 
23709 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
23710 	if (temp_tcp_array == NULL) {
23711 		rw_exit(&tcps->tcps_reserved_port_lock);
23712 		netstack_rele(tcps->tcps_netstack);
23713 		return (B_FALSE);
23714 	}
23715 
23716 	/* Go thru the port range to see if some ports are already bound. */
23717 	for (port = *lo_port, cur_size = 0;
23718 	    cur_size < size && port <= *hi_port;
23719 	    cur_size++, port++) {
23720 		used = B_FALSE;
23721 		net_port = htons(port);
23722 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(net_port)];
23723 		mutex_enter(&tbf->tf_lock);
23724 		for (tcp = tbf->tf_tcp; tcp != NULL;
23725 		    tcp = tcp->tcp_bind_hash) {
23726 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
23727 			    net_port == tcp->tcp_lport) {
23728 				/*
23729 				 * A port is already bound.  Search again
23730 				 * starting from port + 1.  Release all
23731 				 * temporary tcps.
23732 				 */
23733 				mutex_exit(&tbf->tf_lock);
23734 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23735 				    tcps);
23736 				*lo_port = port + 1;
23737 				cur_size = -1;
23738 				used = B_TRUE;
23739 				break;
23740 			}
23741 		}
23742 		if (!used) {
23743 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port, tcps)) ==
23744 			    NULL) {
23745 				/*
23746 				 * Allocation failure.  Just fail the request.
23747 				 * Need to remove all those temporary tcp
23748 				 * structures.
23749 				 */
23750 				mutex_exit(&tbf->tf_lock);
23751 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23752 				    tcps);
23753 				rw_exit(&tcps->tcps_reserved_port_lock);
23754 				kmem_free(temp_tcp_array,
23755 				    (hi_port - lo_port + 1) *
23756 				    sizeof (tcp_t *));
23757 				netstack_rele(tcps->tcps_netstack);
23758 				return (B_FALSE);
23759 			}
23760 			temp_tcp_array[cur_size] = tmp_tcp;
23761 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
23762 			mutex_exit(&tbf->tf_lock);
23763 		}
23764 	}
23765 
23766 	/*
23767 	 * The current range is not large enough.  We can actually do another
23768 	 * search if this search is done between 2 reserved port ranges.  But
23769 	 * for first release, we just stop here and return saying that no port
23770 	 * range is available.
23771 	 */
23772 	if (cur_size < size) {
23773 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size, tcps);
23774 		rw_exit(&tcps->tcps_reserved_port_lock);
23775 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23776 		netstack_rele(tcps->tcps_netstack);
23777 		return (B_FALSE);
23778 	}
23779 	*hi_port = port - 1;
23780 
23781 	/*
23782 	 * Insert range into array in ascending order.  Since this function
23783 	 * must not be called often, we choose to use the simplest method.
23784 	 * The above array should not consume excessive stack space as
23785 	 * the size must be very small.  If in future releases, we find
23786 	 * that we should provide more reserved port ranges, this function
23787 	 * has to be modified to be more efficient.
23788 	 */
23789 	if (tcps->tcps_reserved_port_array_size == 0) {
23790 		tcps->tcps_reserved_port[0].lo_port = *lo_port;
23791 		tcps->tcps_reserved_port[0].hi_port = *hi_port;
23792 		tcps->tcps_reserved_port[0].temp_tcp_array = temp_tcp_array;
23793 	} else {
23794 		for (i = 0, j = 0; i < tcps->tcps_reserved_port_array_size;
23795 		    i++, j++) {
23796 			if (*lo_port < tcps->tcps_reserved_port[i].lo_port &&
23797 			    i == j) {
23798 				tmp_ports[j].lo_port = *lo_port;
23799 				tmp_ports[j].hi_port = *hi_port;
23800 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23801 				j++;
23802 			}
23803 			tmp_ports[j].lo_port =
23804 			    tcps->tcps_reserved_port[i].lo_port;
23805 			tmp_ports[j].hi_port =
23806 			    tcps->tcps_reserved_port[i].hi_port;
23807 			tmp_ports[j].temp_tcp_array =
23808 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23809 		}
23810 		if (j == i) {
23811 			tmp_ports[j].lo_port = *lo_port;
23812 			tmp_ports[j].hi_port = *hi_port;
23813 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23814 		}
23815 		bcopy(tmp_ports, tcps->tcps_reserved_port, sizeof (tmp_ports));
23816 	}
23817 	tcps->tcps_reserved_port_array_size++;
23818 	rw_exit(&tcps->tcps_reserved_port_lock);
23819 	netstack_rele(tcps->tcps_netstack);
23820 	return (B_TRUE);
23821 }
23822 
23823 /*
23824  * Check to see if a port is in any reserved port range.
23825  *
23826  * Params:
23827  *	in_port_t port: the port to be verified.
23828  *
23829  * Return:
23830  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23831  */
23832 boolean_t
23833 tcp_reserved_port_check(in_port_t port, tcp_stack_t *tcps)
23834 {
23835 	int i;
23836 
23837 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23838 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23839 		if (port >= tcps->tcps_reserved_port[i].lo_port ||
23840 		    port <= tcps->tcps_reserved_port[i].hi_port) {
23841 			rw_exit(&tcps->tcps_reserved_port_lock);
23842 			return (B_TRUE);
23843 		}
23844 	}
23845 	rw_exit(&tcps->tcps_reserved_port_lock);
23846 	return (B_FALSE);
23847 }
23848 
23849 /*
23850  * To list all reserved port ranges.  This is the function to handle
23851  * ndd tcp_reserved_port_list.
23852  */
23853 /* ARGSUSED */
23854 static int
23855 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23856 {
23857 	int i;
23858 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23859 
23860 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23861 	if (tcps->tcps_reserved_port_array_size > 0)
23862 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23863 	else
23864 		(void) mi_mpprintf(mp, "No port is reserved.");
23865 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23866 		(void) mi_mpprintf(mp, "%d-%d",
23867 		    tcps->tcps_reserved_port[i].lo_port,
23868 		    tcps->tcps_reserved_port[i].hi_port);
23869 	}
23870 	rw_exit(&tcps->tcps_reserved_port_lock);
23871 	return (0);
23872 }
23873 
23874 /*
23875  * Hash list insertion routine for tcp_t structures.
23876  * Inserts entries with the ones bound to a specific IP address first
23877  * followed by those bound to INADDR_ANY.
23878  */
23879 static void
23880 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23881 {
23882 	tcp_t	**tcpp;
23883 	tcp_t	*tcpnext;
23884 
23885 	if (tcp->tcp_ptpbhn != NULL) {
23886 		ASSERT(!caller_holds_lock);
23887 		tcp_bind_hash_remove(tcp);
23888 	}
23889 	tcpp = &tbf->tf_tcp;
23890 	if (!caller_holds_lock) {
23891 		mutex_enter(&tbf->tf_lock);
23892 	} else {
23893 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23894 	}
23895 	tcpnext = tcpp[0];
23896 	if (tcpnext) {
23897 		/*
23898 		 * If the new tcp bound to the INADDR_ANY address
23899 		 * and the first one in the list is not bound to
23900 		 * INADDR_ANY we skip all entries until we find the
23901 		 * first one bound to INADDR_ANY.
23902 		 * This makes sure that applications binding to a
23903 		 * specific address get preference over those binding to
23904 		 * INADDR_ANY.
23905 		 */
23906 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23907 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23908 			while ((tcpnext = tcpp[0]) != NULL &&
23909 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23910 				tcpp = &(tcpnext->tcp_bind_hash);
23911 			if (tcpnext)
23912 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23913 		} else
23914 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23915 	}
23916 	tcp->tcp_bind_hash = tcpnext;
23917 	tcp->tcp_ptpbhn = tcpp;
23918 	tcpp[0] = tcp;
23919 	if (!caller_holds_lock)
23920 		mutex_exit(&tbf->tf_lock);
23921 }
23922 
23923 /*
23924  * Hash list removal routine for tcp_t structures.
23925  */
23926 static void
23927 tcp_bind_hash_remove(tcp_t *tcp)
23928 {
23929 	tcp_t	*tcpnext;
23930 	kmutex_t *lockp;
23931 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23932 
23933 	if (tcp->tcp_ptpbhn == NULL)
23934 		return;
23935 
23936 	/*
23937 	 * Extract the lock pointer in case there are concurrent
23938 	 * hash_remove's for this instance.
23939 	 */
23940 	ASSERT(tcp->tcp_lport != 0);
23941 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23942 
23943 	ASSERT(lockp != NULL);
23944 	mutex_enter(lockp);
23945 	if (tcp->tcp_ptpbhn) {
23946 		tcpnext = tcp->tcp_bind_hash;
23947 		if (tcpnext) {
23948 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23949 			tcp->tcp_bind_hash = NULL;
23950 		}
23951 		*tcp->tcp_ptpbhn = tcpnext;
23952 		tcp->tcp_ptpbhn = NULL;
23953 	}
23954 	mutex_exit(lockp);
23955 }
23956 
23957 
23958 /*
23959  * Hash list lookup routine for tcp_t structures.
23960  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23961  */
23962 static tcp_t *
23963 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23964 {
23965 	tf_t	*tf;
23966 	tcp_t	*tcp;
23967 
23968 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23969 	mutex_enter(&tf->tf_lock);
23970 	for (tcp = tf->tf_tcp; tcp != NULL;
23971 	    tcp = tcp->tcp_acceptor_hash) {
23972 		if (tcp->tcp_acceptor_id == id) {
23973 			CONN_INC_REF(tcp->tcp_connp);
23974 			mutex_exit(&tf->tf_lock);
23975 			return (tcp);
23976 		}
23977 	}
23978 	mutex_exit(&tf->tf_lock);
23979 	return (NULL);
23980 }
23981 
23982 
23983 /*
23984  * Hash list insertion routine for tcp_t structures.
23985  */
23986 void
23987 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23988 {
23989 	tf_t	*tf;
23990 	tcp_t	**tcpp;
23991 	tcp_t	*tcpnext;
23992 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23993 
23994 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23995 
23996 	if (tcp->tcp_ptpahn != NULL)
23997 		tcp_acceptor_hash_remove(tcp);
23998 	tcpp = &tf->tf_tcp;
23999 	mutex_enter(&tf->tf_lock);
24000 	tcpnext = tcpp[0];
24001 	if (tcpnext)
24002 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24003 	tcp->tcp_acceptor_hash = tcpnext;
24004 	tcp->tcp_ptpahn = tcpp;
24005 	tcpp[0] = tcp;
24006 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24007 	mutex_exit(&tf->tf_lock);
24008 }
24009 
24010 /*
24011  * Hash list removal routine for tcp_t structures.
24012  */
24013 static void
24014 tcp_acceptor_hash_remove(tcp_t *tcp)
24015 {
24016 	tcp_t	*tcpnext;
24017 	kmutex_t *lockp;
24018 
24019 	/*
24020 	 * Extract the lock pointer in case there are concurrent
24021 	 * hash_remove's for this instance.
24022 	 */
24023 	lockp = tcp->tcp_acceptor_lockp;
24024 
24025 	if (tcp->tcp_ptpahn == NULL)
24026 		return;
24027 
24028 	ASSERT(lockp != NULL);
24029 	mutex_enter(lockp);
24030 	if (tcp->tcp_ptpahn) {
24031 		tcpnext = tcp->tcp_acceptor_hash;
24032 		if (tcpnext) {
24033 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24034 			tcp->tcp_acceptor_hash = NULL;
24035 		}
24036 		*tcp->tcp_ptpahn = tcpnext;
24037 		tcp->tcp_ptpahn = NULL;
24038 	}
24039 	mutex_exit(lockp);
24040 	tcp->tcp_acceptor_lockp = NULL;
24041 }
24042 
24043 /* ARGSUSED */
24044 static int
24045 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
24046 {
24047 	int error = 0;
24048 	int retval;
24049 	char *end;
24050 	tcp_hsp_t *hsp;
24051 	tcp_hsp_t *hspprev;
24052 	ipaddr_t addr = 0;		/* Address we're looking for */
24053 	in6_addr_t v6addr;		/* Address we're looking for */
24054 	uint32_t hash;			/* Hash of that address */
24055 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24056 
24057 	/*
24058 	 * If the following variables are still zero after parsing the input
24059 	 * string, the user didn't specify them and we don't change them in
24060 	 * the HSP.
24061 	 */
24062 
24063 	ipaddr_t mask = 0;		/* Subnet mask */
24064 	in6_addr_t v6mask;
24065 	long sendspace = 0;		/* Send buffer size */
24066 	long recvspace = 0;		/* Receive buffer size */
24067 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
24068 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
24069 
24070 	rw_enter(&tcps->tcps_hsp_lock, RW_WRITER);
24071 
24072 	/* Parse and validate address */
24073 	if (af == AF_INET) {
24074 		retval = inet_pton(af, value, &addr);
24075 		if (retval == 1)
24076 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
24077 	} else if (af == AF_INET6) {
24078 		retval = inet_pton(af, value, &v6addr);
24079 	} else {
24080 		error = EINVAL;
24081 		goto done;
24082 	}
24083 	if (retval == 0) {
24084 		error = EINVAL;
24085 		goto done;
24086 	}
24087 
24088 	while ((*value) && *value != ' ')
24089 		value++;
24090 
24091 	/* Parse individual keywords, set variables if found */
24092 	while (*value) {
24093 		/* Skip leading blanks */
24094 
24095 		while (*value == ' ' || *value == '\t')
24096 			value++;
24097 
24098 		/* If at end of string, we're done */
24099 
24100 		if (!*value)
24101 			break;
24102 
24103 		/* We have a word, figure out what it is */
24104 
24105 		if (strncmp("mask", value, 4) == 0) {
24106 			value += 4;
24107 			while (*value == ' ' || *value == '\t')
24108 				value++;
24109 			/* Parse subnet mask */
24110 			if (af == AF_INET) {
24111 				retval = inet_pton(af, value, &mask);
24112 				if (retval == 1) {
24113 					V4MASK_TO_V6(mask, v6mask);
24114 				}
24115 			} else if (af == AF_INET6) {
24116 				retval = inet_pton(af, value, &v6mask);
24117 			}
24118 			if (retval != 1) {
24119 				error = EINVAL;
24120 				goto done;
24121 			}
24122 			while ((*value) && *value != ' ')
24123 				value++;
24124 		} else if (strncmp("sendspace", value, 9) == 0) {
24125 			value += 9;
24126 
24127 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
24128 			    sendspace < TCP_XMIT_HIWATER ||
24129 			    sendspace >= (1L<<30)) {
24130 				error = EINVAL;
24131 				goto done;
24132 			}
24133 			value = end;
24134 		} else if (strncmp("recvspace", value, 9) == 0) {
24135 			value += 9;
24136 
24137 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
24138 			    recvspace < TCP_RECV_HIWATER ||
24139 			    recvspace >= (1L<<30)) {
24140 				error = EINVAL;
24141 				goto done;
24142 			}
24143 			value = end;
24144 		} else if (strncmp("timestamp", value, 9) == 0) {
24145 			value += 9;
24146 
24147 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
24148 			    timestamp < 0 || timestamp > 1) {
24149 				error = EINVAL;
24150 				goto done;
24151 			}
24152 
24153 			/*
24154 			 * We increment timestamp so we know it's been set;
24155 			 * this is undone when we put it in the HSP
24156 			 */
24157 			timestamp++;
24158 			value = end;
24159 		} else if (strncmp("delete", value, 6) == 0) {
24160 			value += 6;
24161 			delete = B_TRUE;
24162 		} else {
24163 			error = EINVAL;
24164 			goto done;
24165 		}
24166 	}
24167 
24168 	/* Hash address for lookup */
24169 
24170 	hash = TCP_HSP_HASH(addr);
24171 
24172 	if (delete) {
24173 		/*
24174 		 * Note that deletes don't return an error if the thing
24175 		 * we're trying to delete isn't there.
24176 		 */
24177 		if (tcps->tcps_hsp_hash == NULL)
24178 			goto done;
24179 		hsp = tcps->tcps_hsp_hash[hash];
24180 
24181 		if (hsp) {
24182 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24183 			    &v6addr)) {
24184 				tcps->tcps_hsp_hash[hash] = hsp->tcp_hsp_next;
24185 				mi_free((char *)hsp);
24186 			} else {
24187 				hspprev = hsp;
24188 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
24189 					if (IN6_ARE_ADDR_EQUAL(
24190 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
24191 						hspprev->tcp_hsp_next =
24192 						    hsp->tcp_hsp_next;
24193 						mi_free((char *)hsp);
24194 						break;
24195 					}
24196 					hspprev = hsp;
24197 				}
24198 			}
24199 		}
24200 	} else {
24201 		/*
24202 		 * We're adding/modifying an HSP.  If we haven't already done
24203 		 * so, allocate the hash table.
24204 		 */
24205 
24206 		if (!tcps->tcps_hsp_hash) {
24207 			tcps->tcps_hsp_hash = (tcp_hsp_t **)
24208 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
24209 			if (!tcps->tcps_hsp_hash) {
24210 				error = EINVAL;
24211 				goto done;
24212 			}
24213 		}
24214 
24215 		/* Get head of hash chain */
24216 
24217 		hsp = tcps->tcps_hsp_hash[hash];
24218 
24219 		/* Try to find pre-existing hsp on hash chain */
24220 		/* Doesn't handle CIDR prefixes. */
24221 		while (hsp) {
24222 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
24223 				break;
24224 			hsp = hsp->tcp_hsp_next;
24225 		}
24226 
24227 		/*
24228 		 * If we didn't, create one with default values and put it
24229 		 * at head of hash chain
24230 		 */
24231 
24232 		if (!hsp) {
24233 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
24234 			if (!hsp) {
24235 				error = EINVAL;
24236 				goto done;
24237 			}
24238 			hsp->tcp_hsp_next = tcps->tcps_hsp_hash[hash];
24239 			tcps->tcps_hsp_hash[hash] = hsp;
24240 		}
24241 
24242 		/* Set values that the user asked us to change */
24243 
24244 		hsp->tcp_hsp_addr_v6 = v6addr;
24245 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
24246 			hsp->tcp_hsp_vers = IPV4_VERSION;
24247 		else
24248 			hsp->tcp_hsp_vers = IPV6_VERSION;
24249 		hsp->tcp_hsp_subnet_v6 = v6mask;
24250 		if (sendspace > 0)
24251 			hsp->tcp_hsp_sendspace = sendspace;
24252 		if (recvspace > 0)
24253 			hsp->tcp_hsp_recvspace = recvspace;
24254 		if (timestamp > 0)
24255 			hsp->tcp_hsp_tstamp = timestamp - 1;
24256 	}
24257 
24258 done:
24259 	rw_exit(&tcps->tcps_hsp_lock);
24260 	return (error);
24261 }
24262 
24263 /* Set callback routine passed to nd_load by tcp_param_register. */
24264 /* ARGSUSED */
24265 static int
24266 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
24267 {
24268 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
24269 }
24270 /* ARGSUSED */
24271 static int
24272 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24273     cred_t *cr)
24274 {
24275 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
24276 }
24277 
24278 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
24279 /* ARGSUSED */
24280 static int
24281 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24282 {
24283 	tcp_hsp_t *hsp;
24284 	int i;
24285 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
24286 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24287 
24288 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24289 	(void) mi_mpprintf(mp,
24290 	    "Hash HSP     " MI_COL_HDRPAD_STR
24291 	    "Address         Subnet Mask     Send       Receive    TStamp");
24292 	if (tcps->tcps_hsp_hash) {
24293 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24294 			hsp = tcps->tcps_hsp_hash[i];
24295 			while (hsp) {
24296 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24297 					(void) inet_ntop(AF_INET,
24298 					    &hsp->tcp_hsp_addr,
24299 					    addrbuf, sizeof (addrbuf));
24300 					(void) inet_ntop(AF_INET,
24301 					    &hsp->tcp_hsp_subnet,
24302 					    subnetbuf, sizeof (subnetbuf));
24303 				} else {
24304 					(void) inet_ntop(AF_INET6,
24305 					    &hsp->tcp_hsp_addr_v6,
24306 					    addrbuf, sizeof (addrbuf));
24307 					(void) inet_ntop(AF_INET6,
24308 					    &hsp->tcp_hsp_subnet_v6,
24309 					    subnetbuf, sizeof (subnetbuf));
24310 				}
24311 				(void) mi_mpprintf(mp,
24312 				    " %03d " MI_COL_PTRFMT_STR
24313 				    "%s %s %010d %010d      %d",
24314 				    i,
24315 				    (void *)hsp,
24316 				    addrbuf,
24317 				    subnetbuf,
24318 				    hsp->tcp_hsp_sendspace,
24319 				    hsp->tcp_hsp_recvspace,
24320 				    hsp->tcp_hsp_tstamp);
24321 
24322 				hsp = hsp->tcp_hsp_next;
24323 			}
24324 		}
24325 	}
24326 	rw_exit(&tcps->tcps_hsp_lock);
24327 	return (0);
24328 }
24329 
24330 
24331 /* Data for fast netmask macro used by tcp_hsp_lookup */
24332 
24333 static ipaddr_t netmasks[] = {
24334 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24335 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24336 };
24337 
24338 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24339 
24340 /*
24341  * XXX This routine should go away and instead we should use the metrics
24342  * associated with the routes to determine the default sndspace and rcvspace.
24343  */
24344 static tcp_hsp_t *
24345 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24346 {
24347 	tcp_hsp_t *hsp = NULL;
24348 
24349 	/* Quick check without acquiring the lock. */
24350 	if (tcps->tcps_hsp_hash == NULL)
24351 		return (NULL);
24352 
24353 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24354 
24355 	/* This routine finds the best-matching HSP for address addr. */
24356 
24357 	if (tcps->tcps_hsp_hash) {
24358 		int i;
24359 		ipaddr_t srchaddr;
24360 		tcp_hsp_t *hsp_net;
24361 
24362 		/* We do three passes: host, network, and subnet. */
24363 
24364 		srchaddr = addr;
24365 
24366 		for (i = 1; i <= 3; i++) {
24367 			/* Look for exact match on srchaddr */
24368 
24369 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24370 			while (hsp) {
24371 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24372 				    hsp->tcp_hsp_addr == srchaddr)
24373 					break;
24374 				hsp = hsp->tcp_hsp_next;
24375 			}
24376 			ASSERT(hsp == NULL ||
24377 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24378 
24379 			/*
24380 			 * If this is the first pass:
24381 			 *   If we found a match, great, return it.
24382 			 *   If not, search for the network on the second pass.
24383 			 */
24384 
24385 			if (i == 1)
24386 				if (hsp)
24387 					break;
24388 				else
24389 				{
24390 					srchaddr = addr & netmask(addr);
24391 					continue;
24392 				}
24393 
24394 			/*
24395 			 * If this is the second pass:
24396 			 *   If we found a match, but there's a subnet mask,
24397 			 *    save the match but try again using the subnet
24398 			 *    mask on the third pass.
24399 			 *   Otherwise, return whatever we found.
24400 			 */
24401 
24402 			if (i == 2) {
24403 				if (hsp && hsp->tcp_hsp_subnet) {
24404 					hsp_net = hsp;
24405 					srchaddr = addr & hsp->tcp_hsp_subnet;
24406 					continue;
24407 				} else {
24408 					break;
24409 				}
24410 			}
24411 
24412 			/*
24413 			 * This must be the third pass.  If we didn't find
24414 			 * anything, return the saved network HSP instead.
24415 			 */
24416 
24417 			if (!hsp)
24418 				hsp = hsp_net;
24419 		}
24420 	}
24421 
24422 	rw_exit(&tcps->tcps_hsp_lock);
24423 	return (hsp);
24424 }
24425 
24426 /*
24427  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24428  * match lookup.
24429  */
24430 static tcp_hsp_t *
24431 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24432 {
24433 	tcp_hsp_t *hsp = NULL;
24434 
24435 	/* Quick check without acquiring the lock. */
24436 	if (tcps->tcps_hsp_hash == NULL)
24437 		return (NULL);
24438 
24439 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24440 
24441 	/* This routine finds the best-matching HSP for address addr. */
24442 
24443 	if (tcps->tcps_hsp_hash) {
24444 		int i;
24445 		in6_addr_t v6srchaddr;
24446 		tcp_hsp_t *hsp_net;
24447 
24448 		/* We do three passes: host, network, and subnet. */
24449 
24450 		v6srchaddr = *v6addr;
24451 
24452 		for (i = 1; i <= 3; i++) {
24453 			/* Look for exact match on srchaddr */
24454 
24455 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24456 			    V4_PART_OF_V6(v6srchaddr))];
24457 			while (hsp) {
24458 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24459 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24460 				    &v6srchaddr))
24461 					break;
24462 				hsp = hsp->tcp_hsp_next;
24463 			}
24464 
24465 			/*
24466 			 * If this is the first pass:
24467 			 *   If we found a match, great, return it.
24468 			 *   If not, search for the network on the second pass.
24469 			 */
24470 
24471 			if (i == 1)
24472 				if (hsp)
24473 					break;
24474 				else {
24475 					/* Assume a 64 bit mask */
24476 					v6srchaddr.s6_addr32[0] =
24477 					    v6addr->s6_addr32[0];
24478 					v6srchaddr.s6_addr32[1] =
24479 					    v6addr->s6_addr32[1];
24480 					v6srchaddr.s6_addr32[2] = 0;
24481 					v6srchaddr.s6_addr32[3] = 0;
24482 					continue;
24483 				}
24484 
24485 			/*
24486 			 * If this is the second pass:
24487 			 *   If we found a match, but there's a subnet mask,
24488 			 *    save the match but try again using the subnet
24489 			 *    mask on the third pass.
24490 			 *   Otherwise, return whatever we found.
24491 			 */
24492 
24493 			if (i == 2) {
24494 				ASSERT(hsp == NULL ||
24495 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24496 				if (hsp &&
24497 				    !IN6_IS_ADDR_UNSPECIFIED(
24498 				    &hsp->tcp_hsp_subnet_v6)) {
24499 					hsp_net = hsp;
24500 					V6_MASK_COPY(*v6addr,
24501 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24502 					continue;
24503 				} else {
24504 					break;
24505 				}
24506 			}
24507 
24508 			/*
24509 			 * This must be the third pass.  If we didn't find
24510 			 * anything, return the saved network HSP instead.
24511 			 */
24512 
24513 			if (!hsp)
24514 				hsp = hsp_net;
24515 		}
24516 	}
24517 
24518 	rw_exit(&tcps->tcps_hsp_lock);
24519 	return (hsp);
24520 }
24521 
24522 /*
24523  * Type three generator adapted from the random() function in 4.4 BSD:
24524  */
24525 
24526 /*
24527  * Copyright (c) 1983, 1993
24528  *	The Regents of the University of California.  All rights reserved.
24529  *
24530  * Redistribution and use in source and binary forms, with or without
24531  * modification, are permitted provided that the following conditions
24532  * are met:
24533  * 1. Redistributions of source code must retain the above copyright
24534  *    notice, this list of conditions and the following disclaimer.
24535  * 2. Redistributions in binary form must reproduce the above copyright
24536  *    notice, this list of conditions and the following disclaimer in the
24537  *    documentation and/or other materials provided with the distribution.
24538  * 3. All advertising materials mentioning features or use of this software
24539  *    must display the following acknowledgement:
24540  *	This product includes software developed by the University of
24541  *	California, Berkeley and its contributors.
24542  * 4. Neither the name of the University nor the names of its contributors
24543  *    may be used to endorse or promote products derived from this software
24544  *    without specific prior written permission.
24545  *
24546  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24547  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24548  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24549  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24550  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24551  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24552  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24553  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24554  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24555  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24556  * SUCH DAMAGE.
24557  */
24558 
24559 /* Type 3 -- x**31 + x**3 + 1 */
24560 #define	DEG_3		31
24561 #define	SEP_3		3
24562 
24563 
24564 /* Protected by tcp_random_lock */
24565 static int tcp_randtbl[DEG_3 + 1];
24566 
24567 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24568 static int *tcp_random_rptr = &tcp_randtbl[1];
24569 
24570 static int *tcp_random_state = &tcp_randtbl[1];
24571 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24572 
24573 kmutex_t tcp_random_lock;
24574 
24575 void
24576 tcp_random_init(void)
24577 {
24578 	int i;
24579 	hrtime_t hrt;
24580 	time_t wallclock;
24581 	uint64_t result;
24582 
24583 	/*
24584 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24585 	 * a longlong, which may contain resolution down to nanoseconds.
24586 	 * The current time will either be a 32-bit or a 64-bit quantity.
24587 	 * XOR the two together in a 64-bit result variable.
24588 	 * Convert the result to a 32-bit value by multiplying the high-order
24589 	 * 32-bits by the low-order 32-bits.
24590 	 */
24591 
24592 	hrt = gethrtime();
24593 	(void) drv_getparm(TIME, &wallclock);
24594 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24595 	mutex_enter(&tcp_random_lock);
24596 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24597 	    (result & 0xffffffff);
24598 
24599 	for (i = 1; i < DEG_3; i++)
24600 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24601 			+ 12345;
24602 	tcp_random_fptr = &tcp_random_state[SEP_3];
24603 	tcp_random_rptr = &tcp_random_state[0];
24604 	mutex_exit(&tcp_random_lock);
24605 	for (i = 0; i < 10 * DEG_3; i++)
24606 		(void) tcp_random();
24607 }
24608 
24609 /*
24610  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24611  * This range is selected to be approximately centered on TCP_ISS / 2,
24612  * and easy to compute. We get this value by generating a 32-bit random
24613  * number, selecting out the high-order 17 bits, and then adding one so
24614  * that we never return zero.
24615  */
24616 int
24617 tcp_random(void)
24618 {
24619 	int i;
24620 
24621 	mutex_enter(&tcp_random_lock);
24622 	*tcp_random_fptr += *tcp_random_rptr;
24623 
24624 	/*
24625 	 * The high-order bits are more random than the low-order bits,
24626 	 * so we select out the high-order 17 bits and add one so that
24627 	 * we never return zero.
24628 	 */
24629 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24630 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24631 		tcp_random_fptr = tcp_random_state;
24632 		++tcp_random_rptr;
24633 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24634 		tcp_random_rptr = tcp_random_state;
24635 
24636 	mutex_exit(&tcp_random_lock);
24637 	return (i);
24638 }
24639 
24640 /*
24641  * XXX This will go away when TPI is extended to send
24642  * info reqs to sockfs/timod .....
24643  * Given a queue, set the max packet size for the write
24644  * side of the queue below stream head.  This value is
24645  * cached on the stream head.
24646  * Returns 1 on success, 0 otherwise.
24647  */
24648 static int
24649 setmaxps(queue_t *q, int maxpsz)
24650 {
24651 	struct stdata	*stp;
24652 	queue_t		*wq;
24653 	stp = STREAM(q);
24654 
24655 	/*
24656 	 * At this point change of a queue parameter is not allowed
24657 	 * when a multiplexor is sitting on top.
24658 	 */
24659 	if (stp->sd_flag & STPLEX)
24660 		return (0);
24661 
24662 	claimstr(stp->sd_wrq);
24663 	wq = stp->sd_wrq->q_next;
24664 	ASSERT(wq != NULL);
24665 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24666 	releasestr(stp->sd_wrq);
24667 	return (1);
24668 }
24669 
24670 static int
24671 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24672     int *t_errorp, int *sys_errorp)
24673 {
24674 	int error;
24675 	int is_absreq_failure;
24676 	t_scalar_t *opt_lenp;
24677 	t_scalar_t opt_offset;
24678 	int prim_type;
24679 	struct T_conn_req *tcreqp;
24680 	struct T_conn_res *tcresp;
24681 	cred_t *cr;
24682 
24683 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24684 
24685 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24686 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24687 	    prim_type == T_CONN_RES);
24688 
24689 	switch (prim_type) {
24690 	case T_CONN_REQ:
24691 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24692 		opt_offset = tcreqp->OPT_offset;
24693 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24694 		break;
24695 	case O_T_CONN_RES:
24696 	case T_CONN_RES:
24697 		tcresp = (struct T_conn_res *)mp->b_rptr;
24698 		opt_offset = tcresp->OPT_offset;
24699 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24700 		break;
24701 	}
24702 
24703 	*t_errorp = 0;
24704 	*sys_errorp = 0;
24705 	*do_disconnectp = 0;
24706 
24707 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24708 	    opt_offset, cr, &tcp_opt_obj,
24709 	    NULL, &is_absreq_failure);
24710 
24711 	switch (error) {
24712 	case  0:		/* no error */
24713 		ASSERT(is_absreq_failure == 0);
24714 		return (0);
24715 	case ENOPROTOOPT:
24716 		*t_errorp = TBADOPT;
24717 		break;
24718 	case EACCES:
24719 		*t_errorp = TACCES;
24720 		break;
24721 	default:
24722 		*t_errorp = TSYSERR; *sys_errorp = error;
24723 		break;
24724 	}
24725 	if (is_absreq_failure != 0) {
24726 		/*
24727 		 * The connection request should get the local ack
24728 		 * T_OK_ACK and then a T_DISCON_IND.
24729 		 */
24730 		*do_disconnectp = 1;
24731 	}
24732 	return (-1);
24733 }
24734 
24735 /*
24736  * Split this function out so that if the secret changes, I'm okay.
24737  *
24738  * Initialize the tcp_iss_cookie and tcp_iss_key.
24739  */
24740 
24741 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24742 
24743 static void
24744 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24745 {
24746 	struct {
24747 		int32_t current_time;
24748 		uint32_t randnum;
24749 		uint16_t pad;
24750 		uint8_t ether[6];
24751 		uint8_t passwd[PASSWD_SIZE];
24752 	} tcp_iss_cookie;
24753 	time_t t;
24754 
24755 	/*
24756 	 * Start with the current absolute time.
24757 	 */
24758 	(void) drv_getparm(TIME, &t);
24759 	tcp_iss_cookie.current_time = t;
24760 
24761 	/*
24762 	 * XXX - Need a more random number per RFC 1750, not this crap.
24763 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24764 	 */
24765 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24766 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24767 
24768 	/*
24769 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24770 	 * as a good template.
24771 	 */
24772 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24773 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24774 
24775 	/*
24776 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24777 	 */
24778 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24779 
24780 	/*
24781 	 * See 4010593 if this section becomes a problem again,
24782 	 * but the local ethernet address is useful here.
24783 	 */
24784 	(void) localetheraddr(NULL,
24785 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24786 
24787 	/*
24788 	 * Hash 'em all together.  The MD5Final is called per-connection.
24789 	 */
24790 	mutex_enter(&tcps->tcps_iss_key_lock);
24791 	MD5Init(&tcps->tcps_iss_key);
24792 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24793 	    sizeof (tcp_iss_cookie));
24794 	mutex_exit(&tcps->tcps_iss_key_lock);
24795 }
24796 
24797 /*
24798  * Set the RFC 1948 pass phrase
24799  */
24800 /* ARGSUSED */
24801 static int
24802 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24803     cred_t *cr)
24804 {
24805 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24806 
24807 	/*
24808 	 * Basically, value contains a new pass phrase.  Pass it along!
24809 	 */
24810 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24811 	return (0);
24812 }
24813 
24814 /* ARGSUSED */
24815 static int
24816 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24817 {
24818 	bzero(buf, sizeof (tcp_sack_info_t));
24819 	return (0);
24820 }
24821 
24822 /* ARGSUSED */
24823 static int
24824 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24825 {
24826 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24827 	return (0);
24828 }
24829 
24830 /*
24831  * Make sure we wait until the default queue is setup, yet allow
24832  * tcp_g_q_create() to open a TCP stream.
24833  * We need to allow tcp_g_q_create() do do an open
24834  * of tcp, hence we compare curhread.
24835  * All others have to wait until the tcps_g_q has been
24836  * setup.
24837  */
24838 void
24839 tcp_g_q_setup(tcp_stack_t *tcps)
24840 {
24841 	mutex_enter(&tcps->tcps_g_q_lock);
24842 	if (tcps->tcps_g_q != NULL) {
24843 		mutex_exit(&tcps->tcps_g_q_lock);
24844 		return;
24845 	}
24846 	if (tcps->tcps_g_q_creator == NULL) {
24847 		/* This thread will set it up */
24848 		tcps->tcps_g_q_creator = curthread;
24849 		mutex_exit(&tcps->tcps_g_q_lock);
24850 		tcp_g_q_create(tcps);
24851 		mutex_enter(&tcps->tcps_g_q_lock);
24852 		ASSERT(tcps->tcps_g_q_creator == curthread);
24853 		tcps->tcps_g_q_creator = NULL;
24854 		cv_signal(&tcps->tcps_g_q_cv);
24855 		ASSERT(tcps->tcps_g_q != NULL);
24856 		mutex_exit(&tcps->tcps_g_q_lock);
24857 		return;
24858 	}
24859 	/* Everybody but the creator has to wait */
24860 	if (tcps->tcps_g_q_creator != curthread) {
24861 		while (tcps->tcps_g_q == NULL)
24862 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24863 	}
24864 	mutex_exit(&tcps->tcps_g_q_lock);
24865 }
24866 
24867 major_t IP_MAJ;
24868 #define	IP	"ip"
24869 
24870 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24871 
24872 /*
24873  * Create a default tcp queue here instead of in strplumb
24874  */
24875 void
24876 tcp_g_q_create(tcp_stack_t *tcps)
24877 {
24878 	int error;
24879 	ldi_handle_t	lh = NULL;
24880 	ldi_ident_t	li = NULL;
24881 	int		rval;
24882 	cred_t		*cr;
24883 
24884 #ifdef NS_DEBUG
24885 	(void) printf("tcp_g_q_create()\n");
24886 #endif
24887 
24888 	ASSERT(tcps->tcps_g_q_creator == curthread);
24889 
24890 	error = ldi_ident_from_major(IP_MAJ, &li);
24891 	if (error) {
24892 #ifdef DEBUG
24893 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24894 		    error);
24895 #endif
24896 		return;
24897 	}
24898 
24899 	cr = zone_get_kcred(netstackid_to_zoneid(
24900 				tcps->tcps_netstack->netstack_stackid));
24901 	ASSERT(cr != NULL);
24902 	/*
24903 	 * We set the tcp default queue to IPv6 because IPv4 falls
24904 	 * back to IPv6 when it can't find a client, but
24905 	 * IPv6 does not fall back to IPv4.
24906 	 */
24907 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24908 	if (error) {
24909 #ifdef DEBUG
24910 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24911 		    error);
24912 #endif
24913 		goto out;
24914 	}
24915 
24916 	/*
24917 	 * This ioctl causes the tcp framework to cache a pointer to
24918 	 * this stream, so we don't want to close the stream after
24919 	 * this operation.
24920 	 * Use the kernel credentials that are for the zone we're in.
24921 	 */
24922 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24923 	    (intptr_t)0, FKIOCTL, cr, &rval);
24924 	if (error) {
24925 #ifdef DEBUG
24926 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24927 		    "error %d\n", error);
24928 #endif
24929 		goto out;
24930 	}
24931 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24932 	lh = NULL;
24933 out:
24934 	/* Close layered handles */
24935 	if (li)
24936 		ldi_ident_release(li);
24937 	/* Keep cred around until _inactive needs it */
24938 	tcps->tcps_g_q_cr = cr;
24939 }
24940 
24941 /*
24942  * We keep tcp_g_q set until all other tcp_t's in the zone
24943  * has gone away, and then when tcp_g_q_inactive() is called
24944  * we clear it.
24945  */
24946 void
24947 tcp_g_q_destroy(tcp_stack_t *tcps)
24948 {
24949 #ifdef NS_DEBUG
24950 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24951 	    tcps->tcps_netstack->netstack_stackid);
24952 #endif
24953 
24954 	if (tcps->tcps_g_q == NULL) {
24955 		return;	/* Nothing to cleanup */
24956 	}
24957 	/*
24958 	 * Drop reference corresponding to the default queue.
24959 	 * This reference was added from tcp_open when the default queue
24960 	 * was created, hence we compensate for this extra drop in
24961 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24962 	 * the default queue was the last one to be open, in which
24963 	 * case, then tcp_g_q_inactive will be
24964 	 * called as a result of the refrele.
24965 	 */
24966 	TCPS_REFRELE(tcps);
24967 }
24968 
24969 /*
24970  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24971  * Run by tcp_q_q_inactive using a taskq.
24972  */
24973 static void
24974 tcp_g_q_close(void *arg)
24975 {
24976 	tcp_stack_t *tcps = arg;
24977 	int error;
24978 	ldi_handle_t	lh = NULL;
24979 	ldi_ident_t	li = NULL;
24980 	cred_t		*cr;
24981 
24982 #ifdef NS_DEBUG
24983 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24984 	    tcps->tcps_netstack->netstack_stackid,
24985 	    tcps->tcps_netstack->netstack_refcnt);
24986 #endif
24987 	lh = tcps->tcps_g_q_lh;
24988 	if (lh == NULL)
24989 		return;	/* Nothing to cleanup */
24990 
24991 	ASSERT(tcps->tcps_refcnt == 1);
24992 	ASSERT(tcps->tcps_g_q != NULL);
24993 
24994 	error = ldi_ident_from_major(IP_MAJ, &li);
24995 	if (error) {
24996 #ifdef DEBUG
24997 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24998 		    error);
24999 #endif
25000 		return;
25001 	}
25002 
25003 	cr = tcps->tcps_g_q_cr;
25004 	tcps->tcps_g_q_cr = NULL;
25005 	ASSERT(cr != NULL);
25006 
25007 	/*
25008 	 * Make sure we can break the recursion when tcp_close decrements
25009 	 * the reference count causing g_q_inactive to be called again.
25010 	 */
25011 	tcps->tcps_g_q_lh = NULL;
25012 
25013 	/* close the default queue */
25014 	(void) ldi_close(lh, FREAD|FWRITE, cr);
25015 	/*
25016 	 * At this point in time tcps and the rest of netstack_t might
25017 	 * have been deleted.
25018 	 */
25019 	tcps = NULL;
25020 
25021 	/* Close layered handles */
25022 	ldi_ident_release(li);
25023 	crfree(cr);
25024 }
25025 
25026 /*
25027  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25028  *
25029  * Have to ensure that the ldi routines are not used by an
25030  * interrupt thread by using a taskq.
25031  */
25032 void
25033 tcp_g_q_inactive(tcp_stack_t *tcps)
25034 {
25035 	if (tcps->tcps_g_q_lh == NULL)
25036 		return;	/* Nothing to cleanup */
25037 
25038 	ASSERT(tcps->tcps_refcnt == 0);
25039 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
25040 
25041 	if (servicing_interrupt()) {
25042 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
25043 			    (void *) tcps, TQ_SLEEP);
25044 	} else {
25045 		tcp_g_q_close(tcps);
25046 	}
25047 }
25048 
25049 /*
25050  * Called by IP when IP is loaded into the kernel
25051  */
25052 void
25053 tcp_ddi_g_init(void)
25054 {
25055 	IP_MAJ = ddi_name_to_major(IP);
25056 
25057 	tcp_timercache = kmem_cache_create("tcp_timercache",
25058 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
25059 	    NULL, NULL, NULL, NULL, NULL, 0);
25060 
25061 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
25062 	    sizeof (tcp_sack_info_t), 0,
25063 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
25064 
25065 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
25066 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
25067 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
25068 
25069 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
25070 
25071 	/* Initialize the random number generator */
25072 	tcp_random_init();
25073 
25074 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
25075 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
25076 
25077 	/* A single callback independently of how many netstacks we have */
25078 	ip_squeue_init(tcp_squeue_add);
25079 
25080 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
25081 
25082 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
25083 	    TASKQ_PREPOPULATE);
25084 
25085 	/*
25086 	 * We want to be informed each time a stack is created or
25087 	 * destroyed in the kernel, so we can maintain the
25088 	 * set of tcp_stack_t's.
25089 	 */
25090 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
25091 	    tcp_stack_fini);
25092 }
25093 
25094 
25095 /*
25096  * Initialize the TCP stack instance.
25097  */
25098 static void *
25099 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
25100 {
25101 	tcp_stack_t	*tcps;
25102 	tcpparam_t	*pa;
25103 	int		i;
25104 
25105 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
25106 	tcps->tcps_netstack = ns;
25107 
25108 	/* Initialize locks */
25109 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
25110 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
25111 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
25112 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
25113 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
25114 	rw_init(&tcps->tcps_reserved_port_lock, NULL, RW_DEFAULT, NULL);
25115 
25116 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
25117 	tcps->tcps_g_epriv_ports[0] = 2049;
25118 	tcps->tcps_g_epriv_ports[1] = 4045;
25119 	tcps->tcps_min_anonpriv_port = 512;
25120 
25121 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
25122 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
25123 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
25124 	    TCP_FANOUT_SIZE, KM_SLEEP);
25125 	tcps->tcps_reserved_port = kmem_zalloc(sizeof (tcp_rport_t) *
25126 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE, KM_SLEEP);
25127 
25128 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25129 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
25130 		    MUTEX_DEFAULT, NULL);
25131 	}
25132 
25133 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25134 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25135 		    MUTEX_DEFAULT, NULL);
25136 	}
25137 
25138 	/* TCP's IPsec code calls the packet dropper. */
25139 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25140 
25141 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25142 	tcps->tcps_params = pa;
25143 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25144 
25145 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25146 	    A_CNT(lcl_tcp_param_arr), tcps);
25147 
25148 	/*
25149 	 * Note: To really walk the device tree you need the devinfo
25150 	 * pointer to your device which is only available after probe/attach.
25151 	 * The following is safe only because it uses ddi_root_node()
25152 	 */
25153 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25154 	    tcp_opt_obj.odb_opt_arr_cnt);
25155 
25156 	/*
25157 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25158 	 * by the boot scripts.
25159 	 *
25160 	 * Use NULL name, as the name is caught by the new lockstats.
25161 	 *
25162 	 * Initialize with some random, non-guessable string, like the global
25163 	 * T_INFO_ACK.
25164 	 */
25165 
25166 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25167 	    sizeof (tcp_g_t_info_ack), tcps);
25168 
25169 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25170 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25171 
25172 	return (tcps);
25173 }
25174 
25175 /*
25176  * Called when the IP module is about to be unloaded.
25177  */
25178 void
25179 tcp_ddi_g_destroy(void)
25180 {
25181 	tcp_g_kstat_fini(tcp_g_kstat);
25182 	tcp_g_kstat = NULL;
25183 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25184 
25185 	mutex_destroy(&tcp_random_lock);
25186 
25187 	kmem_cache_destroy(tcp_timercache);
25188 	kmem_cache_destroy(tcp_sack_info_cache);
25189 	kmem_cache_destroy(tcp_iphc_cache);
25190 
25191 	netstack_unregister(NS_TCP);
25192 	taskq_destroy(tcp_taskq);
25193 }
25194 
25195 /*
25196  * Shut down the TCP stack instance.
25197  */
25198 /* ARGSUSED */
25199 static void
25200 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25201 {
25202 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25203 
25204 	tcp_g_q_destroy(tcps);
25205 }
25206 
25207 /*
25208  * Free the TCP stack instance.
25209  */
25210 static void
25211 tcp_stack_fini(netstackid_t stackid, void *arg)
25212 {
25213 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25214 	int i;
25215 
25216 	nd_free(&tcps->tcps_g_nd);
25217 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25218 	tcps->tcps_params = NULL;
25219 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25220 	tcps->tcps_wroff_xtra_param = NULL;
25221 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25222 	tcps->tcps_mdt_head_param = NULL;
25223 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25224 	tcps->tcps_mdt_tail_param = NULL;
25225 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25226 	tcps->tcps_mdt_max_pbufs_param = NULL;
25227 
25228 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25229 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25230 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25231 	}
25232 
25233 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25234 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25235 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25236 	}
25237 
25238 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25239 	tcps->tcps_bind_fanout = NULL;
25240 
25241 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25242 	tcps->tcps_acceptor_fanout = NULL;
25243 
25244 	kmem_free(tcps->tcps_reserved_port, sizeof (tcp_rport_t) *
25245 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE);
25246 	tcps->tcps_reserved_port = NULL;
25247 
25248 	mutex_destroy(&tcps->tcps_iss_key_lock);
25249 	rw_destroy(&tcps->tcps_hsp_lock);
25250 	mutex_destroy(&tcps->tcps_g_q_lock);
25251 	cv_destroy(&tcps->tcps_g_q_cv);
25252 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25253 	rw_destroy(&tcps->tcps_reserved_port_lock);
25254 
25255 	ip_drop_unregister(&tcps->tcps_dropper);
25256 
25257 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25258 	tcps->tcps_kstat = NULL;
25259 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25260 
25261 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25262 	tcps->tcps_mibkp = NULL;
25263 
25264 	kmem_free(tcps, sizeof (*tcps));
25265 }
25266 
25267 /*
25268  * Generate ISS, taking into account NDD changes may happen halfway through.
25269  * (If the iss is not zero, set it.)
25270  */
25271 
25272 static void
25273 tcp_iss_init(tcp_t *tcp)
25274 {
25275 	MD5_CTX context;
25276 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25277 	uint32_t answer[4];
25278 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25279 
25280 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25281 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25282 	switch (tcps->tcps_strong_iss) {
25283 	case 2:
25284 		mutex_enter(&tcps->tcps_iss_key_lock);
25285 		context = tcps->tcps_iss_key;
25286 		mutex_exit(&tcps->tcps_iss_key_lock);
25287 		arg.ports = tcp->tcp_ports;
25288 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25289 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25290 			    &arg.src);
25291 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25292 			    &arg.dst);
25293 		} else {
25294 			arg.src = tcp->tcp_ip6h->ip6_src;
25295 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25296 		}
25297 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25298 		MD5Final((uchar_t *)answer, &context);
25299 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25300 		/*
25301 		 * Now that we've hashed into a unique per-connection sequence
25302 		 * space, add a random increment per strong_iss == 1.  So I
25303 		 * guess we'll have to...
25304 		 */
25305 		/* FALLTHRU */
25306 	case 1:
25307 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25308 		break;
25309 	default:
25310 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25311 		break;
25312 	}
25313 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25314 	tcp->tcp_fss = tcp->tcp_iss - 1;
25315 	tcp->tcp_suna = tcp->tcp_iss;
25316 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25317 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25318 	tcp->tcp_csuna = tcp->tcp_snxt;
25319 }
25320 
25321 /*
25322  * Exported routine for extracting active tcp connection status.
25323  *
25324  * This is used by the Solaris Cluster Networking software to
25325  * gather a list of connections that need to be forwarded to
25326  * specific nodes in the cluster when configuration changes occur.
25327  *
25328  * The callback is invoked for each tcp_t structure. Returning
25329  * non-zero from the callback routine terminates the search.
25330  */
25331 int
25332 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25333     void *arg)
25334 {
25335 	netstack_handle_t nh;
25336 	netstack_t *ns;
25337 	int ret = 0;
25338 
25339 	netstack_next_init(&nh);
25340 	while ((ns = netstack_next(&nh)) != NULL) {
25341 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25342 		    ns->netstack_tcp);
25343 		netstack_rele(ns);
25344 	}
25345 	netstack_next_fini(&nh);
25346 	return (ret);
25347 }
25348 
25349 static int
25350 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25351     tcp_stack_t *tcps)
25352 {
25353 	tcp_t *tcp;
25354 	cl_tcp_info_t	cl_tcpi;
25355 	connf_t	*connfp;
25356 	conn_t	*connp;
25357 	int	i;
25358 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25359 
25360 	ASSERT(callback != NULL);
25361 
25362 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25363 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25364 		connp = NULL;
25365 
25366 		while ((connp =
25367 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25368 
25369 			tcp = connp->conn_tcp;
25370 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25371 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25372 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25373 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25374 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25375 			/*
25376 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25377 			 * addresses. They are copied implicitly below as
25378 			 * mapped addresses.
25379 			 */
25380 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25381 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25382 				cl_tcpi.cl_tcpi_faddr =
25383 				    tcp->tcp_ipha->ipha_dst;
25384 			} else {
25385 				cl_tcpi.cl_tcpi_faddr_v6 =
25386 				    tcp->tcp_ip6h->ip6_dst;
25387 			}
25388 
25389 			/*
25390 			 * If the callback returns non-zero
25391 			 * we terminate the traversal.
25392 			 */
25393 			if ((*callback)(&cl_tcpi, arg) != 0) {
25394 				CONN_DEC_REF(tcp->tcp_connp);
25395 				return (1);
25396 			}
25397 		}
25398 	}
25399 
25400 	return (0);
25401 }
25402 
25403 /*
25404  * Macros used for accessing the different types of sockaddr
25405  * structures inside a tcp_ioc_abort_conn_t.
25406  */
25407 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25408 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25409 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25410 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25411 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25412 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25413 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25414 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25415 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25416 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25417 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25418 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25419 
25420 /*
25421  * Return the correct error code to mimic the behavior
25422  * of a connection reset.
25423  */
25424 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25425 		switch ((state)) {		\
25426 		case TCPS_SYN_SENT:		\
25427 		case TCPS_SYN_RCVD:		\
25428 			(err) = ECONNREFUSED;	\
25429 			break;			\
25430 		case TCPS_ESTABLISHED:		\
25431 		case TCPS_FIN_WAIT_1:		\
25432 		case TCPS_FIN_WAIT_2:		\
25433 		case TCPS_CLOSE_WAIT:		\
25434 			(err) = ECONNRESET;	\
25435 			break;			\
25436 		case TCPS_CLOSING:		\
25437 		case TCPS_LAST_ACK:		\
25438 		case TCPS_TIME_WAIT:		\
25439 			(err) = 0;		\
25440 			break;			\
25441 		default:			\
25442 			(err) = ENXIO;		\
25443 		}				\
25444 	}
25445 
25446 /*
25447  * Check if a tcp structure matches the info in acp.
25448  */
25449 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25450 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25451 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25452 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25453 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25454 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25455 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25456 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25457 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25458 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25459 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25460 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25461 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25462 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25463 	&(tcp)->tcp_ip_src_v6)) &&				\
25464 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25465 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25466 	&(tcp)->tcp_remote_v6)) &&				\
25467 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25468 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25469 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25470 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25471 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25472 	(acp)->ac_end >= (tcp)->tcp_state))
25473 
25474 #define	TCP_AC_MATCH(acp, tcp)					\
25475 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25476 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25477 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25478 
25479 /*
25480  * Build a message containing a tcp_ioc_abort_conn_t structure
25481  * which is filled in with information from acp and tp.
25482  */
25483 static mblk_t *
25484 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25485 {
25486 	mblk_t *mp;
25487 	tcp_ioc_abort_conn_t *tacp;
25488 
25489 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25490 	if (mp == NULL)
25491 		return (NULL);
25492 
25493 	mp->b_datap->db_type = M_CTL;
25494 
25495 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25496 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25497 		sizeof (uint32_t));
25498 
25499 	tacp->ac_start = acp->ac_start;
25500 	tacp->ac_end = acp->ac_end;
25501 	tacp->ac_zoneid = acp->ac_zoneid;
25502 
25503 	if (acp->ac_local.ss_family == AF_INET) {
25504 		tacp->ac_local.ss_family = AF_INET;
25505 		tacp->ac_remote.ss_family = AF_INET;
25506 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25507 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25508 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25509 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25510 	} else {
25511 		tacp->ac_local.ss_family = AF_INET6;
25512 		tacp->ac_remote.ss_family = AF_INET6;
25513 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25514 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25515 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25516 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25517 	}
25518 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25519 	return (mp);
25520 }
25521 
25522 /*
25523  * Print a tcp_ioc_abort_conn_t structure.
25524  */
25525 static void
25526 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25527 {
25528 	char lbuf[128];
25529 	char rbuf[128];
25530 	sa_family_t af;
25531 	in_port_t lport, rport;
25532 	ushort_t logflags;
25533 
25534 	af = acp->ac_local.ss_family;
25535 
25536 	if (af == AF_INET) {
25537 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25538 				lbuf, 128);
25539 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25540 				rbuf, 128);
25541 		lport = ntohs(TCP_AC_V4LPORT(acp));
25542 		rport = ntohs(TCP_AC_V4RPORT(acp));
25543 	} else {
25544 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25545 				lbuf, 128);
25546 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25547 				rbuf, 128);
25548 		lport = ntohs(TCP_AC_V6LPORT(acp));
25549 		rport = ntohs(TCP_AC_V6RPORT(acp));
25550 	}
25551 
25552 	logflags = SL_TRACE | SL_NOTE;
25553 	/*
25554 	 * Don't print this message to the console if the operation was done
25555 	 * to a non-global zone.
25556 	 */
25557 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25558 		logflags |= SL_CONSOLE;
25559 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25560 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25561 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25562 		acp->ac_start, acp->ac_end);
25563 }
25564 
25565 /*
25566  * Called inside tcp_rput when a message built using
25567  * tcp_ioctl_abort_build_msg is put into a queue.
25568  * Note that when we get here there is no wildcard in acp any more.
25569  */
25570 static void
25571 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25572 {
25573 	tcp_ioc_abort_conn_t *acp;
25574 
25575 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25576 	if (tcp->tcp_state <= acp->ac_end) {
25577 		/*
25578 		 * If we get here, we are already on the correct
25579 		 * squeue. This ioctl follows the following path
25580 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25581 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25582 		 * different squeue)
25583 		 */
25584 		int errcode;
25585 
25586 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25587 		(void) tcp_clean_death(tcp, errcode, 26);
25588 	}
25589 	freemsg(mp);
25590 }
25591 
25592 /*
25593  * Abort all matching connections on a hash chain.
25594  */
25595 static int
25596 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25597     boolean_t exact, tcp_stack_t *tcps)
25598 {
25599 	int nmatch, err = 0;
25600 	tcp_t *tcp;
25601 	MBLKP mp, last, listhead = NULL;
25602 	conn_t	*tconnp;
25603 	connf_t	*connfp;
25604 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25605 
25606 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25607 
25608 startover:
25609 	nmatch = 0;
25610 
25611 	mutex_enter(&connfp->connf_lock);
25612 	for (tconnp = connfp->connf_head; tconnp != NULL;
25613 	    tconnp = tconnp->conn_next) {
25614 		tcp = tconnp->conn_tcp;
25615 		if (TCP_AC_MATCH(acp, tcp)) {
25616 			CONN_INC_REF(tcp->tcp_connp);
25617 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25618 			if (mp == NULL) {
25619 				err = ENOMEM;
25620 				CONN_DEC_REF(tcp->tcp_connp);
25621 				break;
25622 			}
25623 			mp->b_prev = (mblk_t *)tcp;
25624 
25625 			if (listhead == NULL) {
25626 				listhead = mp;
25627 				last = mp;
25628 			} else {
25629 				last->b_next = mp;
25630 				last = mp;
25631 			}
25632 			nmatch++;
25633 			if (exact)
25634 				break;
25635 		}
25636 
25637 		/* Avoid holding lock for too long. */
25638 		if (nmatch >= 500)
25639 			break;
25640 	}
25641 	mutex_exit(&connfp->connf_lock);
25642 
25643 	/* Pass mp into the correct tcp */
25644 	while ((mp = listhead) != NULL) {
25645 		listhead = listhead->b_next;
25646 		tcp = (tcp_t *)mp->b_prev;
25647 		mp->b_next = mp->b_prev = NULL;
25648 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25649 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25650 	}
25651 
25652 	*count += nmatch;
25653 	if (nmatch >= 500 && err == 0)
25654 		goto startover;
25655 	return (err);
25656 }
25657 
25658 /*
25659  * Abort all connections that matches the attributes specified in acp.
25660  */
25661 static int
25662 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25663 {
25664 	sa_family_t af;
25665 	uint32_t  ports;
25666 	uint16_t *pports;
25667 	int err = 0, count = 0;
25668 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25669 	int index = -1;
25670 	ushort_t logflags;
25671 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25672 
25673 	af = acp->ac_local.ss_family;
25674 
25675 	if (af == AF_INET) {
25676 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25677 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25678 			pports = (uint16_t *)&ports;
25679 			pports[1] = TCP_AC_V4LPORT(acp);
25680 			pports[0] = TCP_AC_V4RPORT(acp);
25681 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25682 		}
25683 	} else {
25684 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25685 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25686 			pports = (uint16_t *)&ports;
25687 			pports[1] = TCP_AC_V6LPORT(acp);
25688 			pports[0] = TCP_AC_V6RPORT(acp);
25689 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25690 		}
25691 	}
25692 
25693 	/*
25694 	 * For cases where remote addr, local port, and remote port are non-
25695 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25696 	 */
25697 	if (index != -1) {
25698 		err = tcp_ioctl_abort_bucket(acp, index,
25699 			    &count, exact, tcps);
25700 	} else {
25701 		/*
25702 		 * loop through all entries for wildcard case
25703 		 */
25704 		for (index = 0;
25705 		    index < ipst->ips_ipcl_conn_fanout_size;
25706 		    index++) {
25707 			err = tcp_ioctl_abort_bucket(acp, index,
25708 			    &count, exact, tcps);
25709 			if (err != 0)
25710 				break;
25711 		}
25712 	}
25713 
25714 	logflags = SL_TRACE | SL_NOTE;
25715 	/*
25716 	 * Don't print this message to the console if the operation was done
25717 	 * to a non-global zone.
25718 	 */
25719 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25720 		logflags |= SL_CONSOLE;
25721 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25722 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25723 	if (err == 0 && count == 0)
25724 		err = ENOENT;
25725 	return (err);
25726 }
25727 
25728 /*
25729  * Process the TCP_IOC_ABORT_CONN ioctl request.
25730  */
25731 static void
25732 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25733 {
25734 	int	err;
25735 	IOCP    iocp;
25736 	MBLKP   mp1;
25737 	sa_family_t laf, raf;
25738 	tcp_ioc_abort_conn_t *acp;
25739 	zone_t		*zptr;
25740 	conn_t		*connp = Q_TO_CONN(q);
25741 	zoneid_t	zoneid = connp->conn_zoneid;
25742 	tcp_t		*tcp = connp->conn_tcp;
25743 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25744 
25745 	iocp = (IOCP)mp->b_rptr;
25746 
25747 	if ((mp1 = mp->b_cont) == NULL ||
25748 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25749 		err = EINVAL;
25750 		goto out;
25751 	}
25752 
25753 	/* check permissions */
25754 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25755 		err = EPERM;
25756 		goto out;
25757 	}
25758 
25759 	if (mp1->b_cont != NULL) {
25760 		freemsg(mp1->b_cont);
25761 		mp1->b_cont = NULL;
25762 	}
25763 
25764 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25765 	laf = acp->ac_local.ss_family;
25766 	raf = acp->ac_remote.ss_family;
25767 
25768 	/* check that a zone with the supplied zoneid exists */
25769 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25770 		zptr = zone_find_by_id(zoneid);
25771 		if (zptr != NULL) {
25772 			zone_rele(zptr);
25773 		} else {
25774 			err = EINVAL;
25775 			goto out;
25776 		}
25777 	}
25778 
25779 	/*
25780 	 * For exclusive stacks we set the zoneid to zero
25781 	 * to make TCP operate as if in the global zone.
25782 	 */
25783 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25784 		acp->ac_zoneid = GLOBAL_ZONEID;
25785 
25786 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25787 	    acp->ac_start > acp->ac_end || laf != raf ||
25788 	    (laf != AF_INET && laf != AF_INET6)) {
25789 		err = EINVAL;
25790 		goto out;
25791 	}
25792 
25793 	tcp_ioctl_abort_dump(acp);
25794 	err = tcp_ioctl_abort(acp, tcps);
25795 
25796 out:
25797 	if (mp1 != NULL) {
25798 		freemsg(mp1);
25799 		mp->b_cont = NULL;
25800 	}
25801 
25802 	if (err != 0)
25803 		miocnak(q, mp, 0, err);
25804 	else
25805 		miocack(q, mp, 0, 0);
25806 }
25807 
25808 /*
25809  * tcp_time_wait_processing() handles processing of incoming packets when
25810  * the tcp is in the TIME_WAIT state.
25811  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25812  * on the time wait list.
25813  */
25814 void
25815 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25816     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25817 {
25818 	int32_t		bytes_acked;
25819 	int32_t		gap;
25820 	int32_t		rgap;
25821 	tcp_opt_t	tcpopt;
25822 	uint_t		flags;
25823 	uint32_t	new_swnd = 0;
25824 	conn_t		*connp;
25825 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25826 
25827 	BUMP_LOCAL(tcp->tcp_ibsegs);
25828 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
25829 
25830 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25831 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25832 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25833 	if (tcp->tcp_snd_ts_ok) {
25834 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25835 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25836 			    tcp->tcp_rnxt, TH_ACK);
25837 			goto done;
25838 		}
25839 	}
25840 	gap = seg_seq - tcp->tcp_rnxt;
25841 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25842 	if (gap < 0) {
25843 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25844 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25845 		    (seg_len > -gap ? -gap : seg_len));
25846 		seg_len += gap;
25847 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25848 			if (flags & TH_RST) {
25849 				goto done;
25850 			}
25851 			if ((flags & TH_FIN) && seg_len == -1) {
25852 				/*
25853 				 * When TCP receives a duplicate FIN in
25854 				 * TIME_WAIT state, restart the 2 MSL timer.
25855 				 * See page 73 in RFC 793. Make sure this TCP
25856 				 * is already on the TIME_WAIT list. If not,
25857 				 * just restart the timer.
25858 				 */
25859 				if (TCP_IS_DETACHED(tcp)) {
25860 					if (tcp_time_wait_remove(tcp, NULL) ==
25861 					    B_TRUE) {
25862 						tcp_time_wait_append(tcp);
25863 						TCP_DBGSTAT(tcps,
25864 						    tcp_rput_time_wait);
25865 					}
25866 				} else {
25867 					ASSERT(tcp != NULL);
25868 					TCP_TIMER_RESTART(tcp,
25869 					    tcps->tcps_time_wait_interval);
25870 				}
25871 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25872 				    tcp->tcp_rnxt, TH_ACK);
25873 				goto done;
25874 			}
25875 			flags |=  TH_ACK_NEEDED;
25876 			seg_len = 0;
25877 			goto process_ack;
25878 		}
25879 
25880 		/* Fix seg_seq, and chew the gap off the front. */
25881 		seg_seq = tcp->tcp_rnxt;
25882 	}
25883 
25884 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25885 		/*
25886 		 * Make sure that when we accept the connection, pick
25887 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25888 		 * old connection.
25889 		 *
25890 		 * The next ISS generated is equal to tcp_iss_incr_extra
25891 		 * + ISS_INCR/2 + other components depending on the
25892 		 * value of tcp_strong_iss.  We pre-calculate the new
25893 		 * ISS here and compare with tcp_snxt to determine if
25894 		 * we need to make adjustment to tcp_iss_incr_extra.
25895 		 *
25896 		 * The above calculation is ugly and is a
25897 		 * waste of CPU cycles...
25898 		 */
25899 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25900 		int32_t adj;
25901 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25902 
25903 		switch (tcps->tcps_strong_iss) {
25904 		case 2: {
25905 			/* Add time and MD5 components. */
25906 			uint32_t answer[4];
25907 			struct {
25908 				uint32_t ports;
25909 				in6_addr_t src;
25910 				in6_addr_t dst;
25911 			} arg;
25912 			MD5_CTX context;
25913 
25914 			mutex_enter(&tcps->tcps_iss_key_lock);
25915 			context = tcps->tcps_iss_key;
25916 			mutex_exit(&tcps->tcps_iss_key_lock);
25917 			arg.ports = tcp->tcp_ports;
25918 			/* We use MAPPED addresses in tcp_iss_init */
25919 			arg.src = tcp->tcp_ip_src_v6;
25920 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25921 				IN6_IPADDR_TO_V4MAPPED(
25922 					tcp->tcp_ipha->ipha_dst,
25923 					    &arg.dst);
25924 			} else {
25925 				arg.dst =
25926 				    tcp->tcp_ip6h->ip6_dst;
25927 			}
25928 			MD5Update(&context, (uchar_t *)&arg,
25929 			    sizeof (arg));
25930 			MD5Final((uchar_t *)answer, &context);
25931 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25932 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25933 			break;
25934 		}
25935 		case 1:
25936 			/* Add time component and min random (i.e. 1). */
25937 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25938 			break;
25939 		default:
25940 			/* Add only time component. */
25941 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25942 			break;
25943 		}
25944 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25945 			/*
25946 			 * New ISS not guaranteed to be ISS_INCR/2
25947 			 * ahead of the current tcp_snxt, so add the
25948 			 * difference to tcp_iss_incr_extra.
25949 			 */
25950 			tcps->tcps_iss_incr_extra += adj;
25951 		}
25952 		/*
25953 		 * If tcp_clean_death() can not perform the task now,
25954 		 * drop the SYN packet and let the other side re-xmit.
25955 		 * Otherwise pass the SYN packet back in, since the
25956 		 * old tcp state has been cleaned up or freed.
25957 		 */
25958 		if (tcp_clean_death(tcp, 0, 27) == -1)
25959 			goto done;
25960 		/*
25961 		 * We will come back to tcp_rput_data
25962 		 * on the global queue. Packets destined
25963 		 * for the global queue will be checked
25964 		 * with global policy. But the policy for
25965 		 * this packet has already been checked as
25966 		 * this was destined for the detached
25967 		 * connection. We need to bypass policy
25968 		 * check this time by attaching a dummy
25969 		 * ipsec_in with ipsec_in_dont_check set.
25970 		 */
25971 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25972 		if (connp != NULL) {
25973 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25974 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25975 			return;
25976 		}
25977 		goto done;
25978 	}
25979 
25980 	/*
25981 	 * rgap is the amount of stuff received out of window.  A negative
25982 	 * value is the amount out of window.
25983 	 */
25984 	if (rgap < 0) {
25985 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25986 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25987 		/* Fix seg_len and make sure there is something left. */
25988 		seg_len += rgap;
25989 		if (seg_len <= 0) {
25990 			if (flags & TH_RST) {
25991 				goto done;
25992 			}
25993 			flags |=  TH_ACK_NEEDED;
25994 			seg_len = 0;
25995 			goto process_ack;
25996 		}
25997 	}
25998 	/*
25999 	 * Check whether we can update tcp_ts_recent.  This test is
26000 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
26001 	 * Extensions for High Performance: An Update", Internet Draft.
26002 	 */
26003 	if (tcp->tcp_snd_ts_ok &&
26004 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
26005 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
26006 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
26007 		tcp->tcp_last_rcv_lbolt = lbolt64;
26008 	}
26009 
26010 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
26011 		/* Always ack out of order packets */
26012 		flags |= TH_ACK_NEEDED;
26013 		seg_len = 0;
26014 	} else if (seg_len > 0) {
26015 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
26016 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
26017 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
26018 	}
26019 	if (flags & TH_RST) {
26020 		(void) tcp_clean_death(tcp, 0, 28);
26021 		goto done;
26022 	}
26023 	if (flags & TH_SYN) {
26024 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
26025 		    TH_RST|TH_ACK);
26026 		/*
26027 		 * Do not delete the TCP structure if it is in
26028 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
26029 		 */
26030 		goto done;
26031 	}
26032 process_ack:
26033 	if (flags & TH_ACK) {
26034 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
26035 		if (bytes_acked <= 0) {
26036 			if (bytes_acked == 0 && seg_len == 0 &&
26037 			    new_swnd == tcp->tcp_swnd)
26038 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
26039 		} else {
26040 			/* Acks something not sent */
26041 			flags |= TH_ACK_NEEDED;
26042 		}
26043 	}
26044 	if (flags & TH_ACK_NEEDED) {
26045 		/*
26046 		 * Time to send an ack for some reason.
26047 		 */
26048 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26049 		    tcp->tcp_rnxt, TH_ACK);
26050 	}
26051 done:
26052 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26053 		DB_CKSUMSTART(mp) = 0;
26054 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
26055 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
26056 	}
26057 	freemsg(mp);
26058 }
26059 
26060 /*
26061  * Allocate a T_SVR4_OPTMGMT_REQ.
26062  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
26063  * that tcp_rput_other can drop the acks.
26064  */
26065 static mblk_t *
26066 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
26067 {
26068 	mblk_t *mp;
26069 	struct T_optmgmt_req *tor;
26070 	struct opthdr *oh;
26071 	uint_t size;
26072 	char *optptr;
26073 
26074 	size = sizeof (*tor) + sizeof (*oh) + optlen;
26075 	mp = allocb(size, BPRI_MED);
26076 	if (mp == NULL)
26077 		return (NULL);
26078 
26079 	mp->b_wptr += size;
26080 	mp->b_datap->db_type = M_PROTO;
26081 	tor = (struct T_optmgmt_req *)mp->b_rptr;
26082 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
26083 	tor->MGMT_flags = T_NEGOTIATE;
26084 	tor->OPT_length = sizeof (*oh) + optlen;
26085 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
26086 
26087 	oh = (struct opthdr *)&tor[1];
26088 	oh->level = level;
26089 	oh->name = cmd;
26090 	oh->len = optlen;
26091 	if (optlen != 0) {
26092 		optptr = (char *)&oh[1];
26093 		bcopy(opt, optptr, optlen);
26094 	}
26095 	return (mp);
26096 }
26097 
26098 /*
26099  * TCP Timers Implementation.
26100  */
26101 timeout_id_t
26102 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
26103 {
26104 	mblk_t *mp;
26105 	tcp_timer_t *tcpt;
26106 	tcp_t *tcp = connp->conn_tcp;
26107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26108 
26109 	ASSERT(connp->conn_sqp != NULL);
26110 
26111 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
26112 
26113 	if (tcp->tcp_timercache == NULL) {
26114 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
26115 	} else {
26116 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
26117 		mp = tcp->tcp_timercache;
26118 		tcp->tcp_timercache = mp->b_next;
26119 		mp->b_next = NULL;
26120 		ASSERT(mp->b_wptr == NULL);
26121 	}
26122 
26123 	CONN_INC_REF(connp);
26124 	tcpt = (tcp_timer_t *)mp->b_rptr;
26125 	tcpt->connp = connp;
26126 	tcpt->tcpt_proc = f;
26127 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
26128 	return ((timeout_id_t)mp);
26129 }
26130 
26131 static void
26132 tcp_timer_callback(void *arg)
26133 {
26134 	mblk_t *mp = (mblk_t *)arg;
26135 	tcp_timer_t *tcpt;
26136 	conn_t	*connp;
26137 
26138 	tcpt = (tcp_timer_t *)mp->b_rptr;
26139 	connp = tcpt->connp;
26140 	squeue_fill(connp->conn_sqp, mp,
26141 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26142 }
26143 
26144 static void
26145 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26146 {
26147 	tcp_timer_t *tcpt;
26148 	conn_t *connp = (conn_t *)arg;
26149 	tcp_t *tcp = connp->conn_tcp;
26150 
26151 	tcpt = (tcp_timer_t *)mp->b_rptr;
26152 	ASSERT(connp == tcpt->connp);
26153 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26154 
26155 	/*
26156 	 * If the TCP has reached the closed state, don't proceed any
26157 	 * further. This TCP logically does not exist on the system.
26158 	 * tcpt_proc could for example access queues, that have already
26159 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26160 	 */
26161 	if (tcp->tcp_state != TCPS_CLOSED) {
26162 		(*tcpt->tcpt_proc)(connp);
26163 	} else {
26164 		tcp->tcp_timer_tid = 0;
26165 	}
26166 	tcp_timer_free(connp->conn_tcp, mp);
26167 }
26168 
26169 /*
26170  * There is potential race with untimeout and the handler firing at the same
26171  * time. The mblock may be freed by the handler while we are trying to use
26172  * it. But since both should execute on the same squeue, this race should not
26173  * occur.
26174  */
26175 clock_t
26176 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26177 {
26178 	mblk_t	*mp = (mblk_t *)id;
26179 	tcp_timer_t *tcpt;
26180 	clock_t delta;
26181 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26182 
26183 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26184 
26185 	if (mp == NULL)
26186 		return (-1);
26187 
26188 	tcpt = (tcp_timer_t *)mp->b_rptr;
26189 	ASSERT(tcpt->connp == connp);
26190 
26191 	delta = untimeout(tcpt->tcpt_tid);
26192 
26193 	if (delta >= 0) {
26194 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26195 		tcp_timer_free(connp->conn_tcp, mp);
26196 		CONN_DEC_REF(connp);
26197 	}
26198 
26199 	return (delta);
26200 }
26201 
26202 /*
26203  * Allocate space for the timer event. The allocation looks like mblk, but it is
26204  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26205  *
26206  * Dealing with failures: If we can't allocate from the timer cache we try
26207  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26208  * points to b_rptr.
26209  * If we can't allocate anything using allocb_tryhard(), we perform a last
26210  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26211  * save the actual allocation size in b_datap.
26212  */
26213 mblk_t *
26214 tcp_timermp_alloc(int kmflags)
26215 {
26216 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26217 	    kmflags & ~KM_PANIC);
26218 
26219 	if (mp != NULL) {
26220 		mp->b_next = mp->b_prev = NULL;
26221 		mp->b_rptr = (uchar_t *)(&mp[1]);
26222 		mp->b_wptr = NULL;
26223 		mp->b_datap = NULL;
26224 		mp->b_queue = NULL;
26225 		mp->b_cont = NULL;
26226 	} else if (kmflags & KM_PANIC) {
26227 		/*
26228 		 * Failed to allocate memory for the timer. Try allocating from
26229 		 * dblock caches.
26230 		 */
26231 		/* ipclassifier calls this from a constructor - hence no tcps */
26232 		TCP_G_STAT(tcp_timermp_allocfail);
26233 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26234 		if (mp == NULL) {
26235 			size_t size = 0;
26236 			/*
26237 			 * Memory is really low. Try tryhard allocation.
26238 			 *
26239 			 * ipclassifier calls this from a constructor -
26240 			 * hence no tcps
26241 			 */
26242 			TCP_G_STAT(tcp_timermp_allocdblfail);
26243 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26244 			    sizeof (tcp_timer_t), &size, kmflags);
26245 			mp->b_rptr = (uchar_t *)(&mp[1]);
26246 			mp->b_next = mp->b_prev = NULL;
26247 			mp->b_wptr = (uchar_t *)-1;
26248 			mp->b_datap = (dblk_t *)size;
26249 			mp->b_queue = NULL;
26250 			mp->b_cont = NULL;
26251 		}
26252 		ASSERT(mp->b_wptr != NULL);
26253 	}
26254 	/* ipclassifier calls this from a constructor - hence no tcps */
26255 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26256 
26257 	return (mp);
26258 }
26259 
26260 /*
26261  * Free per-tcp timer cache.
26262  * It can only contain entries from tcp_timercache.
26263  */
26264 void
26265 tcp_timermp_free(tcp_t *tcp)
26266 {
26267 	mblk_t *mp;
26268 
26269 	while ((mp = tcp->tcp_timercache) != NULL) {
26270 		ASSERT(mp->b_wptr == NULL);
26271 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26272 		kmem_cache_free(tcp_timercache, mp);
26273 	}
26274 }
26275 
26276 /*
26277  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26278  * events there already (currently at most two events are cached).
26279  * If the event is not allocated from the timer cache, free it right away.
26280  */
26281 static void
26282 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26283 {
26284 	mblk_t *mp1 = tcp->tcp_timercache;
26285 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26286 
26287 	if (mp->b_wptr != NULL) {
26288 		/*
26289 		 * This allocation is not from a timer cache, free it right
26290 		 * away.
26291 		 */
26292 		if (mp->b_wptr != (uchar_t *)-1)
26293 			freeb(mp);
26294 		else
26295 			kmem_free(mp, (size_t)mp->b_datap);
26296 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26297 		/* Cache this timer block for future allocations */
26298 		mp->b_rptr = (uchar_t *)(&mp[1]);
26299 		mp->b_next = mp1;
26300 		tcp->tcp_timercache = mp;
26301 	} else {
26302 		kmem_cache_free(tcp_timercache, mp);
26303 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26304 	}
26305 }
26306 
26307 /*
26308  * End of TCP Timers implementation.
26309  */
26310 
26311 /*
26312  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26313  * on the specified backing STREAMS q. Note, the caller may make the
26314  * decision to call based on the tcp_t.tcp_flow_stopped value which
26315  * when check outside the q's lock is only an advisory check ...
26316  */
26317 
26318 void
26319 tcp_setqfull(tcp_t *tcp)
26320 {
26321 	queue_t *q = tcp->tcp_wq;
26322 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26323 
26324 	if (!(q->q_flag & QFULL)) {
26325 		mutex_enter(QLOCK(q));
26326 		if (!(q->q_flag & QFULL)) {
26327 			/* still need to set QFULL */
26328 			q->q_flag |= QFULL;
26329 			tcp->tcp_flow_stopped = B_TRUE;
26330 			mutex_exit(QLOCK(q));
26331 			TCP_STAT(tcps, tcp_flwctl_on);
26332 		} else {
26333 			mutex_exit(QLOCK(q));
26334 		}
26335 	}
26336 }
26337 
26338 void
26339 tcp_clrqfull(tcp_t *tcp)
26340 {
26341 	queue_t *q = tcp->tcp_wq;
26342 
26343 	if (q->q_flag & QFULL) {
26344 		mutex_enter(QLOCK(q));
26345 		if (q->q_flag & QFULL) {
26346 			q->q_flag &= ~QFULL;
26347 			tcp->tcp_flow_stopped = B_FALSE;
26348 			mutex_exit(QLOCK(q));
26349 			if (q->q_flag & QWANTW)
26350 				qbackenable(q, 0);
26351 		} else {
26352 			mutex_exit(QLOCK(q));
26353 		}
26354 	}
26355 }
26356 
26357 
26358 /*
26359  * kstats related to squeues i.e. not per IP instance
26360  */
26361 static void *
26362 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26363 {
26364 	kstat_t *ksp;
26365 
26366 	tcp_g_stat_t template = {
26367 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26368 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26369 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26370 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26371 	};
26372 
26373 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26374 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26375 	    KSTAT_FLAG_VIRTUAL);
26376 
26377 	if (ksp == NULL)
26378 		return (NULL);
26379 
26380 	bcopy(&template, tcp_g_statp, sizeof (template));
26381 	ksp->ks_data = (void *)tcp_g_statp;
26382 
26383 	kstat_install(ksp);
26384 	return (ksp);
26385 }
26386 
26387 static void
26388 tcp_g_kstat_fini(kstat_t *ksp)
26389 {
26390 	if (ksp != NULL) {
26391 		kstat_delete(ksp);
26392 	}
26393 }
26394 
26395 
26396 static void *
26397 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26398 {
26399 	kstat_t *ksp;
26400 
26401 	tcp_stat_t template = {
26402 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26403 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26404 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26405 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26406 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26407 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26408 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26409 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26410 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26411 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26412 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26413 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26414 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26415 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26416 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26417 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26418 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26419 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26420 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26421 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26422 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26423 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26424 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26425 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26426 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26427 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26428 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26429 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26430 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26431 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26432 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26433 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26434 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26435 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26436 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26437 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26438 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26439 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26440 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26441 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26442 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26443 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26444 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26445 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26446 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26447 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26448 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26449 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26450 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26451 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26452 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26453 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26454 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26455 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26456 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26457 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26458 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26459 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26460 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26461 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26462 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26463 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26464 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26465 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26466 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26467 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26468 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26469 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26470 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26471 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26472 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26473 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26474 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26475 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26476 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26477 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26478 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26479 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26480 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26481 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26482 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26483 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26484 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26485 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26486 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26487 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26488 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26489 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26490 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26491 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26492 	};
26493 
26494 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26495 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26496 	    KSTAT_FLAG_VIRTUAL, stackid);
26497 
26498 	if (ksp == NULL)
26499 		return (NULL);
26500 
26501 	bcopy(&template, tcps_statisticsp, sizeof (template));
26502 	ksp->ks_data = (void *)tcps_statisticsp;
26503 	ksp->ks_private = (void *)(uintptr_t)stackid;
26504 
26505 	kstat_install(ksp);
26506 	return (ksp);
26507 }
26508 
26509 static void
26510 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26511 {
26512 	if (ksp != NULL) {
26513 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26514 		kstat_delete_netstack(ksp, stackid);
26515 	}
26516 }
26517 
26518 /*
26519  * TCP Kstats implementation
26520  */
26521 static void *
26522 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26523 {
26524 	kstat_t	*ksp;
26525 
26526 	tcp_named_kstat_t template = {
26527 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26528 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26529 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26530 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26531 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26532 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26533 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26534 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26535 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26536 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26537 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26538 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26539 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26540 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26541 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26542 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26543 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26544 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26545 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26546 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26547 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26548 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26549 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26550 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26551 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26552 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26553 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26554 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26555 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26556 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26557 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26558 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26559 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26560 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26561 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26562 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26563 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26564 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26565 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26566 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26567 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26568 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26569 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26570 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26571 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26572 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26573 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26574 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26575 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26576 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26577 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26578 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26579 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26580 	};
26581 
26582 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26583 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26584 
26585 	if (ksp == NULL)
26586 		return (NULL);
26587 
26588 	template.rtoAlgorithm.value.ui32 = 4;
26589 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26590 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26591 	template.maxConn.value.i32 = -1;
26592 
26593 	bcopy(&template, ksp->ks_data, sizeof (template));
26594 	ksp->ks_update = tcp_kstat_update;
26595 	ksp->ks_private = (void *)(uintptr_t)stackid;
26596 
26597 	kstat_install(ksp);
26598 	return (ksp);
26599 }
26600 
26601 static void
26602 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26603 {
26604 	if (ksp != NULL) {
26605 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26606 		kstat_delete_netstack(ksp, stackid);
26607 	}
26608 }
26609 
26610 static int
26611 tcp_kstat_update(kstat_t *kp, int rw)
26612 {
26613 	tcp_named_kstat_t *tcpkp;
26614 	tcp_t		*tcp;
26615 	connf_t		*connfp;
26616 	conn_t		*connp;
26617 	int 		i;
26618 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26619 	netstack_t	*ns;
26620 	tcp_stack_t	*tcps;
26621 	ip_stack_t	*ipst;
26622 
26623 	if ((kp == NULL) || (kp->ks_data == NULL))
26624 		return (EIO);
26625 
26626 	if (rw == KSTAT_WRITE)
26627 		return (EACCES);
26628 
26629 	ns = netstack_find_by_stackid(stackid);
26630 	if (ns == NULL)
26631 		return (-1);
26632 	tcps = ns->netstack_tcp;
26633 	if (tcps == NULL) {
26634 		netstack_rele(ns);
26635 		return (-1);
26636 	}
26637 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26638 
26639 	tcpkp->currEstab.value.ui32 = 0;
26640 
26641 	ipst = ns->netstack_ip;
26642 
26643 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26644 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26645 		connp = NULL;
26646 		while ((connp =
26647 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26648 			tcp = connp->conn_tcp;
26649 			switch (tcp_snmp_state(tcp)) {
26650 			case MIB2_TCP_established:
26651 			case MIB2_TCP_closeWait:
26652 				tcpkp->currEstab.value.ui32++;
26653 				break;
26654 			}
26655 		}
26656 	}
26657 
26658 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26659 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26660 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26661 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26662 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26663 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26664 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26665 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26666 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26667 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26668 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26669 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26670 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26671 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26672 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26673 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26674 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26675 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26676 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26677 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26678 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26679 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26680 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26681 	tcpkp->inDataInorderSegs.value.ui32 =
26682 	    tcps->tcps_mib.tcpInDataInorderSegs;
26683 	tcpkp->inDataInorderBytes.value.ui32 =
26684 	    tcps->tcps_mib.tcpInDataInorderBytes;
26685 	tcpkp->inDataUnorderSegs.value.ui32 =
26686 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26687 	tcpkp->inDataUnorderBytes.value.ui32 =
26688 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26689 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26690 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26691 	tcpkp->inDataPartDupSegs.value.ui32 =
26692 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26693 	tcpkp->inDataPartDupBytes.value.ui32 =
26694 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26695 	tcpkp->inDataPastWinSegs.value.ui32 =
26696 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26697 	tcpkp->inDataPastWinBytes.value.ui32 =
26698 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26699 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26700 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26701 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26702 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26703 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26704 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26705 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26706 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26707 	tcpkp->timKeepaliveProbe.value.ui32 =
26708 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26709 	tcpkp->timKeepaliveDrop.value.ui32 =
26710 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26711 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26712 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26713 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26714 	tcpkp->outSackRetransSegs.value.ui32 =
26715 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26716 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26717 
26718 	netstack_rele(ns);
26719 	return (0);
26720 }
26721 
26722 void
26723 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26724 {
26725 	uint16_t	hdr_len;
26726 	ipha_t		*ipha;
26727 	uint8_t		*nexthdrp;
26728 	tcph_t		*tcph;
26729 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26730 
26731 	/* Already has an eager */
26732 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26733 		TCP_STAT(tcps, tcp_reinput_syn);
26734 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26735 		    connp, SQTAG_TCP_REINPUT_EAGER);
26736 		return;
26737 	}
26738 
26739 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26740 	case IPV4_VERSION:
26741 		ipha = (ipha_t *)mp->b_rptr;
26742 		hdr_len = IPH_HDR_LENGTH(ipha);
26743 		break;
26744 	case IPV6_VERSION:
26745 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26746 		    &hdr_len, &nexthdrp)) {
26747 			CONN_DEC_REF(connp);
26748 			freemsg(mp);
26749 			return;
26750 		}
26751 		break;
26752 	}
26753 
26754 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26755 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26756 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26757 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26758 	}
26759 
26760 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26761 	    SQTAG_TCP_REINPUT);
26762 }
26763 
26764 static squeue_func_t
26765 tcp_squeue_switch(int val)
26766 {
26767 	squeue_func_t rval = squeue_fill;
26768 
26769 	switch (val) {
26770 	case 1:
26771 		rval = squeue_enter_nodrain;
26772 		break;
26773 	case 2:
26774 		rval = squeue_enter;
26775 		break;
26776 	default:
26777 		break;
26778 	}
26779 	return (rval);
26780 }
26781 
26782 /*
26783  * This is called once for each squeue - globally for all stack
26784  * instances.
26785  */
26786 static void
26787 tcp_squeue_add(squeue_t *sqp)
26788 {
26789 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26790 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
26791 
26792 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26793 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
26794 	    sqp, TCP_TIME_WAIT_DELAY);
26795 	if (tcp_free_list_max_cnt == 0) {
26796 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26797 			max_ncpus : boot_max_ncpus);
26798 
26799 		/*
26800 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26801 		 */
26802 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26803 			(tcp_ncpus * sizeof (tcp_t) * 100);
26804 	}
26805 	tcp_time_wait->tcp_free_list_cnt = 0;
26806 }
26807