xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision da6c28aaf62fa55f0fdb8004aa40f88f23bf53f0)
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 /*
238  * Values for squeue switch:
239  * 1: squeue_enter_nodrain
240  * 2: squeue_enter
241  * 3: squeue_fill
242  */
243 int tcp_squeue_close = 2;	/* Setable in /etc/system */
244 int tcp_squeue_wput = 2;
245 
246 squeue_func_t tcp_squeue_close_proc;
247 squeue_func_t tcp_squeue_wput_proc;
248 
249 /*
250  * This controls how tiny a write must be before we try to copy it
251  * into the the mblk on the tail of the transmit queue.  Not much
252  * speedup is observed for values larger than sixteen.  Zero will
253  * disable the optimisation.
254  */
255 int tcp_tx_pull_len = 16;
256 
257 /*
258  * TCP Statistics.
259  *
260  * How TCP statistics work.
261  *
262  * There are two types of statistics invoked by two macros.
263  *
264  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
265  * supposed to be used in non MT-hot paths of the code.
266  *
267  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
268  * supposed to be used for DEBUG purposes and may be used on a hot path.
269  *
270  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
271  * (use "kstat tcp" to get them).
272  *
273  * There is also additional debugging facility that marks tcp_clean_death()
274  * instances and saves them in tcp_t structure. It is triggered by
275  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
276  * tcp_clean_death() calls that counts the number of times each tag was hit. It
277  * is triggered by TCP_CLD_COUNTERS define.
278  *
279  * How to add new counters.
280  *
281  * 1) Add a field in the tcp_stat structure describing your counter.
282  * 2) Add a line in the template in tcp_kstat2_init() with the name
283  *    of the counter.
284  *
285  *    IMPORTANT!! - make sure that both are in sync !!
286  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
287  *
288  * Please avoid using private counters which are not kstat-exported.
289  *
290  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
291  * in tcp_t structure.
292  *
293  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
294  */
295 
296 #ifndef TCP_DEBUG_COUNTER
297 #ifdef DEBUG
298 #define	TCP_DEBUG_COUNTER 1
299 #else
300 #define	TCP_DEBUG_COUNTER 0
301 #endif
302 #endif
303 
304 #define	TCP_CLD_COUNTERS 0
305 
306 #define	TCP_TAG_CLEAN_DEATH 1
307 #define	TCP_MAX_CLEAN_DEATH_TAG 32
308 
309 #ifdef lint
310 static int _lint_dummy_;
311 #endif
312 
313 #if TCP_CLD_COUNTERS
314 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
315 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
316 #elif defined(lint)
317 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
318 #else
319 #define	TCP_CLD_STAT(x)
320 #endif
321 
322 #if TCP_DEBUG_COUNTER
323 #define	TCP_DBGSTAT(tcps, x)	\
324 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
325 #define	TCP_G_DBGSTAT(x)	\
326 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
327 #elif defined(lint)
328 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
329 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
330 #else
331 #define	TCP_DBGSTAT(tcps, x)
332 #define	TCP_G_DBGSTAT(x)
333 #endif
334 
335 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
336 
337 tcp_g_stat_t	tcp_g_statistics;
338 kstat_t		*tcp_g_kstat;
339 
340 /*
341  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
342  * tcp write side.
343  */
344 #define	CALL_IP_WPUT(connp, q, mp) {					\
345 	tcp_stack_t	*tcps;						\
346 									\
347 	tcps = connp->conn_netstack->netstack_tcp;			\
348 	ASSERT(((q)->q_flag & QREADR) == 0);				\
349 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
350 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
351 }
352 
353 /* Macros for timestamp comparisons */
354 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
355 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
356 
357 /*
358  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
359  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
360  * by adding three components: a time component which grows by 1 every 4096
361  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
362  * a per-connection component which grows by 125000 for every new connection;
363  * and an "extra" component that grows by a random amount centered
364  * approximately on 64000.  This causes the the ISS generator to cycle every
365  * 4.89 hours if no TCP connections are made, and faster if connections are
366  * made.
367  *
368  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
369  * components: a time component which grows by 250000 every second; and
370  * a per-connection component which grows by 125000 for every new connections.
371  *
372  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
373  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
374  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
375  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
376  * password.
377  */
378 #define	ISS_INCR	250000
379 #define	ISS_NSEC_SHT	12
380 
381 static sin_t	sin_null;	/* Zero address for quick clears */
382 static sin6_t	sin6_null;	/* Zero address for quick clears */
383 
384 /*
385  * This implementation follows the 4.3BSD interpretation of the urgent
386  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
387  * incompatible changes in protocols like telnet and rlogin.
388  */
389 #define	TCP_OLD_URP_INTERPRETATION	1
390 
391 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
392 	(TCP_IS_DETACHED(tcp) && \
393 	    (!(tcp)->tcp_hard_binding))
394 
395 /*
396  * TCP reassembly macros.  We hide starting and ending sequence numbers in
397  * b_next and b_prev of messages on the reassembly queue.  The messages are
398  * chained using b_cont.  These macros are used in tcp_reass() so we don't
399  * have to see the ugly casts and assignments.
400  */
401 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
402 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
403 					(mblk_t *)(uintptr_t)(u))
404 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
405 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
406 					(mblk_t *)(uintptr_t)(u))
407 
408 /*
409  * Implementation of TCP Timers.
410  * =============================
411  *
412  * INTERFACE:
413  *
414  * There are two basic functions dealing with tcp timers:
415  *
416  *	timeout_id_t	tcp_timeout(connp, func, time)
417  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
418  *	TCP_TIMER_RESTART(tcp, intvl)
419  *
420  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
421  * after 'time' ticks passed. The function called by timeout() must adhere to
422  * the same restrictions as a driver soft interrupt handler - it must not sleep
423  * or call other functions that might sleep. The value returned is the opaque
424  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
425  * cancel the request. The call to tcp_timeout() may fail in which case it
426  * returns zero. This is different from the timeout(9F) function which never
427  * fails.
428  *
429  * The call-back function 'func' always receives 'connp' as its single
430  * argument. It is always executed in the squeue corresponding to the tcp
431  * structure. The tcp structure is guaranteed to be present at the time the
432  * call-back is called.
433  *
434  * NOTE: The call-back function 'func' is never called if tcp is in
435  * 	the TCPS_CLOSED state.
436  *
437  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
438  * request. locks acquired by the call-back routine should not be held across
439  * the call to tcp_timeout_cancel() or a deadlock may result.
440  *
441  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
442  * Otherwise, it returns an integer value greater than or equal to 0. In
443  * particular, if the call-back function is already placed on the squeue, it can
444  * not be canceled.
445  *
446  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
447  * 	within squeue context corresponding to the tcp instance. Since the
448  *	call-back is also called via the same squeue, there are no race
449  *	conditions described in untimeout(9F) manual page since all calls are
450  *	strictly serialized.
451  *
452  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
453  *	stored in tcp_timer_tid and starts a new one using
454  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
455  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
456  *	field.
457  *
458  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
459  *	call-back may still be called, so it is possible tcp_timer() will be
460  *	called several times. This should not be a problem since tcp_timer()
461  *	should always check the tcp instance state.
462  *
463  *
464  * IMPLEMENTATION:
465  *
466  * TCP timers are implemented using three-stage process. The call to
467  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
468  * when the timer expires. The tcp_timer_callback() arranges the call of the
469  * tcp_timer_handler() function via squeue corresponding to the tcp
470  * instance. The tcp_timer_handler() calls actual requested timeout call-back
471  * and passes tcp instance as an argument to it. Information is passed between
472  * stages using the tcp_timer_t structure which contains the connp pointer, the
473  * tcp call-back to call and the timeout id returned by the timeout(9F).
474  *
475  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
476  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
477  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
478  * returns the pointer to this mblk.
479  *
480  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
481  * looks like a normal mblk without actual dblk attached to it.
482  *
483  * To optimize performance each tcp instance holds a small cache of timer
484  * mblocks. In the current implementation it caches up to two timer mblocks per
485  * tcp instance. The cache is preserved over tcp frees and is only freed when
486  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
487  * timer processing happens on a corresponding squeue, the cache manipulation
488  * does not require any locks. Experiments show that majority of timer mblocks
489  * allocations are satisfied from the tcp cache and do not involve kmem calls.
490  *
491  * The tcp_timeout() places a refhold on the connp instance which guarantees
492  * that it will be present at the time the call-back function fires. The
493  * tcp_timer_handler() drops the reference after calling the call-back, so the
494  * call-back function does not need to manipulate the references explicitly.
495  */
496 
497 typedef struct tcp_timer_s {
498 	conn_t	*connp;
499 	void 	(*tcpt_proc)(void *);
500 	timeout_id_t   tcpt_tid;
501 } tcp_timer_t;
502 
503 static kmem_cache_t *tcp_timercache;
504 kmem_cache_t	*tcp_sack_info_cache;
505 kmem_cache_t	*tcp_iphc_cache;
506 
507 /*
508  * For scalability, we must not run a timer for every TCP connection
509  * in TIME_WAIT state.  To see why, consider (for time wait interval of
510  * 4 minutes):
511  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
512  *
513  * This list is ordered by time, so you need only delete from the head
514  * until you get to entries which aren't old enough to delete yet.
515  * The list consists of only the detached TIME_WAIT connections.
516  *
517  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
518  * becomes detached TIME_WAIT (either by changing the state and already
519  * being detached or the other way around). This means that the TIME_WAIT
520  * state can be extended (up to doubled) if the connection doesn't become
521  * detached for a long time.
522  *
523  * The list manipulations (including tcp_time_wait_next/prev)
524  * are protected by the tcp_time_wait_lock. The content of the
525  * detached TIME_WAIT connections is protected by the normal perimeters.
526  *
527  * This list is per squeue and squeues are shared across the tcp_stack_t's.
528  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
529  * and conn_netstack.
530  * The tcp_t's that are added to tcp_free_list are disassociated and
531  * have NULL tcp_tcps and conn_netstack pointers.
532  */
533 typedef struct tcp_squeue_priv_s {
534 	kmutex_t	tcp_time_wait_lock;
535 	timeout_id_t	tcp_time_wait_tid;
536 	tcp_t		*tcp_time_wait_head;
537 	tcp_t		*tcp_time_wait_tail;
538 	tcp_t		*tcp_free_list;
539 	uint_t		tcp_free_list_cnt;
540 } tcp_squeue_priv_t;
541 
542 /*
543  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
544  * Running it every 5 seconds seems to give the best results.
545  */
546 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
547 
548 /*
549  * To prevent memory hog, limit the number of entries in tcp_free_list
550  * to 1% of available memory / number of cpus
551  */
552 uint_t tcp_free_list_max_cnt = 0;
553 
554 #define	TCP_XMIT_LOWATER	4096
555 #define	TCP_XMIT_HIWATER	49152
556 #define	TCP_RECV_LOWATER	2048
557 #define	TCP_RECV_HIWATER	49152
558 
559 /*
560  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
561  */
562 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
563 
564 #define	TIDUSZ	4096	/* transport interface data unit size */
565 
566 /*
567  * Bind hash list size and has function.  It has to be a power of 2 for
568  * hashing.
569  */
570 #define	TCP_BIND_FANOUT_SIZE	512
571 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
572 /*
573  * Size of listen and acceptor hash list.  It has to be a power of 2 for
574  * hashing.
575  */
576 #define	TCP_FANOUT_SIZE		256
577 
578 #ifdef	_ILP32
579 #define	TCP_ACCEPTOR_HASH(accid)					\
580 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
581 #else
582 #define	TCP_ACCEPTOR_HASH(accid)					\
583 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
584 #endif	/* _ILP32 */
585 
586 #define	IP_ADDR_CACHE_SIZE	2048
587 #define	IP_ADDR_CACHE_HASH(faddr)					\
588 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
589 
590 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
591 #define	TCP_HSP_HASH_SIZE 256
592 
593 #define	TCP_HSP_HASH(addr)					\
594 	(((addr>>24) ^ (addr >>16) ^			\
595 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
596 
597 /*
598  * TCP options struct returned from tcp_parse_options.
599  */
600 typedef struct tcp_opt_s {
601 	uint32_t	tcp_opt_mss;
602 	uint32_t	tcp_opt_wscale;
603 	uint32_t	tcp_opt_ts_val;
604 	uint32_t	tcp_opt_ts_ecr;
605 	tcp_t		*tcp;
606 } tcp_opt_t;
607 
608 /*
609  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
610  */
611 
612 #ifdef _BIG_ENDIAN
613 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
614 	(TCPOPT_TSTAMP << 8) | 10)
615 #else
616 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
617 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
618 #endif
619 
620 /*
621  * Flags returned from tcp_parse_options.
622  */
623 #define	TCP_OPT_MSS_PRESENT	1
624 #define	TCP_OPT_WSCALE_PRESENT	2
625 #define	TCP_OPT_TSTAMP_PRESENT	4
626 #define	TCP_OPT_SACK_OK_PRESENT	8
627 #define	TCP_OPT_SACK_PRESENT	16
628 
629 /* TCP option length */
630 #define	TCPOPT_NOP_LEN		1
631 #define	TCPOPT_MAXSEG_LEN	4
632 #define	TCPOPT_WS_LEN		3
633 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
634 #define	TCPOPT_TSTAMP_LEN	10
635 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
636 #define	TCPOPT_SACK_OK_LEN	2
637 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
638 #define	TCPOPT_REAL_SACK_LEN	4
639 #define	TCPOPT_MAX_SACK_LEN	36
640 #define	TCPOPT_HEADER_LEN	2
641 
642 /* TCP cwnd burst factor. */
643 #define	TCP_CWND_INFINITE	65535
644 #define	TCP_CWND_SS		3
645 #define	TCP_CWND_NORMAL		5
646 
647 /* Maximum TCP initial cwin (start/restart). */
648 #define	TCP_MAX_INIT_CWND	8
649 
650 /*
651  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
652  * either tcp_slow_start_initial or tcp_slow_start_after idle
653  * depending on the caller.  If the upper layer has not used the
654  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
655  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
656  * If the upper layer has changed set the tcp_init_cwnd, just use
657  * it to calculate the tcp_cwnd.
658  */
659 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
660 {									\
661 	if ((tcp)->tcp_init_cwnd == 0) {				\
662 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
663 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
664 	} else {							\
665 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
666 	}								\
667 	tcp->tcp_cwnd_cnt = 0;						\
668 }
669 
670 /* TCP Timer control structure */
671 typedef struct tcpt_s {
672 	pfv_t	tcpt_pfv;	/* The routine we are to call */
673 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
674 } tcpt_t;
675 
676 /* Host Specific Parameter structure */
677 typedef struct tcp_hsp {
678 	struct tcp_hsp	*tcp_hsp_next;
679 	in6_addr_t	tcp_hsp_addr_v6;
680 	in6_addr_t	tcp_hsp_subnet_v6;
681 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
682 	int32_t		tcp_hsp_sendspace;
683 	int32_t		tcp_hsp_recvspace;
684 	int32_t		tcp_hsp_tstamp;
685 } tcp_hsp_t;
686 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
687 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
688 
689 /*
690  * Functions called directly via squeue having a prototype of edesc_t.
691  */
692 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
693 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
694 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
695 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
696 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
697 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
698 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
699 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
700 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
701 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
702 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
703 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
704 
705 
706 /* Prototype for TCP functions */
707 static void	tcp_random_init(void);
708 int		tcp_random(void);
709 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
710 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
711 		    tcp_t *eager);
712 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
713 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
714     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
715     boolean_t user_specified);
716 static void	tcp_closei_local(tcp_t *tcp);
717 static void	tcp_close_detached(tcp_t *tcp);
718 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
719 			mblk_t *idmp, mblk_t **defermp);
720 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
721 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
722 		    in_port_t dstport, uint_t srcid);
723 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
724 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
725 		    uint32_t scope_id);
726 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
727 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
728 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
729 static char	*tcp_display(tcp_t *tcp, char *, char);
730 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
731 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
732 static void	tcp_eager_unlink(tcp_t *tcp);
733 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
734 		    int unixerr);
735 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
736 		    int tlierr, int unixerr);
737 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
738 		    cred_t *cr);
739 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
740 		    char *value, caddr_t cp, cred_t *cr);
741 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
742 		    char *value, caddr_t cp, cred_t *cr);
743 static int	tcp_tpistate(tcp_t *tcp);
744 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
745     int caller_holds_lock);
746 static void	tcp_bind_hash_remove(tcp_t *tcp);
747 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
748 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
749 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
750 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
751 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
752 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
753 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
754 void		tcp_g_q_setup(tcp_stack_t *);
755 void		tcp_g_q_create(tcp_stack_t *);
756 void		tcp_g_q_destroy(tcp_stack_t *);
757 static int	tcp_header_init_ipv4(tcp_t *tcp);
758 static int	tcp_header_init_ipv6(tcp_t *tcp);
759 int		tcp_init(tcp_t *tcp, queue_t *q);
760 static int	tcp_init_values(tcp_t *tcp);
761 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
762 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
763 		    t_scalar_t addr_length);
764 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
765 static void	tcp_ip_notify(tcp_t *tcp);
766 static mblk_t	*tcp_ire_mp(mblk_t *mp);
767 static void	tcp_iss_init(tcp_t *tcp);
768 static void	tcp_keepalive_killer(void *arg);
769 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
770 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
771 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
772 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
773 static boolean_t tcp_allow_connopt_set(int level, int name);
774 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
775 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
776 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
777 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
778 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
779 		    mblk_t *mblk);
780 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
781 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
782 		    uchar_t *ptr, uint_t len);
783 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
784 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
785     tcp_stack_t *);
786 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
787 		    caddr_t cp, cred_t *cr);
788 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
789 		    caddr_t cp, cred_t *cr);
790 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
791 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
792 		    caddr_t cp, cred_t *cr);
793 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
794 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
795 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
796 static void	tcp_reinit(tcp_t *tcp);
797 static void	tcp_reinit_values(tcp_t *tcp);
798 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
799 		    tcp_t *thisstream, cred_t *cr);
800 
801 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
802 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
803 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
804 static void	tcp_ss_rexmit(tcp_t *tcp);
805 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
806 static void	tcp_process_options(tcp_t *, tcph_t *);
807 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
808 static void	tcp_rsrv(queue_t *q);
809 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
810 static int	tcp_snmp_state(tcp_t *tcp);
811 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
812 		    cred_t *cr);
813 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
814 		    cred_t *cr);
815 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
816 		    cred_t *cr);
817 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
818 		    cred_t *cr);
819 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
820 		    cred_t *cr);
821 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
822 		    caddr_t cp, cred_t *cr);
823 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
824 		    caddr_t cp, cred_t *cr);
825 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
826 		    cred_t *cr);
827 static void	tcp_timer(void *arg);
828 static void	tcp_timer_callback(void *);
829 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
830     boolean_t random);
831 static in_port_t tcp_get_next_priv_port(const tcp_t *);
832 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
833 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
834 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
835 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
836 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
837 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
838 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
839 		    const int num_sack_blk, int *usable, uint_t *snxt,
840 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
841 		    const int mdt_thres);
842 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
843 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
844 		    const int num_sack_blk, int *usable, uint_t *snxt,
845 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
846 		    const int mdt_thres);
847 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
848 		    int num_sack_blk);
849 static void	tcp_wsrv(queue_t *q);
850 static int	tcp_xmit_end(tcp_t *tcp);
851 static void	tcp_ack_timer(void *arg);
852 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
853 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
854 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
855 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
856 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
857 		    uint32_t ack, int ctl);
858 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
859 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
860 static int	setmaxps(queue_t *q, int maxpsz);
861 static void	tcp_set_rto(tcp_t *, time_t);
862 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
863 		    boolean_t, boolean_t);
864 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
865 		    boolean_t ipsec_mctl);
866 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
867 		    char *opt, int optlen);
868 static int	tcp_build_hdrs(queue_t *, tcp_t *);
869 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
870 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
871 		    tcph_t *tcph);
872 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
873 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
874 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
875 boolean_t	tcp_reserved_port_check(in_port_t, tcp_stack_t *);
876 static tcp_t	*tcp_alloc_temp_tcp(in_port_t, tcp_stack_t *);
877 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
878 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
879 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
880 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
881 		    const boolean_t, const uint32_t, const uint32_t,
882 		    const uint32_t, const uint32_t, tcp_stack_t *);
883 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
884 		    const uint_t, const uint_t, boolean_t *);
885 static mblk_t	*tcp_lso_info_mp(mblk_t *);
886 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
887 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
888 extern mblk_t	*tcp_timermp_alloc(int);
889 extern void	tcp_timermp_free(tcp_t *);
890 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
891 static void	tcp_stop_lingering(tcp_t *tcp);
892 static void	tcp_close_linger_timeout(void *arg);
893 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
894 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
895 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
896 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
897 static void	tcp_g_kstat_fini(kstat_t *);
898 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
899 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
900 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
901 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
902 static int	tcp_kstat_update(kstat_t *kp, int rw);
903 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
904 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
905 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
906 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
907 			tcph_t *tcph, mblk_t *idmp);
908 static squeue_func_t tcp_squeue_switch(int);
909 
910 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
911 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
912 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
913 static int	tcp_close(queue_t *, int);
914 static int	tcpclose_accept(queue_t *);
915 
916 static void	tcp_squeue_add(squeue_t *);
917 static boolean_t tcp_zcopy_check(tcp_t *);
918 static void	tcp_zcopy_notify(tcp_t *);
919 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
920 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
921 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
922 
923 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
924 
925 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
926 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
927 
928 /*
929  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
930  *
931  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
932  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
933  * (defined in tcp.h) needs to be filled in and passed into the kernel
934  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
935  * structure contains the four-tuple of a TCP connection and a range of TCP
936  * states (specified by ac_start and ac_end). The use of wildcard addresses
937  * and ports is allowed. Connections with a matching four tuple and a state
938  * within the specified range will be aborted. The valid states for the
939  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
940  * inclusive.
941  *
942  * An application which has its connection aborted by this ioctl will receive
943  * an error that is dependent on the connection state at the time of the abort.
944  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
945  * though a RST packet has been received.  If the connection state is equal to
946  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
947  * and all resources associated with the connection will be freed.
948  */
949 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
950 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
951 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
952 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
953 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
954 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
955     boolean_t, tcp_stack_t *);
956 
957 static struct module_info tcp_rinfo =  {
958 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
959 };
960 
961 static struct module_info tcp_winfo =  {
962 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
963 };
964 
965 /*
966  * Entry points for TCP as a device. The normal case which supports
967  * the TCP functionality.
968  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
969  */
970 struct qinit tcp_rinitv4 = {
971 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, NULL, &tcp_rinfo
972 };
973 
974 struct qinit tcp_rinitv6 = {
975 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_close, NULL, &tcp_rinfo
976 };
977 
978 struct qinit tcp_winit = {
979 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
980 };
981 
982 /* Initial entry point for TCP in socket mode. */
983 struct qinit tcp_sock_winit = {
984 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
985 };
986 
987 /*
988  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
989  * an accept. Avoid allocating data structures since eager has already
990  * been created.
991  */
992 struct qinit tcp_acceptor_rinit = {
993 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
994 };
995 
996 struct qinit tcp_acceptor_winit = {
997 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
998 };
999 
1000 /*
1001  * Entry points for TCP loopback (read side only)
1002  * The open routine is only used for reopens, thus no need to
1003  * have a separate one for tcp_openv6.
1004  */
1005 struct qinit tcp_loopback_rinit = {
1006 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, (pfi_t)0,
1007 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1008 };
1009 
1010 /* For AF_INET aka /dev/tcp */
1011 struct streamtab tcpinfov4 = {
1012 	&tcp_rinitv4, &tcp_winit
1013 };
1014 
1015 /* For AF_INET6 aka /dev/tcp6 */
1016 struct streamtab tcpinfov6 = {
1017 	&tcp_rinitv6, &tcp_winit
1018 };
1019 
1020 /*
1021  * Have to ensure that tcp_g_q_close is not done by an
1022  * interrupt thread.
1023  */
1024 static taskq_t *tcp_taskq;
1025 
1026 /*
1027  * TCP has a private interface for other kernel modules to reserve a
1028  * port range for them to use.  Once reserved, TCP will not use any ports
1029  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1030  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1031  * has to be verified.
1032  *
1033  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1034  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1035  * range is [port a, port b] inclusive.  And each port range is between
1036  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1037  *
1038  * Note that the default anonymous port range starts from 32768.  There is
1039  * no port "collision" between that and the reserved port range.  If there
1040  * is port collision (because the default smallest anonymous port is lowered
1041  * or some apps specifically bind to ports in the reserved port range), the
1042  * system may not be able to reserve a port range even there are enough
1043  * unbound ports as a reserved port range contains consecutive ports .
1044  */
1045 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1046 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1047 #define	TCP_SMALLEST_RESERVED_PORT		10240
1048 #define	TCP_LARGEST_RESERVED_PORT		20480
1049 
1050 /* Structure to represent those reserved port ranges. */
1051 typedef struct tcp_rport_s {
1052 	in_port_t	lo_port;
1053 	in_port_t	hi_port;
1054 	tcp_t		**temp_tcp_array;
1055 } tcp_rport_t;
1056 
1057 /* Setable only in /etc/system. Move to ndd? */
1058 boolean_t tcp_icmp_source_quench = B_FALSE;
1059 
1060 /*
1061  * Following assumes TPI alignment requirements stay along 32 bit
1062  * boundaries
1063  */
1064 #define	ROUNDUP32(x) \
1065 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1066 
1067 /* Template for response to info request. */
1068 static struct T_info_ack tcp_g_t_info_ack = {
1069 	T_INFO_ACK,		/* PRIM_type */
1070 	0,			/* TSDU_size */
1071 	T_INFINITE,		/* ETSDU_size */
1072 	T_INVALID,		/* CDATA_size */
1073 	T_INVALID,		/* DDATA_size */
1074 	sizeof (sin_t),		/* ADDR_size */
1075 	0,			/* OPT_size - not initialized here */
1076 	TIDUSZ,			/* TIDU_size */
1077 	T_COTS_ORD,		/* SERV_type */
1078 	TCPS_IDLE,		/* CURRENT_state */
1079 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1080 };
1081 
1082 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1083 	T_INFO_ACK,		/* PRIM_type */
1084 	0,			/* TSDU_size */
1085 	T_INFINITE,		/* ETSDU_size */
1086 	T_INVALID,		/* CDATA_size */
1087 	T_INVALID,		/* DDATA_size */
1088 	sizeof (sin6_t),	/* ADDR_size */
1089 	0,			/* OPT_size - not initialized here */
1090 	TIDUSZ,		/* TIDU_size */
1091 	T_COTS_ORD,		/* SERV_type */
1092 	TCPS_IDLE,		/* CURRENT_state */
1093 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1094 };
1095 
1096 #define	MS	1L
1097 #define	SECONDS	(1000 * MS)
1098 #define	MINUTES	(60 * SECONDS)
1099 #define	HOURS	(60 * MINUTES)
1100 #define	DAYS	(24 * HOURS)
1101 
1102 #define	PARAM_MAX (~(uint32_t)0)
1103 
1104 /* Max size IP datagram is 64k - 1 */
1105 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1106 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1107 /* Max of the above */
1108 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1109 
1110 /* Largest TCP port number */
1111 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1112 
1113 /*
1114  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1115  * layer header.  It has to be a multiple of 4.
1116  */
1117 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1118 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1119 
1120 /*
1121  * All of these are alterable, within the min/max values given, at run time.
1122  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1123  * per the TCP spec.
1124  */
1125 /* BEGIN CSTYLED */
1126 static tcpparam_t	lcl_tcp_param_arr[] = {
1127  /*min		max		value		name */
1128  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1129  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1130  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1131  { 1,		1024,		1,		"tcp_conn_req_min" },
1132  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1133  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1134  { 0,		10,		0,		"tcp_debug" },
1135  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1136  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1137  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1138  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1139  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1140  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1141  { 1,		255,		64,		"tcp_ipv4_ttl"},
1142  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1143  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1144  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1145  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1146  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1147  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1148  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1149  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1150  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1151  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1152  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1153  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1154  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1155  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1156  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1157  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1158  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1159  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1160  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1161  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1162  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1163  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1164  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1165  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1166 /*
1167  * Question:  What default value should I set for tcp_strong_iss?
1168  */
1169  { 0,		2,		1,		"tcp_strong_iss"},
1170  { 0,		65536,		20,		"tcp_rtt_updates"},
1171  { 0,		1,		1,		"tcp_wscale_always"},
1172  { 0,		1,		0,		"tcp_tstamp_always"},
1173  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1174  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1175  { 0,		16,		2,		"tcp_deferred_acks_max"},
1176  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1177  { 1,		4,		4,		"tcp_slow_start_initial"},
1178  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1179  { 0,		2,		2,		"tcp_sack_permitted"},
1180  { 0,		1,		0,		"tcp_trace"},
1181  { 0,		1,		1,		"tcp_compression_enabled"},
1182  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1183  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1184  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1185  { 0,		1,		0,		"tcp_rev_src_routes"},
1186  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1187  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1188  { 0,		16,		8,		"tcp_local_dacks_max"},
1189  { 0,		2,		1,		"tcp_ecn_permitted"},
1190  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1191  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1192  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1193  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1194  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1195 };
1196 /* END CSTYLED */
1197 
1198 /*
1199  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1200  * each header fragment in the header buffer.  Each parameter value has
1201  * to be a multiple of 4 (32-bit aligned).
1202  */
1203 static tcpparam_t lcl_tcp_mdt_head_param =
1204 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1205 static tcpparam_t lcl_tcp_mdt_tail_param =
1206 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1207 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1208 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1209 
1210 /*
1211  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1212  * the maximum number of payload buffers associated per Multidata.
1213  */
1214 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1215 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1216 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1217 
1218 /* Round up the value to the nearest mss. */
1219 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1220 
1221 /*
1222  * Set ECN capable transport (ECT) code point in IP header.
1223  *
1224  * Note that there are 2 ECT code points '01' and '10', which are called
1225  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1226  * point ECT(0) for TCP as described in RFC 2481.
1227  */
1228 #define	SET_ECT(tcp, iph) \
1229 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1230 		/* We need to clear the code point first. */ \
1231 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1232 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1233 	} else { \
1234 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1235 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1236 	}
1237 
1238 /*
1239  * The format argument to pass to tcp_display().
1240  * DISP_PORT_ONLY means that the returned string has only port info.
1241  * DISP_ADDR_AND_PORT means that the returned string also contains the
1242  * remote and local IP address.
1243  */
1244 #define	DISP_PORT_ONLY		1
1245 #define	DISP_ADDR_AND_PORT	2
1246 
1247 #define	NDD_TOO_QUICK_MSG \
1248 	"ndd get info rate too high for non-privileged users, try again " \
1249 	"later.\n"
1250 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1251 
1252 #define	IS_VMLOANED_MBLK(mp) \
1253 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1254 
1255 
1256 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1257 boolean_t tcp_mdt_chain = B_TRUE;
1258 
1259 /*
1260  * MDT threshold in the form of effective send MSS multiplier; we take
1261  * the MDT path if the amount of unsent data exceeds the threshold value
1262  * (default threshold is 1*SMSS).
1263  */
1264 uint_t tcp_mdt_smss_threshold = 1;
1265 
1266 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1267 
1268 /*
1269  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1270  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1271  * determined dynamically during tcp_adapt_ire(), which is the default.
1272  */
1273 boolean_t tcp_static_maxpsz = B_FALSE;
1274 
1275 /* Setable in /etc/system */
1276 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1277 uint32_t tcp_random_anon_port = 1;
1278 
1279 /*
1280  * To reach to an eager in Q0 which can be dropped due to an incoming
1281  * new SYN request when Q0 is full, a new doubly linked list is
1282  * introduced. This list allows to select an eager from Q0 in O(1) time.
1283  * This is needed to avoid spending too much time walking through the
1284  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1285  * this new list has to be a member of Q0.
1286  * This list is headed by listener's tcp_t. When the list is empty,
1287  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1288  * of listener's tcp_t point to listener's tcp_t itself.
1289  *
1290  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1291  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1292  * These macros do not affect the eager's membership to Q0.
1293  */
1294 
1295 
1296 #define	MAKE_DROPPABLE(listener, eager)					\
1297 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1298 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1299 		    = (eager);						\
1300 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1301 		(eager)->tcp_eager_next_drop_q0 =			\
1302 		    (listener)->tcp_eager_next_drop_q0;			\
1303 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1304 	}
1305 
1306 #define	MAKE_UNDROPPABLE(eager)						\
1307 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1308 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1309 		    = (eager)->tcp_eager_prev_drop_q0;			\
1310 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1311 		    = (eager)->tcp_eager_next_drop_q0;			\
1312 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1313 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1314 	}
1315 
1316 /*
1317  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1318  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1319  * data, TCP will not respond with an ACK.  RFC 793 requires that
1320  * TCP responds with an ACK for such a bogus ACK.  By not following
1321  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1322  * an attacker successfully spoofs an acceptable segment to our
1323  * peer; or when our peer is "confused."
1324  */
1325 uint32_t tcp_drop_ack_unsent_cnt = 10;
1326 
1327 /*
1328  * Hook functions to enable cluster networking
1329  * On non-clustered systems these vectors must always be NULL.
1330  */
1331 
1332 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1333 			    uint8_t *laddrp, in_port_t lport) = NULL;
1334 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1335 			    uint8_t *laddrp, in_port_t lport) = NULL;
1336 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1337 			    uint8_t *laddrp, in_port_t lport,
1338 			    uint8_t *faddrp, in_port_t fport) = NULL;
1339 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1340 			    uint8_t *laddrp, in_port_t lport,
1341 			    uint8_t *faddrp, in_port_t fport) = NULL;
1342 
1343 /*
1344  * The following are defined in ip.c
1345  */
1346 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1347 				uint8_t *laddrp);
1348 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1349 				uint8_t *laddrp, uint8_t *faddrp);
1350 
1351 #define	CL_INET_CONNECT(tcp)		{			\
1352 	if (cl_inet_connect != NULL) {				\
1353 		/*						\
1354 		 * Running in cluster mode - register active connection	\
1355 		 * information						\
1356 		 */							\
1357 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1358 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1359 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1360 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1361 				    (in_port_t)(tcp)->tcp_lport,	\
1362 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1363 				    (in_port_t)(tcp)->tcp_fport);	\
1364 			}						\
1365 		} else {						\
1366 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1367 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1368 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1369 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1370 				    (in_port_t)(tcp)->tcp_lport,	\
1371 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1372 				    (in_port_t)(tcp)->tcp_fport);	\
1373 			}						\
1374 		}							\
1375 	}								\
1376 }
1377 
1378 #define	CL_INET_DISCONNECT(tcp)	{				\
1379 	if (cl_inet_disconnect != NULL) {				\
1380 		/*							\
1381 		 * Running in cluster mode - deregister active		\
1382 		 * connection information				\
1383 		 */							\
1384 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1385 			if ((tcp)->tcp_ip_src != 0) {			\
1386 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1387 				    AF_INET,				\
1388 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1389 				    (in_port_t)(tcp)->tcp_lport,	\
1390 				    (uint8_t *)				\
1391 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1392 				    (in_port_t)(tcp)->tcp_fport);	\
1393 			}						\
1394 		} else {						\
1395 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1396 			    &(tcp)->tcp_ip_src_v6)) {			\
1397 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1398 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1399 				    (in_port_t)(tcp)->tcp_lport,	\
1400 				    (uint8_t *)				\
1401 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1402 				    (in_port_t)(tcp)->tcp_fport);	\
1403 			}						\
1404 		}							\
1405 	}								\
1406 }
1407 
1408 /*
1409  * Cluster networking hook for traversing current connection list.
1410  * This routine is used to extract the current list of live connections
1411  * which must continue to to be dispatched to this node.
1412  */
1413 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1414 
1415 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1416     void *arg, tcp_stack_t *tcps);
1417 
1418 /*
1419  * Figure out the value of window scale opton.  Note that the rwnd is
1420  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1421  * We cannot find the scale value and then do a round up of tcp_rwnd
1422  * because the scale value may not be correct after that.
1423  *
1424  * Set the compiler flag to make this function inline.
1425  */
1426 static void
1427 tcp_set_ws_value(tcp_t *tcp)
1428 {
1429 	int i;
1430 	uint32_t rwnd = tcp->tcp_rwnd;
1431 
1432 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1433 	    i++, rwnd >>= 1)
1434 		;
1435 	tcp->tcp_rcv_ws = i;
1436 }
1437 
1438 /*
1439  * Remove a connection from the list of detached TIME_WAIT connections.
1440  * It returns B_FALSE if it can't remove the connection from the list
1441  * as the connection has already been removed from the list due to an
1442  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1443  */
1444 static boolean_t
1445 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1446 {
1447 	boolean_t	locked = B_FALSE;
1448 
1449 	if (tcp_time_wait == NULL) {
1450 		tcp_time_wait = *((tcp_squeue_priv_t **)
1451 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1452 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1453 		locked = B_TRUE;
1454 	} else {
1455 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1456 	}
1457 
1458 	if (tcp->tcp_time_wait_expire == 0) {
1459 		ASSERT(tcp->tcp_time_wait_next == NULL);
1460 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1461 		if (locked)
1462 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1463 		return (B_FALSE);
1464 	}
1465 	ASSERT(TCP_IS_DETACHED(tcp));
1466 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1467 
1468 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1469 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1470 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1471 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1472 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1473 			    NULL;
1474 		} else {
1475 			tcp_time_wait->tcp_time_wait_tail = NULL;
1476 		}
1477 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1478 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1479 		ASSERT(tcp->tcp_time_wait_next == NULL);
1480 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1481 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1482 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1483 	} else {
1484 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1485 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1486 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1487 		    tcp->tcp_time_wait_next;
1488 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1489 		    tcp->tcp_time_wait_prev;
1490 	}
1491 	tcp->tcp_time_wait_next = NULL;
1492 	tcp->tcp_time_wait_prev = NULL;
1493 	tcp->tcp_time_wait_expire = 0;
1494 
1495 	if (locked)
1496 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1497 	return (B_TRUE);
1498 }
1499 
1500 /*
1501  * Add a connection to the list of detached TIME_WAIT connections
1502  * and set its time to expire.
1503  */
1504 static void
1505 tcp_time_wait_append(tcp_t *tcp)
1506 {
1507 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1508 	tcp_squeue_priv_t *tcp_time_wait =
1509 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1510 	    SQPRIVATE_TCP));
1511 
1512 	tcp_timers_stop(tcp);
1513 
1514 	/* Freed above */
1515 	ASSERT(tcp->tcp_timer_tid == 0);
1516 	ASSERT(tcp->tcp_ack_tid == 0);
1517 
1518 	/* must have happened at the time of detaching the tcp */
1519 	ASSERT(tcp->tcp_ptpahn == NULL);
1520 	ASSERT(tcp->tcp_flow_stopped == 0);
1521 	ASSERT(tcp->tcp_time_wait_next == NULL);
1522 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1523 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1524 	ASSERT(tcp->tcp_listener == NULL);
1525 
1526 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1527 	/*
1528 	 * The value computed below in tcp->tcp_time_wait_expire may
1529 	 * appear negative or wrap around. That is ok since our
1530 	 * interest is only in the difference between the current lbolt
1531 	 * value and tcp->tcp_time_wait_expire. But the value should not
1532 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1533 	 * The corresponding comparison in tcp_time_wait_collector() uses
1534 	 * modular arithmetic.
1535 	 */
1536 	tcp->tcp_time_wait_expire +=
1537 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1538 	if (tcp->tcp_time_wait_expire == 0)
1539 		tcp->tcp_time_wait_expire = 1;
1540 
1541 	ASSERT(TCP_IS_DETACHED(tcp));
1542 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1543 	ASSERT(tcp->tcp_time_wait_next == NULL);
1544 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1545 	TCP_DBGSTAT(tcps, tcp_time_wait);
1546 
1547 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1548 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1549 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1550 		tcp_time_wait->tcp_time_wait_head = tcp;
1551 	} else {
1552 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1553 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1554 		    TCPS_TIME_WAIT);
1555 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1556 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1557 	}
1558 	tcp_time_wait->tcp_time_wait_tail = tcp;
1559 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1560 }
1561 
1562 /* ARGSUSED */
1563 void
1564 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1565 {
1566 	conn_t	*connp = (conn_t *)arg;
1567 	tcp_t	*tcp = connp->conn_tcp;
1568 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1569 
1570 	ASSERT(tcp != NULL);
1571 	if (tcp->tcp_state == TCPS_CLOSED) {
1572 		return;
1573 	}
1574 
1575 	ASSERT((tcp->tcp_family == AF_INET &&
1576 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1577 	    (tcp->tcp_family == AF_INET6 &&
1578 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1579 	    tcp->tcp_ipversion == IPV6_VERSION)));
1580 	ASSERT(!tcp->tcp_listener);
1581 
1582 	TCP_STAT(tcps, tcp_time_wait_reap);
1583 	ASSERT(TCP_IS_DETACHED(tcp));
1584 
1585 	/*
1586 	 * Because they have no upstream client to rebind or tcp_close()
1587 	 * them later, we axe the connection here and now.
1588 	 */
1589 	tcp_close_detached(tcp);
1590 }
1591 
1592 /*
1593  * Remove cached/latched IPsec references.
1594  */
1595 void
1596 tcp_ipsec_cleanup(tcp_t *tcp)
1597 {
1598 	conn_t		*connp = tcp->tcp_connp;
1599 
1600 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1601 
1602 	if (connp->conn_latch != NULL) {
1603 		IPLATCH_REFRELE(connp->conn_latch,
1604 		    connp->conn_netstack);
1605 		connp->conn_latch = NULL;
1606 	}
1607 	if (connp->conn_policy != NULL) {
1608 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1609 		connp->conn_policy = NULL;
1610 	}
1611 }
1612 
1613 /*
1614  * Cleaup before placing on free list.
1615  * Disassociate from the netstack/tcp_stack_t since the freelist
1616  * is per squeue and not per netstack.
1617  */
1618 void
1619 tcp_cleanup(tcp_t *tcp)
1620 {
1621 	mblk_t		*mp;
1622 	char		*tcp_iphc;
1623 	int		tcp_iphc_len;
1624 	int		tcp_hdr_grown;
1625 	tcp_sack_info_t	*tcp_sack_info;
1626 	conn_t		*connp = tcp->tcp_connp;
1627 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1628 	netstack_t	*ns = tcps->tcps_netstack;
1629 
1630 	tcp_bind_hash_remove(tcp);
1631 
1632 	/* Cleanup that which needs the netstack first */
1633 	tcp_ipsec_cleanup(tcp);
1634 
1635 	tcp_free(tcp);
1636 
1637 	/* Release any SSL context */
1638 	if (tcp->tcp_kssl_ent != NULL) {
1639 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1640 		tcp->tcp_kssl_ent = NULL;
1641 	}
1642 
1643 	if (tcp->tcp_kssl_ctx != NULL) {
1644 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1645 		tcp->tcp_kssl_ctx = NULL;
1646 	}
1647 	tcp->tcp_kssl_pending = B_FALSE;
1648 
1649 	conn_delete_ire(connp, NULL);
1650 
1651 	/*
1652 	 * Since we will bzero the entire structure, we need to
1653 	 * remove it and reinsert it in global hash list. We
1654 	 * know the walkers can't get to this conn because we
1655 	 * had set CONDEMNED flag earlier and checked reference
1656 	 * under conn_lock so walker won't pick it and when we
1657 	 * go the ipcl_globalhash_remove() below, no walker
1658 	 * can get to it.
1659 	 */
1660 	ipcl_globalhash_remove(connp);
1661 
1662 	/*
1663 	 * Now it is safe to decrement the reference counts.
1664 	 * This might be the last reference on the netstack and TCPS
1665 	 * in which case it will cause the tcp_g_q_close and
1666 	 * the freeing of the IP Instance.
1667 	 */
1668 	connp->conn_netstack = NULL;
1669 	netstack_rele(ns);
1670 	ASSERT(tcps != NULL);
1671 	tcp->tcp_tcps = NULL;
1672 	TCPS_REFRELE(tcps);
1673 
1674 	/* Save some state */
1675 	mp = tcp->tcp_timercache;
1676 
1677 	tcp_sack_info = tcp->tcp_sack_info;
1678 	tcp_iphc = tcp->tcp_iphc;
1679 	tcp_iphc_len = tcp->tcp_iphc_len;
1680 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1681 
1682 	if (connp->conn_cred != NULL) {
1683 		crfree(connp->conn_cred);
1684 		connp->conn_cred = NULL;
1685 	}
1686 	if (connp->conn_peercred != NULL) {
1687 		crfree(connp->conn_peercred);
1688 		connp->conn_peercred = NULL;
1689 	}
1690 	ipcl_conn_cleanup(connp);
1691 	connp->conn_flags = IPCL_TCPCONN;
1692 	bzero(tcp, sizeof (tcp_t));
1693 
1694 	/* restore the state */
1695 	tcp->tcp_timercache = mp;
1696 
1697 	tcp->tcp_sack_info = tcp_sack_info;
1698 	tcp->tcp_iphc = tcp_iphc;
1699 	tcp->tcp_iphc_len = tcp_iphc_len;
1700 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1701 
1702 	tcp->tcp_connp = connp;
1703 
1704 	ASSERT(connp->conn_tcp == tcp);
1705 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1706 	connp->conn_state_flags = CONN_INCIPIENT;
1707 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1708 	ASSERT(connp->conn_ref == 1);
1709 }
1710 
1711 /*
1712  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1713  * is done forwards from the head.
1714  * This walks all stack instances since
1715  * tcp_time_wait remains global across all stacks.
1716  */
1717 /* ARGSUSED */
1718 void
1719 tcp_time_wait_collector(void *arg)
1720 {
1721 	tcp_t *tcp;
1722 	clock_t now;
1723 	mblk_t *mp;
1724 	conn_t *connp;
1725 	kmutex_t *lock;
1726 	boolean_t removed;
1727 
1728 	squeue_t *sqp = (squeue_t *)arg;
1729 	tcp_squeue_priv_t *tcp_time_wait =
1730 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1731 
1732 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1733 	tcp_time_wait->tcp_time_wait_tid = 0;
1734 
1735 	if (tcp_time_wait->tcp_free_list != NULL &&
1736 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1737 		TCP_G_STAT(tcp_freelist_cleanup);
1738 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1739 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1740 			tcp->tcp_time_wait_next = NULL;
1741 			tcp_time_wait->tcp_free_list_cnt--;
1742 			ASSERT(tcp->tcp_tcps == NULL);
1743 			CONN_DEC_REF(tcp->tcp_connp);
1744 		}
1745 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1746 	}
1747 
1748 	/*
1749 	 * In order to reap time waits reliably, we should use a
1750 	 * source of time that is not adjustable by the user -- hence
1751 	 * the call to ddi_get_lbolt().
1752 	 */
1753 	now = ddi_get_lbolt();
1754 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1755 		/*
1756 		 * Compare times using modular arithmetic, since
1757 		 * lbolt can wrapover.
1758 		 */
1759 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1760 			break;
1761 		}
1762 
1763 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1764 		ASSERT(removed);
1765 
1766 		connp = tcp->tcp_connp;
1767 		ASSERT(connp->conn_fanout != NULL);
1768 		lock = &connp->conn_fanout->connf_lock;
1769 		/*
1770 		 * This is essentially a TW reclaim fast path optimization for
1771 		 * performance where the timewait collector checks under the
1772 		 * fanout lock (so that no one else can get access to the
1773 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1774 		 * the classifier hash list. If ref count is indeed 2, we can
1775 		 * just remove the conn under the fanout lock and avoid
1776 		 * cleaning up the conn under the squeue, provided that
1777 		 * clustering callbacks are not enabled. If clustering is
1778 		 * enabled, we need to make the clustering callback before
1779 		 * setting the CONDEMNED flag and after dropping all locks and
1780 		 * so we forego this optimization and fall back to the slow
1781 		 * path. Also please see the comments in tcp_closei_local
1782 		 * regarding the refcnt logic.
1783 		 *
1784 		 * Since we are holding the tcp_time_wait_lock, its better
1785 		 * not to block on the fanout_lock because other connections
1786 		 * can't add themselves to time_wait list. So we do a
1787 		 * tryenter instead of mutex_enter.
1788 		 */
1789 		if (mutex_tryenter(lock)) {
1790 			mutex_enter(&connp->conn_lock);
1791 			if ((connp->conn_ref == 2) &&
1792 			    (cl_inet_disconnect == NULL)) {
1793 				ipcl_hash_remove_locked(connp,
1794 				    connp->conn_fanout);
1795 				/*
1796 				 * Set the CONDEMNED flag now itself so that
1797 				 * the refcnt cannot increase due to any
1798 				 * walker. But we have still not cleaned up
1799 				 * conn_ire_cache. This is still ok since
1800 				 * we are going to clean it up in tcp_cleanup
1801 				 * immediately and any interface unplumb
1802 				 * thread will wait till the ire is blown away
1803 				 */
1804 				connp->conn_state_flags |= CONN_CONDEMNED;
1805 				mutex_exit(lock);
1806 				mutex_exit(&connp->conn_lock);
1807 				if (tcp_time_wait->tcp_free_list_cnt <
1808 				    tcp_free_list_max_cnt) {
1809 					/* Add to head of tcp_free_list */
1810 					mutex_exit(
1811 					    &tcp_time_wait->tcp_time_wait_lock);
1812 					tcp_cleanup(tcp);
1813 					ASSERT(connp->conn_latch == NULL);
1814 					ASSERT(connp->conn_policy == NULL);
1815 					ASSERT(tcp->tcp_tcps == NULL);
1816 					ASSERT(connp->conn_netstack == NULL);
1817 
1818 					mutex_enter(
1819 					    &tcp_time_wait->tcp_time_wait_lock);
1820 					tcp->tcp_time_wait_next =
1821 					    tcp_time_wait->tcp_free_list;
1822 					tcp_time_wait->tcp_free_list = tcp;
1823 					tcp_time_wait->tcp_free_list_cnt++;
1824 					continue;
1825 				} else {
1826 					/* Do not add to tcp_free_list */
1827 					mutex_exit(
1828 					    &tcp_time_wait->tcp_time_wait_lock);
1829 					tcp_bind_hash_remove(tcp);
1830 					conn_delete_ire(tcp->tcp_connp, NULL);
1831 					tcp_ipsec_cleanup(tcp);
1832 					CONN_DEC_REF(tcp->tcp_connp);
1833 				}
1834 			} else {
1835 				CONN_INC_REF_LOCKED(connp);
1836 				mutex_exit(lock);
1837 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1838 				mutex_exit(&connp->conn_lock);
1839 				/*
1840 				 * We can reuse the closemp here since conn has
1841 				 * detached (otherwise we wouldn't even be in
1842 				 * time_wait list). tcp_closemp_used can safely
1843 				 * be changed without taking a lock as no other
1844 				 * thread can concurrently access it at this
1845 				 * point in the connection lifecycle.
1846 				 */
1847 
1848 				if (tcp->tcp_closemp.b_prev == NULL)
1849 					tcp->tcp_closemp_used = B_TRUE;
1850 				else
1851 					cmn_err(CE_PANIC,
1852 					    "tcp_timewait_collector: "
1853 					    "concurrent use of tcp_closemp: "
1854 					    "connp %p tcp %p\n", (void *)connp,
1855 					    (void *)tcp);
1856 
1857 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1858 				mp = &tcp->tcp_closemp;
1859 				squeue_fill(connp->conn_sqp, mp,
1860 				    tcp_timewait_output, connp,
1861 				    SQTAG_TCP_TIMEWAIT);
1862 			}
1863 		} else {
1864 			mutex_enter(&connp->conn_lock);
1865 			CONN_INC_REF_LOCKED(connp);
1866 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1867 			mutex_exit(&connp->conn_lock);
1868 			/*
1869 			 * We can reuse the closemp here since conn has
1870 			 * detached (otherwise we wouldn't even be in
1871 			 * time_wait list). tcp_closemp_used can safely
1872 			 * be changed without taking a lock as no other
1873 			 * thread can concurrently access it at this
1874 			 * point in the connection lifecycle.
1875 			 */
1876 
1877 			if (tcp->tcp_closemp.b_prev == NULL)
1878 				tcp->tcp_closemp_used = B_TRUE;
1879 			else
1880 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1881 				    "concurrent use of tcp_closemp: "
1882 				    "connp %p tcp %p\n", (void *)connp,
1883 				    (void *)tcp);
1884 
1885 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1886 			mp = &tcp->tcp_closemp;
1887 			squeue_fill(connp->conn_sqp, mp,
1888 			    tcp_timewait_output, connp, 0);
1889 		}
1890 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1891 	}
1892 
1893 	if (tcp_time_wait->tcp_free_list != NULL)
1894 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1895 
1896 	tcp_time_wait->tcp_time_wait_tid =
1897 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1898 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1899 }
1900 /*
1901  * Reply to a clients T_CONN_RES TPI message. This function
1902  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1903  * on the acceptor STREAM and processed in tcp_wput_accept().
1904  * Read the block comment on top of tcp_conn_request().
1905  */
1906 static void
1907 tcp_accept(tcp_t *listener, mblk_t *mp)
1908 {
1909 	tcp_t	*acceptor;
1910 	tcp_t	*eager;
1911 	tcp_t   *tcp;
1912 	struct T_conn_res	*tcr;
1913 	t_uscalar_t	acceptor_id;
1914 	t_scalar_t	seqnum;
1915 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1916 	mblk_t	*ok_mp;
1917 	mblk_t	*mp1;
1918 	tcp_stack_t	*tcps = listener->tcp_tcps;
1919 
1920 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1921 		tcp_err_ack(listener, mp, TPROTO, 0);
1922 		return;
1923 	}
1924 	tcr = (struct T_conn_res *)mp->b_rptr;
1925 
1926 	/*
1927 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1928 	 * read side queue of the streams device underneath us i.e. the
1929 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1930 	 * look it up in the queue_hash.  Under LP64 it sends down the
1931 	 * minor_t of the accepting endpoint.
1932 	 *
1933 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1934 	 * fanout hash lock is held.
1935 	 * This prevents any thread from entering the acceptor queue from
1936 	 * below (since it has not been hard bound yet i.e. any inbound
1937 	 * packets will arrive on the listener or default tcp queue and
1938 	 * go through tcp_lookup).
1939 	 * The CONN_INC_REF will prevent the acceptor from closing.
1940 	 *
1941 	 * XXX It is still possible for a tli application to send down data
1942 	 * on the accepting stream while another thread calls t_accept.
1943 	 * This should not be a problem for well-behaved applications since
1944 	 * the T_OK_ACK is sent after the queue swapping is completed.
1945 	 *
1946 	 * If the accepting fd is the same as the listening fd, avoid
1947 	 * queue hash lookup since that will return an eager listener in a
1948 	 * already established state.
1949 	 */
1950 	acceptor_id = tcr->ACCEPTOR_id;
1951 	mutex_enter(&listener->tcp_eager_lock);
1952 	if (listener->tcp_acceptor_id == acceptor_id) {
1953 		eager = listener->tcp_eager_next_q;
1954 		/* only count how many T_CONN_INDs so don't count q0 */
1955 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1956 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1957 			mutex_exit(&listener->tcp_eager_lock);
1958 			tcp_err_ack(listener, mp, TBADF, 0);
1959 			return;
1960 		}
1961 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1962 			/* Throw away all the eagers on q0. */
1963 			tcp_eager_cleanup(listener, 1);
1964 		}
1965 		if (listener->tcp_syn_defense) {
1966 			listener->tcp_syn_defense = B_FALSE;
1967 			if (listener->tcp_ip_addr_cache != NULL) {
1968 				kmem_free(listener->tcp_ip_addr_cache,
1969 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1970 				listener->tcp_ip_addr_cache = NULL;
1971 			}
1972 		}
1973 		/*
1974 		 * Transfer tcp_conn_req_max to the eager so that when
1975 		 * a disconnect occurs we can revert the endpoint to the
1976 		 * listen state.
1977 		 */
1978 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1979 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1980 		/*
1981 		 * Get a reference on the acceptor just like the
1982 		 * tcp_acceptor_hash_lookup below.
1983 		 */
1984 		acceptor = listener;
1985 		CONN_INC_REF(acceptor->tcp_connp);
1986 	} else {
1987 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1988 		if (acceptor == NULL) {
1989 			if (listener->tcp_debug) {
1990 				(void) strlog(TCP_MOD_ID, 0, 1,
1991 				    SL_ERROR|SL_TRACE,
1992 				    "tcp_accept: did not find acceptor 0x%x\n",
1993 				    acceptor_id);
1994 			}
1995 			mutex_exit(&listener->tcp_eager_lock);
1996 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1997 			return;
1998 		}
1999 		/*
2000 		 * Verify acceptor state. The acceptable states for an acceptor
2001 		 * include TCPS_IDLE and TCPS_BOUND.
2002 		 */
2003 		switch (acceptor->tcp_state) {
2004 		case TCPS_IDLE:
2005 			/* FALLTHRU */
2006 		case TCPS_BOUND:
2007 			break;
2008 		default:
2009 			CONN_DEC_REF(acceptor->tcp_connp);
2010 			mutex_exit(&listener->tcp_eager_lock);
2011 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2012 			return;
2013 		}
2014 	}
2015 
2016 	/* The listener must be in TCPS_LISTEN */
2017 	if (listener->tcp_state != TCPS_LISTEN) {
2018 		CONN_DEC_REF(acceptor->tcp_connp);
2019 		mutex_exit(&listener->tcp_eager_lock);
2020 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2021 		return;
2022 	}
2023 
2024 	/*
2025 	 * Rendezvous with an eager connection request packet hanging off
2026 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2027 	 * tcp structure when the connection packet arrived in
2028 	 * tcp_conn_request().
2029 	 */
2030 	seqnum = tcr->SEQ_number;
2031 	eager = listener;
2032 	do {
2033 		eager = eager->tcp_eager_next_q;
2034 		if (eager == NULL) {
2035 			CONN_DEC_REF(acceptor->tcp_connp);
2036 			mutex_exit(&listener->tcp_eager_lock);
2037 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2038 			return;
2039 		}
2040 	} while (eager->tcp_conn_req_seqnum != seqnum);
2041 	mutex_exit(&listener->tcp_eager_lock);
2042 
2043 	/*
2044 	 * At this point, both acceptor and listener have 2 ref
2045 	 * that they begin with. Acceptor has one additional ref
2046 	 * we placed in lookup while listener has 3 additional
2047 	 * ref for being behind the squeue (tcp_accept() is
2048 	 * done on listener's squeue); being in classifier hash;
2049 	 * and eager's ref on listener.
2050 	 */
2051 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2052 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2053 
2054 	/*
2055 	 * The eager at this point is set in its own squeue and
2056 	 * could easily have been killed (tcp_accept_finish will
2057 	 * deal with that) because of a TH_RST so we can only
2058 	 * ASSERT for a single ref.
2059 	 */
2060 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2061 
2062 	/* Pre allocate the stroptions mblk also */
2063 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2064 	if (opt_mp == NULL) {
2065 		CONN_DEC_REF(acceptor->tcp_connp);
2066 		CONN_DEC_REF(eager->tcp_connp);
2067 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2068 		return;
2069 	}
2070 	DB_TYPE(opt_mp) = M_SETOPTS;
2071 	opt_mp->b_wptr += sizeof (struct stroptions);
2072 
2073 	/*
2074 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2075 	 * from listener to acceptor. The message is chained on opt_mp
2076 	 * which will be sent onto eager's squeue.
2077 	 */
2078 	if (listener->tcp_bound_if != 0) {
2079 		/* allocate optmgmt req */
2080 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2081 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2082 		    sizeof (int));
2083 		if (mp1 != NULL)
2084 			linkb(opt_mp, mp1);
2085 	}
2086 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2087 		uint_t on = 1;
2088 
2089 		/* allocate optmgmt req */
2090 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2091 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2092 		if (mp1 != NULL)
2093 			linkb(opt_mp, mp1);
2094 	}
2095 
2096 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2097 	if ((mp1 = copymsg(mp)) == NULL) {
2098 		CONN_DEC_REF(acceptor->tcp_connp);
2099 		CONN_DEC_REF(eager->tcp_connp);
2100 		freemsg(opt_mp);
2101 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2102 		return;
2103 	}
2104 
2105 	tcr = (struct T_conn_res *)mp1->b_rptr;
2106 
2107 	/*
2108 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2109 	 * which allocates a larger mblk and appends the new
2110 	 * local address to the ok_ack.  The address is copied by
2111 	 * soaccept() for getsockname().
2112 	 */
2113 	{
2114 		int extra;
2115 
2116 		extra = (eager->tcp_family == AF_INET) ?
2117 		    sizeof (sin_t) : sizeof (sin6_t);
2118 
2119 		/*
2120 		 * Try to re-use mp, if possible.  Otherwise, allocate
2121 		 * an mblk and return it as ok_mp.  In any case, mp
2122 		 * is no longer usable upon return.
2123 		 */
2124 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2125 			CONN_DEC_REF(acceptor->tcp_connp);
2126 			CONN_DEC_REF(eager->tcp_connp);
2127 			freemsg(opt_mp);
2128 			/* Original mp has been freed by now, so use mp1 */
2129 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2130 			return;
2131 		}
2132 
2133 		mp = NULL;	/* We should never use mp after this point */
2134 
2135 		switch (extra) {
2136 		case sizeof (sin_t): {
2137 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2138 
2139 				ok_mp->b_wptr += extra;
2140 				sin->sin_family = AF_INET;
2141 				sin->sin_port = eager->tcp_lport;
2142 				sin->sin_addr.s_addr =
2143 				    eager->tcp_ipha->ipha_src;
2144 				break;
2145 			}
2146 		case sizeof (sin6_t): {
2147 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2148 
2149 				ok_mp->b_wptr += extra;
2150 				sin6->sin6_family = AF_INET6;
2151 				sin6->sin6_port = eager->tcp_lport;
2152 				if (eager->tcp_ipversion == IPV4_VERSION) {
2153 					sin6->sin6_flowinfo = 0;
2154 					IN6_IPADDR_TO_V4MAPPED(
2155 					    eager->tcp_ipha->ipha_src,
2156 					    &sin6->sin6_addr);
2157 				} else {
2158 					ASSERT(eager->tcp_ip6h != NULL);
2159 					sin6->sin6_flowinfo =
2160 					    eager->tcp_ip6h->ip6_vcf &
2161 					    ~IPV6_VERS_AND_FLOW_MASK;
2162 					sin6->sin6_addr =
2163 					    eager->tcp_ip6h->ip6_src;
2164 				}
2165 				sin6->sin6_scope_id = 0;
2166 				sin6->__sin6_src_id = 0;
2167 				break;
2168 			}
2169 		default:
2170 			break;
2171 		}
2172 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2173 	}
2174 
2175 	/*
2176 	 * If there are no options we know that the T_CONN_RES will
2177 	 * succeed. However, we can't send the T_OK_ACK upstream until
2178 	 * the tcp_accept_swap is done since it would be dangerous to
2179 	 * let the application start using the new fd prior to the swap.
2180 	 */
2181 	tcp_accept_swap(listener, acceptor, eager);
2182 
2183 	/*
2184 	 * tcp_accept_swap unlinks eager from listener but does not drop
2185 	 * the eager's reference on the listener.
2186 	 */
2187 	ASSERT(eager->tcp_listener == NULL);
2188 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2189 
2190 	/*
2191 	 * The eager is now associated with its own queue. Insert in
2192 	 * the hash so that the connection can be reused for a future
2193 	 * T_CONN_RES.
2194 	 */
2195 	tcp_acceptor_hash_insert(acceptor_id, eager);
2196 
2197 	/*
2198 	 * We now do the processing of options with T_CONN_RES.
2199 	 * We delay till now since we wanted to have queue to pass to
2200 	 * option processing routines that points back to the right
2201 	 * instance structure which does not happen until after
2202 	 * tcp_accept_swap().
2203 	 *
2204 	 * Note:
2205 	 * The sanity of the logic here assumes that whatever options
2206 	 * are appropriate to inherit from listner=>eager are done
2207 	 * before this point, and whatever were to be overridden (or not)
2208 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2209 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2210 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2211 	 * This may not be true at this point in time but can be fixed
2212 	 * independently. This option processing code starts with
2213 	 * the instantiated acceptor instance and the final queue at
2214 	 * this point.
2215 	 */
2216 
2217 	if (tcr->OPT_length != 0) {
2218 		/* Options to process */
2219 		int t_error = 0;
2220 		int sys_error = 0;
2221 		int do_disconnect = 0;
2222 
2223 		if (tcp_conprim_opt_process(eager, mp1,
2224 		    &do_disconnect, &t_error, &sys_error) < 0) {
2225 			eager->tcp_accept_error = 1;
2226 			if (do_disconnect) {
2227 				/*
2228 				 * An option failed which does not allow
2229 				 * connection to be accepted.
2230 				 *
2231 				 * We allow T_CONN_RES to succeed and
2232 				 * put a T_DISCON_IND on the eager queue.
2233 				 */
2234 				ASSERT(t_error == 0 && sys_error == 0);
2235 				eager->tcp_send_discon_ind = 1;
2236 			} else {
2237 				ASSERT(t_error != 0);
2238 				freemsg(ok_mp);
2239 				/*
2240 				 * Original mp was either freed or set
2241 				 * to ok_mp above, so use mp1 instead.
2242 				 */
2243 				tcp_err_ack(listener, mp1, t_error, sys_error);
2244 				goto finish;
2245 			}
2246 		}
2247 		/*
2248 		 * Most likely success in setting options (except if
2249 		 * eager->tcp_send_discon_ind set).
2250 		 * mp1 option buffer represented by OPT_length/offset
2251 		 * potentially modified and contains results of setting
2252 		 * options at this point
2253 		 */
2254 	}
2255 
2256 	/* We no longer need mp1, since all options processing has passed */
2257 	freemsg(mp1);
2258 
2259 	putnext(listener->tcp_rq, ok_mp);
2260 
2261 	mutex_enter(&listener->tcp_eager_lock);
2262 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2263 		tcp_t	*tail;
2264 		mblk_t	*conn_ind;
2265 
2266 		/*
2267 		 * This path should not be executed if listener and
2268 		 * acceptor streams are the same.
2269 		 */
2270 		ASSERT(listener != acceptor);
2271 
2272 		tcp = listener->tcp_eager_prev_q0;
2273 		/*
2274 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2275 		 * deferred T_conn_ind queue. We need to get to the head of
2276 		 * the queue in order to send up T_conn_ind the same order as
2277 		 * how the 3WHS is completed.
2278 		 */
2279 		while (tcp != listener) {
2280 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2281 				break;
2282 			else
2283 				tcp = tcp->tcp_eager_prev_q0;
2284 		}
2285 		ASSERT(tcp != listener);
2286 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2287 		ASSERT(conn_ind != NULL);
2288 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2289 
2290 		/* Move from q0 to q */
2291 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2292 		listener->tcp_conn_req_cnt_q0--;
2293 		listener->tcp_conn_req_cnt_q++;
2294 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2295 		    tcp->tcp_eager_prev_q0;
2296 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2297 		    tcp->tcp_eager_next_q0;
2298 		tcp->tcp_eager_prev_q0 = NULL;
2299 		tcp->tcp_eager_next_q0 = NULL;
2300 		tcp->tcp_conn_def_q0 = B_FALSE;
2301 
2302 		/* Make sure the tcp isn't in the list of droppables */
2303 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2304 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2305 
2306 		/*
2307 		 * Insert at end of the queue because sockfs sends
2308 		 * down T_CONN_RES in chronological order. Leaving
2309 		 * the older conn indications at front of the queue
2310 		 * helps reducing search time.
2311 		 */
2312 		tail = listener->tcp_eager_last_q;
2313 		if (tail != NULL)
2314 			tail->tcp_eager_next_q = tcp;
2315 		else
2316 			listener->tcp_eager_next_q = tcp;
2317 		listener->tcp_eager_last_q = tcp;
2318 		tcp->tcp_eager_next_q = NULL;
2319 		mutex_exit(&listener->tcp_eager_lock);
2320 		putnext(tcp->tcp_rq, conn_ind);
2321 	} else {
2322 		mutex_exit(&listener->tcp_eager_lock);
2323 	}
2324 
2325 	/*
2326 	 * Done with the acceptor - free it
2327 	 *
2328 	 * Note: from this point on, no access to listener should be made
2329 	 * as listener can be equal to acceptor.
2330 	 */
2331 finish:
2332 	ASSERT(acceptor->tcp_detached);
2333 	ASSERT(tcps->tcps_g_q != NULL);
2334 	acceptor->tcp_rq = tcps->tcps_g_q;
2335 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2336 	(void) tcp_clean_death(acceptor, 0, 2);
2337 	CONN_DEC_REF(acceptor->tcp_connp);
2338 
2339 	/*
2340 	 * In case we already received a FIN we have to make tcp_rput send
2341 	 * the ordrel_ind. This will also send up a window update if the window
2342 	 * has opened up.
2343 	 *
2344 	 * In the normal case of a successful connection acceptance
2345 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2346 	 * indication that this was just accepted. This tells tcp_rput to
2347 	 * pass up any data queued in tcp_rcv_list.
2348 	 *
2349 	 * In the fringe case where options sent with T_CONN_RES failed and
2350 	 * we required, we would be indicating a T_DISCON_IND to blow
2351 	 * away this connection.
2352 	 */
2353 
2354 	/*
2355 	 * XXX: we currently have a problem if XTI application closes the
2356 	 * acceptor stream in between. This problem exists in on10-gate also
2357 	 * and is well know but nothing can be done short of major rewrite
2358 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2359 	 * eager same squeue as listener (we can distinguish non socket
2360 	 * listeners at the time of handling a SYN in tcp_conn_request)
2361 	 * and do most of the work that tcp_accept_finish does here itself
2362 	 * and then get behind the acceptor squeue to access the acceptor
2363 	 * queue.
2364 	 */
2365 	/*
2366 	 * We already have a ref on tcp so no need to do one before squeue_fill
2367 	 */
2368 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2369 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2370 }
2371 
2372 /*
2373  * Swap information between the eager and acceptor for a TLI/XTI client.
2374  * The sockfs accept is done on the acceptor stream and control goes
2375  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2376  * called. In either case, both the eager and listener are in their own
2377  * perimeter (squeue) and the code has to deal with potential race.
2378  *
2379  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2380  */
2381 static void
2382 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2383 {
2384 	conn_t	*econnp, *aconnp;
2385 
2386 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2387 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2388 	ASSERT(!eager->tcp_hard_bound);
2389 	ASSERT(!TCP_IS_SOCKET(acceptor));
2390 	ASSERT(!TCP_IS_SOCKET(eager));
2391 	ASSERT(!TCP_IS_SOCKET(listener));
2392 
2393 	acceptor->tcp_detached = B_TRUE;
2394 	/*
2395 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2396 	 * the acceptor id.
2397 	 */
2398 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2399 
2400 	/* remove eager from listen list... */
2401 	mutex_enter(&listener->tcp_eager_lock);
2402 	tcp_eager_unlink(eager);
2403 	ASSERT(eager->tcp_eager_next_q == NULL &&
2404 	    eager->tcp_eager_last_q == NULL);
2405 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2406 	    eager->tcp_eager_prev_q0 == NULL);
2407 	mutex_exit(&listener->tcp_eager_lock);
2408 	eager->tcp_rq = acceptor->tcp_rq;
2409 	eager->tcp_wq = acceptor->tcp_wq;
2410 
2411 	econnp = eager->tcp_connp;
2412 	aconnp = acceptor->tcp_connp;
2413 
2414 	eager->tcp_rq->q_ptr = econnp;
2415 	eager->tcp_wq->q_ptr = econnp;
2416 
2417 	/*
2418 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2419 	 * which might be a different squeue from our peer TCP instance.
2420 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2421 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2422 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2423 	 * above reach global visibility prior to the clearing of tcp_detached.
2424 	 */
2425 	membar_producer();
2426 	eager->tcp_detached = B_FALSE;
2427 
2428 	ASSERT(eager->tcp_ack_tid == 0);
2429 
2430 	econnp->conn_dev = aconnp->conn_dev;
2431 	if (eager->tcp_cred != NULL)
2432 		crfree(eager->tcp_cred);
2433 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2434 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2435 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2436 
2437 	aconnp->conn_cred = NULL;
2438 
2439 	econnp->conn_zoneid = aconnp->conn_zoneid;
2440 	econnp->conn_allzones = aconnp->conn_allzones;
2441 
2442 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2443 	aconnp->conn_mac_exempt = B_FALSE;
2444 
2445 	ASSERT(aconnp->conn_peercred == NULL);
2446 
2447 	/* Do the IPC initialization */
2448 	CONN_INC_REF(econnp);
2449 
2450 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2451 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2452 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2453 
2454 	/* Done with old IPC. Drop its ref on its connp */
2455 	CONN_DEC_REF(aconnp);
2456 }
2457 
2458 
2459 /*
2460  * Adapt to the information, such as rtt and rtt_sd, provided from the
2461  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2462  *
2463  * Checks for multicast and broadcast destination address.
2464  * Returns zero on failure; non-zero if ok.
2465  *
2466  * Note that the MSS calculation here is based on the info given in
2467  * the IRE.  We do not do any calculation based on TCP options.  They
2468  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2469  * knows which options to use.
2470  *
2471  * Note on how TCP gets its parameters for a connection.
2472  *
2473  * When a tcp_t structure is allocated, it gets all the default parameters.
2474  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2475  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2476  * default.  But if there is an associated tcp_host_param, it will override
2477  * the metrics.
2478  *
2479  * An incoming SYN with a multicast or broadcast destination address, is dropped
2480  * in 1 of 2 places.
2481  *
2482  * 1. If the packet was received over the wire it is dropped in
2483  * ip_rput_process_broadcast()
2484  *
2485  * 2. If the packet was received through internal IP loopback, i.e. the packet
2486  * was generated and received on the same machine, it is dropped in
2487  * ip_wput_local()
2488  *
2489  * An incoming SYN with a multicast or broadcast source address is always
2490  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2491  * reject an attempt to connect to a broadcast or multicast (destination)
2492  * address.
2493  */
2494 static int
2495 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2496 {
2497 	tcp_hsp_t	*hsp;
2498 	ire_t		*ire;
2499 	ire_t		*sire = NULL;
2500 	iulp_t		*ire_uinfo = NULL;
2501 	uint32_t	mss_max;
2502 	uint32_t	mss;
2503 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2504 	conn_t		*connp = tcp->tcp_connp;
2505 	boolean_t	ire_cacheable = B_FALSE;
2506 	zoneid_t	zoneid = connp->conn_zoneid;
2507 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2508 	    MATCH_IRE_SECATTR;
2509 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2510 	ill_t		*ill = NULL;
2511 	boolean_t	incoming = (ire_mp == NULL);
2512 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2513 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2514 
2515 	ASSERT(connp->conn_ire_cache == NULL);
2516 
2517 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2518 
2519 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2520 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2521 			return (0);
2522 		}
2523 		/*
2524 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2525 		 * for the destination with the nexthop as gateway.
2526 		 * ire_ctable_lookup() is used because this particular
2527 		 * ire, if it exists, will be marked private.
2528 		 * If that is not available, use the interface ire
2529 		 * for the nexthop.
2530 		 *
2531 		 * TSol: tcp_update_label will detect label mismatches based
2532 		 * only on the destination's label, but that would not
2533 		 * detect label mismatches based on the security attributes
2534 		 * of routes or next hop gateway. Hence we need to pass the
2535 		 * label to ire_ftable_lookup below in order to locate the
2536 		 * right prefix (and/or) ire cache. Similarly we also need
2537 		 * pass the label to the ire_cache_lookup below to locate
2538 		 * the right ire that also matches on the label.
2539 		 */
2540 		if (tcp->tcp_connp->conn_nexthop_set) {
2541 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2542 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2543 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2544 			    ipst);
2545 			if (ire == NULL) {
2546 				ire = ire_ftable_lookup(
2547 				    tcp->tcp_connp->conn_nexthop_v4,
2548 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2549 				    tsl, match_flags, ipst);
2550 				if (ire == NULL)
2551 					return (0);
2552 			} else {
2553 				ire_uinfo = &ire->ire_uinfo;
2554 			}
2555 		} else {
2556 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2557 			    zoneid, tsl, ipst);
2558 			if (ire != NULL) {
2559 				ire_cacheable = B_TRUE;
2560 				ire_uinfo = (ire_mp != NULL) ?
2561 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2562 				    &ire->ire_uinfo;
2563 
2564 			} else {
2565 				if (ire_mp == NULL) {
2566 					ire = ire_ftable_lookup(
2567 					    tcp->tcp_connp->conn_rem,
2568 					    0, 0, 0, NULL, &sire, zoneid, 0,
2569 					    tsl, (MATCH_IRE_RECURSIVE |
2570 					    MATCH_IRE_DEFAULT), ipst);
2571 					if (ire == NULL)
2572 						return (0);
2573 					ire_uinfo = (sire != NULL) ?
2574 					    &sire->ire_uinfo :
2575 					    &ire->ire_uinfo;
2576 				} else {
2577 					ire = (ire_t *)ire_mp->b_rptr;
2578 					ire_uinfo =
2579 					    &((ire_t *)
2580 					    ire_mp->b_rptr)->ire_uinfo;
2581 				}
2582 			}
2583 		}
2584 		ASSERT(ire != NULL);
2585 
2586 		if ((ire->ire_src_addr == INADDR_ANY) ||
2587 		    (ire->ire_type & IRE_BROADCAST)) {
2588 			/*
2589 			 * ire->ire_mp is non null when ire_mp passed in is used
2590 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2591 			 */
2592 			if (ire->ire_mp == NULL)
2593 				ire_refrele(ire);
2594 			if (sire != NULL)
2595 				ire_refrele(sire);
2596 			return (0);
2597 		}
2598 
2599 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2600 			ipaddr_t src_addr;
2601 
2602 			/*
2603 			 * ip_bind_connected() has stored the correct source
2604 			 * address in conn_src.
2605 			 */
2606 			src_addr = tcp->tcp_connp->conn_src;
2607 			tcp->tcp_ipha->ipha_src = src_addr;
2608 			/*
2609 			 * Copy of the src addr. in tcp_t is needed
2610 			 * for the lookup funcs.
2611 			 */
2612 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2613 		}
2614 		/*
2615 		 * Set the fragment bit so that IP will tell us if the MTU
2616 		 * should change. IP tells us the latest setting of
2617 		 * ip_path_mtu_discovery through ire_frag_flag.
2618 		 */
2619 		if (ipst->ips_ip_path_mtu_discovery) {
2620 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2621 			    htons(IPH_DF);
2622 		}
2623 		/*
2624 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2625 		 * for IP_NEXTHOP. No cache ire has been found for the
2626 		 * destination and we are working with the nexthop's
2627 		 * interface ire. Since we need to forward all packets
2628 		 * to the nexthop first, we "blindly" set tcp_localnet
2629 		 * to false, eventhough the destination may also be
2630 		 * onlink.
2631 		 */
2632 		if (ire_uinfo == NULL)
2633 			tcp->tcp_localnet = 0;
2634 		else
2635 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2636 	} else {
2637 		/*
2638 		 * For incoming connection ire_mp = NULL
2639 		 * For outgoing connection ire_mp != NULL
2640 		 * Technically we should check conn_incoming_ill
2641 		 * when ire_mp is NULL and conn_outgoing_ill when
2642 		 * ire_mp is non-NULL. But this is performance
2643 		 * critical path and for IPV*_BOUND_IF, outgoing
2644 		 * and incoming ill are always set to the same value.
2645 		 */
2646 		ill_t	*dst_ill = NULL;
2647 		ipif_t  *dst_ipif = NULL;
2648 
2649 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2650 
2651 		if (connp->conn_outgoing_ill != NULL) {
2652 			/* Outgoing or incoming path */
2653 			int   err;
2654 
2655 			dst_ill = conn_get_held_ill(connp,
2656 			    &connp->conn_outgoing_ill, &err);
2657 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2658 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2659 				return (0);
2660 			}
2661 			match_flags |= MATCH_IRE_ILL;
2662 			dst_ipif = dst_ill->ill_ipif;
2663 		}
2664 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2665 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2666 
2667 		if (ire != NULL) {
2668 			ire_cacheable = B_TRUE;
2669 			ire_uinfo = (ire_mp != NULL) ?
2670 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2671 			    &ire->ire_uinfo;
2672 		} else {
2673 			if (ire_mp == NULL) {
2674 				ire = ire_ftable_lookup_v6(
2675 				    &tcp->tcp_connp->conn_remv6,
2676 				    0, 0, 0, dst_ipif, &sire, zoneid,
2677 				    0, tsl, match_flags, ipst);
2678 				if (ire == NULL) {
2679 					if (dst_ill != NULL)
2680 						ill_refrele(dst_ill);
2681 					return (0);
2682 				}
2683 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2684 				    &ire->ire_uinfo;
2685 			} else {
2686 				ire = (ire_t *)ire_mp->b_rptr;
2687 				ire_uinfo =
2688 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2689 			}
2690 		}
2691 		if (dst_ill != NULL)
2692 			ill_refrele(dst_ill);
2693 
2694 		ASSERT(ire != NULL);
2695 		ASSERT(ire_uinfo != NULL);
2696 
2697 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2698 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2699 			/*
2700 			 * ire->ire_mp is non null when ire_mp passed in is used
2701 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2702 			 */
2703 			if (ire->ire_mp == NULL)
2704 				ire_refrele(ire);
2705 			if (sire != NULL)
2706 				ire_refrele(sire);
2707 			return (0);
2708 		}
2709 
2710 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2711 			in6_addr_t	src_addr;
2712 
2713 			/*
2714 			 * ip_bind_connected_v6() has stored the correct source
2715 			 * address per IPv6 addr. selection policy in
2716 			 * conn_src_v6.
2717 			 */
2718 			src_addr = tcp->tcp_connp->conn_srcv6;
2719 
2720 			tcp->tcp_ip6h->ip6_src = src_addr;
2721 			/*
2722 			 * Copy of the src addr. in tcp_t is needed
2723 			 * for the lookup funcs.
2724 			 */
2725 			tcp->tcp_ip_src_v6 = src_addr;
2726 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2727 			    &connp->conn_srcv6));
2728 		}
2729 		tcp->tcp_localnet =
2730 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2731 	}
2732 
2733 	/*
2734 	 * This allows applications to fail quickly when connections are made
2735 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2736 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2737 	 */
2738 	if ((ire->ire_flags & RTF_REJECT) &&
2739 	    (ire->ire_flags & RTF_PRIVATE))
2740 		goto error;
2741 
2742 	/*
2743 	 * Make use of the cached rtt and rtt_sd values to calculate the
2744 	 * initial RTO.  Note that they are already initialized in
2745 	 * tcp_init_values().
2746 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2747 	 * IP_NEXTHOP, but instead are using the interface ire for the
2748 	 * nexthop, then we do not use the ire_uinfo from that ire to
2749 	 * do any initializations.
2750 	 */
2751 	if (ire_uinfo != NULL) {
2752 		if (ire_uinfo->iulp_rtt != 0) {
2753 			clock_t	rto;
2754 
2755 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2756 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2757 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2758 			    tcps->tcps_rexmit_interval_extra +
2759 			    (tcp->tcp_rtt_sa >> 5);
2760 
2761 			if (rto > tcps->tcps_rexmit_interval_max) {
2762 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2763 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2764 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2765 			} else {
2766 				tcp->tcp_rto = rto;
2767 			}
2768 		}
2769 		if (ire_uinfo->iulp_ssthresh != 0)
2770 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2771 		else
2772 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2773 		if (ire_uinfo->iulp_spipe > 0) {
2774 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2775 			    tcps->tcps_max_buf);
2776 			if (tcps->tcps_snd_lowat_fraction != 0)
2777 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2778 				    tcps->tcps_snd_lowat_fraction;
2779 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2780 		}
2781 		/*
2782 		 * Note that up till now, acceptor always inherits receive
2783 		 * window from the listener.  But if there is a metrics
2784 		 * associated with a host, we should use that instead of
2785 		 * inheriting it from listener. Thus we need to pass this
2786 		 * info back to the caller.
2787 		 */
2788 		if (ire_uinfo->iulp_rpipe > 0) {
2789 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2790 			    tcps->tcps_max_buf);
2791 		}
2792 
2793 		if (ire_uinfo->iulp_rtomax > 0) {
2794 			tcp->tcp_second_timer_threshold =
2795 			    ire_uinfo->iulp_rtomax;
2796 		}
2797 
2798 		/*
2799 		 * Use the metric option settings, iulp_tstamp_ok and
2800 		 * iulp_wscale_ok, only for active open. What this means
2801 		 * is that if the other side uses timestamp or window
2802 		 * scale option, TCP will also use those options. That
2803 		 * is for passive open.  If the application sets a
2804 		 * large window, window scale is enabled regardless of
2805 		 * the value in iulp_wscale_ok.  This is the behavior
2806 		 * since 2.6.  So we keep it.
2807 		 * The only case left in passive open processing is the
2808 		 * check for SACK.
2809 		 * For ECN, it should probably be like SACK.  But the
2810 		 * current value is binary, so we treat it like the other
2811 		 * cases.  The metric only controls active open.For passive
2812 		 * open, the ndd param, tcp_ecn_permitted, controls the
2813 		 * behavior.
2814 		 */
2815 		if (!tcp_detached) {
2816 			/*
2817 			 * The if check means that the following can only
2818 			 * be turned on by the metrics only IRE, but not off.
2819 			 */
2820 			if (ire_uinfo->iulp_tstamp_ok)
2821 				tcp->tcp_snd_ts_ok = B_TRUE;
2822 			if (ire_uinfo->iulp_wscale_ok)
2823 				tcp->tcp_snd_ws_ok = B_TRUE;
2824 			if (ire_uinfo->iulp_sack == 2)
2825 				tcp->tcp_snd_sack_ok = B_TRUE;
2826 			if (ire_uinfo->iulp_ecn_ok)
2827 				tcp->tcp_ecn_ok = B_TRUE;
2828 		} else {
2829 			/*
2830 			 * Passive open.
2831 			 *
2832 			 * As above, the if check means that SACK can only be
2833 			 * turned on by the metric only IRE.
2834 			 */
2835 			if (ire_uinfo->iulp_sack > 0) {
2836 				tcp->tcp_snd_sack_ok = B_TRUE;
2837 			}
2838 		}
2839 	}
2840 
2841 
2842 	/*
2843 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2844 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2845 	 * length of all those options exceeds 28 bytes.  But because
2846 	 * of the tcp_mss_min check below, we may not have a problem if
2847 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2848 	 * the negative problem still exists.  And the check defeats PMTUd.
2849 	 * In fact, if PMTUd finds that the MSS should be smaller than
2850 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2851 	 * value.
2852 	 *
2853 	 * We do not deal with that now.  All those problems related to
2854 	 * PMTUd will be fixed later.
2855 	 */
2856 	ASSERT(ire->ire_max_frag != 0);
2857 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2858 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2859 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2860 			mss = MIN(mss, IPV6_MIN_MTU);
2861 		}
2862 	}
2863 
2864 	/* Sanity check for MSS value. */
2865 	if (tcp->tcp_ipversion == IPV4_VERSION)
2866 		mss_max = tcps->tcps_mss_max_ipv4;
2867 	else
2868 		mss_max = tcps->tcps_mss_max_ipv6;
2869 
2870 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2871 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2872 		/*
2873 		 * After receiving an ICMPv6 "packet too big" message with a
2874 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2875 		 * will insert a 8-byte fragment header in every packet; we
2876 		 * reduce the MSS by that amount here.
2877 		 */
2878 		mss -= sizeof (ip6_frag_t);
2879 	}
2880 
2881 	if (tcp->tcp_ipsec_overhead == 0)
2882 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2883 
2884 	mss -= tcp->tcp_ipsec_overhead;
2885 
2886 	if (mss < tcps->tcps_mss_min)
2887 		mss = tcps->tcps_mss_min;
2888 	if (mss > mss_max)
2889 		mss = mss_max;
2890 
2891 	/* Note that this is the maximum MSS, excluding all options. */
2892 	tcp->tcp_mss = mss;
2893 
2894 	/*
2895 	 * Initialize the ISS here now that we have the full connection ID.
2896 	 * The RFC 1948 method of initial sequence number generation requires
2897 	 * knowledge of the full connection ID before setting the ISS.
2898 	 */
2899 
2900 	tcp_iss_init(tcp);
2901 
2902 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2903 		tcp->tcp_loopback = B_TRUE;
2904 
2905 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2906 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2907 	} else {
2908 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2909 	}
2910 
2911 	if (hsp != NULL) {
2912 		/* Only modify if we're going to make them bigger */
2913 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2914 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2915 			if (tcps->tcps_snd_lowat_fraction != 0)
2916 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2917 				    tcps->tcps_snd_lowat_fraction;
2918 		}
2919 
2920 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2921 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2922 		}
2923 
2924 		/* Copy timestamp flag only for active open */
2925 		if (!tcp_detached)
2926 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2927 	}
2928 
2929 	if (sire != NULL)
2930 		IRE_REFRELE(sire);
2931 
2932 	/*
2933 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2934 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2935 	 */
2936 	if (tcp->tcp_loopback ||
2937 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2938 		/*
2939 		 * For incoming, see if this tcp may be MDT-capable.  For
2940 		 * outgoing, this process has been taken care of through
2941 		 * tcp_rput_other.
2942 		 */
2943 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2944 		tcp->tcp_ire_ill_check_done = B_TRUE;
2945 	}
2946 
2947 	mutex_enter(&connp->conn_lock);
2948 	/*
2949 	 * Make sure that conn is not marked incipient
2950 	 * for incoming connections. A blind
2951 	 * removal of incipient flag is cheaper than
2952 	 * check and removal.
2953 	 */
2954 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2955 
2956 	/*
2957 	 * Must not cache forwarding table routes
2958 	 * or recache an IRE after the conn_t has
2959 	 * had conn_ire_cache cleared and is flagged
2960 	 * unusable, (see the CONN_CACHE_IRE() macro).
2961 	 */
2962 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2963 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2964 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2965 			connp->conn_ire_cache = ire;
2966 			IRE_UNTRACE_REF(ire);
2967 			rw_exit(&ire->ire_bucket->irb_lock);
2968 			mutex_exit(&connp->conn_lock);
2969 			return (1);
2970 		}
2971 		rw_exit(&ire->ire_bucket->irb_lock);
2972 	}
2973 	mutex_exit(&connp->conn_lock);
2974 
2975 	if (ire->ire_mp == NULL)
2976 		ire_refrele(ire);
2977 	return (1);
2978 
2979 error:
2980 	if (ire->ire_mp == NULL)
2981 		ire_refrele(ire);
2982 	if (sire != NULL)
2983 		ire_refrele(sire);
2984 	return (0);
2985 }
2986 
2987 /*
2988  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2989  * O_T_BIND_REQ/T_BIND_REQ message.
2990  */
2991 static void
2992 tcp_bind(tcp_t *tcp, mblk_t *mp)
2993 {
2994 	sin_t	*sin;
2995 	sin6_t	*sin6;
2996 	mblk_t	*mp1;
2997 	in_port_t requested_port;
2998 	in_port_t allocated_port;
2999 	struct T_bind_req *tbr;
3000 	boolean_t	bind_to_req_port_only;
3001 	boolean_t	backlog_update = B_FALSE;
3002 	boolean_t	user_specified;
3003 	in6_addr_t	v6addr;
3004 	ipaddr_t	v4addr;
3005 	uint_t	origipversion;
3006 	int	err;
3007 	queue_t *q = tcp->tcp_wq;
3008 	conn_t	*connp = tcp->tcp_connp;
3009 	mlp_type_t addrtype, mlptype;
3010 	zone_t	*zone;
3011 	cred_t	*cr;
3012 	in_port_t mlp_port;
3013 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3014 
3015 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3017 		if (tcp->tcp_debug) {
3018 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3019 			    "tcp_bind: bad req, len %u",
3020 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3021 		}
3022 		tcp_err_ack(tcp, mp, TPROTO, 0);
3023 		return;
3024 	}
3025 	/* Make sure the largest address fits */
3026 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3027 	if (mp1 == NULL) {
3028 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3029 		return;
3030 	}
3031 	mp = mp1;
3032 	tbr = (struct T_bind_req *)mp->b_rptr;
3033 	if (tcp->tcp_state >= TCPS_BOUND) {
3034 		if ((tcp->tcp_state == TCPS_BOUND ||
3035 		    tcp->tcp_state == TCPS_LISTEN) &&
3036 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3037 		    tbr->CONIND_number > 0) {
3038 			/*
3039 			 * Handle listen() increasing CONIND_number.
3040 			 * This is more "liberal" then what the TPI spec
3041 			 * requires but is needed to avoid a t_unbind
3042 			 * when handling listen() since the port number
3043 			 * might be "stolen" between the unbind and bind.
3044 			 */
3045 			backlog_update = B_TRUE;
3046 			goto do_bind;
3047 		}
3048 		if (tcp->tcp_debug) {
3049 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3050 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3051 		}
3052 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3053 		return;
3054 	}
3055 	origipversion = tcp->tcp_ipversion;
3056 
3057 	switch (tbr->ADDR_length) {
3058 	case 0:			/* request for a generic port */
3059 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3060 		if (tcp->tcp_family == AF_INET) {
3061 			tbr->ADDR_length = sizeof (sin_t);
3062 			sin = (sin_t *)&tbr[1];
3063 			*sin = sin_null;
3064 			sin->sin_family = AF_INET;
3065 			mp->b_wptr = (uchar_t *)&sin[1];
3066 			tcp->tcp_ipversion = IPV4_VERSION;
3067 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3068 		} else {
3069 			ASSERT(tcp->tcp_family == AF_INET6);
3070 			tbr->ADDR_length = sizeof (sin6_t);
3071 			sin6 = (sin6_t *)&tbr[1];
3072 			*sin6 = sin6_null;
3073 			sin6->sin6_family = AF_INET6;
3074 			mp->b_wptr = (uchar_t *)&sin6[1];
3075 			tcp->tcp_ipversion = IPV6_VERSION;
3076 			V6_SET_ZERO(v6addr);
3077 		}
3078 		requested_port = 0;
3079 		break;
3080 
3081 	case sizeof (sin_t):	/* Complete IPv4 address */
3082 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3083 		    sizeof (sin_t));
3084 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3085 			if (tcp->tcp_debug) {
3086 				(void) strlog(TCP_MOD_ID, 0, 1,
3087 				    SL_ERROR|SL_TRACE,
3088 				    "tcp_bind: bad address parameter, "
3089 				    "offset %d, len %d",
3090 				    tbr->ADDR_offset, tbr->ADDR_length);
3091 			}
3092 			tcp_err_ack(tcp, mp, TPROTO, 0);
3093 			return;
3094 		}
3095 		/*
3096 		 * With sockets sockfs will accept bogus sin_family in
3097 		 * bind() and replace it with the family used in the socket
3098 		 * call.
3099 		 */
3100 		if (sin->sin_family != AF_INET ||
3101 		    tcp->tcp_family != AF_INET) {
3102 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3103 			return;
3104 		}
3105 		requested_port = ntohs(sin->sin_port);
3106 		tcp->tcp_ipversion = IPV4_VERSION;
3107 		v4addr = sin->sin_addr.s_addr;
3108 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3109 		break;
3110 
3111 	case sizeof (sin6_t): /* Complete IPv6 address */
3112 		sin6 = (sin6_t *)mi_offset_param(mp,
3113 		    tbr->ADDR_offset, sizeof (sin6_t));
3114 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3115 			if (tcp->tcp_debug) {
3116 				(void) strlog(TCP_MOD_ID, 0, 1,
3117 				    SL_ERROR|SL_TRACE,
3118 				    "tcp_bind: bad IPv6 address parameter, "
3119 				    "offset %d, len %d", tbr->ADDR_offset,
3120 				    tbr->ADDR_length);
3121 			}
3122 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3123 			return;
3124 		}
3125 		if (sin6->sin6_family != AF_INET6 ||
3126 		    tcp->tcp_family != AF_INET6) {
3127 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3128 			return;
3129 		}
3130 		requested_port = ntohs(sin6->sin6_port);
3131 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3132 		    IPV4_VERSION : IPV6_VERSION;
3133 		v6addr = sin6->sin6_addr;
3134 		break;
3135 
3136 	default:
3137 		if (tcp->tcp_debug) {
3138 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3139 			    "tcp_bind: bad address length, %d",
3140 			    tbr->ADDR_length);
3141 		}
3142 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3143 		return;
3144 	}
3145 	tcp->tcp_bound_source_v6 = v6addr;
3146 
3147 	/* Check for change in ipversion */
3148 	if (origipversion != tcp->tcp_ipversion) {
3149 		ASSERT(tcp->tcp_family == AF_INET6);
3150 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3151 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3152 		if (err) {
3153 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3154 			return;
3155 		}
3156 	}
3157 
3158 	/*
3159 	 * Initialize family specific fields. Copy of the src addr.
3160 	 * in tcp_t is needed for the lookup funcs.
3161 	 */
3162 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3163 		tcp->tcp_ip6h->ip6_src = v6addr;
3164 	} else {
3165 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3166 	}
3167 	tcp->tcp_ip_src_v6 = v6addr;
3168 
3169 	/*
3170 	 * For O_T_BIND_REQ:
3171 	 * Verify that the target port/addr is available, or choose
3172 	 * another.
3173 	 * For  T_BIND_REQ:
3174 	 * Verify that the target port/addr is available or fail.
3175 	 * In both cases when it succeeds the tcp is inserted in the
3176 	 * bind hash table. This ensures that the operation is atomic
3177 	 * under the lock on the hash bucket.
3178 	 */
3179 	bind_to_req_port_only = requested_port != 0 &&
3180 	    tbr->PRIM_type != O_T_BIND_REQ;
3181 	/*
3182 	 * Get a valid port (within the anonymous range and should not
3183 	 * be a privileged one) to use if the user has not given a port.
3184 	 * If multiple threads are here, they may all start with
3185 	 * with the same initial port. But, it should be fine as long as
3186 	 * tcp_bindi will ensure that no two threads will be assigned
3187 	 * the same port.
3188 	 *
3189 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3190 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3191 	 * unless TCP_ANONPRIVBIND option is set.
3192 	 */
3193 	mlptype = mlptSingle;
3194 	mlp_port = requested_port;
3195 	if (requested_port == 0) {
3196 		requested_port = tcp->tcp_anon_priv_bind ?
3197 		    tcp_get_next_priv_port(tcp) :
3198 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3199 		    tcp, B_TRUE);
3200 		if (requested_port == 0) {
3201 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3202 			return;
3203 		}
3204 		user_specified = B_FALSE;
3205 
3206 		/*
3207 		 * If the user went through one of the RPC interfaces to create
3208 		 * this socket and RPC is MLP in this zone, then give him an
3209 		 * anonymous MLP.
3210 		 */
3211 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3212 		if (connp->conn_anon_mlp && is_system_labeled()) {
3213 			zone = crgetzone(cr);
3214 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3215 			    IPV6_VERSION, &v6addr,
3216 			    tcps->tcps_netstack->netstack_ip);
3217 			if (addrtype == mlptSingle) {
3218 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3219 				return;
3220 			}
3221 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3222 			    PMAPPORT, addrtype);
3223 			mlp_port = PMAPPORT;
3224 		}
3225 	} else {
3226 		int i;
3227 		boolean_t priv = B_FALSE;
3228 
3229 		/*
3230 		 * If the requested_port is in the well-known privileged range,
3231 		 * verify that the stream was opened by a privileged user.
3232 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3233 		 * but instead the code relies on:
3234 		 * - the fact that the address of the array and its size never
3235 		 *   changes
3236 		 * - the atomic assignment of the elements of the array
3237 		 */
3238 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3239 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3240 			priv = B_TRUE;
3241 		} else {
3242 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3243 				if (requested_port ==
3244 				    tcps->tcps_g_epriv_ports[i]) {
3245 					priv = B_TRUE;
3246 					break;
3247 				}
3248 			}
3249 		}
3250 		if (priv) {
3251 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3252 				if (tcp->tcp_debug) {
3253 					(void) strlog(TCP_MOD_ID, 0, 1,
3254 					    SL_ERROR|SL_TRACE,
3255 					    "tcp_bind: no priv for port %d",
3256 					    requested_port);
3257 				}
3258 				tcp_err_ack(tcp, mp, TACCES, 0);
3259 				return;
3260 			}
3261 		}
3262 		user_specified = B_TRUE;
3263 
3264 		if (is_system_labeled()) {
3265 			zone = crgetzone(cr);
3266 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3267 			    IPV6_VERSION, &v6addr,
3268 			    tcps->tcps_netstack->netstack_ip);
3269 			if (addrtype == mlptSingle) {
3270 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3271 				return;
3272 			}
3273 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3274 			    requested_port, addrtype);
3275 		}
3276 	}
3277 
3278 	if (mlptype != mlptSingle) {
3279 		if (secpolicy_net_bindmlp(cr) != 0) {
3280 			if (tcp->tcp_debug) {
3281 				(void) strlog(TCP_MOD_ID, 0, 1,
3282 				    SL_ERROR|SL_TRACE,
3283 				    "tcp_bind: no priv for multilevel port %d",
3284 				    requested_port);
3285 			}
3286 			tcp_err_ack(tcp, mp, TACCES, 0);
3287 			return;
3288 		}
3289 
3290 		/*
3291 		 * If we're specifically binding a shared IP address and the
3292 		 * port is MLP on shared addresses, then check to see if this
3293 		 * zone actually owns the MLP.  Reject if not.
3294 		 */
3295 		if (mlptype == mlptShared && addrtype == mlptShared) {
3296 			/*
3297 			 * No need to handle exclusive-stack zones since
3298 			 * ALL_ZONES only applies to the shared stack.
3299 			 */
3300 			zoneid_t mlpzone;
3301 
3302 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3303 			    htons(mlp_port));
3304 			if (connp->conn_zoneid != mlpzone) {
3305 				if (tcp->tcp_debug) {
3306 					(void) strlog(TCP_MOD_ID, 0, 1,
3307 					    SL_ERROR|SL_TRACE,
3308 					    "tcp_bind: attempt to bind port "
3309 					    "%d on shared addr in zone %d "
3310 					    "(should be %d)",
3311 					    mlp_port, connp->conn_zoneid,
3312 					    mlpzone);
3313 				}
3314 				tcp_err_ack(tcp, mp, TACCES, 0);
3315 				return;
3316 			}
3317 		}
3318 
3319 		if (!user_specified) {
3320 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3321 			    requested_port, B_TRUE);
3322 			if (err != 0) {
3323 				if (tcp->tcp_debug) {
3324 					(void) strlog(TCP_MOD_ID, 0, 1,
3325 					    SL_ERROR|SL_TRACE,
3326 					    "tcp_bind: cannot establish anon "
3327 					    "MLP for port %d",
3328 					    requested_port);
3329 				}
3330 				tcp_err_ack(tcp, mp, TSYSERR, err);
3331 				return;
3332 			}
3333 			connp->conn_anon_port = B_TRUE;
3334 		}
3335 		connp->conn_mlp_type = mlptype;
3336 	}
3337 
3338 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3339 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3340 
3341 	if (allocated_port == 0) {
3342 		connp->conn_mlp_type = mlptSingle;
3343 		if (connp->conn_anon_port) {
3344 			connp->conn_anon_port = B_FALSE;
3345 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3346 			    requested_port, B_FALSE);
3347 		}
3348 		if (bind_to_req_port_only) {
3349 			if (tcp->tcp_debug) {
3350 				(void) strlog(TCP_MOD_ID, 0, 1,
3351 				    SL_ERROR|SL_TRACE,
3352 				    "tcp_bind: requested addr busy");
3353 			}
3354 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3355 		} else {
3356 			/* If we are out of ports, fail the bind. */
3357 			if (tcp->tcp_debug) {
3358 				(void) strlog(TCP_MOD_ID, 0, 1,
3359 				    SL_ERROR|SL_TRACE,
3360 				    "tcp_bind: out of ports?");
3361 			}
3362 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3363 		}
3364 		return;
3365 	}
3366 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3367 do_bind:
3368 	if (!backlog_update) {
3369 		if (tcp->tcp_family == AF_INET)
3370 			sin->sin_port = htons(allocated_port);
3371 		else
3372 			sin6->sin6_port = htons(allocated_port);
3373 	}
3374 	if (tcp->tcp_family == AF_INET) {
3375 		if (tbr->CONIND_number != 0) {
3376 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3377 			    sizeof (sin_t));
3378 		} else {
3379 			/* Just verify the local IP address */
3380 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3381 		}
3382 	} else {
3383 		if (tbr->CONIND_number != 0) {
3384 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3385 			    sizeof (sin6_t));
3386 		} else {
3387 			/* Just verify the local IP address */
3388 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3389 			    IPV6_ADDR_LEN);
3390 		}
3391 	}
3392 	if (mp1 == NULL) {
3393 		if (connp->conn_anon_port) {
3394 			connp->conn_anon_port = B_FALSE;
3395 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3396 			    requested_port, B_FALSE);
3397 		}
3398 		connp->conn_mlp_type = mlptSingle;
3399 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3400 		return;
3401 	}
3402 
3403 	tbr->PRIM_type = T_BIND_ACK;
3404 	mp->b_datap->db_type = M_PCPROTO;
3405 
3406 	/* Chain in the reply mp for tcp_rput() */
3407 	mp1->b_cont = mp;
3408 	mp = mp1;
3409 
3410 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3411 	if (tcp->tcp_conn_req_max) {
3412 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3413 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3414 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3415 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3416 		/*
3417 		 * If this is a listener, do not reset the eager list
3418 		 * and other stuffs.  Note that we don't check if the
3419 		 * existing eager list meets the new tcp_conn_req_max
3420 		 * requirement.
3421 		 */
3422 		if (tcp->tcp_state != TCPS_LISTEN) {
3423 			tcp->tcp_state = TCPS_LISTEN;
3424 			/* Initialize the chain. Don't need the eager_lock */
3425 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3426 			tcp->tcp_eager_next_drop_q0 = tcp;
3427 			tcp->tcp_eager_prev_drop_q0 = tcp;
3428 			tcp->tcp_second_ctimer_threshold =
3429 			    tcps->tcps_ip_abort_linterval;
3430 		}
3431 	}
3432 
3433 	/*
3434 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3435 	 * processing continues in tcp_rput_other().
3436 	 *
3437 	 * We need to make sure that the conn_recv is set to a non-null
3438 	 * value before we insert the conn into the classifier table.
3439 	 * This is to avoid a race with an incoming packet which does an
3440 	 * ipcl_classify().
3441 	 */
3442 	connp->conn_recv = tcp_conn_request;
3443 	if (tcp->tcp_family == AF_INET6) {
3444 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3445 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3446 	} else {
3447 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3448 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3449 	}
3450 	/*
3451 	 * If the bind cannot complete immediately
3452 	 * IP will arrange to call tcp_rput_other
3453 	 * when the bind completes.
3454 	 */
3455 	if (mp != NULL) {
3456 		tcp_rput_other(tcp, mp);
3457 	} else {
3458 		/*
3459 		 * Bind will be resumed later. Need to ensure
3460 		 * that conn doesn't disappear when that happens.
3461 		 * This will be decremented in ip_resume_tcp_bind().
3462 		 */
3463 		CONN_INC_REF(tcp->tcp_connp);
3464 	}
3465 }
3466 
3467 
3468 /*
3469  * If the "bind_to_req_port_only" parameter is set, if the requested port
3470  * number is available, return it, If not return 0
3471  *
3472  * If "bind_to_req_port_only" parameter is not set and
3473  * If the requested port number is available, return it.  If not, return
3474  * the first anonymous port we happen across.  If no anonymous ports are
3475  * available, return 0. addr is the requested local address, if any.
3476  *
3477  * In either case, when succeeding update the tcp_t to record the port number
3478  * and insert it in the bind hash table.
3479  *
3480  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3481  * without setting SO_REUSEADDR. This is needed so that they
3482  * can be viewed as two independent transport protocols.
3483  */
3484 static in_port_t
3485 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3486     int reuseaddr, boolean_t quick_connect,
3487     boolean_t bind_to_req_port_only, boolean_t user_specified)
3488 {
3489 	/* number of times we have run around the loop */
3490 	int count = 0;
3491 	/* maximum number of times to run around the loop */
3492 	int loopmax;
3493 	conn_t *connp = tcp->tcp_connp;
3494 	zoneid_t zoneid = connp->conn_zoneid;
3495 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3496 
3497 	/*
3498 	 * Lookup for free addresses is done in a loop and "loopmax"
3499 	 * influences how long we spin in the loop
3500 	 */
3501 	if (bind_to_req_port_only) {
3502 		/*
3503 		 * If the requested port is busy, don't bother to look
3504 		 * for a new one. Setting loop maximum count to 1 has
3505 		 * that effect.
3506 		 */
3507 		loopmax = 1;
3508 	} else {
3509 		/*
3510 		 * If the requested port is busy, look for a free one
3511 		 * in the anonymous port range.
3512 		 * Set loopmax appropriately so that one does not look
3513 		 * forever in the case all of the anonymous ports are in use.
3514 		 */
3515 		if (tcp->tcp_anon_priv_bind) {
3516 			/*
3517 			 * loopmax =
3518 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3519 			 */
3520 			loopmax = IPPORT_RESERVED -
3521 			    tcps->tcps_min_anonpriv_port;
3522 		} else {
3523 			loopmax = (tcps->tcps_largest_anon_port -
3524 			    tcps->tcps_smallest_anon_port + 1);
3525 		}
3526 	}
3527 	do {
3528 		uint16_t	lport;
3529 		tf_t		*tbf;
3530 		tcp_t		*ltcp;
3531 		conn_t		*lconnp;
3532 
3533 		lport = htons(port);
3534 
3535 		/*
3536 		 * Ensure that the tcp_t is not currently in the bind hash.
3537 		 * Hold the lock on the hash bucket to ensure that
3538 		 * the duplicate check plus the insertion is an atomic
3539 		 * operation.
3540 		 *
3541 		 * This function does an inline lookup on the bind hash list
3542 		 * Make sure that we access only members of tcp_t
3543 		 * and that we don't look at tcp_tcp, since we are not
3544 		 * doing a CONN_INC_REF.
3545 		 */
3546 		tcp_bind_hash_remove(tcp);
3547 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3548 		mutex_enter(&tbf->tf_lock);
3549 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3550 		    ltcp = ltcp->tcp_bind_hash) {
3551 			boolean_t not_socket;
3552 			boolean_t exclbind;
3553 
3554 			if (lport != ltcp->tcp_lport)
3555 				continue;
3556 
3557 			lconnp = ltcp->tcp_connp;
3558 
3559 			/*
3560 			 * On a labeled system, we must treat bindings to ports
3561 			 * on shared IP addresses by sockets with MAC exemption
3562 			 * privilege as being in all zones, as there's
3563 			 * otherwise no way to identify the right receiver.
3564 			 */
3565 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3566 			    IPCL_ZONE_MATCH(connp,
3567 			    ltcp->tcp_connp->conn_zoneid)) &&
3568 			    !lconnp->conn_mac_exempt &&
3569 			    !connp->conn_mac_exempt)
3570 				continue;
3571 
3572 			/*
3573 			 * If TCP_EXCLBIND is set for either the bound or
3574 			 * binding endpoint, the semantics of bind
3575 			 * is changed according to the following.
3576 			 *
3577 			 * spec = specified address (v4 or v6)
3578 			 * unspec = unspecified address (v4 or v6)
3579 			 * A = specified addresses are different for endpoints
3580 			 *
3581 			 * bound	bind to		allowed
3582 			 * -------------------------------------
3583 			 * unspec	unspec		no
3584 			 * unspec	spec		no
3585 			 * spec		unspec		no
3586 			 * spec		spec		yes if A
3587 			 *
3588 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3589 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3590 			 *
3591 			 * Note:
3592 			 *
3593 			 * 1. Because of TLI semantics, an endpoint can go
3594 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3595 			 * TCPS_BOUND, depending on whether it is originally
3596 			 * a listener or not.  That is why we need to check
3597 			 * for states greater than or equal to TCPS_BOUND
3598 			 * here.
3599 			 *
3600 			 * 2. Ideally, we should only check for state equals
3601 			 * to TCPS_LISTEN. And the following check should be
3602 			 * added.
3603 			 *
3604 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3605 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3606 			 *		...
3607 			 * }
3608 			 *
3609 			 * The semantics will be changed to this.  If the
3610 			 * endpoint on the list is in state not equal to
3611 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3612 			 * set, let the bind succeed.
3613 			 *
3614 			 * Because of (1), we cannot do that for TLI
3615 			 * endpoints.  But we can do that for socket endpoints.
3616 			 * If in future, we can change this going back
3617 			 * semantics, we can use the above check for TLI also.
3618 			 */
3619 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3620 			    TCP_IS_SOCKET(tcp));
3621 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3622 
3623 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3624 			    (exclbind && (not_socket ||
3625 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3626 				if (V6_OR_V4_INADDR_ANY(
3627 				    ltcp->tcp_bound_source_v6) ||
3628 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3629 				    IN6_ARE_ADDR_EQUAL(laddr,
3630 				    &ltcp->tcp_bound_source_v6)) {
3631 					break;
3632 				}
3633 				continue;
3634 			}
3635 
3636 			/*
3637 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3638 			 * have disjoint port number spaces, if *_EXCLBIND
3639 			 * is not set and only if the application binds to a
3640 			 * specific port. We use the same autoassigned port
3641 			 * number space for IPv4 and IPv6 sockets.
3642 			 */
3643 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3644 			    bind_to_req_port_only)
3645 				continue;
3646 
3647 			/*
3648 			 * Ideally, we should make sure that the source
3649 			 * address, remote address, and remote port in the
3650 			 * four tuple for this tcp-connection is unique.
3651 			 * However, trying to find out the local source
3652 			 * address would require too much code duplication
3653 			 * with IP, since IP needs needs to have that code
3654 			 * to support userland TCP implementations.
3655 			 */
3656 			if (quick_connect &&
3657 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3658 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3659 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3660 			    &ltcp->tcp_remote_v6)))
3661 				continue;
3662 
3663 			if (!reuseaddr) {
3664 				/*
3665 				 * No socket option SO_REUSEADDR.
3666 				 * If existing port is bound to
3667 				 * a non-wildcard IP address
3668 				 * and the requesting stream is
3669 				 * bound to a distinct
3670 				 * different IP addresses
3671 				 * (non-wildcard, also), keep
3672 				 * going.
3673 				 */
3674 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3675 				    !V6_OR_V4_INADDR_ANY(
3676 				    ltcp->tcp_bound_source_v6) &&
3677 				    !IN6_ARE_ADDR_EQUAL(laddr,
3678 				    &ltcp->tcp_bound_source_v6))
3679 					continue;
3680 				if (ltcp->tcp_state >= TCPS_BOUND) {
3681 					/*
3682 					 * This port is being used and
3683 					 * its state is >= TCPS_BOUND,
3684 					 * so we can't bind to it.
3685 					 */
3686 					break;
3687 				}
3688 			} else {
3689 				/*
3690 				 * socket option SO_REUSEADDR is set on the
3691 				 * binding tcp_t.
3692 				 *
3693 				 * If two streams are bound to
3694 				 * same IP address or both addr
3695 				 * and bound source are wildcards
3696 				 * (INADDR_ANY), we want to stop
3697 				 * searching.
3698 				 * We have found a match of IP source
3699 				 * address and source port, which is
3700 				 * refused regardless of the
3701 				 * SO_REUSEADDR setting, so we break.
3702 				 */
3703 				if (IN6_ARE_ADDR_EQUAL(laddr,
3704 				    &ltcp->tcp_bound_source_v6) &&
3705 				    (ltcp->tcp_state == TCPS_LISTEN ||
3706 				    ltcp->tcp_state == TCPS_BOUND))
3707 					break;
3708 			}
3709 		}
3710 		if (ltcp != NULL) {
3711 			/* The port number is busy */
3712 			mutex_exit(&tbf->tf_lock);
3713 		} else {
3714 			/*
3715 			 * This port is ours. Insert in fanout and mark as
3716 			 * bound to prevent others from getting the port
3717 			 * number.
3718 			 */
3719 			tcp->tcp_state = TCPS_BOUND;
3720 			tcp->tcp_lport = htons(port);
3721 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3722 
3723 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3724 			    tcp->tcp_lport)] == tbf);
3725 			tcp_bind_hash_insert(tbf, tcp, 1);
3726 
3727 			mutex_exit(&tbf->tf_lock);
3728 
3729 			/*
3730 			 * We don't want tcp_next_port_to_try to "inherit"
3731 			 * a port number supplied by the user in a bind.
3732 			 */
3733 			if (user_specified)
3734 				return (port);
3735 
3736 			/*
3737 			 * This is the only place where tcp_next_port_to_try
3738 			 * is updated. After the update, it may or may not
3739 			 * be in the valid range.
3740 			 */
3741 			if (!tcp->tcp_anon_priv_bind)
3742 				tcps->tcps_next_port_to_try = port + 1;
3743 			return (port);
3744 		}
3745 
3746 		if (tcp->tcp_anon_priv_bind) {
3747 			port = tcp_get_next_priv_port(tcp);
3748 		} else {
3749 			if (count == 0 && user_specified) {
3750 				/*
3751 				 * We may have to return an anonymous port. So
3752 				 * get one to start with.
3753 				 */
3754 				port =
3755 				    tcp_update_next_port(
3756 				    tcps->tcps_next_port_to_try,
3757 				    tcp, B_TRUE);
3758 				user_specified = B_FALSE;
3759 			} else {
3760 				port = tcp_update_next_port(port + 1, tcp,
3761 				    B_FALSE);
3762 			}
3763 		}
3764 		if (port == 0)
3765 			break;
3766 
3767 		/*
3768 		 * Don't let this loop run forever in the case where
3769 		 * all of the anonymous ports are in use.
3770 		 */
3771 	} while (++count < loopmax);
3772 	return (0);
3773 }
3774 
3775 /*
3776  * tcp_clean_death / tcp_close_detached must not be called more than once
3777  * on a tcp. Thus every function that potentially calls tcp_clean_death
3778  * must check for the tcp state before calling tcp_clean_death.
3779  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3780  * tcp_timer_handler, all check for the tcp state.
3781  */
3782 /* ARGSUSED */
3783 void
3784 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3785 {
3786 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3787 
3788 	freemsg(mp);
3789 	if (tcp->tcp_state > TCPS_BOUND)
3790 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3791 		    ETIMEDOUT, 5);
3792 }
3793 
3794 /*
3795  * We are dying for some reason.  Try to do it gracefully.  (May be called
3796  * as writer.)
3797  *
3798  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3799  * done by a service procedure).
3800  * TBD - Should the return value distinguish between the tcp_t being
3801  * freed and it being reinitialized?
3802  */
3803 static int
3804 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3805 {
3806 	mblk_t	*mp;
3807 	queue_t	*q;
3808 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3809 
3810 	TCP_CLD_STAT(tag);
3811 
3812 #if TCP_TAG_CLEAN_DEATH
3813 	tcp->tcp_cleandeathtag = tag;
3814 #endif
3815 
3816 	if (tcp->tcp_fused)
3817 		tcp_unfuse(tcp);
3818 
3819 	if (tcp->tcp_linger_tid != 0 &&
3820 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3821 		tcp_stop_lingering(tcp);
3822 	}
3823 
3824 	ASSERT(tcp != NULL);
3825 	ASSERT((tcp->tcp_family == AF_INET &&
3826 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3827 	    (tcp->tcp_family == AF_INET6 &&
3828 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3829 	    tcp->tcp_ipversion == IPV6_VERSION)));
3830 
3831 	if (TCP_IS_DETACHED(tcp)) {
3832 		if (tcp->tcp_hard_binding) {
3833 			/*
3834 			 * Its an eager that we are dealing with. We close the
3835 			 * eager but in case a conn_ind has already gone to the
3836 			 * listener, let tcp_accept_finish() send a discon_ind
3837 			 * to the listener and drop the last reference. If the
3838 			 * listener doesn't even know about the eager i.e. the
3839 			 * conn_ind hasn't gone up, blow away the eager and drop
3840 			 * the last reference as well. If the conn_ind has gone
3841 			 * up, state should be BOUND. tcp_accept_finish
3842 			 * will figure out that the connection has received a
3843 			 * RST and will send a DISCON_IND to the application.
3844 			 */
3845 			tcp_closei_local(tcp);
3846 			if (!tcp->tcp_tconnind_started) {
3847 				CONN_DEC_REF(tcp->tcp_connp);
3848 			} else {
3849 				tcp->tcp_state = TCPS_BOUND;
3850 			}
3851 		} else {
3852 			tcp_close_detached(tcp);
3853 		}
3854 		return (0);
3855 	}
3856 
3857 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3858 
3859 	/*
3860 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3861 	 * is run) postpone cleaning up the endpoint until service routine
3862 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3863 	 * client_errno since tcp_close uses the client_errno field.
3864 	 */
3865 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3866 		if (err != 0)
3867 			tcp->tcp_client_errno = err;
3868 
3869 		tcp->tcp_deferred_clean_death = B_TRUE;
3870 		return (-1);
3871 	}
3872 
3873 	q = tcp->tcp_rq;
3874 
3875 	/* Trash all inbound data */
3876 	flushq(q, FLUSHALL);
3877 
3878 	/*
3879 	 * If we are at least part way open and there is error
3880 	 * (err==0 implies no error)
3881 	 * notify our client by a T_DISCON_IND.
3882 	 */
3883 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3884 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3885 		    !TCP_IS_SOCKET(tcp)) {
3886 			/*
3887 			 * Send M_FLUSH according to TPI. Because sockets will
3888 			 * (and must) ignore FLUSHR we do that only for TPI
3889 			 * endpoints and sockets in STREAMS mode.
3890 			 */
3891 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3892 		}
3893 		if (tcp->tcp_debug) {
3894 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3895 			    "tcp_clean_death: discon err %d", err);
3896 		}
3897 		mp = mi_tpi_discon_ind(NULL, err, 0);
3898 		if (mp != NULL) {
3899 			putnext(q, mp);
3900 		} else {
3901 			if (tcp->tcp_debug) {
3902 				(void) strlog(TCP_MOD_ID, 0, 1,
3903 				    SL_ERROR|SL_TRACE,
3904 				    "tcp_clean_death, sending M_ERROR");
3905 			}
3906 			(void) putnextctl1(q, M_ERROR, EPROTO);
3907 		}
3908 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3909 			/* SYN_SENT or SYN_RCVD */
3910 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3911 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3912 			/* ESTABLISHED or CLOSE_WAIT */
3913 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3914 		}
3915 	}
3916 
3917 	tcp_reinit(tcp);
3918 	return (-1);
3919 }
3920 
3921 /*
3922  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3923  * to expire, stop the wait and finish the close.
3924  */
3925 static void
3926 tcp_stop_lingering(tcp_t *tcp)
3927 {
3928 	clock_t	delta = 0;
3929 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3930 
3931 	tcp->tcp_linger_tid = 0;
3932 	if (tcp->tcp_state > TCPS_LISTEN) {
3933 		tcp_acceptor_hash_remove(tcp);
3934 		mutex_enter(&tcp->tcp_non_sq_lock);
3935 		if (tcp->tcp_flow_stopped) {
3936 			tcp_clrqfull(tcp);
3937 		}
3938 		mutex_exit(&tcp->tcp_non_sq_lock);
3939 
3940 		if (tcp->tcp_timer_tid != 0) {
3941 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3942 			tcp->tcp_timer_tid = 0;
3943 		}
3944 		/*
3945 		 * Need to cancel those timers which will not be used when
3946 		 * TCP is detached.  This has to be done before the tcp_wq
3947 		 * is set to the global queue.
3948 		 */
3949 		tcp_timers_stop(tcp);
3950 
3951 
3952 		tcp->tcp_detached = B_TRUE;
3953 		ASSERT(tcps->tcps_g_q != NULL);
3954 		tcp->tcp_rq = tcps->tcps_g_q;
3955 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3956 
3957 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3958 			tcp_time_wait_append(tcp);
3959 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3960 			goto finish;
3961 		}
3962 
3963 		/*
3964 		 * If delta is zero the timer event wasn't executed and was
3965 		 * successfully canceled. In this case we need to restart it
3966 		 * with the minimal delta possible.
3967 		 */
3968 		if (delta >= 0) {
3969 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3970 			    delta ? delta : 1);
3971 		}
3972 	} else {
3973 		tcp_closei_local(tcp);
3974 		CONN_DEC_REF(tcp->tcp_connp);
3975 	}
3976 finish:
3977 	/* Signal closing thread that it can complete close */
3978 	mutex_enter(&tcp->tcp_closelock);
3979 	tcp->tcp_detached = B_TRUE;
3980 	ASSERT(tcps->tcps_g_q != NULL);
3981 	tcp->tcp_rq = tcps->tcps_g_q;
3982 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3983 	tcp->tcp_closed = 1;
3984 	cv_signal(&tcp->tcp_closecv);
3985 	mutex_exit(&tcp->tcp_closelock);
3986 }
3987 
3988 /*
3989  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3990  * expires.
3991  */
3992 static void
3993 tcp_close_linger_timeout(void *arg)
3994 {
3995 	conn_t	*connp = (conn_t *)arg;
3996 	tcp_t 	*tcp = connp->conn_tcp;
3997 
3998 	tcp->tcp_client_errno = ETIMEDOUT;
3999 	tcp_stop_lingering(tcp);
4000 }
4001 
4002 static int
4003 tcp_close(queue_t *q, int flags)
4004 {
4005 	conn_t		*connp = Q_TO_CONN(q);
4006 	tcp_t		*tcp = connp->conn_tcp;
4007 	mblk_t 		*mp = &tcp->tcp_closemp;
4008 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4009 	boolean_t	linger_interrupted = B_FALSE;
4010 	mblk_t		*bp;
4011 
4012 	ASSERT(WR(q)->q_next == NULL);
4013 	ASSERT(connp->conn_ref >= 2);
4014 
4015 	/*
4016 	 * We are being closed as /dev/tcp or /dev/tcp6.
4017 	 *
4018 	 * Mark the conn as closing. ill_pending_mp_add will not
4019 	 * add any mp to the pending mp list, after this conn has
4020 	 * started closing. Same for sq_pending_mp_add
4021 	 */
4022 	mutex_enter(&connp->conn_lock);
4023 	connp->conn_state_flags |= CONN_CLOSING;
4024 	if (connp->conn_oper_pending_ill != NULL)
4025 		conn_ioctl_cleanup_reqd = B_TRUE;
4026 	CONN_INC_REF_LOCKED(connp);
4027 	mutex_exit(&connp->conn_lock);
4028 	tcp->tcp_closeflags = (uint8_t)flags;
4029 	ASSERT(connp->conn_ref >= 3);
4030 
4031 	/*
4032 	 * tcp_closemp_used is used below without any protection of a lock
4033 	 * as we don't expect any one else to use it concurrently at this
4034 	 * point otherwise it would be a major defect.
4035 	 */
4036 
4037 	if (mp->b_prev == NULL)
4038 		tcp->tcp_closemp_used = B_TRUE;
4039 	else
4040 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4041 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4042 
4043 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4044 
4045 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4046 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4047 
4048 	mutex_enter(&tcp->tcp_closelock);
4049 	while (!tcp->tcp_closed) {
4050 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4051 			/*
4052 			 * We got interrupted. Check if we are lingering,
4053 			 * if yes, post a message to stop and wait until
4054 			 * tcp_closed is set. If we aren't lingering,
4055 			 * just go back around.
4056 			 */
4057 			if (tcp->tcp_linger &&
4058 			    tcp->tcp_lingertime > 0 &&
4059 			    !linger_interrupted) {
4060 				mutex_exit(&tcp->tcp_closelock);
4061 				/* Entering squeue, bump ref count. */
4062 				CONN_INC_REF(connp);
4063 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4064 				squeue_enter(connp->conn_sqp, bp,
4065 				    tcp_linger_interrupted, connp,
4066 				    SQTAG_IP_TCP_CLOSE);
4067 				linger_interrupted = B_TRUE;
4068 				mutex_enter(&tcp->tcp_closelock);
4069 			}
4070 		}
4071 	}
4072 	mutex_exit(&tcp->tcp_closelock);
4073 
4074 	/*
4075 	 * In the case of listener streams that have eagers in the q or q0
4076 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4077 	 * tcp_wq of the eagers point to our queues. By waiting for the
4078 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4079 	 * up their queue pointers and also dropped their references to us.
4080 	 */
4081 	if (tcp->tcp_wait_for_eagers) {
4082 		mutex_enter(&connp->conn_lock);
4083 		while (connp->conn_ref != 1) {
4084 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4085 		}
4086 		mutex_exit(&connp->conn_lock);
4087 	}
4088 	/*
4089 	 * ioctl cleanup. The mp is queued in the
4090 	 * ill_pending_mp or in the sq_pending_mp.
4091 	 */
4092 	if (conn_ioctl_cleanup_reqd)
4093 		conn_ioctl_cleanup(connp);
4094 
4095 	qprocsoff(q);
4096 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4097 
4098 	tcp->tcp_cpid = -1;
4099 
4100 	/*
4101 	 * Drop IP's reference on the conn. This is the last reference
4102 	 * on the connp if the state was less than established. If the
4103 	 * connection has gone into timewait state, then we will have
4104 	 * one ref for the TCP and one more ref (total of two) for the
4105 	 * classifier connected hash list (a timewait connections stays
4106 	 * in connected hash till closed).
4107 	 *
4108 	 * We can't assert the references because there might be other
4109 	 * transient reference places because of some walkers or queued
4110 	 * packets in squeue for the timewait state.
4111 	 */
4112 	CONN_DEC_REF(connp);
4113 	q->q_ptr = WR(q)->q_ptr = NULL;
4114 	return (0);
4115 }
4116 
4117 static int
4118 tcpclose_accept(queue_t *q)
4119 {
4120 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4121 
4122 	/*
4123 	 * We had opened an acceptor STREAM for sockfs which is
4124 	 * now being closed due to some error.
4125 	 */
4126 	qprocsoff(q);
4127 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4128 	q->q_ptr = WR(q)->q_ptr = NULL;
4129 	return (0);
4130 }
4131 
4132 /*
4133  * Called by tcp_close() routine via squeue when lingering is
4134  * interrupted by a signal.
4135  */
4136 
4137 /* ARGSUSED */
4138 static void
4139 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4140 {
4141 	conn_t	*connp = (conn_t *)arg;
4142 	tcp_t	*tcp = connp->conn_tcp;
4143 
4144 	freeb(mp);
4145 	if (tcp->tcp_linger_tid != 0 &&
4146 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4147 		tcp_stop_lingering(tcp);
4148 		tcp->tcp_client_errno = EINTR;
4149 	}
4150 }
4151 
4152 /*
4153  * Called by streams close routine via squeues when our client blows off her
4154  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4155  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4156  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4157  * acked.
4158  *
4159  * NOTE: tcp_close potentially returns error when lingering.
4160  * However, the stream head currently does not pass these errors
4161  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4162  * errors to the application (from tsleep()) and not errors
4163  * like ECONNRESET caused by receiving a reset packet.
4164  */
4165 
4166 /* ARGSUSED */
4167 static void
4168 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4169 {
4170 	char	*msg;
4171 	conn_t	*connp = (conn_t *)arg;
4172 	tcp_t	*tcp = connp->conn_tcp;
4173 	clock_t	delta = 0;
4174 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4175 
4176 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4177 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4178 
4179 	/* Cancel any pending timeout */
4180 	if (tcp->tcp_ordrelid != 0) {
4181 		if (tcp->tcp_timeout) {
4182 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4183 		}
4184 		tcp->tcp_ordrelid = 0;
4185 		tcp->tcp_timeout = B_FALSE;
4186 	}
4187 
4188 	mutex_enter(&tcp->tcp_eager_lock);
4189 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4190 		/* Cleanup for listener */
4191 		tcp_eager_cleanup(tcp, 0);
4192 		tcp->tcp_wait_for_eagers = 1;
4193 	}
4194 	mutex_exit(&tcp->tcp_eager_lock);
4195 
4196 	connp->conn_mdt_ok = B_FALSE;
4197 	tcp->tcp_mdt = B_FALSE;
4198 
4199 	connp->conn_lso_ok = B_FALSE;
4200 	tcp->tcp_lso = B_FALSE;
4201 
4202 	msg = NULL;
4203 	switch (tcp->tcp_state) {
4204 	case TCPS_CLOSED:
4205 	case TCPS_IDLE:
4206 	case TCPS_BOUND:
4207 	case TCPS_LISTEN:
4208 		break;
4209 	case TCPS_SYN_SENT:
4210 		msg = "tcp_close, during connect";
4211 		break;
4212 	case TCPS_SYN_RCVD:
4213 		/*
4214 		 * Close during the connect 3-way handshake
4215 		 * but here there may or may not be pending data
4216 		 * already on queue. Process almost same as in
4217 		 * the ESTABLISHED state.
4218 		 */
4219 		/* FALLTHRU */
4220 	default:
4221 		if (tcp->tcp_fused)
4222 			tcp_unfuse(tcp);
4223 
4224 		/*
4225 		 * If SO_LINGER has set a zero linger time, abort the
4226 		 * connection with a reset.
4227 		 */
4228 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4229 			msg = "tcp_close, zero lingertime";
4230 			break;
4231 		}
4232 
4233 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4234 		/*
4235 		 * Abort connection if there is unread data queued.
4236 		 */
4237 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4238 			msg = "tcp_close, unread data";
4239 			break;
4240 		}
4241 		/*
4242 		 * tcp_hard_bound is now cleared thus all packets go through
4243 		 * tcp_lookup. This fact is used by tcp_detach below.
4244 		 *
4245 		 * We have done a qwait() above which could have possibly
4246 		 * drained more messages in turn causing transition to a
4247 		 * different state. Check whether we have to do the rest
4248 		 * of the processing or not.
4249 		 */
4250 		if (tcp->tcp_state <= TCPS_LISTEN)
4251 			break;
4252 
4253 		/*
4254 		 * Transmit the FIN before detaching the tcp_t.
4255 		 * After tcp_detach returns this queue/perimeter
4256 		 * no longer owns the tcp_t thus others can modify it.
4257 		 */
4258 		(void) tcp_xmit_end(tcp);
4259 
4260 		/*
4261 		 * If lingering on close then wait until the fin is acked,
4262 		 * the SO_LINGER time passes, or a reset is sent/received.
4263 		 */
4264 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4265 		    !(tcp->tcp_fin_acked) &&
4266 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4267 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4268 				tcp->tcp_client_errno = EWOULDBLOCK;
4269 			} else if (tcp->tcp_client_errno == 0) {
4270 
4271 				ASSERT(tcp->tcp_linger_tid == 0);
4272 
4273 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4274 				    tcp_close_linger_timeout,
4275 				    tcp->tcp_lingertime * hz);
4276 
4277 				/* tcp_close_linger_timeout will finish close */
4278 				if (tcp->tcp_linger_tid == 0)
4279 					tcp->tcp_client_errno = ENOSR;
4280 				else
4281 					return;
4282 			}
4283 
4284 			/*
4285 			 * Check if we need to detach or just close
4286 			 * the instance.
4287 			 */
4288 			if (tcp->tcp_state <= TCPS_LISTEN)
4289 				break;
4290 		}
4291 
4292 		/*
4293 		 * Make sure that no other thread will access the tcp_rq of
4294 		 * this instance (through lookups etc.) as tcp_rq will go
4295 		 * away shortly.
4296 		 */
4297 		tcp_acceptor_hash_remove(tcp);
4298 
4299 		mutex_enter(&tcp->tcp_non_sq_lock);
4300 		if (tcp->tcp_flow_stopped) {
4301 			tcp_clrqfull(tcp);
4302 		}
4303 		mutex_exit(&tcp->tcp_non_sq_lock);
4304 
4305 		if (tcp->tcp_timer_tid != 0) {
4306 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4307 			tcp->tcp_timer_tid = 0;
4308 		}
4309 		/*
4310 		 * Need to cancel those timers which will not be used when
4311 		 * TCP is detached.  This has to be done before the tcp_wq
4312 		 * is set to the global queue.
4313 		 */
4314 		tcp_timers_stop(tcp);
4315 
4316 		tcp->tcp_detached = B_TRUE;
4317 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4318 			tcp_time_wait_append(tcp);
4319 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4320 			ASSERT(connp->conn_ref >= 3);
4321 			goto finish;
4322 		}
4323 
4324 		/*
4325 		 * If delta is zero the timer event wasn't executed and was
4326 		 * successfully canceled. In this case we need to restart it
4327 		 * with the minimal delta possible.
4328 		 */
4329 		if (delta >= 0)
4330 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4331 			    delta ? delta : 1);
4332 
4333 		ASSERT(connp->conn_ref >= 3);
4334 		goto finish;
4335 	}
4336 
4337 	/* Detach did not complete. Still need to remove q from stream. */
4338 	if (msg) {
4339 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4340 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4341 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4342 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4343 		    tcp->tcp_state == TCPS_SYN_RCVD)
4344 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4345 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4346 	}
4347 
4348 	tcp_closei_local(tcp);
4349 	CONN_DEC_REF(connp);
4350 	ASSERT(connp->conn_ref >= 2);
4351 
4352 finish:
4353 	/*
4354 	 * Although packets are always processed on the correct
4355 	 * tcp's perimeter and access is serialized via squeue's,
4356 	 * IP still needs a queue when sending packets in time_wait
4357 	 * state so use WR(tcps_g_q) till ip_output() can be
4358 	 * changed to deal with just connp. For read side, we
4359 	 * could have set tcp_rq to NULL but there are some cases
4360 	 * in tcp_rput_data() from early days of this code which
4361 	 * do a putnext without checking if tcp is closed. Those
4362 	 * need to be identified before both tcp_rq and tcp_wq
4363 	 * can be set to NULL and tcps_g_q can disappear forever.
4364 	 */
4365 	mutex_enter(&tcp->tcp_closelock);
4366 	/*
4367 	 * Don't change the queues in the case of a listener that has
4368 	 * eagers in its q or q0. It could surprise the eagers.
4369 	 * Instead wait for the eagers outside the squeue.
4370 	 */
4371 	if (!tcp->tcp_wait_for_eagers) {
4372 		tcp->tcp_detached = B_TRUE;
4373 		/*
4374 		 * When default queue is closing we set tcps_g_q to NULL
4375 		 * after the close is done.
4376 		 */
4377 		ASSERT(tcps->tcps_g_q != NULL);
4378 		tcp->tcp_rq = tcps->tcps_g_q;
4379 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4380 	}
4381 
4382 	/* Signal tcp_close() to finish closing. */
4383 	tcp->tcp_closed = 1;
4384 	cv_signal(&tcp->tcp_closecv);
4385 	mutex_exit(&tcp->tcp_closelock);
4386 }
4387 
4388 
4389 /*
4390  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4391  * Some stream heads get upset if they see these later on as anything but NULL.
4392  */
4393 static void
4394 tcp_close_mpp(mblk_t **mpp)
4395 {
4396 	mblk_t	*mp;
4397 
4398 	if ((mp = *mpp) != NULL) {
4399 		do {
4400 			mp->b_next = NULL;
4401 			mp->b_prev = NULL;
4402 		} while ((mp = mp->b_cont) != NULL);
4403 
4404 		mp = *mpp;
4405 		*mpp = NULL;
4406 		freemsg(mp);
4407 	}
4408 }
4409 
4410 /* Do detached close. */
4411 static void
4412 tcp_close_detached(tcp_t *tcp)
4413 {
4414 	if (tcp->tcp_fused)
4415 		tcp_unfuse(tcp);
4416 
4417 	/*
4418 	 * Clustering code serializes TCP disconnect callbacks and
4419 	 * cluster tcp list walks by blocking a TCP disconnect callback
4420 	 * if a cluster tcp list walk is in progress. This ensures
4421 	 * accurate accounting of TCPs in the cluster code even though
4422 	 * the TCP list walk itself is not atomic.
4423 	 */
4424 	tcp_closei_local(tcp);
4425 	CONN_DEC_REF(tcp->tcp_connp);
4426 }
4427 
4428 /*
4429  * Stop all TCP timers, and free the timer mblks if requested.
4430  */
4431 void
4432 tcp_timers_stop(tcp_t *tcp)
4433 {
4434 	if (tcp->tcp_timer_tid != 0) {
4435 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4436 		tcp->tcp_timer_tid = 0;
4437 	}
4438 	if (tcp->tcp_ka_tid != 0) {
4439 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4440 		tcp->tcp_ka_tid = 0;
4441 	}
4442 	if (tcp->tcp_ack_tid != 0) {
4443 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4444 		tcp->tcp_ack_tid = 0;
4445 	}
4446 	if (tcp->tcp_push_tid != 0) {
4447 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4448 		tcp->tcp_push_tid = 0;
4449 	}
4450 }
4451 
4452 /*
4453  * The tcp_t is going away. Remove it from all lists and set it
4454  * to TCPS_CLOSED. The freeing up of memory is deferred until
4455  * tcp_inactive. This is needed since a thread in tcp_rput might have
4456  * done a CONN_INC_REF on this structure before it was removed from the
4457  * hashes.
4458  */
4459 static void
4460 tcp_closei_local(tcp_t *tcp)
4461 {
4462 	ire_t 	*ire;
4463 	conn_t	*connp = tcp->tcp_connp;
4464 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4465 
4466 	if (!TCP_IS_SOCKET(tcp))
4467 		tcp_acceptor_hash_remove(tcp);
4468 
4469 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4470 	tcp->tcp_ibsegs = 0;
4471 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4472 	tcp->tcp_obsegs = 0;
4473 
4474 	/*
4475 	 * If we are an eager connection hanging off a listener that
4476 	 * hasn't formally accepted the connection yet, get off his
4477 	 * list and blow off any data that we have accumulated.
4478 	 */
4479 	if (tcp->tcp_listener != NULL) {
4480 		tcp_t	*listener = tcp->tcp_listener;
4481 		mutex_enter(&listener->tcp_eager_lock);
4482 		/*
4483 		 * tcp_tconnind_started == B_TRUE means that the
4484 		 * conn_ind has already gone to listener. At
4485 		 * this point, eager will be closed but we
4486 		 * leave it in listeners eager list so that
4487 		 * if listener decides to close without doing
4488 		 * accept, we can clean this up. In tcp_wput_accept
4489 		 * we take care of the case of accept on closed
4490 		 * eager.
4491 		 */
4492 		if (!tcp->tcp_tconnind_started) {
4493 			tcp_eager_unlink(tcp);
4494 			mutex_exit(&listener->tcp_eager_lock);
4495 			/*
4496 			 * We don't want to have any pointers to the
4497 			 * listener queue, after we have released our
4498 			 * reference on the listener
4499 			 */
4500 			ASSERT(tcps->tcps_g_q != NULL);
4501 			tcp->tcp_rq = tcps->tcps_g_q;
4502 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4503 			CONN_DEC_REF(listener->tcp_connp);
4504 		} else {
4505 			mutex_exit(&listener->tcp_eager_lock);
4506 		}
4507 	}
4508 
4509 	/* Stop all the timers */
4510 	tcp_timers_stop(tcp);
4511 
4512 	if (tcp->tcp_state == TCPS_LISTEN) {
4513 		if (tcp->tcp_ip_addr_cache) {
4514 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4515 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4516 			tcp->tcp_ip_addr_cache = NULL;
4517 		}
4518 	}
4519 	mutex_enter(&tcp->tcp_non_sq_lock);
4520 	if (tcp->tcp_flow_stopped)
4521 		tcp_clrqfull(tcp);
4522 	mutex_exit(&tcp->tcp_non_sq_lock);
4523 
4524 	tcp_bind_hash_remove(tcp);
4525 	/*
4526 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4527 	 * is trying to remove this tcp from the time wait list, we will
4528 	 * block in tcp_time_wait_remove while trying to acquire the
4529 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4530 	 * requires the ipcl_hash_remove to be ordered after the
4531 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4532 	 */
4533 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4534 		(void) tcp_time_wait_remove(tcp, NULL);
4535 	CL_INET_DISCONNECT(tcp);
4536 	ipcl_hash_remove(connp);
4537 
4538 	/*
4539 	 * Delete the cached ire in conn_ire_cache and also mark
4540 	 * the conn as CONDEMNED
4541 	 */
4542 	mutex_enter(&connp->conn_lock);
4543 	connp->conn_state_flags |= CONN_CONDEMNED;
4544 	ire = connp->conn_ire_cache;
4545 	connp->conn_ire_cache = NULL;
4546 	mutex_exit(&connp->conn_lock);
4547 	if (ire != NULL)
4548 		IRE_REFRELE_NOTR(ire);
4549 
4550 	/* Need to cleanup any pending ioctls */
4551 	ASSERT(tcp->tcp_time_wait_next == NULL);
4552 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4553 	ASSERT(tcp->tcp_time_wait_expire == 0);
4554 	tcp->tcp_state = TCPS_CLOSED;
4555 
4556 	/* Release any SSL context */
4557 	if (tcp->tcp_kssl_ent != NULL) {
4558 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4559 		tcp->tcp_kssl_ent = NULL;
4560 	}
4561 	if (tcp->tcp_kssl_ctx != NULL) {
4562 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4563 		tcp->tcp_kssl_ctx = NULL;
4564 	}
4565 	tcp->tcp_kssl_pending = B_FALSE;
4566 
4567 	tcp_ipsec_cleanup(tcp);
4568 }
4569 
4570 /*
4571  * tcp is dying (called from ipcl_conn_destroy and error cases).
4572  * Free the tcp_t in either case.
4573  */
4574 void
4575 tcp_free(tcp_t *tcp)
4576 {
4577 	mblk_t	*mp;
4578 	ip6_pkt_t	*ipp;
4579 
4580 	ASSERT(tcp != NULL);
4581 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4582 
4583 	tcp->tcp_rq = NULL;
4584 	tcp->tcp_wq = NULL;
4585 
4586 	tcp_close_mpp(&tcp->tcp_xmit_head);
4587 	tcp_close_mpp(&tcp->tcp_reass_head);
4588 	if (tcp->tcp_rcv_list != NULL) {
4589 		/* Free b_next chain */
4590 		tcp_close_mpp(&tcp->tcp_rcv_list);
4591 	}
4592 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4593 		freemsg(mp);
4594 	}
4595 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4596 		freemsg(mp);
4597 	}
4598 
4599 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4600 		freeb(tcp->tcp_fused_sigurg_mp);
4601 		tcp->tcp_fused_sigurg_mp = NULL;
4602 	}
4603 
4604 	if (tcp->tcp_sack_info != NULL) {
4605 		if (tcp->tcp_notsack_list != NULL) {
4606 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4607 		}
4608 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4609 	}
4610 
4611 	if (tcp->tcp_hopopts != NULL) {
4612 		mi_free(tcp->tcp_hopopts);
4613 		tcp->tcp_hopopts = NULL;
4614 		tcp->tcp_hopoptslen = 0;
4615 	}
4616 	ASSERT(tcp->tcp_hopoptslen == 0);
4617 	if (tcp->tcp_dstopts != NULL) {
4618 		mi_free(tcp->tcp_dstopts);
4619 		tcp->tcp_dstopts = NULL;
4620 		tcp->tcp_dstoptslen = 0;
4621 	}
4622 	ASSERT(tcp->tcp_dstoptslen == 0);
4623 	if (tcp->tcp_rtdstopts != NULL) {
4624 		mi_free(tcp->tcp_rtdstopts);
4625 		tcp->tcp_rtdstopts = NULL;
4626 		tcp->tcp_rtdstoptslen = 0;
4627 	}
4628 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4629 	if (tcp->tcp_rthdr != NULL) {
4630 		mi_free(tcp->tcp_rthdr);
4631 		tcp->tcp_rthdr = NULL;
4632 		tcp->tcp_rthdrlen = 0;
4633 	}
4634 	ASSERT(tcp->tcp_rthdrlen == 0);
4635 
4636 	ipp = &tcp->tcp_sticky_ipp;
4637 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4638 	    IPPF_RTHDR))
4639 		ip6_pkt_free(ipp);
4640 
4641 	/*
4642 	 * Free memory associated with the tcp/ip header template.
4643 	 */
4644 
4645 	if (tcp->tcp_iphc != NULL)
4646 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4647 
4648 	/*
4649 	 * Following is really a blowing away a union.
4650 	 * It happens to have exactly two members of identical size
4651 	 * the following code is enough.
4652 	 */
4653 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4654 
4655 	if (tcp->tcp_tracebuf != NULL) {
4656 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4657 		tcp->tcp_tracebuf = NULL;
4658 	}
4659 }
4660 
4661 
4662 /*
4663  * Put a connection confirmation message upstream built from the
4664  * address information within 'iph' and 'tcph'.  Report our success or failure.
4665  */
4666 static boolean_t
4667 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4668     mblk_t **defermp)
4669 {
4670 	sin_t	sin;
4671 	sin6_t	sin6;
4672 	mblk_t	*mp;
4673 	char	*optp = NULL;
4674 	int	optlen = 0;
4675 	cred_t	*cr;
4676 
4677 	if (defermp != NULL)
4678 		*defermp = NULL;
4679 
4680 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4681 		/*
4682 		 * Return in T_CONN_CON results of option negotiation through
4683 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4684 		 * negotiation, then what is received from remote end needs
4685 		 * to be taken into account but there is no such thing (yet?)
4686 		 * in our TCP/IP.
4687 		 * Note: We do not use mi_offset_param() here as
4688 		 * tcp_opts_conn_req contents do not directly come from
4689 		 * an application and are either generated in kernel or
4690 		 * from user input that was already verified.
4691 		 */
4692 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4693 		optp = (char *)(mp->b_rptr +
4694 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4695 		optlen = (int)
4696 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4697 	}
4698 
4699 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4700 		ipha_t *ipha = (ipha_t *)iphdr;
4701 
4702 		/* packet is IPv4 */
4703 		if (tcp->tcp_family == AF_INET) {
4704 			sin = sin_null;
4705 			sin.sin_addr.s_addr = ipha->ipha_src;
4706 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4707 			sin.sin_family = AF_INET;
4708 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4709 			    (int)sizeof (sin_t), optp, optlen);
4710 		} else {
4711 			sin6 = sin6_null;
4712 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4713 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4714 			sin6.sin6_family = AF_INET6;
4715 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4716 			    (int)sizeof (sin6_t), optp, optlen);
4717 
4718 		}
4719 	} else {
4720 		ip6_t	*ip6h = (ip6_t *)iphdr;
4721 
4722 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4723 		ASSERT(tcp->tcp_family == AF_INET6);
4724 		sin6 = sin6_null;
4725 		sin6.sin6_addr = ip6h->ip6_src;
4726 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4727 		sin6.sin6_family = AF_INET6;
4728 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4729 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4730 		    (int)sizeof (sin6_t), optp, optlen);
4731 	}
4732 
4733 	if (!mp)
4734 		return (B_FALSE);
4735 
4736 	if ((cr = DB_CRED(idmp)) != NULL) {
4737 		mblk_setcred(mp, cr);
4738 		DB_CPID(mp) = DB_CPID(idmp);
4739 	}
4740 
4741 	if (defermp == NULL)
4742 		putnext(tcp->tcp_rq, mp);
4743 	else
4744 		*defermp = mp;
4745 
4746 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4747 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4748 	return (B_TRUE);
4749 }
4750 
4751 /*
4752  * Defense for the SYN attack -
4753  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4754  *    one from the list of droppable eagers. This list is a subset of q0.
4755  *    see comments before the definition of MAKE_DROPPABLE().
4756  * 2. Don't drop a SYN request before its first timeout. This gives every
4757  *    request at least til the first timeout to complete its 3-way handshake.
4758  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4759  *    requests currently on the queue that has timed out. This will be used
4760  *    as an indicator of whether an attack is under way, so that appropriate
4761  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4762  *    either when eager goes into ESTABLISHED, or gets freed up.)
4763  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4764  *    # of timeout drops back to <= q0len/32 => SYN alert off
4765  */
4766 static boolean_t
4767 tcp_drop_q0(tcp_t *tcp)
4768 {
4769 	tcp_t	*eager;
4770 	mblk_t	*mp;
4771 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4772 
4773 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4774 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4775 
4776 	/* Pick oldest eager from the list of droppable eagers */
4777 	eager = tcp->tcp_eager_prev_drop_q0;
4778 
4779 	/* If list is empty. return B_FALSE */
4780 	if (eager == tcp) {
4781 		return (B_FALSE);
4782 	}
4783 
4784 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4785 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4786 		return (B_FALSE);
4787 
4788 	/*
4789 	 * Take this eager out from the list of droppable eagers since we are
4790 	 * going to drop it.
4791 	 */
4792 	MAKE_UNDROPPABLE(eager);
4793 
4794 	if (tcp->tcp_debug) {
4795 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4796 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4797 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4798 		    tcp->tcp_conn_req_cnt_q0,
4799 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4800 	}
4801 
4802 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4803 
4804 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4805 	CONN_INC_REF(eager->tcp_connp);
4806 
4807 	/* Mark the IRE created for this SYN request temporary */
4808 	tcp_ip_ire_mark_advice(eager);
4809 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4810 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4811 
4812 	return (B_TRUE);
4813 }
4814 
4815 int
4816 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4817     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4818 {
4819 	tcp_t 		*ltcp = lconnp->conn_tcp;
4820 	tcp_t		*tcp = connp->conn_tcp;
4821 	mblk_t		*tpi_mp;
4822 	ipha_t		*ipha;
4823 	ip6_t		*ip6h;
4824 	sin6_t 		sin6;
4825 	in6_addr_t 	v6dst;
4826 	int		err;
4827 	int		ifindex = 0;
4828 	cred_t		*cr;
4829 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4830 
4831 	if (ipvers == IPV4_VERSION) {
4832 		ipha = (ipha_t *)mp->b_rptr;
4833 
4834 		connp->conn_send = ip_output;
4835 		connp->conn_recv = tcp_input;
4836 
4837 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4838 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4839 
4840 		sin6 = sin6_null;
4841 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4842 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4843 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4844 		sin6.sin6_family = AF_INET6;
4845 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4846 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4847 		if (tcp->tcp_recvdstaddr) {
4848 			sin6_t	sin6d;
4849 
4850 			sin6d = sin6_null;
4851 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4852 			    &sin6d.sin6_addr);
4853 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4854 			sin6d.sin6_family = AF_INET;
4855 			tpi_mp = mi_tpi_extconn_ind(NULL,
4856 			    (char *)&sin6d, sizeof (sin6_t),
4857 			    (char *)&tcp,
4858 			    (t_scalar_t)sizeof (intptr_t),
4859 			    (char *)&sin6d, sizeof (sin6_t),
4860 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4861 		} else {
4862 			tpi_mp = mi_tpi_conn_ind(NULL,
4863 			    (char *)&sin6, sizeof (sin6_t),
4864 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4865 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4866 		}
4867 	} else {
4868 		ip6h = (ip6_t *)mp->b_rptr;
4869 
4870 		connp->conn_send = ip_output_v6;
4871 		connp->conn_recv = tcp_input;
4872 
4873 		connp->conn_srcv6 = ip6h->ip6_dst;
4874 		connp->conn_remv6 = ip6h->ip6_src;
4875 
4876 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4877 		ifindex = (int)DB_CKSUMSTUFF(mp);
4878 		DB_CKSUMSTUFF(mp) = 0;
4879 
4880 		sin6 = sin6_null;
4881 		sin6.sin6_addr = ip6h->ip6_src;
4882 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4883 		sin6.sin6_family = AF_INET6;
4884 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4885 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4886 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4887 
4888 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4889 			/* Pass up the scope_id of remote addr */
4890 			sin6.sin6_scope_id = ifindex;
4891 		} else {
4892 			sin6.sin6_scope_id = 0;
4893 		}
4894 		if (tcp->tcp_recvdstaddr) {
4895 			sin6_t	sin6d;
4896 
4897 			sin6d = sin6_null;
4898 			sin6.sin6_addr = ip6h->ip6_dst;
4899 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4900 			sin6d.sin6_family = AF_INET;
4901 			tpi_mp = mi_tpi_extconn_ind(NULL,
4902 			    (char *)&sin6d, sizeof (sin6_t),
4903 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4904 			    (char *)&sin6d, sizeof (sin6_t),
4905 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4906 		} else {
4907 			tpi_mp = mi_tpi_conn_ind(NULL,
4908 			    (char *)&sin6, sizeof (sin6_t),
4909 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4910 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4911 		}
4912 	}
4913 
4914 	if (tpi_mp == NULL)
4915 		return (ENOMEM);
4916 
4917 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4918 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4919 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4920 	connp->conn_fully_bound = B_FALSE;
4921 
4922 	if (tcps->tcps_trace)
4923 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4924 
4925 	/* Inherit information from the "parent" */
4926 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4927 	tcp->tcp_family = ltcp->tcp_family;
4928 	tcp->tcp_wq = ltcp->tcp_wq;
4929 	tcp->tcp_rq = ltcp->tcp_rq;
4930 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4931 	tcp->tcp_detached = B_TRUE;
4932 	if ((err = tcp_init_values(tcp)) != 0) {
4933 		freemsg(tpi_mp);
4934 		return (err);
4935 	}
4936 
4937 	if (ipvers == IPV4_VERSION) {
4938 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4939 			freemsg(tpi_mp);
4940 			return (err);
4941 		}
4942 		ASSERT(tcp->tcp_ipha != NULL);
4943 	} else {
4944 		/* ifindex must be already set */
4945 		ASSERT(ifindex != 0);
4946 
4947 		if (ltcp->tcp_bound_if != 0) {
4948 			/*
4949 			 * Set newtcp's bound_if equal to
4950 			 * listener's value. If ifindex is
4951 			 * not the same as ltcp->tcp_bound_if,
4952 			 * it must be a packet for the ipmp group
4953 			 * of interfaces
4954 			 */
4955 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4956 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4957 			tcp->tcp_bound_if = ifindex;
4958 		}
4959 
4960 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4961 		tcp->tcp_recvifindex = 0;
4962 		tcp->tcp_recvhops = 0xffffffffU;
4963 		ASSERT(tcp->tcp_ip6h != NULL);
4964 	}
4965 
4966 	tcp->tcp_lport = ltcp->tcp_lport;
4967 
4968 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4969 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4970 			/*
4971 			 * Listener had options of some sort; eager inherits.
4972 			 * Free up the eager template and allocate one
4973 			 * of the right size.
4974 			 */
4975 			if (tcp->tcp_hdr_grown) {
4976 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4977 			} else {
4978 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4979 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4980 			}
4981 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4982 			    KM_NOSLEEP);
4983 			if (tcp->tcp_iphc == NULL) {
4984 				tcp->tcp_iphc_len = 0;
4985 				freemsg(tpi_mp);
4986 				return (ENOMEM);
4987 			}
4988 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4989 			tcp->tcp_hdr_grown = B_TRUE;
4990 		}
4991 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4992 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4993 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4994 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4995 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4996 
4997 		/*
4998 		 * Copy the IP+TCP header template from listener to eager
4999 		 */
5000 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5001 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5002 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5003 			    IPPROTO_RAW) {
5004 				tcp->tcp_ip6h =
5005 				    (ip6_t *)(tcp->tcp_iphc +
5006 				    sizeof (ip6i_t));
5007 			} else {
5008 				tcp->tcp_ip6h =
5009 				    (ip6_t *)(tcp->tcp_iphc);
5010 			}
5011 			tcp->tcp_ipha = NULL;
5012 		} else {
5013 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5014 			tcp->tcp_ip6h = NULL;
5015 		}
5016 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5017 		    tcp->tcp_ip_hdr_len);
5018 	} else {
5019 		/*
5020 		 * only valid case when ipversion of listener and
5021 		 * eager differ is when listener is IPv6 and
5022 		 * eager is IPv4.
5023 		 * Eager header template has been initialized to the
5024 		 * maximum v4 header sizes, which includes space for
5025 		 * TCP and IP options.
5026 		 */
5027 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5028 		    (tcp->tcp_ipversion == IPV4_VERSION));
5029 		ASSERT(tcp->tcp_iphc_len >=
5030 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5031 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5032 		/* copy IP header fields individually */
5033 		tcp->tcp_ipha->ipha_ttl =
5034 		    ltcp->tcp_ip6h->ip6_hops;
5035 		bcopy(ltcp->tcp_tcph->th_lport,
5036 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5037 	}
5038 
5039 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5040 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5041 	    sizeof (in_port_t));
5042 
5043 	if (ltcp->tcp_lport == 0) {
5044 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5045 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5046 		    sizeof (in_port_t));
5047 	}
5048 
5049 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5050 		ASSERT(ipha != NULL);
5051 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5052 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5053 
5054 		/* Source routing option copyover (reverse it) */
5055 		if (tcps->tcps_rev_src_routes)
5056 			tcp_opt_reverse(tcp, ipha);
5057 	} else {
5058 		ASSERT(ip6h != NULL);
5059 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5060 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5061 	}
5062 
5063 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5064 	ASSERT(!tcp->tcp_tconnind_started);
5065 	/*
5066 	 * If the SYN contains a credential, it's a loopback packet; attach
5067 	 * the credential to the TPI message.
5068 	 */
5069 	if ((cr = DB_CRED(idmp)) != NULL) {
5070 		mblk_setcred(tpi_mp, cr);
5071 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5072 	}
5073 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5074 
5075 	/* Inherit the listener's SSL protection state */
5076 
5077 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5078 		kssl_hold_ent(tcp->tcp_kssl_ent);
5079 		tcp->tcp_kssl_pending = B_TRUE;
5080 	}
5081 
5082 	return (0);
5083 }
5084 
5085 
5086 int
5087 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5088     tcph_t *tcph, mblk_t *idmp)
5089 {
5090 	tcp_t 		*ltcp = lconnp->conn_tcp;
5091 	tcp_t		*tcp = connp->conn_tcp;
5092 	sin_t		sin;
5093 	mblk_t		*tpi_mp = NULL;
5094 	int		err;
5095 	cred_t		*cr;
5096 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5097 
5098 	sin = sin_null;
5099 	sin.sin_addr.s_addr = ipha->ipha_src;
5100 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5101 	sin.sin_family = AF_INET;
5102 	if (ltcp->tcp_recvdstaddr) {
5103 		sin_t	sind;
5104 
5105 		sind = sin_null;
5106 		sind.sin_addr.s_addr = ipha->ipha_dst;
5107 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5108 		sind.sin_family = AF_INET;
5109 		tpi_mp = mi_tpi_extconn_ind(NULL,
5110 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5111 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5112 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5113 	} else {
5114 		tpi_mp = mi_tpi_conn_ind(NULL,
5115 		    (char *)&sin, sizeof (sin_t),
5116 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5117 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5118 	}
5119 
5120 	if (tpi_mp == NULL) {
5121 		return (ENOMEM);
5122 	}
5123 
5124 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5125 	connp->conn_send = ip_output;
5126 	connp->conn_recv = tcp_input;
5127 	connp->conn_fully_bound = B_FALSE;
5128 
5129 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5130 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5131 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5132 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5133 
5134 	if (tcps->tcps_trace) {
5135 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5136 	}
5137 
5138 	/* Inherit information from the "parent" */
5139 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5140 	tcp->tcp_family = ltcp->tcp_family;
5141 	tcp->tcp_wq = ltcp->tcp_wq;
5142 	tcp->tcp_rq = ltcp->tcp_rq;
5143 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5144 	tcp->tcp_detached = B_TRUE;
5145 	if ((err = tcp_init_values(tcp)) != 0) {
5146 		freemsg(tpi_mp);
5147 		return (err);
5148 	}
5149 
5150 	/*
5151 	 * Let's make sure that eager tcp template has enough space to
5152 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5153 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5154 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5155 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5156 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5157 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5158 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5159 	 */
5160 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5161 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5162 
5163 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5164 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5165 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5166 	tcp->tcp_ttl = ltcp->tcp_ttl;
5167 	tcp->tcp_tos = ltcp->tcp_tos;
5168 
5169 	/* Copy the IP+TCP header template from listener to eager */
5170 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5171 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5172 	tcp->tcp_ip6h = NULL;
5173 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5174 	    tcp->tcp_ip_hdr_len);
5175 
5176 	/* Initialize the IP addresses and Ports */
5177 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5178 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5179 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5180 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5181 
5182 	/* Source routing option copyover (reverse it) */
5183 	if (tcps->tcps_rev_src_routes)
5184 		tcp_opt_reverse(tcp, ipha);
5185 
5186 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5187 	ASSERT(!tcp->tcp_tconnind_started);
5188 
5189 	/*
5190 	 * If the SYN contains a credential, it's a loopback packet; attach
5191 	 * the credential to the TPI message.
5192 	 */
5193 	if ((cr = DB_CRED(idmp)) != NULL) {
5194 		mblk_setcred(tpi_mp, cr);
5195 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5196 	}
5197 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5198 
5199 	/* Inherit the listener's SSL protection state */
5200 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5201 		kssl_hold_ent(tcp->tcp_kssl_ent);
5202 		tcp->tcp_kssl_pending = B_TRUE;
5203 	}
5204 
5205 	return (0);
5206 }
5207 
5208 /*
5209  * sets up conn for ipsec.
5210  * if the first mblk is M_CTL it is consumed and mpp is updated.
5211  * in case of error mpp is freed.
5212  */
5213 conn_t *
5214 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5215 {
5216 	conn_t 		*connp = tcp->tcp_connp;
5217 	conn_t 		*econnp;
5218 	squeue_t 	*new_sqp;
5219 	mblk_t 		*first_mp = *mpp;
5220 	mblk_t		*mp = *mpp;
5221 	boolean_t	mctl_present = B_FALSE;
5222 	uint_t		ipvers;
5223 
5224 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5225 	if (econnp == NULL) {
5226 		freemsg(first_mp);
5227 		return (NULL);
5228 	}
5229 	if (DB_TYPE(mp) == M_CTL) {
5230 		if (mp->b_cont == NULL ||
5231 		    mp->b_cont->b_datap->db_type != M_DATA) {
5232 			freemsg(first_mp);
5233 			return (NULL);
5234 		}
5235 		mp = mp->b_cont;
5236 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5237 			freemsg(first_mp);
5238 			return (NULL);
5239 		}
5240 
5241 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5242 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5243 		mctl_present = B_TRUE;
5244 	} else {
5245 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5246 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5247 	}
5248 
5249 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5250 	DB_CKSUMSTART(mp) = 0;
5251 
5252 	ASSERT(OK_32PTR(mp->b_rptr));
5253 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5254 	if (ipvers == IPV4_VERSION) {
5255 		uint16_t  	*up;
5256 		uint32_t	ports;
5257 		ipha_t		*ipha;
5258 
5259 		ipha = (ipha_t *)mp->b_rptr;
5260 		up = (uint16_t *)((uchar_t *)ipha +
5261 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5262 		ports = *(uint32_t *)up;
5263 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5264 		    ipha->ipha_dst, ipha->ipha_src, ports);
5265 	} else {
5266 		uint16_t  	*up;
5267 		uint32_t	ports;
5268 		uint16_t	ip_hdr_len;
5269 		uint8_t		*nexthdrp;
5270 		ip6_t 		*ip6h;
5271 		tcph_t		*tcph;
5272 
5273 		ip6h = (ip6_t *)mp->b_rptr;
5274 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5275 			ip_hdr_len = IPV6_HDR_LEN;
5276 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5277 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5278 			CONN_DEC_REF(econnp);
5279 			freemsg(first_mp);
5280 			return (NULL);
5281 		}
5282 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5283 		up = (uint16_t *)tcph->th_lport;
5284 		ports = *(uint32_t *)up;
5285 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5286 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5287 	}
5288 
5289 	/*
5290 	 * The caller already ensured that there is a sqp present.
5291 	 */
5292 	econnp->conn_sqp = new_sqp;
5293 
5294 	if (connp->conn_policy != NULL) {
5295 		ipsec_in_t *ii;
5296 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5297 		ASSERT(ii->ipsec_in_policy == NULL);
5298 		IPPH_REFHOLD(connp->conn_policy);
5299 		ii->ipsec_in_policy = connp->conn_policy;
5300 
5301 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5302 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5303 			CONN_DEC_REF(econnp);
5304 			freemsg(first_mp);
5305 			return (NULL);
5306 		}
5307 	}
5308 
5309 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5310 		CONN_DEC_REF(econnp);
5311 		freemsg(first_mp);
5312 		return (NULL);
5313 	}
5314 
5315 	/*
5316 	 * If we know we have some policy, pass the "IPSEC"
5317 	 * options size TCP uses this adjust the MSS.
5318 	 */
5319 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5320 	if (mctl_present) {
5321 		freeb(first_mp);
5322 		*mpp = mp;
5323 	}
5324 
5325 	return (econnp);
5326 }
5327 
5328 /*
5329  * tcp_get_conn/tcp_free_conn
5330  *
5331  * tcp_get_conn is used to get a clean tcp connection structure.
5332  * It tries to reuse the connections put on the freelist by the
5333  * time_wait_collector failing which it goes to kmem_cache. This
5334  * way has two benefits compared to just allocating from and
5335  * freeing to kmem_cache.
5336  * 1) The time_wait_collector can free (which includes the cleanup)
5337  * outside the squeue. So when the interrupt comes, we have a clean
5338  * connection sitting in the freelist. Obviously, this buys us
5339  * performance.
5340  *
5341  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5342  * has multiple disadvantages - tying up the squeue during alloc, and the
5343  * fact that IPSec policy initialization has to happen here which
5344  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5345  * But allocating the conn/tcp in IP land is also not the best since
5346  * we can't check the 'q' and 'q0' which are protected by squeue and
5347  * blindly allocate memory which might have to be freed here if we are
5348  * not allowed to accept the connection. By using the freelist and
5349  * putting the conn/tcp back in freelist, we don't pay a penalty for
5350  * allocating memory without checking 'q/q0' and freeing it if we can't
5351  * accept the connection.
5352  *
5353  * Care should be taken to put the conn back in the same squeue's freelist
5354  * from which it was allocated. Best results are obtained if conn is
5355  * allocated from listener's squeue and freed to the same. Time wait
5356  * collector will free up the freelist is the connection ends up sitting
5357  * there for too long.
5358  */
5359 void *
5360 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5361 {
5362 	tcp_t			*tcp = NULL;
5363 	conn_t			*connp = NULL;
5364 	squeue_t		*sqp = (squeue_t *)arg;
5365 	tcp_squeue_priv_t 	*tcp_time_wait;
5366 	netstack_t		*ns;
5367 
5368 	tcp_time_wait =
5369 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5370 
5371 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5372 	tcp = tcp_time_wait->tcp_free_list;
5373 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5374 	if (tcp != NULL) {
5375 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5376 		tcp_time_wait->tcp_free_list_cnt--;
5377 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5378 		tcp->tcp_time_wait_next = NULL;
5379 		connp = tcp->tcp_connp;
5380 		connp->conn_flags |= IPCL_REUSED;
5381 
5382 		ASSERT(tcp->tcp_tcps == NULL);
5383 		ASSERT(connp->conn_netstack == NULL);
5384 		ns = tcps->tcps_netstack;
5385 		netstack_hold(ns);
5386 		connp->conn_netstack = ns;
5387 		tcp->tcp_tcps = tcps;
5388 		TCPS_REFHOLD(tcps);
5389 		ipcl_globalhash_insert(connp);
5390 		return ((void *)connp);
5391 	}
5392 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5393 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5394 	    tcps->tcps_netstack)) == NULL)
5395 		return (NULL);
5396 	tcp = connp->conn_tcp;
5397 	tcp->tcp_tcps = tcps;
5398 	TCPS_REFHOLD(tcps);
5399 	return ((void *)connp);
5400 }
5401 
5402 /*
5403  * Update the cached label for the given tcp_t.  This should be called once per
5404  * connection, and before any packets are sent or tcp_process_options is
5405  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5406  */
5407 static boolean_t
5408 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5409 {
5410 	conn_t *connp = tcp->tcp_connp;
5411 
5412 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5413 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5414 		int added;
5415 
5416 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5417 		    connp->conn_mac_exempt,
5418 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5419 			return (B_FALSE);
5420 
5421 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5422 		if (added == -1)
5423 			return (B_FALSE);
5424 		tcp->tcp_hdr_len += added;
5425 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5426 		tcp->tcp_ip_hdr_len += added;
5427 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5428 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5429 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5430 			    tcp->tcp_hdr_len);
5431 			if (added == -1)
5432 				return (B_FALSE);
5433 			tcp->tcp_hdr_len += added;
5434 			tcp->tcp_tcph = (tcph_t *)
5435 			    ((uchar_t *)tcp->tcp_tcph + added);
5436 			tcp->tcp_ip_hdr_len += added;
5437 		}
5438 	} else {
5439 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5440 
5441 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5442 		    connp->conn_mac_exempt,
5443 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5444 			return (B_FALSE);
5445 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5446 		    &tcp->tcp_label_len, optbuf) != 0)
5447 			return (B_FALSE);
5448 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5449 			return (B_FALSE);
5450 	}
5451 
5452 	connp->conn_ulp_labeled = 1;
5453 
5454 	return (B_TRUE);
5455 }
5456 
5457 /* BEGIN CSTYLED */
5458 /*
5459  *
5460  * The sockfs ACCEPT path:
5461  * =======================
5462  *
5463  * The eager is now established in its own perimeter as soon as SYN is
5464  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5465  * completes the accept processing on the acceptor STREAM. The sending
5466  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5467  * listener but a TLI/XTI listener completes the accept processing
5468  * on the listener perimeter.
5469  *
5470  * Common control flow for 3 way handshake:
5471  * ----------------------------------------
5472  *
5473  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5474  *					-> tcp_conn_request()
5475  *
5476  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5477  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5478  *
5479  * Sockfs ACCEPT Path:
5480  * -------------------
5481  *
5482  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5483  * as STREAM entry point)
5484  *
5485  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5486  *
5487  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5488  * association (we are not behind eager's squeue but sockfs is protecting us
5489  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5490  * is changed to point at tcp_wput().
5491  *
5492  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5493  * listener (done on listener's perimeter).
5494  *
5495  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5496  * accept.
5497  *
5498  * TLI/XTI client ACCEPT path:
5499  * ---------------------------
5500  *
5501  * soaccept() sends T_CONN_RES on the listener STREAM.
5502  *
5503  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5504  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5505  *
5506  * Locks:
5507  * ======
5508  *
5509  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5510  * and listeners->tcp_eager_next_q.
5511  *
5512  * Referencing:
5513  * ============
5514  *
5515  * 1) We start out in tcp_conn_request by eager placing a ref on
5516  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5517  *
5518  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5519  * doing so we place a ref on the eager. This ref is finally dropped at the
5520  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5521  * reference is dropped by the squeue framework.
5522  *
5523  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5524  *
5525  * The reference must be released by the same entity that added the reference
5526  * In the above scheme, the eager is the entity that adds and releases the
5527  * references. Note that tcp_accept_finish executes in the squeue of the eager
5528  * (albeit after it is attached to the acceptor stream). Though 1. executes
5529  * in the listener's squeue, the eager is nascent at this point and the
5530  * reference can be considered to have been added on behalf of the eager.
5531  *
5532  * Eager getting a Reset or listener closing:
5533  * ==========================================
5534  *
5535  * Once the listener and eager are linked, the listener never does the unlink.
5536  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5537  * a message on all eager perimeter. The eager then does the unlink, clears
5538  * any pointers to the listener's queue and drops the reference to the
5539  * listener. The listener waits in tcp_close outside the squeue until its
5540  * refcount has dropped to 1. This ensures that the listener has waited for
5541  * all eagers to clear their association with the listener.
5542  *
5543  * Similarly, if eager decides to go away, it can unlink itself and close.
5544  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5545  * the reference to eager is still valid because of the extra ref we put
5546  * in tcp_send_conn_ind.
5547  *
5548  * Listener can always locate the eager under the protection
5549  * of the listener->tcp_eager_lock, and then do a refhold
5550  * on the eager during the accept processing.
5551  *
5552  * The acceptor stream accesses the eager in the accept processing
5553  * based on the ref placed on eager before sending T_conn_ind.
5554  * The only entity that can negate this refhold is a listener close
5555  * which is mutually exclusive with an active acceptor stream.
5556  *
5557  * Eager's reference on the listener
5558  * ===================================
5559  *
5560  * If the accept happens (even on a closed eager) the eager drops its
5561  * reference on the listener at the start of tcp_accept_finish. If the
5562  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5563  * the reference is dropped in tcp_closei_local. If the listener closes,
5564  * the reference is dropped in tcp_eager_kill. In all cases the reference
5565  * is dropped while executing in the eager's context (squeue).
5566  */
5567 /* END CSTYLED */
5568 
5569 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5570 
5571 /*
5572  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5573  * tcp_rput_data will not see any SYN packets.
5574  */
5575 /* ARGSUSED */
5576 void
5577 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5578 {
5579 	tcph_t		*tcph;
5580 	uint32_t	seg_seq;
5581 	tcp_t		*eager;
5582 	uint_t		ipvers;
5583 	ipha_t		*ipha;
5584 	ip6_t		*ip6h;
5585 	int		err;
5586 	conn_t		*econnp = NULL;
5587 	squeue_t	*new_sqp;
5588 	mblk_t		*mp1;
5589 	uint_t 		ip_hdr_len;
5590 	conn_t		*connp = (conn_t *)arg;
5591 	tcp_t		*tcp = connp->conn_tcp;
5592 	cred_t		*credp;
5593 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5594 	ip_stack_t	*ipst;
5595 
5596 	if (tcp->tcp_state != TCPS_LISTEN)
5597 		goto error2;
5598 
5599 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5600 
5601 	mutex_enter(&tcp->tcp_eager_lock);
5602 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5603 		mutex_exit(&tcp->tcp_eager_lock);
5604 		TCP_STAT(tcps, tcp_listendrop);
5605 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5606 		if (tcp->tcp_debug) {
5607 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5608 			    "tcp_conn_request: listen backlog (max=%d) "
5609 			    "overflow (%d pending) on %s",
5610 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5611 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5612 		}
5613 		goto error2;
5614 	}
5615 
5616 	if (tcp->tcp_conn_req_cnt_q0 >=
5617 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5618 		/*
5619 		 * Q0 is full. Drop a pending half-open req from the queue
5620 		 * to make room for the new SYN req. Also mark the time we
5621 		 * drop a SYN.
5622 		 *
5623 		 * A more aggressive defense against SYN attack will
5624 		 * be to set the "tcp_syn_defense" flag now.
5625 		 */
5626 		TCP_STAT(tcps, tcp_listendropq0);
5627 		tcp->tcp_last_rcv_lbolt = lbolt64;
5628 		if (!tcp_drop_q0(tcp)) {
5629 			mutex_exit(&tcp->tcp_eager_lock);
5630 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5631 			if (tcp->tcp_debug) {
5632 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5633 				    "tcp_conn_request: listen half-open queue "
5634 				    "(max=%d) full (%d pending) on %s",
5635 				    tcps->tcps_conn_req_max_q0,
5636 				    tcp->tcp_conn_req_cnt_q0,
5637 				    tcp_display(tcp, NULL,
5638 				    DISP_PORT_ONLY));
5639 			}
5640 			goto error2;
5641 		}
5642 	}
5643 	mutex_exit(&tcp->tcp_eager_lock);
5644 
5645 	/*
5646 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5647 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5648 	 * link local address.  If IPSec is enabled, db_struioflag has
5649 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5650 	 * otherwise an error case if neither of them is set.
5651 	 */
5652 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5653 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5654 		DB_CKSUMSTART(mp) = 0;
5655 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5656 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5657 		if (econnp == NULL)
5658 			goto error2;
5659 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5660 		econnp->conn_sqp = new_sqp;
5661 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5662 		/*
5663 		 * mp is updated in tcp_get_ipsec_conn().
5664 		 */
5665 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5666 		if (econnp == NULL) {
5667 			/*
5668 			 * mp freed by tcp_get_ipsec_conn.
5669 			 */
5670 			return;
5671 		}
5672 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5673 	} else {
5674 		goto error2;
5675 	}
5676 
5677 	ASSERT(DB_TYPE(mp) == M_DATA);
5678 
5679 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5680 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5681 	ASSERT(OK_32PTR(mp->b_rptr));
5682 	if (ipvers == IPV4_VERSION) {
5683 		ipha = (ipha_t *)mp->b_rptr;
5684 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5685 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5686 	} else {
5687 		ip6h = (ip6_t *)mp->b_rptr;
5688 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5689 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5690 	}
5691 
5692 	if (tcp->tcp_family == AF_INET) {
5693 		ASSERT(ipvers == IPV4_VERSION);
5694 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5695 	} else {
5696 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5697 	}
5698 
5699 	if (err)
5700 		goto error3;
5701 
5702 	eager = econnp->conn_tcp;
5703 
5704 	/* Inherit various TCP parameters from the listener */
5705 	eager->tcp_naglim = tcp->tcp_naglim;
5706 	eager->tcp_first_timer_threshold =
5707 	    tcp->tcp_first_timer_threshold;
5708 	eager->tcp_second_timer_threshold =
5709 	    tcp->tcp_second_timer_threshold;
5710 
5711 	eager->tcp_first_ctimer_threshold =
5712 	    tcp->tcp_first_ctimer_threshold;
5713 	eager->tcp_second_ctimer_threshold =
5714 	    tcp->tcp_second_ctimer_threshold;
5715 
5716 	/*
5717 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5718 	 * If it does not, the eager's receive window will be set to the
5719 	 * listener's receive window later in this function.
5720 	 */
5721 	eager->tcp_rwnd = 0;
5722 
5723 	/*
5724 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5725 	 * calling tcp_process_options() where tcp_mss_set() is called
5726 	 * to set the initial cwnd.
5727 	 */
5728 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5729 
5730 	/*
5731 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5732 	 * zone id before the accept is completed in tcp_wput_accept().
5733 	 */
5734 	econnp->conn_zoneid = connp->conn_zoneid;
5735 	econnp->conn_allzones = connp->conn_allzones;
5736 
5737 	/* Copy nexthop information from listener to eager */
5738 	if (connp->conn_nexthop_set) {
5739 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5740 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5741 	}
5742 
5743 	/*
5744 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5745 	 * eager is accepted
5746 	 */
5747 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5748 	crhold(credp);
5749 
5750 	/*
5751 	 * If the caller has the process-wide flag set, then default to MAC
5752 	 * exempt mode.  This allows read-down to unlabeled hosts.
5753 	 */
5754 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5755 		econnp->conn_mac_exempt = B_TRUE;
5756 
5757 	if (is_system_labeled()) {
5758 		cred_t *cr;
5759 
5760 		if (connp->conn_mlp_type != mlptSingle) {
5761 			cr = econnp->conn_peercred = DB_CRED(mp);
5762 			if (cr != NULL)
5763 				crhold(cr);
5764 			else
5765 				cr = econnp->conn_cred;
5766 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5767 			    econnp, cred_t *, cr)
5768 		} else {
5769 			cr = econnp->conn_cred;
5770 			DTRACE_PROBE2(syn_accept, conn_t *,
5771 			    econnp, cred_t *, cr)
5772 		}
5773 
5774 		if (!tcp_update_label(eager, cr)) {
5775 			DTRACE_PROBE3(
5776 			    tx__ip__log__error__connrequest__tcp,
5777 			    char *, "eager connp(1) label on SYN mp(2) failed",
5778 			    conn_t *, econnp, mblk_t *, mp);
5779 			goto error3;
5780 		}
5781 	}
5782 
5783 	eager->tcp_hard_binding = B_TRUE;
5784 
5785 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5786 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5787 
5788 	CL_INET_CONNECT(eager);
5789 
5790 	/*
5791 	 * No need to check for multicast destination since ip will only pass
5792 	 * up multicasts to those that have expressed interest
5793 	 * TODO: what about rejecting broadcasts?
5794 	 * Also check that source is not a multicast or broadcast address.
5795 	 */
5796 	eager->tcp_state = TCPS_SYN_RCVD;
5797 
5798 
5799 	/*
5800 	 * There should be no ire in the mp as we are being called after
5801 	 * receiving the SYN.
5802 	 */
5803 	ASSERT(tcp_ire_mp(mp) == NULL);
5804 
5805 	/*
5806 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5807 	 */
5808 
5809 	if (tcp_adapt_ire(eager, NULL) == 0) {
5810 		/* Undo the bind_hash_insert */
5811 		tcp_bind_hash_remove(eager);
5812 		goto error3;
5813 	}
5814 
5815 	/* Process all TCP options. */
5816 	tcp_process_options(eager, tcph);
5817 
5818 	/* Is the other end ECN capable? */
5819 	if (tcps->tcps_ecn_permitted >= 1 &&
5820 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5821 		eager->tcp_ecn_ok = B_TRUE;
5822 	}
5823 
5824 	/*
5825 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5826 	 * window size changed via SO_RCVBUF option.  First round up the
5827 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5828 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5829 	 * setting.
5830 	 *
5831 	 * Note if there is a rpipe metric associated with the remote host,
5832 	 * we should not inherit receive window size from listener.
5833 	 */
5834 	eager->tcp_rwnd = MSS_ROUNDUP(
5835 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5836 	    eager->tcp_rwnd), eager->tcp_mss);
5837 	if (eager->tcp_snd_ws_ok)
5838 		tcp_set_ws_value(eager);
5839 	/*
5840 	 * Note that this is the only place tcp_rwnd_set() is called for
5841 	 * accepting a connection.  We need to call it here instead of
5842 	 * after the 3-way handshake because we need to tell the other
5843 	 * side our rwnd in the SYN-ACK segment.
5844 	 */
5845 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5846 
5847 	/*
5848 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5849 	 * via soaccept()->soinheritoptions() which essentially applies
5850 	 * all the listener options to the new STREAM. The options that we
5851 	 * need to take care of are:
5852 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5853 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5854 	 * SO_SNDBUF, SO_RCVBUF.
5855 	 *
5856 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5857 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5858 	 *		tcp_maxpsz_set() gets called later from
5859 	 *		tcp_accept_finish(), the option takes effect.
5860 	 *
5861 	 */
5862 	/* Set the TCP options */
5863 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5864 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5865 	eager->tcp_oobinline = tcp->tcp_oobinline;
5866 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5867 	eager->tcp_broadcast = tcp->tcp_broadcast;
5868 	eager->tcp_useloopback = tcp->tcp_useloopback;
5869 	eager->tcp_dontroute = tcp->tcp_dontroute;
5870 	eager->tcp_linger = tcp->tcp_linger;
5871 	eager->tcp_lingertime = tcp->tcp_lingertime;
5872 	if (tcp->tcp_ka_enabled)
5873 		eager->tcp_ka_enabled = 1;
5874 
5875 	/* Set the IP options */
5876 	econnp->conn_broadcast = connp->conn_broadcast;
5877 	econnp->conn_loopback = connp->conn_loopback;
5878 	econnp->conn_dontroute = connp->conn_dontroute;
5879 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5880 
5881 	/* Put a ref on the listener for the eager. */
5882 	CONN_INC_REF(connp);
5883 	mutex_enter(&tcp->tcp_eager_lock);
5884 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5885 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5886 	tcp->tcp_eager_next_q0 = eager;
5887 	eager->tcp_eager_prev_q0 = tcp;
5888 
5889 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5890 	eager->tcp_listener = tcp;
5891 	eager->tcp_saved_listener = tcp;
5892 
5893 	/*
5894 	 * Tag this detached tcp vector for later retrieval
5895 	 * by our listener client in tcp_accept().
5896 	 */
5897 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5898 	tcp->tcp_conn_req_cnt_q0++;
5899 	if (++tcp->tcp_conn_req_seqnum == -1) {
5900 		/*
5901 		 * -1 is "special" and defined in TPI as something
5902 		 * that should never be used in T_CONN_IND
5903 		 */
5904 		++tcp->tcp_conn_req_seqnum;
5905 	}
5906 	mutex_exit(&tcp->tcp_eager_lock);
5907 
5908 	if (tcp->tcp_syn_defense) {
5909 		/* Don't drop the SYN that comes from a good IP source */
5910 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5911 		if (addr_cache != NULL && eager->tcp_remote ==
5912 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5913 			eager->tcp_dontdrop = B_TRUE;
5914 		}
5915 	}
5916 
5917 	/*
5918 	 * We need to insert the eager in its own perimeter but as soon
5919 	 * as we do that, we expose the eager to the classifier and
5920 	 * should not touch any field outside the eager's perimeter.
5921 	 * So do all the work necessary before inserting the eager
5922 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5923 	 * will succeed but undo everything if it fails.
5924 	 */
5925 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5926 	eager->tcp_irs = seg_seq;
5927 	eager->tcp_rack = seg_seq;
5928 	eager->tcp_rnxt = seg_seq + 1;
5929 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5930 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5931 	eager->tcp_state = TCPS_SYN_RCVD;
5932 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5933 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5934 	if (mp1 == NULL) {
5935 		/*
5936 		 * Increment the ref count as we are going to
5937 		 * enqueueing an mp in squeue
5938 		 */
5939 		CONN_INC_REF(econnp);
5940 		goto error;
5941 	}
5942 	DB_CPID(mp1) = tcp->tcp_cpid;
5943 	eager->tcp_cpid = tcp->tcp_cpid;
5944 	eager->tcp_open_time = lbolt64;
5945 
5946 	/*
5947 	 * We need to start the rto timer. In normal case, we start
5948 	 * the timer after sending the packet on the wire (or at
5949 	 * least believing that packet was sent by waiting for
5950 	 * CALL_IP_WPUT() to return). Since this is the first packet
5951 	 * being sent on the wire for the eager, our initial tcp_rto
5952 	 * is at least tcp_rexmit_interval_min which is a fairly
5953 	 * large value to allow the algorithm to adjust slowly to large
5954 	 * fluctuations of RTT during first few transmissions.
5955 	 *
5956 	 * Starting the timer first and then sending the packet in this
5957 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5958 	 * is of the order of several 100ms and starting the timer
5959 	 * first and then sending the packet will result in difference
5960 	 * of few micro seconds.
5961 	 *
5962 	 * Without this optimization, we are forced to hold the fanout
5963 	 * lock across the ipcl_bind_insert() and sending the packet
5964 	 * so that we don't race against an incoming packet (maybe RST)
5965 	 * for this eager.
5966 	 *
5967 	 * It is necessary to acquire an extra reference on the eager
5968 	 * at this point and hold it until after tcp_send_data() to
5969 	 * ensure against an eager close race.
5970 	 */
5971 
5972 	CONN_INC_REF(eager->tcp_connp);
5973 
5974 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5975 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5976 
5977 
5978 	/*
5979 	 * Insert the eager in its own perimeter now. We are ready to deal
5980 	 * with any packets on eager.
5981 	 */
5982 	if (eager->tcp_ipversion == IPV4_VERSION) {
5983 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5984 			goto error;
5985 		}
5986 	} else {
5987 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5988 			goto error;
5989 		}
5990 	}
5991 
5992 	/* mark conn as fully-bound */
5993 	econnp->conn_fully_bound = B_TRUE;
5994 
5995 	/* Send the SYN-ACK */
5996 	tcp_send_data(eager, eager->tcp_wq, mp1);
5997 	CONN_DEC_REF(eager->tcp_connp);
5998 	freemsg(mp);
5999 
6000 	return;
6001 error:
6002 	freemsg(mp1);
6003 	eager->tcp_closemp_used = B_TRUE;
6004 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6005 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6006 	    econnp, SQTAG_TCP_CONN_REQ_2);
6007 
6008 	/*
6009 	 * If a connection already exists, send the mp to that connections so
6010 	 * that it can be appropriately dealt with.
6011 	 */
6012 	ipst = tcps->tcps_netstack->netstack_ip;
6013 
6014 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6015 		if (!IPCL_IS_CONNECTED(econnp)) {
6016 			/*
6017 			 * Something bad happened. ipcl_conn_insert()
6018 			 * failed because a connection already existed
6019 			 * in connected hash but we can't find it
6020 			 * anymore (someone blew it away). Just
6021 			 * free this message and hopefully remote
6022 			 * will retransmit at which time the SYN can be
6023 			 * treated as a new connection or dealth with
6024 			 * a TH_RST if a connection already exists.
6025 			 */
6026 			CONN_DEC_REF(econnp);
6027 			freemsg(mp);
6028 		} else {
6029 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6030 			    econnp, SQTAG_TCP_CONN_REQ_1);
6031 		}
6032 	} else {
6033 		/* Nobody wants this packet */
6034 		freemsg(mp);
6035 	}
6036 	return;
6037 error3:
6038 	CONN_DEC_REF(econnp);
6039 error2:
6040 	freemsg(mp);
6041 }
6042 
6043 /*
6044  * In an ideal case of vertical partition in NUMA architecture, its
6045  * beneficial to have the listener and all the incoming connections
6046  * tied to the same squeue. The other constraint is that incoming
6047  * connections should be tied to the squeue attached to interrupted
6048  * CPU for obvious locality reason so this leaves the listener to
6049  * be tied to the same squeue. Our only problem is that when listener
6050  * is binding, the CPU that will get interrupted by the NIC whose
6051  * IP address the listener is binding to is not even known. So
6052  * the code below allows us to change that binding at the time the
6053  * CPU is interrupted by virtue of incoming connection's squeue.
6054  *
6055  * This is usefull only in case of a listener bound to a specific IP
6056  * address. For other kind of listeners, they get bound the
6057  * very first time and there is no attempt to rebind them.
6058  */
6059 void
6060 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6061 {
6062 	conn_t		*connp = (conn_t *)arg;
6063 	squeue_t	*sqp = (squeue_t *)arg2;
6064 	squeue_t	*new_sqp;
6065 	uint32_t	conn_flags;
6066 
6067 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6068 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6069 	} else {
6070 		goto done;
6071 	}
6072 
6073 	if (connp->conn_fanout == NULL)
6074 		goto done;
6075 
6076 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6077 		mutex_enter(&connp->conn_fanout->connf_lock);
6078 		mutex_enter(&connp->conn_lock);
6079 		/*
6080 		 * No one from read or write side can access us now
6081 		 * except for already queued packets on this squeue.
6082 		 * But since we haven't changed the squeue yet, they
6083 		 * can't execute. If they are processed after we have
6084 		 * changed the squeue, they are sent back to the
6085 		 * correct squeue down below.
6086 		 * But a listner close can race with processing of
6087 		 * incoming SYN. If incoming SYN processing changes
6088 		 * the squeue then the listener close which is waiting
6089 		 * to enter the squeue would operate on the wrong
6090 		 * squeue. Hence we don't change the squeue here unless
6091 		 * the refcount is exactly the minimum refcount. The
6092 		 * minimum refcount of 4 is counted as - 1 each for
6093 		 * TCP and IP, 1 for being in the classifier hash, and
6094 		 * 1 for the mblk being processed.
6095 		 */
6096 
6097 		if (connp->conn_ref != 4 ||
6098 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6099 			mutex_exit(&connp->conn_lock);
6100 			mutex_exit(&connp->conn_fanout->connf_lock);
6101 			goto done;
6102 		}
6103 		if (connp->conn_sqp != new_sqp) {
6104 			while (connp->conn_sqp != new_sqp)
6105 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6106 		}
6107 
6108 		do {
6109 			conn_flags = connp->conn_flags;
6110 			conn_flags |= IPCL_FULLY_BOUND;
6111 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6112 			    conn_flags);
6113 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6114 
6115 		mutex_exit(&connp->conn_fanout->connf_lock);
6116 		mutex_exit(&connp->conn_lock);
6117 	}
6118 
6119 done:
6120 	if (connp->conn_sqp != sqp) {
6121 		CONN_INC_REF(connp);
6122 		squeue_fill(connp->conn_sqp, mp,
6123 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6124 	} else {
6125 		tcp_conn_request(connp, mp, sqp);
6126 	}
6127 }
6128 
6129 /*
6130  * Successful connect request processing begins when our client passes
6131  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6132  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6133  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6134  *   upstream <- tcp_rput()                <- IP
6135  * After various error checks are completed, tcp_connect() lays
6136  * the target address and port into the composite header template,
6137  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6138  * request followed by an IRE request, and passes the three mblk message
6139  * down to IP looking like this:
6140  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6141  * Processing continues in tcp_rput() when we receive the following message:
6142  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6143  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6144  * to fire off the connection request, and then passes the T_OK_ACK mblk
6145  * upstream that we filled in below.  There are, of course, numerous
6146  * error conditions along the way which truncate the processing described
6147  * above.
6148  */
6149 static void
6150 tcp_connect(tcp_t *tcp, mblk_t *mp)
6151 {
6152 	sin_t		*sin;
6153 	sin6_t		*sin6;
6154 	queue_t		*q = tcp->tcp_wq;
6155 	struct T_conn_req	*tcr;
6156 	ipaddr_t	*dstaddrp;
6157 	in_port_t	dstport;
6158 	uint_t		srcid;
6159 
6160 	tcr = (struct T_conn_req *)mp->b_rptr;
6161 
6162 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6163 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6164 		tcp_err_ack(tcp, mp, TPROTO, 0);
6165 		return;
6166 	}
6167 
6168 	/*
6169 	 * Determine packet type based on type of address passed in
6170 	 * the request should contain an IPv4 or IPv6 address.
6171 	 * Make sure that address family matches the type of
6172 	 * family of the the address passed down
6173 	 */
6174 	switch (tcr->DEST_length) {
6175 	default:
6176 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6177 		return;
6178 
6179 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6180 		/*
6181 		 * XXX: The check for valid DEST_length was not there
6182 		 * in earlier releases and some buggy
6183 		 * TLI apps (e.g Sybase) got away with not feeding
6184 		 * in sin_zero part of address.
6185 		 * We allow that bug to keep those buggy apps humming.
6186 		 * Test suites require the check on DEST_length.
6187 		 * We construct a new mblk with valid DEST_length
6188 		 * free the original so the rest of the code does
6189 		 * not have to keep track of this special shorter
6190 		 * length address case.
6191 		 */
6192 		mblk_t *nmp;
6193 		struct T_conn_req *ntcr;
6194 		sin_t *nsin;
6195 
6196 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6197 		    tcr->OPT_length, BPRI_HI);
6198 		if (nmp == NULL) {
6199 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6200 			return;
6201 		}
6202 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6203 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6204 		ntcr->PRIM_type = T_CONN_REQ;
6205 		ntcr->DEST_length = sizeof (sin_t);
6206 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6207 
6208 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6209 		*nsin = sin_null;
6210 		/* Get pointer to shorter address to copy from original mp */
6211 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6212 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6213 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6214 			freemsg(nmp);
6215 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6216 			return;
6217 		}
6218 		nsin->sin_family = sin->sin_family;
6219 		nsin->sin_port = sin->sin_port;
6220 		nsin->sin_addr = sin->sin_addr;
6221 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6222 		nmp->b_wptr = (uchar_t *)&nsin[1];
6223 		if (tcr->OPT_length != 0) {
6224 			ntcr->OPT_length = tcr->OPT_length;
6225 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6226 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6227 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6228 			    tcr->OPT_length);
6229 			nmp->b_wptr += tcr->OPT_length;
6230 		}
6231 		freemsg(mp);	/* original mp freed */
6232 		mp = nmp;	/* re-initialize original variables */
6233 		tcr = ntcr;
6234 	}
6235 	/* FALLTHRU */
6236 
6237 	case sizeof (sin_t):
6238 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6239 		    sizeof (sin_t));
6240 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6241 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6242 			return;
6243 		}
6244 		if (tcp->tcp_family != AF_INET ||
6245 		    sin->sin_family != AF_INET) {
6246 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6247 			return;
6248 		}
6249 		if (sin->sin_port == 0) {
6250 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6251 			return;
6252 		}
6253 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6254 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6255 			return;
6256 		}
6257 
6258 		break;
6259 
6260 	case sizeof (sin6_t):
6261 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6262 		    sizeof (sin6_t));
6263 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6264 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6265 			return;
6266 		}
6267 		if (tcp->tcp_family != AF_INET6 ||
6268 		    sin6->sin6_family != AF_INET6) {
6269 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6270 			return;
6271 		}
6272 		if (sin6->sin6_port == 0) {
6273 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6274 			return;
6275 		}
6276 		break;
6277 	}
6278 	/*
6279 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6280 	 * should key on their sequence number and cut them loose.
6281 	 */
6282 
6283 	/*
6284 	 * If options passed in, feed it for verification and handling
6285 	 */
6286 	if (tcr->OPT_length != 0) {
6287 		mblk_t	*ok_mp;
6288 		mblk_t	*discon_mp;
6289 		mblk_t  *conn_opts_mp;
6290 		int t_error, sys_error, do_disconnect;
6291 
6292 		conn_opts_mp = NULL;
6293 
6294 		if (tcp_conprim_opt_process(tcp, mp,
6295 		    &do_disconnect, &t_error, &sys_error) < 0) {
6296 			if (do_disconnect) {
6297 				ASSERT(t_error == 0 && sys_error == 0);
6298 				discon_mp = mi_tpi_discon_ind(NULL,
6299 				    ECONNREFUSED, 0);
6300 				if (!discon_mp) {
6301 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6302 					    TSYSERR, ENOMEM);
6303 					return;
6304 				}
6305 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6306 				if (!ok_mp) {
6307 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6308 					    TSYSERR, ENOMEM);
6309 					return;
6310 				}
6311 				qreply(q, ok_mp);
6312 				qreply(q, discon_mp); /* no flush! */
6313 			} else {
6314 				ASSERT(t_error != 0);
6315 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6316 				    sys_error);
6317 			}
6318 			return;
6319 		}
6320 		/*
6321 		 * Success in setting options, the mp option buffer represented
6322 		 * by OPT_length/offset has been potentially modified and
6323 		 * contains results of option processing. We copy it in
6324 		 * another mp to save it for potentially influencing returning
6325 		 * it in T_CONN_CONN.
6326 		 */
6327 		if (tcr->OPT_length != 0) { /* there are resulting options */
6328 			conn_opts_mp = copyb(mp);
6329 			if (!conn_opts_mp) {
6330 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6331 				    TSYSERR, ENOMEM);
6332 				return;
6333 			}
6334 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6335 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6336 			/*
6337 			 * Note:
6338 			 * These resulting option negotiation can include any
6339 			 * end-to-end negotiation options but there no such
6340 			 * thing (yet?) in our TCP/IP.
6341 			 */
6342 		}
6343 	}
6344 
6345 	/*
6346 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6347 	 * make sure that the template IP header in the tcp structure is an
6348 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6349 	 * need to this before we call tcp_bindi() so that the port lookup
6350 	 * code will look for ports in the correct port space (IPv4 and
6351 	 * IPv6 have separate port spaces).
6352 	 */
6353 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6354 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6355 		int err = 0;
6356 
6357 		err = tcp_header_init_ipv4(tcp);
6358 		if (err != 0) {
6359 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6360 			goto connect_failed;
6361 		}
6362 		if (tcp->tcp_lport != 0)
6363 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6364 	}
6365 
6366 	switch (tcp->tcp_state) {
6367 	case TCPS_IDLE:
6368 		/*
6369 		 * We support quick connect, refer to comments in
6370 		 * tcp_connect_*()
6371 		 */
6372 		/* FALLTHRU */
6373 	case TCPS_BOUND:
6374 	case TCPS_LISTEN:
6375 		if (tcp->tcp_family == AF_INET6) {
6376 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6377 				tcp_connect_ipv6(tcp, mp,
6378 				    &sin6->sin6_addr,
6379 				    sin6->sin6_port, sin6->sin6_flowinfo,
6380 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6381 				return;
6382 			}
6383 			/*
6384 			 * Destination adress is mapped IPv6 address.
6385 			 * Source bound address should be unspecified or
6386 			 * IPv6 mapped address as well.
6387 			 */
6388 			if (!IN6_IS_ADDR_UNSPECIFIED(
6389 			    &tcp->tcp_bound_source_v6) &&
6390 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6391 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6392 				    EADDRNOTAVAIL);
6393 				break;
6394 			}
6395 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6396 			dstport = sin6->sin6_port;
6397 			srcid = sin6->__sin6_src_id;
6398 		} else {
6399 			dstaddrp = &sin->sin_addr.s_addr;
6400 			dstport = sin->sin_port;
6401 			srcid = 0;
6402 		}
6403 
6404 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6405 		return;
6406 	default:
6407 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6408 		break;
6409 	}
6410 	/*
6411 	 * Note: Code below is the "failure" case
6412 	 */
6413 	/* return error ack and blow away saved option results if any */
6414 connect_failed:
6415 	if (mp != NULL)
6416 		putnext(tcp->tcp_rq, mp);
6417 	else {
6418 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6419 		    TSYSERR, ENOMEM);
6420 	}
6421 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6422 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6423 }
6424 
6425 /*
6426  * Handle connect to IPv4 destinations, including connections for AF_INET6
6427  * sockets connecting to IPv4 mapped IPv6 destinations.
6428  */
6429 static void
6430 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6431     uint_t srcid)
6432 {
6433 	tcph_t	*tcph;
6434 	mblk_t	*mp1;
6435 	ipaddr_t dstaddr = *dstaddrp;
6436 	int32_t	oldstate;
6437 	uint16_t lport;
6438 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6439 
6440 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6441 
6442 	/* Check for attempt to connect to INADDR_ANY */
6443 	if (dstaddr == INADDR_ANY)  {
6444 		/*
6445 		 * SunOS 4.x and 4.3 BSD allow an application
6446 		 * to connect a TCP socket to INADDR_ANY.
6447 		 * When they do this, the kernel picks the
6448 		 * address of one interface and uses it
6449 		 * instead.  The kernel usually ends up
6450 		 * picking the address of the loopback
6451 		 * interface.  This is an undocumented feature.
6452 		 * However, we provide the same thing here
6453 		 * in order to have source and binary
6454 		 * compatibility with SunOS 4.x.
6455 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6456 		 * generate the T_CONN_CON.
6457 		 */
6458 		dstaddr = htonl(INADDR_LOOPBACK);
6459 		*dstaddrp = dstaddr;
6460 	}
6461 
6462 	/* Handle __sin6_src_id if socket not bound to an IP address */
6463 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6464 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6465 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6466 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6467 		    tcp->tcp_ipha->ipha_src);
6468 	}
6469 
6470 	/*
6471 	 * Don't let an endpoint connect to itself.  Note that
6472 	 * the test here does not catch the case where the
6473 	 * source IP addr was left unspecified by the user. In
6474 	 * this case, the source addr is set in tcp_adapt_ire()
6475 	 * using the reply to the T_BIND message that we send
6476 	 * down to IP here and the check is repeated in tcp_rput_other.
6477 	 */
6478 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6479 	    dstport == tcp->tcp_lport) {
6480 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6481 		goto failed;
6482 	}
6483 
6484 	tcp->tcp_ipha->ipha_dst = dstaddr;
6485 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6486 
6487 	/*
6488 	 * Massage a source route if any putting the first hop
6489 	 * in iph_dst. Compute a starting value for the checksum which
6490 	 * takes into account that the original iph_dst should be
6491 	 * included in the checksum but that ip will include the
6492 	 * first hop in the source route in the tcp checksum.
6493 	 */
6494 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6495 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6496 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6497 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6498 	if ((int)tcp->tcp_sum < 0)
6499 		tcp->tcp_sum--;
6500 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6501 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6502 	    (tcp->tcp_sum >> 16));
6503 	tcph = tcp->tcp_tcph;
6504 	*(uint16_t *)tcph->th_fport = dstport;
6505 	tcp->tcp_fport = dstport;
6506 
6507 	oldstate = tcp->tcp_state;
6508 	/*
6509 	 * At this point the remote destination address and remote port fields
6510 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6511 	 * have to see which state tcp was in so we can take apropriate action.
6512 	 */
6513 	if (oldstate == TCPS_IDLE) {
6514 		/*
6515 		 * We support a quick connect capability here, allowing
6516 		 * clients to transition directly from IDLE to SYN_SENT
6517 		 * tcp_bindi will pick an unused port, insert the connection
6518 		 * in the bind hash and transition to BOUND state.
6519 		 */
6520 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6521 		    tcp, B_TRUE);
6522 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6523 		    B_FALSE, B_FALSE);
6524 		if (lport == 0) {
6525 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6526 			goto failed;
6527 		}
6528 	}
6529 	tcp->tcp_state = TCPS_SYN_SENT;
6530 
6531 	/*
6532 	 * TODO: allow data with connect requests
6533 	 * by unlinking M_DATA trailers here and
6534 	 * linking them in behind the T_OK_ACK mblk.
6535 	 * The tcp_rput() bind ack handler would then
6536 	 * feed them to tcp_wput_data() rather than call
6537 	 * tcp_timer().
6538 	 */
6539 	mp = mi_tpi_ok_ack_alloc(mp);
6540 	if (!mp) {
6541 		tcp->tcp_state = oldstate;
6542 		goto failed;
6543 	}
6544 	if (tcp->tcp_family == AF_INET) {
6545 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6546 		    sizeof (ipa_conn_t));
6547 	} else {
6548 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6549 		    sizeof (ipa6_conn_t));
6550 	}
6551 	if (mp1) {
6552 		/*
6553 		 * We need to make sure that the conn_recv is set to a non-null
6554 		 * value before we insert the conn_t into the classifier table.
6555 		 * This is to avoid a race with an incoming packet which does
6556 		 * an ipcl_classify().
6557 		 */
6558 		tcp->tcp_connp->conn_recv = tcp_input;
6559 
6560 		/* Hang onto the T_OK_ACK for later. */
6561 		linkb(mp1, mp);
6562 		mblk_setcred(mp1, tcp->tcp_cred);
6563 		if (tcp->tcp_family == AF_INET)
6564 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6565 		else {
6566 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6567 			    &tcp->tcp_sticky_ipp);
6568 		}
6569 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6570 		tcp->tcp_active_open = 1;
6571 		/*
6572 		 * If the bind cannot complete immediately
6573 		 * IP will arrange to call tcp_rput_other
6574 		 * when the bind completes.
6575 		 */
6576 		if (mp1 != NULL)
6577 			tcp_rput_other(tcp, mp1);
6578 		return;
6579 	}
6580 	/* Error case */
6581 	tcp->tcp_state = oldstate;
6582 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6583 
6584 failed:
6585 	/* return error ack and blow away saved option results if any */
6586 	if (mp != NULL)
6587 		putnext(tcp->tcp_rq, mp);
6588 	else {
6589 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6590 		    TSYSERR, ENOMEM);
6591 	}
6592 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6593 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6594 
6595 }
6596 
6597 /*
6598  * Handle connect to IPv6 destinations.
6599  */
6600 static void
6601 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6602     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6603 {
6604 	tcph_t	*tcph;
6605 	mblk_t	*mp1;
6606 	ip6_rthdr_t *rth;
6607 	int32_t  oldstate;
6608 	uint16_t lport;
6609 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6610 
6611 	ASSERT(tcp->tcp_family == AF_INET6);
6612 
6613 	/*
6614 	 * If we're here, it means that the destination address is a native
6615 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6616 	 * reason why it might not be IPv6 is if the socket was bound to an
6617 	 * IPv4-mapped IPv6 address.
6618 	 */
6619 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6620 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6621 		goto failed;
6622 	}
6623 
6624 	/*
6625 	 * Interpret a zero destination to mean loopback.
6626 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6627 	 * generate the T_CONN_CON.
6628 	 */
6629 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6630 		*dstaddrp = ipv6_loopback;
6631 	}
6632 
6633 	/* Handle __sin6_src_id if socket not bound to an IP address */
6634 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6635 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6636 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6637 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6638 	}
6639 
6640 	/*
6641 	 * Take care of the scope_id now and add ip6i_t
6642 	 * if ip6i_t is not already allocated through TCP
6643 	 * sticky options. At this point tcp_ip6h does not
6644 	 * have dst info, thus use dstaddrp.
6645 	 */
6646 	if (scope_id != 0 &&
6647 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6648 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6649 		ip6i_t  *ip6i;
6650 
6651 		ipp->ipp_ifindex = scope_id;
6652 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6653 
6654 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6655 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6656 			/* Already allocated */
6657 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6658 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6659 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6660 		} else {
6661 			int reterr;
6662 
6663 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6664 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6665 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6666 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6667 			if (reterr != 0)
6668 				goto failed;
6669 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6670 		}
6671 	}
6672 
6673 	/*
6674 	 * Don't let an endpoint connect to itself.  Note that
6675 	 * the test here does not catch the case where the
6676 	 * source IP addr was left unspecified by the user. In
6677 	 * this case, the source addr is set in tcp_adapt_ire()
6678 	 * using the reply to the T_BIND message that we send
6679 	 * down to IP here and the check is repeated in tcp_rput_other.
6680 	 */
6681 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6682 	    (dstport == tcp->tcp_lport)) {
6683 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6684 		goto failed;
6685 	}
6686 
6687 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6688 	tcp->tcp_remote_v6 = *dstaddrp;
6689 	tcp->tcp_ip6h->ip6_vcf =
6690 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6691 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6692 
6693 
6694 	/*
6695 	 * Massage a routing header (if present) putting the first hop
6696 	 * in ip6_dst. Compute a starting value for the checksum which
6697 	 * takes into account that the original ip6_dst should be
6698 	 * included in the checksum but that ip will include the
6699 	 * first hop in the source route in the tcp checksum.
6700 	 */
6701 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6702 	if (rth != NULL) {
6703 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6704 		    tcps->tcps_netstack);
6705 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6706 		    (tcp->tcp_sum >> 16));
6707 	} else {
6708 		tcp->tcp_sum = 0;
6709 	}
6710 
6711 	tcph = tcp->tcp_tcph;
6712 	*(uint16_t *)tcph->th_fport = dstport;
6713 	tcp->tcp_fport = dstport;
6714 
6715 	oldstate = tcp->tcp_state;
6716 	/*
6717 	 * At this point the remote destination address and remote port fields
6718 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6719 	 * have to see which state tcp was in so we can take apropriate action.
6720 	 */
6721 	if (oldstate == TCPS_IDLE) {
6722 		/*
6723 		 * We support a quick connect capability here, allowing
6724 		 * clients to transition directly from IDLE to SYN_SENT
6725 		 * tcp_bindi will pick an unused port, insert the connection
6726 		 * in the bind hash and transition to BOUND state.
6727 		 */
6728 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6729 		    tcp, B_TRUE);
6730 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6731 		    B_FALSE, B_FALSE);
6732 		if (lport == 0) {
6733 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6734 			goto failed;
6735 		}
6736 	}
6737 	tcp->tcp_state = TCPS_SYN_SENT;
6738 	/*
6739 	 * TODO: allow data with connect requests
6740 	 * by unlinking M_DATA trailers here and
6741 	 * linking them in behind the T_OK_ACK mblk.
6742 	 * The tcp_rput() bind ack handler would then
6743 	 * feed them to tcp_wput_data() rather than call
6744 	 * tcp_timer().
6745 	 */
6746 	mp = mi_tpi_ok_ack_alloc(mp);
6747 	if (!mp) {
6748 		tcp->tcp_state = oldstate;
6749 		goto failed;
6750 	}
6751 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6752 	if (mp1) {
6753 		/*
6754 		 * We need to make sure that the conn_recv is set to a non-null
6755 		 * value before we insert the conn_t into the classifier table.
6756 		 * This is to avoid a race with an incoming packet which does
6757 		 * an ipcl_classify().
6758 		 */
6759 		tcp->tcp_connp->conn_recv = tcp_input;
6760 
6761 		/* Hang onto the T_OK_ACK for later. */
6762 		linkb(mp1, mp);
6763 		mblk_setcred(mp1, tcp->tcp_cred);
6764 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6765 		    &tcp->tcp_sticky_ipp);
6766 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6767 		tcp->tcp_active_open = 1;
6768 		/* ip_bind_v6() may return ACK or ERROR */
6769 		if (mp1 != NULL)
6770 			tcp_rput_other(tcp, mp1);
6771 		return;
6772 	}
6773 	/* Error case */
6774 	tcp->tcp_state = oldstate;
6775 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6776 
6777 failed:
6778 	/* return error ack and blow away saved option results if any */
6779 	if (mp != NULL)
6780 		putnext(tcp->tcp_rq, mp);
6781 	else {
6782 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6783 		    TSYSERR, ENOMEM);
6784 	}
6785 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6786 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6787 }
6788 
6789 /*
6790  * We need a stream q for detached closing tcp connections
6791  * to use.  Our client hereby indicates that this q is the
6792  * one to use.
6793  */
6794 static void
6795 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6796 {
6797 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6798 	queue_t	*q = tcp->tcp_wq;
6799 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6800 
6801 #ifdef NS_DEBUG
6802 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6803 	    tcps->tcps_netstack->netstack_stackid);
6804 #endif
6805 	mp->b_datap->db_type = M_IOCACK;
6806 	iocp->ioc_count = 0;
6807 	mutex_enter(&tcps->tcps_g_q_lock);
6808 	if (tcps->tcps_g_q != NULL) {
6809 		mutex_exit(&tcps->tcps_g_q_lock);
6810 		iocp->ioc_error = EALREADY;
6811 	} else {
6812 		mblk_t *mp1;
6813 
6814 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6815 		if (mp1 == NULL) {
6816 			mutex_exit(&tcps->tcps_g_q_lock);
6817 			iocp->ioc_error = ENOMEM;
6818 		} else {
6819 			tcps->tcps_g_q = tcp->tcp_rq;
6820 			mutex_exit(&tcps->tcps_g_q_lock);
6821 			iocp->ioc_error = 0;
6822 			iocp->ioc_rval = 0;
6823 			/*
6824 			 * We are passing tcp_sticky_ipp as NULL
6825 			 * as it is not useful for tcp_default queue
6826 			 *
6827 			 * Set conn_recv just in case.
6828 			 */
6829 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6830 
6831 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6832 			if (mp1 != NULL)
6833 				tcp_rput_other(tcp, mp1);
6834 		}
6835 	}
6836 	qreply(q, mp);
6837 }
6838 
6839 /*
6840  * Our client hereby directs us to reject the connection request
6841  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6842  * of sending the appropriate RST, not an ICMP error.
6843  */
6844 static void
6845 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6846 {
6847 	tcp_t	*ltcp = NULL;
6848 	t_scalar_t seqnum;
6849 	conn_t	*connp;
6850 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6851 
6852 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6853 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6854 		tcp_err_ack(tcp, mp, TPROTO, 0);
6855 		return;
6856 	}
6857 
6858 	/*
6859 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6860 	 * when the stream is in BOUND state. Do not send a reset,
6861 	 * since the destination IP address is not valid, and it can
6862 	 * be the initialized value of all zeros (broadcast address).
6863 	 *
6864 	 * If TCP has sent down a bind request to IP and has not
6865 	 * received the reply, reject the request.  Otherwise, TCP
6866 	 * will be confused.
6867 	 */
6868 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6869 		if (tcp->tcp_debug) {
6870 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6871 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6872 		}
6873 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6874 		return;
6875 	}
6876 
6877 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6878 
6879 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6880 
6881 		/*
6882 		 * According to TPI, for non-listeners, ignore seqnum
6883 		 * and disconnect.
6884 		 * Following interpretation of -1 seqnum is historical
6885 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6886 		 * a valid seqnum should not be -1).
6887 		 *
6888 		 *	-1 means disconnect everything
6889 		 *	regardless even on a listener.
6890 		 */
6891 
6892 		int old_state = tcp->tcp_state;
6893 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6894 
6895 		/*
6896 		 * The connection can't be on the tcp_time_wait_head list
6897 		 * since it is not detached.
6898 		 */
6899 		ASSERT(tcp->tcp_time_wait_next == NULL);
6900 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6901 		ASSERT(tcp->tcp_time_wait_expire == 0);
6902 		ltcp = NULL;
6903 		/*
6904 		 * If it used to be a listener, check to make sure no one else
6905 		 * has taken the port before switching back to LISTEN state.
6906 		 */
6907 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6908 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6909 			    tcp->tcp_ipha->ipha_src,
6910 			    tcp->tcp_connp->conn_zoneid, ipst);
6911 			if (connp != NULL)
6912 				ltcp = connp->conn_tcp;
6913 		} else {
6914 			/* Allow tcp_bound_if listeners? */
6915 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6916 			    &tcp->tcp_ip6h->ip6_src, 0,
6917 			    tcp->tcp_connp->conn_zoneid, ipst);
6918 			if (connp != NULL)
6919 				ltcp = connp->conn_tcp;
6920 		}
6921 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6922 			tcp->tcp_state = TCPS_LISTEN;
6923 		} else if (old_state > TCPS_BOUND) {
6924 			tcp->tcp_conn_req_max = 0;
6925 			tcp->tcp_state = TCPS_BOUND;
6926 		}
6927 		if (ltcp != NULL)
6928 			CONN_DEC_REF(ltcp->tcp_connp);
6929 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6930 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6931 		} else if (old_state == TCPS_ESTABLISHED ||
6932 		    old_state == TCPS_CLOSE_WAIT) {
6933 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6934 		}
6935 
6936 		if (tcp->tcp_fused)
6937 			tcp_unfuse(tcp);
6938 
6939 		mutex_enter(&tcp->tcp_eager_lock);
6940 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6941 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6942 			tcp_eager_cleanup(tcp, 0);
6943 		}
6944 		mutex_exit(&tcp->tcp_eager_lock);
6945 
6946 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6947 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6948 
6949 		tcp_reinit(tcp);
6950 
6951 		if (old_state >= TCPS_ESTABLISHED) {
6952 			/* Send M_FLUSH according to TPI */
6953 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6954 		}
6955 		mp = mi_tpi_ok_ack_alloc(mp);
6956 		if (mp)
6957 			putnext(tcp->tcp_rq, mp);
6958 		return;
6959 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6960 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6961 		return;
6962 	}
6963 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6964 		/* Send M_FLUSH according to TPI */
6965 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6966 	}
6967 	mp = mi_tpi_ok_ack_alloc(mp);
6968 	if (mp)
6969 		putnext(tcp->tcp_rq, mp);
6970 }
6971 
6972 /*
6973  * Diagnostic routine used to return a string associated with the tcp state.
6974  * Note that if the caller does not supply a buffer, it will use an internal
6975  * static string.  This means that if multiple threads call this function at
6976  * the same time, output can be corrupted...  Note also that this function
6977  * does not check the size of the supplied buffer.  The caller has to make
6978  * sure that it is big enough.
6979  */
6980 static char *
6981 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6982 {
6983 	char		buf1[30];
6984 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6985 	char		*buf;
6986 	char		*cp;
6987 	in6_addr_t	local, remote;
6988 	char		local_addrbuf[INET6_ADDRSTRLEN];
6989 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6990 
6991 	if (sup_buf != NULL)
6992 		buf = sup_buf;
6993 	else
6994 		buf = priv_buf;
6995 
6996 	if (tcp == NULL)
6997 		return ("NULL_TCP");
6998 	switch (tcp->tcp_state) {
6999 	case TCPS_CLOSED:
7000 		cp = "TCP_CLOSED";
7001 		break;
7002 	case TCPS_IDLE:
7003 		cp = "TCP_IDLE";
7004 		break;
7005 	case TCPS_BOUND:
7006 		cp = "TCP_BOUND";
7007 		break;
7008 	case TCPS_LISTEN:
7009 		cp = "TCP_LISTEN";
7010 		break;
7011 	case TCPS_SYN_SENT:
7012 		cp = "TCP_SYN_SENT";
7013 		break;
7014 	case TCPS_SYN_RCVD:
7015 		cp = "TCP_SYN_RCVD";
7016 		break;
7017 	case TCPS_ESTABLISHED:
7018 		cp = "TCP_ESTABLISHED";
7019 		break;
7020 	case TCPS_CLOSE_WAIT:
7021 		cp = "TCP_CLOSE_WAIT";
7022 		break;
7023 	case TCPS_FIN_WAIT_1:
7024 		cp = "TCP_FIN_WAIT_1";
7025 		break;
7026 	case TCPS_CLOSING:
7027 		cp = "TCP_CLOSING";
7028 		break;
7029 	case TCPS_LAST_ACK:
7030 		cp = "TCP_LAST_ACK";
7031 		break;
7032 	case TCPS_FIN_WAIT_2:
7033 		cp = "TCP_FIN_WAIT_2";
7034 		break;
7035 	case TCPS_TIME_WAIT:
7036 		cp = "TCP_TIME_WAIT";
7037 		break;
7038 	default:
7039 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7040 		cp = buf1;
7041 		break;
7042 	}
7043 	switch (format) {
7044 	case DISP_ADDR_AND_PORT:
7045 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7046 			/*
7047 			 * Note that we use the remote address in the tcp_b
7048 			 * structure.  This means that it will print out
7049 			 * the real destination address, not the next hop's
7050 			 * address if source routing is used.
7051 			 */
7052 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7053 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7054 
7055 		} else {
7056 			local = tcp->tcp_ip_src_v6;
7057 			remote = tcp->tcp_remote_v6;
7058 		}
7059 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7060 		    sizeof (local_addrbuf));
7061 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7062 		    sizeof (remote_addrbuf));
7063 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7064 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7065 		    ntohs(tcp->tcp_fport), cp);
7066 		break;
7067 	case DISP_PORT_ONLY:
7068 	default:
7069 		(void) mi_sprintf(buf, "[%u, %u] %s",
7070 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7071 		break;
7072 	}
7073 
7074 	return (buf);
7075 }
7076 
7077 /*
7078  * Called via squeue to get on to eager's perimeter. It sends a
7079  * TH_RST if eager is in the fanout table. The listener wants the
7080  * eager to disappear either by means of tcp_eager_blowoff() or
7081  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7082  * called (via squeue) if the eager cannot be inserted in the
7083  * fanout table in tcp_conn_request().
7084  */
7085 /* ARGSUSED */
7086 void
7087 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7088 {
7089 	conn_t	*econnp = (conn_t *)arg;
7090 	tcp_t	*eager = econnp->conn_tcp;
7091 	tcp_t	*listener = eager->tcp_listener;
7092 	tcp_stack_t	*tcps = eager->tcp_tcps;
7093 
7094 	/*
7095 	 * We could be called because listener is closing. Since
7096 	 * the eager is using listener's queue's, its not safe.
7097 	 * Better use the default queue just to send the TH_RST
7098 	 * out.
7099 	 */
7100 	ASSERT(tcps->tcps_g_q != NULL);
7101 	eager->tcp_rq = tcps->tcps_g_q;
7102 	eager->tcp_wq = WR(tcps->tcps_g_q);
7103 
7104 	/*
7105 	 * An eager's conn_fanout will be NULL if it's a duplicate
7106 	 * for an existing 4-tuples in the conn fanout table.
7107 	 * We don't want to send an RST out in such case.
7108 	 */
7109 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7110 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7111 		    eager, eager->tcp_snxt, 0, TH_RST);
7112 	}
7113 
7114 	/* We are here because listener wants this eager gone */
7115 	if (listener != NULL) {
7116 		mutex_enter(&listener->tcp_eager_lock);
7117 		tcp_eager_unlink(eager);
7118 		if (eager->tcp_tconnind_started) {
7119 			/*
7120 			 * The eager has sent a conn_ind up to the
7121 			 * listener but listener decides to close
7122 			 * instead. We need to drop the extra ref
7123 			 * placed on eager in tcp_rput_data() before
7124 			 * sending the conn_ind to listener.
7125 			 */
7126 			CONN_DEC_REF(econnp);
7127 		}
7128 		mutex_exit(&listener->tcp_eager_lock);
7129 		CONN_DEC_REF(listener->tcp_connp);
7130 	}
7131 
7132 	if (eager->tcp_state > TCPS_BOUND)
7133 		tcp_close_detached(eager);
7134 }
7135 
7136 /*
7137  * Reset any eager connection hanging off this listener marked
7138  * with 'seqnum' and then reclaim it's resources.
7139  */
7140 static boolean_t
7141 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7142 {
7143 	tcp_t	*eager;
7144 	mblk_t 	*mp;
7145 	tcp_stack_t	*tcps = listener->tcp_tcps;
7146 
7147 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7148 	eager = listener;
7149 	mutex_enter(&listener->tcp_eager_lock);
7150 	do {
7151 		eager = eager->tcp_eager_next_q;
7152 		if (eager == NULL) {
7153 			mutex_exit(&listener->tcp_eager_lock);
7154 			return (B_FALSE);
7155 		}
7156 	} while (eager->tcp_conn_req_seqnum != seqnum);
7157 
7158 	if (eager->tcp_closemp_used) {
7159 		mutex_exit(&listener->tcp_eager_lock);
7160 		return (B_TRUE);
7161 	}
7162 	eager->tcp_closemp_used = B_TRUE;
7163 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7164 	CONN_INC_REF(eager->tcp_connp);
7165 	mutex_exit(&listener->tcp_eager_lock);
7166 	mp = &eager->tcp_closemp;
7167 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7168 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7169 	return (B_TRUE);
7170 }
7171 
7172 /*
7173  * Reset any eager connection hanging off this listener
7174  * and then reclaim it's resources.
7175  */
7176 static void
7177 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7178 {
7179 	tcp_t	*eager;
7180 	mblk_t	*mp;
7181 	tcp_stack_t	*tcps = listener->tcp_tcps;
7182 
7183 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7184 
7185 	if (!q0_only) {
7186 		/* First cleanup q */
7187 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7188 		eager = listener->tcp_eager_next_q;
7189 		while (eager != NULL) {
7190 			if (!eager->tcp_closemp_used) {
7191 				eager->tcp_closemp_used = B_TRUE;
7192 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7193 				CONN_INC_REF(eager->tcp_connp);
7194 				mp = &eager->tcp_closemp;
7195 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7196 				    tcp_eager_kill, eager->tcp_connp,
7197 				    SQTAG_TCP_EAGER_CLEANUP);
7198 			}
7199 			eager = eager->tcp_eager_next_q;
7200 		}
7201 	}
7202 	/* Then cleanup q0 */
7203 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7204 	eager = listener->tcp_eager_next_q0;
7205 	while (eager != listener) {
7206 		if (!eager->tcp_closemp_used) {
7207 			eager->tcp_closemp_used = B_TRUE;
7208 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7209 			CONN_INC_REF(eager->tcp_connp);
7210 			mp = &eager->tcp_closemp;
7211 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7212 			    tcp_eager_kill, eager->tcp_connp,
7213 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7214 		}
7215 		eager = eager->tcp_eager_next_q0;
7216 	}
7217 }
7218 
7219 /*
7220  * If we are an eager connection hanging off a listener that hasn't
7221  * formally accepted the connection yet, get off his list and blow off
7222  * any data that we have accumulated.
7223  */
7224 static void
7225 tcp_eager_unlink(tcp_t *tcp)
7226 {
7227 	tcp_t	*listener = tcp->tcp_listener;
7228 
7229 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7230 	ASSERT(listener != NULL);
7231 	if (tcp->tcp_eager_next_q0 != NULL) {
7232 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7233 
7234 		/* Remove the eager tcp from q0 */
7235 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7236 		    tcp->tcp_eager_prev_q0;
7237 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7238 		    tcp->tcp_eager_next_q0;
7239 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7240 		listener->tcp_conn_req_cnt_q0--;
7241 
7242 		tcp->tcp_eager_next_q0 = NULL;
7243 		tcp->tcp_eager_prev_q0 = NULL;
7244 
7245 		/*
7246 		 * Take the eager out, if it is in the list of droppable
7247 		 * eagers.
7248 		 */
7249 		MAKE_UNDROPPABLE(tcp);
7250 
7251 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7252 			/* we have timed out before */
7253 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7254 			listener->tcp_syn_rcvd_timeout--;
7255 		}
7256 	} else {
7257 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7258 		tcp_t	*prev = NULL;
7259 
7260 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7261 			if (tcpp[0] == tcp) {
7262 				if (listener->tcp_eager_last_q == tcp) {
7263 					/*
7264 					 * If we are unlinking the last
7265 					 * element on the list, adjust
7266 					 * tail pointer. Set tail pointer
7267 					 * to nil when list is empty.
7268 					 */
7269 					ASSERT(tcp->tcp_eager_next_q == NULL);
7270 					if (listener->tcp_eager_last_q ==
7271 					    listener->tcp_eager_next_q) {
7272 						listener->tcp_eager_last_q =
7273 						    NULL;
7274 					} else {
7275 						/*
7276 						 * We won't get here if there
7277 						 * is only one eager in the
7278 						 * list.
7279 						 */
7280 						ASSERT(prev != NULL);
7281 						listener->tcp_eager_last_q =
7282 						    prev;
7283 					}
7284 				}
7285 				tcpp[0] = tcp->tcp_eager_next_q;
7286 				tcp->tcp_eager_next_q = NULL;
7287 				tcp->tcp_eager_last_q = NULL;
7288 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7289 				listener->tcp_conn_req_cnt_q--;
7290 				break;
7291 			}
7292 			prev = tcpp[0];
7293 		}
7294 	}
7295 	tcp->tcp_listener = NULL;
7296 }
7297 
7298 /* Shorthand to generate and send TPI error acks to our client */
7299 static void
7300 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7301 {
7302 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7303 		putnext(tcp->tcp_rq, mp);
7304 }
7305 
7306 /* Shorthand to generate and send TPI error acks to our client */
7307 static void
7308 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7309     int t_error, int sys_error)
7310 {
7311 	struct T_error_ack	*teackp;
7312 
7313 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7314 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7315 		teackp = (struct T_error_ack *)mp->b_rptr;
7316 		teackp->ERROR_prim = primitive;
7317 		teackp->TLI_error = t_error;
7318 		teackp->UNIX_error = sys_error;
7319 		putnext(tcp->tcp_rq, mp);
7320 	}
7321 }
7322 
7323 /*
7324  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7325  * but instead the code relies on:
7326  * - the fact that the address of the array and its size never changes
7327  * - the atomic assignment of the elements of the array
7328  */
7329 /* ARGSUSED */
7330 static int
7331 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7332 {
7333 	int i;
7334 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7335 
7336 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7337 		if (tcps->tcps_g_epriv_ports[i] != 0)
7338 			(void) mi_mpprintf(mp, "%d ",
7339 			    tcps->tcps_g_epriv_ports[i]);
7340 	}
7341 	return (0);
7342 }
7343 
7344 /*
7345  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7346  * threads from changing it at the same time.
7347  */
7348 /* ARGSUSED */
7349 static int
7350 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7351     cred_t *cr)
7352 {
7353 	long	new_value;
7354 	int	i;
7355 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7356 
7357 	/*
7358 	 * Fail the request if the new value does not lie within the
7359 	 * port number limits.
7360 	 */
7361 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7362 	    new_value <= 0 || new_value >= 65536) {
7363 		return (EINVAL);
7364 	}
7365 
7366 	mutex_enter(&tcps->tcps_epriv_port_lock);
7367 	/* Check if the value is already in the list */
7368 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7369 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7370 			mutex_exit(&tcps->tcps_epriv_port_lock);
7371 			return (EEXIST);
7372 		}
7373 	}
7374 	/* Find an empty slot */
7375 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7376 		if (tcps->tcps_g_epriv_ports[i] == 0)
7377 			break;
7378 	}
7379 	if (i == tcps->tcps_g_num_epriv_ports) {
7380 		mutex_exit(&tcps->tcps_epriv_port_lock);
7381 		return (EOVERFLOW);
7382 	}
7383 	/* Set the new value */
7384 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7385 	mutex_exit(&tcps->tcps_epriv_port_lock);
7386 	return (0);
7387 }
7388 
7389 /*
7390  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7391  * threads from changing it at the same time.
7392  */
7393 /* ARGSUSED */
7394 static int
7395 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7396     cred_t *cr)
7397 {
7398 	long	new_value;
7399 	int	i;
7400 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7401 
7402 	/*
7403 	 * Fail the request if the new value does not lie within the
7404 	 * port number limits.
7405 	 */
7406 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7407 	    new_value >= 65536) {
7408 		return (EINVAL);
7409 	}
7410 
7411 	mutex_enter(&tcps->tcps_epriv_port_lock);
7412 	/* Check that the value is already in the list */
7413 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7414 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7415 			break;
7416 	}
7417 	if (i == tcps->tcps_g_num_epriv_ports) {
7418 		mutex_exit(&tcps->tcps_epriv_port_lock);
7419 		return (ESRCH);
7420 	}
7421 	/* Clear the value */
7422 	tcps->tcps_g_epriv_ports[i] = 0;
7423 	mutex_exit(&tcps->tcps_epriv_port_lock);
7424 	return (0);
7425 }
7426 
7427 /* Return the TPI/TLI equivalent of our current tcp_state */
7428 static int
7429 tcp_tpistate(tcp_t *tcp)
7430 {
7431 	switch (tcp->tcp_state) {
7432 	case TCPS_IDLE:
7433 		return (TS_UNBND);
7434 	case TCPS_LISTEN:
7435 		/*
7436 		 * Return whether there are outstanding T_CONN_IND waiting
7437 		 * for the matching T_CONN_RES. Therefore don't count q0.
7438 		 */
7439 		if (tcp->tcp_conn_req_cnt_q > 0)
7440 			return (TS_WRES_CIND);
7441 		else
7442 			return (TS_IDLE);
7443 	case TCPS_BOUND:
7444 		return (TS_IDLE);
7445 	case TCPS_SYN_SENT:
7446 		return (TS_WCON_CREQ);
7447 	case TCPS_SYN_RCVD:
7448 		/*
7449 		 * Note: assumption: this has to the active open SYN_RCVD.
7450 		 * The passive instance is detached in SYN_RCVD stage of
7451 		 * incoming connection processing so we cannot get request
7452 		 * for T_info_ack on it.
7453 		 */
7454 		return (TS_WACK_CRES);
7455 	case TCPS_ESTABLISHED:
7456 		return (TS_DATA_XFER);
7457 	case TCPS_CLOSE_WAIT:
7458 		return (TS_WREQ_ORDREL);
7459 	case TCPS_FIN_WAIT_1:
7460 		return (TS_WIND_ORDREL);
7461 	case TCPS_FIN_WAIT_2:
7462 		return (TS_WIND_ORDREL);
7463 
7464 	case TCPS_CLOSING:
7465 	case TCPS_LAST_ACK:
7466 	case TCPS_TIME_WAIT:
7467 	case TCPS_CLOSED:
7468 		/*
7469 		 * Following TS_WACK_DREQ7 is a rendition of "not
7470 		 * yet TS_IDLE" TPI state. There is no best match to any
7471 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7472 		 * choose a value chosen that will map to TLI/XTI level
7473 		 * state of TSTATECHNG (state is process of changing) which
7474 		 * captures what this dummy state represents.
7475 		 */
7476 		return (TS_WACK_DREQ7);
7477 	default:
7478 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7479 		    tcp->tcp_state, tcp_display(tcp, NULL,
7480 		    DISP_PORT_ONLY));
7481 		return (TS_UNBND);
7482 	}
7483 }
7484 
7485 static void
7486 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7487 {
7488 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7489 
7490 	if (tcp->tcp_family == AF_INET6)
7491 		*tia = tcp_g_t_info_ack_v6;
7492 	else
7493 		*tia = tcp_g_t_info_ack;
7494 	tia->CURRENT_state = tcp_tpistate(tcp);
7495 	tia->OPT_size = tcp_max_optsize;
7496 	if (tcp->tcp_mss == 0) {
7497 		/* Not yet set - tcp_open does not set mss */
7498 		if (tcp->tcp_ipversion == IPV4_VERSION)
7499 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7500 		else
7501 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7502 	} else {
7503 		tia->TIDU_size = tcp->tcp_mss;
7504 	}
7505 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7506 }
7507 
7508 /*
7509  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7510  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7511  * tcp_g_t_info_ack.  The current state of the stream is copied from
7512  * tcp_state.
7513  */
7514 static void
7515 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7516 {
7517 	t_uscalar_t		cap_bits1;
7518 	struct T_capability_ack	*tcap;
7519 
7520 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7521 		freemsg(mp);
7522 		return;
7523 	}
7524 
7525 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7526 
7527 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7528 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7529 	if (mp == NULL)
7530 		return;
7531 
7532 	tcap = (struct T_capability_ack *)mp->b_rptr;
7533 	tcap->CAP_bits1 = 0;
7534 
7535 	if (cap_bits1 & TC1_INFO) {
7536 		tcp_copy_info(&tcap->INFO_ack, tcp);
7537 		tcap->CAP_bits1 |= TC1_INFO;
7538 	}
7539 
7540 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7541 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7542 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7543 	}
7544 
7545 	putnext(tcp->tcp_rq, mp);
7546 }
7547 
7548 /*
7549  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7550  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7551  * The current state of the stream is copied from tcp_state.
7552  */
7553 static void
7554 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7555 {
7556 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7557 	    T_INFO_ACK);
7558 	if (!mp) {
7559 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7560 		return;
7561 	}
7562 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7563 	putnext(tcp->tcp_rq, mp);
7564 }
7565 
7566 /* Respond to the TPI addr request */
7567 static void
7568 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7569 {
7570 	sin_t	*sin;
7571 	mblk_t	*ackmp;
7572 	struct T_addr_ack *taa;
7573 
7574 	/* Make it large enough for worst case */
7575 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7576 	    2 * sizeof (sin6_t), 1);
7577 	if (ackmp == NULL) {
7578 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7579 		return;
7580 	}
7581 
7582 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7583 		tcp_addr_req_ipv6(tcp, ackmp);
7584 		return;
7585 	}
7586 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7587 
7588 	bzero(taa, sizeof (struct T_addr_ack));
7589 	ackmp->b_wptr = (uchar_t *)&taa[1];
7590 
7591 	taa->PRIM_type = T_ADDR_ACK;
7592 	ackmp->b_datap->db_type = M_PCPROTO;
7593 
7594 	/*
7595 	 * Note: Following code assumes 32 bit alignment of basic
7596 	 * data structures like sin_t and struct T_addr_ack.
7597 	 */
7598 	if (tcp->tcp_state >= TCPS_BOUND) {
7599 		/*
7600 		 * Fill in local address
7601 		 */
7602 		taa->LOCADDR_length = sizeof (sin_t);
7603 		taa->LOCADDR_offset = sizeof (*taa);
7604 
7605 		sin = (sin_t *)&taa[1];
7606 
7607 		/* Fill zeroes and then intialize non-zero fields */
7608 		*sin = sin_null;
7609 
7610 		sin->sin_family = AF_INET;
7611 
7612 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7613 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7614 
7615 		ackmp->b_wptr = (uchar_t *)&sin[1];
7616 
7617 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7618 			/*
7619 			 * Fill in Remote address
7620 			 */
7621 			taa->REMADDR_length = sizeof (sin_t);
7622 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7623 			    taa->LOCADDR_length);
7624 
7625 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7626 			*sin = sin_null;
7627 			sin->sin_family = AF_INET;
7628 			sin->sin_addr.s_addr = tcp->tcp_remote;
7629 			sin->sin_port = tcp->tcp_fport;
7630 
7631 			ackmp->b_wptr = (uchar_t *)&sin[1];
7632 		}
7633 	}
7634 	putnext(tcp->tcp_rq, ackmp);
7635 }
7636 
7637 /* Assumes that tcp_addr_req gets enough space and alignment */
7638 static void
7639 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7640 {
7641 	sin6_t	*sin6;
7642 	struct T_addr_ack *taa;
7643 
7644 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7645 	ASSERT(OK_32PTR(ackmp->b_rptr));
7646 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7647 	    2 * sizeof (sin6_t));
7648 
7649 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7650 
7651 	bzero(taa, sizeof (struct T_addr_ack));
7652 	ackmp->b_wptr = (uchar_t *)&taa[1];
7653 
7654 	taa->PRIM_type = T_ADDR_ACK;
7655 	ackmp->b_datap->db_type = M_PCPROTO;
7656 
7657 	/*
7658 	 * Note: Following code assumes 32 bit alignment of basic
7659 	 * data structures like sin6_t and struct T_addr_ack.
7660 	 */
7661 	if (tcp->tcp_state >= TCPS_BOUND) {
7662 		/*
7663 		 * Fill in local address
7664 		 */
7665 		taa->LOCADDR_length = sizeof (sin6_t);
7666 		taa->LOCADDR_offset = sizeof (*taa);
7667 
7668 		sin6 = (sin6_t *)&taa[1];
7669 		*sin6 = sin6_null;
7670 
7671 		sin6->sin6_family = AF_INET6;
7672 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7673 		sin6->sin6_port = tcp->tcp_lport;
7674 
7675 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7676 
7677 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7678 			/*
7679 			 * Fill in Remote address
7680 			 */
7681 			taa->REMADDR_length = sizeof (sin6_t);
7682 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7683 			    taa->LOCADDR_length);
7684 
7685 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7686 			*sin6 = sin6_null;
7687 			sin6->sin6_family = AF_INET6;
7688 			sin6->sin6_flowinfo =
7689 			    tcp->tcp_ip6h->ip6_vcf &
7690 			    ~IPV6_VERS_AND_FLOW_MASK;
7691 			sin6->sin6_addr = tcp->tcp_remote_v6;
7692 			sin6->sin6_port = tcp->tcp_fport;
7693 
7694 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7695 		}
7696 	}
7697 	putnext(tcp->tcp_rq, ackmp);
7698 }
7699 
7700 /*
7701  * Handle reinitialization of a tcp structure.
7702  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7703  */
7704 static void
7705 tcp_reinit(tcp_t *tcp)
7706 {
7707 	mblk_t	*mp;
7708 	int 	err;
7709 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7710 
7711 	TCP_STAT(tcps, tcp_reinit_calls);
7712 
7713 	/* tcp_reinit should never be called for detached tcp_t's */
7714 	ASSERT(tcp->tcp_listener == NULL);
7715 	ASSERT((tcp->tcp_family == AF_INET &&
7716 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7717 	    (tcp->tcp_family == AF_INET6 &&
7718 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7719 	    tcp->tcp_ipversion == IPV6_VERSION)));
7720 
7721 	/* Cancel outstanding timers */
7722 	tcp_timers_stop(tcp);
7723 
7724 	/*
7725 	 * Reset everything in the state vector, after updating global
7726 	 * MIB data from instance counters.
7727 	 */
7728 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7729 	tcp->tcp_ibsegs = 0;
7730 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7731 	tcp->tcp_obsegs = 0;
7732 
7733 	tcp_close_mpp(&tcp->tcp_xmit_head);
7734 	if (tcp->tcp_snd_zcopy_aware)
7735 		tcp_zcopy_notify(tcp);
7736 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7737 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7738 	mutex_enter(&tcp->tcp_non_sq_lock);
7739 	if (tcp->tcp_flow_stopped &&
7740 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7741 		tcp_clrqfull(tcp);
7742 	}
7743 	mutex_exit(&tcp->tcp_non_sq_lock);
7744 	tcp_close_mpp(&tcp->tcp_reass_head);
7745 	tcp->tcp_reass_tail = NULL;
7746 	if (tcp->tcp_rcv_list != NULL) {
7747 		/* Free b_next chain */
7748 		tcp_close_mpp(&tcp->tcp_rcv_list);
7749 		tcp->tcp_rcv_last_head = NULL;
7750 		tcp->tcp_rcv_last_tail = NULL;
7751 		tcp->tcp_rcv_cnt = 0;
7752 	}
7753 	tcp->tcp_rcv_last_tail = NULL;
7754 
7755 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7756 		freemsg(mp);
7757 		tcp->tcp_urp_mp = NULL;
7758 	}
7759 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7760 		freemsg(mp);
7761 		tcp->tcp_urp_mark_mp = NULL;
7762 	}
7763 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7764 		freeb(tcp->tcp_fused_sigurg_mp);
7765 		tcp->tcp_fused_sigurg_mp = NULL;
7766 	}
7767 
7768 	/*
7769 	 * Following is a union with two members which are
7770 	 * identical types and size so the following cleanup
7771 	 * is enough.
7772 	 */
7773 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7774 
7775 	CL_INET_DISCONNECT(tcp);
7776 
7777 	/*
7778 	 * The connection can't be on the tcp_time_wait_head list
7779 	 * since it is not detached.
7780 	 */
7781 	ASSERT(tcp->tcp_time_wait_next == NULL);
7782 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7783 	ASSERT(tcp->tcp_time_wait_expire == 0);
7784 
7785 	if (tcp->tcp_kssl_pending) {
7786 		tcp->tcp_kssl_pending = B_FALSE;
7787 
7788 		/* Don't reset if the initialized by bind. */
7789 		if (tcp->tcp_kssl_ent != NULL) {
7790 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7791 			    KSSL_NO_PROXY);
7792 		}
7793 	}
7794 	if (tcp->tcp_kssl_ctx != NULL) {
7795 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7796 		tcp->tcp_kssl_ctx = NULL;
7797 	}
7798 
7799 	/*
7800 	 * Reset/preserve other values
7801 	 */
7802 	tcp_reinit_values(tcp);
7803 	ipcl_hash_remove(tcp->tcp_connp);
7804 	conn_delete_ire(tcp->tcp_connp, NULL);
7805 	tcp_ipsec_cleanup(tcp);
7806 
7807 	if (tcp->tcp_conn_req_max != 0) {
7808 		/*
7809 		 * This is the case when a TLI program uses the same
7810 		 * transport end point to accept a connection.  This
7811 		 * makes the TCP both a listener and acceptor.  When
7812 		 * this connection is closed, we need to set the state
7813 		 * back to TCPS_LISTEN.  Make sure that the eager list
7814 		 * is reinitialized.
7815 		 *
7816 		 * Note that this stream is still bound to the four
7817 		 * tuples of the previous connection in IP.  If a new
7818 		 * SYN with different foreign address comes in, IP will
7819 		 * not find it and will send it to the global queue.  In
7820 		 * the global queue, TCP will do a tcp_lookup_listener()
7821 		 * to find this stream.  This works because this stream
7822 		 * is only removed from connected hash.
7823 		 *
7824 		 */
7825 		tcp->tcp_state = TCPS_LISTEN;
7826 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7827 		tcp->tcp_eager_next_drop_q0 = tcp;
7828 		tcp->tcp_eager_prev_drop_q0 = tcp;
7829 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7830 		if (tcp->tcp_family == AF_INET6) {
7831 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7832 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7833 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7834 		} else {
7835 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7836 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7837 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7838 		}
7839 	} else {
7840 		tcp->tcp_state = TCPS_BOUND;
7841 	}
7842 
7843 	/*
7844 	 * Initialize to default values
7845 	 * Can't fail since enough header template space already allocated
7846 	 * at open().
7847 	 */
7848 	err = tcp_init_values(tcp);
7849 	ASSERT(err == 0);
7850 	/* Restore state in tcp_tcph */
7851 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7852 	if (tcp->tcp_ipversion == IPV4_VERSION)
7853 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7854 	else
7855 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7856 	/*
7857 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7858 	 * since the lookup funcs can only lookup on tcp_t
7859 	 */
7860 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7861 
7862 	ASSERT(tcp->tcp_ptpbhn != NULL);
7863 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7864 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7865 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7866 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7867 }
7868 
7869 /*
7870  * Force values to zero that need be zero.
7871  * Do not touch values asociated with the BOUND or LISTEN state
7872  * since the connection will end up in that state after the reinit.
7873  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7874  * structure!
7875  */
7876 static void
7877 tcp_reinit_values(tcp)
7878 	tcp_t *tcp;
7879 {
7880 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7881 
7882 #ifndef	lint
7883 #define	DONTCARE(x)
7884 #define	PRESERVE(x)
7885 #else
7886 #define	DONTCARE(x)	((x) = (x))
7887 #define	PRESERVE(x)	((x) = (x))
7888 #endif	/* lint */
7889 
7890 	PRESERVE(tcp->tcp_bind_hash);
7891 	PRESERVE(tcp->tcp_ptpbhn);
7892 	PRESERVE(tcp->tcp_acceptor_hash);
7893 	PRESERVE(tcp->tcp_ptpahn);
7894 
7895 	/* Should be ASSERT NULL on these with new code! */
7896 	ASSERT(tcp->tcp_time_wait_next == NULL);
7897 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7898 	ASSERT(tcp->tcp_time_wait_expire == 0);
7899 	PRESERVE(tcp->tcp_state);
7900 	PRESERVE(tcp->tcp_rq);
7901 	PRESERVE(tcp->tcp_wq);
7902 
7903 	ASSERT(tcp->tcp_xmit_head == NULL);
7904 	ASSERT(tcp->tcp_xmit_last == NULL);
7905 	ASSERT(tcp->tcp_unsent == 0);
7906 	ASSERT(tcp->tcp_xmit_tail == NULL);
7907 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7908 
7909 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7910 	tcp->tcp_suna = 0;			/* Displayed in mib */
7911 	tcp->tcp_swnd = 0;
7912 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7913 
7914 	ASSERT(tcp->tcp_ibsegs == 0);
7915 	ASSERT(tcp->tcp_obsegs == 0);
7916 
7917 	if (tcp->tcp_iphc != NULL) {
7918 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7919 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7920 	}
7921 
7922 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7923 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7924 	DONTCARE(tcp->tcp_ipha);
7925 	DONTCARE(tcp->tcp_ip6h);
7926 	DONTCARE(tcp->tcp_ip_hdr_len);
7927 	DONTCARE(tcp->tcp_tcph);
7928 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7929 	tcp->tcp_valid_bits = 0;
7930 
7931 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7932 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7933 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7934 	tcp->tcp_last_rcv_lbolt = 0;
7935 
7936 	tcp->tcp_init_cwnd = 0;
7937 
7938 	tcp->tcp_urp_last_valid = 0;
7939 	tcp->tcp_hard_binding = 0;
7940 	tcp->tcp_hard_bound = 0;
7941 	PRESERVE(tcp->tcp_cred);
7942 	PRESERVE(tcp->tcp_cpid);
7943 	PRESERVE(tcp->tcp_open_time);
7944 	PRESERVE(tcp->tcp_exclbind);
7945 
7946 	tcp->tcp_fin_acked = 0;
7947 	tcp->tcp_fin_rcvd = 0;
7948 	tcp->tcp_fin_sent = 0;
7949 	tcp->tcp_ordrel_done = 0;
7950 
7951 	tcp->tcp_debug = 0;
7952 	tcp->tcp_dontroute = 0;
7953 	tcp->tcp_broadcast = 0;
7954 
7955 	tcp->tcp_useloopback = 0;
7956 	tcp->tcp_reuseaddr = 0;
7957 	tcp->tcp_oobinline = 0;
7958 	tcp->tcp_dgram_errind = 0;
7959 
7960 	tcp->tcp_detached = 0;
7961 	tcp->tcp_bind_pending = 0;
7962 	tcp->tcp_unbind_pending = 0;
7963 	tcp->tcp_deferred_clean_death = 0;
7964 
7965 	tcp->tcp_snd_ws_ok = B_FALSE;
7966 	tcp->tcp_snd_ts_ok = B_FALSE;
7967 	tcp->tcp_linger = 0;
7968 	tcp->tcp_ka_enabled = 0;
7969 	tcp->tcp_zero_win_probe = 0;
7970 
7971 	tcp->tcp_loopback = 0;
7972 	tcp->tcp_localnet = 0;
7973 	tcp->tcp_syn_defense = 0;
7974 	tcp->tcp_set_timer = 0;
7975 
7976 	tcp->tcp_active_open = 0;
7977 	ASSERT(tcp->tcp_timeout == B_FALSE);
7978 	tcp->tcp_rexmit = B_FALSE;
7979 	tcp->tcp_xmit_zc_clean = B_FALSE;
7980 
7981 	tcp->tcp_snd_sack_ok = B_FALSE;
7982 	PRESERVE(tcp->tcp_recvdstaddr);
7983 	tcp->tcp_hwcksum = B_FALSE;
7984 
7985 	tcp->tcp_ire_ill_check_done = B_FALSE;
7986 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7987 
7988 	tcp->tcp_mdt = B_FALSE;
7989 	tcp->tcp_mdt_hdr_head = 0;
7990 	tcp->tcp_mdt_hdr_tail = 0;
7991 
7992 	tcp->tcp_conn_def_q0 = 0;
7993 	tcp->tcp_ip_forward_progress = B_FALSE;
7994 	tcp->tcp_anon_priv_bind = 0;
7995 	tcp->tcp_ecn_ok = B_FALSE;
7996 
7997 	tcp->tcp_cwr = B_FALSE;
7998 	tcp->tcp_ecn_echo_on = B_FALSE;
7999 
8000 	if (tcp->tcp_sack_info != NULL) {
8001 		if (tcp->tcp_notsack_list != NULL) {
8002 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8003 		}
8004 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8005 		tcp->tcp_sack_info = NULL;
8006 	}
8007 
8008 	tcp->tcp_rcv_ws = 0;
8009 	tcp->tcp_snd_ws = 0;
8010 	tcp->tcp_ts_recent = 0;
8011 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8012 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8013 	tcp->tcp_if_mtu = 0;
8014 
8015 	ASSERT(tcp->tcp_reass_head == NULL);
8016 	ASSERT(tcp->tcp_reass_tail == NULL);
8017 
8018 	tcp->tcp_cwnd_cnt = 0;
8019 
8020 	ASSERT(tcp->tcp_rcv_list == NULL);
8021 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8022 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8023 	ASSERT(tcp->tcp_rcv_cnt == 0);
8024 
8025 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8026 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8027 	tcp->tcp_csuna = 0;
8028 
8029 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8030 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8031 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8032 	tcp->tcp_rtt_update = 0;
8033 
8034 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8035 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8036 
8037 	tcp->tcp_rack = 0;			/* Displayed in mib */
8038 	tcp->tcp_rack_cnt = 0;
8039 	tcp->tcp_rack_cur_max = 0;
8040 	tcp->tcp_rack_abs_max = 0;
8041 
8042 	tcp->tcp_max_swnd = 0;
8043 
8044 	ASSERT(tcp->tcp_listener == NULL);
8045 
8046 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8047 
8048 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8049 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8050 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8051 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8052 
8053 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8054 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8055 	PRESERVE(tcp->tcp_conn_req_max);
8056 	PRESERVE(tcp->tcp_conn_req_seqnum);
8057 
8058 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8059 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8060 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8061 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8062 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8063 
8064 	tcp->tcp_lingertime = 0;
8065 
8066 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8067 	ASSERT(tcp->tcp_urp_mp == NULL);
8068 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8069 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8070 
8071 	ASSERT(tcp->tcp_eager_next_q == NULL);
8072 	ASSERT(tcp->tcp_eager_last_q == NULL);
8073 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8074 	    tcp->tcp_eager_prev_q0 == NULL) ||
8075 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8076 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8077 
8078 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8079 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8080 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8081 
8082 	tcp->tcp_client_errno = 0;
8083 
8084 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8085 
8086 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8087 
8088 	PRESERVE(tcp->tcp_bound_source_v6);
8089 	tcp->tcp_last_sent_len = 0;
8090 	tcp->tcp_dupack_cnt = 0;
8091 
8092 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8093 	PRESERVE(tcp->tcp_lport);
8094 
8095 	PRESERVE(tcp->tcp_acceptor_lockp);
8096 
8097 	ASSERT(tcp->tcp_ordrelid == 0);
8098 	PRESERVE(tcp->tcp_acceptor_id);
8099 	DONTCARE(tcp->tcp_ipsec_overhead);
8100 
8101 	/*
8102 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8103 	 * in tcp structure and now tracing), Re-initialize all
8104 	 * members of tcp_traceinfo.
8105 	 */
8106 	if (tcp->tcp_tracebuf != NULL) {
8107 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8108 	}
8109 
8110 	PRESERVE(tcp->tcp_family);
8111 	if (tcp->tcp_family == AF_INET6) {
8112 		tcp->tcp_ipversion = IPV6_VERSION;
8113 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8114 	} else {
8115 		tcp->tcp_ipversion = IPV4_VERSION;
8116 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8117 	}
8118 
8119 	tcp->tcp_bound_if = 0;
8120 	tcp->tcp_ipv6_recvancillary = 0;
8121 	tcp->tcp_recvifindex = 0;
8122 	tcp->tcp_recvhops = 0;
8123 	tcp->tcp_closed = 0;
8124 	tcp->tcp_cleandeathtag = 0;
8125 	if (tcp->tcp_hopopts != NULL) {
8126 		mi_free(tcp->tcp_hopopts);
8127 		tcp->tcp_hopopts = NULL;
8128 		tcp->tcp_hopoptslen = 0;
8129 	}
8130 	ASSERT(tcp->tcp_hopoptslen == 0);
8131 	if (tcp->tcp_dstopts != NULL) {
8132 		mi_free(tcp->tcp_dstopts);
8133 		tcp->tcp_dstopts = NULL;
8134 		tcp->tcp_dstoptslen = 0;
8135 	}
8136 	ASSERT(tcp->tcp_dstoptslen == 0);
8137 	if (tcp->tcp_rtdstopts != NULL) {
8138 		mi_free(tcp->tcp_rtdstopts);
8139 		tcp->tcp_rtdstopts = NULL;
8140 		tcp->tcp_rtdstoptslen = 0;
8141 	}
8142 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8143 	if (tcp->tcp_rthdr != NULL) {
8144 		mi_free(tcp->tcp_rthdr);
8145 		tcp->tcp_rthdr = NULL;
8146 		tcp->tcp_rthdrlen = 0;
8147 	}
8148 	ASSERT(tcp->tcp_rthdrlen == 0);
8149 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8150 
8151 	/* Reset fusion-related fields */
8152 	tcp->tcp_fused = B_FALSE;
8153 	tcp->tcp_unfusable = B_FALSE;
8154 	tcp->tcp_fused_sigurg = B_FALSE;
8155 	tcp->tcp_direct_sockfs = B_FALSE;
8156 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8157 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8158 	tcp->tcp_loopback_peer = NULL;
8159 	tcp->tcp_fuse_rcv_hiwater = 0;
8160 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8161 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8162 
8163 	tcp->tcp_lso = B_FALSE;
8164 
8165 	tcp->tcp_in_ack_unsent = 0;
8166 	tcp->tcp_cork = B_FALSE;
8167 	tcp->tcp_tconnind_started = B_FALSE;
8168 
8169 	PRESERVE(tcp->tcp_squeue_bytes);
8170 
8171 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8172 	ASSERT(!tcp->tcp_kssl_pending);
8173 	PRESERVE(tcp->tcp_kssl_ent);
8174 
8175 	tcp->tcp_closemp_used = B_FALSE;
8176 
8177 #ifdef DEBUG
8178 	DONTCARE(tcp->tcmp_stk[0]);
8179 #endif
8180 
8181 
8182 #undef	DONTCARE
8183 #undef	PRESERVE
8184 }
8185 
8186 /*
8187  * Allocate necessary resources and initialize state vector.
8188  * Guaranteed not to fail so that when an error is returned,
8189  * the caller doesn't need to do any additional cleanup.
8190  */
8191 int
8192 tcp_init(tcp_t *tcp, queue_t *q)
8193 {
8194 	int	err;
8195 
8196 	tcp->tcp_rq = q;
8197 	tcp->tcp_wq = WR(q);
8198 	tcp->tcp_state = TCPS_IDLE;
8199 	if ((err = tcp_init_values(tcp)) != 0)
8200 		tcp_timers_stop(tcp);
8201 	return (err);
8202 }
8203 
8204 static int
8205 tcp_init_values(tcp_t *tcp)
8206 {
8207 	int	err;
8208 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8209 
8210 	ASSERT((tcp->tcp_family == AF_INET &&
8211 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8212 	    (tcp->tcp_family == AF_INET6 &&
8213 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8214 	    tcp->tcp_ipversion == IPV6_VERSION)));
8215 
8216 	/*
8217 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8218 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8219 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8220 	 * during first few transmissions of a connection as seen in slow
8221 	 * links.
8222 	 */
8223 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8224 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8225 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8226 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8227 	    tcps->tcps_conn_grace_period;
8228 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8229 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8230 	tcp->tcp_timer_backoff = 0;
8231 	tcp->tcp_ms_we_have_waited = 0;
8232 	tcp->tcp_last_recv_time = lbolt;
8233 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8234 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8235 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8236 
8237 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8238 
8239 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8240 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8241 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8242 	/*
8243 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8244 	 * passive open.
8245 	 */
8246 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8247 
8248 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8249 
8250 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8251 
8252 	tcp->tcp_mdt_hdr_head = 0;
8253 	tcp->tcp_mdt_hdr_tail = 0;
8254 
8255 	/* Reset fusion-related fields */
8256 	tcp->tcp_fused = B_FALSE;
8257 	tcp->tcp_unfusable = B_FALSE;
8258 	tcp->tcp_fused_sigurg = B_FALSE;
8259 	tcp->tcp_direct_sockfs = B_FALSE;
8260 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8261 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8262 	tcp->tcp_loopback_peer = NULL;
8263 	tcp->tcp_fuse_rcv_hiwater = 0;
8264 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8265 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8266 
8267 	/* Initialize the header template */
8268 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8269 		err = tcp_header_init_ipv4(tcp);
8270 	} else {
8271 		err = tcp_header_init_ipv6(tcp);
8272 	}
8273 	if (err)
8274 		return (err);
8275 
8276 	/*
8277 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8278 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8279 	 */
8280 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8281 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8282 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8283 
8284 	tcp->tcp_cork = B_FALSE;
8285 	/*
8286 	 * Init the tcp_debug option.  This value determines whether TCP
8287 	 * calls strlog() to print out debug messages.  Doing this
8288 	 * initialization here means that this value is not inherited thru
8289 	 * tcp_reinit().
8290 	 */
8291 	tcp->tcp_debug = tcps->tcps_dbg;
8292 
8293 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8294 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8295 
8296 	return (0);
8297 }
8298 
8299 /*
8300  * Initialize the IPv4 header. Loses any record of any IP options.
8301  */
8302 static int
8303 tcp_header_init_ipv4(tcp_t *tcp)
8304 {
8305 	tcph_t		*tcph;
8306 	uint32_t	sum;
8307 	conn_t		*connp;
8308 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8309 
8310 	/*
8311 	 * This is a simple initialization. If there's
8312 	 * already a template, it should never be too small,
8313 	 * so reuse it.  Otherwise, allocate space for the new one.
8314 	 */
8315 	if (tcp->tcp_iphc == NULL) {
8316 		ASSERT(tcp->tcp_iphc_len == 0);
8317 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8318 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8319 		if (tcp->tcp_iphc == NULL) {
8320 			tcp->tcp_iphc_len = 0;
8321 			return (ENOMEM);
8322 		}
8323 	}
8324 
8325 	/* options are gone; may need a new label */
8326 	connp = tcp->tcp_connp;
8327 	connp->conn_mlp_type = mlptSingle;
8328 	connp->conn_ulp_labeled = !is_system_labeled();
8329 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8330 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8331 	tcp->tcp_ip6h = NULL;
8332 	tcp->tcp_ipversion = IPV4_VERSION;
8333 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8334 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8335 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8336 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8337 	tcp->tcp_ipha->ipha_version_and_hdr_length
8338 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8339 	tcp->tcp_ipha->ipha_ident = 0;
8340 
8341 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8342 	tcp->tcp_tos = 0;
8343 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8344 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8345 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8346 
8347 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8348 	tcp->tcp_tcph = tcph;
8349 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8350 	/*
8351 	 * IP wants our header length in the checksum field to
8352 	 * allow it to perform a single pseudo-header+checksum
8353 	 * calculation on behalf of TCP.
8354 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8355 	 */
8356 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8357 	sum = (sum >> 16) + (sum & 0xFFFF);
8358 	U16_TO_ABE16(sum, tcph->th_sum);
8359 	return (0);
8360 }
8361 
8362 /*
8363  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8364  */
8365 static int
8366 tcp_header_init_ipv6(tcp_t *tcp)
8367 {
8368 	tcph_t	*tcph;
8369 	uint32_t	sum;
8370 	conn_t	*connp;
8371 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8372 
8373 	/*
8374 	 * This is a simple initialization. If there's
8375 	 * already a template, it should never be too small,
8376 	 * so reuse it. Otherwise, allocate space for the new one.
8377 	 * Ensure that there is enough space to "downgrade" the tcp_t
8378 	 * to an IPv4 tcp_t. This requires having space for a full load
8379 	 * of IPv4 options, as well as a full load of TCP options
8380 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8381 	 * than a v6 header and a TCP header with a full load of TCP options
8382 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8383 	 * We want to avoid reallocation in the "downgraded" case when
8384 	 * processing outbound IPv4 options.
8385 	 */
8386 	if (tcp->tcp_iphc == NULL) {
8387 		ASSERT(tcp->tcp_iphc_len == 0);
8388 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8389 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8390 		if (tcp->tcp_iphc == NULL) {
8391 			tcp->tcp_iphc_len = 0;
8392 			return (ENOMEM);
8393 		}
8394 	}
8395 
8396 	/* options are gone; may need a new label */
8397 	connp = tcp->tcp_connp;
8398 	connp->conn_mlp_type = mlptSingle;
8399 	connp->conn_ulp_labeled = !is_system_labeled();
8400 
8401 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8402 	tcp->tcp_ipversion = IPV6_VERSION;
8403 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8404 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8405 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8406 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8407 	tcp->tcp_ipha = NULL;
8408 
8409 	/* Initialize the header template */
8410 
8411 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8412 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8413 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8414 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8415 
8416 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8417 	tcp->tcp_tcph = tcph;
8418 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8419 	/*
8420 	 * IP wants our header length in the checksum field to
8421 	 * allow it to perform a single psuedo-header+checksum
8422 	 * calculation on behalf of TCP.
8423 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8424 	 */
8425 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8426 	sum = (sum >> 16) + (sum & 0xFFFF);
8427 	U16_TO_ABE16(sum, tcph->th_sum);
8428 	return (0);
8429 }
8430 
8431 /* At minimum we need 8 bytes in the TCP header for the lookup */
8432 #define	ICMP_MIN_TCP_HDR	8
8433 
8434 /*
8435  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8436  * passed up by IP. The message is always received on the correct tcp_t.
8437  * Assumes that IP has pulled up everything up to and including the ICMP header.
8438  */
8439 void
8440 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8441 {
8442 	icmph_t *icmph;
8443 	ipha_t	*ipha;
8444 	int	iph_hdr_length;
8445 	tcph_t	*tcph;
8446 	boolean_t ipsec_mctl = B_FALSE;
8447 	boolean_t secure;
8448 	mblk_t *first_mp = mp;
8449 	uint32_t new_mss;
8450 	uint32_t ratio;
8451 	size_t mp_size = MBLKL(mp);
8452 	uint32_t seg_seq;
8453 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8454 
8455 	/* Assume IP provides aligned packets - otherwise toss */
8456 	if (!OK_32PTR(mp->b_rptr)) {
8457 		freemsg(mp);
8458 		return;
8459 	}
8460 
8461 	/*
8462 	 * Since ICMP errors are normal data marked with M_CTL when sent
8463 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8464 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8465 	 */
8466 	if ((mp_size == sizeof (ipsec_info_t)) &&
8467 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8468 		ASSERT(mp->b_cont != NULL);
8469 		mp = mp->b_cont;
8470 		/* IP should have done this */
8471 		ASSERT(OK_32PTR(mp->b_rptr));
8472 		mp_size = MBLKL(mp);
8473 		ipsec_mctl = B_TRUE;
8474 	}
8475 
8476 	/*
8477 	 * Verify that we have a complete outer IP header. If not, drop it.
8478 	 */
8479 	if (mp_size < sizeof (ipha_t)) {
8480 noticmpv4:
8481 		freemsg(first_mp);
8482 		return;
8483 	}
8484 
8485 	ipha = (ipha_t *)mp->b_rptr;
8486 	/*
8487 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8488 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8489 	 */
8490 	switch (IPH_HDR_VERSION(ipha)) {
8491 	case IPV6_VERSION:
8492 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8493 		return;
8494 	case IPV4_VERSION:
8495 		break;
8496 	default:
8497 		goto noticmpv4;
8498 	}
8499 
8500 	/* Skip past the outer IP and ICMP headers */
8501 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8502 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8503 	/*
8504 	 * If we don't have the correct outer IP header length or if the ULP
8505 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8506 	 * send it upstream.
8507 	 */
8508 	if (iph_hdr_length < sizeof (ipha_t) ||
8509 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8510 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8511 		goto noticmpv4;
8512 	}
8513 	ipha = (ipha_t *)&icmph[1];
8514 
8515 	/* Skip past the inner IP and find the ULP header */
8516 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8517 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8518 	/*
8519 	 * If we don't have the correct inner IP header length or if the ULP
8520 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8521 	 * bytes of TCP header, drop it.
8522 	 */
8523 	if (iph_hdr_length < sizeof (ipha_t) ||
8524 	    ipha->ipha_protocol != IPPROTO_TCP ||
8525 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8526 		goto noticmpv4;
8527 	}
8528 
8529 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8530 		if (ipsec_mctl) {
8531 			secure = ipsec_in_is_secure(first_mp);
8532 		} else {
8533 			secure = B_FALSE;
8534 		}
8535 		if (secure) {
8536 			/*
8537 			 * If we are willing to accept this in clear
8538 			 * we don't have to verify policy.
8539 			 */
8540 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8541 				if (!tcp_check_policy(tcp, first_mp,
8542 				    ipha, NULL, secure, ipsec_mctl)) {
8543 					/*
8544 					 * tcp_check_policy called
8545 					 * ip_drop_packet() on failure.
8546 					 */
8547 					return;
8548 				}
8549 			}
8550 		}
8551 	} else if (ipsec_mctl) {
8552 		/*
8553 		 * This is a hard_bound connection. IP has already
8554 		 * verified policy. We don't have to do it again.
8555 		 */
8556 		freeb(first_mp);
8557 		first_mp = mp;
8558 		ipsec_mctl = B_FALSE;
8559 	}
8560 
8561 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8562 	/*
8563 	 * TCP SHOULD check that the TCP sequence number contained in
8564 	 * payload of the ICMP error message is within the range
8565 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8566 	 */
8567 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8568 		/*
8569 		 * If the ICMP message is bogus, should we kill the
8570 		 * connection, or should we just drop the bogus ICMP
8571 		 * message? It would probably make more sense to just
8572 		 * drop the message so that if this one managed to get
8573 		 * in, the real connection should not suffer.
8574 		 */
8575 		goto noticmpv4;
8576 	}
8577 
8578 	switch (icmph->icmph_type) {
8579 	case ICMP_DEST_UNREACHABLE:
8580 		switch (icmph->icmph_code) {
8581 		case ICMP_FRAGMENTATION_NEEDED:
8582 			/*
8583 			 * Reduce the MSS based on the new MTU.  This will
8584 			 * eliminate any fragmentation locally.
8585 			 * N.B.  There may well be some funny side-effects on
8586 			 * the local send policy and the remote receive policy.
8587 			 * Pending further research, we provide
8588 			 * tcp_ignore_path_mtu just in case this proves
8589 			 * disastrous somewhere.
8590 			 *
8591 			 * After updating the MSS, retransmit part of the
8592 			 * dropped segment using the new mss by calling
8593 			 * tcp_wput_data().  Need to adjust all those
8594 			 * params to make sure tcp_wput_data() work properly.
8595 			 */
8596 			if (tcps->tcps_ignore_path_mtu)
8597 				break;
8598 
8599 			/*
8600 			 * Decrease the MSS by time stamp options
8601 			 * IP options and IPSEC options. tcp_hdr_len
8602 			 * includes time stamp option and IP option
8603 			 * length.
8604 			 */
8605 
8606 			new_mss = ntohs(icmph->icmph_du_mtu) -
8607 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8608 
8609 			/*
8610 			 * Only update the MSS if the new one is
8611 			 * smaller than the previous one.  This is
8612 			 * to avoid problems when getting multiple
8613 			 * ICMP errors for the same MTU.
8614 			 */
8615 			if (new_mss >= tcp->tcp_mss)
8616 				break;
8617 
8618 			/*
8619 			 * Stop doing PMTU if new_mss is less than 68
8620 			 * or less than tcp_mss_min.
8621 			 * The value 68 comes from rfc 1191.
8622 			 */
8623 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8624 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8625 				    0;
8626 
8627 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8628 			ASSERT(ratio >= 1);
8629 			tcp_mss_set(tcp, new_mss, B_TRUE);
8630 
8631 			/*
8632 			 * Make sure we have something to
8633 			 * send.
8634 			 */
8635 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8636 			    (tcp->tcp_xmit_head != NULL)) {
8637 				/*
8638 				 * Shrink tcp_cwnd in
8639 				 * proportion to the old MSS/new MSS.
8640 				 */
8641 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8642 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8643 				    (tcp->tcp_unsent == 0)) {
8644 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8645 				} else {
8646 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8647 				}
8648 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8649 				tcp->tcp_rexmit = B_TRUE;
8650 				tcp->tcp_dupack_cnt = 0;
8651 				tcp->tcp_snd_burst = TCP_CWND_SS;
8652 				tcp_ss_rexmit(tcp);
8653 			}
8654 			break;
8655 		case ICMP_PORT_UNREACHABLE:
8656 		case ICMP_PROTOCOL_UNREACHABLE:
8657 			switch (tcp->tcp_state) {
8658 			case TCPS_SYN_SENT:
8659 			case TCPS_SYN_RCVD:
8660 				/*
8661 				 * ICMP can snipe away incipient
8662 				 * TCP connections as long as
8663 				 * seq number is same as initial
8664 				 * send seq number.
8665 				 */
8666 				if (seg_seq == tcp->tcp_iss) {
8667 					(void) tcp_clean_death(tcp,
8668 					    ECONNREFUSED, 6);
8669 				}
8670 				break;
8671 			}
8672 			break;
8673 		case ICMP_HOST_UNREACHABLE:
8674 		case ICMP_NET_UNREACHABLE:
8675 			/* Record the error in case we finally time out. */
8676 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8677 				tcp->tcp_client_errno = EHOSTUNREACH;
8678 			else
8679 				tcp->tcp_client_errno = ENETUNREACH;
8680 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8681 				if (tcp->tcp_listener != NULL &&
8682 				    tcp->tcp_listener->tcp_syn_defense) {
8683 					/*
8684 					 * Ditch the half-open connection if we
8685 					 * suspect a SYN attack is under way.
8686 					 */
8687 					tcp_ip_ire_mark_advice(tcp);
8688 					(void) tcp_clean_death(tcp,
8689 					    tcp->tcp_client_errno, 7);
8690 				}
8691 			}
8692 			break;
8693 		default:
8694 			break;
8695 		}
8696 		break;
8697 	case ICMP_SOURCE_QUENCH: {
8698 		/*
8699 		 * use a global boolean to control
8700 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8701 		 * The default is false.
8702 		 */
8703 		if (tcp_icmp_source_quench) {
8704 			/*
8705 			 * Reduce the sending rate as if we got a
8706 			 * retransmit timeout
8707 			 */
8708 			uint32_t npkt;
8709 
8710 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8711 			    tcp->tcp_mss;
8712 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8713 			tcp->tcp_cwnd = tcp->tcp_mss;
8714 			tcp->tcp_cwnd_cnt = 0;
8715 		}
8716 		break;
8717 	}
8718 	}
8719 	freemsg(first_mp);
8720 }
8721 
8722 /*
8723  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8724  * error messages passed up by IP.
8725  * Assumes that IP has pulled up all the extension headers as well
8726  * as the ICMPv6 header.
8727  */
8728 static void
8729 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8730 {
8731 	icmp6_t *icmp6;
8732 	ip6_t	*ip6h;
8733 	uint16_t	iph_hdr_length;
8734 	tcpha_t	*tcpha;
8735 	uint8_t	*nexthdrp;
8736 	uint32_t new_mss;
8737 	uint32_t ratio;
8738 	boolean_t secure;
8739 	mblk_t *first_mp = mp;
8740 	size_t mp_size;
8741 	uint32_t seg_seq;
8742 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8743 
8744 	/*
8745 	 * The caller has determined if this is an IPSEC_IN packet and
8746 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8747 	 */
8748 	if (ipsec_mctl)
8749 		mp = mp->b_cont;
8750 
8751 	mp_size = MBLKL(mp);
8752 
8753 	/*
8754 	 * Verify that we have a complete IP header. If not, send it upstream.
8755 	 */
8756 	if (mp_size < sizeof (ip6_t)) {
8757 noticmpv6:
8758 		freemsg(first_mp);
8759 		return;
8760 	}
8761 
8762 	/*
8763 	 * Verify this is an ICMPV6 packet, else send it upstream.
8764 	 */
8765 	ip6h = (ip6_t *)mp->b_rptr;
8766 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8767 		iph_hdr_length = IPV6_HDR_LEN;
8768 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8769 	    &nexthdrp) ||
8770 	    *nexthdrp != IPPROTO_ICMPV6) {
8771 		goto noticmpv6;
8772 	}
8773 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8774 	ip6h = (ip6_t *)&icmp6[1];
8775 	/*
8776 	 * Verify if we have a complete ICMP and inner IP header.
8777 	 */
8778 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8779 		goto noticmpv6;
8780 
8781 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8782 		goto noticmpv6;
8783 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8784 	/*
8785 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8786 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8787 	 * packet.
8788 	 */
8789 	if ((*nexthdrp != IPPROTO_TCP) ||
8790 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8791 		goto noticmpv6;
8792 	}
8793 
8794 	/*
8795 	 * ICMP errors come on the right queue or come on
8796 	 * listener/global queue for detached connections and
8797 	 * get switched to the right queue. If it comes on the
8798 	 * right queue, policy check has already been done by IP
8799 	 * and thus free the first_mp without verifying the policy.
8800 	 * If it has come for a non-hard bound connection, we need
8801 	 * to verify policy as IP may not have done it.
8802 	 */
8803 	if (!tcp->tcp_hard_bound) {
8804 		if (ipsec_mctl) {
8805 			secure = ipsec_in_is_secure(first_mp);
8806 		} else {
8807 			secure = B_FALSE;
8808 		}
8809 		if (secure) {
8810 			/*
8811 			 * If we are willing to accept this in clear
8812 			 * we don't have to verify policy.
8813 			 */
8814 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8815 				if (!tcp_check_policy(tcp, first_mp,
8816 				    NULL, ip6h, secure, ipsec_mctl)) {
8817 					/*
8818 					 * tcp_check_policy called
8819 					 * ip_drop_packet() on failure.
8820 					 */
8821 					return;
8822 				}
8823 			}
8824 		}
8825 	} else if (ipsec_mctl) {
8826 		/*
8827 		 * This is a hard_bound connection. IP has already
8828 		 * verified policy. We don't have to do it again.
8829 		 */
8830 		freeb(first_mp);
8831 		first_mp = mp;
8832 		ipsec_mctl = B_FALSE;
8833 	}
8834 
8835 	seg_seq = ntohl(tcpha->tha_seq);
8836 	/*
8837 	 * TCP SHOULD check that the TCP sequence number contained in
8838 	 * payload of the ICMP error message is within the range
8839 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8840 	 */
8841 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8842 		/*
8843 		 * If the ICMP message is bogus, should we kill the
8844 		 * connection, or should we just drop the bogus ICMP
8845 		 * message? It would probably make more sense to just
8846 		 * drop the message so that if this one managed to get
8847 		 * in, the real connection should not suffer.
8848 		 */
8849 		goto noticmpv6;
8850 	}
8851 
8852 	switch (icmp6->icmp6_type) {
8853 	case ICMP6_PACKET_TOO_BIG:
8854 		/*
8855 		 * Reduce the MSS based on the new MTU.  This will
8856 		 * eliminate any fragmentation locally.
8857 		 * N.B.  There may well be some funny side-effects on
8858 		 * the local send policy and the remote receive policy.
8859 		 * Pending further research, we provide
8860 		 * tcp_ignore_path_mtu just in case this proves
8861 		 * disastrous somewhere.
8862 		 *
8863 		 * After updating the MSS, retransmit part of the
8864 		 * dropped segment using the new mss by calling
8865 		 * tcp_wput_data().  Need to adjust all those
8866 		 * params to make sure tcp_wput_data() work properly.
8867 		 */
8868 		if (tcps->tcps_ignore_path_mtu)
8869 			break;
8870 
8871 		/*
8872 		 * Decrease the MSS by time stamp options
8873 		 * IP options and IPSEC options. tcp_hdr_len
8874 		 * includes time stamp option and IP option
8875 		 * length.
8876 		 */
8877 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8878 		    tcp->tcp_ipsec_overhead;
8879 
8880 		/*
8881 		 * Only update the MSS if the new one is
8882 		 * smaller than the previous one.  This is
8883 		 * to avoid problems when getting multiple
8884 		 * ICMP errors for the same MTU.
8885 		 */
8886 		if (new_mss >= tcp->tcp_mss)
8887 			break;
8888 
8889 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8890 		ASSERT(ratio >= 1);
8891 		tcp_mss_set(tcp, new_mss, B_TRUE);
8892 
8893 		/*
8894 		 * Make sure we have something to
8895 		 * send.
8896 		 */
8897 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8898 		    (tcp->tcp_xmit_head != NULL)) {
8899 			/*
8900 			 * Shrink tcp_cwnd in
8901 			 * proportion to the old MSS/new MSS.
8902 			 */
8903 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8904 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8905 			    (tcp->tcp_unsent == 0)) {
8906 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8907 			} else {
8908 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8909 			}
8910 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8911 			tcp->tcp_rexmit = B_TRUE;
8912 			tcp->tcp_dupack_cnt = 0;
8913 			tcp->tcp_snd_burst = TCP_CWND_SS;
8914 			tcp_ss_rexmit(tcp);
8915 		}
8916 		break;
8917 
8918 	case ICMP6_DST_UNREACH:
8919 		switch (icmp6->icmp6_code) {
8920 		case ICMP6_DST_UNREACH_NOPORT:
8921 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8922 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8923 			    (seg_seq == tcp->tcp_iss)) {
8924 				(void) tcp_clean_death(tcp,
8925 				    ECONNREFUSED, 8);
8926 			}
8927 			break;
8928 
8929 		case ICMP6_DST_UNREACH_ADMIN:
8930 		case ICMP6_DST_UNREACH_NOROUTE:
8931 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8932 		case ICMP6_DST_UNREACH_ADDR:
8933 			/* Record the error in case we finally time out. */
8934 			tcp->tcp_client_errno = EHOSTUNREACH;
8935 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8936 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8937 			    (seg_seq == tcp->tcp_iss)) {
8938 				if (tcp->tcp_listener != NULL &&
8939 				    tcp->tcp_listener->tcp_syn_defense) {
8940 					/*
8941 					 * Ditch the half-open connection if we
8942 					 * suspect a SYN attack is under way.
8943 					 */
8944 					tcp_ip_ire_mark_advice(tcp);
8945 					(void) tcp_clean_death(tcp,
8946 					    tcp->tcp_client_errno, 9);
8947 				}
8948 			}
8949 
8950 
8951 			break;
8952 		default:
8953 			break;
8954 		}
8955 		break;
8956 
8957 	case ICMP6_PARAM_PROB:
8958 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8959 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8960 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8961 		    (uchar_t *)nexthdrp) {
8962 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8963 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8964 				(void) tcp_clean_death(tcp,
8965 				    ECONNREFUSED, 10);
8966 			}
8967 			break;
8968 		}
8969 		break;
8970 
8971 	case ICMP6_TIME_EXCEEDED:
8972 	default:
8973 		break;
8974 	}
8975 	freemsg(first_mp);
8976 }
8977 
8978 /*
8979  * IP recognizes seven kinds of bind requests:
8980  *
8981  * - A zero-length address binds only to the protocol number.
8982  *
8983  * - A 4-byte address is treated as a request to
8984  * validate that the address is a valid local IPv4
8985  * address, appropriate for an application to bind to.
8986  * IP does the verification, but does not make any note
8987  * of the address at this time.
8988  *
8989  * - A 16-byte address contains is treated as a request
8990  * to validate a local IPv6 address, as the 4-byte
8991  * address case above.
8992  *
8993  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8994  * use it for the inbound fanout of packets.
8995  *
8996  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8997  * use it for the inbound fanout of packets.
8998  *
8999  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9000  * information consisting of local and remote addresses
9001  * and ports.  In this case, the addresses are both
9002  * validated as appropriate for this operation, and, if
9003  * so, the information is retained for use in the
9004  * inbound fanout.
9005  *
9006  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9007  * fanout information, like the 12-byte case above.
9008  *
9009  * IP will also fill in the IRE request mblk with information
9010  * regarding our peer.  In all cases, we notify IP of our protocol
9011  * type by appending a single protocol byte to the bind request.
9012  */
9013 static mblk_t *
9014 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9015 {
9016 	char	*cp;
9017 	mblk_t	*mp;
9018 	struct T_bind_req *tbr;
9019 	ipa_conn_t	*ac;
9020 	ipa6_conn_t	*ac6;
9021 	sin_t		*sin;
9022 	sin6_t		*sin6;
9023 
9024 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9025 	ASSERT((tcp->tcp_family == AF_INET &&
9026 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9027 	    (tcp->tcp_family == AF_INET6 &&
9028 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9029 	    tcp->tcp_ipversion == IPV6_VERSION)));
9030 
9031 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9032 	if (!mp)
9033 		return (mp);
9034 	mp->b_datap->db_type = M_PROTO;
9035 	tbr = (struct T_bind_req *)mp->b_rptr;
9036 	tbr->PRIM_type = bind_prim;
9037 	tbr->ADDR_offset = sizeof (*tbr);
9038 	tbr->CONIND_number = 0;
9039 	tbr->ADDR_length = addr_length;
9040 	cp = (char *)&tbr[1];
9041 	switch (addr_length) {
9042 	case sizeof (ipa_conn_t):
9043 		ASSERT(tcp->tcp_family == AF_INET);
9044 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9045 
9046 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9047 		if (mp->b_cont == NULL) {
9048 			freemsg(mp);
9049 			return (NULL);
9050 		}
9051 		mp->b_cont->b_wptr += sizeof (ire_t);
9052 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9053 
9054 		/* cp known to be 32 bit aligned */
9055 		ac = (ipa_conn_t *)cp;
9056 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9057 		ac->ac_faddr = tcp->tcp_remote;
9058 		ac->ac_fport = tcp->tcp_fport;
9059 		ac->ac_lport = tcp->tcp_lport;
9060 		tcp->tcp_hard_binding = 1;
9061 		break;
9062 
9063 	case sizeof (ipa6_conn_t):
9064 		ASSERT(tcp->tcp_family == AF_INET6);
9065 
9066 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9067 		if (mp->b_cont == NULL) {
9068 			freemsg(mp);
9069 			return (NULL);
9070 		}
9071 		mp->b_cont->b_wptr += sizeof (ire_t);
9072 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9073 
9074 		/* cp known to be 32 bit aligned */
9075 		ac6 = (ipa6_conn_t *)cp;
9076 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9077 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9078 			    &ac6->ac6_laddr);
9079 		} else {
9080 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9081 		}
9082 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9083 		ac6->ac6_fport = tcp->tcp_fport;
9084 		ac6->ac6_lport = tcp->tcp_lport;
9085 		tcp->tcp_hard_binding = 1;
9086 		break;
9087 
9088 	case sizeof (sin_t):
9089 		/*
9090 		 * NOTE: IPV6_ADDR_LEN also has same size.
9091 		 * Use family to discriminate.
9092 		 */
9093 		if (tcp->tcp_family == AF_INET) {
9094 			sin = (sin_t *)cp;
9095 
9096 			*sin = sin_null;
9097 			sin->sin_family = AF_INET;
9098 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9099 			sin->sin_port = tcp->tcp_lport;
9100 			break;
9101 		} else {
9102 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9103 		}
9104 		break;
9105 
9106 	case sizeof (sin6_t):
9107 		ASSERT(tcp->tcp_family == AF_INET6);
9108 		sin6 = (sin6_t *)cp;
9109 
9110 		*sin6 = sin6_null;
9111 		sin6->sin6_family = AF_INET6;
9112 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9113 		sin6->sin6_port = tcp->tcp_lport;
9114 		break;
9115 
9116 	case IP_ADDR_LEN:
9117 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9118 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9119 		break;
9120 
9121 	}
9122 	/* Add protocol number to end */
9123 	cp[addr_length] = (char)IPPROTO_TCP;
9124 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9125 	return (mp);
9126 }
9127 
9128 /*
9129  * Notify IP that we are having trouble with this connection.  IP should
9130  * blow the IRE away and start over.
9131  */
9132 static void
9133 tcp_ip_notify(tcp_t *tcp)
9134 {
9135 	struct iocblk	*iocp;
9136 	ipid_t	*ipid;
9137 	mblk_t	*mp;
9138 
9139 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9140 	if (tcp->tcp_ipversion == IPV6_VERSION)
9141 		return;
9142 
9143 	mp = mkiocb(IP_IOCTL);
9144 	if (mp == NULL)
9145 		return;
9146 
9147 	iocp = (struct iocblk *)mp->b_rptr;
9148 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9149 
9150 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9151 	if (!mp->b_cont) {
9152 		freeb(mp);
9153 		return;
9154 	}
9155 
9156 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9157 	mp->b_cont->b_wptr += iocp->ioc_count;
9158 	bzero(ipid, sizeof (*ipid));
9159 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9160 	ipid->ipid_ire_type = IRE_CACHE;
9161 	ipid->ipid_addr_offset = sizeof (ipid_t);
9162 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9163 	/*
9164 	 * Note: in the case of source routing we want to blow away the
9165 	 * route to the first source route hop.
9166 	 */
9167 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9168 	    sizeof (tcp->tcp_ipha->ipha_dst));
9169 
9170 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9171 }
9172 
9173 /* Unlink and return any mblk that looks like it contains an ire */
9174 static mblk_t *
9175 tcp_ire_mp(mblk_t *mp)
9176 {
9177 	mblk_t	*prev_mp;
9178 
9179 	for (;;) {
9180 		prev_mp = mp;
9181 		mp = mp->b_cont;
9182 		if (mp == NULL)
9183 			break;
9184 		switch (DB_TYPE(mp)) {
9185 		case IRE_DB_TYPE:
9186 		case IRE_DB_REQ_TYPE:
9187 			if (prev_mp != NULL)
9188 				prev_mp->b_cont = mp->b_cont;
9189 			mp->b_cont = NULL;
9190 			return (mp);
9191 		default:
9192 			break;
9193 		}
9194 	}
9195 	return (mp);
9196 }
9197 
9198 /*
9199  * Timer callback routine for keepalive probe.  We do a fake resend of
9200  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9201  * check to see if we have heard anything from the other end for the last
9202  * RTO period.  If we have, set the timer to expire for another
9203  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9204  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9205  * the timeout if we have not heard from the other side.  If for more than
9206  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9207  * kill the connection unless the keepalive abort threshold is 0.  In
9208  * that case, we will probe "forever."
9209  */
9210 static void
9211 tcp_keepalive_killer(void *arg)
9212 {
9213 	mblk_t	*mp;
9214 	conn_t	*connp = (conn_t *)arg;
9215 	tcp_t  	*tcp = connp->conn_tcp;
9216 	int32_t	firetime;
9217 	int32_t	idletime;
9218 	int32_t	ka_intrvl;
9219 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9220 
9221 	tcp->tcp_ka_tid = 0;
9222 
9223 	if (tcp->tcp_fused)
9224 		return;
9225 
9226 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9227 	ka_intrvl = tcp->tcp_ka_interval;
9228 
9229 	/*
9230 	 * Keepalive probe should only be sent if the application has not
9231 	 * done a close on the connection.
9232 	 */
9233 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9234 		return;
9235 	}
9236 	/* Timer fired too early, restart it. */
9237 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9238 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9239 		    MSEC_TO_TICK(ka_intrvl));
9240 		return;
9241 	}
9242 
9243 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9244 	/*
9245 	 * If we have not heard from the other side for a long
9246 	 * time, kill the connection unless the keepalive abort
9247 	 * threshold is 0.  In that case, we will probe "forever."
9248 	 */
9249 	if (tcp->tcp_ka_abort_thres != 0 &&
9250 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9251 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9252 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9253 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9254 		return;
9255 	}
9256 
9257 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9258 	    idletime >= ka_intrvl) {
9259 		/* Fake resend of last ACKed byte. */
9260 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9261 
9262 		if (mp1 != NULL) {
9263 			*mp1->b_wptr++ = '\0';
9264 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9265 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9266 			freeb(mp1);
9267 			/*
9268 			 * if allocation failed, fall through to start the
9269 			 * timer back.
9270 			 */
9271 			if (mp != NULL) {
9272 				TCP_RECORD_TRACE(tcp, mp,
9273 				    TCP_TRACE_SEND_PKT);
9274 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9275 				BUMP_MIB(&tcps->tcps_mib,
9276 				    tcpTimKeepaliveProbe);
9277 				if (tcp->tcp_ka_last_intrvl != 0) {
9278 					int max;
9279 					/*
9280 					 * We should probe again at least
9281 					 * in ka_intrvl, but not more than
9282 					 * tcp_rexmit_interval_max.
9283 					 */
9284 					max = tcps->tcps_rexmit_interval_max;
9285 					firetime = MIN(ka_intrvl - 1,
9286 					    tcp->tcp_ka_last_intrvl << 1);
9287 					if (firetime > max)
9288 						firetime = max;
9289 				} else {
9290 					firetime = tcp->tcp_rto;
9291 				}
9292 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9293 				    tcp_keepalive_killer,
9294 				    MSEC_TO_TICK(firetime));
9295 				tcp->tcp_ka_last_intrvl = firetime;
9296 				return;
9297 			}
9298 		}
9299 	} else {
9300 		tcp->tcp_ka_last_intrvl = 0;
9301 	}
9302 
9303 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9304 	if ((firetime = ka_intrvl - idletime) < 0) {
9305 		firetime = ka_intrvl;
9306 	}
9307 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9308 	    MSEC_TO_TICK(firetime));
9309 }
9310 
9311 int
9312 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9313 {
9314 	queue_t	*q = tcp->tcp_rq;
9315 	int32_t	mss = tcp->tcp_mss;
9316 	int	maxpsz;
9317 
9318 	if (TCP_IS_DETACHED(tcp))
9319 		return (mss);
9320 
9321 	if (tcp->tcp_fused) {
9322 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9323 		mss = INFPSZ;
9324 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9325 		/*
9326 		 * Set the sd_qn_maxpsz according to the socket send buffer
9327 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9328 		 * instruct the stream head to copyin user data into contiguous
9329 		 * kernel-allocated buffers without breaking it up into smaller
9330 		 * chunks.  We round up the buffer size to the nearest SMSS.
9331 		 */
9332 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9333 		if (tcp->tcp_kssl_ctx == NULL)
9334 			mss = INFPSZ;
9335 		else
9336 			mss = SSL3_MAX_RECORD_LEN;
9337 	} else {
9338 		/*
9339 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9340 		 * (and a multiple of the mss).  This instructs the stream
9341 		 * head to break down larger than SMSS writes into SMSS-
9342 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9343 		 */
9344 		maxpsz = tcp->tcp_maxpsz * mss;
9345 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9346 			maxpsz = tcp->tcp_xmit_hiwater/2;
9347 			/* Round up to nearest mss */
9348 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9349 		}
9350 	}
9351 	(void) setmaxps(q, maxpsz);
9352 	tcp->tcp_wq->q_maxpsz = maxpsz;
9353 
9354 	if (set_maxblk)
9355 		(void) mi_set_sth_maxblk(q, mss);
9356 
9357 	return (mss);
9358 }
9359 
9360 /*
9361  * Extract option values from a tcp header.  We put any found values into the
9362  * tcpopt struct and return a bitmask saying which options were found.
9363  */
9364 static int
9365 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9366 {
9367 	uchar_t		*endp;
9368 	int		len;
9369 	uint32_t	mss;
9370 	uchar_t		*up = (uchar_t *)tcph;
9371 	int		found = 0;
9372 	int32_t		sack_len;
9373 	tcp_seq		sack_begin, sack_end;
9374 	tcp_t		*tcp;
9375 
9376 	endp = up + TCP_HDR_LENGTH(tcph);
9377 	up += TCP_MIN_HEADER_LENGTH;
9378 	while (up < endp) {
9379 		len = endp - up;
9380 		switch (*up) {
9381 		case TCPOPT_EOL:
9382 			break;
9383 
9384 		case TCPOPT_NOP:
9385 			up++;
9386 			continue;
9387 
9388 		case TCPOPT_MAXSEG:
9389 			if (len < TCPOPT_MAXSEG_LEN ||
9390 			    up[1] != TCPOPT_MAXSEG_LEN)
9391 				break;
9392 
9393 			mss = BE16_TO_U16(up+2);
9394 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9395 			tcpopt->tcp_opt_mss = mss;
9396 			found |= TCP_OPT_MSS_PRESENT;
9397 
9398 			up += TCPOPT_MAXSEG_LEN;
9399 			continue;
9400 
9401 		case TCPOPT_WSCALE:
9402 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9403 				break;
9404 
9405 			if (up[2] > TCP_MAX_WINSHIFT)
9406 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9407 			else
9408 				tcpopt->tcp_opt_wscale = up[2];
9409 			found |= TCP_OPT_WSCALE_PRESENT;
9410 
9411 			up += TCPOPT_WS_LEN;
9412 			continue;
9413 
9414 		case TCPOPT_SACK_PERMITTED:
9415 			if (len < TCPOPT_SACK_OK_LEN ||
9416 			    up[1] != TCPOPT_SACK_OK_LEN)
9417 				break;
9418 			found |= TCP_OPT_SACK_OK_PRESENT;
9419 			up += TCPOPT_SACK_OK_LEN;
9420 			continue;
9421 
9422 		case TCPOPT_SACK:
9423 			if (len <= 2 || up[1] <= 2 || len < up[1])
9424 				break;
9425 
9426 			/* If TCP is not interested in SACK blks... */
9427 			if ((tcp = tcpopt->tcp) == NULL) {
9428 				up += up[1];
9429 				continue;
9430 			}
9431 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9432 			up += TCPOPT_HEADER_LEN;
9433 
9434 			/*
9435 			 * If the list is empty, allocate one and assume
9436 			 * nothing is sack'ed.
9437 			 */
9438 			ASSERT(tcp->tcp_sack_info != NULL);
9439 			if (tcp->tcp_notsack_list == NULL) {
9440 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9441 				    tcp->tcp_suna, tcp->tcp_snxt,
9442 				    &(tcp->tcp_num_notsack_blk),
9443 				    &(tcp->tcp_cnt_notsack_list));
9444 
9445 				/*
9446 				 * Make sure tcp_notsack_list is not NULL.
9447 				 * This happens when kmem_alloc(KM_NOSLEEP)
9448 				 * returns NULL.
9449 				 */
9450 				if (tcp->tcp_notsack_list == NULL) {
9451 					up += sack_len;
9452 					continue;
9453 				}
9454 				tcp->tcp_fack = tcp->tcp_suna;
9455 			}
9456 
9457 			while (sack_len > 0) {
9458 				if (up + 8 > endp) {
9459 					up = endp;
9460 					break;
9461 				}
9462 				sack_begin = BE32_TO_U32(up);
9463 				up += 4;
9464 				sack_end = BE32_TO_U32(up);
9465 				up += 4;
9466 				sack_len -= 8;
9467 				/*
9468 				 * Bounds checking.  Make sure the SACK
9469 				 * info is within tcp_suna and tcp_snxt.
9470 				 * If this SACK blk is out of bound, ignore
9471 				 * it but continue to parse the following
9472 				 * blks.
9473 				 */
9474 				if (SEQ_LEQ(sack_end, sack_begin) ||
9475 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9476 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9477 					continue;
9478 				}
9479 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9480 				    sack_begin, sack_end,
9481 				    &(tcp->tcp_num_notsack_blk),
9482 				    &(tcp->tcp_cnt_notsack_list));
9483 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9484 					tcp->tcp_fack = sack_end;
9485 				}
9486 			}
9487 			found |= TCP_OPT_SACK_PRESENT;
9488 			continue;
9489 
9490 		case TCPOPT_TSTAMP:
9491 			if (len < TCPOPT_TSTAMP_LEN ||
9492 			    up[1] != TCPOPT_TSTAMP_LEN)
9493 				break;
9494 
9495 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9496 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9497 
9498 			found |= TCP_OPT_TSTAMP_PRESENT;
9499 
9500 			up += TCPOPT_TSTAMP_LEN;
9501 			continue;
9502 
9503 		default:
9504 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9505 				break;
9506 			up += up[1];
9507 			continue;
9508 		}
9509 		break;
9510 	}
9511 	return (found);
9512 }
9513 
9514 /*
9515  * Set the mss associated with a particular tcp based on its current value,
9516  * and a new one passed in. Observe minimums and maximums, and reset
9517  * other state variables that we want to view as multiples of mss.
9518  *
9519  * This function is called in various places mainly because
9520  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9521  *    other side's SYN/SYN-ACK packet arrives.
9522  * 2) PMTUd may get us a new MSS.
9523  * 3) If the other side stops sending us timestamp option, we need to
9524  *    increase the MSS size to use the extra bytes available.
9525  *
9526  * do_ss is used to control whether we will be doing slow start or
9527  * not if there is a change in the mss. Note that for some events like
9528  * tcp_paws_check() we allow the tcp_cwnd to adjust to the new mss but
9529  * do not perform a slow start specifically.
9530  */
9531 static void
9532 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9533 {
9534 	uint32_t	mss_max;
9535 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9536 
9537 	if (tcp->tcp_ipversion == IPV4_VERSION)
9538 		mss_max = tcps->tcps_mss_max_ipv4;
9539 	else
9540 		mss_max = tcps->tcps_mss_max_ipv6;
9541 
9542 	if (mss < tcps->tcps_mss_min)
9543 		mss = tcps->tcps_mss_min;
9544 	if (mss > mss_max)
9545 		mss = mss_max;
9546 	/*
9547 	 * Unless naglim has been set by our client to
9548 	 * a non-mss value, force naglim to track mss.
9549 	 * This can help to aggregate small writes.
9550 	 */
9551 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9552 		tcp->tcp_naglim = mss;
9553 	/*
9554 	 * TCP should be able to buffer at least 4 MSS data for obvious
9555 	 * performance reason.
9556 	 */
9557 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9558 		tcp->tcp_xmit_hiwater = mss << 2;
9559 
9560 	/*
9561 	 * Check if we need to apply the tcp_init_cwnd here.  If
9562 	 * it is set and the MSS gets bigger (should not happen
9563 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9564 	 * The new tcp_cwnd should not get bigger.
9565 	 */
9566 	/*
9567 	 * We need to avoid setting tcp_cwnd to its slow start value
9568 	 * unnecessarily. However we have to let the tcp_cwnd adjust
9569 	 * to the modified mss.
9570 	 */
9571 	if (tcp->tcp_init_cwnd == 0 && do_ss) {
9572 		tcp->tcp_cwnd = MIN(tcps->tcps_slow_start_initial *
9573 		    mss, MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9574 	} else {
9575 		if (tcp->tcp_mss < mss) {
9576 			tcp->tcp_cwnd = MAX(1,
9577 			    (tcp->tcp_init_cwnd * tcp->tcp_mss /
9578 			    mss)) * mss;
9579 		} else {
9580 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9581 		}
9582 	}
9583 	tcp->tcp_mss = mss;
9584 	tcp->tcp_cwnd_cnt = 0;
9585 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9586 }
9587 
9588 /* For /dev/tcp aka AF_INET open */
9589 static int
9590 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9591 {
9592 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9593 }
9594 
9595 /* For /dev/tcp6 aka AF_INET6 open */
9596 static int
9597 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9598 {
9599 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9600 }
9601 
9602 static int
9603 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9604     boolean_t isv6)
9605 {
9606 	tcp_t		*tcp = NULL;
9607 	conn_t		*connp;
9608 	int		err;
9609 	dev_t		conn_dev;
9610 	zoneid_t	zoneid;
9611 	tcp_stack_t	*tcps = NULL;
9612 
9613 	if (q->q_ptr != NULL)
9614 		return (0);
9615 
9616 	if (sflag == MODOPEN)
9617 		return (EINVAL);
9618 
9619 	if (!(flag & SO_ACCEPTOR)) {
9620 		/*
9621 		 * Special case for install: miniroot needs to be able to
9622 		 * access files via NFS as though it were always in the
9623 		 * global zone.
9624 		 */
9625 		if (credp == kcred && nfs_global_client_only != 0) {
9626 			zoneid = GLOBAL_ZONEID;
9627 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9628 			    netstack_tcp;
9629 			ASSERT(tcps != NULL);
9630 		} else {
9631 			netstack_t *ns;
9632 
9633 			ns = netstack_find_by_cred(credp);
9634 			ASSERT(ns != NULL);
9635 			tcps = ns->netstack_tcp;
9636 			ASSERT(tcps != NULL);
9637 
9638 			/*
9639 			 * For exclusive stacks we set the zoneid to zero
9640 			 * to make TCP operate as if in the global zone.
9641 			 */
9642 			if (tcps->tcps_netstack->netstack_stackid !=
9643 			    GLOBAL_NETSTACKID)
9644 				zoneid = GLOBAL_ZONEID;
9645 			else
9646 				zoneid = crgetzoneid(credp);
9647 		}
9648 		/*
9649 		 * For stackid zero this is done from strplumb.c, but
9650 		 * non-zero stackids are handled here.
9651 		 */
9652 		if (tcps->tcps_g_q == NULL &&
9653 		    tcps->tcps_netstack->netstack_stackid !=
9654 		    GLOBAL_NETSTACKID) {
9655 			tcp_g_q_setup(tcps);
9656 		}
9657 	}
9658 
9659 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9660 		if (tcps != NULL)
9661 			netstack_rele(tcps->tcps_netstack);
9662 		return (EBUSY);
9663 	}
9664 
9665 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9666 
9667 	if (flag & SO_ACCEPTOR) {
9668 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9669 		ASSERT(tcps == NULL);
9670 		q->q_qinfo = &tcp_acceptor_rinit;
9671 		q->q_ptr = (void *)conn_dev;
9672 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9673 		WR(q)->q_ptr = (void *)conn_dev;
9674 		qprocson(q);
9675 		return (0);
9676 	}
9677 
9678 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9679 	/*
9680 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9681 	 * so we drop it by one.
9682 	 */
9683 	netstack_rele(tcps->tcps_netstack);
9684 	if (connp == NULL) {
9685 		inet_minor_free(ip_minor_arena, conn_dev);
9686 		q->q_ptr = NULL;
9687 		return (ENOSR);
9688 	}
9689 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9690 	tcp = connp->conn_tcp;
9691 
9692 	q->q_ptr = WR(q)->q_ptr = connp;
9693 	if (isv6) {
9694 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9695 		connp->conn_send = ip_output_v6;
9696 		connp->conn_af_isv6 = B_TRUE;
9697 		connp->conn_pkt_isv6 = B_TRUE;
9698 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9699 		tcp->tcp_ipversion = IPV6_VERSION;
9700 		tcp->tcp_family = AF_INET6;
9701 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9702 	} else {
9703 		connp->conn_flags |= IPCL_TCP4;
9704 		connp->conn_send = ip_output;
9705 		connp->conn_af_isv6 = B_FALSE;
9706 		connp->conn_pkt_isv6 = B_FALSE;
9707 		tcp->tcp_ipversion = IPV4_VERSION;
9708 		tcp->tcp_family = AF_INET;
9709 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9710 	}
9711 
9712 	/*
9713 	 * TCP keeps a copy of cred for cache locality reasons but
9714 	 * we put a reference only once. If connp->conn_cred
9715 	 * becomes invalid, tcp_cred should also be set to NULL.
9716 	 */
9717 	tcp->tcp_cred = connp->conn_cred = credp;
9718 	crhold(connp->conn_cred);
9719 	tcp->tcp_cpid = curproc->p_pid;
9720 	tcp->tcp_open_time = lbolt64;
9721 	connp->conn_zoneid = zoneid;
9722 	connp->conn_mlp_type = mlptSingle;
9723 	connp->conn_ulp_labeled = !is_system_labeled();
9724 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9725 	ASSERT(tcp->tcp_tcps == tcps);
9726 
9727 	/*
9728 	 * If the caller has the process-wide flag set, then default to MAC
9729 	 * exempt mode.  This allows read-down to unlabeled hosts.
9730 	 */
9731 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9732 		connp->conn_mac_exempt = B_TRUE;
9733 
9734 	connp->conn_dev = conn_dev;
9735 
9736 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9737 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9738 
9739 	if (flag & SO_SOCKSTR) {
9740 		/*
9741 		 * No need to insert a socket in tcp acceptor hash.
9742 		 * If it was a socket acceptor stream, we dealt with
9743 		 * it above. A socket listener can never accept a
9744 		 * connection and doesn't need acceptor_id.
9745 		 */
9746 		connp->conn_flags |= IPCL_SOCKET;
9747 		tcp->tcp_issocket = 1;
9748 		WR(q)->q_qinfo = &tcp_sock_winit;
9749 	} else {
9750 #ifdef	_ILP32
9751 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9752 #else
9753 		tcp->tcp_acceptor_id = conn_dev;
9754 #endif	/* _ILP32 */
9755 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9756 	}
9757 
9758 	if (tcps->tcps_trace)
9759 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9760 
9761 	err = tcp_init(tcp, q);
9762 	if (err != 0) {
9763 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9764 		tcp_acceptor_hash_remove(tcp);
9765 		CONN_DEC_REF(connp);
9766 		q->q_ptr = WR(q)->q_ptr = NULL;
9767 		return (err);
9768 	}
9769 
9770 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9771 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9772 
9773 	/* Non-zero default values */
9774 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9775 	/*
9776 	 * Put the ref for TCP. Ref for IP was already put
9777 	 * by ipcl_conn_create. Also Make the conn_t globally
9778 	 * visible to walkers
9779 	 */
9780 	mutex_enter(&connp->conn_lock);
9781 	CONN_INC_REF_LOCKED(connp);
9782 	ASSERT(connp->conn_ref == 2);
9783 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9784 	mutex_exit(&connp->conn_lock);
9785 
9786 	qprocson(q);
9787 	return (0);
9788 }
9789 
9790 /*
9791  * Some TCP options can be "set" by requesting them in the option
9792  * buffer. This is needed for XTI feature test though we do not
9793  * allow it in general. We interpret that this mechanism is more
9794  * applicable to OSI protocols and need not be allowed in general.
9795  * This routine filters out options for which it is not allowed (most)
9796  * and lets through those (few) for which it is. [ The XTI interface
9797  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9798  * ever implemented will have to be allowed here ].
9799  */
9800 static boolean_t
9801 tcp_allow_connopt_set(int level, int name)
9802 {
9803 
9804 	switch (level) {
9805 	case IPPROTO_TCP:
9806 		switch (name) {
9807 		case TCP_NODELAY:
9808 			return (B_TRUE);
9809 		default:
9810 			return (B_FALSE);
9811 		}
9812 		/*NOTREACHED*/
9813 	default:
9814 		return (B_FALSE);
9815 	}
9816 	/*NOTREACHED*/
9817 }
9818 
9819 /*
9820  * This routine gets default values of certain options whose default
9821  * values are maintained by protocol specific code
9822  */
9823 /* ARGSUSED */
9824 int
9825 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9826 {
9827 	int32_t	*i1 = (int32_t *)ptr;
9828 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9829 
9830 	switch (level) {
9831 	case IPPROTO_TCP:
9832 		switch (name) {
9833 		case TCP_NOTIFY_THRESHOLD:
9834 			*i1 = tcps->tcps_ip_notify_interval;
9835 			break;
9836 		case TCP_ABORT_THRESHOLD:
9837 			*i1 = tcps->tcps_ip_abort_interval;
9838 			break;
9839 		case TCP_CONN_NOTIFY_THRESHOLD:
9840 			*i1 = tcps->tcps_ip_notify_cinterval;
9841 			break;
9842 		case TCP_CONN_ABORT_THRESHOLD:
9843 			*i1 = tcps->tcps_ip_abort_cinterval;
9844 			break;
9845 		default:
9846 			return (-1);
9847 		}
9848 		break;
9849 	case IPPROTO_IP:
9850 		switch (name) {
9851 		case IP_TTL:
9852 			*i1 = tcps->tcps_ipv4_ttl;
9853 			break;
9854 		default:
9855 			return (-1);
9856 		}
9857 		break;
9858 	case IPPROTO_IPV6:
9859 		switch (name) {
9860 		case IPV6_UNICAST_HOPS:
9861 			*i1 = tcps->tcps_ipv6_hoplimit;
9862 			break;
9863 		default:
9864 			return (-1);
9865 		}
9866 		break;
9867 	default:
9868 		return (-1);
9869 	}
9870 	return (sizeof (int));
9871 }
9872 
9873 
9874 /*
9875  * TCP routine to get the values of options.
9876  */
9877 int
9878 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9879 {
9880 	int		*i1 = (int *)ptr;
9881 	conn_t		*connp = Q_TO_CONN(q);
9882 	tcp_t		*tcp = connp->conn_tcp;
9883 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9884 
9885 	switch (level) {
9886 	case SOL_SOCKET:
9887 		switch (name) {
9888 		case SO_LINGER:	{
9889 			struct linger *lgr = (struct linger *)ptr;
9890 
9891 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9892 			lgr->l_linger = tcp->tcp_lingertime;
9893 			}
9894 			return (sizeof (struct linger));
9895 		case SO_DEBUG:
9896 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9897 			break;
9898 		case SO_KEEPALIVE:
9899 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9900 			break;
9901 		case SO_DONTROUTE:
9902 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9903 			break;
9904 		case SO_USELOOPBACK:
9905 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9906 			break;
9907 		case SO_BROADCAST:
9908 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9909 			break;
9910 		case SO_REUSEADDR:
9911 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9912 			break;
9913 		case SO_OOBINLINE:
9914 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9915 			break;
9916 		case SO_DGRAM_ERRIND:
9917 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9918 			break;
9919 		case SO_TYPE:
9920 			*i1 = SOCK_STREAM;
9921 			break;
9922 		case SO_SNDBUF:
9923 			*i1 = tcp->tcp_xmit_hiwater;
9924 			break;
9925 		case SO_RCVBUF:
9926 			*i1 = RD(q)->q_hiwat;
9927 			break;
9928 		case SO_SND_COPYAVOID:
9929 			*i1 = tcp->tcp_snd_zcopy_on ?
9930 			    SO_SND_COPYAVOID : 0;
9931 			break;
9932 		case SO_ALLZONES:
9933 			*i1 = connp->conn_allzones ? 1 : 0;
9934 			break;
9935 		case SO_ANON_MLP:
9936 			*i1 = connp->conn_anon_mlp;
9937 			break;
9938 		case SO_MAC_EXEMPT:
9939 			*i1 = connp->conn_mac_exempt;
9940 			break;
9941 		case SO_EXCLBIND:
9942 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9943 			break;
9944 		case SO_PROTOTYPE:
9945 			*i1 = IPPROTO_TCP;
9946 			break;
9947 		case SO_DOMAIN:
9948 			*i1 = tcp->tcp_family;
9949 			break;
9950 		default:
9951 			return (-1);
9952 		}
9953 		break;
9954 	case IPPROTO_TCP:
9955 		switch (name) {
9956 		case TCP_NODELAY:
9957 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9958 			break;
9959 		case TCP_MAXSEG:
9960 			*i1 = tcp->tcp_mss;
9961 			break;
9962 		case TCP_NOTIFY_THRESHOLD:
9963 			*i1 = (int)tcp->tcp_first_timer_threshold;
9964 			break;
9965 		case TCP_ABORT_THRESHOLD:
9966 			*i1 = tcp->tcp_second_timer_threshold;
9967 			break;
9968 		case TCP_CONN_NOTIFY_THRESHOLD:
9969 			*i1 = tcp->tcp_first_ctimer_threshold;
9970 			break;
9971 		case TCP_CONN_ABORT_THRESHOLD:
9972 			*i1 = tcp->tcp_second_ctimer_threshold;
9973 			break;
9974 		case TCP_RECVDSTADDR:
9975 			*i1 = tcp->tcp_recvdstaddr;
9976 			break;
9977 		case TCP_ANONPRIVBIND:
9978 			*i1 = tcp->tcp_anon_priv_bind;
9979 			break;
9980 		case TCP_EXCLBIND:
9981 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9982 			break;
9983 		case TCP_INIT_CWND:
9984 			*i1 = tcp->tcp_init_cwnd;
9985 			break;
9986 		case TCP_KEEPALIVE_THRESHOLD:
9987 			*i1 = tcp->tcp_ka_interval;
9988 			break;
9989 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9990 			*i1 = tcp->tcp_ka_abort_thres;
9991 			break;
9992 		case TCP_CORK:
9993 			*i1 = tcp->tcp_cork;
9994 			break;
9995 		default:
9996 			return (-1);
9997 		}
9998 		break;
9999 	case IPPROTO_IP:
10000 		if (tcp->tcp_family != AF_INET)
10001 			return (-1);
10002 		switch (name) {
10003 		case IP_OPTIONS:
10004 		case T_IP_OPTIONS: {
10005 			/*
10006 			 * This is compatible with BSD in that in only return
10007 			 * the reverse source route with the final destination
10008 			 * as the last entry. The first 4 bytes of the option
10009 			 * will contain the final destination.
10010 			 */
10011 			int	opt_len;
10012 
10013 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10014 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10015 			ASSERT(opt_len >= 0);
10016 			/* Caller ensures enough space */
10017 			if (opt_len > 0) {
10018 				/*
10019 				 * TODO: Do we have to handle getsockopt on an
10020 				 * initiator as well?
10021 				 */
10022 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10023 			}
10024 			return (0);
10025 			}
10026 		case IP_TOS:
10027 		case T_IP_TOS:
10028 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10029 			break;
10030 		case IP_TTL:
10031 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10032 			break;
10033 		case IP_NEXTHOP:
10034 			/* Handled at IP level */
10035 			return (-EINVAL);
10036 		default:
10037 			return (-1);
10038 		}
10039 		break;
10040 	case IPPROTO_IPV6:
10041 		/*
10042 		 * IPPROTO_IPV6 options are only supported for sockets
10043 		 * that are using IPv6 on the wire.
10044 		 */
10045 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10046 			return (-1);
10047 		}
10048 		switch (name) {
10049 		case IPV6_UNICAST_HOPS:
10050 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10051 			break;	/* goto sizeof (int) option return */
10052 		case IPV6_BOUND_IF:
10053 			/* Zero if not set */
10054 			*i1 = tcp->tcp_bound_if;
10055 			break;	/* goto sizeof (int) option return */
10056 		case IPV6_RECVPKTINFO:
10057 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10058 				*i1 = 1;
10059 			else
10060 				*i1 = 0;
10061 			break;	/* goto sizeof (int) option return */
10062 		case IPV6_RECVTCLASS:
10063 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10064 				*i1 = 1;
10065 			else
10066 				*i1 = 0;
10067 			break;	/* goto sizeof (int) option return */
10068 		case IPV6_RECVHOPLIMIT:
10069 			if (tcp->tcp_ipv6_recvancillary &
10070 			    TCP_IPV6_RECVHOPLIMIT)
10071 				*i1 = 1;
10072 			else
10073 				*i1 = 0;
10074 			break;	/* goto sizeof (int) option return */
10075 		case IPV6_RECVHOPOPTS:
10076 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10077 				*i1 = 1;
10078 			else
10079 				*i1 = 0;
10080 			break;	/* goto sizeof (int) option return */
10081 		case IPV6_RECVDSTOPTS:
10082 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10083 				*i1 = 1;
10084 			else
10085 				*i1 = 0;
10086 			break;	/* goto sizeof (int) option return */
10087 		case _OLD_IPV6_RECVDSTOPTS:
10088 			if (tcp->tcp_ipv6_recvancillary &
10089 			    TCP_OLD_IPV6_RECVDSTOPTS)
10090 				*i1 = 1;
10091 			else
10092 				*i1 = 0;
10093 			break;	/* goto sizeof (int) option return */
10094 		case IPV6_RECVRTHDR:
10095 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10096 				*i1 = 1;
10097 			else
10098 				*i1 = 0;
10099 			break;	/* goto sizeof (int) option return */
10100 		case IPV6_RECVRTHDRDSTOPTS:
10101 			if (tcp->tcp_ipv6_recvancillary &
10102 			    TCP_IPV6_RECVRTDSTOPTS)
10103 				*i1 = 1;
10104 			else
10105 				*i1 = 0;
10106 			break;	/* goto sizeof (int) option return */
10107 		case IPV6_PKTINFO: {
10108 			/* XXX assumes that caller has room for max size! */
10109 			struct in6_pktinfo *pkti;
10110 
10111 			pkti = (struct in6_pktinfo *)ptr;
10112 			if (ipp->ipp_fields & IPPF_IFINDEX)
10113 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10114 			else
10115 				pkti->ipi6_ifindex = 0;
10116 			if (ipp->ipp_fields & IPPF_ADDR)
10117 				pkti->ipi6_addr = ipp->ipp_addr;
10118 			else
10119 				pkti->ipi6_addr = ipv6_all_zeros;
10120 			return (sizeof (struct in6_pktinfo));
10121 		}
10122 		case IPV6_TCLASS:
10123 			if (ipp->ipp_fields & IPPF_TCLASS)
10124 				*i1 = ipp->ipp_tclass;
10125 			else
10126 				*i1 = IPV6_FLOW_TCLASS(
10127 				    IPV6_DEFAULT_VERS_AND_FLOW);
10128 			break;	/* goto sizeof (int) option return */
10129 		case IPV6_NEXTHOP: {
10130 			sin6_t *sin6 = (sin6_t *)ptr;
10131 
10132 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10133 				return (0);
10134 			*sin6 = sin6_null;
10135 			sin6->sin6_family = AF_INET6;
10136 			sin6->sin6_addr = ipp->ipp_nexthop;
10137 			return (sizeof (sin6_t));
10138 		}
10139 		case IPV6_HOPOPTS:
10140 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10141 				return (0);
10142 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10143 				return (0);
10144 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10145 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10146 			if (tcp->tcp_label_len > 0) {
10147 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10148 				ptr[1] = (ipp->ipp_hopoptslen -
10149 				    tcp->tcp_label_len + 7) / 8 - 1;
10150 			}
10151 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10152 		case IPV6_RTHDRDSTOPTS:
10153 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10154 				return (0);
10155 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10156 			return (ipp->ipp_rtdstoptslen);
10157 		case IPV6_RTHDR:
10158 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10159 				return (0);
10160 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10161 			return (ipp->ipp_rthdrlen);
10162 		case IPV6_DSTOPTS:
10163 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10164 				return (0);
10165 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10166 			return (ipp->ipp_dstoptslen);
10167 		case IPV6_SRC_PREFERENCES:
10168 			return (ip6_get_src_preferences(connp,
10169 			    (uint32_t *)ptr));
10170 		case IPV6_PATHMTU: {
10171 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10172 
10173 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10174 				return (-1);
10175 
10176 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10177 			    connp->conn_fport, mtuinfo,
10178 			    connp->conn_netstack));
10179 		}
10180 		default:
10181 			return (-1);
10182 		}
10183 		break;
10184 	default:
10185 		return (-1);
10186 	}
10187 	return (sizeof (int));
10188 }
10189 
10190 /*
10191  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10192  * Parameters are assumed to be verified by the caller.
10193  */
10194 /* ARGSUSED */
10195 int
10196 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10197     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10198     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10199 {
10200 	conn_t	*connp = Q_TO_CONN(q);
10201 	tcp_t	*tcp = connp->conn_tcp;
10202 	int	*i1 = (int *)invalp;
10203 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10204 	boolean_t checkonly;
10205 	int	reterr;
10206 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10207 
10208 	switch (optset_context) {
10209 	case SETFN_OPTCOM_CHECKONLY:
10210 		checkonly = B_TRUE;
10211 		/*
10212 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10213 		 * inlen != 0 implies value supplied and
10214 		 * 	we have to "pretend" to set it.
10215 		 * inlen == 0 implies that there is no
10216 		 * 	value part in T_CHECK request and just validation
10217 		 * done elsewhere should be enough, we just return here.
10218 		 */
10219 		if (inlen == 0) {
10220 			*outlenp = 0;
10221 			return (0);
10222 		}
10223 		break;
10224 	case SETFN_OPTCOM_NEGOTIATE:
10225 		checkonly = B_FALSE;
10226 		break;
10227 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10228 	case SETFN_CONN_NEGOTIATE:
10229 		checkonly = B_FALSE;
10230 		/*
10231 		 * Negotiating local and "association-related" options
10232 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10233 		 * primitives is allowed by XTI, but we choose
10234 		 * to not implement this style negotiation for Internet
10235 		 * protocols (We interpret it is a must for OSI world but
10236 		 * optional for Internet protocols) for all options.
10237 		 * [ Will do only for the few options that enable test
10238 		 * suites that our XTI implementation of this feature
10239 		 * works for transports that do allow it ]
10240 		 */
10241 		if (!tcp_allow_connopt_set(level, name)) {
10242 			*outlenp = 0;
10243 			return (EINVAL);
10244 		}
10245 		break;
10246 	default:
10247 		/*
10248 		 * We should never get here
10249 		 */
10250 		*outlenp = 0;
10251 		return (EINVAL);
10252 	}
10253 
10254 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10255 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10256 
10257 	/*
10258 	 * For TCP, we should have no ancillary data sent down
10259 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10260 	 * has to be zero.
10261 	 */
10262 	ASSERT(thisdg_attrs == NULL);
10263 
10264 	/*
10265 	 * For fixed length options, no sanity check
10266 	 * of passed in length is done. It is assumed *_optcom_req()
10267 	 * routines do the right thing.
10268 	 */
10269 
10270 	switch (level) {
10271 	case SOL_SOCKET:
10272 		switch (name) {
10273 		case SO_LINGER: {
10274 			struct linger *lgr = (struct linger *)invalp;
10275 
10276 			if (!checkonly) {
10277 				if (lgr->l_onoff) {
10278 					tcp->tcp_linger = 1;
10279 					tcp->tcp_lingertime = lgr->l_linger;
10280 				} else {
10281 					tcp->tcp_linger = 0;
10282 					tcp->tcp_lingertime = 0;
10283 				}
10284 				/* struct copy */
10285 				*(struct linger *)outvalp = *lgr;
10286 			} else {
10287 				if (!lgr->l_onoff) {
10288 					((struct linger *)
10289 					    outvalp)->l_onoff = 0;
10290 					((struct linger *)
10291 					    outvalp)->l_linger = 0;
10292 				} else {
10293 					/* struct copy */
10294 					*(struct linger *)outvalp = *lgr;
10295 				}
10296 			}
10297 			*outlenp = sizeof (struct linger);
10298 			return (0);
10299 		}
10300 		case SO_DEBUG:
10301 			if (!checkonly)
10302 				tcp->tcp_debug = onoff;
10303 			break;
10304 		case SO_KEEPALIVE:
10305 			if (checkonly) {
10306 				/* T_CHECK case */
10307 				break;
10308 			}
10309 
10310 			if (!onoff) {
10311 				if (tcp->tcp_ka_enabled) {
10312 					if (tcp->tcp_ka_tid != 0) {
10313 						(void) TCP_TIMER_CANCEL(tcp,
10314 						    tcp->tcp_ka_tid);
10315 						tcp->tcp_ka_tid = 0;
10316 					}
10317 					tcp->tcp_ka_enabled = 0;
10318 				}
10319 				break;
10320 			}
10321 			if (!tcp->tcp_ka_enabled) {
10322 				/* Crank up the keepalive timer */
10323 				tcp->tcp_ka_last_intrvl = 0;
10324 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10325 				    tcp_keepalive_killer,
10326 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10327 				tcp->tcp_ka_enabled = 1;
10328 			}
10329 			break;
10330 		case SO_DONTROUTE:
10331 			/*
10332 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10333 			 * only of interest to IP.  We track them here only so
10334 			 * that we can report their current value.
10335 			 */
10336 			if (!checkonly) {
10337 				tcp->tcp_dontroute = onoff;
10338 				tcp->tcp_connp->conn_dontroute = onoff;
10339 			}
10340 			break;
10341 		case SO_USELOOPBACK:
10342 			if (!checkonly) {
10343 				tcp->tcp_useloopback = onoff;
10344 				tcp->tcp_connp->conn_loopback = onoff;
10345 			}
10346 			break;
10347 		case SO_BROADCAST:
10348 			if (!checkonly) {
10349 				tcp->tcp_broadcast = onoff;
10350 				tcp->tcp_connp->conn_broadcast = onoff;
10351 			}
10352 			break;
10353 		case SO_REUSEADDR:
10354 			if (!checkonly) {
10355 				tcp->tcp_reuseaddr = onoff;
10356 				tcp->tcp_connp->conn_reuseaddr = onoff;
10357 			}
10358 			break;
10359 		case SO_OOBINLINE:
10360 			if (!checkonly)
10361 				tcp->tcp_oobinline = onoff;
10362 			break;
10363 		case SO_DGRAM_ERRIND:
10364 			if (!checkonly)
10365 				tcp->tcp_dgram_errind = onoff;
10366 			break;
10367 		case SO_SNDBUF: {
10368 			if (*i1 > tcps->tcps_max_buf) {
10369 				*outlenp = 0;
10370 				return (ENOBUFS);
10371 			}
10372 			if (checkonly)
10373 				break;
10374 
10375 			tcp->tcp_xmit_hiwater = *i1;
10376 			if (tcps->tcps_snd_lowat_fraction != 0)
10377 				tcp->tcp_xmit_lowater =
10378 				    tcp->tcp_xmit_hiwater /
10379 				    tcps->tcps_snd_lowat_fraction;
10380 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10381 			/*
10382 			 * If we are flow-controlled, recheck the condition.
10383 			 * There are apps that increase SO_SNDBUF size when
10384 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10385 			 * control condition to be lifted right away.
10386 			 */
10387 			mutex_enter(&tcp->tcp_non_sq_lock);
10388 			if (tcp->tcp_flow_stopped &&
10389 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10390 				tcp_clrqfull(tcp);
10391 			}
10392 			mutex_exit(&tcp->tcp_non_sq_lock);
10393 			break;
10394 		}
10395 		case SO_RCVBUF:
10396 			if (*i1 > tcps->tcps_max_buf) {
10397 				*outlenp = 0;
10398 				return (ENOBUFS);
10399 			}
10400 			/* Silently ignore zero */
10401 			if (!checkonly && *i1 != 0) {
10402 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10403 				(void) tcp_rwnd_set(tcp, *i1);
10404 			}
10405 			/*
10406 			 * XXX should we return the rwnd here
10407 			 * and tcp_opt_get ?
10408 			 */
10409 			break;
10410 		case SO_SND_COPYAVOID:
10411 			if (!checkonly) {
10412 				/* we only allow enable at most once for now */
10413 				if (tcp->tcp_loopback ||
10414 				    (!tcp->tcp_snd_zcopy_aware &&
10415 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10416 					*outlenp = 0;
10417 					return (EOPNOTSUPP);
10418 				}
10419 				tcp->tcp_snd_zcopy_aware = 1;
10420 			}
10421 			break;
10422 		case SO_ALLZONES:
10423 			/* Handled at the IP level */
10424 			return (-EINVAL);
10425 		case SO_ANON_MLP:
10426 			if (!checkonly) {
10427 				mutex_enter(&connp->conn_lock);
10428 				connp->conn_anon_mlp = onoff;
10429 				mutex_exit(&connp->conn_lock);
10430 			}
10431 			break;
10432 		case SO_MAC_EXEMPT:
10433 			if (secpolicy_net_mac_aware(cr) != 0 ||
10434 			    IPCL_IS_BOUND(connp))
10435 				return (EACCES);
10436 			if (!checkonly) {
10437 				mutex_enter(&connp->conn_lock);
10438 				connp->conn_mac_exempt = onoff;
10439 				mutex_exit(&connp->conn_lock);
10440 			}
10441 			break;
10442 		case SO_EXCLBIND:
10443 			if (!checkonly)
10444 				tcp->tcp_exclbind = onoff;
10445 			break;
10446 		default:
10447 			*outlenp = 0;
10448 			return (EINVAL);
10449 		}
10450 		break;
10451 	case IPPROTO_TCP:
10452 		switch (name) {
10453 		case TCP_NODELAY:
10454 			if (!checkonly)
10455 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10456 			break;
10457 		case TCP_NOTIFY_THRESHOLD:
10458 			if (!checkonly)
10459 				tcp->tcp_first_timer_threshold = *i1;
10460 			break;
10461 		case TCP_ABORT_THRESHOLD:
10462 			if (!checkonly)
10463 				tcp->tcp_second_timer_threshold = *i1;
10464 			break;
10465 		case TCP_CONN_NOTIFY_THRESHOLD:
10466 			if (!checkonly)
10467 				tcp->tcp_first_ctimer_threshold = *i1;
10468 			break;
10469 		case TCP_CONN_ABORT_THRESHOLD:
10470 			if (!checkonly)
10471 				tcp->tcp_second_ctimer_threshold = *i1;
10472 			break;
10473 		case TCP_RECVDSTADDR:
10474 			if (tcp->tcp_state > TCPS_LISTEN)
10475 				return (EOPNOTSUPP);
10476 			if (!checkonly)
10477 				tcp->tcp_recvdstaddr = onoff;
10478 			break;
10479 		case TCP_ANONPRIVBIND:
10480 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10481 				*outlenp = 0;
10482 				return (reterr);
10483 			}
10484 			if (!checkonly) {
10485 				tcp->tcp_anon_priv_bind = onoff;
10486 			}
10487 			break;
10488 		case TCP_EXCLBIND:
10489 			if (!checkonly)
10490 				tcp->tcp_exclbind = onoff;
10491 			break;	/* goto sizeof (int) option return */
10492 		case TCP_INIT_CWND: {
10493 			uint32_t init_cwnd = *((uint32_t *)invalp);
10494 
10495 			if (checkonly)
10496 				break;
10497 
10498 			/*
10499 			 * Only allow socket with network configuration
10500 			 * privilege to set the initial cwnd to be larger
10501 			 * than allowed by RFC 3390.
10502 			 */
10503 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10504 				tcp->tcp_init_cwnd = init_cwnd;
10505 				break;
10506 			}
10507 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10508 				*outlenp = 0;
10509 				return (reterr);
10510 			}
10511 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10512 				*outlenp = 0;
10513 				return (EINVAL);
10514 			}
10515 			tcp->tcp_init_cwnd = init_cwnd;
10516 			break;
10517 		}
10518 		case TCP_KEEPALIVE_THRESHOLD:
10519 			if (checkonly)
10520 				break;
10521 
10522 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10523 			    *i1 > tcps->tcps_keepalive_interval_high) {
10524 				*outlenp = 0;
10525 				return (EINVAL);
10526 			}
10527 			if (*i1 != tcp->tcp_ka_interval) {
10528 				tcp->tcp_ka_interval = *i1;
10529 				/*
10530 				 * Check if we need to restart the
10531 				 * keepalive timer.
10532 				 */
10533 				if (tcp->tcp_ka_tid != 0) {
10534 					ASSERT(tcp->tcp_ka_enabled);
10535 					(void) TCP_TIMER_CANCEL(tcp,
10536 					    tcp->tcp_ka_tid);
10537 					tcp->tcp_ka_last_intrvl = 0;
10538 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10539 					    tcp_keepalive_killer,
10540 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10541 				}
10542 			}
10543 			break;
10544 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10545 			if (!checkonly) {
10546 				if (*i1 <
10547 				    tcps->tcps_keepalive_abort_interval_low ||
10548 				    *i1 >
10549 				    tcps->tcps_keepalive_abort_interval_high) {
10550 					*outlenp = 0;
10551 					return (EINVAL);
10552 				}
10553 				tcp->tcp_ka_abort_thres = *i1;
10554 			}
10555 			break;
10556 		case TCP_CORK:
10557 			if (!checkonly) {
10558 				/*
10559 				 * if tcp->tcp_cork was set and is now
10560 				 * being unset, we have to make sure that
10561 				 * the remaining data gets sent out. Also
10562 				 * unset tcp->tcp_cork so that tcp_wput_data()
10563 				 * can send data even if it is less than mss
10564 				 */
10565 				if (tcp->tcp_cork && onoff == 0 &&
10566 				    tcp->tcp_unsent > 0) {
10567 					tcp->tcp_cork = B_FALSE;
10568 					tcp_wput_data(tcp, NULL, B_FALSE);
10569 				}
10570 				tcp->tcp_cork = onoff;
10571 			}
10572 			break;
10573 		default:
10574 			*outlenp = 0;
10575 			return (EINVAL);
10576 		}
10577 		break;
10578 	case IPPROTO_IP:
10579 		if (tcp->tcp_family != AF_INET) {
10580 			*outlenp = 0;
10581 			return (ENOPROTOOPT);
10582 		}
10583 		switch (name) {
10584 		case IP_OPTIONS:
10585 		case T_IP_OPTIONS:
10586 			reterr = tcp_opt_set_header(tcp, checkonly,
10587 			    invalp, inlen);
10588 			if (reterr) {
10589 				*outlenp = 0;
10590 				return (reterr);
10591 			}
10592 			/* OK return - copy input buffer into output buffer */
10593 			if (invalp != outvalp) {
10594 				/* don't trust bcopy for identical src/dst */
10595 				bcopy(invalp, outvalp, inlen);
10596 			}
10597 			*outlenp = inlen;
10598 			return (0);
10599 		case IP_TOS:
10600 		case T_IP_TOS:
10601 			if (!checkonly) {
10602 				tcp->tcp_ipha->ipha_type_of_service =
10603 				    (uchar_t)*i1;
10604 				tcp->tcp_tos = (uchar_t)*i1;
10605 			}
10606 			break;
10607 		case IP_TTL:
10608 			if (!checkonly) {
10609 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10610 				tcp->tcp_ttl = (uchar_t)*i1;
10611 			}
10612 			break;
10613 		case IP_BOUND_IF:
10614 		case IP_NEXTHOP:
10615 			/* Handled at the IP level */
10616 			return (-EINVAL);
10617 		case IP_SEC_OPT:
10618 			/*
10619 			 * We should not allow policy setting after
10620 			 * we start listening for connections.
10621 			 */
10622 			if (tcp->tcp_state == TCPS_LISTEN) {
10623 				return (EINVAL);
10624 			} else {
10625 				/* Handled at the IP level */
10626 				return (-EINVAL);
10627 			}
10628 		default:
10629 			*outlenp = 0;
10630 			return (EINVAL);
10631 		}
10632 		break;
10633 	case IPPROTO_IPV6: {
10634 		ip6_pkt_t		*ipp;
10635 
10636 		/*
10637 		 * IPPROTO_IPV6 options are only supported for sockets
10638 		 * that are using IPv6 on the wire.
10639 		 */
10640 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10641 			*outlenp = 0;
10642 			return (ENOPROTOOPT);
10643 		}
10644 		/*
10645 		 * Only sticky options; no ancillary data
10646 		 */
10647 		ASSERT(thisdg_attrs == NULL);
10648 		ipp = &tcp->tcp_sticky_ipp;
10649 
10650 		switch (name) {
10651 		case IPV6_UNICAST_HOPS:
10652 			/* -1 means use default */
10653 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10654 				*outlenp = 0;
10655 				return (EINVAL);
10656 			}
10657 			if (!checkonly) {
10658 				if (*i1 == -1) {
10659 					tcp->tcp_ip6h->ip6_hops =
10660 					    ipp->ipp_unicast_hops =
10661 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10662 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10663 					/* Pass modified value to IP. */
10664 					*i1 = tcp->tcp_ip6h->ip6_hops;
10665 				} else {
10666 					tcp->tcp_ip6h->ip6_hops =
10667 					    ipp->ipp_unicast_hops =
10668 					    (uint8_t)*i1;
10669 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10670 				}
10671 				reterr = tcp_build_hdrs(q, tcp);
10672 				if (reterr != 0)
10673 					return (reterr);
10674 			}
10675 			break;
10676 		case IPV6_BOUND_IF:
10677 			if (!checkonly) {
10678 				int error = 0;
10679 
10680 				tcp->tcp_bound_if = *i1;
10681 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10682 				    B_TRUE, checkonly, level, name, mblk);
10683 				if (error != 0) {
10684 					*outlenp = 0;
10685 					return (error);
10686 				}
10687 			}
10688 			break;
10689 		/*
10690 		 * Set boolean switches for ancillary data delivery
10691 		 */
10692 		case IPV6_RECVPKTINFO:
10693 			if (!checkonly) {
10694 				if (onoff)
10695 					tcp->tcp_ipv6_recvancillary |=
10696 					    TCP_IPV6_RECVPKTINFO;
10697 				else
10698 					tcp->tcp_ipv6_recvancillary &=
10699 					    ~TCP_IPV6_RECVPKTINFO;
10700 				/* Force it to be sent up with the next msg */
10701 				tcp->tcp_recvifindex = 0;
10702 			}
10703 			break;
10704 		case IPV6_RECVTCLASS:
10705 			if (!checkonly) {
10706 				if (onoff)
10707 					tcp->tcp_ipv6_recvancillary |=
10708 					    TCP_IPV6_RECVTCLASS;
10709 				else
10710 					tcp->tcp_ipv6_recvancillary &=
10711 					    ~TCP_IPV6_RECVTCLASS;
10712 			}
10713 			break;
10714 		case IPV6_RECVHOPLIMIT:
10715 			if (!checkonly) {
10716 				if (onoff)
10717 					tcp->tcp_ipv6_recvancillary |=
10718 					    TCP_IPV6_RECVHOPLIMIT;
10719 				else
10720 					tcp->tcp_ipv6_recvancillary &=
10721 					    ~TCP_IPV6_RECVHOPLIMIT;
10722 				/* Force it to be sent up with the next msg */
10723 				tcp->tcp_recvhops = 0xffffffffU;
10724 			}
10725 			break;
10726 		case IPV6_RECVHOPOPTS:
10727 			if (!checkonly) {
10728 				if (onoff)
10729 					tcp->tcp_ipv6_recvancillary |=
10730 					    TCP_IPV6_RECVHOPOPTS;
10731 				else
10732 					tcp->tcp_ipv6_recvancillary &=
10733 					    ~TCP_IPV6_RECVHOPOPTS;
10734 			}
10735 			break;
10736 		case IPV6_RECVDSTOPTS:
10737 			if (!checkonly) {
10738 				if (onoff)
10739 					tcp->tcp_ipv6_recvancillary |=
10740 					    TCP_IPV6_RECVDSTOPTS;
10741 				else
10742 					tcp->tcp_ipv6_recvancillary &=
10743 					    ~TCP_IPV6_RECVDSTOPTS;
10744 			}
10745 			break;
10746 		case _OLD_IPV6_RECVDSTOPTS:
10747 			if (!checkonly) {
10748 				if (onoff)
10749 					tcp->tcp_ipv6_recvancillary |=
10750 					    TCP_OLD_IPV6_RECVDSTOPTS;
10751 				else
10752 					tcp->tcp_ipv6_recvancillary &=
10753 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10754 			}
10755 			break;
10756 		case IPV6_RECVRTHDR:
10757 			if (!checkonly) {
10758 				if (onoff)
10759 					tcp->tcp_ipv6_recvancillary |=
10760 					    TCP_IPV6_RECVRTHDR;
10761 				else
10762 					tcp->tcp_ipv6_recvancillary &=
10763 					    ~TCP_IPV6_RECVRTHDR;
10764 			}
10765 			break;
10766 		case IPV6_RECVRTHDRDSTOPTS:
10767 			if (!checkonly) {
10768 				if (onoff)
10769 					tcp->tcp_ipv6_recvancillary |=
10770 					    TCP_IPV6_RECVRTDSTOPTS;
10771 				else
10772 					tcp->tcp_ipv6_recvancillary &=
10773 					    ~TCP_IPV6_RECVRTDSTOPTS;
10774 			}
10775 			break;
10776 		case IPV6_PKTINFO:
10777 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10778 				return (EINVAL);
10779 			if (checkonly)
10780 				break;
10781 
10782 			if (inlen == 0) {
10783 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10784 			} else {
10785 				struct in6_pktinfo *pkti;
10786 
10787 				pkti = (struct in6_pktinfo *)invalp;
10788 				/*
10789 				 * RFC 3542 states that ipi6_addr must be
10790 				 * the unspecified address when setting the
10791 				 * IPV6_PKTINFO sticky socket option on a
10792 				 * TCP socket.
10793 				 */
10794 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10795 					return (EINVAL);
10796 				/*
10797 				 * ip6_set_pktinfo() validates the source
10798 				 * address and interface index.
10799 				 */
10800 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10801 				    pkti, mblk);
10802 				if (reterr != 0)
10803 					return (reterr);
10804 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10805 				ipp->ipp_addr = pkti->ipi6_addr;
10806 				if (ipp->ipp_ifindex != 0)
10807 					ipp->ipp_fields |= IPPF_IFINDEX;
10808 				else
10809 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10810 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10811 					ipp->ipp_fields |= IPPF_ADDR;
10812 				else
10813 					ipp->ipp_fields &= ~IPPF_ADDR;
10814 			}
10815 			reterr = tcp_build_hdrs(q, tcp);
10816 			if (reterr != 0)
10817 				return (reterr);
10818 			break;
10819 		case IPV6_TCLASS:
10820 			if (inlen != 0 && inlen != sizeof (int))
10821 				return (EINVAL);
10822 			if (checkonly)
10823 				break;
10824 
10825 			if (inlen == 0) {
10826 				ipp->ipp_fields &= ~IPPF_TCLASS;
10827 			} else {
10828 				if (*i1 > 255 || *i1 < -1)
10829 					return (EINVAL);
10830 				if (*i1 == -1) {
10831 					ipp->ipp_tclass = 0;
10832 					*i1 = 0;
10833 				} else {
10834 					ipp->ipp_tclass = *i1;
10835 				}
10836 				ipp->ipp_fields |= IPPF_TCLASS;
10837 			}
10838 			reterr = tcp_build_hdrs(q, tcp);
10839 			if (reterr != 0)
10840 				return (reterr);
10841 			break;
10842 		case IPV6_NEXTHOP:
10843 			/*
10844 			 * IP will verify that the nexthop is reachable
10845 			 * and fail for sticky options.
10846 			 */
10847 			if (inlen != 0 && inlen != sizeof (sin6_t))
10848 				return (EINVAL);
10849 			if (checkonly)
10850 				break;
10851 
10852 			if (inlen == 0) {
10853 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10854 			} else {
10855 				sin6_t *sin6 = (sin6_t *)invalp;
10856 
10857 				if (sin6->sin6_family != AF_INET6)
10858 					return (EAFNOSUPPORT);
10859 				if (IN6_IS_ADDR_V4MAPPED(
10860 				    &sin6->sin6_addr))
10861 					return (EADDRNOTAVAIL);
10862 				ipp->ipp_nexthop = sin6->sin6_addr;
10863 				if (!IN6_IS_ADDR_UNSPECIFIED(
10864 				    &ipp->ipp_nexthop))
10865 					ipp->ipp_fields |= IPPF_NEXTHOP;
10866 				else
10867 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10868 			}
10869 			reterr = tcp_build_hdrs(q, tcp);
10870 			if (reterr != 0)
10871 				return (reterr);
10872 			break;
10873 		case IPV6_HOPOPTS: {
10874 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10875 
10876 			/*
10877 			 * Sanity checks - minimum size, size a multiple of
10878 			 * eight bytes, and matching size passed in.
10879 			 */
10880 			if (inlen != 0 &&
10881 			    inlen != (8 * (hopts->ip6h_len + 1)))
10882 				return (EINVAL);
10883 
10884 			if (checkonly)
10885 				break;
10886 
10887 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10888 			    (uchar_t **)&ipp->ipp_hopopts,
10889 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10890 			if (reterr != 0)
10891 				return (reterr);
10892 			if (ipp->ipp_hopoptslen == 0)
10893 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10894 			else
10895 				ipp->ipp_fields |= IPPF_HOPOPTS;
10896 			reterr = tcp_build_hdrs(q, tcp);
10897 			if (reterr != 0)
10898 				return (reterr);
10899 			break;
10900 		}
10901 		case IPV6_RTHDRDSTOPTS: {
10902 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10903 
10904 			/*
10905 			 * Sanity checks - minimum size, size a multiple of
10906 			 * eight bytes, and matching size passed in.
10907 			 */
10908 			if (inlen != 0 &&
10909 			    inlen != (8 * (dopts->ip6d_len + 1)))
10910 				return (EINVAL);
10911 
10912 			if (checkonly)
10913 				break;
10914 
10915 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10916 			    (uchar_t **)&ipp->ipp_rtdstopts,
10917 			    &ipp->ipp_rtdstoptslen, 0);
10918 			if (reterr != 0)
10919 				return (reterr);
10920 			if (ipp->ipp_rtdstoptslen == 0)
10921 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10922 			else
10923 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10924 			reterr = tcp_build_hdrs(q, tcp);
10925 			if (reterr != 0)
10926 				return (reterr);
10927 			break;
10928 		}
10929 		case IPV6_DSTOPTS: {
10930 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10931 
10932 			/*
10933 			 * Sanity checks - minimum size, size a multiple of
10934 			 * eight bytes, and matching size passed in.
10935 			 */
10936 			if (inlen != 0 &&
10937 			    inlen != (8 * (dopts->ip6d_len + 1)))
10938 				return (EINVAL);
10939 
10940 			if (checkonly)
10941 				break;
10942 
10943 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10944 			    (uchar_t **)&ipp->ipp_dstopts,
10945 			    &ipp->ipp_dstoptslen, 0);
10946 			if (reterr != 0)
10947 				return (reterr);
10948 			if (ipp->ipp_dstoptslen == 0)
10949 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10950 			else
10951 				ipp->ipp_fields |= IPPF_DSTOPTS;
10952 			reterr = tcp_build_hdrs(q, tcp);
10953 			if (reterr != 0)
10954 				return (reterr);
10955 			break;
10956 		}
10957 		case IPV6_RTHDR: {
10958 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10959 
10960 			/*
10961 			 * Sanity checks - minimum size, size a multiple of
10962 			 * eight bytes, and matching size passed in.
10963 			 */
10964 			if (inlen != 0 &&
10965 			    inlen != (8 * (rt->ip6r_len + 1)))
10966 				return (EINVAL);
10967 
10968 			if (checkonly)
10969 				break;
10970 
10971 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10972 			    (uchar_t **)&ipp->ipp_rthdr,
10973 			    &ipp->ipp_rthdrlen, 0);
10974 			if (reterr != 0)
10975 				return (reterr);
10976 			if (ipp->ipp_rthdrlen == 0)
10977 				ipp->ipp_fields &= ~IPPF_RTHDR;
10978 			else
10979 				ipp->ipp_fields |= IPPF_RTHDR;
10980 			reterr = tcp_build_hdrs(q, tcp);
10981 			if (reterr != 0)
10982 				return (reterr);
10983 			break;
10984 		}
10985 		case IPV6_V6ONLY:
10986 			if (!checkonly)
10987 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10988 			break;
10989 		case IPV6_USE_MIN_MTU:
10990 			if (inlen != sizeof (int))
10991 				return (EINVAL);
10992 
10993 			if (*i1 < -1 || *i1 > 1)
10994 				return (EINVAL);
10995 
10996 			if (checkonly)
10997 				break;
10998 
10999 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11000 			ipp->ipp_use_min_mtu = *i1;
11001 			break;
11002 		case IPV6_BOUND_PIF:
11003 			/* Handled at the IP level */
11004 			return (-EINVAL);
11005 		case IPV6_SEC_OPT:
11006 			/*
11007 			 * We should not allow policy setting after
11008 			 * we start listening for connections.
11009 			 */
11010 			if (tcp->tcp_state == TCPS_LISTEN) {
11011 				return (EINVAL);
11012 			} else {
11013 				/* Handled at the IP level */
11014 				return (-EINVAL);
11015 			}
11016 		case IPV6_SRC_PREFERENCES:
11017 			if (inlen != sizeof (uint32_t))
11018 				return (EINVAL);
11019 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11020 			    *(uint32_t *)invalp);
11021 			if (reterr != 0) {
11022 				*outlenp = 0;
11023 				return (reterr);
11024 			}
11025 			break;
11026 		default:
11027 			*outlenp = 0;
11028 			return (EINVAL);
11029 		}
11030 		break;
11031 	}		/* end IPPROTO_IPV6 */
11032 	default:
11033 		*outlenp = 0;
11034 		return (EINVAL);
11035 	}
11036 	/*
11037 	 * Common case of OK return with outval same as inval
11038 	 */
11039 	if (invalp != outvalp) {
11040 		/* don't trust bcopy for identical src/dst */
11041 		(void) bcopy(invalp, outvalp, inlen);
11042 	}
11043 	*outlenp = inlen;
11044 	return (0);
11045 }
11046 
11047 /*
11048  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11049  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11050  * headers, and the maximum size tcp header (to avoid reallocation
11051  * on the fly for additional tcp options).
11052  * Returns failure if can't allocate memory.
11053  */
11054 static int
11055 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11056 {
11057 	char	*hdrs;
11058 	uint_t	hdrs_len;
11059 	ip6i_t	*ip6i;
11060 	char	buf[TCP_MAX_HDR_LENGTH];
11061 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11062 	in6_addr_t src, dst;
11063 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11064 
11065 	/*
11066 	 * save the existing tcp header and source/dest IP addresses
11067 	 */
11068 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11069 	src = tcp->tcp_ip6h->ip6_src;
11070 	dst = tcp->tcp_ip6h->ip6_dst;
11071 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11072 	ASSERT(hdrs_len != 0);
11073 	if (hdrs_len > tcp->tcp_iphc_len) {
11074 		/* Need to reallocate */
11075 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11076 		if (hdrs == NULL)
11077 			return (ENOMEM);
11078 		if (tcp->tcp_iphc != NULL) {
11079 			if (tcp->tcp_hdr_grown) {
11080 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11081 			} else {
11082 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11083 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11084 			}
11085 			tcp->tcp_iphc_len = 0;
11086 		}
11087 		ASSERT(tcp->tcp_iphc_len == 0);
11088 		tcp->tcp_iphc = hdrs;
11089 		tcp->tcp_iphc_len = hdrs_len;
11090 		tcp->tcp_hdr_grown = B_TRUE;
11091 	}
11092 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11093 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11094 
11095 	/* Set header fields not in ipp */
11096 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11097 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11098 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11099 	} else {
11100 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11101 	}
11102 	/*
11103 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11104 	 *
11105 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11106 	 */
11107 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11108 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11109 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11110 
11111 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11112 
11113 	tcp->tcp_ip6h->ip6_src = src;
11114 	tcp->tcp_ip6h->ip6_dst = dst;
11115 
11116 	/*
11117 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11118 	 * the default value for TCP.
11119 	 */
11120 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11121 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11122 
11123 	/*
11124 	 * If we're setting extension headers after a connection
11125 	 * has been established, and if we have a routing header
11126 	 * among the extension headers, call ip_massage_options_v6 to
11127 	 * manipulate the routing header/ip6_dst set the checksum
11128 	 * difference in the tcp header template.
11129 	 * (This happens in tcp_connect_ipv6 if the routing header
11130 	 * is set prior to the connect.)
11131 	 * Set the tcp_sum to zero first in case we've cleared a
11132 	 * routing header or don't have one at all.
11133 	 */
11134 	tcp->tcp_sum = 0;
11135 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11136 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11137 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11138 		    (uint8_t *)tcp->tcp_tcph);
11139 		if (rth != NULL) {
11140 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11141 			    rth, tcps->tcps_netstack);
11142 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11143 			    (tcp->tcp_sum >> 16));
11144 		}
11145 	}
11146 
11147 	/* Try to get everything in a single mblk */
11148 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11149 	return (0);
11150 }
11151 
11152 /*
11153  * Transfer any source route option from ipha to buf/dst in reversed form.
11154  */
11155 static int
11156 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11157 {
11158 	ipoptp_t	opts;
11159 	uchar_t		*opt;
11160 	uint8_t		optval;
11161 	uint8_t		optlen;
11162 	uint32_t	len = 0;
11163 
11164 	for (optval = ipoptp_first(&opts, ipha);
11165 	    optval != IPOPT_EOL;
11166 	    optval = ipoptp_next(&opts)) {
11167 		opt = opts.ipoptp_cur;
11168 		optlen = opts.ipoptp_len;
11169 		switch (optval) {
11170 			int	off1, off2;
11171 		case IPOPT_SSRR:
11172 		case IPOPT_LSRR:
11173 
11174 			/* Reverse source route */
11175 			/*
11176 			 * First entry should be the next to last one in the
11177 			 * current source route (the last entry is our
11178 			 * address.)
11179 			 * The last entry should be the final destination.
11180 			 */
11181 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11182 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11183 			off1 = IPOPT_MINOFF_SR - 1;
11184 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11185 			if (off2 < 0) {
11186 				/* No entries in source route */
11187 				break;
11188 			}
11189 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11190 			/*
11191 			 * Note: use src since ipha has not had its src
11192 			 * and dst reversed (it is in the state it was
11193 			 * received.
11194 			 */
11195 			bcopy(&ipha->ipha_src, buf + off2,
11196 			    IP_ADDR_LEN);
11197 			off2 -= IP_ADDR_LEN;
11198 
11199 			while (off2 > 0) {
11200 				bcopy(opt + off2, buf + off1,
11201 				    IP_ADDR_LEN);
11202 				off1 += IP_ADDR_LEN;
11203 				off2 -= IP_ADDR_LEN;
11204 			}
11205 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11206 			buf += optlen;
11207 			len += optlen;
11208 			break;
11209 		}
11210 	}
11211 done:
11212 	/* Pad the resulting options */
11213 	while (len & 0x3) {
11214 		*buf++ = IPOPT_EOL;
11215 		len++;
11216 	}
11217 	return (len);
11218 }
11219 
11220 
11221 /*
11222  * Extract and revert a source route from ipha (if any)
11223  * and then update the relevant fields in both tcp_t and the standard header.
11224  */
11225 static void
11226 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11227 {
11228 	char	buf[TCP_MAX_HDR_LENGTH];
11229 	uint_t	tcph_len;
11230 	int	len;
11231 
11232 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11233 	len = IPH_HDR_LENGTH(ipha);
11234 	if (len == IP_SIMPLE_HDR_LENGTH)
11235 		/* Nothing to do */
11236 		return;
11237 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11238 	    (len & 0x3))
11239 		return;
11240 
11241 	tcph_len = tcp->tcp_tcp_hdr_len;
11242 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11243 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11244 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11245 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11246 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11247 	len += IP_SIMPLE_HDR_LENGTH;
11248 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11249 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11250 	if ((int)tcp->tcp_sum < 0)
11251 		tcp->tcp_sum--;
11252 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11253 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11254 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11255 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11256 	tcp->tcp_ip_hdr_len = len;
11257 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11258 	    (IP_VERSION << 4) | (len >> 2);
11259 	len += tcph_len;
11260 	tcp->tcp_hdr_len = len;
11261 }
11262 
11263 /*
11264  * Copy the standard header into its new location,
11265  * lay in the new options and then update the relevant
11266  * fields in both tcp_t and the standard header.
11267  */
11268 static int
11269 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11270 {
11271 	uint_t	tcph_len;
11272 	uint8_t	*ip_optp;
11273 	tcph_t	*new_tcph;
11274 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11275 
11276 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11277 		return (EINVAL);
11278 
11279 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11280 		return (EINVAL);
11281 
11282 	if (checkonly) {
11283 		/*
11284 		 * do not really set, just pretend to - T_CHECK
11285 		 */
11286 		return (0);
11287 	}
11288 
11289 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11290 	if (tcp->tcp_label_len > 0) {
11291 		int padlen;
11292 		uint8_t opt;
11293 
11294 		/* convert list termination to no-ops */
11295 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11296 		ip_optp += ip_optp[IPOPT_OLEN];
11297 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11298 		while (--padlen >= 0)
11299 			*ip_optp++ = opt;
11300 	}
11301 	tcph_len = tcp->tcp_tcp_hdr_len;
11302 	new_tcph = (tcph_t *)(ip_optp + len);
11303 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11304 	tcp->tcp_tcph = new_tcph;
11305 	bcopy(ptr, ip_optp, len);
11306 
11307 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11308 
11309 	tcp->tcp_ip_hdr_len = len;
11310 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11311 	    (IP_VERSION << 4) | (len >> 2);
11312 	tcp->tcp_hdr_len = len + tcph_len;
11313 	if (!TCP_IS_DETACHED(tcp)) {
11314 		/* Always allocate room for all options. */
11315 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11316 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11317 	}
11318 	return (0);
11319 }
11320 
11321 /* Get callback routine passed to nd_load by tcp_param_register */
11322 /* ARGSUSED */
11323 static int
11324 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11325 {
11326 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11327 
11328 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11329 	return (0);
11330 }
11331 
11332 /*
11333  * Walk through the param array specified registering each element with the
11334  * named dispatch handler.
11335  */
11336 static boolean_t
11337 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11338 {
11339 	for (; cnt-- > 0; tcppa++) {
11340 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11341 			if (!nd_load(ndp, tcppa->tcp_param_name,
11342 			    tcp_param_get, tcp_param_set,
11343 			    (caddr_t)tcppa)) {
11344 				nd_free(ndp);
11345 				return (B_FALSE);
11346 			}
11347 		}
11348 	}
11349 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11350 	    KM_SLEEP);
11351 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11352 	    sizeof (tcpparam_t));
11353 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11354 	    tcp_param_get, tcp_param_set_aligned,
11355 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11356 		nd_free(ndp);
11357 		return (B_FALSE);
11358 	}
11359 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11360 	    KM_SLEEP);
11361 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11362 	    sizeof (tcpparam_t));
11363 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11364 	    tcp_param_get, tcp_param_set_aligned,
11365 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11366 		nd_free(ndp);
11367 		return (B_FALSE);
11368 	}
11369 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11370 	    KM_SLEEP);
11371 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11372 	    sizeof (tcpparam_t));
11373 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11374 	    tcp_param_get, tcp_param_set_aligned,
11375 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11376 		nd_free(ndp);
11377 		return (B_FALSE);
11378 	}
11379 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11380 	    KM_SLEEP);
11381 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11382 	    sizeof (tcpparam_t));
11383 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11384 	    tcp_param_get, tcp_param_set_aligned,
11385 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11386 		nd_free(ndp);
11387 		return (B_FALSE);
11388 	}
11389 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11390 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11391 		nd_free(ndp);
11392 		return (B_FALSE);
11393 	}
11394 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11395 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11396 		nd_free(ndp);
11397 		return (B_FALSE);
11398 	}
11399 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11400 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11401 		nd_free(ndp);
11402 		return (B_FALSE);
11403 	}
11404 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11405 	    NULL)) {
11406 		nd_free(ndp);
11407 		return (B_FALSE);
11408 	}
11409 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11410 	    NULL, NULL)) {
11411 		nd_free(ndp);
11412 		return (B_FALSE);
11413 	}
11414 	if (!nd_load(ndp, "tcp_listen_hash",
11415 	    tcp_listen_hash_report, NULL, NULL)) {
11416 		nd_free(ndp);
11417 		return (B_FALSE);
11418 	}
11419 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11420 	    NULL, NULL)) {
11421 		nd_free(ndp);
11422 		return (B_FALSE);
11423 	}
11424 	if (!nd_load(ndp, "tcp_acceptor_hash",
11425 	    tcp_acceptor_hash_report, NULL, NULL)) {
11426 		nd_free(ndp);
11427 		return (B_FALSE);
11428 	}
11429 	if (!nd_load(ndp, "tcp_host_param", tcp_host_param_report,
11430 	    tcp_host_param_set, NULL)) {
11431 		nd_free(ndp);
11432 		return (B_FALSE);
11433 	}
11434 	if (!nd_load(ndp, "tcp_host_param_ipv6",
11435 	    tcp_host_param_report, tcp_host_param_set_ipv6, NULL)) {
11436 		nd_free(ndp);
11437 		return (B_FALSE);
11438 	}
11439 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11440 	    tcp_1948_phrase_set, NULL)) {
11441 		nd_free(ndp);
11442 		return (B_FALSE);
11443 	}
11444 	if (!nd_load(ndp, "tcp_reserved_port_list",
11445 	    tcp_reserved_port_list, NULL, NULL)) {
11446 		nd_free(ndp);
11447 		return (B_FALSE);
11448 	}
11449 	/*
11450 	 * Dummy ndd variables - only to convey obsolescence information
11451 	 * through printing of their name (no get or set routines)
11452 	 * XXX Remove in future releases ?
11453 	 */
11454 	if (!nd_load(ndp,
11455 	    "tcp_close_wait_interval(obsoleted - "
11456 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11457 		nd_free(ndp);
11458 		return (B_FALSE);
11459 	}
11460 	return (B_TRUE);
11461 }
11462 
11463 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11464 /* ARGSUSED */
11465 static int
11466 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11467     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 	/*
11478 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11479 	 * round it up.  For future 64 bit requirement, we actually make it
11480 	 * a multiple of 8.
11481 	 */
11482 	if (new_value & 0x7) {
11483 		new_value = (new_value & ~0x7) + 0x8;
11484 	}
11485 	tcppa->tcp_param_val = new_value;
11486 	return (0);
11487 }
11488 
11489 /* Set callback routine passed to nd_load by tcp_param_register */
11490 /* ARGSUSED */
11491 static int
11492 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11493 {
11494 	long	new_value;
11495 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11496 
11497 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11498 	    new_value < tcppa->tcp_param_min ||
11499 	    new_value > tcppa->tcp_param_max) {
11500 		return (EINVAL);
11501 	}
11502 	tcppa->tcp_param_val = new_value;
11503 	return (0);
11504 }
11505 
11506 /*
11507  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11508  * is filled, return as much as we can.  The message passed in may be
11509  * multi-part, chained using b_cont.  "start" is the starting sequence
11510  * number for this piece.
11511  */
11512 static mblk_t *
11513 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11514 {
11515 	uint32_t	end;
11516 	mblk_t		*mp1;
11517 	mblk_t		*mp2;
11518 	mblk_t		*next_mp;
11519 	uint32_t	u1;
11520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11521 
11522 	/* Walk through all the new pieces. */
11523 	do {
11524 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11525 		    (uintptr_t)INT_MAX);
11526 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11527 		next_mp = mp->b_cont;
11528 		if (start == end) {
11529 			/* Empty.  Blast it. */
11530 			freeb(mp);
11531 			continue;
11532 		}
11533 		mp->b_cont = NULL;
11534 		TCP_REASS_SET_SEQ(mp, start);
11535 		TCP_REASS_SET_END(mp, end);
11536 		mp1 = tcp->tcp_reass_tail;
11537 		if (!mp1) {
11538 			tcp->tcp_reass_tail = mp;
11539 			tcp->tcp_reass_head = mp;
11540 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11541 			UPDATE_MIB(&tcps->tcps_mib,
11542 			    tcpInDataUnorderBytes, end - start);
11543 			continue;
11544 		}
11545 		/* New stuff completely beyond tail? */
11546 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11547 			/* Link it on end. */
11548 			mp1->b_cont = mp;
11549 			tcp->tcp_reass_tail = mp;
11550 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11551 			UPDATE_MIB(&tcps->tcps_mib,
11552 			    tcpInDataUnorderBytes, end - start);
11553 			continue;
11554 		}
11555 		mp1 = tcp->tcp_reass_head;
11556 		u1 = TCP_REASS_SEQ(mp1);
11557 		/* New stuff at the front? */
11558 		if (SEQ_LT(start, u1)) {
11559 			/* Yes... Check for overlap. */
11560 			mp->b_cont = mp1;
11561 			tcp->tcp_reass_head = mp;
11562 			tcp_reass_elim_overlap(tcp, mp);
11563 			continue;
11564 		}
11565 		/*
11566 		 * The new piece fits somewhere between the head and tail.
11567 		 * We find our slot, where mp1 precedes us and mp2 trails.
11568 		 */
11569 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11570 			u1 = TCP_REASS_SEQ(mp2);
11571 			if (SEQ_LEQ(start, u1))
11572 				break;
11573 		}
11574 		/* Link ourselves in */
11575 		mp->b_cont = mp2;
11576 		mp1->b_cont = mp;
11577 
11578 		/* Trim overlap with following mblk(s) first */
11579 		tcp_reass_elim_overlap(tcp, mp);
11580 
11581 		/* Trim overlap with preceding mblk */
11582 		tcp_reass_elim_overlap(tcp, mp1);
11583 
11584 	} while (start = end, mp = next_mp);
11585 	mp1 = tcp->tcp_reass_head;
11586 	/* Anything ready to go? */
11587 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11588 		return (NULL);
11589 	/* Eat what we can off the queue */
11590 	for (;;) {
11591 		mp = mp1->b_cont;
11592 		end = TCP_REASS_END(mp1);
11593 		TCP_REASS_SET_SEQ(mp1, 0);
11594 		TCP_REASS_SET_END(mp1, 0);
11595 		if (!mp) {
11596 			tcp->tcp_reass_tail = NULL;
11597 			break;
11598 		}
11599 		if (end != TCP_REASS_SEQ(mp)) {
11600 			mp1->b_cont = NULL;
11601 			break;
11602 		}
11603 		mp1 = mp;
11604 	}
11605 	mp1 = tcp->tcp_reass_head;
11606 	tcp->tcp_reass_head = mp;
11607 	return (mp1);
11608 }
11609 
11610 /* Eliminate any overlap that mp may have over later mblks */
11611 static void
11612 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11613 {
11614 	uint32_t	end;
11615 	mblk_t		*mp1;
11616 	uint32_t	u1;
11617 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11618 
11619 	end = TCP_REASS_END(mp);
11620 	while ((mp1 = mp->b_cont) != NULL) {
11621 		u1 = TCP_REASS_SEQ(mp1);
11622 		if (!SEQ_GT(end, u1))
11623 			break;
11624 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11625 			mp->b_wptr -= end - u1;
11626 			TCP_REASS_SET_END(mp, u1);
11627 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11628 			UPDATE_MIB(&tcps->tcps_mib,
11629 			    tcpInDataPartDupBytes, end - u1);
11630 			break;
11631 		}
11632 		mp->b_cont = mp1->b_cont;
11633 		TCP_REASS_SET_SEQ(mp1, 0);
11634 		TCP_REASS_SET_END(mp1, 0);
11635 		freeb(mp1);
11636 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11637 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11638 	}
11639 	if (!mp1)
11640 		tcp->tcp_reass_tail = mp;
11641 }
11642 
11643 /*
11644  * Send up all messages queued on tcp_rcv_list.
11645  */
11646 static uint_t
11647 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11648 {
11649 	mblk_t *mp;
11650 	uint_t ret = 0;
11651 	uint_t thwin;
11652 #ifdef DEBUG
11653 	uint_t cnt = 0;
11654 #endif
11655 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11656 
11657 	/* Can't drain on an eager connection */
11658 	if (tcp->tcp_listener != NULL)
11659 		return (ret);
11660 
11661 	/*
11662 	 * Handle two cases here: we are currently fused or we were
11663 	 * previously fused and have some urgent data to be delivered
11664 	 * upstream.  The latter happens because we either ran out of
11665 	 * memory or were detached and therefore sending the SIGURG was
11666 	 * deferred until this point.  In either case we pass control
11667 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11668 	 * some work.
11669 	 */
11670 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11671 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11672 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11673 		    &tcp->tcp_fused_sigurg_mp))
11674 			return (ret);
11675 	}
11676 
11677 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11678 		tcp->tcp_rcv_list = mp->b_next;
11679 		mp->b_next = NULL;
11680 #ifdef DEBUG
11681 		cnt += msgdsize(mp);
11682 #endif
11683 		/* Does this need SSL processing first? */
11684 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11685 			tcp_kssl_input(tcp, mp);
11686 			continue;
11687 		}
11688 		putnext(q, mp);
11689 	}
11690 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11691 	tcp->tcp_rcv_last_head = NULL;
11692 	tcp->tcp_rcv_last_tail = NULL;
11693 	tcp->tcp_rcv_cnt = 0;
11694 
11695 	/* Learn the latest rwnd information that we sent to the other side. */
11696 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11697 	    << tcp->tcp_rcv_ws;
11698 	/* This is peer's calculated send window (our receive window). */
11699 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11700 	/*
11701 	 * Increase the receive window to max.  But we need to do receiver
11702 	 * SWS avoidance.  This means that we need to check the increase of
11703 	 * of receive window is at least 1 MSS.
11704 	 */
11705 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11706 		/*
11707 		 * If the window that the other side knows is less than max
11708 		 * deferred acks segments, send an update immediately.
11709 		 */
11710 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11711 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11712 			ret = TH_ACK_NEEDED;
11713 		}
11714 		tcp->tcp_rwnd = q->q_hiwat;
11715 	}
11716 	/* No need for the push timer now. */
11717 	if (tcp->tcp_push_tid != 0) {
11718 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11719 		tcp->tcp_push_tid = 0;
11720 	}
11721 	return (ret);
11722 }
11723 
11724 /*
11725  * Queue data on tcp_rcv_list which is a b_next chain.
11726  * tcp_rcv_last_head/tail is the last element of this chain.
11727  * Each element of the chain is a b_cont chain.
11728  *
11729  * M_DATA messages are added to the current element.
11730  * Other messages are added as new (b_next) elements.
11731  */
11732 void
11733 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11734 {
11735 	ASSERT(seg_len == msgdsize(mp));
11736 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11737 
11738 	if (tcp->tcp_rcv_list == NULL) {
11739 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11740 		tcp->tcp_rcv_list = mp;
11741 		tcp->tcp_rcv_last_head = mp;
11742 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11743 		tcp->tcp_rcv_last_tail->b_cont = mp;
11744 	} else {
11745 		tcp->tcp_rcv_last_head->b_next = mp;
11746 		tcp->tcp_rcv_last_head = mp;
11747 	}
11748 
11749 	while (mp->b_cont)
11750 		mp = mp->b_cont;
11751 
11752 	tcp->tcp_rcv_last_tail = mp;
11753 	tcp->tcp_rcv_cnt += seg_len;
11754 	tcp->tcp_rwnd -= seg_len;
11755 }
11756 
11757 /*
11758  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11759  *
11760  * This is the default entry function into TCP on the read side. TCP is
11761  * always entered via squeue i.e. using squeue's for mutual exclusion.
11762  * When classifier does a lookup to find the tcp, it also puts a reference
11763  * on the conn structure associated so the tcp is guaranteed to exist
11764  * when we come here. We still need to check the state because it might
11765  * as well has been closed. The squeue processing function i.e. squeue_enter,
11766  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11767  * CONN_DEC_REF.
11768  *
11769  * Apart from the default entry point, IP also sends packets directly to
11770  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11771  * connections.
11772  */
11773 void
11774 tcp_input(void *arg, mblk_t *mp, void *arg2)
11775 {
11776 	conn_t	*connp = (conn_t *)arg;
11777 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11778 
11779 	/* arg2 is the sqp */
11780 	ASSERT(arg2 != NULL);
11781 	ASSERT(mp != NULL);
11782 
11783 	/*
11784 	 * Don't accept any input on a closed tcp as this TCP logically does
11785 	 * not exist on the system. Don't proceed further with this TCP.
11786 	 * For eg. this packet could trigger another close of this tcp
11787 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11788 	 * tcp_clean_death / tcp_closei_local must be called at most once
11789 	 * on a TCP. In this case we need to refeed the packet into the
11790 	 * classifier and figure out where the packet should go. Need to
11791 	 * preserve the recv_ill somehow. Until we figure that out, for
11792 	 * now just drop the packet if we can't classify the packet.
11793 	 */
11794 	if (tcp->tcp_state == TCPS_CLOSED ||
11795 	    tcp->tcp_state == TCPS_BOUND) {
11796 		conn_t	*new_connp;
11797 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11798 
11799 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11800 		if (new_connp != NULL) {
11801 			tcp_reinput(new_connp, mp, arg2);
11802 			return;
11803 		}
11804 		/* We failed to classify. For now just drop the packet */
11805 		freemsg(mp);
11806 		return;
11807 	}
11808 
11809 	if (DB_TYPE(mp) == M_DATA)
11810 		tcp_rput_data(connp, mp, arg2);
11811 	else
11812 		tcp_rput_common(tcp, mp);
11813 }
11814 
11815 /*
11816  * The read side put procedure.
11817  * The packets passed up by ip are assume to be aligned according to
11818  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11819  */
11820 static void
11821 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11822 {
11823 	/*
11824 	 * tcp_rput_data() does not expect M_CTL except for the case
11825 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11826 	 * type. Need to make sure that any other M_CTLs don't make
11827 	 * it to tcp_rput_data since it is not expecting any and doesn't
11828 	 * check for it.
11829 	 */
11830 	if (DB_TYPE(mp) == M_CTL) {
11831 		switch (*(uint32_t *)(mp->b_rptr)) {
11832 		case TCP_IOC_ABORT_CONN:
11833 			/*
11834 			 * Handle connection abort request.
11835 			 */
11836 			tcp_ioctl_abort_handler(tcp, mp);
11837 			return;
11838 		case IPSEC_IN:
11839 			/*
11840 			 * Only secure icmp arrive in TCP and they
11841 			 * don't go through data path.
11842 			 */
11843 			tcp_icmp_error(tcp, mp);
11844 			return;
11845 		case IN_PKTINFO:
11846 			/*
11847 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11848 			 * sockets that are receiving IPv4 traffic. tcp
11849 			 */
11850 			ASSERT(tcp->tcp_family == AF_INET6);
11851 			ASSERT(tcp->tcp_ipv6_recvancillary &
11852 			    TCP_IPV6_RECVPKTINFO);
11853 			tcp_rput_data(tcp->tcp_connp, mp,
11854 			    tcp->tcp_connp->conn_sqp);
11855 			return;
11856 		case MDT_IOC_INFO_UPDATE:
11857 			/*
11858 			 * Handle Multidata information update; the
11859 			 * following routine will free the message.
11860 			 */
11861 			if (tcp->tcp_connp->conn_mdt_ok) {
11862 				tcp_mdt_update(tcp,
11863 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11864 				    B_FALSE);
11865 			}
11866 			freemsg(mp);
11867 			return;
11868 		case LSO_IOC_INFO_UPDATE:
11869 			/*
11870 			 * Handle LSO information update; the following
11871 			 * routine will free the message.
11872 			 */
11873 			if (tcp->tcp_connp->conn_lso_ok) {
11874 				tcp_lso_update(tcp,
11875 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11876 			}
11877 			freemsg(mp);
11878 			return;
11879 		default:
11880 			/*
11881 			 * tcp_icmp_err() will process the M_CTL packets.
11882 			 * Non-ICMP packets, if any, will be discarded in
11883 			 * tcp_icmp_err(). We will process the ICMP packet
11884 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11885 			 * incoming ICMP packet may result in changing
11886 			 * the tcp_mss, which we would need if we have
11887 			 * packets to retransmit.
11888 			 */
11889 			tcp_icmp_error(tcp, mp);
11890 			return;
11891 		}
11892 	}
11893 
11894 	/* No point processing the message if tcp is already closed */
11895 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11896 		freemsg(mp);
11897 		return;
11898 	}
11899 
11900 	tcp_rput_other(tcp, mp);
11901 }
11902 
11903 
11904 /* The minimum of smoothed mean deviation in RTO calculation. */
11905 #define	TCP_SD_MIN	400
11906 
11907 /*
11908  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11909  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11910  * are the same as those in Appendix A.2 of that paper.
11911  *
11912  * m = new measurement
11913  * sa = smoothed RTT average (8 * average estimates).
11914  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11915  */
11916 static void
11917 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11918 {
11919 	long m = TICK_TO_MSEC(rtt);
11920 	clock_t sa = tcp->tcp_rtt_sa;
11921 	clock_t sv = tcp->tcp_rtt_sd;
11922 	clock_t rto;
11923 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11924 
11925 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11926 	tcp->tcp_rtt_update++;
11927 
11928 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11929 	if (sa != 0) {
11930 		/*
11931 		 * Update average estimator:
11932 		 *	new rtt = 7/8 old rtt + 1/8 Error
11933 		 */
11934 
11935 		/* m is now Error in estimate. */
11936 		m -= sa >> 3;
11937 		if ((sa += m) <= 0) {
11938 			/*
11939 			 * Don't allow the smoothed average to be negative.
11940 			 * We use 0 to denote reinitialization of the
11941 			 * variables.
11942 			 */
11943 			sa = 1;
11944 		}
11945 
11946 		/*
11947 		 * Update deviation estimator:
11948 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11949 		 */
11950 		if (m < 0)
11951 			m = -m;
11952 		m -= sv >> 2;
11953 		sv += m;
11954 	} else {
11955 		/*
11956 		 * This follows BSD's implementation.  So the reinitialized
11957 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11958 		 * link is bandwidth dominated, doubling the window size
11959 		 * during slow start means doubling the RTT.  We want to be
11960 		 * more conservative when we reinitialize our estimates.  3
11961 		 * is just a convenient number.
11962 		 */
11963 		sa = m << 3;
11964 		sv = m << 1;
11965 	}
11966 	if (sv < TCP_SD_MIN) {
11967 		/*
11968 		 * We do not know that if sa captures the delay ACK
11969 		 * effect as in a long train of segments, a receiver
11970 		 * does not delay its ACKs.  So set the minimum of sv
11971 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11972 		 * of BSD DATO.  That means the minimum of mean
11973 		 * deviation is 100 ms.
11974 		 *
11975 		 */
11976 		sv = TCP_SD_MIN;
11977 	}
11978 	tcp->tcp_rtt_sa = sa;
11979 	tcp->tcp_rtt_sd = sv;
11980 	/*
11981 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11982 	 *
11983 	 * Add tcp_rexmit_interval extra in case of extreme environment
11984 	 * where the algorithm fails to work.  The default value of
11985 	 * tcp_rexmit_interval_extra should be 0.
11986 	 *
11987 	 * As we use a finer grained clock than BSD and update
11988 	 * RTO for every ACKs, add in another .25 of RTT to the
11989 	 * deviation of RTO to accomodate burstiness of 1/4 of
11990 	 * window size.
11991 	 */
11992 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11993 
11994 	if (rto > tcps->tcps_rexmit_interval_max) {
11995 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11996 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11997 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11998 	} else {
11999 		tcp->tcp_rto = rto;
12000 	}
12001 
12002 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12003 	tcp->tcp_timer_backoff = 0;
12004 }
12005 
12006 /*
12007  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12008  * send queue which starts at the given seq. no.
12009  *
12010  * Parameters:
12011  *	tcp_t *tcp: the tcp instance pointer.
12012  *	uint32_t seq: the starting seq. no of the requested segment.
12013  *	int32_t *off: after the execution, *off will be the offset to
12014  *		the returned mblk which points to the requested seq no.
12015  *		It is the caller's responsibility to send in a non-null off.
12016  *
12017  * Return:
12018  *	A mblk_t pointer pointing to the requested segment in send queue.
12019  */
12020 static mblk_t *
12021 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12022 {
12023 	int32_t	cnt;
12024 	mblk_t	*mp;
12025 
12026 	/* Defensive coding.  Make sure we don't send incorrect data. */
12027 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12028 		return (NULL);
12029 
12030 	cnt = seq - tcp->tcp_suna;
12031 	mp = tcp->tcp_xmit_head;
12032 	while (cnt > 0 && mp != NULL) {
12033 		cnt -= mp->b_wptr - mp->b_rptr;
12034 		if (cnt < 0) {
12035 			cnt += mp->b_wptr - mp->b_rptr;
12036 			break;
12037 		}
12038 		mp = mp->b_cont;
12039 	}
12040 	ASSERT(mp != NULL);
12041 	*off = cnt;
12042 	return (mp);
12043 }
12044 
12045 /*
12046  * This function handles all retransmissions if SACK is enabled for this
12047  * connection.  First it calculates how many segments can be retransmitted
12048  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12049  * segments.  A segment is eligible if sack_cnt for that segment is greater
12050  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12051  * all eligible segments, it checks to see if TCP can send some new segments
12052  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12053  *
12054  * Parameters:
12055  *	tcp_t *tcp: the tcp structure of the connection.
12056  *	uint_t *flags: in return, appropriate value will be set for
12057  *	tcp_rput_data().
12058  */
12059 static void
12060 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12061 {
12062 	notsack_blk_t	*notsack_blk;
12063 	int32_t		usable_swnd;
12064 	int32_t		mss;
12065 	uint32_t	seg_len;
12066 	mblk_t		*xmit_mp;
12067 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12068 
12069 	ASSERT(tcp->tcp_sack_info != NULL);
12070 	ASSERT(tcp->tcp_notsack_list != NULL);
12071 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12072 
12073 	/* Defensive coding in case there is a bug... */
12074 	if (tcp->tcp_notsack_list == NULL) {
12075 		return;
12076 	}
12077 	notsack_blk = tcp->tcp_notsack_list;
12078 	mss = tcp->tcp_mss;
12079 
12080 	/*
12081 	 * Limit the num of outstanding data in the network to be
12082 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12083 	 */
12084 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12085 
12086 	/* At least retransmit 1 MSS of data. */
12087 	if (usable_swnd <= 0) {
12088 		usable_swnd = mss;
12089 	}
12090 
12091 	/* Make sure no new RTT samples will be taken. */
12092 	tcp->tcp_csuna = tcp->tcp_snxt;
12093 
12094 	notsack_blk = tcp->tcp_notsack_list;
12095 	while (usable_swnd > 0) {
12096 		mblk_t		*snxt_mp, *tmp_mp;
12097 		tcp_seq		begin = tcp->tcp_sack_snxt;
12098 		tcp_seq		end;
12099 		int32_t		off;
12100 
12101 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12102 			if (SEQ_GT(notsack_blk->end, begin) &&
12103 			    (notsack_blk->sack_cnt >=
12104 			    tcps->tcps_dupack_fast_retransmit)) {
12105 				end = notsack_blk->end;
12106 				if (SEQ_LT(begin, notsack_blk->begin)) {
12107 					begin = notsack_blk->begin;
12108 				}
12109 				break;
12110 			}
12111 		}
12112 		/*
12113 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12114 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12115 		 * set to tcp_cwnd_ssthresh.
12116 		 */
12117 		if (notsack_blk == NULL) {
12118 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12119 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12120 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12121 				ASSERT(tcp->tcp_cwnd > 0);
12122 				return;
12123 			} else {
12124 				usable_swnd = usable_swnd / mss;
12125 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12126 				    MAX(usable_swnd * mss, mss);
12127 				*flags |= TH_XMIT_NEEDED;
12128 				return;
12129 			}
12130 		}
12131 
12132 		/*
12133 		 * Note that we may send more than usable_swnd allows here
12134 		 * because of round off, but no more than 1 MSS of data.
12135 		 */
12136 		seg_len = end - begin;
12137 		if (seg_len > mss)
12138 			seg_len = mss;
12139 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12140 		ASSERT(snxt_mp != NULL);
12141 		/* This should not happen.  Defensive coding again... */
12142 		if (snxt_mp == NULL) {
12143 			return;
12144 		}
12145 
12146 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12147 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12148 		if (xmit_mp == NULL)
12149 			return;
12150 
12151 		usable_swnd -= seg_len;
12152 		tcp->tcp_pipe += seg_len;
12153 		tcp->tcp_sack_snxt = begin + seg_len;
12154 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12155 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12156 
12157 		/*
12158 		 * Update the send timestamp to avoid false retransmission.
12159 		 */
12160 		snxt_mp->b_prev = (mblk_t *)lbolt;
12161 
12162 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12163 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12164 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12165 		/*
12166 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12167 		 * This happens when new data sent during fast recovery is
12168 		 * also lost.  If TCP retransmits those new data, it needs
12169 		 * to extend SACK recover phase to avoid starting another
12170 		 * fast retransmit/recovery unnecessarily.
12171 		 */
12172 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12173 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12174 		}
12175 	}
12176 }
12177 
12178 /*
12179  * This function handles policy checking at TCP level for non-hard_bound/
12180  * detached connections.
12181  */
12182 static boolean_t
12183 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12184     boolean_t secure, boolean_t mctl_present)
12185 {
12186 	ipsec_latch_t *ipl = NULL;
12187 	ipsec_action_t *act = NULL;
12188 	mblk_t *data_mp;
12189 	ipsec_in_t *ii;
12190 	const char *reason;
12191 	kstat_named_t *counter;
12192 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12193 	ipsec_stack_t	*ipss;
12194 	ip_stack_t	*ipst;
12195 
12196 	ASSERT(mctl_present || !secure);
12197 
12198 	ASSERT((ipha == NULL && ip6h != NULL) ||
12199 	    (ip6h == NULL && ipha != NULL));
12200 
12201 	/*
12202 	 * We don't necessarily have an ipsec_in_act action to verify
12203 	 * policy because of assymetrical policy where we have only
12204 	 * outbound policy and no inbound policy (possible with global
12205 	 * policy).
12206 	 */
12207 	if (!secure) {
12208 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12209 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12210 			return (B_TRUE);
12211 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12212 		    "tcp_check_policy", ipha, ip6h, secure,
12213 		    tcps->tcps_netstack);
12214 		ipss = tcps->tcps_netstack->netstack_ipsec;
12215 
12216 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12217 		    DROPPER(ipss, ipds_tcp_clear),
12218 		    &tcps->tcps_dropper);
12219 		return (B_FALSE);
12220 	}
12221 
12222 	/*
12223 	 * We have a secure packet.
12224 	 */
12225 	if (act == NULL) {
12226 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12227 		    "tcp_check_policy", ipha, ip6h, secure,
12228 		    tcps->tcps_netstack);
12229 		ipss = tcps->tcps_netstack->netstack_ipsec;
12230 
12231 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12232 		    DROPPER(ipss, ipds_tcp_secure),
12233 		    &tcps->tcps_dropper);
12234 		return (B_FALSE);
12235 	}
12236 
12237 	/*
12238 	 * XXX This whole routine is currently incorrect.  ipl should
12239 	 * be set to the latch pointer, but is currently not set, so
12240 	 * we initialize it to NULL to avoid picking up random garbage.
12241 	 */
12242 	if (ipl == NULL)
12243 		return (B_TRUE);
12244 
12245 	data_mp = first_mp->b_cont;
12246 
12247 	ii = (ipsec_in_t *)first_mp->b_rptr;
12248 
12249 	ipst = tcps->tcps_netstack->netstack_ip;
12250 
12251 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12252 	    &counter, tcp->tcp_connp)) {
12253 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12254 		return (B_TRUE);
12255 	}
12256 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12257 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12258 	    reason);
12259 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12260 
12261 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12262 	    &tcps->tcps_dropper);
12263 	return (B_FALSE);
12264 }
12265 
12266 /*
12267  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12268  * retransmission after a timeout.
12269  *
12270  * To limit the number of duplicate segments, we limit the number of segment
12271  * to be sent in one time to tcp_snd_burst, the burst variable.
12272  */
12273 static void
12274 tcp_ss_rexmit(tcp_t *tcp)
12275 {
12276 	uint32_t	snxt;
12277 	uint32_t	smax;
12278 	int32_t		win;
12279 	int32_t		mss;
12280 	int32_t		off;
12281 	int32_t		burst = tcp->tcp_snd_burst;
12282 	mblk_t		*snxt_mp;
12283 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12284 
12285 	/*
12286 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12287 	 * all unack'ed segments.
12288 	 */
12289 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12290 		smax = tcp->tcp_rexmit_max;
12291 		snxt = tcp->tcp_rexmit_nxt;
12292 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12293 			snxt = tcp->tcp_suna;
12294 		}
12295 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12296 		win -= snxt - tcp->tcp_suna;
12297 		mss = tcp->tcp_mss;
12298 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12299 
12300 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12301 		    (burst > 0) && (snxt_mp != NULL)) {
12302 			mblk_t	*xmit_mp;
12303 			mblk_t	*old_snxt_mp = snxt_mp;
12304 			uint32_t cnt = mss;
12305 
12306 			if (win < cnt) {
12307 				cnt = win;
12308 			}
12309 			if (SEQ_GT(snxt + cnt, smax)) {
12310 				cnt = smax - snxt;
12311 			}
12312 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12313 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12314 			if (xmit_mp == NULL)
12315 				return;
12316 
12317 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12318 
12319 			snxt += cnt;
12320 			win -= cnt;
12321 			/*
12322 			 * Update the send timestamp to avoid false
12323 			 * retransmission.
12324 			 */
12325 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12326 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12327 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12328 
12329 			tcp->tcp_rexmit_nxt = snxt;
12330 			burst--;
12331 		}
12332 		/*
12333 		 * If we have transmitted all we have at the time
12334 		 * we started the retranmission, we can leave
12335 		 * the rest of the job to tcp_wput_data().  But we
12336 		 * need to check the send window first.  If the
12337 		 * win is not 0, go on with tcp_wput_data().
12338 		 */
12339 		if (SEQ_LT(snxt, smax) || win == 0) {
12340 			return;
12341 		}
12342 	}
12343 	/* Only call tcp_wput_data() if there is data to be sent. */
12344 	if (tcp->tcp_unsent) {
12345 		tcp_wput_data(tcp, NULL, B_FALSE);
12346 	}
12347 }
12348 
12349 /*
12350  * Process all TCP option in SYN segment.  Note that this function should
12351  * be called after tcp_adapt_ire() is called so that the necessary info
12352  * from IRE is already set in the tcp structure.
12353  *
12354  * This function sets up the correct tcp_mss value according to the
12355  * MSS option value and our header size.  It also sets up the window scale
12356  * and timestamp values, and initialize SACK info blocks.  But it does not
12357  * change receive window size after setting the tcp_mss value.  The caller
12358  * should do the appropriate change.
12359  */
12360 void
12361 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12362 {
12363 	int options;
12364 	tcp_opt_t tcpopt;
12365 	uint32_t mss_max;
12366 	char *tmp_tcph;
12367 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12368 
12369 	tcpopt.tcp = NULL;
12370 	options = tcp_parse_options(tcph, &tcpopt);
12371 
12372 	/*
12373 	 * Process MSS option.  Note that MSS option value does not account
12374 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12375 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12376 	 * IPv6.
12377 	 */
12378 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12379 		if (tcp->tcp_ipversion == IPV4_VERSION)
12380 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12381 		else
12382 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12383 	} else {
12384 		if (tcp->tcp_ipversion == IPV4_VERSION)
12385 			mss_max = tcps->tcps_mss_max_ipv4;
12386 		else
12387 			mss_max = tcps->tcps_mss_max_ipv6;
12388 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12389 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12390 		else if (tcpopt.tcp_opt_mss > mss_max)
12391 			tcpopt.tcp_opt_mss = mss_max;
12392 	}
12393 
12394 	/* Process Window Scale option. */
12395 	if (options & TCP_OPT_WSCALE_PRESENT) {
12396 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12397 		tcp->tcp_snd_ws_ok = B_TRUE;
12398 	} else {
12399 		tcp->tcp_snd_ws = B_FALSE;
12400 		tcp->tcp_snd_ws_ok = B_FALSE;
12401 		tcp->tcp_rcv_ws = B_FALSE;
12402 	}
12403 
12404 	/* Process Timestamp option. */
12405 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12406 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12407 		tmp_tcph = (char *)tcp->tcp_tcph;
12408 
12409 		tcp->tcp_snd_ts_ok = B_TRUE;
12410 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12411 		tcp->tcp_last_rcv_lbolt = lbolt64;
12412 		ASSERT(OK_32PTR(tmp_tcph));
12413 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12414 
12415 		/* Fill in our template header with basic timestamp option. */
12416 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12417 		tmp_tcph[0] = TCPOPT_NOP;
12418 		tmp_tcph[1] = TCPOPT_NOP;
12419 		tmp_tcph[2] = TCPOPT_TSTAMP;
12420 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12421 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12422 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12423 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12424 	} else {
12425 		tcp->tcp_snd_ts_ok = B_FALSE;
12426 	}
12427 
12428 	/*
12429 	 * Process SACK options.  If SACK is enabled for this connection,
12430 	 * then allocate the SACK info structure.  Note the following ways
12431 	 * when tcp_snd_sack_ok is set to true.
12432 	 *
12433 	 * For active connection: in tcp_adapt_ire() called in
12434 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12435 	 * is checked.
12436 	 *
12437 	 * For passive connection: in tcp_adapt_ire() called in
12438 	 * tcp_accept_comm().
12439 	 *
12440 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12441 	 * That check makes sure that if we did not send a SACK OK option,
12442 	 * we will not enable SACK for this connection even though the other
12443 	 * side sends us SACK OK option.  For active connection, the SACK
12444 	 * info structure has already been allocated.  So we need to free
12445 	 * it if SACK is disabled.
12446 	 */
12447 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12448 	    (tcp->tcp_snd_sack_ok ||
12449 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12450 		/* This should be true only in the passive case. */
12451 		if (tcp->tcp_sack_info == NULL) {
12452 			ASSERT(TCP_IS_DETACHED(tcp));
12453 			tcp->tcp_sack_info =
12454 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12455 		}
12456 		if (tcp->tcp_sack_info == NULL) {
12457 			tcp->tcp_snd_sack_ok = B_FALSE;
12458 		} else {
12459 			tcp->tcp_snd_sack_ok = B_TRUE;
12460 			if (tcp->tcp_snd_ts_ok) {
12461 				tcp->tcp_max_sack_blk = 3;
12462 			} else {
12463 				tcp->tcp_max_sack_blk = 4;
12464 			}
12465 		}
12466 	} else {
12467 		/*
12468 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12469 		 * no SACK info will be used for this
12470 		 * connection.  This assumes that SACK usage
12471 		 * permission is negotiated.  This may need
12472 		 * to be changed once this is clarified.
12473 		 */
12474 		if (tcp->tcp_sack_info != NULL) {
12475 			ASSERT(tcp->tcp_notsack_list == NULL);
12476 			kmem_cache_free(tcp_sack_info_cache,
12477 			    tcp->tcp_sack_info);
12478 			tcp->tcp_sack_info = NULL;
12479 		}
12480 		tcp->tcp_snd_sack_ok = B_FALSE;
12481 	}
12482 
12483 	/*
12484 	 * Now we know the exact TCP/IP header length, subtract
12485 	 * that from tcp_mss to get our side's MSS.
12486 	 */
12487 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12488 	/*
12489 	 * Here we assume that the other side's header size will be equal to
12490 	 * our header size.  We calculate the real MSS accordingly.  Need to
12491 	 * take into additional stuffs IPsec puts in.
12492 	 *
12493 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12494 	 */
12495 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12496 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12497 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12498 
12499 	/*
12500 	 * Set MSS to the smaller one of both ends of the connection.
12501 	 * We should not have called tcp_mss_set() before, but our
12502 	 * side of the MSS should have been set to a proper value
12503 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12504 	 * STREAM head parameters properly.
12505 	 *
12506 	 * If we have a larger-than-16-bit window but the other side
12507 	 * didn't want to do window scale, tcp_rwnd_set() will take
12508 	 * care of that.
12509 	 */
12510 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12511 }
12512 
12513 /*
12514  * Sends the T_CONN_IND to the listener. The caller calls this
12515  * functions via squeue to get inside the listener's perimeter
12516  * once the 3 way hand shake is done a T_CONN_IND needs to be
12517  * sent. As an optimization, the caller can call this directly
12518  * if listener's perimeter is same as eager's.
12519  */
12520 /* ARGSUSED */
12521 void
12522 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12523 {
12524 	conn_t			*lconnp = (conn_t *)arg;
12525 	tcp_t			*listener = lconnp->conn_tcp;
12526 	tcp_t			*tcp;
12527 	struct T_conn_ind	*conn_ind;
12528 	ipaddr_t 		*addr_cache;
12529 	boolean_t		need_send_conn_ind = B_FALSE;
12530 	tcp_stack_t		*tcps = listener->tcp_tcps;
12531 
12532 	/* retrieve the eager */
12533 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12534 	ASSERT(conn_ind->OPT_offset != 0 &&
12535 	    conn_ind->OPT_length == sizeof (intptr_t));
12536 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12537 	    conn_ind->OPT_length);
12538 
12539 	/*
12540 	 * TLI/XTI applications will get confused by
12541 	 * sending eager as an option since it violates
12542 	 * the option semantics. So remove the eager as
12543 	 * option since TLI/XTI app doesn't need it anyway.
12544 	 */
12545 	if (!TCP_IS_SOCKET(listener)) {
12546 		conn_ind->OPT_length = 0;
12547 		conn_ind->OPT_offset = 0;
12548 	}
12549 	if (listener->tcp_state == TCPS_CLOSED ||
12550 	    TCP_IS_DETACHED(listener)) {
12551 		/*
12552 		 * If listener has closed, it would have caused a
12553 		 * a cleanup/blowoff to happen for the eager. We
12554 		 * just need to return.
12555 		 */
12556 		freemsg(mp);
12557 		return;
12558 	}
12559 
12560 
12561 	/*
12562 	 * if the conn_req_q is full defer passing up the
12563 	 * T_CONN_IND until space is availabe after t_accept()
12564 	 * processing
12565 	 */
12566 	mutex_enter(&listener->tcp_eager_lock);
12567 
12568 	/*
12569 	 * Take the eager out, if it is in the list of droppable eagers
12570 	 * as we are here because the 3W handshake is over.
12571 	 */
12572 	MAKE_UNDROPPABLE(tcp);
12573 
12574 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12575 		tcp_t *tail;
12576 
12577 		/*
12578 		 * The eager already has an extra ref put in tcp_rput_data
12579 		 * so that it stays till accept comes back even though it
12580 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12581 		 */
12582 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12583 		listener->tcp_conn_req_cnt_q0--;
12584 		listener->tcp_conn_req_cnt_q++;
12585 
12586 		/* Move from SYN_RCVD to ESTABLISHED list  */
12587 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12588 		    tcp->tcp_eager_prev_q0;
12589 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12590 		    tcp->tcp_eager_next_q0;
12591 		tcp->tcp_eager_prev_q0 = NULL;
12592 		tcp->tcp_eager_next_q0 = NULL;
12593 
12594 		/*
12595 		 * Insert at end of the queue because sockfs
12596 		 * sends down T_CONN_RES in chronological
12597 		 * order. Leaving the older conn indications
12598 		 * at front of the queue helps reducing search
12599 		 * time.
12600 		 */
12601 		tail = listener->tcp_eager_last_q;
12602 		if (tail != NULL)
12603 			tail->tcp_eager_next_q = tcp;
12604 		else
12605 			listener->tcp_eager_next_q = tcp;
12606 		listener->tcp_eager_last_q = tcp;
12607 		tcp->tcp_eager_next_q = NULL;
12608 		/*
12609 		 * Delay sending up the T_conn_ind until we are
12610 		 * done with the eager. Once we have have sent up
12611 		 * the T_conn_ind, the accept can potentially complete
12612 		 * any time and release the refhold we have on the eager.
12613 		 */
12614 		need_send_conn_ind = B_TRUE;
12615 	} else {
12616 		/*
12617 		 * Defer connection on q0 and set deferred
12618 		 * connection bit true
12619 		 */
12620 		tcp->tcp_conn_def_q0 = B_TRUE;
12621 
12622 		/* take tcp out of q0 ... */
12623 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12624 		    tcp->tcp_eager_next_q0;
12625 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12626 		    tcp->tcp_eager_prev_q0;
12627 
12628 		/* ... and place it at the end of q0 */
12629 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12630 		tcp->tcp_eager_next_q0 = listener;
12631 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12632 		listener->tcp_eager_prev_q0 = tcp;
12633 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12634 	}
12635 
12636 	/* we have timed out before */
12637 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12638 		tcp->tcp_syn_rcvd_timeout = 0;
12639 		listener->tcp_syn_rcvd_timeout--;
12640 		if (listener->tcp_syn_defense &&
12641 		    listener->tcp_syn_rcvd_timeout <=
12642 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12643 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12644 		    listener->tcp_last_rcv_lbolt)) {
12645 			/*
12646 			 * Turn off the defense mode if we
12647 			 * believe the SYN attack is over.
12648 			 */
12649 			listener->tcp_syn_defense = B_FALSE;
12650 			if (listener->tcp_ip_addr_cache) {
12651 				kmem_free((void *)listener->tcp_ip_addr_cache,
12652 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12653 				listener->tcp_ip_addr_cache = NULL;
12654 			}
12655 		}
12656 	}
12657 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12658 	if (addr_cache != NULL) {
12659 		/*
12660 		 * We have finished a 3-way handshake with this
12661 		 * remote host. This proves the IP addr is good.
12662 		 * Cache it!
12663 		 */
12664 		addr_cache[IP_ADDR_CACHE_HASH(
12665 		    tcp->tcp_remote)] = tcp->tcp_remote;
12666 	}
12667 	mutex_exit(&listener->tcp_eager_lock);
12668 	if (need_send_conn_ind)
12669 		putnext(listener->tcp_rq, mp);
12670 }
12671 
12672 mblk_t *
12673 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12674     uint_t *ifindexp, ip6_pkt_t *ippp)
12675 {
12676 	ip_pktinfo_t	*pinfo;
12677 	ip6_t		*ip6h;
12678 	uchar_t		*rptr;
12679 	mblk_t		*first_mp = mp;
12680 	boolean_t	mctl_present = B_FALSE;
12681 	uint_t 		ifindex = 0;
12682 	ip6_pkt_t	ipp;
12683 	uint_t		ipvers;
12684 	uint_t		ip_hdr_len;
12685 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12686 
12687 	rptr = mp->b_rptr;
12688 	ASSERT(OK_32PTR(rptr));
12689 	ASSERT(tcp != NULL);
12690 	ipp.ipp_fields = 0;
12691 
12692 	switch DB_TYPE(mp) {
12693 	case M_CTL:
12694 		mp = mp->b_cont;
12695 		if (mp == NULL) {
12696 			freemsg(first_mp);
12697 			return (NULL);
12698 		}
12699 		if (DB_TYPE(mp) != M_DATA) {
12700 			freemsg(first_mp);
12701 			return (NULL);
12702 		}
12703 		mctl_present = B_TRUE;
12704 		break;
12705 	case M_DATA:
12706 		break;
12707 	default:
12708 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12709 		freemsg(mp);
12710 		return (NULL);
12711 	}
12712 	ipvers = IPH_HDR_VERSION(rptr);
12713 	if (ipvers == IPV4_VERSION) {
12714 		if (tcp == NULL) {
12715 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12716 			goto done;
12717 		}
12718 
12719 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12720 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12721 
12722 		/*
12723 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12724 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12725 		 */
12726 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12727 		    mctl_present) {
12728 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12729 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12730 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12731 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12732 				ipp.ipp_fields |= IPPF_IFINDEX;
12733 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12734 				ifindex = pinfo->ip_pkt_ifindex;
12735 			}
12736 			freeb(first_mp);
12737 			mctl_present = B_FALSE;
12738 		}
12739 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12740 	} else {
12741 		ip6h = (ip6_t *)rptr;
12742 
12743 		ASSERT(ipvers == IPV6_VERSION);
12744 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12745 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12746 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12747 
12748 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12749 			uint8_t	nexthdrp;
12750 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12751 
12752 			/* Look for ifindex information */
12753 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12754 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12755 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12756 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12757 					freemsg(first_mp);
12758 					return (NULL);
12759 				}
12760 
12761 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12762 					ASSERT(ip6i->ip6i_ifindex != 0);
12763 					ipp.ipp_fields |= IPPF_IFINDEX;
12764 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12765 					ifindex = ip6i->ip6i_ifindex;
12766 				}
12767 				rptr = (uchar_t *)&ip6i[1];
12768 				mp->b_rptr = rptr;
12769 				if (rptr == mp->b_wptr) {
12770 					mblk_t *mp1;
12771 					mp1 = mp->b_cont;
12772 					freeb(mp);
12773 					mp = mp1;
12774 					rptr = mp->b_rptr;
12775 				}
12776 				if (MBLKL(mp) < IPV6_HDR_LEN +
12777 				    sizeof (tcph_t)) {
12778 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12779 					freemsg(first_mp);
12780 					return (NULL);
12781 				}
12782 				ip6h = (ip6_t *)rptr;
12783 			}
12784 
12785 			/*
12786 			 * Find any potentially interesting extension headers
12787 			 * as well as the length of the IPv6 + extension
12788 			 * headers.
12789 			 */
12790 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12791 			/* Verify if this is a TCP packet */
12792 			if (nexthdrp != IPPROTO_TCP) {
12793 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12794 				freemsg(first_mp);
12795 				return (NULL);
12796 			}
12797 		} else {
12798 			ip_hdr_len = IPV6_HDR_LEN;
12799 		}
12800 	}
12801 
12802 done:
12803 	if (ipversp != NULL)
12804 		*ipversp = ipvers;
12805 	if (ip_hdr_lenp != NULL)
12806 		*ip_hdr_lenp = ip_hdr_len;
12807 	if (ippp != NULL)
12808 		*ippp = ipp;
12809 	if (ifindexp != NULL)
12810 		*ifindexp = ifindex;
12811 	if (mctl_present) {
12812 		freeb(first_mp);
12813 	}
12814 	return (mp);
12815 }
12816 
12817 /*
12818  * Handle M_DATA messages from IP. Its called directly from IP via
12819  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12820  * in this path.
12821  *
12822  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12823  * v4 and v6), we are called through tcp_input() and a M_CTL can
12824  * be present for options but tcp_find_pktinfo() deals with it. We
12825  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12826  *
12827  * The first argument is always the connp/tcp to which the mp belongs.
12828  * There are no exceptions to this rule. The caller has already put
12829  * a reference on this connp/tcp and once tcp_rput_data() returns,
12830  * the squeue will do the refrele.
12831  *
12832  * The TH_SYN for the listener directly go to tcp_conn_request via
12833  * squeue.
12834  *
12835  * sqp: NULL = recursive, sqp != NULL means called from squeue
12836  */
12837 void
12838 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12839 {
12840 	int32_t		bytes_acked;
12841 	int32_t		gap;
12842 	mblk_t		*mp1;
12843 	uint_t		flags;
12844 	uint32_t	new_swnd = 0;
12845 	uchar_t		*iphdr;
12846 	uchar_t		*rptr;
12847 	int32_t		rgap;
12848 	uint32_t	seg_ack;
12849 	int		seg_len;
12850 	uint_t		ip_hdr_len;
12851 	uint32_t	seg_seq;
12852 	tcph_t		*tcph;
12853 	int		urp;
12854 	tcp_opt_t	tcpopt;
12855 	uint_t		ipvers;
12856 	ip6_pkt_t	ipp;
12857 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12858 	uint32_t	cwnd;
12859 	uint32_t	add;
12860 	int		npkt;
12861 	int		mss;
12862 	conn_t		*connp = (conn_t *)arg;
12863 	squeue_t	*sqp = (squeue_t *)arg2;
12864 	tcp_t		*tcp = connp->conn_tcp;
12865 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12866 
12867 	/*
12868 	 * RST from fused tcp loopback peer should trigger an unfuse.
12869 	 */
12870 	if (tcp->tcp_fused) {
12871 		TCP_STAT(tcps, tcp_fusion_aborted);
12872 		tcp_unfuse(tcp);
12873 	}
12874 
12875 	iphdr = mp->b_rptr;
12876 	rptr = mp->b_rptr;
12877 	ASSERT(OK_32PTR(rptr));
12878 
12879 	/*
12880 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12881 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12882 	 * necessary information.
12883 	 */
12884 	if (IPCL_IS_TCP4(connp)) {
12885 		ipvers = IPV4_VERSION;
12886 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12887 	} else {
12888 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12889 		    NULL, &ipp);
12890 		if (mp == NULL) {
12891 			TCP_STAT(tcps, tcp_rput_v6_error);
12892 			return;
12893 		}
12894 		iphdr = mp->b_rptr;
12895 		rptr = mp->b_rptr;
12896 	}
12897 	ASSERT(DB_TYPE(mp) == M_DATA);
12898 
12899 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12900 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12901 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12902 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12903 	seg_len = (int)(mp->b_wptr - rptr) -
12904 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12905 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12906 		do {
12907 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12908 			    (uintptr_t)INT_MAX);
12909 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12910 		} while ((mp1 = mp1->b_cont) != NULL &&
12911 		    mp1->b_datap->db_type == M_DATA);
12912 	}
12913 
12914 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12915 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12916 		    seg_len, tcph);
12917 		return;
12918 	}
12919 
12920 	if (sqp != NULL) {
12921 		/*
12922 		 * This is the correct place to update tcp_last_recv_time. Note
12923 		 * that it is also updated for tcp structure that belongs to
12924 		 * global and listener queues which do not really need updating.
12925 		 * But that should not cause any harm.  And it is updated for
12926 		 * all kinds of incoming segments, not only for data segments.
12927 		 */
12928 		tcp->tcp_last_recv_time = lbolt;
12929 	}
12930 
12931 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12932 
12933 	BUMP_LOCAL(tcp->tcp_ibsegs);
12934 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12935 
12936 	if ((flags & TH_URG) && sqp != NULL) {
12937 		/*
12938 		 * TCP can't handle urgent pointers that arrive before
12939 		 * the connection has been accept()ed since it can't
12940 		 * buffer OOB data.  Discard segment if this happens.
12941 		 *
12942 		 * We can't just rely on a non-null tcp_listener to indicate
12943 		 * that the accept() has completed since unlinking of the
12944 		 * eager and completion of the accept are not atomic.
12945 		 * tcp_detached, when it is not set (B_FALSE) indicates
12946 		 * that the accept() has completed.
12947 		 *
12948 		 * Nor can it reassemble urgent pointers, so discard
12949 		 * if it's not the next segment expected.
12950 		 *
12951 		 * Otherwise, collapse chain into one mblk (discard if
12952 		 * that fails).  This makes sure the headers, retransmitted
12953 		 * data, and new data all are in the same mblk.
12954 		 */
12955 		ASSERT(mp != NULL);
12956 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12957 			freemsg(mp);
12958 			return;
12959 		}
12960 		/* Update pointers into message */
12961 		iphdr = rptr = mp->b_rptr;
12962 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12963 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12964 			/*
12965 			 * Since we can't handle any data with this urgent
12966 			 * pointer that is out of sequence, we expunge
12967 			 * the data.  This allows us to still register
12968 			 * the urgent mark and generate the M_PCSIG,
12969 			 * which we can do.
12970 			 */
12971 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12972 			seg_len = 0;
12973 		}
12974 	}
12975 
12976 	switch (tcp->tcp_state) {
12977 	case TCPS_SYN_SENT:
12978 		if (flags & TH_ACK) {
12979 			/*
12980 			 * Note that our stack cannot send data before a
12981 			 * connection is established, therefore the
12982 			 * following check is valid.  Otherwise, it has
12983 			 * to be changed.
12984 			 */
12985 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12986 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12987 				freemsg(mp);
12988 				if (flags & TH_RST)
12989 					return;
12990 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12991 				    tcp, seg_ack, 0, TH_RST);
12992 				return;
12993 			}
12994 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12995 		}
12996 		if (flags & TH_RST) {
12997 			freemsg(mp);
12998 			if (flags & TH_ACK)
12999 				(void) tcp_clean_death(tcp,
13000 				    ECONNREFUSED, 13);
13001 			return;
13002 		}
13003 		if (!(flags & TH_SYN)) {
13004 			freemsg(mp);
13005 			return;
13006 		}
13007 
13008 		/* Process all TCP options. */
13009 		tcp_process_options(tcp, tcph);
13010 		/*
13011 		 * The following changes our rwnd to be a multiple of the
13012 		 * MIN(peer MSS, our MSS) for performance reason.
13013 		 */
13014 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13015 		    tcp->tcp_mss));
13016 
13017 		/* Is the other end ECN capable? */
13018 		if (tcp->tcp_ecn_ok) {
13019 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13020 				tcp->tcp_ecn_ok = B_FALSE;
13021 			}
13022 		}
13023 		/*
13024 		 * Clear ECN flags because it may interfere with later
13025 		 * processing.
13026 		 */
13027 		flags &= ~(TH_ECE|TH_CWR);
13028 
13029 		tcp->tcp_irs = seg_seq;
13030 		tcp->tcp_rack = seg_seq;
13031 		tcp->tcp_rnxt = seg_seq + 1;
13032 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13033 		if (!TCP_IS_DETACHED(tcp)) {
13034 			/* Allocate room for SACK options if needed. */
13035 			if (tcp->tcp_snd_sack_ok) {
13036 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13037 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13038 				    (tcp->tcp_loopback ? 0 :
13039 				    tcps->tcps_wroff_xtra));
13040 			} else {
13041 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13042 				    tcp->tcp_hdr_len +
13043 				    (tcp->tcp_loopback ? 0 :
13044 				    tcps->tcps_wroff_xtra));
13045 			}
13046 		}
13047 		if (flags & TH_ACK) {
13048 			/*
13049 			 * If we can't get the confirmation upstream, pretend
13050 			 * we didn't even see this one.
13051 			 *
13052 			 * XXX: how can we pretend we didn't see it if we
13053 			 * have updated rnxt et. al.
13054 			 *
13055 			 * For loopback we defer sending up the T_CONN_CON
13056 			 * until after some checks below.
13057 			 */
13058 			mp1 = NULL;
13059 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13060 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13061 				freemsg(mp);
13062 				return;
13063 			}
13064 			/* SYN was acked - making progress */
13065 			if (tcp->tcp_ipversion == IPV6_VERSION)
13066 				tcp->tcp_ip_forward_progress = B_TRUE;
13067 
13068 			/* One for the SYN */
13069 			tcp->tcp_suna = tcp->tcp_iss + 1;
13070 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13071 			tcp->tcp_state = TCPS_ESTABLISHED;
13072 
13073 			/*
13074 			 * If SYN was retransmitted, need to reset all
13075 			 * retransmission info.  This is because this
13076 			 * segment will be treated as a dup ACK.
13077 			 */
13078 			if (tcp->tcp_rexmit) {
13079 				tcp->tcp_rexmit = B_FALSE;
13080 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13081 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13082 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13083 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13084 				tcp->tcp_ms_we_have_waited = 0;
13085 
13086 				/*
13087 				 * Set tcp_cwnd back to 1 MSS, per
13088 				 * recommendation from
13089 				 * draft-floyd-incr-init-win-01.txt,
13090 				 * Increasing TCP's Initial Window.
13091 				 */
13092 				tcp->tcp_cwnd = tcp->tcp_mss;
13093 			}
13094 
13095 			tcp->tcp_swl1 = seg_seq;
13096 			tcp->tcp_swl2 = seg_ack;
13097 
13098 			new_swnd = BE16_TO_U16(tcph->th_win);
13099 			tcp->tcp_swnd = new_swnd;
13100 			if (new_swnd > tcp->tcp_max_swnd)
13101 				tcp->tcp_max_swnd = new_swnd;
13102 
13103 			/*
13104 			 * Always send the three-way handshake ack immediately
13105 			 * in order to make the connection complete as soon as
13106 			 * possible on the accepting host.
13107 			 */
13108 			flags |= TH_ACK_NEEDED;
13109 
13110 			/*
13111 			 * Special case for loopback.  At this point we have
13112 			 * received SYN-ACK from the remote endpoint.  In
13113 			 * order to ensure that both endpoints reach the
13114 			 * fused state prior to any data exchange, the final
13115 			 * ACK needs to be sent before we indicate T_CONN_CON
13116 			 * to the module upstream.
13117 			 */
13118 			if (tcp->tcp_loopback) {
13119 				mblk_t *ack_mp;
13120 
13121 				ASSERT(!tcp->tcp_unfusable);
13122 				ASSERT(mp1 != NULL);
13123 				/*
13124 				 * For loopback, we always get a pure SYN-ACK
13125 				 * and only need to send back the final ACK
13126 				 * with no data (this is because the other
13127 				 * tcp is ours and we don't do T/TCP).  This
13128 				 * final ACK triggers the passive side to
13129 				 * perform fusion in ESTABLISHED state.
13130 				 */
13131 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13132 					if (tcp->tcp_ack_tid != 0) {
13133 						(void) TCP_TIMER_CANCEL(tcp,
13134 						    tcp->tcp_ack_tid);
13135 						tcp->tcp_ack_tid = 0;
13136 					}
13137 					TCP_RECORD_TRACE(tcp, ack_mp,
13138 					    TCP_TRACE_SEND_PKT);
13139 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13140 					BUMP_LOCAL(tcp->tcp_obsegs);
13141 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13142 
13143 					/* Send up T_CONN_CON */
13144 					putnext(tcp->tcp_rq, mp1);
13145 
13146 					freemsg(mp);
13147 					return;
13148 				}
13149 				/*
13150 				 * Forget fusion; we need to handle more
13151 				 * complex cases below.  Send the deferred
13152 				 * T_CONN_CON message upstream and proceed
13153 				 * as usual.  Mark this tcp as not capable
13154 				 * of fusion.
13155 				 */
13156 				TCP_STAT(tcps, tcp_fusion_unfusable);
13157 				tcp->tcp_unfusable = B_TRUE;
13158 				putnext(tcp->tcp_rq, mp1);
13159 			}
13160 
13161 			/*
13162 			 * Check to see if there is data to be sent.  If
13163 			 * yes, set the transmit flag.  Then check to see
13164 			 * if received data processing needs to be done.
13165 			 * If not, go straight to xmit_check.  This short
13166 			 * cut is OK as we don't support T/TCP.
13167 			 */
13168 			if (tcp->tcp_unsent)
13169 				flags |= TH_XMIT_NEEDED;
13170 
13171 			if (seg_len == 0 && !(flags & TH_URG)) {
13172 				freemsg(mp);
13173 				goto xmit_check;
13174 			}
13175 
13176 			flags &= ~TH_SYN;
13177 			seg_seq++;
13178 			break;
13179 		}
13180 		tcp->tcp_state = TCPS_SYN_RCVD;
13181 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13182 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13183 		if (mp1) {
13184 			DB_CPID(mp1) = tcp->tcp_cpid;
13185 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13186 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13187 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13188 		}
13189 		freemsg(mp);
13190 		return;
13191 	case TCPS_SYN_RCVD:
13192 		if (flags & TH_ACK) {
13193 			/*
13194 			 * In this state, a SYN|ACK packet is either bogus
13195 			 * because the other side must be ACKing our SYN which
13196 			 * indicates it has seen the ACK for their SYN and
13197 			 * shouldn't retransmit it or we're crossing SYNs
13198 			 * on active open.
13199 			 */
13200 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13201 				freemsg(mp);
13202 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13203 				    tcp, seg_ack, 0, TH_RST);
13204 				return;
13205 			}
13206 			/*
13207 			 * NOTE: RFC 793 pg. 72 says this should be
13208 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13209 			 * but that would mean we have an ack that ignored
13210 			 * our SYN.
13211 			 */
13212 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13213 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13214 				freemsg(mp);
13215 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13216 				    tcp, seg_ack, 0, TH_RST);
13217 				return;
13218 			}
13219 		}
13220 		break;
13221 	case TCPS_LISTEN:
13222 		/*
13223 		 * Only a TLI listener can come through this path when a
13224 		 * acceptor is going back to be a listener and a packet
13225 		 * for the acceptor hits the classifier. For a socket
13226 		 * listener, this can never happen because a listener
13227 		 * can never accept connection on itself and hence a
13228 		 * socket acceptor can not go back to being a listener.
13229 		 */
13230 		ASSERT(!TCP_IS_SOCKET(tcp));
13231 		/*FALLTHRU*/
13232 	case TCPS_CLOSED:
13233 	case TCPS_BOUND: {
13234 		conn_t	*new_connp;
13235 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13236 
13237 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13238 		if (new_connp != NULL) {
13239 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13240 			return;
13241 		}
13242 		/* We failed to classify. For now just drop the packet */
13243 		freemsg(mp);
13244 		return;
13245 	}
13246 	case TCPS_IDLE:
13247 		/*
13248 		 * Handle the case where the tcp_clean_death() has happened
13249 		 * on a connection (application hasn't closed yet) but a packet
13250 		 * was already queued on squeue before tcp_clean_death()
13251 		 * was processed. Calling tcp_clean_death() twice on same
13252 		 * connection can result in weird behaviour.
13253 		 */
13254 		freemsg(mp);
13255 		return;
13256 	default:
13257 		break;
13258 	}
13259 
13260 	/*
13261 	 * Already on the correct queue/perimeter.
13262 	 * If this is a detached connection and not an eager
13263 	 * connection hanging off a listener then new data
13264 	 * (past the FIN) will cause a reset.
13265 	 * We do a special check here where it
13266 	 * is out of the main line, rather than check
13267 	 * if we are detached every time we see new
13268 	 * data down below.
13269 	 */
13270 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13271 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13272 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13273 		TCP_RECORD_TRACE(tcp,
13274 		    mp, TCP_TRACE_RECV_PKT);
13275 
13276 		freemsg(mp);
13277 		/*
13278 		 * This could be an SSL closure alert. We're detached so just
13279 		 * acknowledge it this last time.
13280 		 */
13281 		if (tcp->tcp_kssl_ctx != NULL) {
13282 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13283 			tcp->tcp_kssl_ctx = NULL;
13284 
13285 			tcp->tcp_rnxt += seg_len;
13286 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13287 			flags |= TH_ACK_NEEDED;
13288 			goto ack_check;
13289 		}
13290 
13291 		tcp_xmit_ctl("new data when detached", tcp,
13292 		    tcp->tcp_snxt, 0, TH_RST);
13293 		(void) tcp_clean_death(tcp, EPROTO, 12);
13294 		return;
13295 	}
13296 
13297 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13298 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13299 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13300 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13301 
13302 	if (tcp->tcp_snd_ts_ok) {
13303 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13304 			/*
13305 			 * This segment is not acceptable.
13306 			 * Drop it and send back an ACK.
13307 			 */
13308 			freemsg(mp);
13309 			flags |= TH_ACK_NEEDED;
13310 			goto ack_check;
13311 		}
13312 	} else if (tcp->tcp_snd_sack_ok) {
13313 		ASSERT(tcp->tcp_sack_info != NULL);
13314 		tcpopt.tcp = tcp;
13315 		/*
13316 		 * SACK info in already updated in tcp_parse_options.  Ignore
13317 		 * all other TCP options...
13318 		 */
13319 		(void) tcp_parse_options(tcph, &tcpopt);
13320 	}
13321 try_again:;
13322 	mss = tcp->tcp_mss;
13323 	gap = seg_seq - tcp->tcp_rnxt;
13324 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13325 	/*
13326 	 * gap is the amount of sequence space between what we expect to see
13327 	 * and what we got for seg_seq.  A positive value for gap means
13328 	 * something got lost.  A negative value means we got some old stuff.
13329 	 */
13330 	if (gap < 0) {
13331 		/* Old stuff present.  Is the SYN in there? */
13332 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13333 		    (seg_len != 0)) {
13334 			flags &= ~TH_SYN;
13335 			seg_seq++;
13336 			urp--;
13337 			/* Recompute the gaps after noting the SYN. */
13338 			goto try_again;
13339 		}
13340 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13341 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13342 		    (seg_len > -gap ? -gap : seg_len));
13343 		/* Remove the old stuff from seg_len. */
13344 		seg_len += gap;
13345 		/*
13346 		 * Anything left?
13347 		 * Make sure to check for unack'd FIN when rest of data
13348 		 * has been previously ack'd.
13349 		 */
13350 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13351 			/*
13352 			 * Resets are only valid if they lie within our offered
13353 			 * window.  If the RST bit is set, we just ignore this
13354 			 * segment.
13355 			 */
13356 			if (flags & TH_RST) {
13357 				freemsg(mp);
13358 				return;
13359 			}
13360 
13361 			/*
13362 			 * The arriving of dup data packets indicate that we
13363 			 * may have postponed an ack for too long, or the other
13364 			 * side's RTT estimate is out of shape. Start acking
13365 			 * more often.
13366 			 */
13367 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13368 			    tcp->tcp_rack_cnt >= 1 &&
13369 			    tcp->tcp_rack_abs_max > 2) {
13370 				tcp->tcp_rack_abs_max--;
13371 			}
13372 			tcp->tcp_rack_cur_max = 1;
13373 
13374 			/*
13375 			 * This segment is "unacceptable".  None of its
13376 			 * sequence space lies within our advertized window.
13377 			 *
13378 			 * Adjust seg_len to the original value for tracing.
13379 			 */
13380 			seg_len -= gap;
13381 			if (tcp->tcp_debug) {
13382 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13383 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13384 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13385 				    "seg_len %d, rnxt %u, snxt %u, %s",
13386 				    gap, rgap, flags, seg_seq, seg_ack,
13387 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13388 				    tcp_display(tcp, NULL,
13389 				    DISP_ADDR_AND_PORT));
13390 			}
13391 
13392 			/*
13393 			 * Arrange to send an ACK in response to the
13394 			 * unacceptable segment per RFC 793 page 69. There
13395 			 * is only one small difference between ours and the
13396 			 * acceptability test in the RFC - we accept ACK-only
13397 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13398 			 * will be generated.
13399 			 *
13400 			 * Note that we have to ACK an ACK-only packet at least
13401 			 * for stacks that send 0-length keep-alives with
13402 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13403 			 * section 4.2.3.6. As long as we don't ever generate
13404 			 * an unacceptable packet in response to an incoming
13405 			 * packet that is unacceptable, it should not cause
13406 			 * "ACK wars".
13407 			 */
13408 			flags |=  TH_ACK_NEEDED;
13409 
13410 			/*
13411 			 * Continue processing this segment in order to use the
13412 			 * ACK information it contains, but skip all other
13413 			 * sequence-number processing.	Processing the ACK
13414 			 * information is necessary in order to
13415 			 * re-synchronize connections that may have lost
13416 			 * synchronization.
13417 			 *
13418 			 * We clear seg_len and flag fields related to
13419 			 * sequence number processing as they are not
13420 			 * to be trusted for an unacceptable segment.
13421 			 */
13422 			seg_len = 0;
13423 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13424 			goto process_ack;
13425 		}
13426 
13427 		/* Fix seg_seq, and chew the gap off the front. */
13428 		seg_seq = tcp->tcp_rnxt;
13429 		urp += gap;
13430 		do {
13431 			mblk_t	*mp2;
13432 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13433 			    (uintptr_t)UINT_MAX);
13434 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13435 			if (gap > 0) {
13436 				mp->b_rptr = mp->b_wptr - gap;
13437 				break;
13438 			}
13439 			mp2 = mp;
13440 			mp = mp->b_cont;
13441 			freeb(mp2);
13442 		} while (gap < 0);
13443 		/*
13444 		 * If the urgent data has already been acknowledged, we
13445 		 * should ignore TH_URG below
13446 		 */
13447 		if (urp < 0)
13448 			flags &= ~TH_URG;
13449 	}
13450 	/*
13451 	 * rgap is the amount of stuff received out of window.  A negative
13452 	 * value is the amount out of window.
13453 	 */
13454 	if (rgap < 0) {
13455 		mblk_t	*mp2;
13456 
13457 		if (tcp->tcp_rwnd == 0) {
13458 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13459 		} else {
13460 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13461 			UPDATE_MIB(&tcps->tcps_mib,
13462 			    tcpInDataPastWinBytes, -rgap);
13463 		}
13464 
13465 		/*
13466 		 * seg_len does not include the FIN, so if more than
13467 		 * just the FIN is out of window, we act like we don't
13468 		 * see it.  (If just the FIN is out of window, rgap
13469 		 * will be zero and we will go ahead and acknowledge
13470 		 * the FIN.)
13471 		 */
13472 		flags &= ~TH_FIN;
13473 
13474 		/* Fix seg_len and make sure there is something left. */
13475 		seg_len += rgap;
13476 		if (seg_len <= 0) {
13477 			/*
13478 			 * Resets are only valid if they lie within our offered
13479 			 * window.  If the RST bit is set, we just ignore this
13480 			 * segment.
13481 			 */
13482 			if (flags & TH_RST) {
13483 				freemsg(mp);
13484 				return;
13485 			}
13486 
13487 			/* Per RFC 793, we need to send back an ACK. */
13488 			flags |= TH_ACK_NEEDED;
13489 
13490 			/*
13491 			 * Send SIGURG as soon as possible i.e. even
13492 			 * if the TH_URG was delivered in a window probe
13493 			 * packet (which will be unacceptable).
13494 			 *
13495 			 * We generate a signal if none has been generated
13496 			 * for this connection or if this is a new urgent
13497 			 * byte. Also send a zero-length "unmarked" message
13498 			 * to inform SIOCATMARK that this is not the mark.
13499 			 *
13500 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13501 			 * is sent up. This plus the check for old data
13502 			 * (gap >= 0) handles the wraparound of the sequence
13503 			 * number space without having to always track the
13504 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13505 			 * this max in its rcv_up variable).
13506 			 *
13507 			 * This prevents duplicate SIGURGS due to a "late"
13508 			 * zero-window probe when the T_EXDATA_IND has already
13509 			 * been sent up.
13510 			 */
13511 			if ((flags & TH_URG) &&
13512 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13513 			    tcp->tcp_urp_last))) {
13514 				mp1 = allocb(0, BPRI_MED);
13515 				if (mp1 == NULL) {
13516 					freemsg(mp);
13517 					return;
13518 				}
13519 				if (!TCP_IS_DETACHED(tcp) &&
13520 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13521 				    SIGURG)) {
13522 					/* Try again on the rexmit. */
13523 					freemsg(mp1);
13524 					freemsg(mp);
13525 					return;
13526 				}
13527 				/*
13528 				 * If the next byte would be the mark
13529 				 * then mark with MARKNEXT else mark
13530 				 * with NOTMARKNEXT.
13531 				 */
13532 				if (gap == 0 && urp == 0)
13533 					mp1->b_flag |= MSGMARKNEXT;
13534 				else
13535 					mp1->b_flag |= MSGNOTMARKNEXT;
13536 				freemsg(tcp->tcp_urp_mark_mp);
13537 				tcp->tcp_urp_mark_mp = mp1;
13538 				flags |= TH_SEND_URP_MARK;
13539 				tcp->tcp_urp_last_valid = B_TRUE;
13540 				tcp->tcp_urp_last = urp + seg_seq;
13541 			}
13542 			/*
13543 			 * If this is a zero window probe, continue to
13544 			 * process the ACK part.  But we need to set seg_len
13545 			 * to 0 to avoid data processing.  Otherwise just
13546 			 * drop the segment and send back an ACK.
13547 			 */
13548 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13549 				flags &= ~(TH_SYN | TH_URG);
13550 				seg_len = 0;
13551 				goto process_ack;
13552 			} else {
13553 				freemsg(mp);
13554 				goto ack_check;
13555 			}
13556 		}
13557 		/* Pitch out of window stuff off the end. */
13558 		rgap = seg_len;
13559 		mp2 = mp;
13560 		do {
13561 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13562 			    (uintptr_t)INT_MAX);
13563 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13564 			if (rgap < 0) {
13565 				mp2->b_wptr += rgap;
13566 				if ((mp1 = mp2->b_cont) != NULL) {
13567 					mp2->b_cont = NULL;
13568 					freemsg(mp1);
13569 				}
13570 				break;
13571 			}
13572 		} while ((mp2 = mp2->b_cont) != NULL);
13573 	}
13574 ok:;
13575 	/*
13576 	 * TCP should check ECN info for segments inside the window only.
13577 	 * Therefore the check should be done here.
13578 	 */
13579 	if (tcp->tcp_ecn_ok) {
13580 		if (flags & TH_CWR) {
13581 			tcp->tcp_ecn_echo_on = B_FALSE;
13582 		}
13583 		/*
13584 		 * Note that both ECN_CE and CWR can be set in the
13585 		 * same segment.  In this case, we once again turn
13586 		 * on ECN_ECHO.
13587 		 */
13588 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13589 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13590 
13591 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13592 				tcp->tcp_ecn_echo_on = B_TRUE;
13593 			}
13594 		} else {
13595 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13596 
13597 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13598 			    htonl(IPH_ECN_CE << 20)) {
13599 				tcp->tcp_ecn_echo_on = B_TRUE;
13600 			}
13601 		}
13602 	}
13603 
13604 	/*
13605 	 * Check whether we can update tcp_ts_recent.  This test is
13606 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13607 	 * Extensions for High Performance: An Update", Internet Draft.
13608 	 */
13609 	if (tcp->tcp_snd_ts_ok &&
13610 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13611 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13612 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13613 		tcp->tcp_last_rcv_lbolt = lbolt64;
13614 	}
13615 
13616 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13617 		/*
13618 		 * FIN in an out of order segment.  We record this in
13619 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13620 		 * Clear the FIN so that any check on FIN flag will fail.
13621 		 * Remember that FIN also counts in the sequence number
13622 		 * space.  So we need to ack out of order FIN only segments.
13623 		 */
13624 		if (flags & TH_FIN) {
13625 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13626 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13627 			flags &= ~TH_FIN;
13628 			flags |= TH_ACK_NEEDED;
13629 		}
13630 		if (seg_len > 0) {
13631 			/* Fill in the SACK blk list. */
13632 			if (tcp->tcp_snd_sack_ok) {
13633 				ASSERT(tcp->tcp_sack_info != NULL);
13634 				tcp_sack_insert(tcp->tcp_sack_list,
13635 				    seg_seq, seg_seq + seg_len,
13636 				    &(tcp->tcp_num_sack_blk));
13637 			}
13638 
13639 			/*
13640 			 * Attempt reassembly and see if we have something
13641 			 * ready to go.
13642 			 */
13643 			mp = tcp_reass(tcp, mp, seg_seq);
13644 			/* Always ack out of order packets */
13645 			flags |= TH_ACK_NEEDED | TH_PUSH;
13646 			if (mp) {
13647 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13648 				    (uintptr_t)INT_MAX);
13649 				seg_len = mp->b_cont ? msgdsize(mp) :
13650 				    (int)(mp->b_wptr - mp->b_rptr);
13651 				seg_seq = tcp->tcp_rnxt;
13652 				/*
13653 				 * A gap is filled and the seq num and len
13654 				 * of the gap match that of a previously
13655 				 * received FIN, put the FIN flag back in.
13656 				 */
13657 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13658 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13659 					flags |= TH_FIN;
13660 					tcp->tcp_valid_bits &=
13661 					    ~TCP_OFO_FIN_VALID;
13662 				}
13663 			} else {
13664 				/*
13665 				 * Keep going even with NULL mp.
13666 				 * There may be a useful ACK or something else
13667 				 * we don't want to miss.
13668 				 *
13669 				 * But TCP should not perform fast retransmit
13670 				 * because of the ack number.  TCP uses
13671 				 * seg_len == 0 to determine if it is a pure
13672 				 * ACK.  And this is not a pure ACK.
13673 				 */
13674 				seg_len = 0;
13675 				ofo_seg = B_TRUE;
13676 			}
13677 		}
13678 	} else if (seg_len > 0) {
13679 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13680 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13681 		/*
13682 		 * If an out of order FIN was received before, and the seq
13683 		 * num and len of the new segment match that of the FIN,
13684 		 * put the FIN flag back in.
13685 		 */
13686 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13687 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13688 			flags |= TH_FIN;
13689 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13690 		}
13691 	}
13692 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13693 	if (flags & TH_RST) {
13694 		freemsg(mp);
13695 		switch (tcp->tcp_state) {
13696 		case TCPS_SYN_RCVD:
13697 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13698 			break;
13699 		case TCPS_ESTABLISHED:
13700 		case TCPS_FIN_WAIT_1:
13701 		case TCPS_FIN_WAIT_2:
13702 		case TCPS_CLOSE_WAIT:
13703 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13704 			break;
13705 		case TCPS_CLOSING:
13706 		case TCPS_LAST_ACK:
13707 			(void) tcp_clean_death(tcp, 0, 16);
13708 			break;
13709 		default:
13710 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13711 			(void) tcp_clean_death(tcp, ENXIO, 17);
13712 			break;
13713 		}
13714 		return;
13715 	}
13716 	if (flags & TH_SYN) {
13717 		/*
13718 		 * See RFC 793, Page 71
13719 		 *
13720 		 * The seq number must be in the window as it should
13721 		 * be "fixed" above.  If it is outside window, it should
13722 		 * be already rejected.  Note that we allow seg_seq to be
13723 		 * rnxt + rwnd because we want to accept 0 window probe.
13724 		 */
13725 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13726 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13727 		freemsg(mp);
13728 		/*
13729 		 * If the ACK flag is not set, just use our snxt as the
13730 		 * seq number of the RST segment.
13731 		 */
13732 		if (!(flags & TH_ACK)) {
13733 			seg_ack = tcp->tcp_snxt;
13734 		}
13735 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13736 		    TH_RST|TH_ACK);
13737 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13738 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13739 		return;
13740 	}
13741 	/*
13742 	 * urp could be -1 when the urp field in the packet is 0
13743 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13744 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13745 	 */
13746 	if (flags & TH_URG && urp >= 0) {
13747 		if (!tcp->tcp_urp_last_valid ||
13748 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13749 			/*
13750 			 * If we haven't generated the signal yet for this
13751 			 * urgent pointer value, do it now.  Also, send up a
13752 			 * zero-length M_DATA indicating whether or not this is
13753 			 * the mark. The latter is not needed when a
13754 			 * T_EXDATA_IND is sent up. However, if there are
13755 			 * allocation failures this code relies on the sender
13756 			 * retransmitting and the socket code for determining
13757 			 * the mark should not block waiting for the peer to
13758 			 * transmit. Thus, for simplicity we always send up the
13759 			 * mark indication.
13760 			 */
13761 			mp1 = allocb(0, BPRI_MED);
13762 			if (mp1 == NULL) {
13763 				freemsg(mp);
13764 				return;
13765 			}
13766 			if (!TCP_IS_DETACHED(tcp) &&
13767 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13768 				/* Try again on the rexmit. */
13769 				freemsg(mp1);
13770 				freemsg(mp);
13771 				return;
13772 			}
13773 			/*
13774 			 * Mark with NOTMARKNEXT for now.
13775 			 * The code below will change this to MARKNEXT
13776 			 * if we are at the mark.
13777 			 *
13778 			 * If there are allocation failures (e.g. in dupmsg
13779 			 * below) the next time tcp_rput_data sees the urgent
13780 			 * segment it will send up the MSG*MARKNEXT message.
13781 			 */
13782 			mp1->b_flag |= MSGNOTMARKNEXT;
13783 			freemsg(tcp->tcp_urp_mark_mp);
13784 			tcp->tcp_urp_mark_mp = mp1;
13785 			flags |= TH_SEND_URP_MARK;
13786 #ifdef DEBUG
13787 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13788 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13789 			    "last %x, %s",
13790 			    seg_seq, urp, tcp->tcp_urp_last,
13791 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13792 #endif /* DEBUG */
13793 			tcp->tcp_urp_last_valid = B_TRUE;
13794 			tcp->tcp_urp_last = urp + seg_seq;
13795 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13796 			/*
13797 			 * An allocation failure prevented the previous
13798 			 * tcp_rput_data from sending up the allocated
13799 			 * MSG*MARKNEXT message - send it up this time
13800 			 * around.
13801 			 */
13802 			flags |= TH_SEND_URP_MARK;
13803 		}
13804 
13805 		/*
13806 		 * If the urgent byte is in this segment, make sure that it is
13807 		 * all by itself.  This makes it much easier to deal with the
13808 		 * possibility of an allocation failure on the T_exdata_ind.
13809 		 * Note that seg_len is the number of bytes in the segment, and
13810 		 * urp is the offset into the segment of the urgent byte.
13811 		 * urp < seg_len means that the urgent byte is in this segment.
13812 		 */
13813 		if (urp < seg_len) {
13814 			if (seg_len != 1) {
13815 				uint32_t  tmp_rnxt;
13816 				/*
13817 				 * Break it up and feed it back in.
13818 				 * Re-attach the IP header.
13819 				 */
13820 				mp->b_rptr = iphdr;
13821 				if (urp > 0) {
13822 					/*
13823 					 * There is stuff before the urgent
13824 					 * byte.
13825 					 */
13826 					mp1 = dupmsg(mp);
13827 					if (!mp1) {
13828 						/*
13829 						 * Trim from urgent byte on.
13830 						 * The rest will come back.
13831 						 */
13832 						(void) adjmsg(mp,
13833 						    urp - seg_len);
13834 						tcp_rput_data(connp,
13835 						    mp, NULL);
13836 						return;
13837 					}
13838 					(void) adjmsg(mp1, urp - seg_len);
13839 					/* Feed this piece back in. */
13840 					tmp_rnxt = tcp->tcp_rnxt;
13841 					tcp_rput_data(connp, mp1, NULL);
13842 					/*
13843 					 * If the data passed back in was not
13844 					 * processed (ie: bad ACK) sending
13845 					 * the remainder back in will cause a
13846 					 * loop. In this case, drop the
13847 					 * packet and let the sender try
13848 					 * sending a good packet.
13849 					 */
13850 					if (tmp_rnxt == tcp->tcp_rnxt) {
13851 						freemsg(mp);
13852 						return;
13853 					}
13854 				}
13855 				if (urp != seg_len - 1) {
13856 					uint32_t  tmp_rnxt;
13857 					/*
13858 					 * There is stuff after the urgent
13859 					 * byte.
13860 					 */
13861 					mp1 = dupmsg(mp);
13862 					if (!mp1) {
13863 						/*
13864 						 * Trim everything beyond the
13865 						 * urgent byte.  The rest will
13866 						 * come back.
13867 						 */
13868 						(void) adjmsg(mp,
13869 						    urp + 1 - seg_len);
13870 						tcp_rput_data(connp,
13871 						    mp, NULL);
13872 						return;
13873 					}
13874 					(void) adjmsg(mp1, urp + 1 - seg_len);
13875 					tmp_rnxt = tcp->tcp_rnxt;
13876 					tcp_rput_data(connp, mp1, NULL);
13877 					/*
13878 					 * If the data passed back in was not
13879 					 * processed (ie: bad ACK) sending
13880 					 * the remainder back in will cause a
13881 					 * loop. In this case, drop the
13882 					 * packet and let the sender try
13883 					 * sending a good packet.
13884 					 */
13885 					if (tmp_rnxt == tcp->tcp_rnxt) {
13886 						freemsg(mp);
13887 						return;
13888 					}
13889 				}
13890 				tcp_rput_data(connp, mp, NULL);
13891 				return;
13892 			}
13893 			/*
13894 			 * This segment contains only the urgent byte.  We
13895 			 * have to allocate the T_exdata_ind, if we can.
13896 			 */
13897 			if (!tcp->tcp_urp_mp) {
13898 				struct T_exdata_ind *tei;
13899 				mp1 = allocb(sizeof (struct T_exdata_ind),
13900 				    BPRI_MED);
13901 				if (!mp1) {
13902 					/*
13903 					 * Sigh... It'll be back.
13904 					 * Generate any MSG*MARK message now.
13905 					 */
13906 					freemsg(mp);
13907 					seg_len = 0;
13908 					if (flags & TH_SEND_URP_MARK) {
13909 
13910 
13911 						ASSERT(tcp->tcp_urp_mark_mp);
13912 						tcp->tcp_urp_mark_mp->b_flag &=
13913 						    ~MSGNOTMARKNEXT;
13914 						tcp->tcp_urp_mark_mp->b_flag |=
13915 						    MSGMARKNEXT;
13916 					}
13917 					goto ack_check;
13918 				}
13919 				mp1->b_datap->db_type = M_PROTO;
13920 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13921 				tei->PRIM_type = T_EXDATA_IND;
13922 				tei->MORE_flag = 0;
13923 				mp1->b_wptr = (uchar_t *)&tei[1];
13924 				tcp->tcp_urp_mp = mp1;
13925 #ifdef DEBUG
13926 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13927 				    "tcp_rput: allocated exdata_ind %s",
13928 				    tcp_display(tcp, NULL,
13929 				    DISP_PORT_ONLY));
13930 #endif /* DEBUG */
13931 				/*
13932 				 * There is no need to send a separate MSG*MARK
13933 				 * message since the T_EXDATA_IND will be sent
13934 				 * now.
13935 				 */
13936 				flags &= ~TH_SEND_URP_MARK;
13937 				freemsg(tcp->tcp_urp_mark_mp);
13938 				tcp->tcp_urp_mark_mp = NULL;
13939 			}
13940 			/*
13941 			 * Now we are all set.  On the next putnext upstream,
13942 			 * tcp_urp_mp will be non-NULL and will get prepended
13943 			 * to what has to be this piece containing the urgent
13944 			 * byte.  If for any reason we abort this segment below,
13945 			 * if it comes back, we will have this ready, or it
13946 			 * will get blown off in close.
13947 			 */
13948 		} else if (urp == seg_len) {
13949 			/*
13950 			 * The urgent byte is the next byte after this sequence
13951 			 * number. If there is data it is marked with
13952 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13953 			 * since it is not needed. Otherwise, if the code
13954 			 * above just allocated a zero-length tcp_urp_mark_mp
13955 			 * message, that message is tagged with MSGMARKNEXT.
13956 			 * Sending up these MSGMARKNEXT messages makes
13957 			 * SIOCATMARK work correctly even though
13958 			 * the T_EXDATA_IND will not be sent up until the
13959 			 * urgent byte arrives.
13960 			 */
13961 			if (seg_len != 0) {
13962 				flags |= TH_MARKNEXT_NEEDED;
13963 				freemsg(tcp->tcp_urp_mark_mp);
13964 				tcp->tcp_urp_mark_mp = NULL;
13965 				flags &= ~TH_SEND_URP_MARK;
13966 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13967 				flags |= TH_SEND_URP_MARK;
13968 				tcp->tcp_urp_mark_mp->b_flag &=
13969 				    ~MSGNOTMARKNEXT;
13970 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13971 			}
13972 #ifdef DEBUG
13973 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13974 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13975 			    seg_len, flags,
13976 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13977 #endif /* DEBUG */
13978 		} else {
13979 			/* Data left until we hit mark */
13980 #ifdef DEBUG
13981 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13982 			    "tcp_rput: URP %d bytes left, %s",
13983 			    urp - seg_len, tcp_display(tcp, NULL,
13984 			    DISP_PORT_ONLY));
13985 #endif /* DEBUG */
13986 		}
13987 	}
13988 
13989 process_ack:
13990 	if (!(flags & TH_ACK)) {
13991 		freemsg(mp);
13992 		goto xmit_check;
13993 	}
13994 	}
13995 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13996 
13997 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13998 		tcp->tcp_ip_forward_progress = B_TRUE;
13999 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14000 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14001 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14002 			/* 3-way handshake complete - pass up the T_CONN_IND */
14003 			tcp_t	*listener = tcp->tcp_listener;
14004 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14005 
14006 			tcp->tcp_tconnind_started = B_TRUE;
14007 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14008 			/*
14009 			 * We are here means eager is fine but it can
14010 			 * get a TH_RST at any point between now and till
14011 			 * accept completes and disappear. We need to
14012 			 * ensure that reference to eager is valid after
14013 			 * we get out of eager's perimeter. So we do
14014 			 * an extra refhold.
14015 			 */
14016 			CONN_INC_REF(connp);
14017 
14018 			/*
14019 			 * The listener also exists because of the refhold
14020 			 * done in tcp_conn_request. Its possible that it
14021 			 * might have closed. We will check that once we
14022 			 * get inside listeners context.
14023 			 */
14024 			CONN_INC_REF(listener->tcp_connp);
14025 			if (listener->tcp_connp->conn_sqp ==
14026 			    connp->conn_sqp) {
14027 				tcp_send_conn_ind(listener->tcp_connp, mp,
14028 				    listener->tcp_connp->conn_sqp);
14029 				CONN_DEC_REF(listener->tcp_connp);
14030 			} else if (!tcp->tcp_loopback) {
14031 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14032 				    tcp_send_conn_ind,
14033 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14034 			} else {
14035 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14036 				    tcp_send_conn_ind, listener->tcp_connp,
14037 				    SQTAG_TCP_CONN_IND);
14038 			}
14039 		}
14040 
14041 		if (tcp->tcp_active_open) {
14042 			/*
14043 			 * We are seeing the final ack in the three way
14044 			 * hand shake of a active open'ed connection
14045 			 * so we must send up a T_CONN_CON
14046 			 */
14047 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14048 				freemsg(mp);
14049 				return;
14050 			}
14051 			/*
14052 			 * Don't fuse the loopback endpoints for
14053 			 * simultaneous active opens.
14054 			 */
14055 			if (tcp->tcp_loopback) {
14056 				TCP_STAT(tcps, tcp_fusion_unfusable);
14057 				tcp->tcp_unfusable = B_TRUE;
14058 			}
14059 		}
14060 
14061 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14062 		bytes_acked--;
14063 		/* SYN was acked - making progress */
14064 		if (tcp->tcp_ipversion == IPV6_VERSION)
14065 			tcp->tcp_ip_forward_progress = B_TRUE;
14066 
14067 		/*
14068 		 * If SYN was retransmitted, need to reset all
14069 		 * retransmission info as this segment will be
14070 		 * treated as a dup ACK.
14071 		 */
14072 		if (tcp->tcp_rexmit) {
14073 			tcp->tcp_rexmit = B_FALSE;
14074 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14075 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14076 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14077 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14078 			tcp->tcp_ms_we_have_waited = 0;
14079 			tcp->tcp_cwnd = mss;
14080 		}
14081 
14082 		/*
14083 		 * We set the send window to zero here.
14084 		 * This is needed if there is data to be
14085 		 * processed already on the queue.
14086 		 * Later (at swnd_update label), the
14087 		 * "new_swnd > tcp_swnd" condition is satisfied
14088 		 * the XMIT_NEEDED flag is set in the current
14089 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14090 		 * called if there is already data on queue in
14091 		 * this state.
14092 		 */
14093 		tcp->tcp_swnd = 0;
14094 
14095 		if (new_swnd > tcp->tcp_max_swnd)
14096 			tcp->tcp_max_swnd = new_swnd;
14097 		tcp->tcp_swl1 = seg_seq;
14098 		tcp->tcp_swl2 = seg_ack;
14099 		tcp->tcp_state = TCPS_ESTABLISHED;
14100 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14101 
14102 		/* Fuse when both sides are in ESTABLISHED state */
14103 		if (tcp->tcp_loopback && do_tcp_fusion)
14104 			tcp_fuse(tcp, iphdr, tcph);
14105 
14106 	}
14107 	/* This code follows 4.4BSD-Lite2 mostly. */
14108 	if (bytes_acked < 0)
14109 		goto est;
14110 
14111 	/*
14112 	 * If TCP is ECN capable and the congestion experience bit is
14113 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14114 	 * done once per window (or more loosely, per RTT).
14115 	 */
14116 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14117 		tcp->tcp_cwr = B_FALSE;
14118 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14119 		if (!tcp->tcp_cwr) {
14120 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14121 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14122 			tcp->tcp_cwnd = npkt * mss;
14123 			/*
14124 			 * If the cwnd is 0, use the timer to clock out
14125 			 * new segments.  This is required by the ECN spec.
14126 			 */
14127 			if (npkt == 0) {
14128 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14129 				/*
14130 				 * This makes sure that when the ACK comes
14131 				 * back, we will increase tcp_cwnd by 1 MSS.
14132 				 */
14133 				tcp->tcp_cwnd_cnt = 0;
14134 			}
14135 			tcp->tcp_cwr = B_TRUE;
14136 			/*
14137 			 * This marks the end of the current window of in
14138 			 * flight data.  That is why we don't use
14139 			 * tcp_suna + tcp_swnd.  Only data in flight can
14140 			 * provide ECN info.
14141 			 */
14142 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14143 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14144 		}
14145 	}
14146 
14147 	mp1 = tcp->tcp_xmit_head;
14148 	if (bytes_acked == 0) {
14149 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14150 			int dupack_cnt;
14151 
14152 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14153 			/*
14154 			 * Fast retransmit.  When we have seen exactly three
14155 			 * identical ACKs while we have unacked data
14156 			 * outstanding we take it as a hint that our peer
14157 			 * dropped something.
14158 			 *
14159 			 * If TCP is retransmitting, don't do fast retransmit.
14160 			 */
14161 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14162 			    ! tcp->tcp_rexmit) {
14163 				/* Do Limited Transmit */
14164 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14165 				    tcps->tcps_dupack_fast_retransmit) {
14166 					/*
14167 					 * RFC 3042
14168 					 *
14169 					 * What we need to do is temporarily
14170 					 * increase tcp_cwnd so that new
14171 					 * data can be sent if it is allowed
14172 					 * by the receive window (tcp_rwnd).
14173 					 * tcp_wput_data() will take care of
14174 					 * the rest.
14175 					 *
14176 					 * If the connection is SACK capable,
14177 					 * only do limited xmit when there
14178 					 * is SACK info.
14179 					 *
14180 					 * Note how tcp_cwnd is incremented.
14181 					 * The first dup ACK will increase
14182 					 * it by 1 MSS.  The second dup ACK
14183 					 * will increase it by 2 MSS.  This
14184 					 * means that only 1 new segment will
14185 					 * be sent for each dup ACK.
14186 					 */
14187 					if (tcp->tcp_unsent > 0 &&
14188 					    (!tcp->tcp_snd_sack_ok ||
14189 					    (tcp->tcp_snd_sack_ok &&
14190 					    tcp->tcp_notsack_list != NULL))) {
14191 						tcp->tcp_cwnd += mss <<
14192 						    (tcp->tcp_dupack_cnt - 1);
14193 						flags |= TH_LIMIT_XMIT;
14194 					}
14195 				} else if (dupack_cnt ==
14196 				    tcps->tcps_dupack_fast_retransmit) {
14197 
14198 				/*
14199 				 * If we have reduced tcp_ssthresh
14200 				 * because of ECN, do not reduce it again
14201 				 * unless it is already one window of data
14202 				 * away.  After one window of data, tcp_cwr
14203 				 * should then be cleared.  Note that
14204 				 * for non ECN capable connection, tcp_cwr
14205 				 * should always be false.
14206 				 *
14207 				 * Adjust cwnd since the duplicate
14208 				 * ack indicates that a packet was
14209 				 * dropped (due to congestion.)
14210 				 */
14211 				if (!tcp->tcp_cwr) {
14212 					npkt = ((tcp->tcp_snxt -
14213 					    tcp->tcp_suna) >> 1) / mss;
14214 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14215 					    mss;
14216 					tcp->tcp_cwnd = (npkt +
14217 					    tcp->tcp_dupack_cnt) * mss;
14218 				}
14219 				if (tcp->tcp_ecn_ok) {
14220 					tcp->tcp_cwr = B_TRUE;
14221 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14222 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14223 				}
14224 
14225 				/*
14226 				 * We do Hoe's algorithm.  Refer to her
14227 				 * paper "Improving the Start-up Behavior
14228 				 * of a Congestion Control Scheme for TCP,"
14229 				 * appeared in SIGCOMM'96.
14230 				 *
14231 				 * Save highest seq no we have sent so far.
14232 				 * Be careful about the invisible FIN byte.
14233 				 */
14234 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14235 				    (tcp->tcp_unsent == 0)) {
14236 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14237 				} else {
14238 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14239 				}
14240 
14241 				/*
14242 				 * Do not allow bursty traffic during.
14243 				 * fast recovery.  Refer to Fall and Floyd's
14244 				 * paper "Simulation-based Comparisons of
14245 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14246 				 * This is a best current practise.
14247 				 */
14248 				tcp->tcp_snd_burst = TCP_CWND_SS;
14249 
14250 				/*
14251 				 * For SACK:
14252 				 * Calculate tcp_pipe, which is the
14253 				 * estimated number of bytes in
14254 				 * network.
14255 				 *
14256 				 * tcp_fack is the highest sack'ed seq num
14257 				 * TCP has received.
14258 				 *
14259 				 * tcp_pipe is explained in the above quoted
14260 				 * Fall and Floyd's paper.  tcp_fack is
14261 				 * explained in Mathis and Mahdavi's
14262 				 * "Forward Acknowledgment: Refining TCP
14263 				 * Congestion Control" in SIGCOMM '96.
14264 				 */
14265 				if (tcp->tcp_snd_sack_ok) {
14266 					ASSERT(tcp->tcp_sack_info != NULL);
14267 					if (tcp->tcp_notsack_list != NULL) {
14268 						tcp->tcp_pipe = tcp->tcp_snxt -
14269 						    tcp->tcp_fack;
14270 						tcp->tcp_sack_snxt = seg_ack;
14271 						flags |= TH_NEED_SACK_REXMIT;
14272 					} else {
14273 						/*
14274 						 * Always initialize tcp_pipe
14275 						 * even though we don't have
14276 						 * any SACK info.  If later
14277 						 * we get SACK info and
14278 						 * tcp_pipe is not initialized,
14279 						 * funny things will happen.
14280 						 */
14281 						tcp->tcp_pipe =
14282 						    tcp->tcp_cwnd_ssthresh;
14283 					}
14284 				} else {
14285 					flags |= TH_REXMIT_NEEDED;
14286 				} /* tcp_snd_sack_ok */
14287 
14288 				} else {
14289 					/*
14290 					 * Here we perform congestion
14291 					 * avoidance, but NOT slow start.
14292 					 * This is known as the Fast
14293 					 * Recovery Algorithm.
14294 					 */
14295 					if (tcp->tcp_snd_sack_ok &&
14296 					    tcp->tcp_notsack_list != NULL) {
14297 						flags |= TH_NEED_SACK_REXMIT;
14298 						tcp->tcp_pipe -= mss;
14299 						if (tcp->tcp_pipe < 0)
14300 							tcp->tcp_pipe = 0;
14301 					} else {
14302 					/*
14303 					 * We know that one more packet has
14304 					 * left the pipe thus we can update
14305 					 * cwnd.
14306 					 */
14307 					cwnd = tcp->tcp_cwnd + mss;
14308 					if (cwnd > tcp->tcp_cwnd_max)
14309 						cwnd = tcp->tcp_cwnd_max;
14310 					tcp->tcp_cwnd = cwnd;
14311 					if (tcp->tcp_unsent > 0)
14312 						flags |= TH_XMIT_NEEDED;
14313 					}
14314 				}
14315 			}
14316 		} else if (tcp->tcp_zero_win_probe) {
14317 			/*
14318 			 * If the window has opened, need to arrange
14319 			 * to send additional data.
14320 			 */
14321 			if (new_swnd != 0) {
14322 				/* tcp_suna != tcp_snxt */
14323 				/* Packet contains a window update */
14324 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14325 				tcp->tcp_zero_win_probe = 0;
14326 				tcp->tcp_timer_backoff = 0;
14327 				tcp->tcp_ms_we_have_waited = 0;
14328 
14329 				/*
14330 				 * Transmit starting with tcp_suna since
14331 				 * the one byte probe is not ack'ed.
14332 				 * If TCP has sent more than one identical
14333 				 * probe, tcp_rexmit will be set.  That means
14334 				 * tcp_ss_rexmit() will send out the one
14335 				 * byte along with new data.  Otherwise,
14336 				 * fake the retransmission.
14337 				 */
14338 				flags |= TH_XMIT_NEEDED;
14339 				if (!tcp->tcp_rexmit) {
14340 					tcp->tcp_rexmit = B_TRUE;
14341 					tcp->tcp_dupack_cnt = 0;
14342 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14343 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14344 				}
14345 			}
14346 		}
14347 		goto swnd_update;
14348 	}
14349 
14350 	/*
14351 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14352 	 * If the ACK value acks something that we have not yet sent, it might
14353 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14354 	 * other side.
14355 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14356 	 * state is handled above, so we can always just drop the segment and
14357 	 * send an ACK here.
14358 	 *
14359 	 * Should we send ACKs in response to ACK only segments?
14360 	 */
14361 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14362 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14363 		/* drop the received segment */
14364 		freemsg(mp);
14365 
14366 		/*
14367 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14368 		 * greater than 0, check if the number of such
14369 		 * bogus ACks is greater than that count.  If yes,
14370 		 * don't send back any ACK.  This prevents TCP from
14371 		 * getting into an ACK storm if somehow an attacker
14372 		 * successfully spoofs an acceptable segment to our
14373 		 * peer.
14374 		 */
14375 		if (tcp_drop_ack_unsent_cnt > 0 &&
14376 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14377 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14378 			return;
14379 		}
14380 		mp = tcp_ack_mp(tcp);
14381 		if (mp != NULL) {
14382 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14383 			BUMP_LOCAL(tcp->tcp_obsegs);
14384 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14385 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14386 		}
14387 		return;
14388 	}
14389 
14390 	/*
14391 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14392 	 * blocks that are covered by this ACK.
14393 	 */
14394 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14395 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14396 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14397 	}
14398 
14399 	/*
14400 	 * If we got an ACK after fast retransmit, check to see
14401 	 * if it is a partial ACK.  If it is not and the congestion
14402 	 * window was inflated to account for the other side's
14403 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14404 	 */
14405 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14406 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14407 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14408 			tcp->tcp_dupack_cnt = 0;
14409 			/*
14410 			 * Restore the orig tcp_cwnd_ssthresh after
14411 			 * fast retransmit phase.
14412 			 */
14413 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14414 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14415 			}
14416 			tcp->tcp_rexmit_max = seg_ack;
14417 			tcp->tcp_cwnd_cnt = 0;
14418 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14419 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14420 
14421 			/*
14422 			 * Remove all notsack info to avoid confusion with
14423 			 * the next fast retrasnmit/recovery phase.
14424 			 */
14425 			if (tcp->tcp_snd_sack_ok &&
14426 			    tcp->tcp_notsack_list != NULL) {
14427 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14428 			}
14429 		} else {
14430 			if (tcp->tcp_snd_sack_ok &&
14431 			    tcp->tcp_notsack_list != NULL) {
14432 				flags |= TH_NEED_SACK_REXMIT;
14433 				tcp->tcp_pipe -= mss;
14434 				if (tcp->tcp_pipe < 0)
14435 					tcp->tcp_pipe = 0;
14436 			} else {
14437 				/*
14438 				 * Hoe's algorithm:
14439 				 *
14440 				 * Retransmit the unack'ed segment and
14441 				 * restart fast recovery.  Note that we
14442 				 * need to scale back tcp_cwnd to the
14443 				 * original value when we started fast
14444 				 * recovery.  This is to prevent overly
14445 				 * aggressive behaviour in sending new
14446 				 * segments.
14447 				 */
14448 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14449 				    tcps->tcps_dupack_fast_retransmit * mss;
14450 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14451 				flags |= TH_REXMIT_NEEDED;
14452 			}
14453 		}
14454 	} else {
14455 		tcp->tcp_dupack_cnt = 0;
14456 		if (tcp->tcp_rexmit) {
14457 			/*
14458 			 * TCP is retranmitting.  If the ACK ack's all
14459 			 * outstanding data, update tcp_rexmit_max and
14460 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14461 			 * to the correct value.
14462 			 *
14463 			 * Note that SEQ_LEQ() is used.  This is to avoid
14464 			 * unnecessary fast retransmit caused by dup ACKs
14465 			 * received when TCP does slow start retransmission
14466 			 * after a time out.  During this phase, TCP may
14467 			 * send out segments which are already received.
14468 			 * This causes dup ACKs to be sent back.
14469 			 */
14470 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14471 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14472 					tcp->tcp_rexmit_nxt = seg_ack;
14473 				}
14474 				if (seg_ack != tcp->tcp_rexmit_max) {
14475 					flags |= TH_XMIT_NEEDED;
14476 				}
14477 			} else {
14478 				tcp->tcp_rexmit = B_FALSE;
14479 				tcp->tcp_xmit_zc_clean = B_FALSE;
14480 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14481 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14482 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14483 			}
14484 			tcp->tcp_ms_we_have_waited = 0;
14485 		}
14486 	}
14487 
14488 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14489 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14490 	tcp->tcp_suna = seg_ack;
14491 	if (tcp->tcp_zero_win_probe != 0) {
14492 		tcp->tcp_zero_win_probe = 0;
14493 		tcp->tcp_timer_backoff = 0;
14494 	}
14495 
14496 	/*
14497 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14498 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14499 	 * will not reach here.
14500 	 */
14501 	if (mp1 == NULL) {
14502 		goto fin_acked;
14503 	}
14504 
14505 	/*
14506 	 * Update the congestion window.
14507 	 *
14508 	 * If TCP is not ECN capable or TCP is ECN capable but the
14509 	 * congestion experience bit is not set, increase the tcp_cwnd as
14510 	 * usual.
14511 	 */
14512 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14513 		cwnd = tcp->tcp_cwnd;
14514 		add = mss;
14515 
14516 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14517 			/*
14518 			 * This is to prevent an increase of less than 1 MSS of
14519 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14520 			 * may send out tinygrams in order to preserve mblk
14521 			 * boundaries.
14522 			 *
14523 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14524 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14525 			 * increased by 1 MSS for every RTTs.
14526 			 */
14527 			if (tcp->tcp_cwnd_cnt <= 0) {
14528 				tcp->tcp_cwnd_cnt = cwnd + add;
14529 			} else {
14530 				tcp->tcp_cwnd_cnt -= add;
14531 				add = 0;
14532 			}
14533 		}
14534 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14535 	}
14536 
14537 	/* See if the latest urgent data has been acknowledged */
14538 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14539 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14540 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14541 
14542 	/* Can we update the RTT estimates? */
14543 	if (tcp->tcp_snd_ts_ok) {
14544 		/* Ignore zero timestamp echo-reply. */
14545 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14546 			tcp_set_rto(tcp, (int32_t)lbolt -
14547 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14548 		}
14549 
14550 		/* If needed, restart the timer. */
14551 		if (tcp->tcp_set_timer == 1) {
14552 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14553 			tcp->tcp_set_timer = 0;
14554 		}
14555 		/*
14556 		 * Update tcp_csuna in case the other side stops sending
14557 		 * us timestamps.
14558 		 */
14559 		tcp->tcp_csuna = tcp->tcp_snxt;
14560 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14561 		/*
14562 		 * An ACK sequence we haven't seen before, so get the RTT
14563 		 * and update the RTO. But first check if the timestamp is
14564 		 * valid to use.
14565 		 */
14566 		if ((mp1->b_next != NULL) &&
14567 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14568 			tcp_set_rto(tcp, (int32_t)lbolt -
14569 			    (int32_t)(intptr_t)mp1->b_prev);
14570 		else
14571 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14572 
14573 		/* Remeber the last sequence to be ACKed */
14574 		tcp->tcp_csuna = seg_ack;
14575 		if (tcp->tcp_set_timer == 1) {
14576 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14577 			tcp->tcp_set_timer = 0;
14578 		}
14579 	} else {
14580 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14581 	}
14582 
14583 	/* Eat acknowledged bytes off the xmit queue. */
14584 	for (;;) {
14585 		mblk_t	*mp2;
14586 		uchar_t	*wptr;
14587 
14588 		wptr = mp1->b_wptr;
14589 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14590 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14591 		if (bytes_acked < 0) {
14592 			mp1->b_rptr = wptr + bytes_acked;
14593 			/*
14594 			 * Set a new timestamp if all the bytes timed by the
14595 			 * old timestamp have been ack'ed.
14596 			 */
14597 			if (SEQ_GT(seg_ack,
14598 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14599 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14600 				mp1->b_next = NULL;
14601 			}
14602 			break;
14603 		}
14604 		mp1->b_next = NULL;
14605 		mp1->b_prev = NULL;
14606 		mp2 = mp1;
14607 		mp1 = mp1->b_cont;
14608 
14609 		/*
14610 		 * This notification is required for some zero-copy
14611 		 * clients to maintain a copy semantic. After the data
14612 		 * is ack'ed, client is safe to modify or reuse the buffer.
14613 		 */
14614 		if (tcp->tcp_snd_zcopy_aware &&
14615 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14616 			tcp_zcopy_notify(tcp);
14617 		freeb(mp2);
14618 		if (bytes_acked == 0) {
14619 			if (mp1 == NULL) {
14620 				/* Everything is ack'ed, clear the tail. */
14621 				tcp->tcp_xmit_tail = NULL;
14622 				/*
14623 				 * Cancel the timer unless we are still
14624 				 * waiting for an ACK for the FIN packet.
14625 				 */
14626 				if (tcp->tcp_timer_tid != 0 &&
14627 				    tcp->tcp_snxt == tcp->tcp_suna) {
14628 					(void) TCP_TIMER_CANCEL(tcp,
14629 					    tcp->tcp_timer_tid);
14630 					tcp->tcp_timer_tid = 0;
14631 				}
14632 				goto pre_swnd_update;
14633 			}
14634 			if (mp2 != tcp->tcp_xmit_tail)
14635 				break;
14636 			tcp->tcp_xmit_tail = mp1;
14637 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14638 			    (uintptr_t)INT_MAX);
14639 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14640 			    mp1->b_rptr);
14641 			break;
14642 		}
14643 		if (mp1 == NULL) {
14644 			/*
14645 			 * More was acked but there is nothing more
14646 			 * outstanding.  This means that the FIN was
14647 			 * just acked or that we're talking to a clown.
14648 			 */
14649 fin_acked:
14650 			ASSERT(tcp->tcp_fin_sent);
14651 			tcp->tcp_xmit_tail = NULL;
14652 			if (tcp->tcp_fin_sent) {
14653 				/* FIN was acked - making progress */
14654 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14655 				    !tcp->tcp_fin_acked)
14656 					tcp->tcp_ip_forward_progress = B_TRUE;
14657 				tcp->tcp_fin_acked = B_TRUE;
14658 				if (tcp->tcp_linger_tid != 0 &&
14659 				    TCP_TIMER_CANCEL(tcp,
14660 				    tcp->tcp_linger_tid) >= 0) {
14661 					tcp_stop_lingering(tcp);
14662 					freemsg(mp);
14663 					mp = NULL;
14664 				}
14665 			} else {
14666 				/*
14667 				 * We should never get here because
14668 				 * we have already checked that the
14669 				 * number of bytes ack'ed should be
14670 				 * smaller than or equal to what we
14671 				 * have sent so far (it is the
14672 				 * acceptability check of the ACK).
14673 				 * We can only get here if the send
14674 				 * queue is corrupted.
14675 				 *
14676 				 * Terminate the connection and
14677 				 * panic the system.  It is better
14678 				 * for us to panic instead of
14679 				 * continuing to avoid other disaster.
14680 				 */
14681 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14682 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14683 				panic("Memory corruption "
14684 				    "detected for connection %s.",
14685 				    tcp_display(tcp, NULL,
14686 				    DISP_ADDR_AND_PORT));
14687 				/*NOTREACHED*/
14688 			}
14689 			goto pre_swnd_update;
14690 		}
14691 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14692 	}
14693 	if (tcp->tcp_unsent) {
14694 		flags |= TH_XMIT_NEEDED;
14695 	}
14696 pre_swnd_update:
14697 	tcp->tcp_xmit_head = mp1;
14698 swnd_update:
14699 	/*
14700 	 * The following check is different from most other implementations.
14701 	 * For bi-directional transfer, when segments are dropped, the
14702 	 * "normal" check will not accept a window update in those
14703 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14704 	 * segments which are outside receiver's window.  As TCP accepts
14705 	 * the ack in those retransmitted segments, if the window update in
14706 	 * the same segment is not accepted, TCP will incorrectly calculates
14707 	 * that it can send more segments.  This can create a deadlock
14708 	 * with the receiver if its window becomes zero.
14709 	 */
14710 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14711 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14712 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14713 		/*
14714 		 * The criteria for update is:
14715 		 *
14716 		 * 1. the segment acknowledges some data.  Or
14717 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14718 		 * 3. the segment is not old and the advertised window is
14719 		 * larger than the previous advertised window.
14720 		 */
14721 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14722 			flags |= TH_XMIT_NEEDED;
14723 		tcp->tcp_swnd = new_swnd;
14724 		if (new_swnd > tcp->tcp_max_swnd)
14725 			tcp->tcp_max_swnd = new_swnd;
14726 		tcp->tcp_swl1 = seg_seq;
14727 		tcp->tcp_swl2 = seg_ack;
14728 	}
14729 est:
14730 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14731 
14732 		switch (tcp->tcp_state) {
14733 		case TCPS_FIN_WAIT_1:
14734 			if (tcp->tcp_fin_acked) {
14735 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14736 				/*
14737 				 * We implement the non-standard BSD/SunOS
14738 				 * FIN_WAIT_2 flushing algorithm.
14739 				 * If there is no user attached to this
14740 				 * TCP endpoint, then this TCP struct
14741 				 * could hang around forever in FIN_WAIT_2
14742 				 * state if the peer forgets to send us
14743 				 * a FIN.  To prevent this, we wait only
14744 				 * 2*MSL (a convenient time value) for
14745 				 * the FIN to arrive.  If it doesn't show up,
14746 				 * we flush the TCP endpoint.  This algorithm,
14747 				 * though a violation of RFC-793, has worked
14748 				 * for over 10 years in BSD systems.
14749 				 * Note: SunOS 4.x waits 675 seconds before
14750 				 * flushing the FIN_WAIT_2 connection.
14751 				 */
14752 				TCP_TIMER_RESTART(tcp,
14753 				    tcps->tcps_fin_wait_2_flush_interval);
14754 			}
14755 			break;
14756 		case TCPS_FIN_WAIT_2:
14757 			break;	/* Shutdown hook? */
14758 		case TCPS_LAST_ACK:
14759 			freemsg(mp);
14760 			if (tcp->tcp_fin_acked) {
14761 				(void) tcp_clean_death(tcp, 0, 19);
14762 				return;
14763 			}
14764 			goto xmit_check;
14765 		case TCPS_CLOSING:
14766 			if (tcp->tcp_fin_acked) {
14767 				tcp->tcp_state = TCPS_TIME_WAIT;
14768 				/*
14769 				 * Unconditionally clear the exclusive binding
14770 				 * bit so this TIME-WAIT connection won't
14771 				 * interfere with new ones.
14772 				 */
14773 				tcp->tcp_exclbind = 0;
14774 				if (!TCP_IS_DETACHED(tcp)) {
14775 					TCP_TIMER_RESTART(tcp,
14776 					    tcps->tcps_time_wait_interval);
14777 				} else {
14778 					tcp_time_wait_append(tcp);
14779 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14780 				}
14781 			}
14782 			/*FALLTHRU*/
14783 		case TCPS_CLOSE_WAIT:
14784 			freemsg(mp);
14785 			goto xmit_check;
14786 		default:
14787 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14788 			break;
14789 		}
14790 	}
14791 	if (flags & TH_FIN) {
14792 		/* Make sure we ack the fin */
14793 		flags |= TH_ACK_NEEDED;
14794 		if (!tcp->tcp_fin_rcvd) {
14795 			tcp->tcp_fin_rcvd = B_TRUE;
14796 			tcp->tcp_rnxt++;
14797 			tcph = tcp->tcp_tcph;
14798 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14799 
14800 			/*
14801 			 * Generate the ordrel_ind at the end unless we
14802 			 * are an eager guy.
14803 			 * In the eager case tcp_rsrv will do this when run
14804 			 * after tcp_accept is done.
14805 			 */
14806 			if (tcp->tcp_listener == NULL &&
14807 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14808 				flags |= TH_ORDREL_NEEDED;
14809 			switch (tcp->tcp_state) {
14810 			case TCPS_SYN_RCVD:
14811 			case TCPS_ESTABLISHED:
14812 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14813 				/* Keepalive? */
14814 				break;
14815 			case TCPS_FIN_WAIT_1:
14816 				if (!tcp->tcp_fin_acked) {
14817 					tcp->tcp_state = TCPS_CLOSING;
14818 					break;
14819 				}
14820 				/* FALLTHRU */
14821 			case TCPS_FIN_WAIT_2:
14822 				tcp->tcp_state = TCPS_TIME_WAIT;
14823 				/*
14824 				 * Unconditionally clear the exclusive binding
14825 				 * bit so this TIME-WAIT connection won't
14826 				 * interfere with new ones.
14827 				 */
14828 				tcp->tcp_exclbind = 0;
14829 				if (!TCP_IS_DETACHED(tcp)) {
14830 					TCP_TIMER_RESTART(tcp,
14831 					    tcps->tcps_time_wait_interval);
14832 				} else {
14833 					tcp_time_wait_append(tcp);
14834 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14835 				}
14836 				if (seg_len) {
14837 					/*
14838 					 * implies data piggybacked on FIN.
14839 					 * break to handle data.
14840 					 */
14841 					break;
14842 				}
14843 				freemsg(mp);
14844 				goto ack_check;
14845 			}
14846 		}
14847 	}
14848 	if (mp == NULL)
14849 		goto xmit_check;
14850 	if (seg_len == 0) {
14851 		freemsg(mp);
14852 		goto xmit_check;
14853 	}
14854 	if (mp->b_rptr == mp->b_wptr) {
14855 		/*
14856 		 * The header has been consumed, so we remove the
14857 		 * zero-length mblk here.
14858 		 */
14859 		mp1 = mp;
14860 		mp = mp->b_cont;
14861 		freeb(mp1);
14862 	}
14863 	tcph = tcp->tcp_tcph;
14864 	tcp->tcp_rack_cnt++;
14865 	{
14866 		uint32_t cur_max;
14867 
14868 		cur_max = tcp->tcp_rack_cur_max;
14869 		if (tcp->tcp_rack_cnt >= cur_max) {
14870 			/*
14871 			 * We have more unacked data than we should - send
14872 			 * an ACK now.
14873 			 */
14874 			flags |= TH_ACK_NEEDED;
14875 			cur_max++;
14876 			if (cur_max > tcp->tcp_rack_abs_max)
14877 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14878 			else
14879 				tcp->tcp_rack_cur_max = cur_max;
14880 		} else if (TCP_IS_DETACHED(tcp)) {
14881 			/* We don't have an ACK timer for detached TCP. */
14882 			flags |= TH_ACK_NEEDED;
14883 		} else if (seg_len < mss) {
14884 			/*
14885 			 * If we get a segment that is less than an mss, and we
14886 			 * already have unacknowledged data, and the amount
14887 			 * unacknowledged is not a multiple of mss, then we
14888 			 * better generate an ACK now.  Otherwise, this may be
14889 			 * the tail piece of a transaction, and we would rather
14890 			 * wait for the response.
14891 			 */
14892 			uint32_t udif;
14893 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14894 			    (uintptr_t)INT_MAX);
14895 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14896 			if (udif && (udif % mss))
14897 				flags |= TH_ACK_NEEDED;
14898 			else
14899 				flags |= TH_ACK_TIMER_NEEDED;
14900 		} else {
14901 			/* Start delayed ack timer */
14902 			flags |= TH_ACK_TIMER_NEEDED;
14903 		}
14904 	}
14905 	tcp->tcp_rnxt += seg_len;
14906 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14907 
14908 	/* Update SACK list */
14909 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14910 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14911 		    &(tcp->tcp_num_sack_blk));
14912 	}
14913 
14914 	if (tcp->tcp_urp_mp) {
14915 		tcp->tcp_urp_mp->b_cont = mp;
14916 		mp = tcp->tcp_urp_mp;
14917 		tcp->tcp_urp_mp = NULL;
14918 		/* Ready for a new signal. */
14919 		tcp->tcp_urp_last_valid = B_FALSE;
14920 #ifdef DEBUG
14921 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14922 		    "tcp_rput: sending exdata_ind %s",
14923 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14924 #endif /* DEBUG */
14925 	}
14926 
14927 	/*
14928 	 * Check for ancillary data changes compared to last segment.
14929 	 */
14930 	if (tcp->tcp_ipv6_recvancillary != 0) {
14931 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14932 		if (mp == NULL)
14933 			return;
14934 	}
14935 
14936 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14937 		/*
14938 		 * Side queue inbound data until the accept happens.
14939 		 * tcp_accept/tcp_rput drains this when the accept happens.
14940 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14941 		 * T_EXDATA_IND) it is queued on b_next.
14942 		 * XXX Make urgent data use this. Requires:
14943 		 *	Removing tcp_listener check for TH_URG
14944 		 *	Making M_PCPROTO and MARK messages skip the eager case
14945 		 */
14946 
14947 		if (tcp->tcp_kssl_pending) {
14948 			tcp_kssl_input(tcp, mp);
14949 		} else {
14950 			tcp_rcv_enqueue(tcp, mp, seg_len);
14951 		}
14952 	} else {
14953 		if (mp->b_datap->db_type != M_DATA ||
14954 		    (flags & TH_MARKNEXT_NEEDED)) {
14955 			if (tcp->tcp_rcv_list != NULL) {
14956 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14957 			}
14958 			ASSERT(tcp->tcp_rcv_list == NULL ||
14959 			    tcp->tcp_fused_sigurg);
14960 			if (flags & TH_MARKNEXT_NEEDED) {
14961 #ifdef DEBUG
14962 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14963 				    "tcp_rput: sending MSGMARKNEXT %s",
14964 				    tcp_display(tcp, NULL,
14965 				    DISP_PORT_ONLY));
14966 #endif /* DEBUG */
14967 				mp->b_flag |= MSGMARKNEXT;
14968 				flags &= ~TH_MARKNEXT_NEEDED;
14969 			}
14970 
14971 			/* Does this need SSL processing first? */
14972 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14973 			    (DB_TYPE(mp) == M_DATA)) {
14974 				tcp_kssl_input(tcp, mp);
14975 			} else {
14976 				putnext(tcp->tcp_rq, mp);
14977 				if (!canputnext(tcp->tcp_rq))
14978 					tcp->tcp_rwnd -= seg_len;
14979 			}
14980 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14981 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14982 			if (tcp->tcp_rcv_list != NULL) {
14983 				/*
14984 				 * Enqueue the new segment first and then
14985 				 * call tcp_rcv_drain() to send all data
14986 				 * up.  The other way to do this is to
14987 				 * send all queued data up and then call
14988 				 * putnext() to send the new segment up.
14989 				 * This way can remove the else part later
14990 				 * on.
14991 				 *
14992 				 * We don't this to avoid one more call to
14993 				 * canputnext() as tcp_rcv_drain() needs to
14994 				 * call canputnext().
14995 				 */
14996 				tcp_rcv_enqueue(tcp, mp, seg_len);
14997 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14998 			} else {
14999 				/* Does this need SSL processing first? */
15000 				if ((tcp->tcp_kssl_ctx  != NULL) &&
15001 				    (DB_TYPE(mp) == M_DATA)) {
15002 					tcp_kssl_input(tcp, mp);
15003 				} else {
15004 					putnext(tcp->tcp_rq, mp);
15005 					if (!canputnext(tcp->tcp_rq))
15006 						tcp->tcp_rwnd -= seg_len;
15007 				}
15008 			}
15009 		} else {
15010 			/*
15011 			 * Enqueue all packets when processing an mblk
15012 			 * from the co queue and also enqueue normal packets.
15013 			 * For packets which belong to SSL stream do SSL
15014 			 * processing first.
15015 			 */
15016 			if ((tcp->tcp_kssl_ctx != NULL) &&
15017 			    (DB_TYPE(mp) == M_DATA)) {
15018 				tcp_kssl_input(tcp, mp);
15019 			} else {
15020 				tcp_rcv_enqueue(tcp, mp, seg_len);
15021 			}
15022 		}
15023 		/*
15024 		 * Make sure the timer is running if we have data waiting
15025 		 * for a push bit. This provides resiliency against
15026 		 * implementations that do not correctly generate push bits.
15027 		 */
15028 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15029 			/*
15030 			 * The connection may be closed at this point, so don't
15031 			 * do anything for a detached tcp.
15032 			 */
15033 			if (!TCP_IS_DETACHED(tcp))
15034 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15035 				    tcp_push_timer,
15036 				    MSEC_TO_TICK(
15037 				    tcps->tcps_push_timer_interval));
15038 		}
15039 	}
15040 xmit_check:
15041 	/* Is there anything left to do? */
15042 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15043 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15044 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15045 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15046 		goto done;
15047 
15048 	/* Any transmit work to do and a non-zero window? */
15049 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15050 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15051 		if (flags & TH_REXMIT_NEEDED) {
15052 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15053 
15054 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15055 			if (snd_size > mss)
15056 				snd_size = mss;
15057 			if (snd_size > tcp->tcp_swnd)
15058 				snd_size = tcp->tcp_swnd;
15059 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15060 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15061 			    B_TRUE);
15062 
15063 			if (mp1 != NULL) {
15064 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15065 				tcp->tcp_csuna = tcp->tcp_snxt;
15066 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15067 				UPDATE_MIB(&tcps->tcps_mib,
15068 				    tcpRetransBytes, snd_size);
15069 				TCP_RECORD_TRACE(tcp, mp1,
15070 				    TCP_TRACE_SEND_PKT);
15071 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15072 			}
15073 		}
15074 		if (flags & TH_NEED_SACK_REXMIT) {
15075 			tcp_sack_rxmit(tcp, &flags);
15076 		}
15077 		/*
15078 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15079 		 * out new segment.  Note that tcp_rexmit should not be
15080 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15081 		 */
15082 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15083 			if (!tcp->tcp_rexmit) {
15084 				tcp_wput_data(tcp, NULL, B_FALSE);
15085 			} else {
15086 				tcp_ss_rexmit(tcp);
15087 			}
15088 		}
15089 		/*
15090 		 * Adjust tcp_cwnd back to normal value after sending
15091 		 * new data segments.
15092 		 */
15093 		if (flags & TH_LIMIT_XMIT) {
15094 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15095 			/*
15096 			 * This will restart the timer.  Restarting the
15097 			 * timer is used to avoid a timeout before the
15098 			 * limited transmitted segment's ACK gets back.
15099 			 */
15100 			if (tcp->tcp_xmit_head != NULL)
15101 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15102 		}
15103 
15104 		/* Anything more to do? */
15105 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15106 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15107 			goto done;
15108 	}
15109 ack_check:
15110 	if (flags & TH_SEND_URP_MARK) {
15111 		ASSERT(tcp->tcp_urp_mark_mp);
15112 		/*
15113 		 * Send up any queued data and then send the mark message
15114 		 */
15115 		if (tcp->tcp_rcv_list != NULL) {
15116 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15117 		}
15118 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15119 
15120 		mp1 = tcp->tcp_urp_mark_mp;
15121 		tcp->tcp_urp_mark_mp = NULL;
15122 #ifdef DEBUG
15123 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15124 		    "tcp_rput: sending zero-length %s %s",
15125 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15126 		    "MSGNOTMARKNEXT"),
15127 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15128 #endif /* DEBUG */
15129 		putnext(tcp->tcp_rq, mp1);
15130 		flags &= ~TH_SEND_URP_MARK;
15131 	}
15132 	if (flags & TH_ACK_NEEDED) {
15133 		/*
15134 		 * Time to send an ack for some reason.
15135 		 */
15136 		mp1 = tcp_ack_mp(tcp);
15137 
15138 		if (mp1 != NULL) {
15139 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15140 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15141 			BUMP_LOCAL(tcp->tcp_obsegs);
15142 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15143 		}
15144 		if (tcp->tcp_ack_tid != 0) {
15145 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15146 			tcp->tcp_ack_tid = 0;
15147 		}
15148 	}
15149 	if (flags & TH_ACK_TIMER_NEEDED) {
15150 		/*
15151 		 * Arrange for deferred ACK or push wait timeout.
15152 		 * Start timer if it is not already running.
15153 		 */
15154 		if (tcp->tcp_ack_tid == 0) {
15155 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15156 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15157 			    (clock_t)tcps->tcps_local_dack_interval :
15158 			    (clock_t)tcps->tcps_deferred_ack_interval));
15159 		}
15160 	}
15161 	if (flags & TH_ORDREL_NEEDED) {
15162 		/*
15163 		 * Send up the ordrel_ind unless we are an eager guy.
15164 		 * In the eager case tcp_rsrv will do this when run
15165 		 * after tcp_accept is done.
15166 		 */
15167 		ASSERT(tcp->tcp_listener == NULL);
15168 		if (tcp->tcp_rcv_list != NULL) {
15169 			/*
15170 			 * Push any mblk(s) enqueued from co processing.
15171 			 */
15172 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15173 		}
15174 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15175 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15176 			tcp->tcp_ordrel_done = B_TRUE;
15177 			putnext(tcp->tcp_rq, mp1);
15178 			if (tcp->tcp_deferred_clean_death) {
15179 				/*
15180 				 * tcp_clean_death was deferred
15181 				 * for T_ORDREL_IND - do it now
15182 				 */
15183 				(void) tcp_clean_death(tcp,
15184 				    tcp->tcp_client_errno, 20);
15185 				tcp->tcp_deferred_clean_death =	B_FALSE;
15186 			}
15187 		} else {
15188 			/*
15189 			 * Run the orderly release in the
15190 			 * service routine.
15191 			 */
15192 			qenable(tcp->tcp_rq);
15193 			/*
15194 			 * Caveat(XXX): The machine may be so
15195 			 * overloaded that tcp_rsrv() is not scheduled
15196 			 * until after the endpoint has transitioned
15197 			 * to TCPS_TIME_WAIT
15198 			 * and tcp_time_wait_interval expires. Then
15199 			 * tcp_timer() will blow away state in tcp_t
15200 			 * and T_ORDREL_IND will never be delivered
15201 			 * upstream. Unlikely but potentially
15202 			 * a problem.
15203 			 */
15204 		}
15205 	}
15206 done:
15207 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15208 }
15209 
15210 /*
15211  * This function does PAWS protection check. Returns B_TRUE if the
15212  * segment passes the PAWS test, else returns B_FALSE.
15213  */
15214 boolean_t
15215 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15216 {
15217 	uint8_t	flags;
15218 	int	options;
15219 	uint8_t *up;
15220 
15221 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15222 	/*
15223 	 * If timestamp option is aligned nicely, get values inline,
15224 	 * otherwise call general routine to parse.  Only do that
15225 	 * if timestamp is the only option.
15226 	 */
15227 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15228 	    TCPOPT_REAL_TS_LEN &&
15229 	    OK_32PTR((up = ((uint8_t *)tcph) +
15230 	    TCP_MIN_HEADER_LENGTH)) &&
15231 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15232 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15233 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15234 
15235 		options = TCP_OPT_TSTAMP_PRESENT;
15236 	} else {
15237 		if (tcp->tcp_snd_sack_ok) {
15238 			tcpoptp->tcp = tcp;
15239 		} else {
15240 			tcpoptp->tcp = NULL;
15241 		}
15242 		options = tcp_parse_options(tcph, tcpoptp);
15243 	}
15244 
15245 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15246 		/*
15247 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15248 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15249 		 */
15250 		if ((flags & TH_RST) == 0 &&
15251 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15252 		    tcp->tcp_ts_recent)) {
15253 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15254 			    PAWS_TIMEOUT)) {
15255 				/* This segment is not acceptable. */
15256 				return (B_FALSE);
15257 			} else {
15258 				/*
15259 				 * Connection has been idle for
15260 				 * too long.  Reset the timestamp
15261 				 * and assume the segment is valid.
15262 				 */
15263 				tcp->tcp_ts_recent =
15264 				    tcpoptp->tcp_opt_ts_val;
15265 			}
15266 		}
15267 	} else {
15268 		/*
15269 		 * If we don't get a timestamp on every packet, we
15270 		 * figure we can't really trust 'em, so we stop sending
15271 		 * and parsing them.
15272 		 */
15273 		tcp->tcp_snd_ts_ok = B_FALSE;
15274 
15275 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15276 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15277 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15278 		/*
15279 		 * Adjust the tcp_mss accordingly. We also need to
15280 		 * adjust tcp_cwnd here in accordance with the new mss.
15281 		 * But we avoid doing a slow start here so as to not
15282 		 * to lose on the transfer rate built up so far.
15283 		 */
15284 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15285 		if (tcp->tcp_snd_sack_ok) {
15286 			ASSERT(tcp->tcp_sack_info != NULL);
15287 			tcp->tcp_max_sack_blk = 4;
15288 		}
15289 	}
15290 	return (B_TRUE);
15291 }
15292 
15293 /*
15294  * Attach ancillary data to a received TCP segments for the
15295  * ancillary pieces requested by the application that are
15296  * different than they were in the previous data segment.
15297  *
15298  * Save the "current" values once memory allocation is ok so that
15299  * when memory allocation fails we can just wait for the next data segment.
15300  */
15301 static mblk_t *
15302 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15303 {
15304 	struct T_optdata_ind *todi;
15305 	int optlen;
15306 	uchar_t *optptr;
15307 	struct T_opthdr *toh;
15308 	uint_t addflag;	/* Which pieces to add */
15309 	mblk_t *mp1;
15310 
15311 	optlen = 0;
15312 	addflag = 0;
15313 	/* If app asked for pktinfo and the index has changed ... */
15314 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15315 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15316 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15317 		optlen += sizeof (struct T_opthdr) +
15318 		    sizeof (struct in6_pktinfo);
15319 		addflag |= TCP_IPV6_RECVPKTINFO;
15320 	}
15321 	/* If app asked for hoplimit and it has changed ... */
15322 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15323 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15324 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15325 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15326 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15327 	}
15328 	/* If app asked for tclass and it has changed ... */
15329 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15330 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15331 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15332 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15333 		addflag |= TCP_IPV6_RECVTCLASS;
15334 	}
15335 	/*
15336 	 * If app asked for hopbyhop headers and it has changed ...
15337 	 * For security labels, note that (1) security labels can't change on
15338 	 * a connected socket at all, (2) we're connected to at most one peer,
15339 	 * (3) if anything changes, then it must be some other extra option.
15340 	 */
15341 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15342 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15343 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15344 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15345 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15346 		    tcp->tcp_label_len;
15347 		addflag |= TCP_IPV6_RECVHOPOPTS;
15348 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15349 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15350 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15351 			return (mp);
15352 	}
15353 	/* If app asked for dst headers before routing headers ... */
15354 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15355 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15356 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15357 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15358 		optlen += sizeof (struct T_opthdr) +
15359 		    ipp->ipp_rtdstoptslen;
15360 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15361 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15362 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15363 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15364 			return (mp);
15365 	}
15366 	/* If app asked for routing headers and it has changed ... */
15367 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15368 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15369 	    (ipp->ipp_fields & IPPF_RTHDR),
15370 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15371 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15372 		addflag |= TCP_IPV6_RECVRTHDR;
15373 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15374 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15375 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15376 			return (mp);
15377 	}
15378 	/* If app asked for dest headers and it has changed ... */
15379 	if ((tcp->tcp_ipv6_recvancillary &
15380 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15381 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15382 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15383 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15384 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15385 		addflag |= TCP_IPV6_RECVDSTOPTS;
15386 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15387 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15388 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15389 			return (mp);
15390 	}
15391 
15392 	if (optlen == 0) {
15393 		/* Nothing to add */
15394 		return (mp);
15395 	}
15396 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15397 	if (mp1 == NULL) {
15398 		/*
15399 		 * Defer sending ancillary data until the next TCP segment
15400 		 * arrives.
15401 		 */
15402 		return (mp);
15403 	}
15404 	mp1->b_cont = mp;
15405 	mp = mp1;
15406 	mp->b_wptr += sizeof (*todi) + optlen;
15407 	mp->b_datap->db_type = M_PROTO;
15408 	todi = (struct T_optdata_ind *)mp->b_rptr;
15409 	todi->PRIM_type = T_OPTDATA_IND;
15410 	todi->DATA_flag = 1;	/* MORE data */
15411 	todi->OPT_length = optlen;
15412 	todi->OPT_offset = sizeof (*todi);
15413 	optptr = (uchar_t *)&todi[1];
15414 	/*
15415 	 * If app asked for pktinfo and the index has changed ...
15416 	 * Note that the local address never changes for the connection.
15417 	 */
15418 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15419 		struct in6_pktinfo *pkti;
15420 
15421 		toh = (struct T_opthdr *)optptr;
15422 		toh->level = IPPROTO_IPV6;
15423 		toh->name = IPV6_PKTINFO;
15424 		toh->len = sizeof (*toh) + sizeof (*pkti);
15425 		toh->status = 0;
15426 		optptr += sizeof (*toh);
15427 		pkti = (struct in6_pktinfo *)optptr;
15428 		if (tcp->tcp_ipversion == IPV6_VERSION)
15429 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15430 		else
15431 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15432 			    &pkti->ipi6_addr);
15433 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15434 		optptr += sizeof (*pkti);
15435 		ASSERT(OK_32PTR(optptr));
15436 		/* Save as "last" value */
15437 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15438 	}
15439 	/* If app asked for hoplimit and it has changed ... */
15440 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15441 		toh = (struct T_opthdr *)optptr;
15442 		toh->level = IPPROTO_IPV6;
15443 		toh->name = IPV6_HOPLIMIT;
15444 		toh->len = sizeof (*toh) + sizeof (uint_t);
15445 		toh->status = 0;
15446 		optptr += sizeof (*toh);
15447 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15448 		optptr += sizeof (uint_t);
15449 		ASSERT(OK_32PTR(optptr));
15450 		/* Save as "last" value */
15451 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15452 	}
15453 	/* If app asked for tclass and it has changed ... */
15454 	if (addflag & TCP_IPV6_RECVTCLASS) {
15455 		toh = (struct T_opthdr *)optptr;
15456 		toh->level = IPPROTO_IPV6;
15457 		toh->name = IPV6_TCLASS;
15458 		toh->len = sizeof (*toh) + sizeof (uint_t);
15459 		toh->status = 0;
15460 		optptr += sizeof (*toh);
15461 		*(uint_t *)optptr = ipp->ipp_tclass;
15462 		optptr += sizeof (uint_t);
15463 		ASSERT(OK_32PTR(optptr));
15464 		/* Save as "last" value */
15465 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15466 	}
15467 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15468 		toh = (struct T_opthdr *)optptr;
15469 		toh->level = IPPROTO_IPV6;
15470 		toh->name = IPV6_HOPOPTS;
15471 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15472 		    tcp->tcp_label_len;
15473 		toh->status = 0;
15474 		optptr += sizeof (*toh);
15475 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15476 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15477 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15478 		ASSERT(OK_32PTR(optptr));
15479 		/* Save as last value */
15480 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15481 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15482 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15483 	}
15484 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15485 		toh = (struct T_opthdr *)optptr;
15486 		toh->level = IPPROTO_IPV6;
15487 		toh->name = IPV6_RTHDRDSTOPTS;
15488 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15489 		toh->status = 0;
15490 		optptr += sizeof (*toh);
15491 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15492 		optptr += ipp->ipp_rtdstoptslen;
15493 		ASSERT(OK_32PTR(optptr));
15494 		/* Save as last value */
15495 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15496 		    &tcp->tcp_rtdstoptslen,
15497 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15498 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15499 	}
15500 	if (addflag & TCP_IPV6_RECVRTHDR) {
15501 		toh = (struct T_opthdr *)optptr;
15502 		toh->level = IPPROTO_IPV6;
15503 		toh->name = IPV6_RTHDR;
15504 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15505 		toh->status = 0;
15506 		optptr += sizeof (*toh);
15507 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15508 		optptr += ipp->ipp_rthdrlen;
15509 		ASSERT(OK_32PTR(optptr));
15510 		/* Save as last value */
15511 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15512 		    (ipp->ipp_fields & IPPF_RTHDR),
15513 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15514 	}
15515 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15516 		toh = (struct T_opthdr *)optptr;
15517 		toh->level = IPPROTO_IPV6;
15518 		toh->name = IPV6_DSTOPTS;
15519 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15520 		toh->status = 0;
15521 		optptr += sizeof (*toh);
15522 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15523 		optptr += ipp->ipp_dstoptslen;
15524 		ASSERT(OK_32PTR(optptr));
15525 		/* Save as last value */
15526 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15527 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15528 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15529 	}
15530 	ASSERT(optptr == mp->b_wptr);
15531 	return (mp);
15532 }
15533 
15534 
15535 /*
15536  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15537  * or a "bad" IRE detected by tcp_adapt_ire.
15538  * We can't tell if the failure was due to the laddr or the faddr
15539  * thus we clear out all addresses and ports.
15540  */
15541 static void
15542 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15543 {
15544 	queue_t	*q = tcp->tcp_rq;
15545 	tcph_t	*tcph;
15546 	struct T_error_ack *tea;
15547 	conn_t	*connp = tcp->tcp_connp;
15548 
15549 
15550 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15551 
15552 	if (mp->b_cont) {
15553 		freemsg(mp->b_cont);
15554 		mp->b_cont = NULL;
15555 	}
15556 	tea = (struct T_error_ack *)mp->b_rptr;
15557 	switch (tea->PRIM_type) {
15558 	case T_BIND_ACK:
15559 		/*
15560 		 * Need to unbind with classifier since we were just told that
15561 		 * our bind succeeded.
15562 		 */
15563 		tcp->tcp_hard_bound = B_FALSE;
15564 		tcp->tcp_hard_binding = B_FALSE;
15565 
15566 		ipcl_hash_remove(connp);
15567 		/* Reuse the mblk if possible */
15568 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15569 		    sizeof (*tea));
15570 		mp->b_rptr = mp->b_datap->db_base;
15571 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15572 		tea = (struct T_error_ack *)mp->b_rptr;
15573 		tea->PRIM_type = T_ERROR_ACK;
15574 		tea->TLI_error = TSYSERR;
15575 		tea->UNIX_error = error;
15576 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15577 			tea->ERROR_prim = T_CONN_REQ;
15578 		} else {
15579 			tea->ERROR_prim = O_T_BIND_REQ;
15580 		}
15581 		break;
15582 
15583 	case T_ERROR_ACK:
15584 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15585 			tea->ERROR_prim = T_CONN_REQ;
15586 		break;
15587 	default:
15588 		panic("tcp_bind_failed: unexpected TPI type");
15589 		/*NOTREACHED*/
15590 	}
15591 
15592 	tcp->tcp_state = TCPS_IDLE;
15593 	if (tcp->tcp_ipversion == IPV4_VERSION)
15594 		tcp->tcp_ipha->ipha_src = 0;
15595 	else
15596 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15597 	/*
15598 	 * Copy of the src addr. in tcp_t is needed since
15599 	 * the lookup funcs. can only look at tcp_t
15600 	 */
15601 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15602 
15603 	tcph = tcp->tcp_tcph;
15604 	tcph->th_lport[0] = 0;
15605 	tcph->th_lport[1] = 0;
15606 	tcp_bind_hash_remove(tcp);
15607 	bzero(&connp->u_port, sizeof (connp->u_port));
15608 	/* blow away saved option results if any */
15609 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15610 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15611 
15612 	conn_delete_ire(tcp->tcp_connp, NULL);
15613 	putnext(q, mp);
15614 }
15615 
15616 /*
15617  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15618  * messages.
15619  */
15620 void
15621 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15622 {
15623 	mblk_t	*mp1;
15624 	uchar_t	*rptr = mp->b_rptr;
15625 	queue_t	*q = tcp->tcp_rq;
15626 	struct T_error_ack *tea;
15627 	uint32_t mss;
15628 	mblk_t *syn_mp;
15629 	mblk_t *mdti;
15630 	mblk_t *lsoi;
15631 	int	retval;
15632 	mblk_t *ire_mp;
15633 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15634 
15635 	switch (mp->b_datap->db_type) {
15636 	case M_PROTO:
15637 	case M_PCPROTO:
15638 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15639 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15640 			break;
15641 		tea = (struct T_error_ack *)rptr;
15642 		switch (tea->PRIM_type) {
15643 		case T_BIND_ACK:
15644 			/*
15645 			 * Adapt Multidata information, if any.  The
15646 			 * following tcp_mdt_update routine will free
15647 			 * the message.
15648 			 */
15649 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15650 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15651 				    b_rptr)->mdt_capab, B_TRUE);
15652 				freemsg(mdti);
15653 			}
15654 
15655 			/*
15656 			 * Check to update LSO information with tcp, and
15657 			 * tcp_lso_update routine will free the message.
15658 			 */
15659 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15660 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15661 				    b_rptr)->lso_capab);
15662 				freemsg(lsoi);
15663 			}
15664 
15665 			/* Get the IRE, if we had requested for it */
15666 			ire_mp = tcp_ire_mp(mp);
15667 
15668 			if (tcp->tcp_hard_binding) {
15669 				tcp->tcp_hard_binding = B_FALSE;
15670 				tcp->tcp_hard_bound = B_TRUE;
15671 				CL_INET_CONNECT(tcp);
15672 			} else {
15673 				if (ire_mp != NULL)
15674 					freeb(ire_mp);
15675 				goto after_syn_sent;
15676 			}
15677 
15678 			retval = tcp_adapt_ire(tcp, ire_mp);
15679 			if (ire_mp != NULL)
15680 				freeb(ire_mp);
15681 			if (retval == 0) {
15682 				tcp_bind_failed(tcp, mp,
15683 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15684 				    ENETUNREACH : EADDRNOTAVAIL));
15685 				return;
15686 			}
15687 			/*
15688 			 * Don't let an endpoint connect to itself.
15689 			 * Also checked in tcp_connect() but that
15690 			 * check can't handle the case when the
15691 			 * local IP address is INADDR_ANY.
15692 			 */
15693 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15694 				if ((tcp->tcp_ipha->ipha_dst ==
15695 				    tcp->tcp_ipha->ipha_src) &&
15696 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15697 				    tcp->tcp_tcph->th_fport))) {
15698 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15699 					return;
15700 				}
15701 			} else {
15702 				if (IN6_ARE_ADDR_EQUAL(
15703 				    &tcp->tcp_ip6h->ip6_dst,
15704 				    &tcp->tcp_ip6h->ip6_src) &&
15705 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15706 				    tcp->tcp_tcph->th_fport))) {
15707 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15708 					return;
15709 				}
15710 			}
15711 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15712 			/*
15713 			 * This should not be possible!  Just for
15714 			 * defensive coding...
15715 			 */
15716 			if (tcp->tcp_state != TCPS_SYN_SENT)
15717 				goto after_syn_sent;
15718 
15719 			if (is_system_labeled() &&
15720 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15721 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15722 				return;
15723 			}
15724 
15725 			ASSERT(q == tcp->tcp_rq);
15726 			/*
15727 			 * tcp_adapt_ire() does not adjust
15728 			 * for TCP/IP header length.
15729 			 */
15730 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15731 
15732 			/*
15733 			 * Just make sure our rwnd is at
15734 			 * least tcp_recv_hiwat_mss * MSS
15735 			 * large, and round up to the nearest
15736 			 * MSS.
15737 			 *
15738 			 * We do the round up here because
15739 			 * we need to get the interface
15740 			 * MTU first before we can do the
15741 			 * round up.
15742 			 */
15743 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15744 			    tcps->tcps_recv_hiwat_minmss * mss);
15745 			q->q_hiwat = tcp->tcp_rwnd;
15746 			tcp_set_ws_value(tcp);
15747 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15748 			    tcp->tcp_tcph->th_win);
15749 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
15750 				tcp->tcp_snd_ws_ok = B_TRUE;
15751 
15752 			/*
15753 			 * Set tcp_snd_ts_ok to true
15754 			 * so that tcp_xmit_mp will
15755 			 * include the timestamp
15756 			 * option in the SYN segment.
15757 			 */
15758 			if (tcps->tcps_tstamp_always ||
15759 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
15760 				tcp->tcp_snd_ts_ok = B_TRUE;
15761 			}
15762 
15763 			/*
15764 			 * tcp_snd_sack_ok can be set in
15765 			 * tcp_adapt_ire() if the sack metric
15766 			 * is set.  So check it here also.
15767 			 */
15768 			if (tcps->tcps_sack_permitted == 2 ||
15769 			    tcp->tcp_snd_sack_ok) {
15770 				if (tcp->tcp_sack_info == NULL) {
15771 					tcp->tcp_sack_info =
15772 					    kmem_cache_alloc(
15773 					    tcp_sack_info_cache,
15774 					    KM_SLEEP);
15775 				}
15776 				tcp->tcp_snd_sack_ok = B_TRUE;
15777 			}
15778 
15779 			/*
15780 			 * Should we use ECN?  Note that the current
15781 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15782 			 * is 1.  The reason for doing this is that there
15783 			 * are equipments out there that will drop ECN
15784 			 * enabled IP packets.  Setting it to 1 avoids
15785 			 * compatibility problems.
15786 			 */
15787 			if (tcps->tcps_ecn_permitted == 2)
15788 				tcp->tcp_ecn_ok = B_TRUE;
15789 
15790 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15791 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15792 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15793 			if (syn_mp) {
15794 				cred_t *cr;
15795 				pid_t pid;
15796 
15797 				/*
15798 				 * Obtain the credential from the
15799 				 * thread calling connect(); the credential
15800 				 * lives on in the second mblk which
15801 				 * originated from T_CONN_REQ and is echoed
15802 				 * with the T_BIND_ACK from ip.  If none
15803 				 * can be found, default to the creator
15804 				 * of the socket.
15805 				 */
15806 				if (mp->b_cont == NULL ||
15807 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15808 					cr = tcp->tcp_cred;
15809 					pid = tcp->tcp_cpid;
15810 				} else {
15811 					pid = DB_CPID(mp->b_cont);
15812 				}
15813 
15814 				TCP_RECORD_TRACE(tcp, syn_mp,
15815 				    TCP_TRACE_SEND_PKT);
15816 				mblk_setcred(syn_mp, cr);
15817 				DB_CPID(syn_mp) = pid;
15818 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15819 			}
15820 		after_syn_sent:
15821 			/*
15822 			 * A trailer mblk indicates a waiting client upstream.
15823 			 * We complete here the processing begun in
15824 			 * either tcp_bind() or tcp_connect() by passing
15825 			 * upstream the reply message they supplied.
15826 			 */
15827 			mp1 = mp;
15828 			mp = mp->b_cont;
15829 			freeb(mp1);
15830 			if (mp)
15831 				break;
15832 			return;
15833 		case T_ERROR_ACK:
15834 			if (tcp->tcp_debug) {
15835 				(void) strlog(TCP_MOD_ID, 0, 1,
15836 				    SL_TRACE|SL_ERROR,
15837 				    "tcp_rput_other: case T_ERROR_ACK, "
15838 				    "ERROR_prim == %d",
15839 				    tea->ERROR_prim);
15840 			}
15841 			switch (tea->ERROR_prim) {
15842 			case O_T_BIND_REQ:
15843 			case T_BIND_REQ:
15844 				tcp_bind_failed(tcp, mp,
15845 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15846 				    ENETUNREACH : EADDRNOTAVAIL));
15847 				return;
15848 			case T_UNBIND_REQ:
15849 				tcp->tcp_hard_binding = B_FALSE;
15850 				tcp->tcp_hard_bound = B_FALSE;
15851 				if (mp->b_cont) {
15852 					freemsg(mp->b_cont);
15853 					mp->b_cont = NULL;
15854 				}
15855 				if (tcp->tcp_unbind_pending)
15856 					tcp->tcp_unbind_pending = 0;
15857 				else {
15858 					/* From tcp_ip_unbind() - free */
15859 					freemsg(mp);
15860 					return;
15861 				}
15862 				break;
15863 			case T_SVR4_OPTMGMT_REQ:
15864 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15865 					/* T_OPTMGMT_REQ generated by TCP */
15866 					printf("T_SVR4_OPTMGMT_REQ failed "
15867 					    "%d/%d - dropped (cnt %d)\n",
15868 					    tea->TLI_error, tea->UNIX_error,
15869 					    tcp->tcp_drop_opt_ack_cnt);
15870 					freemsg(mp);
15871 					tcp->tcp_drop_opt_ack_cnt--;
15872 					return;
15873 				}
15874 				break;
15875 			}
15876 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15877 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15878 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15879 				    "- dropped (cnt %d)\n",
15880 				    tea->TLI_error, tea->UNIX_error,
15881 				    tcp->tcp_drop_opt_ack_cnt);
15882 				freemsg(mp);
15883 				tcp->tcp_drop_opt_ack_cnt--;
15884 				return;
15885 			}
15886 			break;
15887 		case T_OPTMGMT_ACK:
15888 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15889 				/* T_OPTMGMT_REQ generated by TCP */
15890 				freemsg(mp);
15891 				tcp->tcp_drop_opt_ack_cnt--;
15892 				return;
15893 			}
15894 			break;
15895 		default:
15896 			break;
15897 		}
15898 		break;
15899 	case M_FLUSH:
15900 		if (*rptr & FLUSHR)
15901 			flushq(q, FLUSHDATA);
15902 		break;
15903 	default:
15904 		/* M_CTL will be directly sent to tcp_icmp_error() */
15905 		ASSERT(DB_TYPE(mp) != M_CTL);
15906 		break;
15907 	}
15908 	/*
15909 	 * Make sure we set this bit before sending the ACK for
15910 	 * bind. Otherwise accept could possibly run and free
15911 	 * this tcp struct.
15912 	 */
15913 	putnext(q, mp);
15914 }
15915 
15916 /*
15917  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15918  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15919  * tcp_rsrv() try again.
15920  */
15921 static void
15922 tcp_ordrel_kick(void *arg)
15923 {
15924 	conn_t 	*connp = (conn_t *)arg;
15925 	tcp_t	*tcp = connp->conn_tcp;
15926 
15927 	tcp->tcp_ordrelid = 0;
15928 	tcp->tcp_timeout = B_FALSE;
15929 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15930 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15931 		qenable(tcp->tcp_rq);
15932 	}
15933 }
15934 
15935 /* ARGSUSED */
15936 static void
15937 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15938 {
15939 	conn_t	*connp = (conn_t *)arg;
15940 	tcp_t	*tcp = connp->conn_tcp;
15941 	queue_t	*q = tcp->tcp_rq;
15942 	uint_t	thwin;
15943 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15944 
15945 	freeb(mp);
15946 
15947 	TCP_STAT(tcps, tcp_rsrv_calls);
15948 
15949 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15950 		return;
15951 	}
15952 
15953 	if (tcp->tcp_fused) {
15954 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15955 
15956 		ASSERT(tcp->tcp_fused);
15957 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15958 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15959 		ASSERT(!TCP_IS_DETACHED(tcp));
15960 		ASSERT(tcp->tcp_connp->conn_sqp ==
15961 		    peer_tcp->tcp_connp->conn_sqp);
15962 
15963 		/*
15964 		 * Normally we would not get backenabled in synchronous
15965 		 * streams mode, but in case this happens, we need to plug
15966 		 * synchronous streams during our drain to prevent a race
15967 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15968 		 */
15969 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15970 		if (tcp->tcp_rcv_list != NULL)
15971 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15972 
15973 		if (peer_tcp > tcp) {
15974 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15975 			mutex_enter(&tcp->tcp_non_sq_lock);
15976 		} else {
15977 			mutex_enter(&tcp->tcp_non_sq_lock);
15978 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15979 		}
15980 
15981 		if (peer_tcp->tcp_flow_stopped &&
15982 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15983 		    peer_tcp->tcp_xmit_lowater)) {
15984 			tcp_clrqfull(peer_tcp);
15985 		}
15986 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15987 		mutex_exit(&tcp->tcp_non_sq_lock);
15988 
15989 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15990 		TCP_STAT(tcps, tcp_fusion_backenabled);
15991 		return;
15992 	}
15993 
15994 	if (canputnext(q)) {
15995 		tcp->tcp_rwnd = q->q_hiwat;
15996 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15997 		    << tcp->tcp_rcv_ws;
15998 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15999 		/*
16000 		 * Send back a window update immediately if TCP is above
16001 		 * ESTABLISHED state and the increase of the rcv window
16002 		 * that the other side knows is at least 1 MSS after flow
16003 		 * control is lifted.
16004 		 */
16005 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16006 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16007 			tcp_xmit_ctl(NULL, tcp,
16008 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16009 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16010 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16011 		}
16012 	}
16013 	/* Handle a failure to allocate a T_ORDREL_IND here */
16014 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16015 		ASSERT(tcp->tcp_listener == NULL);
16016 		if (tcp->tcp_rcv_list != NULL) {
16017 			(void) tcp_rcv_drain(q, tcp);
16018 		}
16019 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
16020 		mp = mi_tpi_ordrel_ind();
16021 		if (mp) {
16022 			tcp->tcp_ordrel_done = B_TRUE;
16023 			putnext(q, mp);
16024 			if (tcp->tcp_deferred_clean_death) {
16025 				/*
16026 				 * tcp_clean_death was deferred for
16027 				 * T_ORDREL_IND - do it now
16028 				 */
16029 				tcp->tcp_deferred_clean_death = B_FALSE;
16030 				(void) tcp_clean_death(tcp,
16031 				    tcp->tcp_client_errno, 22);
16032 			}
16033 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16034 			/*
16035 			 * If there isn't already a timer running
16036 			 * start one.  Use a 4 second
16037 			 * timer as a fallback since it can't fail.
16038 			 */
16039 			tcp->tcp_timeout = B_TRUE;
16040 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16041 			    MSEC_TO_TICK(4000));
16042 		}
16043 	}
16044 }
16045 
16046 /*
16047  * The read side service routine is called mostly when we get back-enabled as a
16048  * result of flow control relief.  Since we don't actually queue anything in
16049  * TCP, we have no data to send out of here.  What we do is clear the receive
16050  * window, and send out a window update.
16051  * This routine is also called to drive an orderly release message upstream
16052  * if the attempt in tcp_rput failed.
16053  */
16054 static void
16055 tcp_rsrv(queue_t *q)
16056 {
16057 	conn_t *connp = Q_TO_CONN(q);
16058 	tcp_t	*tcp = connp->conn_tcp;
16059 	mblk_t	*mp;
16060 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16061 
16062 	/* No code does a putq on the read side */
16063 	ASSERT(q->q_first == NULL);
16064 
16065 	/* Nothing to do for the default queue */
16066 	if (q == tcps->tcps_g_q) {
16067 		return;
16068 	}
16069 
16070 	mp = allocb(0, BPRI_HI);
16071 	if (mp == NULL) {
16072 		/*
16073 		 * We are under memory pressure. Return for now and we
16074 		 * we will be called again later.
16075 		 */
16076 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16077 			/*
16078 			 * If there isn't already a timer running
16079 			 * start one.  Use a 4 second
16080 			 * timer as a fallback since it can't fail.
16081 			 */
16082 			tcp->tcp_timeout = B_TRUE;
16083 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16084 			    MSEC_TO_TICK(4000));
16085 		}
16086 		return;
16087 	}
16088 	CONN_INC_REF(connp);
16089 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16090 	    SQTAG_TCP_RSRV);
16091 }
16092 
16093 /*
16094  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16095  * We do not allow the receive window to shrink.  After setting rwnd,
16096  * set the flow control hiwat of the stream.
16097  *
16098  * This function is called in 2 cases:
16099  *
16100  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16101  *    connection (passive open) and in tcp_rput_data() for active connect.
16102  *    This is called after tcp_mss_set() when the desired MSS value is known.
16103  *    This makes sure that our window size is a mutiple of the other side's
16104  *    MSS.
16105  * 2) Handling SO_RCVBUF option.
16106  *
16107  * It is ASSUMED that the requested size is a multiple of the current MSS.
16108  *
16109  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16110  * user requests so.
16111  */
16112 static int
16113 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16114 {
16115 	uint32_t	mss = tcp->tcp_mss;
16116 	uint32_t	old_max_rwnd;
16117 	uint32_t	max_transmittable_rwnd;
16118 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16119 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16120 
16121 	if (tcp->tcp_fused) {
16122 		size_t sth_hiwat;
16123 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16124 
16125 		ASSERT(peer_tcp != NULL);
16126 		/*
16127 		 * Record the stream head's high water mark for
16128 		 * this endpoint; this is used for flow-control
16129 		 * purposes in tcp_fuse_output().
16130 		 */
16131 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16132 		if (!tcp_detached)
16133 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16134 
16135 		/*
16136 		 * In the fusion case, the maxpsz stream head value of
16137 		 * our peer is set according to its send buffer size
16138 		 * and our receive buffer size; since the latter may
16139 		 * have changed we need to update the peer's maxpsz.
16140 		 */
16141 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16142 		return (rwnd);
16143 	}
16144 
16145 	if (tcp_detached)
16146 		old_max_rwnd = tcp->tcp_rwnd;
16147 	else
16148 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16149 
16150 	/*
16151 	 * Insist on a receive window that is at least
16152 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16153 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16154 	 * and delayed acknowledgement.
16155 	 */
16156 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16157 
16158 	/*
16159 	 * If window size info has already been exchanged, TCP should not
16160 	 * shrink the window.  Shrinking window is doable if done carefully.
16161 	 * We may add that support later.  But so far there is not a real
16162 	 * need to do that.
16163 	 */
16164 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16165 		/* MSS may have changed, do a round up again. */
16166 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16167 	}
16168 
16169 	/*
16170 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16171 	 * can be applied even before the window scale option is decided.
16172 	 */
16173 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16174 	if (rwnd > max_transmittable_rwnd) {
16175 		rwnd = max_transmittable_rwnd -
16176 		    (max_transmittable_rwnd % mss);
16177 		if (rwnd < mss)
16178 			rwnd = max_transmittable_rwnd;
16179 		/*
16180 		 * If we're over the limit we may have to back down tcp_rwnd.
16181 		 * The increment below won't work for us. So we set all three
16182 		 * here and the increment below will have no effect.
16183 		 */
16184 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16185 	}
16186 	if (tcp->tcp_localnet) {
16187 		tcp->tcp_rack_abs_max =
16188 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16189 	} else {
16190 		/*
16191 		 * For a remote host on a different subnet (through a router),
16192 		 * we ack every other packet to be conforming to RFC1122.
16193 		 * tcp_deferred_acks_max is default to 2.
16194 		 */
16195 		tcp->tcp_rack_abs_max =
16196 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16197 	}
16198 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16199 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16200 	else
16201 		tcp->tcp_rack_cur_max = 0;
16202 	/*
16203 	 * Increment the current rwnd by the amount the maximum grew (we
16204 	 * can not overwrite it since we might be in the middle of a
16205 	 * connection.)
16206 	 */
16207 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16208 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16209 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16210 		tcp->tcp_cwnd_max = rwnd;
16211 
16212 	if (tcp_detached)
16213 		return (rwnd);
16214 	/*
16215 	 * We set the maximum receive window into rq->q_hiwat.
16216 	 * This is not actually used for flow control.
16217 	 */
16218 	tcp->tcp_rq->q_hiwat = rwnd;
16219 	/*
16220 	 * Set the Stream head high water mark. This doesn't have to be
16221 	 * here, since we are simply using default values, but we would
16222 	 * prefer to choose these values algorithmically, with a likely
16223 	 * relationship to rwnd.
16224 	 */
16225 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16226 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16227 	return (rwnd);
16228 }
16229 
16230 /*
16231  * Return SNMP stuff in buffer in mpdata.
16232  */
16233 mblk_t *
16234 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16235 {
16236 	mblk_t			*mpdata;
16237 	mblk_t			*mp_conn_ctl = NULL;
16238 	mblk_t			*mp_conn_tail;
16239 	mblk_t			*mp_attr_ctl = NULL;
16240 	mblk_t			*mp_attr_tail;
16241 	mblk_t			*mp6_conn_ctl = NULL;
16242 	mblk_t			*mp6_conn_tail;
16243 	mblk_t			*mp6_attr_ctl = NULL;
16244 	mblk_t			*mp6_attr_tail;
16245 	struct opthdr		*optp;
16246 	mib2_tcpConnEntry_t	tce;
16247 	mib2_tcp6ConnEntry_t	tce6;
16248 	mib2_transportMLPEntry_t mlp;
16249 	connf_t			*connfp;
16250 	int			i;
16251 	boolean_t 		ispriv;
16252 	zoneid_t 		zoneid;
16253 	int			v4_conn_idx;
16254 	int			v6_conn_idx;
16255 	conn_t			*connp = Q_TO_CONN(q);
16256 	tcp_stack_t		*tcps;
16257 	ip_stack_t		*ipst;
16258 	mblk_t			*mp2ctl;
16259 
16260 	/*
16261 	 * make a copy of the original message
16262 	 */
16263 	mp2ctl = copymsg(mpctl);
16264 
16265 	if (mpctl == NULL ||
16266 	    (mpdata = mpctl->b_cont) == NULL ||
16267 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16268 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16269 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16270 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16271 		freemsg(mp_conn_ctl);
16272 		freemsg(mp_attr_ctl);
16273 		freemsg(mp6_conn_ctl);
16274 		freemsg(mp6_attr_ctl);
16275 		freemsg(mpctl);
16276 		freemsg(mp2ctl);
16277 		return (NULL);
16278 	}
16279 
16280 	ipst = connp->conn_netstack->netstack_ip;
16281 	tcps = connp->conn_netstack->netstack_tcp;
16282 
16283 	/* build table of connections -- need count in fixed part */
16284 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16285 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16286 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16287 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16288 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16289 
16290 	ispriv =
16291 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16292 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16293 
16294 	v4_conn_idx = v6_conn_idx = 0;
16295 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16296 
16297 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16298 		ipst = tcps->tcps_netstack->netstack_ip;
16299 
16300 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16301 
16302 		connp = NULL;
16303 
16304 		while ((connp =
16305 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16306 			tcp_t *tcp;
16307 			boolean_t needattr;
16308 
16309 			if (connp->conn_zoneid != zoneid)
16310 				continue;	/* not in this zone */
16311 
16312 			tcp = connp->conn_tcp;
16313 			UPDATE_MIB(&tcps->tcps_mib,
16314 			    tcpHCInSegs, tcp->tcp_ibsegs);
16315 			tcp->tcp_ibsegs = 0;
16316 			UPDATE_MIB(&tcps->tcps_mib,
16317 			    tcpHCOutSegs, tcp->tcp_obsegs);
16318 			tcp->tcp_obsegs = 0;
16319 
16320 			tce6.tcp6ConnState = tce.tcpConnState =
16321 			    tcp_snmp_state(tcp);
16322 			if (tce.tcpConnState == MIB2_TCP_established ||
16323 			    tce.tcpConnState == MIB2_TCP_closeWait)
16324 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16325 
16326 			needattr = B_FALSE;
16327 			bzero(&mlp, sizeof (mlp));
16328 			if (connp->conn_mlp_type != mlptSingle) {
16329 				if (connp->conn_mlp_type == mlptShared ||
16330 				    connp->conn_mlp_type == mlptBoth)
16331 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16332 				if (connp->conn_mlp_type == mlptPrivate ||
16333 				    connp->conn_mlp_type == mlptBoth)
16334 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16335 				needattr = B_TRUE;
16336 			}
16337 			if (connp->conn_peercred != NULL) {
16338 				ts_label_t *tsl;
16339 
16340 				tsl = crgetlabel(connp->conn_peercred);
16341 				mlp.tme_doi = label2doi(tsl);
16342 				mlp.tme_label = *label2bslabel(tsl);
16343 				needattr = B_TRUE;
16344 			}
16345 
16346 			/* Create a message to report on IPv6 entries */
16347 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16348 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16349 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16350 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16351 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16352 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16353 			/* Don't want just anybody seeing these... */
16354 			if (ispriv) {
16355 				tce6.tcp6ConnEntryInfo.ce_snxt =
16356 				    tcp->tcp_snxt;
16357 				tce6.tcp6ConnEntryInfo.ce_suna =
16358 				    tcp->tcp_suna;
16359 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16360 				    tcp->tcp_rnxt;
16361 				tce6.tcp6ConnEntryInfo.ce_rack =
16362 				    tcp->tcp_rack;
16363 			} else {
16364 				/*
16365 				 * Netstat, unfortunately, uses this to
16366 				 * get send/receive queue sizes.  How to fix?
16367 				 * Why not compute the difference only?
16368 				 */
16369 				tce6.tcp6ConnEntryInfo.ce_snxt =
16370 				    tcp->tcp_snxt - tcp->tcp_suna;
16371 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16372 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16373 				    tcp->tcp_rnxt - tcp->tcp_rack;
16374 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16375 			}
16376 
16377 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16378 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16379 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16380 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16381 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16382 
16383 			tce6.tcp6ConnCreationProcess =
16384 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16385 			    tcp->tcp_cpid;
16386 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16387 
16388 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16389 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16390 
16391 			mlp.tme_connidx = v6_conn_idx++;
16392 			if (needattr)
16393 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16394 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16395 			}
16396 			/*
16397 			 * Create an IPv4 table entry for IPv4 entries and also
16398 			 * for IPv6 entries which are bound to in6addr_any
16399 			 * but don't have IPV6_V6ONLY set.
16400 			 * (i.e. anything an IPv4 peer could connect to)
16401 			 */
16402 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16403 			    (tcp->tcp_state <= TCPS_LISTEN &&
16404 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16405 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16406 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16407 					tce.tcpConnRemAddress = INADDR_ANY;
16408 					tce.tcpConnLocalAddress = INADDR_ANY;
16409 				} else {
16410 					tce.tcpConnRemAddress =
16411 					    tcp->tcp_remote;
16412 					tce.tcpConnLocalAddress =
16413 					    tcp->tcp_ip_src;
16414 				}
16415 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16416 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16417 				/* Don't want just anybody seeing these... */
16418 				if (ispriv) {
16419 					tce.tcpConnEntryInfo.ce_snxt =
16420 					    tcp->tcp_snxt;
16421 					tce.tcpConnEntryInfo.ce_suna =
16422 					    tcp->tcp_suna;
16423 					tce.tcpConnEntryInfo.ce_rnxt =
16424 					    tcp->tcp_rnxt;
16425 					tce.tcpConnEntryInfo.ce_rack =
16426 					    tcp->tcp_rack;
16427 				} else {
16428 					/*
16429 					 * Netstat, unfortunately, uses this to
16430 					 * get send/receive queue sizes.  How
16431 					 * to fix?
16432 					 * Why not compute the difference only?
16433 					 */
16434 					tce.tcpConnEntryInfo.ce_snxt =
16435 					    tcp->tcp_snxt - tcp->tcp_suna;
16436 					tce.tcpConnEntryInfo.ce_suna = 0;
16437 					tce.tcpConnEntryInfo.ce_rnxt =
16438 					    tcp->tcp_rnxt - tcp->tcp_rack;
16439 					tce.tcpConnEntryInfo.ce_rack = 0;
16440 				}
16441 
16442 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16443 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16444 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16445 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16446 				tce.tcpConnEntryInfo.ce_state =
16447 				    tcp->tcp_state;
16448 
16449 				tce.tcpConnCreationProcess =
16450 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16451 				    tcp->tcp_cpid;
16452 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16453 
16454 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16455 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16456 
16457 				mlp.tme_connidx = v4_conn_idx++;
16458 				if (needattr)
16459 					(void) snmp_append_data2(
16460 					    mp_attr_ctl->b_cont,
16461 					    &mp_attr_tail, (char *)&mlp,
16462 					    sizeof (mlp));
16463 			}
16464 		}
16465 	}
16466 
16467 	/* fixed length structure for IPv4 and IPv6 counters */
16468 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16469 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16470 	    sizeof (mib2_tcp6ConnEntry_t));
16471 	/* synchronize 32- and 64-bit counters */
16472 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16473 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16474 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16475 	optp->level = MIB2_TCP;
16476 	optp->name = 0;
16477 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16478 	    sizeof (tcps->tcps_mib));
16479 	optp->len = msgdsize(mpdata);
16480 	qreply(q, mpctl);
16481 
16482 	/* table of connections... */
16483 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16484 	    sizeof (struct T_optmgmt_ack)];
16485 	optp->level = MIB2_TCP;
16486 	optp->name = MIB2_TCP_CONN;
16487 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16488 	qreply(q, mp_conn_ctl);
16489 
16490 	/* table of MLP attributes... */
16491 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16492 	    sizeof (struct T_optmgmt_ack)];
16493 	optp->level = MIB2_TCP;
16494 	optp->name = EXPER_XPORT_MLP;
16495 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16496 	if (optp->len == 0)
16497 		freemsg(mp_attr_ctl);
16498 	else
16499 		qreply(q, mp_attr_ctl);
16500 
16501 	/* table of IPv6 connections... */
16502 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16503 	    sizeof (struct T_optmgmt_ack)];
16504 	optp->level = MIB2_TCP6;
16505 	optp->name = MIB2_TCP6_CONN;
16506 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16507 	qreply(q, mp6_conn_ctl);
16508 
16509 	/* table of IPv6 MLP attributes... */
16510 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16511 	    sizeof (struct T_optmgmt_ack)];
16512 	optp->level = MIB2_TCP6;
16513 	optp->name = EXPER_XPORT_MLP;
16514 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16515 	if (optp->len == 0)
16516 		freemsg(mp6_attr_ctl);
16517 	else
16518 		qreply(q, mp6_attr_ctl);
16519 	return (mp2ctl);
16520 }
16521 
16522 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16523 /* ARGSUSED */
16524 int
16525 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16526 {
16527 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16528 
16529 	switch (level) {
16530 	case MIB2_TCP:
16531 		switch (name) {
16532 		case 13:
16533 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16534 				return (0);
16535 			/* TODO: delete entry defined by tce */
16536 			return (1);
16537 		default:
16538 			return (0);
16539 		}
16540 	default:
16541 		return (1);
16542 	}
16543 }
16544 
16545 /* Translate TCP state to MIB2 TCP state. */
16546 static int
16547 tcp_snmp_state(tcp_t *tcp)
16548 {
16549 	if (tcp == NULL)
16550 		return (0);
16551 
16552 	switch (tcp->tcp_state) {
16553 	case TCPS_CLOSED:
16554 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16555 	case TCPS_BOUND:
16556 		return (MIB2_TCP_closed);
16557 	case TCPS_LISTEN:
16558 		return (MIB2_TCP_listen);
16559 	case TCPS_SYN_SENT:
16560 		return (MIB2_TCP_synSent);
16561 	case TCPS_SYN_RCVD:
16562 		return (MIB2_TCP_synReceived);
16563 	case TCPS_ESTABLISHED:
16564 		return (MIB2_TCP_established);
16565 	case TCPS_CLOSE_WAIT:
16566 		return (MIB2_TCP_closeWait);
16567 	case TCPS_FIN_WAIT_1:
16568 		return (MIB2_TCP_finWait1);
16569 	case TCPS_CLOSING:
16570 		return (MIB2_TCP_closing);
16571 	case TCPS_LAST_ACK:
16572 		return (MIB2_TCP_lastAck);
16573 	case TCPS_FIN_WAIT_2:
16574 		return (MIB2_TCP_finWait2);
16575 	case TCPS_TIME_WAIT:
16576 		return (MIB2_TCP_timeWait);
16577 	default:
16578 		return (0);
16579 	}
16580 }
16581 
16582 static char tcp_report_header[] =
16583 	"TCP     " MI_COL_HDRPAD_STR
16584 	"zone dest            snxt     suna     "
16585 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16586 	"recent   [lport,fport] state";
16587 
16588 /*
16589  * TCP status report triggered via the Named Dispatch mechanism.
16590  */
16591 /* ARGSUSED */
16592 static void
16593 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16594     cred_t *cr)
16595 {
16596 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16597 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16598 	char cflag;
16599 	in6_addr_t	v6dst;
16600 	char buf[80];
16601 	uint_t print_len, buf_len;
16602 
16603 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16604 	if (buf_len <= 0)
16605 		return;
16606 
16607 	if (hashval >= 0)
16608 		(void) sprintf(hash, "%03d ", hashval);
16609 	else
16610 		hash[0] = '\0';
16611 
16612 	/*
16613 	 * Note that we use the remote address in the tcp_b  structure.
16614 	 * This means that it will print out the real destination address,
16615 	 * not the next hop's address if source routing is used.  This
16616 	 * avoid the confusion on the output because user may not
16617 	 * know that source routing is used for a connection.
16618 	 */
16619 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16620 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16621 	} else {
16622 		v6dst = tcp->tcp_remote_v6;
16623 	}
16624 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16625 	/*
16626 	 * the ispriv checks are so that normal users cannot determine
16627 	 * sequence number information using NDD.
16628 	 */
16629 
16630 	if (TCP_IS_DETACHED(tcp))
16631 		cflag = '*';
16632 	else
16633 		cflag = ' ';
16634 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16635 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16636 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16637 	    hash,
16638 	    (void *)tcp,
16639 	    tcp->tcp_connp->conn_zoneid,
16640 	    addrbuf,
16641 	    (ispriv) ? tcp->tcp_snxt : 0,
16642 	    (ispriv) ? tcp->tcp_suna : 0,
16643 	    tcp->tcp_swnd,
16644 	    (ispriv) ? tcp->tcp_rnxt : 0,
16645 	    (ispriv) ? tcp->tcp_rack : 0,
16646 	    tcp->tcp_rwnd,
16647 	    tcp->tcp_rto,
16648 	    tcp->tcp_mss,
16649 	    tcp->tcp_snd_ws_ok,
16650 	    tcp->tcp_snd_ws,
16651 	    tcp->tcp_rcv_ws,
16652 	    tcp->tcp_snd_ts_ok,
16653 	    tcp->tcp_ts_recent,
16654 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16655 	if (print_len < buf_len) {
16656 		((mblk_t *)mp)->b_wptr += print_len;
16657 	} else {
16658 		((mblk_t *)mp)->b_wptr += buf_len;
16659 	}
16660 }
16661 
16662 /*
16663  * TCP status report (for listeners only) triggered via the Named Dispatch
16664  * mechanism.
16665  */
16666 /* ARGSUSED */
16667 static void
16668 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16669 {
16670 	char addrbuf[INET6_ADDRSTRLEN];
16671 	in6_addr_t	v6dst;
16672 	uint_t print_len, buf_len;
16673 
16674 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16675 	if (buf_len <= 0)
16676 		return;
16677 
16678 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16679 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16680 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16681 	} else {
16682 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16683 		    addrbuf, sizeof (addrbuf));
16684 	}
16685 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16686 	    "%03d "
16687 	    MI_COL_PTRFMT_STR
16688 	    "%d %s %05u %08u %d/%d/%d%c\n",
16689 	    hashval, (void *)tcp,
16690 	    tcp->tcp_connp->conn_zoneid,
16691 	    addrbuf,
16692 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16693 	    tcp->tcp_conn_req_seqnum,
16694 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16695 	    tcp->tcp_conn_req_max,
16696 	    tcp->tcp_syn_defense ? '*' : ' ');
16697 	if (print_len < buf_len) {
16698 		((mblk_t *)mp)->b_wptr += print_len;
16699 	} else {
16700 		((mblk_t *)mp)->b_wptr += buf_len;
16701 	}
16702 }
16703 
16704 /* TCP status report triggered via the Named Dispatch mechanism. */
16705 /* ARGSUSED */
16706 static int
16707 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16708 {
16709 	tcp_t	*tcp;
16710 	int	i;
16711 	conn_t	*connp;
16712 	connf_t	*connfp;
16713 	zoneid_t zoneid;
16714 	tcp_stack_t *tcps;
16715 	ip_stack_t *ipst;
16716 
16717 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16718 	tcps = Q_TO_TCP(q)->tcp_tcps;
16719 
16720 	/*
16721 	 * Because of the ndd constraint, at most we can have 64K buffer
16722 	 * to put in all TCP info.  So to be more efficient, just
16723 	 * allocate a 64K buffer here, assuming we need that large buffer.
16724 	 * This may be a problem as any user can read tcp_status.  Therefore
16725 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16726 	 * This should be OK as normal users should not do this too often.
16727 	 */
16728 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16729 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16730 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16731 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16732 			return (0);
16733 		}
16734 	}
16735 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16736 		/* The following may work even if we cannot get a large buf. */
16737 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16738 		return (0);
16739 	}
16740 
16741 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16742 
16743 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16744 
16745 		ipst = tcps->tcps_netstack->netstack_ip;
16746 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16747 
16748 		connp = NULL;
16749 
16750 		while ((connp =
16751 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16752 			tcp = connp->conn_tcp;
16753 			if (zoneid != GLOBAL_ZONEID &&
16754 			    zoneid != connp->conn_zoneid)
16755 				continue;
16756 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16757 			    cr);
16758 		}
16759 
16760 	}
16761 
16762 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16763 	return (0);
16764 }
16765 
16766 /* TCP status report triggered via the Named Dispatch mechanism. */
16767 /* ARGSUSED */
16768 static int
16769 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16770 {
16771 	tf_t	*tbf;
16772 	tcp_t	*tcp;
16773 	int	i;
16774 	zoneid_t zoneid;
16775 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16776 
16777 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16778 
16779 	/* Refer to comments in tcp_status_report(). */
16780 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16781 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16782 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16783 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16784 			return (0);
16785 		}
16786 	}
16787 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16788 		/* The following may work even if we cannot get a large buf. */
16789 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16790 		return (0);
16791 	}
16792 
16793 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16794 
16795 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16796 		tbf = &tcps->tcps_bind_fanout[i];
16797 		mutex_enter(&tbf->tf_lock);
16798 		for (tcp = tbf->tf_tcp; tcp != NULL;
16799 		    tcp = tcp->tcp_bind_hash) {
16800 			if (zoneid != GLOBAL_ZONEID &&
16801 			    zoneid != tcp->tcp_connp->conn_zoneid)
16802 				continue;
16803 			CONN_INC_REF(tcp->tcp_connp);
16804 			tcp_report_item(mp->b_cont, tcp, i,
16805 			    Q_TO_TCP(q), cr);
16806 			CONN_DEC_REF(tcp->tcp_connp);
16807 		}
16808 		mutex_exit(&tbf->tf_lock);
16809 	}
16810 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16811 	return (0);
16812 }
16813 
16814 /* TCP status report triggered via the Named Dispatch mechanism. */
16815 /* ARGSUSED */
16816 static int
16817 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16818 {
16819 	connf_t	*connfp;
16820 	conn_t	*connp;
16821 	tcp_t	*tcp;
16822 	int	i;
16823 	zoneid_t zoneid;
16824 	tcp_stack_t *tcps;
16825 	ip_stack_t	*ipst;
16826 
16827 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16828 	tcps = Q_TO_TCP(q)->tcp_tcps;
16829 
16830 	/* Refer to comments in tcp_status_report(). */
16831 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16832 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16833 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16834 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16835 			return (0);
16836 		}
16837 	}
16838 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16839 		/* The following may work even if we cannot get a large buf. */
16840 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16841 		return (0);
16842 	}
16843 
16844 	(void) mi_mpprintf(mp,
16845 	    "    TCP    " MI_COL_HDRPAD_STR
16846 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16847 
16848 	ipst = tcps->tcps_netstack->netstack_ip;
16849 
16850 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16851 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16852 		connp = NULL;
16853 		while ((connp =
16854 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16855 			tcp = connp->conn_tcp;
16856 			if (zoneid != GLOBAL_ZONEID &&
16857 			    zoneid != connp->conn_zoneid)
16858 				continue;
16859 			tcp_report_listener(mp->b_cont, tcp, i);
16860 		}
16861 	}
16862 
16863 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16864 	return (0);
16865 }
16866 
16867 /* TCP status report triggered via the Named Dispatch mechanism. */
16868 /* ARGSUSED */
16869 static int
16870 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16871 {
16872 	connf_t	*connfp;
16873 	conn_t	*connp;
16874 	tcp_t	*tcp;
16875 	int	i;
16876 	zoneid_t zoneid;
16877 	tcp_stack_t *tcps;
16878 	ip_stack_t *ipst;
16879 
16880 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16881 	tcps = Q_TO_TCP(q)->tcp_tcps;
16882 	ipst = tcps->tcps_netstack->netstack_ip;
16883 
16884 	/* Refer to comments in tcp_status_report(). */
16885 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16886 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16887 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16888 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16889 			return (0);
16890 		}
16891 	}
16892 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16893 		/* The following may work even if we cannot get a large buf. */
16894 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16895 		return (0);
16896 	}
16897 
16898 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16899 	    ipst->ips_ipcl_conn_fanout_size);
16900 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16901 
16902 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16903 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16904 		connp = NULL;
16905 		while ((connp =
16906 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16907 			tcp = connp->conn_tcp;
16908 			if (zoneid != GLOBAL_ZONEID &&
16909 			    zoneid != connp->conn_zoneid)
16910 				continue;
16911 			tcp_report_item(mp->b_cont, tcp, i,
16912 			    Q_TO_TCP(q), cr);
16913 		}
16914 	}
16915 
16916 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16917 	return (0);
16918 }
16919 
16920 /* TCP status report triggered via the Named Dispatch mechanism. */
16921 /* ARGSUSED */
16922 static int
16923 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16924 {
16925 	tf_t	*tf;
16926 	tcp_t	*tcp;
16927 	int	i;
16928 	zoneid_t zoneid;
16929 	tcp_stack_t	*tcps;
16930 
16931 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16932 	tcps = Q_TO_TCP(q)->tcp_tcps;
16933 
16934 	/* Refer to comments in tcp_status_report(). */
16935 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16936 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16937 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16938 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16939 			return (0);
16940 		}
16941 	}
16942 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16943 		/* The following may work even if we cannot get a large buf. */
16944 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16945 		return (0);
16946 	}
16947 
16948 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16949 
16950 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16951 		tf = &tcps->tcps_acceptor_fanout[i];
16952 		mutex_enter(&tf->tf_lock);
16953 		for (tcp = tf->tf_tcp; tcp != NULL;
16954 		    tcp = tcp->tcp_acceptor_hash) {
16955 			if (zoneid != GLOBAL_ZONEID &&
16956 			    zoneid != tcp->tcp_connp->conn_zoneid)
16957 				continue;
16958 			tcp_report_item(mp->b_cont, tcp, i,
16959 			    Q_TO_TCP(q), cr);
16960 		}
16961 		mutex_exit(&tf->tf_lock);
16962 	}
16963 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16964 	return (0);
16965 }
16966 
16967 /*
16968  * tcp_timer is the timer service routine.  It handles the retransmission,
16969  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16970  * from the state of the tcp instance what kind of action needs to be done
16971  * at the time it is called.
16972  */
16973 static void
16974 tcp_timer(void *arg)
16975 {
16976 	mblk_t		*mp;
16977 	clock_t		first_threshold;
16978 	clock_t		second_threshold;
16979 	clock_t		ms;
16980 	uint32_t	mss;
16981 	conn_t		*connp = (conn_t *)arg;
16982 	tcp_t		*tcp = connp->conn_tcp;
16983 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16984 
16985 	tcp->tcp_timer_tid = 0;
16986 
16987 	if (tcp->tcp_fused)
16988 		return;
16989 
16990 	first_threshold =  tcp->tcp_first_timer_threshold;
16991 	second_threshold = tcp->tcp_second_timer_threshold;
16992 	switch (tcp->tcp_state) {
16993 	case TCPS_IDLE:
16994 	case TCPS_BOUND:
16995 	case TCPS_LISTEN:
16996 		return;
16997 	case TCPS_SYN_RCVD: {
16998 		tcp_t	*listener = tcp->tcp_listener;
16999 
17000 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17001 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17002 			/* it's our first timeout */
17003 			tcp->tcp_syn_rcvd_timeout = 1;
17004 			mutex_enter(&listener->tcp_eager_lock);
17005 			listener->tcp_syn_rcvd_timeout++;
17006 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17007 				/*
17008 				 * Make this eager available for drop if we
17009 				 * need to drop one to accomodate a new
17010 				 * incoming SYN request.
17011 				 */
17012 				MAKE_DROPPABLE(listener, tcp);
17013 			}
17014 			if (!listener->tcp_syn_defense &&
17015 			    (listener->tcp_syn_rcvd_timeout >
17016 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17017 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17018 				/* We may be under attack. Put on a defense. */
17019 				listener->tcp_syn_defense = B_TRUE;
17020 				cmn_err(CE_WARN, "High TCP connect timeout "
17021 				    "rate! System (port %d) may be under a "
17022 				    "SYN flood attack!",
17023 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17024 
17025 				listener->tcp_ip_addr_cache = kmem_zalloc(
17026 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17027 				    KM_NOSLEEP);
17028 			}
17029 			mutex_exit(&listener->tcp_eager_lock);
17030 		} else if (listener != NULL) {
17031 			mutex_enter(&listener->tcp_eager_lock);
17032 			tcp->tcp_syn_rcvd_timeout++;
17033 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17034 			    !tcp->tcp_closemp_used) {
17035 				/*
17036 				 * This is our second timeout. Put the tcp in
17037 				 * the list of droppable eagers to allow it to
17038 				 * be dropped, if needed. We don't check
17039 				 * whether tcp_dontdrop is set or not to
17040 				 * protect ourselve from a SYN attack where a
17041 				 * remote host can spoof itself as one of the
17042 				 * good IP source and continue to hold
17043 				 * resources too long.
17044 				 */
17045 				MAKE_DROPPABLE(listener, tcp);
17046 			}
17047 			mutex_exit(&listener->tcp_eager_lock);
17048 		}
17049 	}
17050 		/* FALLTHRU */
17051 	case TCPS_SYN_SENT:
17052 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17053 		second_threshold = tcp->tcp_second_ctimer_threshold;
17054 		break;
17055 	case TCPS_ESTABLISHED:
17056 	case TCPS_FIN_WAIT_1:
17057 	case TCPS_CLOSING:
17058 	case TCPS_CLOSE_WAIT:
17059 	case TCPS_LAST_ACK:
17060 		/* If we have data to rexmit */
17061 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17062 			clock_t	time_to_wait;
17063 
17064 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17065 			if (!tcp->tcp_xmit_head)
17066 				break;
17067 			time_to_wait = lbolt -
17068 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17069 			time_to_wait = tcp->tcp_rto -
17070 			    TICK_TO_MSEC(time_to_wait);
17071 			/*
17072 			 * If the timer fires too early, 1 clock tick earlier,
17073 			 * restart the timer.
17074 			 */
17075 			if (time_to_wait > msec_per_tick) {
17076 				TCP_STAT(tcps, tcp_timer_fire_early);
17077 				TCP_TIMER_RESTART(tcp, time_to_wait);
17078 				return;
17079 			}
17080 			/*
17081 			 * When we probe zero windows, we force the swnd open.
17082 			 * If our peer acks with a closed window swnd will be
17083 			 * set to zero by tcp_rput(). As long as we are
17084 			 * receiving acks tcp_rput will
17085 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17086 			 * first and second interval actions.  NOTE: the timer
17087 			 * interval is allowed to continue its exponential
17088 			 * backoff.
17089 			 */
17090 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17091 				if (tcp->tcp_debug) {
17092 					(void) strlog(TCP_MOD_ID, 0, 1,
17093 					    SL_TRACE, "tcp_timer: zero win");
17094 				}
17095 			} else {
17096 				/*
17097 				 * After retransmission, we need to do
17098 				 * slow start.  Set the ssthresh to one
17099 				 * half of current effective window and
17100 				 * cwnd to one MSS.  Also reset
17101 				 * tcp_cwnd_cnt.
17102 				 *
17103 				 * Note that if tcp_ssthresh is reduced because
17104 				 * of ECN, do not reduce it again unless it is
17105 				 * already one window of data away (tcp_cwr
17106 				 * should then be cleared) or this is a
17107 				 * timeout for a retransmitted segment.
17108 				 */
17109 				uint32_t npkt;
17110 
17111 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17112 					npkt = ((tcp->tcp_timer_backoff ?
17113 					    tcp->tcp_cwnd_ssthresh :
17114 					    tcp->tcp_snxt -
17115 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17116 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17117 					    tcp->tcp_mss;
17118 				}
17119 				tcp->tcp_cwnd = tcp->tcp_mss;
17120 				tcp->tcp_cwnd_cnt = 0;
17121 				if (tcp->tcp_ecn_ok) {
17122 					tcp->tcp_cwr = B_TRUE;
17123 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17124 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17125 				}
17126 			}
17127 			break;
17128 		}
17129 		/*
17130 		 * We have something to send yet we cannot send.  The
17131 		 * reason can be:
17132 		 *
17133 		 * 1. Zero send window: we need to do zero window probe.
17134 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17135 		 * segments.
17136 		 * 3. SWS avoidance: receiver may have shrunk window,
17137 		 * reset our knowledge.
17138 		 *
17139 		 * Note that condition 2 can happen with either 1 or
17140 		 * 3.  But 1 and 3 are exclusive.
17141 		 */
17142 		if (tcp->tcp_unsent != 0) {
17143 			if (tcp->tcp_cwnd == 0) {
17144 				/*
17145 				 * Set tcp_cwnd to 1 MSS so that a
17146 				 * new segment can be sent out.  We
17147 				 * are "clocking out" new data when
17148 				 * the network is really congested.
17149 				 */
17150 				ASSERT(tcp->tcp_ecn_ok);
17151 				tcp->tcp_cwnd = tcp->tcp_mss;
17152 			}
17153 			if (tcp->tcp_swnd == 0) {
17154 				/* Extend window for zero window probe */
17155 				tcp->tcp_swnd++;
17156 				tcp->tcp_zero_win_probe = B_TRUE;
17157 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17158 			} else {
17159 				/*
17160 				 * Handle timeout from sender SWS avoidance.
17161 				 * Reset our knowledge of the max send window
17162 				 * since the receiver might have reduced its
17163 				 * receive buffer.  Avoid setting tcp_max_swnd
17164 				 * to one since that will essentially disable
17165 				 * the SWS checks.
17166 				 *
17167 				 * Note that since we don't have a SWS
17168 				 * state variable, if the timeout is set
17169 				 * for ECN but not for SWS, this
17170 				 * code will also be executed.  This is
17171 				 * fine as tcp_max_swnd is updated
17172 				 * constantly and it will not affect
17173 				 * anything.
17174 				 */
17175 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17176 			}
17177 			tcp_wput_data(tcp, NULL, B_FALSE);
17178 			return;
17179 		}
17180 		/* Is there a FIN that needs to be to re retransmitted? */
17181 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17182 		    !tcp->tcp_fin_acked)
17183 			break;
17184 		/* Nothing to do, return without restarting timer. */
17185 		TCP_STAT(tcps, tcp_timer_fire_miss);
17186 		return;
17187 	case TCPS_FIN_WAIT_2:
17188 		/*
17189 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17190 		 * We waited some time for for peer's FIN, but it hasn't
17191 		 * arrived.  We flush the connection now to avoid
17192 		 * case where the peer has rebooted.
17193 		 */
17194 		if (TCP_IS_DETACHED(tcp)) {
17195 			(void) tcp_clean_death(tcp, 0, 23);
17196 		} else {
17197 			TCP_TIMER_RESTART(tcp,
17198 			    tcps->tcps_fin_wait_2_flush_interval);
17199 		}
17200 		return;
17201 	case TCPS_TIME_WAIT:
17202 		(void) tcp_clean_death(tcp, 0, 24);
17203 		return;
17204 	default:
17205 		if (tcp->tcp_debug) {
17206 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17207 			    "tcp_timer: strange state (%d) %s",
17208 			    tcp->tcp_state, tcp_display(tcp, NULL,
17209 			    DISP_PORT_ONLY));
17210 		}
17211 		return;
17212 	}
17213 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17214 		/*
17215 		 * For zero window probe, we need to send indefinitely,
17216 		 * unless we have not heard from the other side for some
17217 		 * time...
17218 		 */
17219 		if ((tcp->tcp_zero_win_probe == 0) ||
17220 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17221 		    second_threshold)) {
17222 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17223 			/*
17224 			 * If TCP is in SYN_RCVD state, send back a
17225 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17226 			 * should be zero in TCPS_SYN_RCVD state.
17227 			 */
17228 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17229 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17230 				    "in SYN_RCVD",
17231 				    tcp, tcp->tcp_snxt,
17232 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17233 			}
17234 			(void) tcp_clean_death(tcp,
17235 			    tcp->tcp_client_errno ?
17236 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17237 			return;
17238 		} else {
17239 			/*
17240 			 * Set tcp_ms_we_have_waited to second_threshold
17241 			 * so that in next timeout, we will do the above
17242 			 * check (lbolt - tcp_last_recv_time).  This is
17243 			 * also to avoid overflow.
17244 			 *
17245 			 * We don't need to decrement tcp_timer_backoff
17246 			 * to avoid overflow because it will be decremented
17247 			 * later if new timeout value is greater than
17248 			 * tcp_rexmit_interval_max.  In the case when
17249 			 * tcp_rexmit_interval_max is greater than
17250 			 * second_threshold, it means that we will wait
17251 			 * longer than second_threshold to send the next
17252 			 * window probe.
17253 			 */
17254 			tcp->tcp_ms_we_have_waited = second_threshold;
17255 		}
17256 	} else if (ms > first_threshold) {
17257 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17258 		    tcp->tcp_xmit_head != NULL) {
17259 			tcp->tcp_xmit_head =
17260 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17261 		}
17262 		/*
17263 		 * We have been retransmitting for too long...  The RTT
17264 		 * we calculated is probably incorrect.  Reinitialize it.
17265 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17266 		 * tcp_rtt_update so that we won't accidentally cache a
17267 		 * bad value.  But only do this if this is not a zero
17268 		 * window probe.
17269 		 */
17270 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17271 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17272 			    (tcp->tcp_rtt_sa >> 5);
17273 			tcp->tcp_rtt_sa = 0;
17274 			tcp_ip_notify(tcp);
17275 			tcp->tcp_rtt_update = 0;
17276 		}
17277 	}
17278 	tcp->tcp_timer_backoff++;
17279 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17280 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17281 	    tcps->tcps_rexmit_interval_min) {
17282 		/*
17283 		 * This means the original RTO is tcp_rexmit_interval_min.
17284 		 * So we will use tcp_rexmit_interval_min as the RTO value
17285 		 * and do the backoff.
17286 		 */
17287 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17288 	} else {
17289 		ms <<= tcp->tcp_timer_backoff;
17290 	}
17291 	if (ms > tcps->tcps_rexmit_interval_max) {
17292 		ms = tcps->tcps_rexmit_interval_max;
17293 		/*
17294 		 * ms is at max, decrement tcp_timer_backoff to avoid
17295 		 * overflow.
17296 		 */
17297 		tcp->tcp_timer_backoff--;
17298 	}
17299 	tcp->tcp_ms_we_have_waited += ms;
17300 	if (tcp->tcp_zero_win_probe == 0) {
17301 		tcp->tcp_rto = ms;
17302 	}
17303 	TCP_TIMER_RESTART(tcp, ms);
17304 	/*
17305 	 * This is after a timeout and tcp_rto is backed off.  Set
17306 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17307 	 * restart the timer with a correct value.
17308 	 */
17309 	tcp->tcp_set_timer = 1;
17310 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17311 	if (mss > tcp->tcp_mss)
17312 		mss = tcp->tcp_mss;
17313 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17314 		mss = tcp->tcp_swnd;
17315 
17316 	if ((mp = tcp->tcp_xmit_head) != NULL)
17317 		mp->b_prev = (mblk_t *)lbolt;
17318 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17319 	    B_TRUE);
17320 
17321 	/*
17322 	 * When slow start after retransmission begins, start with
17323 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17324 	 * start phase.  tcp_snd_burst controls how many segments
17325 	 * can be sent because of an ack.
17326 	 */
17327 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17328 	tcp->tcp_snd_burst = TCP_CWND_SS;
17329 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17330 	    (tcp->tcp_unsent == 0)) {
17331 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17332 	} else {
17333 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17334 	}
17335 	tcp->tcp_rexmit = B_TRUE;
17336 	tcp->tcp_dupack_cnt = 0;
17337 
17338 	/*
17339 	 * Remove all rexmit SACK blk to start from fresh.
17340 	 */
17341 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17342 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17343 		tcp->tcp_num_notsack_blk = 0;
17344 		tcp->tcp_cnt_notsack_list = 0;
17345 	}
17346 	if (mp == NULL) {
17347 		return;
17348 	}
17349 	/* Attach credentials to retransmitted initial SYNs. */
17350 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17351 		mblk_setcred(mp, tcp->tcp_cred);
17352 		DB_CPID(mp) = tcp->tcp_cpid;
17353 	}
17354 
17355 	tcp->tcp_csuna = tcp->tcp_snxt;
17356 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17357 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17358 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17359 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17360 
17361 }
17362 
17363 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17364 static void
17365 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17366 {
17367 	conn_t	*connp;
17368 
17369 	switch (tcp->tcp_state) {
17370 	case TCPS_BOUND:
17371 	case TCPS_LISTEN:
17372 		break;
17373 	default:
17374 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17375 		return;
17376 	}
17377 
17378 	/*
17379 	 * Need to clean up all the eagers since after the unbind, segments
17380 	 * will no longer be delivered to this listener stream.
17381 	 */
17382 	mutex_enter(&tcp->tcp_eager_lock);
17383 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17384 		tcp_eager_cleanup(tcp, 0);
17385 	}
17386 	mutex_exit(&tcp->tcp_eager_lock);
17387 
17388 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17389 		tcp->tcp_ipha->ipha_src = 0;
17390 	} else {
17391 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17392 	}
17393 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17394 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17395 	tcp_bind_hash_remove(tcp);
17396 	tcp->tcp_state = TCPS_IDLE;
17397 	tcp->tcp_mdt = B_FALSE;
17398 	/* Send M_FLUSH according to TPI */
17399 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17400 	connp = tcp->tcp_connp;
17401 	connp->conn_mdt_ok = B_FALSE;
17402 	ipcl_hash_remove(connp);
17403 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17404 	mp = mi_tpi_ok_ack_alloc(mp);
17405 	putnext(tcp->tcp_rq, mp);
17406 }
17407 
17408 /*
17409  * Don't let port fall into the privileged range.
17410  * Since the extra privileged ports can be arbitrary we also
17411  * ensure that we exclude those from consideration.
17412  * tcp_g_epriv_ports is not sorted thus we loop over it until
17413  * there are no changes.
17414  *
17415  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17416  * but instead the code relies on:
17417  * - the fact that the address of the array and its size never changes
17418  * - the atomic assignment of the elements of the array
17419  *
17420  * Returns 0 if there are no more ports available.
17421  *
17422  * TS note: skip multilevel ports.
17423  */
17424 static in_port_t
17425 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17426 {
17427 	int i;
17428 	boolean_t restart = B_FALSE;
17429 	tcp_stack_t *tcps = tcp->tcp_tcps;
17430 
17431 	if (random && tcp_random_anon_port != 0) {
17432 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17433 		    sizeof (in_port_t));
17434 		/*
17435 		 * Unless changed by a sys admin, the smallest anon port
17436 		 * is 32768 and the largest anon port is 65535.  It is
17437 		 * very likely (50%) for the random port to be smaller
17438 		 * than the smallest anon port.  When that happens,
17439 		 * add port % (anon port range) to the smallest anon
17440 		 * port to get the random port.  It should fall into the
17441 		 * valid anon port range.
17442 		 */
17443 		if (port < tcps->tcps_smallest_anon_port) {
17444 			port = tcps->tcps_smallest_anon_port +
17445 			    port % (tcps->tcps_largest_anon_port -
17446 			    tcps->tcps_smallest_anon_port);
17447 		}
17448 	}
17449 
17450 retry:
17451 	if (port < tcps->tcps_smallest_anon_port)
17452 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17453 
17454 	if (port > tcps->tcps_largest_anon_port) {
17455 		if (restart)
17456 			return (0);
17457 		restart = B_TRUE;
17458 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17459 	}
17460 
17461 	if (port < tcps->tcps_smallest_nonpriv_port)
17462 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17463 
17464 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17465 		if (port == tcps->tcps_g_epriv_ports[i]) {
17466 			port++;
17467 			/*
17468 			 * Make sure whether the port is in the
17469 			 * valid range.
17470 			 */
17471 			goto retry;
17472 		}
17473 	}
17474 	if (is_system_labeled() &&
17475 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17476 	    IPPROTO_TCP, B_TRUE)) != 0) {
17477 		port = i;
17478 		goto retry;
17479 	}
17480 	return (port);
17481 }
17482 
17483 /*
17484  * Return the next anonymous port in the privileged port range for
17485  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17486  * downwards.  This is the same behavior as documented in the userland
17487  * library call rresvport(3N).
17488  *
17489  * TS note: skip multilevel ports.
17490  */
17491 static in_port_t
17492 tcp_get_next_priv_port(const tcp_t *tcp)
17493 {
17494 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17495 	in_port_t nextport;
17496 	boolean_t restart = B_FALSE;
17497 	tcp_stack_t *tcps = tcp->tcp_tcps;
17498 retry:
17499 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17500 	    next_priv_port >= IPPORT_RESERVED) {
17501 		next_priv_port = IPPORT_RESERVED - 1;
17502 		if (restart)
17503 			return (0);
17504 		restart = B_TRUE;
17505 	}
17506 	if (is_system_labeled() &&
17507 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17508 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17509 		next_priv_port = nextport;
17510 		goto retry;
17511 	}
17512 	return (next_priv_port--);
17513 }
17514 
17515 /* The write side r/w procedure. */
17516 
17517 #if CCS_STATS
17518 struct {
17519 	struct {
17520 		int64_t count, bytes;
17521 	} tot, hit;
17522 } wrw_stats;
17523 #endif
17524 
17525 /*
17526  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17527  * messages.
17528  */
17529 /* ARGSUSED */
17530 static void
17531 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17532 {
17533 	conn_t	*connp = (conn_t *)arg;
17534 	tcp_t	*tcp = connp->conn_tcp;
17535 	queue_t	*q = tcp->tcp_wq;
17536 
17537 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17538 	/*
17539 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17540 	 * Once the close starts, streamhead and sockfs will not let any data
17541 	 * packets come down (close ensures that there are no threads using the
17542 	 * queue and no new threads will come down) but since qprocsoff()
17543 	 * hasn't happened yet, a M_FLUSH or some non data message might
17544 	 * get reflected back (in response to our own FLUSHRW) and get
17545 	 * processed after tcp_close() is done. The conn would still be valid
17546 	 * because a ref would have added but we need to check the state
17547 	 * before actually processing the packet.
17548 	 */
17549 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17550 		freemsg(mp);
17551 		return;
17552 	}
17553 
17554 	switch (DB_TYPE(mp)) {
17555 	case M_IOCDATA:
17556 		tcp_wput_iocdata(tcp, mp);
17557 		break;
17558 	case M_FLUSH:
17559 		tcp_wput_flush(tcp, mp);
17560 		break;
17561 	default:
17562 		CALL_IP_WPUT(connp, q, mp);
17563 		break;
17564 	}
17565 }
17566 
17567 /*
17568  * The TCP fast path write put procedure.
17569  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17570  */
17571 /* ARGSUSED */
17572 void
17573 tcp_output(void *arg, mblk_t *mp, void *arg2)
17574 {
17575 	int		len;
17576 	int		hdrlen;
17577 	int		plen;
17578 	mblk_t		*mp1;
17579 	uchar_t		*rptr;
17580 	uint32_t	snxt;
17581 	tcph_t		*tcph;
17582 	struct datab	*db;
17583 	uint32_t	suna;
17584 	uint32_t	mss;
17585 	ipaddr_t	*dst;
17586 	ipaddr_t	*src;
17587 	uint32_t	sum;
17588 	int		usable;
17589 	conn_t		*connp = (conn_t *)arg;
17590 	tcp_t		*tcp = connp->conn_tcp;
17591 	uint32_t	msize;
17592 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17593 
17594 	/*
17595 	 * Try and ASSERT the minimum possible references on the
17596 	 * conn early enough. Since we are executing on write side,
17597 	 * the connection is obviously not detached and that means
17598 	 * there is a ref each for TCP and IP. Since we are behind
17599 	 * the squeue, the minimum references needed are 3. If the
17600 	 * conn is in classifier hash list, there should be an
17601 	 * extra ref for that (we check both the possibilities).
17602 	 */
17603 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17604 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17605 
17606 	ASSERT(DB_TYPE(mp) == M_DATA);
17607 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17608 
17609 	mutex_enter(&tcp->tcp_non_sq_lock);
17610 	tcp->tcp_squeue_bytes -= msize;
17611 	mutex_exit(&tcp->tcp_non_sq_lock);
17612 
17613 	/* Bypass tcp protocol for fused tcp loopback */
17614 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17615 		return;
17616 
17617 	mss = tcp->tcp_mss;
17618 	if (tcp->tcp_xmit_zc_clean)
17619 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17620 
17621 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17622 	len = (int)(mp->b_wptr - mp->b_rptr);
17623 
17624 	/*
17625 	 * Criteria for fast path:
17626 	 *
17627 	 *   1. no unsent data
17628 	 *   2. single mblk in request
17629 	 *   3. connection established
17630 	 *   4. data in mblk
17631 	 *   5. len <= mss
17632 	 *   6. no tcp_valid bits
17633 	 */
17634 	if ((tcp->tcp_unsent != 0) ||
17635 	    (tcp->tcp_cork) ||
17636 	    (mp->b_cont != NULL) ||
17637 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17638 	    (len == 0) ||
17639 	    (len > mss) ||
17640 	    (tcp->tcp_valid_bits != 0)) {
17641 		tcp_wput_data(tcp, mp, B_FALSE);
17642 		return;
17643 	}
17644 
17645 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17646 	ASSERT(tcp->tcp_fin_sent == 0);
17647 
17648 	/* queue new packet onto retransmission queue */
17649 	if (tcp->tcp_xmit_head == NULL) {
17650 		tcp->tcp_xmit_head = mp;
17651 	} else {
17652 		tcp->tcp_xmit_last->b_cont = mp;
17653 	}
17654 	tcp->tcp_xmit_last = mp;
17655 	tcp->tcp_xmit_tail = mp;
17656 
17657 	/* find out how much we can send */
17658 	/* BEGIN CSTYLED */
17659 	/*
17660 	 *    un-acked           usable
17661 	 *  |--------------|-----------------|
17662 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17663 	 */
17664 	/* END CSTYLED */
17665 
17666 	/* start sending from tcp_snxt */
17667 	snxt = tcp->tcp_snxt;
17668 
17669 	/*
17670 	 * Check to see if this connection has been idled for some
17671 	 * time and no ACK is expected.  If it is, we need to slow
17672 	 * start again to get back the connection's "self-clock" as
17673 	 * described in VJ's paper.
17674 	 *
17675 	 * Refer to the comment in tcp_mss_set() for the calculation
17676 	 * of tcp_cwnd after idle.
17677 	 */
17678 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17679 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17680 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17681 	}
17682 
17683 	usable = tcp->tcp_swnd;		/* tcp window size */
17684 	if (usable > tcp->tcp_cwnd)
17685 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17686 	usable -= snxt;		/* subtract stuff already sent */
17687 	suna = tcp->tcp_suna;
17688 	usable += suna;
17689 	/* usable can be < 0 if the congestion window is smaller */
17690 	if (len > usable) {
17691 		/* Can't send complete M_DATA in one shot */
17692 		goto slow;
17693 	}
17694 
17695 	mutex_enter(&tcp->tcp_non_sq_lock);
17696 	if (tcp->tcp_flow_stopped &&
17697 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17698 		tcp_clrqfull(tcp);
17699 	}
17700 	mutex_exit(&tcp->tcp_non_sq_lock);
17701 
17702 	/*
17703 	 * determine if anything to send (Nagle).
17704 	 *
17705 	 *   1. len < tcp_mss (i.e. small)
17706 	 *   2. unacknowledged data present
17707 	 *   3. len < nagle limit
17708 	 *   4. last packet sent < nagle limit (previous packet sent)
17709 	 */
17710 	if ((len < mss) && (snxt != suna) &&
17711 	    (len < (int)tcp->tcp_naglim) &&
17712 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17713 		/*
17714 		 * This was the first unsent packet and normally
17715 		 * mss < xmit_hiwater so there is no need to worry
17716 		 * about flow control. The next packet will go
17717 		 * through the flow control check in tcp_wput_data().
17718 		 */
17719 		/* leftover work from above */
17720 		tcp->tcp_unsent = len;
17721 		tcp->tcp_xmit_tail_unsent = len;
17722 
17723 		return;
17724 	}
17725 
17726 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17727 
17728 	if (snxt == suna) {
17729 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17730 	}
17731 
17732 	/* we have always sent something */
17733 	tcp->tcp_rack_cnt = 0;
17734 
17735 	tcp->tcp_snxt = snxt + len;
17736 	tcp->tcp_rack = tcp->tcp_rnxt;
17737 
17738 	if ((mp1 = dupb(mp)) == 0)
17739 		goto no_memory;
17740 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17741 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17742 
17743 	/* adjust tcp header information */
17744 	tcph = tcp->tcp_tcph;
17745 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17746 
17747 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17748 	sum = (sum >> 16) + (sum & 0xFFFF);
17749 	U16_TO_ABE16(sum, tcph->th_sum);
17750 
17751 	U32_TO_ABE32(snxt, tcph->th_seq);
17752 
17753 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17754 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17755 	BUMP_LOCAL(tcp->tcp_obsegs);
17756 
17757 	/* Update the latest receive window size in TCP header. */
17758 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17759 	    tcph->th_win);
17760 
17761 	tcp->tcp_last_sent_len = (ushort_t)len;
17762 
17763 	plen = len + tcp->tcp_hdr_len;
17764 
17765 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17766 		tcp->tcp_ipha->ipha_length = htons(plen);
17767 	} else {
17768 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17769 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17770 	}
17771 
17772 	/* see if we need to allocate a mblk for the headers */
17773 	hdrlen = tcp->tcp_hdr_len;
17774 	rptr = mp1->b_rptr - hdrlen;
17775 	db = mp1->b_datap;
17776 	if ((db->db_ref != 2) || rptr < db->db_base ||
17777 	    (!OK_32PTR(rptr))) {
17778 		/* NOTE: we assume allocb returns an OK_32PTR */
17779 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17780 		    tcps->tcps_wroff_xtra, BPRI_MED);
17781 		if (!mp) {
17782 			freemsg(mp1);
17783 			goto no_memory;
17784 		}
17785 		mp->b_cont = mp1;
17786 		mp1 = mp;
17787 		/* Leave room for Link Level header */
17788 		/* hdrlen = tcp->tcp_hdr_len; */
17789 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17790 		mp1->b_wptr = &rptr[hdrlen];
17791 	}
17792 	mp1->b_rptr = rptr;
17793 
17794 	/* Fill in the timestamp option. */
17795 	if (tcp->tcp_snd_ts_ok) {
17796 		U32_TO_BE32((uint32_t)lbolt,
17797 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17798 		U32_TO_BE32(tcp->tcp_ts_recent,
17799 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17800 	} else {
17801 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17802 	}
17803 
17804 	/* copy header into outgoing packet */
17805 	dst = (ipaddr_t *)rptr;
17806 	src = (ipaddr_t *)tcp->tcp_iphc;
17807 	dst[0] = src[0];
17808 	dst[1] = src[1];
17809 	dst[2] = src[2];
17810 	dst[3] = src[3];
17811 	dst[4] = src[4];
17812 	dst[5] = src[5];
17813 	dst[6] = src[6];
17814 	dst[7] = src[7];
17815 	dst[8] = src[8];
17816 	dst[9] = src[9];
17817 	if (hdrlen -= 40) {
17818 		hdrlen >>= 2;
17819 		dst += 10;
17820 		src += 10;
17821 		do {
17822 			*dst++ = *src++;
17823 		} while (--hdrlen);
17824 	}
17825 
17826 	/*
17827 	 * Set the ECN info in the TCP header.  Note that this
17828 	 * is not the template header.
17829 	 */
17830 	if (tcp->tcp_ecn_ok) {
17831 		SET_ECT(tcp, rptr);
17832 
17833 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17834 		if (tcp->tcp_ecn_echo_on)
17835 			tcph->th_flags[0] |= TH_ECE;
17836 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17837 			tcph->th_flags[0] |= TH_CWR;
17838 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17839 		}
17840 	}
17841 
17842 	if (tcp->tcp_ip_forward_progress) {
17843 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17844 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17845 		tcp->tcp_ip_forward_progress = B_FALSE;
17846 	}
17847 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17848 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17849 	return;
17850 
17851 	/*
17852 	 * If we ran out of memory, we pretend to have sent the packet
17853 	 * and that it was lost on the wire.
17854 	 */
17855 no_memory:
17856 	return;
17857 
17858 slow:
17859 	/* leftover work from above */
17860 	tcp->tcp_unsent = len;
17861 	tcp->tcp_xmit_tail_unsent = len;
17862 	tcp_wput_data(tcp, NULL, B_FALSE);
17863 }
17864 
17865 /*
17866  * The function called through squeue to get behind eager's perimeter to
17867  * finish the accept processing.
17868  */
17869 /* ARGSUSED */
17870 void
17871 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17872 {
17873 	conn_t			*connp = (conn_t *)arg;
17874 	tcp_t			*tcp = connp->conn_tcp;
17875 	queue_t			*q = tcp->tcp_rq;
17876 	mblk_t			*mp1;
17877 	mblk_t			*stropt_mp = mp;
17878 	struct  stroptions	*stropt;
17879 	uint_t			thwin;
17880 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17881 
17882 	/*
17883 	 * Drop the eager's ref on the listener, that was placed when
17884 	 * this eager began life in tcp_conn_request.
17885 	 */
17886 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17887 
17888 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17889 		/*
17890 		 * Someone blewoff the eager before we could finish
17891 		 * the accept.
17892 		 *
17893 		 * The only reason eager exists it because we put in
17894 		 * a ref on it when conn ind went up. We need to send
17895 		 * a disconnect indication up while the last reference
17896 		 * on the eager will be dropped by the squeue when we
17897 		 * return.
17898 		 */
17899 		ASSERT(tcp->tcp_listener == NULL);
17900 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17901 			struct	T_discon_ind	*tdi;
17902 
17903 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17904 			/*
17905 			 * Let us reuse the incoming mblk to avoid memory
17906 			 * allocation failure problems. We know that the
17907 			 * size of the incoming mblk i.e. stroptions is greater
17908 			 * than sizeof T_discon_ind. So the reallocb below
17909 			 * can't fail.
17910 			 */
17911 			freemsg(mp->b_cont);
17912 			mp->b_cont = NULL;
17913 			ASSERT(DB_REF(mp) == 1);
17914 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17915 			    B_FALSE);
17916 			ASSERT(mp != NULL);
17917 			DB_TYPE(mp) = M_PROTO;
17918 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17919 			tdi = (struct T_discon_ind *)mp->b_rptr;
17920 			if (tcp->tcp_issocket) {
17921 				tdi->DISCON_reason = ECONNREFUSED;
17922 				tdi->SEQ_number = 0;
17923 			} else {
17924 				tdi->DISCON_reason = ENOPROTOOPT;
17925 				tdi->SEQ_number =
17926 				    tcp->tcp_conn_req_seqnum;
17927 			}
17928 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17929 			putnext(q, mp);
17930 		} else {
17931 			freemsg(mp);
17932 		}
17933 		if (tcp->tcp_hard_binding) {
17934 			tcp->tcp_hard_binding = B_FALSE;
17935 			tcp->tcp_hard_bound = B_TRUE;
17936 		}
17937 		tcp->tcp_detached = B_FALSE;
17938 		return;
17939 	}
17940 
17941 	mp1 = stropt_mp->b_cont;
17942 	stropt_mp->b_cont = NULL;
17943 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17944 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17945 
17946 	while (mp1 != NULL) {
17947 		mp = mp1;
17948 		mp1 = mp1->b_cont;
17949 		mp->b_cont = NULL;
17950 		tcp->tcp_drop_opt_ack_cnt++;
17951 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17952 	}
17953 	mp = NULL;
17954 
17955 	/*
17956 	 * For a loopback connection with tcp_direct_sockfs on, note that
17957 	 * we don't have to protect tcp_rcv_list yet because synchronous
17958 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17959 	 * possibly race with us.
17960 	 */
17961 
17962 	/*
17963 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17964 	 * properly.  This is the first time we know of the acceptor'
17965 	 * queue.  So we do it here.
17966 	 */
17967 	if (tcp->tcp_rcv_list == NULL) {
17968 		/*
17969 		 * Recv queue is empty, tcp_rwnd should not have changed.
17970 		 * That means it should be equal to the listener's tcp_rwnd.
17971 		 */
17972 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17973 	} else {
17974 #ifdef DEBUG
17975 		uint_t cnt = 0;
17976 
17977 		mp1 = tcp->tcp_rcv_list;
17978 		while ((mp = mp1) != NULL) {
17979 			mp1 = mp->b_next;
17980 			cnt += msgdsize(mp);
17981 		}
17982 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17983 #endif
17984 		/* There is some data, add them back to get the max. */
17985 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17986 	}
17987 
17988 	stropt->so_flags = SO_HIWAT;
17989 	stropt->so_hiwat = MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
17990 
17991 	stropt->so_flags |= SO_MAXBLK;
17992 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17993 
17994 	/*
17995 	 * This is the first time we run on the correct
17996 	 * queue after tcp_accept. So fix all the q parameters
17997 	 * here.
17998 	 */
17999 	/* Allocate room for SACK options if needed. */
18000 	stropt->so_flags |= SO_WROFF;
18001 	if (tcp->tcp_fused) {
18002 		ASSERT(tcp->tcp_loopback);
18003 		ASSERT(tcp->tcp_loopback_peer != NULL);
18004 		/*
18005 		 * For fused tcp loopback, set the stream head's write
18006 		 * offset value to zero since we won't be needing any room
18007 		 * for TCP/IP headers.  This would also improve performance
18008 		 * since it would reduce the amount of work done by kmem.
18009 		 * Non-fused tcp loopback case is handled separately below.
18010 		 */
18011 		stropt->so_wroff = 0;
18012 		/*
18013 		 * Record the stream head's high water mark for this endpoint;
18014 		 * this is used for flow-control purposes in tcp_fuse_output().
18015 		 */
18016 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
18017 		/*
18018 		 * Update the peer's transmit parameters according to
18019 		 * our recently calculated high water mark value.
18020 		 */
18021 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18022 	} else if (tcp->tcp_snd_sack_ok) {
18023 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18024 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18025 	} else {
18026 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18027 		    tcps->tcps_wroff_xtra);
18028 	}
18029 
18030 	/*
18031 	 * If this is endpoint is handling SSL, then reserve extra
18032 	 * offset and space at the end.
18033 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18034 	 * overriding the previous setting. The extra cost of signing and
18035 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18036 	 * instead of a single contiguous one by the stream head
18037 	 * largely outweighs the statistical reduction of ACKs, when
18038 	 * applicable. The peer will also save on decyption and verification
18039 	 * costs.
18040 	 */
18041 	if (tcp->tcp_kssl_ctx != NULL) {
18042 		stropt->so_wroff += SSL3_WROFFSET;
18043 
18044 		stropt->so_flags |= SO_TAIL;
18045 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18046 
18047 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18048 	}
18049 
18050 	/* Send the options up */
18051 	putnext(q, stropt_mp);
18052 
18053 	/*
18054 	 * Pass up any data and/or a fin that has been received.
18055 	 *
18056 	 * Adjust receive window in case it had decreased
18057 	 * (because there is data <=> tcp_rcv_list != NULL)
18058 	 * while the connection was detached. Note that
18059 	 * in case the eager was flow-controlled, w/o this
18060 	 * code, the rwnd may never open up again!
18061 	 */
18062 	if (tcp->tcp_rcv_list != NULL) {
18063 		/* We drain directly in case of fused tcp loopback */
18064 		if (!tcp->tcp_fused && canputnext(q)) {
18065 			tcp->tcp_rwnd = q->q_hiwat;
18066 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18067 			    << tcp->tcp_rcv_ws;
18068 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18069 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18070 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18071 				tcp_xmit_ctl(NULL,
18072 				    tcp, (tcp->tcp_swnd == 0) ?
18073 				    tcp->tcp_suna : tcp->tcp_snxt,
18074 				    tcp->tcp_rnxt, TH_ACK);
18075 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18076 			}
18077 
18078 		}
18079 		(void) tcp_rcv_drain(q, tcp);
18080 
18081 		/*
18082 		 * For fused tcp loopback, back-enable peer endpoint
18083 		 * if it's currently flow-controlled.
18084 		 */
18085 		if (tcp->tcp_fused) {
18086 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18087 
18088 			ASSERT(peer_tcp != NULL);
18089 			ASSERT(peer_tcp->tcp_fused);
18090 			/*
18091 			 * In order to change the peer's tcp_flow_stopped,
18092 			 * we need to take locks for both end points. The
18093 			 * highest address is taken first.
18094 			 */
18095 			if (peer_tcp > tcp) {
18096 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18097 				mutex_enter(&tcp->tcp_non_sq_lock);
18098 			} else {
18099 				mutex_enter(&tcp->tcp_non_sq_lock);
18100 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18101 			}
18102 			if (peer_tcp->tcp_flow_stopped) {
18103 				tcp_clrqfull(peer_tcp);
18104 				TCP_STAT(tcps, tcp_fusion_backenabled);
18105 			}
18106 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18107 			mutex_exit(&tcp->tcp_non_sq_lock);
18108 		}
18109 	}
18110 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18111 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18112 		mp = mi_tpi_ordrel_ind();
18113 		if (mp) {
18114 			tcp->tcp_ordrel_done = B_TRUE;
18115 			putnext(q, mp);
18116 			if (tcp->tcp_deferred_clean_death) {
18117 				/*
18118 				 * tcp_clean_death was deferred
18119 				 * for T_ORDREL_IND - do it now
18120 				 */
18121 				(void) tcp_clean_death(tcp,
18122 				    tcp->tcp_client_errno, 21);
18123 				tcp->tcp_deferred_clean_death = B_FALSE;
18124 			}
18125 		} else {
18126 			/*
18127 			 * Run the orderly release in the
18128 			 * service routine.
18129 			 */
18130 			qenable(q);
18131 		}
18132 	}
18133 	if (tcp->tcp_hard_binding) {
18134 		tcp->tcp_hard_binding = B_FALSE;
18135 		tcp->tcp_hard_bound = B_TRUE;
18136 	}
18137 
18138 	tcp->tcp_detached = B_FALSE;
18139 
18140 	/* We can enable synchronous streams now */
18141 	if (tcp->tcp_fused) {
18142 		tcp_fuse_syncstr_enable_pair(tcp);
18143 	}
18144 
18145 	if (tcp->tcp_ka_enabled) {
18146 		tcp->tcp_ka_last_intrvl = 0;
18147 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18148 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18149 	}
18150 
18151 	/*
18152 	 * At this point, eager is fully established and will
18153 	 * have the following references -
18154 	 *
18155 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18156 	 * 1 reference for the squeue which will be dropped by the squeue as
18157 	 *	soon as this function returns.
18158 	 * There will be 1 additonal reference for being in classifier
18159 	 *	hash list provided something bad hasn't happened.
18160 	 */
18161 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18162 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18163 }
18164 
18165 /*
18166  * The function called through squeue to get behind listener's perimeter to
18167  * send a deffered conn_ind.
18168  */
18169 /* ARGSUSED */
18170 void
18171 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18172 {
18173 	conn_t	*connp = (conn_t *)arg;
18174 	tcp_t *listener = connp->conn_tcp;
18175 
18176 	if (listener->tcp_state == TCPS_CLOSED ||
18177 	    TCP_IS_DETACHED(listener)) {
18178 		/*
18179 		 * If listener has closed, it would have caused a
18180 		 * a cleanup/blowoff to happen for the eager.
18181 		 */
18182 		tcp_t *tcp;
18183 		struct T_conn_ind	*conn_ind;
18184 
18185 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18186 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18187 		    conn_ind->OPT_length);
18188 		/*
18189 		 * We need to drop the ref on eager that was put
18190 		 * tcp_rput_data() before trying to send the conn_ind
18191 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18192 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18193 		 * listener is closed so we drop the ref.
18194 		 */
18195 		CONN_DEC_REF(tcp->tcp_connp);
18196 		freemsg(mp);
18197 		return;
18198 	}
18199 	putnext(listener->tcp_rq, mp);
18200 }
18201 
18202 
18203 /*
18204  * This is the STREAMS entry point for T_CONN_RES coming down on
18205  * Acceptor STREAM when  sockfs listener does accept processing.
18206  * Read the block comment on top of tcp_conn_request().
18207  */
18208 void
18209 tcp_wput_accept(queue_t *q, mblk_t *mp)
18210 {
18211 	queue_t *rq = RD(q);
18212 	struct T_conn_res *conn_res;
18213 	tcp_t *eager;
18214 	tcp_t *listener;
18215 	struct T_ok_ack *ok;
18216 	t_scalar_t PRIM_type;
18217 	mblk_t *opt_mp;
18218 	conn_t *econnp;
18219 
18220 	ASSERT(DB_TYPE(mp) == M_PROTO);
18221 
18222 	conn_res = (struct T_conn_res *)mp->b_rptr;
18223 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18224 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18225 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18226 		if (mp != NULL)
18227 			putnext(rq, mp);
18228 		return;
18229 	}
18230 	switch (conn_res->PRIM_type) {
18231 	case O_T_CONN_RES:
18232 	case T_CONN_RES:
18233 		/*
18234 		 * We pass up an err ack if allocb fails. This will
18235 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18236 		 * tcp_eager_blowoff to be called. sockfs will then call
18237 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18238 		 * we need to do the allocb up here because we have to
18239 		 * make sure rq->q_qinfo->qi_qclose still points to the
18240 		 * correct function (tcpclose_accept) in case allocb
18241 		 * fails.
18242 		 */
18243 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18244 		if (opt_mp == NULL) {
18245 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18246 			if (mp != NULL)
18247 				putnext(rq, mp);
18248 			return;
18249 		}
18250 
18251 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18252 		    &eager, conn_res->OPT_length);
18253 		PRIM_type = conn_res->PRIM_type;
18254 		mp->b_datap->db_type = M_PCPROTO;
18255 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18256 		ok = (struct T_ok_ack *)mp->b_rptr;
18257 		ok->PRIM_type = T_OK_ACK;
18258 		ok->CORRECT_prim = PRIM_type;
18259 		econnp = eager->tcp_connp;
18260 		econnp->conn_dev = (dev_t)q->q_ptr;
18261 		eager->tcp_rq = rq;
18262 		eager->tcp_wq = q;
18263 		rq->q_ptr = econnp;
18264 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18265 		q->q_ptr = econnp;
18266 		q->q_qinfo = &tcp_winit;
18267 		listener = eager->tcp_listener;
18268 		eager->tcp_issocket = B_TRUE;
18269 
18270 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18271 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18272 		ASSERT(econnp->conn_netstack ==
18273 		    listener->tcp_connp->conn_netstack);
18274 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18275 
18276 		/* Put the ref for IP */
18277 		CONN_INC_REF(econnp);
18278 
18279 		/*
18280 		 * We should have minimum of 3 references on the conn
18281 		 * at this point. One each for TCP and IP and one for
18282 		 * the T_conn_ind that was sent up when the 3-way handshake
18283 		 * completed. In the normal case we would also have another
18284 		 * reference (making a total of 4) for the conn being in the
18285 		 * classifier hash list. However the eager could have received
18286 		 * an RST subsequently and tcp_closei_local could have removed
18287 		 * the eager from the classifier hash list, hence we can't
18288 		 * assert that reference.
18289 		 */
18290 		ASSERT(econnp->conn_ref >= 3);
18291 
18292 		/*
18293 		 * Send the new local address also up to sockfs. There
18294 		 * should already be enough space in the mp that came
18295 		 * down from soaccept().
18296 		 */
18297 		if (eager->tcp_family == AF_INET) {
18298 			sin_t *sin;
18299 
18300 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18301 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18302 			sin = (sin_t *)mp->b_wptr;
18303 			mp->b_wptr += sizeof (sin_t);
18304 			sin->sin_family = AF_INET;
18305 			sin->sin_port = eager->tcp_lport;
18306 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18307 		} else {
18308 			sin6_t *sin6;
18309 
18310 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18311 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18312 			sin6 = (sin6_t *)mp->b_wptr;
18313 			mp->b_wptr += sizeof (sin6_t);
18314 			sin6->sin6_family = AF_INET6;
18315 			sin6->sin6_port = eager->tcp_lport;
18316 			if (eager->tcp_ipversion == IPV4_VERSION) {
18317 				sin6->sin6_flowinfo = 0;
18318 				IN6_IPADDR_TO_V4MAPPED(
18319 				    eager->tcp_ipha->ipha_src,
18320 				    &sin6->sin6_addr);
18321 			} else {
18322 				ASSERT(eager->tcp_ip6h != NULL);
18323 				sin6->sin6_flowinfo =
18324 				    eager->tcp_ip6h->ip6_vcf &
18325 				    ~IPV6_VERS_AND_FLOW_MASK;
18326 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18327 			}
18328 			sin6->sin6_scope_id = 0;
18329 			sin6->__sin6_src_id = 0;
18330 		}
18331 
18332 		putnext(rq, mp);
18333 
18334 		opt_mp->b_datap->db_type = M_SETOPTS;
18335 		opt_mp->b_wptr += sizeof (struct stroptions);
18336 
18337 		/*
18338 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18339 		 * from listener to acceptor. The message is chained on the
18340 		 * bind_mp which tcp_rput_other will send down to IP.
18341 		 */
18342 		if (listener->tcp_bound_if != 0) {
18343 			/* allocate optmgmt req */
18344 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18345 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18346 			    sizeof (int));
18347 			if (mp != NULL)
18348 				linkb(opt_mp, mp);
18349 		}
18350 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18351 			uint_t on = 1;
18352 
18353 			/* allocate optmgmt req */
18354 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18355 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18356 			if (mp != NULL)
18357 				linkb(opt_mp, mp);
18358 		}
18359 
18360 
18361 		mutex_enter(&listener->tcp_eager_lock);
18362 
18363 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18364 
18365 			tcp_t *tail;
18366 			tcp_t *tcp;
18367 			mblk_t *mp1;
18368 
18369 			tcp = listener->tcp_eager_prev_q0;
18370 			/*
18371 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18372 			 * deferred T_conn_ind queue. We need to get to the head
18373 			 * of the queue in order to send up T_conn_ind the same
18374 			 * order as how the 3WHS is completed.
18375 			 */
18376 			while (tcp != listener) {
18377 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18378 				    !tcp->tcp_kssl_pending)
18379 					break;
18380 				else
18381 					tcp = tcp->tcp_eager_prev_q0;
18382 			}
18383 			/* None of the pending eagers can be sent up now */
18384 			if (tcp == listener)
18385 				goto no_more_eagers;
18386 
18387 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18388 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18389 			/* Move from q0 to q */
18390 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18391 			listener->tcp_conn_req_cnt_q0--;
18392 			listener->tcp_conn_req_cnt_q++;
18393 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18394 			    tcp->tcp_eager_prev_q0;
18395 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18396 			    tcp->tcp_eager_next_q0;
18397 			tcp->tcp_eager_prev_q0 = NULL;
18398 			tcp->tcp_eager_next_q0 = NULL;
18399 			tcp->tcp_conn_def_q0 = B_FALSE;
18400 
18401 			/* Make sure the tcp isn't in the list of droppables */
18402 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18403 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18404 
18405 			/*
18406 			 * Insert at end of the queue because sockfs sends
18407 			 * down T_CONN_RES in chronological order. Leaving
18408 			 * the older conn indications at front of the queue
18409 			 * helps reducing search time.
18410 			 */
18411 			tail = listener->tcp_eager_last_q;
18412 			if (tail != NULL) {
18413 				tail->tcp_eager_next_q = tcp;
18414 			} else {
18415 				listener->tcp_eager_next_q = tcp;
18416 			}
18417 			listener->tcp_eager_last_q = tcp;
18418 			tcp->tcp_eager_next_q = NULL;
18419 
18420 			/* Need to get inside the listener perimeter */
18421 			CONN_INC_REF(listener->tcp_connp);
18422 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18423 			    tcp_send_pending, listener->tcp_connp,
18424 			    SQTAG_TCP_SEND_PENDING);
18425 		}
18426 no_more_eagers:
18427 		tcp_eager_unlink(eager);
18428 		mutex_exit(&listener->tcp_eager_lock);
18429 
18430 		/*
18431 		 * At this point, the eager is detached from the listener
18432 		 * but we still have an extra refs on eager (apart from the
18433 		 * usual tcp references). The ref was placed in tcp_rput_data
18434 		 * before sending the conn_ind in tcp_send_conn_ind.
18435 		 * The ref will be dropped in tcp_accept_finish().
18436 		 */
18437 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18438 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18439 		return;
18440 	default:
18441 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18442 		if (mp != NULL)
18443 			putnext(rq, mp);
18444 		return;
18445 	}
18446 }
18447 
18448 void
18449 tcp_wput(queue_t *q, mblk_t *mp)
18450 {
18451 	conn_t	*connp = Q_TO_CONN(q);
18452 	tcp_t	*tcp;
18453 	void (*output_proc)();
18454 	t_scalar_t type;
18455 	uchar_t *rptr;
18456 	struct iocblk	*iocp;
18457 	uint32_t	msize;
18458 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18459 
18460 	ASSERT(connp->conn_ref >= 2);
18461 
18462 	switch (DB_TYPE(mp)) {
18463 	case M_DATA:
18464 		tcp = connp->conn_tcp;
18465 		ASSERT(tcp != NULL);
18466 
18467 		msize = msgdsize(mp);
18468 
18469 		mutex_enter(&tcp->tcp_non_sq_lock);
18470 		tcp->tcp_squeue_bytes += msize;
18471 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18472 			tcp_setqfull(tcp);
18473 		}
18474 		mutex_exit(&tcp->tcp_non_sq_lock);
18475 
18476 		CONN_INC_REF(connp);
18477 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18478 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18479 		return;
18480 	case M_PROTO:
18481 	case M_PCPROTO:
18482 		/*
18483 		 * if it is a snmp message, don't get behind the squeue
18484 		 */
18485 		tcp = connp->conn_tcp;
18486 		rptr = mp->b_rptr;
18487 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18488 			type = ((union T_primitives *)rptr)->type;
18489 		} else {
18490 			if (tcp->tcp_debug) {
18491 				(void) strlog(TCP_MOD_ID, 0, 1,
18492 				    SL_ERROR|SL_TRACE,
18493 				    "tcp_wput_proto, dropping one...");
18494 			}
18495 			freemsg(mp);
18496 			return;
18497 		}
18498 		if (type == T_SVR4_OPTMGMT_REQ) {
18499 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18500 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18501 			    cr)) {
18502 				/*
18503 				 * This was a SNMP request
18504 				 */
18505 				return;
18506 			} else {
18507 				output_proc = tcp_wput_proto;
18508 			}
18509 		} else {
18510 			output_proc = tcp_wput_proto;
18511 		}
18512 		break;
18513 	case M_IOCTL:
18514 		/*
18515 		 * Most ioctls can be processed right away without going via
18516 		 * squeues - process them right here. Those that do require
18517 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18518 		 * are processed by tcp_wput_ioctl().
18519 		 */
18520 		iocp = (struct iocblk *)mp->b_rptr;
18521 		tcp = connp->conn_tcp;
18522 
18523 		switch (iocp->ioc_cmd) {
18524 		case TCP_IOC_ABORT_CONN:
18525 			tcp_ioctl_abort_conn(q, mp);
18526 			return;
18527 		case TI_GETPEERNAME:
18528 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18529 				iocp->ioc_error = ENOTCONN;
18530 				iocp->ioc_count = 0;
18531 				mp->b_datap->db_type = M_IOCACK;
18532 				qreply(q, mp);
18533 				return;
18534 			}
18535 			/* FALLTHRU */
18536 		case TI_GETMYNAME:
18537 			mi_copyin(q, mp, NULL,
18538 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18539 			return;
18540 		case ND_SET:
18541 			/* nd_getset does the necessary checks */
18542 		case ND_GET:
18543 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18544 				CALL_IP_WPUT(connp, q, mp);
18545 				return;
18546 			}
18547 			qreply(q, mp);
18548 			return;
18549 		case TCP_IOC_DEFAULT_Q:
18550 			/*
18551 			 * Wants to be the default wq. Check the credentials
18552 			 * first, the rest is executed via squeue.
18553 			 */
18554 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18555 				iocp->ioc_error = EPERM;
18556 				iocp->ioc_count = 0;
18557 				mp->b_datap->db_type = M_IOCACK;
18558 				qreply(q, mp);
18559 				return;
18560 			}
18561 			output_proc = tcp_wput_ioctl;
18562 			break;
18563 		default:
18564 			output_proc = tcp_wput_ioctl;
18565 			break;
18566 		}
18567 		break;
18568 	default:
18569 		output_proc = tcp_wput_nondata;
18570 		break;
18571 	}
18572 
18573 	CONN_INC_REF(connp);
18574 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18575 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18576 }
18577 
18578 /*
18579  * Initial STREAMS write side put() procedure for sockets. It tries to
18580  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18581  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18582  * are handled by tcp_wput() as usual.
18583  *
18584  * All further messages will also be handled by tcp_wput() because we cannot
18585  * be sure that the above short cut is safe later.
18586  */
18587 static void
18588 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18589 {
18590 	conn_t			*connp = Q_TO_CONN(wq);
18591 	tcp_t			*tcp = connp->conn_tcp;
18592 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18593 
18594 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18595 	wq->q_qinfo = &tcp_winit;
18596 
18597 	ASSERT(IPCL_IS_TCP(connp));
18598 	ASSERT(TCP_IS_SOCKET(tcp));
18599 
18600 	if (DB_TYPE(mp) == M_PCPROTO &&
18601 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18602 	    car->PRIM_type == T_CAPABILITY_REQ) {
18603 		tcp_capability_req(tcp, mp);
18604 		return;
18605 	}
18606 
18607 	tcp_wput(wq, mp);
18608 }
18609 
18610 static boolean_t
18611 tcp_zcopy_check(tcp_t *tcp)
18612 {
18613 	conn_t	*connp = tcp->tcp_connp;
18614 	ire_t	*ire;
18615 	boolean_t	zc_enabled = B_FALSE;
18616 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18617 
18618 	if (do_tcpzcopy == 2)
18619 		zc_enabled = B_TRUE;
18620 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18621 	    IPCL_IS_CONNECTED(connp) &&
18622 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18623 	    connp->conn_dontroute == 0 &&
18624 	    !connp->conn_nexthop_set &&
18625 	    connp->conn_xmit_if_ill == NULL &&
18626 	    connp->conn_nofailover_ill == NULL &&
18627 	    do_tcpzcopy == 1) {
18628 		/*
18629 		 * the checks above  closely resemble the fast path checks
18630 		 * in tcp_send_data().
18631 		 */
18632 		mutex_enter(&connp->conn_lock);
18633 		ire = connp->conn_ire_cache;
18634 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18635 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18636 			IRE_REFHOLD(ire);
18637 			if (ire->ire_stq != NULL) {
18638 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18639 
18640 				zc_enabled = ill && (ill->ill_capabilities &
18641 				    ILL_CAPAB_ZEROCOPY) &&
18642 				    (ill->ill_zerocopy_capab->
18643 				    ill_zerocopy_flags != 0);
18644 			}
18645 			IRE_REFRELE(ire);
18646 		}
18647 		mutex_exit(&connp->conn_lock);
18648 	}
18649 	tcp->tcp_snd_zcopy_on = zc_enabled;
18650 	if (!TCP_IS_DETACHED(tcp)) {
18651 		if (zc_enabled) {
18652 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18653 			TCP_STAT(tcps, tcp_zcopy_on);
18654 		} else {
18655 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18656 			TCP_STAT(tcps, tcp_zcopy_off);
18657 		}
18658 	}
18659 	return (zc_enabled);
18660 }
18661 
18662 static mblk_t *
18663 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18664 {
18665 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18666 
18667 	if (do_tcpzcopy == 2)
18668 		return (bp);
18669 	else if (tcp->tcp_snd_zcopy_on) {
18670 		tcp->tcp_snd_zcopy_on = B_FALSE;
18671 		if (!TCP_IS_DETACHED(tcp)) {
18672 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18673 			TCP_STAT(tcps, tcp_zcopy_disable);
18674 		}
18675 	}
18676 	return (tcp_zcopy_backoff(tcp, bp, 0));
18677 }
18678 
18679 /*
18680  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18681  * the original desballoca'ed segmapped mblk.
18682  */
18683 static mblk_t *
18684 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18685 {
18686 	mblk_t *head, *tail, *nbp;
18687 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18688 
18689 	if (IS_VMLOANED_MBLK(bp)) {
18690 		TCP_STAT(tcps, tcp_zcopy_backoff);
18691 		if ((head = copyb(bp)) == NULL) {
18692 			/* fail to backoff; leave it for the next backoff */
18693 			tcp->tcp_xmit_zc_clean = B_FALSE;
18694 			return (bp);
18695 		}
18696 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18697 			if (fix_xmitlist)
18698 				tcp_zcopy_notify(tcp);
18699 			else
18700 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18701 		}
18702 		nbp = bp->b_cont;
18703 		if (fix_xmitlist) {
18704 			head->b_prev = bp->b_prev;
18705 			head->b_next = bp->b_next;
18706 			if (tcp->tcp_xmit_tail == bp)
18707 				tcp->tcp_xmit_tail = head;
18708 		}
18709 		bp->b_next = NULL;
18710 		bp->b_prev = NULL;
18711 		freeb(bp);
18712 	} else {
18713 		head = bp;
18714 		nbp = bp->b_cont;
18715 	}
18716 	tail = head;
18717 	while (nbp) {
18718 		if (IS_VMLOANED_MBLK(nbp)) {
18719 			TCP_STAT(tcps, tcp_zcopy_backoff);
18720 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18721 				tcp->tcp_xmit_zc_clean = B_FALSE;
18722 				tail->b_cont = nbp;
18723 				return (head);
18724 			}
18725 			tail = tail->b_cont;
18726 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18727 				if (fix_xmitlist)
18728 					tcp_zcopy_notify(tcp);
18729 				else
18730 					tail->b_datap->db_struioflag |=
18731 					    STRUIO_ZCNOTIFY;
18732 			}
18733 			bp = nbp;
18734 			nbp = nbp->b_cont;
18735 			if (fix_xmitlist) {
18736 				tail->b_prev = bp->b_prev;
18737 				tail->b_next = bp->b_next;
18738 				if (tcp->tcp_xmit_tail == bp)
18739 					tcp->tcp_xmit_tail = tail;
18740 			}
18741 			bp->b_next = NULL;
18742 			bp->b_prev = NULL;
18743 			freeb(bp);
18744 		} else {
18745 			tail->b_cont = nbp;
18746 			tail = nbp;
18747 			nbp = nbp->b_cont;
18748 		}
18749 	}
18750 	if (fix_xmitlist) {
18751 		tcp->tcp_xmit_last = tail;
18752 		tcp->tcp_xmit_zc_clean = B_TRUE;
18753 	}
18754 	return (head);
18755 }
18756 
18757 static void
18758 tcp_zcopy_notify(tcp_t *tcp)
18759 {
18760 	struct stdata	*stp;
18761 
18762 	if (tcp->tcp_detached)
18763 		return;
18764 	stp = STREAM(tcp->tcp_rq);
18765 	mutex_enter(&stp->sd_lock);
18766 	stp->sd_flag |= STZCNOTIFY;
18767 	cv_broadcast(&stp->sd_zcopy_wait);
18768 	mutex_exit(&stp->sd_lock);
18769 }
18770 
18771 static boolean_t
18772 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18773 {
18774 	ire_t	*ire;
18775 	conn_t	*connp = tcp->tcp_connp;
18776 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18777 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18778 
18779 	mutex_enter(&connp->conn_lock);
18780 	ire = connp->conn_ire_cache;
18781 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18782 
18783 	if ((ire != NULL) &&
18784 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18785 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18786 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18787 		IRE_REFHOLD(ire);
18788 		mutex_exit(&connp->conn_lock);
18789 	} else {
18790 		boolean_t cached = B_FALSE;
18791 		ts_label_t *tsl;
18792 
18793 		/* force a recheck later on */
18794 		tcp->tcp_ire_ill_check_done = B_FALSE;
18795 
18796 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18797 		connp->conn_ire_cache = NULL;
18798 		mutex_exit(&connp->conn_lock);
18799 
18800 		if (ire != NULL)
18801 			IRE_REFRELE_NOTR(ire);
18802 
18803 		tsl = crgetlabel(CONN_CRED(connp));
18804 		ire = (dst ?
18805 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18806 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18807 		    connp->conn_zoneid, tsl, ipst));
18808 
18809 		if (ire == NULL) {
18810 			TCP_STAT(tcps, tcp_ire_null);
18811 			return (B_FALSE);
18812 		}
18813 
18814 		IRE_REFHOLD_NOTR(ire);
18815 		/*
18816 		 * Since we are inside the squeue, there cannot be another
18817 		 * thread in TCP trying to set the conn_ire_cache now.  The
18818 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18819 		 * unplumb thread has not yet started cleaning up the conns.
18820 		 * Hence we don't need to grab the conn lock.
18821 		 */
18822 		if (CONN_CACHE_IRE(connp)) {
18823 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18824 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18825 				TCP_CHECK_IREINFO(tcp, ire);
18826 				connp->conn_ire_cache = ire;
18827 				cached = B_TRUE;
18828 			}
18829 			rw_exit(&ire->ire_bucket->irb_lock);
18830 		}
18831 
18832 		/*
18833 		 * We can continue to use the ire but since it was
18834 		 * not cached, we should drop the extra reference.
18835 		 */
18836 		if (!cached)
18837 			IRE_REFRELE_NOTR(ire);
18838 
18839 		/*
18840 		 * Rampart note: no need to select a new label here, since
18841 		 * labels are not allowed to change during the life of a TCP
18842 		 * connection.
18843 		 */
18844 	}
18845 
18846 	*irep = ire;
18847 
18848 	return (B_TRUE);
18849 }
18850 
18851 /*
18852  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18853  *
18854  * 0 = success;
18855  * 1 = failed to find ire and ill.
18856  */
18857 static boolean_t
18858 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18859 {
18860 	ipha_t		*ipha;
18861 	ipaddr_t	dst;
18862 	ire_t		*ire;
18863 	ill_t		*ill;
18864 	conn_t		*connp = tcp->tcp_connp;
18865 	mblk_t		*ire_fp_mp;
18866 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18867 
18868 	if (mp != NULL)
18869 		ipha = (ipha_t *)mp->b_rptr;
18870 	else
18871 		ipha = tcp->tcp_ipha;
18872 	dst = ipha->ipha_dst;
18873 
18874 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18875 		return (B_FALSE);
18876 
18877 	if ((ire->ire_flags & RTF_MULTIRT) ||
18878 	    (ire->ire_stq == NULL) ||
18879 	    (ire->ire_nce == NULL) ||
18880 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18881 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18882 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18883 		TCP_STAT(tcps, tcp_ip_ire_send);
18884 		IRE_REFRELE(ire);
18885 		return (B_FALSE);
18886 	}
18887 
18888 	ill = ire_to_ill(ire);
18889 	if (connp->conn_outgoing_ill != NULL) {
18890 		ill_t *conn_outgoing_ill = NULL;
18891 		/*
18892 		 * Choose a good ill in the group to send the packets on.
18893 		 */
18894 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18895 		ill = ire_to_ill(ire);
18896 	}
18897 	ASSERT(ill != NULL);
18898 
18899 	if (!tcp->tcp_ire_ill_check_done) {
18900 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18901 		tcp->tcp_ire_ill_check_done = B_TRUE;
18902 	}
18903 
18904 	*irep = ire;
18905 	*illp = ill;
18906 
18907 	return (B_TRUE);
18908 }
18909 
18910 static void
18911 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18912 {
18913 	ipha_t		*ipha;
18914 	ipaddr_t	src;
18915 	ipaddr_t	dst;
18916 	uint32_t	cksum;
18917 	ire_t		*ire;
18918 	uint16_t	*up;
18919 	ill_t		*ill;
18920 	conn_t		*connp = tcp->tcp_connp;
18921 	uint32_t	hcksum_txflags = 0;
18922 	mblk_t		*ire_fp_mp;
18923 	uint_t		ire_fp_mp_len;
18924 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18925 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18926 
18927 	ASSERT(DB_TYPE(mp) == M_DATA);
18928 
18929 	if (DB_CRED(mp) == NULL)
18930 		mblk_setcred(mp, CONN_CRED(connp));
18931 
18932 	ipha = (ipha_t *)mp->b_rptr;
18933 	src = ipha->ipha_src;
18934 	dst = ipha->ipha_dst;
18935 
18936 	/*
18937 	 * Drop off fast path for IPv6 and also if options are present or
18938 	 * we need to resolve a TS label.
18939 	 */
18940 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18941 	    !IPCL_IS_CONNECTED(connp) ||
18942 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18943 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18944 	    !connp->conn_ulp_labeled ||
18945 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18946 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18947 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18948 		if (tcp->tcp_snd_zcopy_aware)
18949 			mp = tcp_zcopy_disable(tcp, mp);
18950 		TCP_STAT(tcps, tcp_ip_send);
18951 		CALL_IP_WPUT(connp, q, mp);
18952 		return;
18953 	}
18954 
18955 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18956 		if (tcp->tcp_snd_zcopy_aware)
18957 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18958 		CALL_IP_WPUT(connp, q, mp);
18959 		return;
18960 	}
18961 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18962 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18963 
18964 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18965 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18966 #ifndef _BIG_ENDIAN
18967 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18968 #endif
18969 
18970 	/*
18971 	 * Check to see if we need to re-enable LSO/MDT for this connection
18972 	 * because it was previously disabled due to changes in the ill;
18973 	 * note that by doing it here, this re-enabling only applies when
18974 	 * the packet is not dispatched through CALL_IP_WPUT().
18975 	 *
18976 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18977 	 * case, since that's how we ended up here.  For IPv6, we do the
18978 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18979 	 */
18980 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18981 		/*
18982 		 * Restore LSO for this connection, so that next time around
18983 		 * it is eligible to go through tcp_lsosend() path again.
18984 		 */
18985 		TCP_STAT(tcps, tcp_lso_enabled);
18986 		tcp->tcp_lso = B_TRUE;
18987 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18988 		    "interface %s\n", (void *)connp, ill->ill_name));
18989 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18990 		/*
18991 		 * Restore MDT for this connection, so that next time around
18992 		 * it is eligible to go through tcp_multisend() path again.
18993 		 */
18994 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18995 		tcp->tcp_mdt = B_TRUE;
18996 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18997 		    "interface %s\n", (void *)connp, ill->ill_name));
18998 	}
18999 
19000 	if (tcp->tcp_snd_zcopy_aware) {
19001 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19002 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19003 			mp = tcp_zcopy_disable(tcp, mp);
19004 		/*
19005 		 * we shouldn't need to reset ipha as the mp containing
19006 		 * ipha should never be a zero-copy mp.
19007 		 */
19008 	}
19009 
19010 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19011 		ASSERT(ill->ill_hcksum_capab != NULL);
19012 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19013 	}
19014 
19015 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19016 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19017 
19018 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19019 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19020 
19021 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19022 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19023 
19024 	/* Software checksum? */
19025 	if (DB_CKSUMFLAGS(mp) == 0) {
19026 		TCP_STAT(tcps, tcp_out_sw_cksum);
19027 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19028 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19029 	}
19030 
19031 	ipha->ipha_fragment_offset_and_flags |=
19032 	    (uint32_t)htons(ire->ire_frag_flag);
19033 
19034 	/* Calculate IP header checksum if hardware isn't capable */
19035 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19036 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19037 		    ((uint16_t *)ipha)[4]);
19038 	}
19039 
19040 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19041 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19042 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19043 
19044 	UPDATE_OB_PKT_COUNT(ire);
19045 	ire->ire_last_used_time = lbolt;
19046 
19047 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19048 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19049 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19050 	    ntohs(ipha->ipha_length));
19051 
19052 	if (ILL_DLS_CAPABLE(ill)) {
19053 		/*
19054 		 * Send the packet directly to DLD, where it may be queued
19055 		 * depending on the availability of transmit resources at
19056 		 * the media layer.
19057 		 */
19058 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19059 	} else {
19060 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19061 		DTRACE_PROBE4(ip4__physical__out__start,
19062 		    ill_t *, NULL, ill_t *, out_ill,
19063 		    ipha_t *, ipha, mblk_t *, mp);
19064 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19065 		    ipst->ips_ipv4firewall_physical_out,
19066 		    NULL, out_ill, ipha, mp, mp, ipst);
19067 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19068 		if (mp != NULL)
19069 			putnext(ire->ire_stq, mp);
19070 	}
19071 	IRE_REFRELE(ire);
19072 }
19073 
19074 /*
19075  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19076  * if the receiver shrinks the window, i.e. moves the right window to the
19077  * left, the we should not send new data, but should retransmit normally the
19078  * old unacked data between suna and suna + swnd. We might has sent data
19079  * that is now outside the new window, pretend that we didn't send  it.
19080  */
19081 static void
19082 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19083 {
19084 	uint32_t	snxt = tcp->tcp_snxt;
19085 	mblk_t		*xmit_tail;
19086 	int32_t		offset;
19087 
19088 	ASSERT(shrunk_count > 0);
19089 
19090 	/* Pretend we didn't send the data outside the window */
19091 	snxt -= shrunk_count;
19092 
19093 	/* Get the mblk and the offset in it per the shrunk window */
19094 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19095 
19096 	ASSERT(xmit_tail != NULL);
19097 
19098 	/* Reset all the values per the now shrunk window */
19099 	tcp->tcp_snxt = snxt;
19100 	tcp->tcp_xmit_tail = xmit_tail;
19101 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19102 	    offset;
19103 	tcp->tcp_unsent += shrunk_count;
19104 
19105 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19106 		/*
19107 		 * Make sure the timer is running so that we will probe a zero
19108 		 * window.
19109 		 */
19110 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19111 }
19112 
19113 
19114 /*
19115  * The TCP normal data output path.
19116  * NOTE: the logic of the fast path is duplicated from this function.
19117  */
19118 static void
19119 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19120 {
19121 	int		len;
19122 	mblk_t		*local_time;
19123 	mblk_t		*mp1;
19124 	uint32_t	snxt;
19125 	int		tail_unsent;
19126 	int		tcpstate;
19127 	int		usable = 0;
19128 	mblk_t		*xmit_tail;
19129 	queue_t		*q = tcp->tcp_wq;
19130 	int32_t		mss;
19131 	int32_t		num_sack_blk = 0;
19132 	int32_t		tcp_hdr_len;
19133 	int32_t		tcp_tcp_hdr_len;
19134 	int		mdt_thres;
19135 	int		rc;
19136 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19137 	ip_stack_t	*ipst;
19138 
19139 	tcpstate = tcp->tcp_state;
19140 	if (mp == NULL) {
19141 		/*
19142 		 * tcp_wput_data() with NULL mp should only be called when
19143 		 * there is unsent data.
19144 		 */
19145 		ASSERT(tcp->tcp_unsent > 0);
19146 		/* Really tacky... but we need this for detached closes. */
19147 		len = tcp->tcp_unsent;
19148 		goto data_null;
19149 	}
19150 
19151 #if CCS_STATS
19152 	wrw_stats.tot.count++;
19153 	wrw_stats.tot.bytes += msgdsize(mp);
19154 #endif
19155 	ASSERT(mp->b_datap->db_type == M_DATA);
19156 	/*
19157 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19158 	 * or before a connection attempt has begun.
19159 	 */
19160 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19161 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19162 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19163 #ifdef DEBUG
19164 			cmn_err(CE_WARN,
19165 			    "tcp_wput_data: data after ordrel, %s",
19166 			    tcp_display(tcp, NULL,
19167 			    DISP_ADDR_AND_PORT));
19168 #else
19169 			if (tcp->tcp_debug) {
19170 				(void) strlog(TCP_MOD_ID, 0, 1,
19171 				    SL_TRACE|SL_ERROR,
19172 				    "tcp_wput_data: data after ordrel, %s\n",
19173 				    tcp_display(tcp, NULL,
19174 				    DISP_ADDR_AND_PORT));
19175 			}
19176 #endif /* DEBUG */
19177 		}
19178 		if (tcp->tcp_snd_zcopy_aware &&
19179 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19180 			tcp_zcopy_notify(tcp);
19181 		freemsg(mp);
19182 		mutex_enter(&tcp->tcp_non_sq_lock);
19183 		if (tcp->tcp_flow_stopped &&
19184 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19185 			tcp_clrqfull(tcp);
19186 		}
19187 		mutex_exit(&tcp->tcp_non_sq_lock);
19188 		return;
19189 	}
19190 
19191 	/* Strip empties */
19192 	for (;;) {
19193 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19194 		    (uintptr_t)INT_MAX);
19195 		len = (int)(mp->b_wptr - mp->b_rptr);
19196 		if (len > 0)
19197 			break;
19198 		mp1 = mp;
19199 		mp = mp->b_cont;
19200 		freeb(mp1);
19201 		if (!mp) {
19202 			return;
19203 		}
19204 	}
19205 
19206 	/* If we are the first on the list ... */
19207 	if (tcp->tcp_xmit_head == NULL) {
19208 		tcp->tcp_xmit_head = mp;
19209 		tcp->tcp_xmit_tail = mp;
19210 		tcp->tcp_xmit_tail_unsent = len;
19211 	} else {
19212 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19213 		struct datab *dp;
19214 
19215 		mp1 = tcp->tcp_xmit_last;
19216 		if (len < tcp_tx_pull_len &&
19217 		    (dp = mp1->b_datap)->db_ref == 1 &&
19218 		    dp->db_lim - mp1->b_wptr >= len) {
19219 			ASSERT(len > 0);
19220 			ASSERT(!mp1->b_cont);
19221 			if (len == 1) {
19222 				*mp1->b_wptr++ = *mp->b_rptr;
19223 			} else {
19224 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19225 				mp1->b_wptr += len;
19226 			}
19227 			if (mp1 == tcp->tcp_xmit_tail)
19228 				tcp->tcp_xmit_tail_unsent += len;
19229 			mp1->b_cont = mp->b_cont;
19230 			if (tcp->tcp_snd_zcopy_aware &&
19231 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19232 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19233 			freeb(mp);
19234 			mp = mp1;
19235 		} else {
19236 			tcp->tcp_xmit_last->b_cont = mp;
19237 		}
19238 		len += tcp->tcp_unsent;
19239 	}
19240 
19241 	/* Tack on however many more positive length mblks we have */
19242 	if ((mp1 = mp->b_cont) != NULL) {
19243 		do {
19244 			int tlen;
19245 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19246 			    (uintptr_t)INT_MAX);
19247 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19248 			if (tlen <= 0) {
19249 				mp->b_cont = mp1->b_cont;
19250 				freeb(mp1);
19251 			} else {
19252 				len += tlen;
19253 				mp = mp1;
19254 			}
19255 		} while ((mp1 = mp->b_cont) != NULL);
19256 	}
19257 	tcp->tcp_xmit_last = mp;
19258 	tcp->tcp_unsent = len;
19259 
19260 	if (urgent)
19261 		usable = 1;
19262 
19263 data_null:
19264 	snxt = tcp->tcp_snxt;
19265 	xmit_tail = tcp->tcp_xmit_tail;
19266 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19267 
19268 	/*
19269 	 * Note that tcp_mss has been adjusted to take into account the
19270 	 * timestamp option if applicable.  Because SACK options do not
19271 	 * appear in every TCP segments and they are of variable lengths,
19272 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19273 	 * the actual segment length when we need to send a segment which
19274 	 * includes SACK options.
19275 	 */
19276 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19277 		int32_t	opt_len;
19278 
19279 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19280 		    tcp->tcp_num_sack_blk);
19281 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19282 		    2 + TCPOPT_HEADER_LEN;
19283 		mss = tcp->tcp_mss - opt_len;
19284 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19285 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19286 	} else {
19287 		mss = tcp->tcp_mss;
19288 		tcp_hdr_len = tcp->tcp_hdr_len;
19289 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19290 	}
19291 
19292 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19293 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19294 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19295 	}
19296 	if (tcpstate == TCPS_SYN_RCVD) {
19297 		/*
19298 		 * The three-way connection establishment handshake is not
19299 		 * complete yet. We want to queue the data for transmission
19300 		 * after entering ESTABLISHED state (RFC793). A jump to
19301 		 * "done" label effectively leaves data on the queue.
19302 		 */
19303 		goto done;
19304 	} else {
19305 		int usable_r;
19306 
19307 		/*
19308 		 * In the special case when cwnd is zero, which can only
19309 		 * happen if the connection is ECN capable, return now.
19310 		 * New segments is sent using tcp_timer().  The timer
19311 		 * is set in tcp_rput_data().
19312 		 */
19313 		if (tcp->tcp_cwnd == 0) {
19314 			/*
19315 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19316 			 * finished.
19317 			 */
19318 			ASSERT(tcp->tcp_ecn_ok ||
19319 			    tcp->tcp_state < TCPS_ESTABLISHED);
19320 			return;
19321 		}
19322 
19323 		/* NOTE: trouble if xmitting while SYN not acked? */
19324 		usable_r = snxt - tcp->tcp_suna;
19325 		usable_r = tcp->tcp_swnd - usable_r;
19326 
19327 		/*
19328 		 * Check if the receiver has shrunk the window.  If
19329 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19330 		 * cannot be set as there is unsent data, so FIN cannot
19331 		 * be sent out.  Otherwise, we need to take into account
19332 		 * of FIN as it consumes an "invisible" sequence number.
19333 		 */
19334 		ASSERT(tcp->tcp_fin_sent == 0);
19335 		if (usable_r < 0) {
19336 			/*
19337 			 * The receiver has shrunk the window and we have sent
19338 			 * -usable_r date beyond the window, re-adjust.
19339 			 *
19340 			 * If TCP window scaling is enabled, there can be
19341 			 * round down error as the advertised receive window
19342 			 * is actually right shifted n bits.  This means that
19343 			 * the lower n bits info is wiped out.  It will look
19344 			 * like the window is shrunk.  Do a check here to
19345 			 * see if the shrunk amount is actually within the
19346 			 * error in window calculation.  If it is, just
19347 			 * return.  Note that this check is inside the
19348 			 * shrunk window check.  This makes sure that even
19349 			 * though tcp_process_shrunk_swnd() is not called,
19350 			 * we will stop further processing.
19351 			 */
19352 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19353 				tcp_process_shrunk_swnd(tcp, -usable_r);
19354 			}
19355 			return;
19356 		}
19357 
19358 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19359 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19360 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19361 
19362 		/* usable = MIN(usable, unsent) */
19363 		if (usable_r > len)
19364 			usable_r = len;
19365 
19366 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19367 		if (usable_r > 0) {
19368 			usable = usable_r;
19369 		} else {
19370 			/* Bypass all other unnecessary processing. */
19371 			goto done;
19372 		}
19373 	}
19374 
19375 	local_time = (mblk_t *)lbolt;
19376 
19377 	/*
19378 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19379 	 * BSD.  This is more in line with the true intent of Nagle.
19380 	 *
19381 	 * The conditions are:
19382 	 * 1. The amount of unsent data (or amount of data which can be
19383 	 *    sent, whichever is smaller) is less than Nagle limit.
19384 	 * 2. The last sent size is also less than Nagle limit.
19385 	 * 3. There is unack'ed data.
19386 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19387 	 *    Nagle algorithm.  This reduces the probability that urgent
19388 	 *    bytes get "merged" together.
19389 	 * 5. The app has not closed the connection.  This eliminates the
19390 	 *    wait time of the receiving side waiting for the last piece of
19391 	 *    (small) data.
19392 	 *
19393 	 * If all are satisified, exit without sending anything.  Note
19394 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19395 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19396 	 * 4095).
19397 	 */
19398 	if (usable < (int)tcp->tcp_naglim &&
19399 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19400 	    snxt != tcp->tcp_suna &&
19401 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19402 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19403 		goto done;
19404 	}
19405 
19406 	if (tcp->tcp_cork) {
19407 		/*
19408 		 * if the tcp->tcp_cork option is set, then we have to force
19409 		 * TCP not to send partial segment (smaller than MSS bytes).
19410 		 * We are calculating the usable now based on full mss and
19411 		 * will save the rest of remaining data for later.
19412 		 */
19413 		if (usable < mss)
19414 			goto done;
19415 		usable = (usable / mss) * mss;
19416 	}
19417 
19418 	/* Update the latest receive window size in TCP header. */
19419 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19420 	    tcp->tcp_tcph->th_win);
19421 
19422 	/*
19423 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19424 	 *
19425 	 * 1. Simple TCP/IP{v4,v6} (no options).
19426 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19427 	 * 3. If the TCP connection is in ESTABLISHED state.
19428 	 * 4. The TCP is not detached.
19429 	 *
19430 	 * If any of the above conditions have changed during the
19431 	 * connection, stop using LSO/MDT and restore the stream head
19432 	 * parameters accordingly.
19433 	 */
19434 	ipst = tcps->tcps_netstack->netstack_ip;
19435 
19436 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19437 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19438 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19439 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19440 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19441 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19442 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19443 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19444 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19445 		if (tcp->tcp_lso) {
19446 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19447 			tcp->tcp_lso = B_FALSE;
19448 		} else {
19449 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19450 			tcp->tcp_mdt = B_FALSE;
19451 		}
19452 
19453 		/* Anything other than detached is considered pathological */
19454 		if (!TCP_IS_DETACHED(tcp)) {
19455 			if (tcp->tcp_lso)
19456 				TCP_STAT(tcps, tcp_lso_disabled);
19457 			else
19458 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19459 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19460 		}
19461 	}
19462 
19463 	/* Use MDT if sendable amount is greater than the threshold */
19464 	if (tcp->tcp_mdt &&
19465 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19466 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19467 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19468 	    (tcp->tcp_valid_bits == 0 ||
19469 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19470 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19471 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19472 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19473 		    local_time, mdt_thres);
19474 	} else {
19475 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19476 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19477 		    local_time, INT_MAX);
19478 	}
19479 
19480 	/* Pretend that all we were trying to send really got sent */
19481 	if (rc < 0 && tail_unsent < 0) {
19482 		do {
19483 			xmit_tail = xmit_tail->b_cont;
19484 			xmit_tail->b_prev = local_time;
19485 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19486 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19487 			tail_unsent += (int)(xmit_tail->b_wptr -
19488 			    xmit_tail->b_rptr);
19489 		} while (tail_unsent < 0);
19490 	}
19491 done:;
19492 	tcp->tcp_xmit_tail = xmit_tail;
19493 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19494 	len = tcp->tcp_snxt - snxt;
19495 	if (len) {
19496 		/*
19497 		 * If new data was sent, need to update the notsack
19498 		 * list, which is, afterall, data blocks that have
19499 		 * not been sack'ed by the receiver.  New data is
19500 		 * not sack'ed.
19501 		 */
19502 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19503 			/* len is a negative value. */
19504 			tcp->tcp_pipe -= len;
19505 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19506 			    tcp->tcp_snxt, snxt,
19507 			    &(tcp->tcp_num_notsack_blk),
19508 			    &(tcp->tcp_cnt_notsack_list));
19509 		}
19510 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19511 		tcp->tcp_rack = tcp->tcp_rnxt;
19512 		tcp->tcp_rack_cnt = 0;
19513 		if ((snxt + len) == tcp->tcp_suna) {
19514 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19515 		}
19516 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19517 		/*
19518 		 * Didn't send anything. Make sure the timer is running
19519 		 * so that we will probe a zero window.
19520 		 */
19521 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19522 	}
19523 	/* Note that len is the amount we just sent but with a negative sign */
19524 	tcp->tcp_unsent += len;
19525 	mutex_enter(&tcp->tcp_non_sq_lock);
19526 	if (tcp->tcp_flow_stopped) {
19527 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19528 			tcp_clrqfull(tcp);
19529 		}
19530 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19531 		tcp_setqfull(tcp);
19532 	}
19533 	mutex_exit(&tcp->tcp_non_sq_lock);
19534 }
19535 
19536 /*
19537  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19538  * outgoing TCP header with the template header, as well as other
19539  * options such as time-stamp, ECN and/or SACK.
19540  */
19541 static void
19542 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19543 {
19544 	tcph_t *tcp_tmpl, *tcp_h;
19545 	uint32_t *dst, *src;
19546 	int hdrlen;
19547 
19548 	ASSERT(OK_32PTR(rptr));
19549 
19550 	/* Template header */
19551 	tcp_tmpl = tcp->tcp_tcph;
19552 
19553 	/* Header of outgoing packet */
19554 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19555 
19556 	/* dst and src are opaque 32-bit fields, used for copying */
19557 	dst = (uint32_t *)rptr;
19558 	src = (uint32_t *)tcp->tcp_iphc;
19559 	hdrlen = tcp->tcp_hdr_len;
19560 
19561 	/* Fill time-stamp option if needed */
19562 	if (tcp->tcp_snd_ts_ok) {
19563 		U32_TO_BE32((uint32_t)now,
19564 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19565 		U32_TO_BE32(tcp->tcp_ts_recent,
19566 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19567 	} else {
19568 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19569 	}
19570 
19571 	/*
19572 	 * Copy the template header; is this really more efficient than
19573 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19574 	 * but perhaps not for other scenarios.
19575 	 */
19576 	dst[0] = src[0];
19577 	dst[1] = src[1];
19578 	dst[2] = src[2];
19579 	dst[3] = src[3];
19580 	dst[4] = src[4];
19581 	dst[5] = src[5];
19582 	dst[6] = src[6];
19583 	dst[7] = src[7];
19584 	dst[8] = src[8];
19585 	dst[9] = src[9];
19586 	if (hdrlen -= 40) {
19587 		hdrlen >>= 2;
19588 		dst += 10;
19589 		src += 10;
19590 		do {
19591 			*dst++ = *src++;
19592 		} while (--hdrlen);
19593 	}
19594 
19595 	/*
19596 	 * Set the ECN info in the TCP header if it is not a zero
19597 	 * window probe.  Zero window probe is only sent in
19598 	 * tcp_wput_data() and tcp_timer().
19599 	 */
19600 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19601 		SET_ECT(tcp, rptr);
19602 
19603 		if (tcp->tcp_ecn_echo_on)
19604 			tcp_h->th_flags[0] |= TH_ECE;
19605 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19606 			tcp_h->th_flags[0] |= TH_CWR;
19607 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19608 		}
19609 	}
19610 
19611 	/* Fill in SACK options */
19612 	if (num_sack_blk > 0) {
19613 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19614 		sack_blk_t *tmp;
19615 		int32_t	i;
19616 
19617 		wptr[0] = TCPOPT_NOP;
19618 		wptr[1] = TCPOPT_NOP;
19619 		wptr[2] = TCPOPT_SACK;
19620 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19621 		    sizeof (sack_blk_t);
19622 		wptr += TCPOPT_REAL_SACK_LEN;
19623 
19624 		tmp = tcp->tcp_sack_list;
19625 		for (i = 0; i < num_sack_blk; i++) {
19626 			U32_TO_BE32(tmp[i].begin, wptr);
19627 			wptr += sizeof (tcp_seq);
19628 			U32_TO_BE32(tmp[i].end, wptr);
19629 			wptr += sizeof (tcp_seq);
19630 		}
19631 		tcp_h->th_offset_and_rsrvd[0] +=
19632 		    ((num_sack_blk * 2 + 1) << 4);
19633 	}
19634 }
19635 
19636 /*
19637  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19638  * the destination address and SAP attribute, and if necessary, the
19639  * hardware checksum offload attribute to a Multidata message.
19640  */
19641 static int
19642 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19643     const uint32_t start, const uint32_t stuff, const uint32_t end,
19644     const uint32_t flags, tcp_stack_t *tcps)
19645 {
19646 	/* Add global destination address & SAP attribute */
19647 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19648 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19649 		    "destination address+SAP\n"));
19650 
19651 		if (dlmp != NULL)
19652 			TCP_STAT(tcps, tcp_mdt_allocfail);
19653 		return (-1);
19654 	}
19655 
19656 	/* Add global hwcksum attribute */
19657 	if (hwcksum &&
19658 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19659 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19660 		    "checksum attribute\n"));
19661 
19662 		TCP_STAT(tcps, tcp_mdt_allocfail);
19663 		return (-1);
19664 	}
19665 
19666 	return (0);
19667 }
19668 
19669 /*
19670  * Smaller and private version of pdescinfo_t used specifically for TCP,
19671  * which allows for only two payload spans per packet.
19672  */
19673 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19674 
19675 /*
19676  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19677  * scheme, and returns one the following:
19678  *
19679  * -1 = failed allocation.
19680  *  0 = success; burst count reached, or usable send window is too small,
19681  *      and that we'd rather wait until later before sending again.
19682  */
19683 static int
19684 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19685     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19686     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19687     const int mdt_thres)
19688 {
19689 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19690 	multidata_t	*mmd;
19691 	uint_t		obsegs, obbytes, hdr_frag_sz;
19692 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19693 	int		num_burst_seg, max_pld;
19694 	pdesc_t		*pkt;
19695 	tcp_pdescinfo_t	tcp_pkt_info;
19696 	pdescinfo_t	*pkt_info;
19697 	int		pbuf_idx, pbuf_idx_nxt;
19698 	int		seg_len, len, spill, af;
19699 	boolean_t	add_buffer, zcopy, clusterwide;
19700 	boolean_t	buf_trunked = B_FALSE;
19701 	boolean_t	rconfirm = B_FALSE;
19702 	boolean_t	done = B_FALSE;
19703 	uint32_t	cksum;
19704 	uint32_t	hwcksum_flags;
19705 	ire_t		*ire = NULL;
19706 	ill_t		*ill;
19707 	ipha_t		*ipha;
19708 	ip6_t		*ip6h;
19709 	ipaddr_t	src, dst;
19710 	ill_zerocopy_capab_t *zc_cap = NULL;
19711 	uint16_t	*up;
19712 	int		err;
19713 	conn_t		*connp;
19714 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19715 	uchar_t		*pld_start;
19716 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19717 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19718 
19719 #ifdef	_BIG_ENDIAN
19720 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19721 #else
19722 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19723 #endif
19724 
19725 #define	PREP_NEW_MULTIDATA() {			\
19726 	mmd = NULL;				\
19727 	md_mp = md_hbuf = NULL;			\
19728 	cur_hdr_off = 0;			\
19729 	max_pld = tcp->tcp_mdt_max_pld;		\
19730 	pbuf_idx = pbuf_idx_nxt = -1;		\
19731 	add_buffer = B_TRUE;			\
19732 	zcopy = B_FALSE;			\
19733 }
19734 
19735 #define	PREP_NEW_PBUF() {			\
19736 	md_pbuf = md_pbuf_nxt = NULL;		\
19737 	pbuf_idx = pbuf_idx_nxt = -1;		\
19738 	cur_pld_off = 0;			\
19739 	first_snxt = *snxt;			\
19740 	ASSERT(*tail_unsent > 0);		\
19741 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19742 }
19743 
19744 	ASSERT(mdt_thres >= mss);
19745 	ASSERT(*usable > 0 && *usable > mdt_thres);
19746 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19747 	ASSERT(!TCP_IS_DETACHED(tcp));
19748 	ASSERT(tcp->tcp_valid_bits == 0 ||
19749 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19750 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19751 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19752 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19753 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19754 
19755 	connp = tcp->tcp_connp;
19756 	ASSERT(connp != NULL);
19757 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19758 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19759 
19760 	/*
19761 	 * Note that tcp will only declare at most 2 payload spans per
19762 	 * packet, which is much lower than the maximum allowable number
19763 	 * of packet spans per Multidata.  For this reason, we use the
19764 	 * privately declared and smaller descriptor info structure, in
19765 	 * order to save some stack space.
19766 	 */
19767 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19768 
19769 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19770 	if (af == AF_INET) {
19771 		dst = tcp->tcp_ipha->ipha_dst;
19772 		src = tcp->tcp_ipha->ipha_src;
19773 		ASSERT(!CLASSD(dst));
19774 	}
19775 	ASSERT(af == AF_INET ||
19776 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19777 
19778 	obsegs = obbytes = 0;
19779 	num_burst_seg = tcp->tcp_snd_burst;
19780 	md_mp_head = NULL;
19781 	PREP_NEW_MULTIDATA();
19782 
19783 	/*
19784 	 * Before we go on further, make sure there is an IRE that we can
19785 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19786 	 * in proceeding any further, and we should just hand everything
19787 	 * off to the legacy path.
19788 	 */
19789 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19790 		goto legacy_send_no_md;
19791 
19792 	ASSERT(ire != NULL);
19793 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19794 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19795 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19796 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19797 	/*
19798 	 * If we do support loopback for MDT (which requires modifications
19799 	 * to the receiving paths), the following assertions should go away,
19800 	 * and we would be sending the Multidata to loopback conn later on.
19801 	 */
19802 	ASSERT(!IRE_IS_LOCAL(ire));
19803 	ASSERT(ire->ire_stq != NULL);
19804 
19805 	ill = ire_to_ill(ire);
19806 	ASSERT(ill != NULL);
19807 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19808 
19809 	if (!tcp->tcp_ire_ill_check_done) {
19810 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19811 		tcp->tcp_ire_ill_check_done = B_TRUE;
19812 	}
19813 
19814 	/*
19815 	 * If the underlying interface conditions have changed, or if the
19816 	 * new interface does not support MDT, go back to legacy path.
19817 	 */
19818 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19819 		/* don't go through this path anymore for this connection */
19820 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19821 		tcp->tcp_mdt = B_FALSE;
19822 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19823 		    "interface %s\n", (void *)connp, ill->ill_name));
19824 		/* IRE will be released prior to returning */
19825 		goto legacy_send_no_md;
19826 	}
19827 
19828 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19829 		zc_cap = ill->ill_zerocopy_capab;
19830 
19831 	/*
19832 	 * Check if we can take tcp fast-path. Note that "incomplete"
19833 	 * ire's (where the link-layer for next hop is not resolved
19834 	 * or where the fast-path header in nce_fp_mp is not available
19835 	 * yet) are sent down the legacy (slow) path.
19836 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19837 	 */
19838 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19839 		/* IRE will be released prior to returning */
19840 		goto legacy_send_no_md;
19841 	}
19842 
19843 	/* go to legacy path if interface doesn't support zerocopy */
19844 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19845 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19846 		/* IRE will be released prior to returning */
19847 		goto legacy_send_no_md;
19848 	}
19849 
19850 	/* does the interface support hardware checksum offload? */
19851 	hwcksum_flags = 0;
19852 	if (ILL_HCKSUM_CAPABLE(ill) &&
19853 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19854 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19855 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19856 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19857 		    HCKSUM_IPHDRCKSUM)
19858 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19859 
19860 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19861 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19862 			hwcksum_flags |= HCK_FULLCKSUM;
19863 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19864 		    HCKSUM_INET_PARTIAL)
19865 			hwcksum_flags |= HCK_PARTIALCKSUM;
19866 	}
19867 
19868 	/*
19869 	 * Each header fragment consists of the leading extra space,
19870 	 * followed by the TCP/IP header, and the trailing extra space.
19871 	 * We make sure that each header fragment begins on a 32-bit
19872 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19873 	 * aligned in tcp_mdt_update).
19874 	 */
19875 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19876 	    tcp->tcp_mdt_hdr_tail), 4);
19877 
19878 	/* are we starting from the beginning of data block? */
19879 	if (*tail_unsent == 0) {
19880 		*xmit_tail = (*xmit_tail)->b_cont;
19881 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19882 		*tail_unsent = (int)MBLKL(*xmit_tail);
19883 	}
19884 
19885 	/*
19886 	 * Here we create one or more Multidata messages, each made up of
19887 	 * one header buffer and up to N payload buffers.  This entire
19888 	 * operation is done within two loops:
19889 	 *
19890 	 * The outer loop mostly deals with creating the Multidata message,
19891 	 * as well as the header buffer that gets added to it.  It also
19892 	 * links the Multidata messages together such that all of them can
19893 	 * be sent down to the lower layer in a single putnext call; this
19894 	 * linking behavior depends on the tcp_mdt_chain tunable.
19895 	 *
19896 	 * The inner loop takes an existing Multidata message, and adds
19897 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19898 	 * packetizes those buffers by filling up the corresponding header
19899 	 * buffer fragments with the proper IP and TCP headers, and by
19900 	 * describing the layout of each packet in the packet descriptors
19901 	 * that get added to the Multidata.
19902 	 */
19903 	do {
19904 		/*
19905 		 * If usable send window is too small, or data blocks in
19906 		 * transmit list are smaller than our threshold (i.e. app
19907 		 * performs large writes followed by small ones), we hand
19908 		 * off the control over to the legacy path.  Note that we'll
19909 		 * get back the control once it encounters a large block.
19910 		 */
19911 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19912 		    (*xmit_tail)->b_cont != NULL &&
19913 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19914 			/* send down what we've got so far */
19915 			if (md_mp_head != NULL) {
19916 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19917 				    obsegs, obbytes, &rconfirm);
19918 			}
19919 			/*
19920 			 * Pass control over to tcp_send(), but tell it to
19921 			 * return to us once a large-size transmission is
19922 			 * possible.
19923 			 */
19924 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19925 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19926 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19927 			    tail_unsent, xmit_tail, local_time,
19928 			    mdt_thres)) <= 0) {
19929 				/* burst count reached, or alloc failed */
19930 				IRE_REFRELE(ire);
19931 				return (err);
19932 			}
19933 
19934 			/* tcp_send() may have sent everything, so check */
19935 			if (*usable <= 0) {
19936 				IRE_REFRELE(ire);
19937 				return (0);
19938 			}
19939 
19940 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19941 			/*
19942 			 * We may have delivered the Multidata, so make sure
19943 			 * to re-initialize before the next round.
19944 			 */
19945 			md_mp_head = NULL;
19946 			obsegs = obbytes = 0;
19947 			num_burst_seg = tcp->tcp_snd_burst;
19948 			PREP_NEW_MULTIDATA();
19949 
19950 			/* are we starting from the beginning of data block? */
19951 			if (*tail_unsent == 0) {
19952 				*xmit_tail = (*xmit_tail)->b_cont;
19953 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19954 				    (uintptr_t)INT_MAX);
19955 				*tail_unsent = (int)MBLKL(*xmit_tail);
19956 			}
19957 		}
19958 
19959 		/*
19960 		 * max_pld limits the number of mblks in tcp's transmit
19961 		 * queue that can be added to a Multidata message.  Once
19962 		 * this counter reaches zero, no more additional mblks
19963 		 * can be added to it.  What happens afterwards depends
19964 		 * on whether or not we are set to chain the Multidata
19965 		 * messages.  If we are to link them together, reset
19966 		 * max_pld to its original value (tcp_mdt_max_pld) and
19967 		 * prepare to create a new Multidata message which will
19968 		 * get linked to md_mp_head.  Else, leave it alone and
19969 		 * let the inner loop break on its own.
19970 		 */
19971 		if (tcp_mdt_chain && max_pld == 0)
19972 			PREP_NEW_MULTIDATA();
19973 
19974 		/* adding a payload buffer; re-initialize values */
19975 		if (add_buffer)
19976 			PREP_NEW_PBUF();
19977 
19978 		/*
19979 		 * If we don't have a Multidata, either because we just
19980 		 * (re)entered this outer loop, or after we branched off
19981 		 * to tcp_send above, setup the Multidata and header
19982 		 * buffer to be used.
19983 		 */
19984 		if (md_mp == NULL) {
19985 			int md_hbuflen;
19986 			uint32_t start, stuff;
19987 
19988 			/*
19989 			 * Calculate Multidata header buffer size large enough
19990 			 * to hold all of the headers that can possibly be
19991 			 * sent at this moment.  We'd rather over-estimate
19992 			 * the size than running out of space; this is okay
19993 			 * since this buffer is small anyway.
19994 			 */
19995 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19996 
19997 			/*
19998 			 * Start and stuff offset for partial hardware
19999 			 * checksum offload; these are currently for IPv4.
20000 			 * For full checksum offload, they are set to zero.
20001 			 */
20002 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20003 				if (af == AF_INET) {
20004 					start = IP_SIMPLE_HDR_LENGTH;
20005 					stuff = IP_SIMPLE_HDR_LENGTH +
20006 					    TCP_CHECKSUM_OFFSET;
20007 				} else {
20008 					start = IPV6_HDR_LEN;
20009 					stuff = IPV6_HDR_LEN +
20010 					    TCP_CHECKSUM_OFFSET;
20011 				}
20012 			} else {
20013 				start = stuff = 0;
20014 			}
20015 
20016 			/*
20017 			 * Create the header buffer, Multidata, as well as
20018 			 * any necessary attributes (destination address,
20019 			 * SAP and hardware checksum offload) that should
20020 			 * be associated with the Multidata message.
20021 			 */
20022 			ASSERT(cur_hdr_off == 0);
20023 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20024 			    ((md_hbuf->b_wptr += md_hbuflen),
20025 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20026 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20027 			    /* fastpath mblk */
20028 			    ire->ire_nce->nce_res_mp,
20029 			    /* hardware checksum enabled */
20030 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20031 			    /* hardware checksum offsets */
20032 			    start, stuff, 0,
20033 			    /* hardware checksum flag */
20034 			    hwcksum_flags, tcps) != 0)) {
20035 legacy_send:
20036 				if (md_mp != NULL) {
20037 					/* Unlink message from the chain */
20038 					if (md_mp_head != NULL) {
20039 						err = (intptr_t)rmvb(md_mp_head,
20040 						    md_mp);
20041 						/*
20042 						 * We can't assert that rmvb
20043 						 * did not return -1, since we
20044 						 * may get here before linkb
20045 						 * happens.  We do, however,
20046 						 * check if we just removed the
20047 						 * only element in the list.
20048 						 */
20049 						if (err == 0)
20050 							md_mp_head = NULL;
20051 					}
20052 					/* md_hbuf gets freed automatically */
20053 					TCP_STAT(tcps, tcp_mdt_discarded);
20054 					freeb(md_mp);
20055 				} else {
20056 					/* Either allocb or mmd_alloc failed */
20057 					TCP_STAT(tcps, tcp_mdt_allocfail);
20058 					if (md_hbuf != NULL)
20059 						freeb(md_hbuf);
20060 				}
20061 
20062 				/* send down what we've got so far */
20063 				if (md_mp_head != NULL) {
20064 					tcp_multisend_data(tcp, ire, ill,
20065 					    md_mp_head, obsegs, obbytes,
20066 					    &rconfirm);
20067 				}
20068 legacy_send_no_md:
20069 				if (ire != NULL)
20070 					IRE_REFRELE(ire);
20071 				/*
20072 				 * Too bad; let the legacy path handle this.
20073 				 * We specify INT_MAX for the threshold, since
20074 				 * we gave up with the Multidata processings
20075 				 * and let the old path have it all.
20076 				 */
20077 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20078 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20079 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20080 				    snxt, tail_unsent, xmit_tail, local_time,
20081 				    INT_MAX));
20082 			}
20083 
20084 			/* link to any existing ones, if applicable */
20085 			TCP_STAT(tcps, tcp_mdt_allocd);
20086 			if (md_mp_head == NULL) {
20087 				md_mp_head = md_mp;
20088 			} else if (tcp_mdt_chain) {
20089 				TCP_STAT(tcps, tcp_mdt_linked);
20090 				linkb(md_mp_head, md_mp);
20091 			}
20092 		}
20093 
20094 		ASSERT(md_mp_head != NULL);
20095 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20096 		ASSERT(md_mp != NULL && mmd != NULL);
20097 		ASSERT(md_hbuf != NULL);
20098 
20099 		/*
20100 		 * Packetize the transmittable portion of the data block;
20101 		 * each data block is essentially added to the Multidata
20102 		 * as a payload buffer.  We also deal with adding more
20103 		 * than one payload buffers, which happens when the remaining
20104 		 * packetized portion of the current payload buffer is less
20105 		 * than MSS, while the next data block in transmit queue
20106 		 * has enough data to make up for one.  This "spillover"
20107 		 * case essentially creates a split-packet, where portions
20108 		 * of the packet's payload fragments may span across two
20109 		 * virtually discontiguous address blocks.
20110 		 */
20111 		seg_len = mss;
20112 		do {
20113 			len = seg_len;
20114 
20115 			ASSERT(len > 0);
20116 			ASSERT(max_pld >= 0);
20117 			ASSERT(!add_buffer || cur_pld_off == 0);
20118 
20119 			/*
20120 			 * First time around for this payload buffer; note
20121 			 * in the case of a spillover, the following has
20122 			 * been done prior to adding the split-packet
20123 			 * descriptor to Multidata, and we don't want to
20124 			 * repeat the process.
20125 			 */
20126 			if (add_buffer) {
20127 				ASSERT(mmd != NULL);
20128 				ASSERT(md_pbuf == NULL);
20129 				ASSERT(md_pbuf_nxt == NULL);
20130 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20131 
20132 				/*
20133 				 * Have we reached the limit?  We'd get to
20134 				 * this case when we're not chaining the
20135 				 * Multidata messages together, and since
20136 				 * we're done, terminate this loop.
20137 				 */
20138 				if (max_pld == 0)
20139 					break; /* done */
20140 
20141 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20142 					TCP_STAT(tcps, tcp_mdt_allocfail);
20143 					goto legacy_send; /* out_of_mem */
20144 				}
20145 
20146 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20147 				    zc_cap != NULL) {
20148 					if (!ip_md_zcopy_attr(mmd, NULL,
20149 					    zc_cap->ill_zerocopy_flags)) {
20150 						freeb(md_pbuf);
20151 						TCP_STAT(tcps,
20152 						    tcp_mdt_allocfail);
20153 						/* out_of_mem */
20154 						goto legacy_send;
20155 					}
20156 					zcopy = B_TRUE;
20157 				}
20158 
20159 				md_pbuf->b_rptr += base_pld_off;
20160 
20161 				/*
20162 				 * Add a payload buffer to the Multidata; this
20163 				 * operation must not fail, or otherwise our
20164 				 * logic in this routine is broken.  There
20165 				 * is no memory allocation done by the
20166 				 * routine, so any returned failure simply
20167 				 * tells us that we've done something wrong.
20168 				 *
20169 				 * A failure tells us that either we're adding
20170 				 * the same payload buffer more than once, or
20171 				 * we're trying to add more buffers than
20172 				 * allowed (max_pld calculation is wrong).
20173 				 * None of the above cases should happen, and
20174 				 * we panic because either there's horrible
20175 				 * heap corruption, and/or programming mistake.
20176 				 */
20177 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20178 				if (pbuf_idx < 0) {
20179 					cmn_err(CE_PANIC, "tcp_multisend: "
20180 					    "payload buffer logic error "
20181 					    "detected for tcp %p mmd %p "
20182 					    "pbuf %p (%d)\n",
20183 					    (void *)tcp, (void *)mmd,
20184 					    (void *)md_pbuf, pbuf_idx);
20185 				}
20186 
20187 				ASSERT(max_pld > 0);
20188 				--max_pld;
20189 				add_buffer = B_FALSE;
20190 			}
20191 
20192 			ASSERT(md_mp_head != NULL);
20193 			ASSERT(md_pbuf != NULL);
20194 			ASSERT(md_pbuf_nxt == NULL);
20195 			ASSERT(pbuf_idx != -1);
20196 			ASSERT(pbuf_idx_nxt == -1);
20197 			ASSERT(*usable > 0);
20198 
20199 			/*
20200 			 * We spillover to the next payload buffer only
20201 			 * if all of the following is true:
20202 			 *
20203 			 *   1. There is not enough data on the current
20204 			 *	payload buffer to make up `len',
20205 			 *   2. We are allowed to send `len',
20206 			 *   3. The next payload buffer length is large
20207 			 *	enough to accomodate `spill'.
20208 			 */
20209 			if ((spill = len - *tail_unsent) > 0 &&
20210 			    *usable >= len &&
20211 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20212 			    max_pld > 0) {
20213 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20214 				if (md_pbuf_nxt == NULL) {
20215 					TCP_STAT(tcps, tcp_mdt_allocfail);
20216 					goto legacy_send; /* out_of_mem */
20217 				}
20218 
20219 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20220 				    zc_cap != NULL) {
20221 					if (!ip_md_zcopy_attr(mmd, NULL,
20222 					    zc_cap->ill_zerocopy_flags)) {
20223 						freeb(md_pbuf_nxt);
20224 						TCP_STAT(tcps,
20225 						    tcp_mdt_allocfail);
20226 						/* out_of_mem */
20227 						goto legacy_send;
20228 					}
20229 					zcopy = B_TRUE;
20230 				}
20231 
20232 				/*
20233 				 * See comments above on the first call to
20234 				 * mmd_addpldbuf for explanation on the panic.
20235 				 */
20236 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20237 				if (pbuf_idx_nxt < 0) {
20238 					panic("tcp_multisend: "
20239 					    "next payload buffer logic error "
20240 					    "detected for tcp %p mmd %p "
20241 					    "pbuf %p (%d)\n",
20242 					    (void *)tcp, (void *)mmd,
20243 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20244 				}
20245 
20246 				ASSERT(max_pld > 0);
20247 				--max_pld;
20248 			} else if (spill > 0) {
20249 				/*
20250 				 * If there's a spillover, but the following
20251 				 * xmit_tail couldn't give us enough octets
20252 				 * to reach "len", then stop the current
20253 				 * Multidata creation and let the legacy
20254 				 * tcp_send() path take over.  We don't want
20255 				 * to send the tiny segment as part of this
20256 				 * Multidata for performance reasons; instead,
20257 				 * we let the legacy path deal with grouping
20258 				 * it with the subsequent small mblks.
20259 				 */
20260 				if (*usable >= len &&
20261 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20262 					max_pld = 0;
20263 					break;	/* done */
20264 				}
20265 
20266 				/*
20267 				 * We can't spillover, and we are near
20268 				 * the end of the current payload buffer,
20269 				 * so send what's left.
20270 				 */
20271 				ASSERT(*tail_unsent > 0);
20272 				len = *tail_unsent;
20273 			}
20274 
20275 			/* tail_unsent is negated if there is a spillover */
20276 			*tail_unsent -= len;
20277 			*usable -= len;
20278 			ASSERT(*usable >= 0);
20279 
20280 			if (*usable < mss)
20281 				seg_len = *usable;
20282 			/*
20283 			 * Sender SWS avoidance; see comments in tcp_send();
20284 			 * everything else is the same, except that we only
20285 			 * do this here if there is no more data to be sent
20286 			 * following the current xmit_tail.  We don't check
20287 			 * for 1-byte urgent data because we shouldn't get
20288 			 * here if TCP_URG_VALID is set.
20289 			 */
20290 			if (*usable > 0 && *usable < mss &&
20291 			    ((md_pbuf_nxt == NULL &&
20292 			    (*xmit_tail)->b_cont == NULL) ||
20293 			    (md_pbuf_nxt != NULL &&
20294 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20295 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20296 			    (tcp->tcp_unsent -
20297 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20298 			    !tcp->tcp_zero_win_probe) {
20299 				if ((*snxt + len) == tcp->tcp_snxt &&
20300 				    (*snxt + len) == tcp->tcp_suna) {
20301 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20302 				}
20303 				done = B_TRUE;
20304 			}
20305 
20306 			/*
20307 			 * Prime pump for IP's checksumming on our behalf;
20308 			 * include the adjustment for a source route if any.
20309 			 * Do this only for software/partial hardware checksum
20310 			 * offload, as this field gets zeroed out later for
20311 			 * the full hardware checksum offload case.
20312 			 */
20313 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20314 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20315 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20316 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20317 			}
20318 
20319 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20320 			*snxt += len;
20321 
20322 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20323 			/*
20324 			 * We set the PUSH bit only if TCP has no more buffered
20325 			 * data to be transmitted (or if sender SWS avoidance
20326 			 * takes place), as opposed to setting it for every
20327 			 * last packet in the burst.
20328 			 */
20329 			if (done ||
20330 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20331 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20332 
20333 			/*
20334 			 * Set FIN bit if this is our last segment; snxt
20335 			 * already includes its length, and it will not
20336 			 * be adjusted after this point.
20337 			 */
20338 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20339 			    *snxt == tcp->tcp_fss) {
20340 				if (!tcp->tcp_fin_acked) {
20341 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20342 					BUMP_MIB(&tcps->tcps_mib,
20343 					    tcpOutControl);
20344 				}
20345 				if (!tcp->tcp_fin_sent) {
20346 					tcp->tcp_fin_sent = B_TRUE;
20347 					/*
20348 					 * tcp state must be ESTABLISHED
20349 					 * in order for us to get here in
20350 					 * the first place.
20351 					 */
20352 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20353 
20354 					/*
20355 					 * Upon returning from this routine,
20356 					 * tcp_wput_data() will set tcp_snxt
20357 					 * to be equal to snxt + tcp_fin_sent.
20358 					 * This is essentially the same as
20359 					 * setting it to tcp_fss + 1.
20360 					 */
20361 				}
20362 			}
20363 
20364 			tcp->tcp_last_sent_len = (ushort_t)len;
20365 
20366 			len += tcp_hdr_len;
20367 			if (tcp->tcp_ipversion == IPV4_VERSION)
20368 				tcp->tcp_ipha->ipha_length = htons(len);
20369 			else
20370 				tcp->tcp_ip6h->ip6_plen = htons(len -
20371 				    ((char *)&tcp->tcp_ip6h[1] -
20372 				    tcp->tcp_iphc));
20373 
20374 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20375 
20376 			/* setup header fragment */
20377 			PDESC_HDR_ADD(pkt_info,
20378 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20379 			    tcp->tcp_mdt_hdr_head,		/* head room */
20380 			    tcp_hdr_len,			/* len */
20381 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20382 
20383 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20384 			    hdr_frag_sz);
20385 			ASSERT(MBLKIN(md_hbuf,
20386 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20387 			    PDESC_HDRSIZE(pkt_info)));
20388 
20389 			/* setup first payload fragment */
20390 			PDESC_PLD_INIT(pkt_info);
20391 			PDESC_PLD_SPAN_ADD(pkt_info,
20392 			    pbuf_idx,				/* index */
20393 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20394 			    tcp->tcp_last_sent_len);		/* len */
20395 
20396 			/* create a split-packet in case of a spillover */
20397 			if (md_pbuf_nxt != NULL) {
20398 				ASSERT(spill > 0);
20399 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20400 				ASSERT(!add_buffer);
20401 
20402 				md_pbuf = md_pbuf_nxt;
20403 				md_pbuf_nxt = NULL;
20404 				pbuf_idx = pbuf_idx_nxt;
20405 				pbuf_idx_nxt = -1;
20406 				cur_pld_off = spill;
20407 
20408 				/* trim out first payload fragment */
20409 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20410 
20411 				/* setup second payload fragment */
20412 				PDESC_PLD_SPAN_ADD(pkt_info,
20413 				    pbuf_idx,			/* index */
20414 				    md_pbuf->b_rptr,		/* start */
20415 				    spill);			/* len */
20416 
20417 				if ((*xmit_tail)->b_next == NULL) {
20418 					/*
20419 					 * Store the lbolt used for RTT
20420 					 * estimation. We can only record one
20421 					 * timestamp per mblk so we do it when
20422 					 * we reach the end of the payload
20423 					 * buffer.  Also we only take a new
20424 					 * timestamp sample when the previous
20425 					 * timed data from the same mblk has
20426 					 * been ack'ed.
20427 					 */
20428 					(*xmit_tail)->b_prev = local_time;
20429 					(*xmit_tail)->b_next =
20430 					    (mblk_t *)(uintptr_t)first_snxt;
20431 				}
20432 
20433 				first_snxt = *snxt - spill;
20434 
20435 				/*
20436 				 * Advance xmit_tail; usable could be 0 by
20437 				 * the time we got here, but we made sure
20438 				 * above that we would only spillover to
20439 				 * the next data block if usable includes
20440 				 * the spilled-over amount prior to the
20441 				 * subtraction.  Therefore, we are sure
20442 				 * that xmit_tail->b_cont can't be NULL.
20443 				 */
20444 				ASSERT((*xmit_tail)->b_cont != NULL);
20445 				*xmit_tail = (*xmit_tail)->b_cont;
20446 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20447 				    (uintptr_t)INT_MAX);
20448 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20449 			} else {
20450 				cur_pld_off += tcp->tcp_last_sent_len;
20451 			}
20452 
20453 			/*
20454 			 * Fill in the header using the template header, and
20455 			 * add options such as time-stamp, ECN and/or SACK,
20456 			 * as needed.
20457 			 */
20458 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20459 			    (clock_t)local_time, num_sack_blk);
20460 
20461 			/* take care of some IP header businesses */
20462 			if (af == AF_INET) {
20463 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20464 
20465 				ASSERT(OK_32PTR((uchar_t *)ipha));
20466 				ASSERT(PDESC_HDRL(pkt_info) >=
20467 				    IP_SIMPLE_HDR_LENGTH);
20468 				ASSERT(ipha->ipha_version_and_hdr_length ==
20469 				    IP_SIMPLE_HDR_VERSION);
20470 
20471 				/*
20472 				 * Assign ident value for current packet; see
20473 				 * related comments in ip_wput_ire() about the
20474 				 * contract private interface with clustering
20475 				 * group.
20476 				 */
20477 				clusterwide = B_FALSE;
20478 				if (cl_inet_ipident != NULL) {
20479 					ASSERT(cl_inet_isclusterwide != NULL);
20480 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20481 					    AF_INET,
20482 					    (uint8_t *)(uintptr_t)src)) {
20483 						ipha->ipha_ident =
20484 						    (*cl_inet_ipident)
20485 						    (IPPROTO_IP, AF_INET,
20486 						    (uint8_t *)(uintptr_t)src,
20487 						    (uint8_t *)(uintptr_t)dst);
20488 						clusterwide = B_TRUE;
20489 					}
20490 				}
20491 
20492 				if (!clusterwide) {
20493 					ipha->ipha_ident = (uint16_t)
20494 					    atomic_add_32_nv(
20495 						&ire->ire_ident, 1);
20496 				}
20497 #ifndef _BIG_ENDIAN
20498 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20499 				    (ipha->ipha_ident >> 8);
20500 #endif
20501 			} else {
20502 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20503 
20504 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20505 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20506 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20507 				ASSERT(PDESC_HDRL(pkt_info) >=
20508 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20509 				    TCP_CHECKSUM_SIZE));
20510 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20511 
20512 				if (tcp->tcp_ip_forward_progress) {
20513 					rconfirm = B_TRUE;
20514 					tcp->tcp_ip_forward_progress = B_FALSE;
20515 				}
20516 			}
20517 
20518 			/* at least one payload span, and at most two */
20519 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20520 
20521 			/* add the packet descriptor to Multidata */
20522 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20523 			    KM_NOSLEEP)) == NULL) {
20524 				/*
20525 				 * Any failure other than ENOMEM indicates
20526 				 * that we have passed in invalid pkt_info
20527 				 * or parameters to mmd_addpdesc, which must
20528 				 * not happen.
20529 				 *
20530 				 * EINVAL is a result of failure on boundary
20531 				 * checks against the pkt_info contents.  It
20532 				 * should not happen, and we panic because
20533 				 * either there's horrible heap corruption,
20534 				 * and/or programming mistake.
20535 				 */
20536 				if (err != ENOMEM) {
20537 					cmn_err(CE_PANIC, "tcp_multisend: "
20538 					    "pdesc logic error detected for "
20539 					    "tcp %p mmd %p pinfo %p (%d)\n",
20540 					    (void *)tcp, (void *)mmd,
20541 					    (void *)pkt_info, err);
20542 				}
20543 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20544 				goto legacy_send; /* out_of_mem */
20545 			}
20546 			ASSERT(pkt != NULL);
20547 
20548 			/* calculate IP header and TCP checksums */
20549 			if (af == AF_INET) {
20550 				/* calculate pseudo-header checksum */
20551 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20552 				    (src >> 16) + (src & 0xFFFF);
20553 
20554 				/* offset for TCP header checksum */
20555 				up = IPH_TCPH_CHECKSUMP(ipha,
20556 				    IP_SIMPLE_HDR_LENGTH);
20557 			} else {
20558 				up = (uint16_t *)&ip6h->ip6_src;
20559 
20560 				/* calculate pseudo-header checksum */
20561 				cksum = up[0] + up[1] + up[2] + up[3] +
20562 				    up[4] + up[5] + up[6] + up[7] +
20563 				    up[8] + up[9] + up[10] + up[11] +
20564 				    up[12] + up[13] + up[14] + up[15];
20565 
20566 				/* Fold the initial sum */
20567 				cksum = (cksum & 0xffff) + (cksum >> 16);
20568 
20569 				up = (uint16_t *)(((uchar_t *)ip6h) +
20570 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20571 			}
20572 
20573 			if (hwcksum_flags & HCK_FULLCKSUM) {
20574 				/* clear checksum field for hardware */
20575 				*up = 0;
20576 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20577 				uint32_t sum;
20578 
20579 				/* pseudo-header checksumming */
20580 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20581 				sum = (sum & 0xFFFF) + (sum >> 16);
20582 				*up = (sum & 0xFFFF) + (sum >> 16);
20583 			} else {
20584 				/* software checksumming */
20585 				TCP_STAT(tcps, tcp_out_sw_cksum);
20586 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20587 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20588 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20589 				    cksum + IP_TCP_CSUM_COMP);
20590 				if (*up == 0)
20591 					*up = 0xFFFF;
20592 			}
20593 
20594 			/* IPv4 header checksum */
20595 			if (af == AF_INET) {
20596 				ipha->ipha_fragment_offset_and_flags |=
20597 				    (uint32_t)htons(ire->ire_frag_flag);
20598 
20599 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20600 					ipha->ipha_hdr_checksum = 0;
20601 				} else {
20602 					IP_HDR_CKSUM(ipha, cksum,
20603 					    ((uint32_t *)ipha)[0],
20604 					    ((uint16_t *)ipha)[4]);
20605 				}
20606 			}
20607 
20608 			if (af == AF_INET &&
20609 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20610 			    af == AF_INET6 &&
20611 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20612 				/* build header(IP/TCP) mblk for this segment */
20613 				if ((mp = dupb(md_hbuf)) == NULL)
20614 					goto legacy_send;
20615 
20616 				mp->b_rptr = pkt_info->hdr_rptr;
20617 				mp->b_wptr = pkt_info->hdr_wptr;
20618 
20619 				/* build payload mblk for this segment */
20620 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20621 					freemsg(mp);
20622 					goto legacy_send;
20623 				}
20624 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20625 				mp1->b_rptr = mp1->b_wptr -
20626 				    tcp->tcp_last_sent_len;
20627 				linkb(mp, mp1);
20628 
20629 				pld_start = mp1->b_rptr;
20630 
20631 				if (af == AF_INET) {
20632 					DTRACE_PROBE4(
20633 					    ip4__physical__out__start,
20634 					    ill_t *, NULL,
20635 					    ill_t *, ill,
20636 					    ipha_t *, ipha,
20637 					    mblk_t *, mp);
20638 					FW_HOOKS(
20639 					    ipst->ips_ip4_physical_out_event,
20640 					    ipst->ips_ipv4firewall_physical_out,
20641 					    NULL, ill, ipha, mp, mp, ipst);
20642 					DTRACE_PROBE1(
20643 					    ip4__physical__out__end,
20644 					    mblk_t *, mp);
20645 				} else {
20646 					DTRACE_PROBE4(
20647 					    ip6__physical__out_start,
20648 					    ill_t *, NULL,
20649 					    ill_t *, ill,
20650 					    ip6_t *, ip6h,
20651 					    mblk_t *, mp);
20652 					FW_HOOKS6(
20653 					    ipst->ips_ip6_physical_out_event,
20654 					    ipst->ips_ipv6firewall_physical_out,
20655 					    NULL, ill, ip6h, mp, mp, ipst);
20656 					DTRACE_PROBE1(
20657 					    ip6__physical__out__end,
20658 					    mblk_t *, mp);
20659 				}
20660 
20661 				if (buf_trunked && mp != NULL) {
20662 					/*
20663 					 * Need to pass it to normal path.
20664 					 */
20665 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20666 				} else if (mp == NULL ||
20667 				    mp->b_rptr != pkt_info->hdr_rptr ||
20668 				    mp->b_wptr != pkt_info->hdr_wptr ||
20669 				    (mp1 = mp->b_cont) == NULL ||
20670 				    mp1->b_rptr != pld_start ||
20671 				    mp1->b_wptr != pld_start +
20672 				    tcp->tcp_last_sent_len ||
20673 				    mp1->b_cont != NULL) {
20674 					/*
20675 					 * Need to pass all packets of this
20676 					 * buffer to normal path, either when
20677 					 * packet is blocked, or when boundary
20678 					 * of header buffer or payload buffer
20679 					 * has been changed by FW_HOOKS[6].
20680 					 */
20681 					buf_trunked = B_TRUE;
20682 					if (md_mp_head != NULL) {
20683 						err = (intptr_t)rmvb(md_mp_head,
20684 						    md_mp);
20685 						if (err == 0)
20686 							md_mp_head = NULL;
20687 					}
20688 
20689 					/* send down what we've got so far */
20690 					if (md_mp_head != NULL) {
20691 						tcp_multisend_data(tcp, ire,
20692 						    ill, md_mp_head, obsegs,
20693 						    obbytes, &rconfirm);
20694 					}
20695 					md_mp_head = NULL;
20696 
20697 					if (mp != NULL)
20698 						CALL_IP_WPUT(tcp->tcp_connp,
20699 						    q, mp);
20700 
20701 					mp1 = fw_mp_head;
20702 					do {
20703 						mp = mp1;
20704 						mp1 = mp1->b_next;
20705 						mp->b_next = NULL;
20706 						mp->b_prev = NULL;
20707 						CALL_IP_WPUT(tcp->tcp_connp,
20708 						    q, mp);
20709 					} while (mp1 != NULL);
20710 
20711 					fw_mp_head = NULL;
20712 				} else {
20713 					if (fw_mp_head == NULL)
20714 						fw_mp_head = mp;
20715 					else
20716 						fw_mp_head->b_prev->b_next = mp;
20717 					fw_mp_head->b_prev = mp;
20718 				}
20719 			}
20720 
20721 			/* advance header offset */
20722 			cur_hdr_off += hdr_frag_sz;
20723 
20724 			obbytes += tcp->tcp_last_sent_len;
20725 			++obsegs;
20726 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20727 		    *tail_unsent > 0);
20728 
20729 		if ((*xmit_tail)->b_next == NULL) {
20730 			/*
20731 			 * Store the lbolt used for RTT estimation. We can only
20732 			 * record one timestamp per mblk so we do it when we
20733 			 * reach the end of the payload buffer. Also we only
20734 			 * take a new timestamp sample when the previous timed
20735 			 * data from the same mblk has been ack'ed.
20736 			 */
20737 			(*xmit_tail)->b_prev = local_time;
20738 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20739 		}
20740 
20741 		ASSERT(*tail_unsent >= 0);
20742 		if (*tail_unsent > 0) {
20743 			/*
20744 			 * We got here because we broke out of the above
20745 			 * loop due to of one of the following cases:
20746 			 *
20747 			 *   1. len < adjusted MSS (i.e. small),
20748 			 *   2. Sender SWS avoidance,
20749 			 *   3. max_pld is zero.
20750 			 *
20751 			 * We are done for this Multidata, so trim our
20752 			 * last payload buffer (if any) accordingly.
20753 			 */
20754 			if (md_pbuf != NULL)
20755 				md_pbuf->b_wptr -= *tail_unsent;
20756 		} else if (*usable > 0) {
20757 			*xmit_tail = (*xmit_tail)->b_cont;
20758 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20759 			    (uintptr_t)INT_MAX);
20760 			*tail_unsent = (int)MBLKL(*xmit_tail);
20761 			add_buffer = B_TRUE;
20762 		}
20763 
20764 		while (fw_mp_head) {
20765 			mp = fw_mp_head;
20766 			fw_mp_head = fw_mp_head->b_next;
20767 			mp->b_prev = mp->b_next = NULL;
20768 			freemsg(mp);
20769 		}
20770 		if (buf_trunked) {
20771 			TCP_STAT(tcps, tcp_mdt_discarded);
20772 			freeb(md_mp);
20773 			buf_trunked = B_FALSE;
20774 		}
20775 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20776 	    (tcp_mdt_chain || max_pld > 0));
20777 
20778 	if (md_mp_head != NULL) {
20779 		/* send everything down */
20780 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20781 		    &rconfirm);
20782 	}
20783 
20784 #undef PREP_NEW_MULTIDATA
20785 #undef PREP_NEW_PBUF
20786 #undef IPVER
20787 
20788 	IRE_REFRELE(ire);
20789 	return (0);
20790 }
20791 
20792 /*
20793  * A wrapper function for sending one or more Multidata messages down to
20794  * the module below ip; this routine does not release the reference of the
20795  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20796  */
20797 static void
20798 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20799     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20800 {
20801 	uint64_t delta;
20802 	nce_t *nce;
20803 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20804 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20805 
20806 	ASSERT(ire != NULL && ill != NULL);
20807 	ASSERT(ire->ire_stq != NULL);
20808 	ASSERT(md_mp_head != NULL);
20809 	ASSERT(rconfirm != NULL);
20810 
20811 	/* adjust MIBs and IRE timestamp */
20812 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20813 	tcp->tcp_obsegs += obsegs;
20814 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20815 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20816 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20817 
20818 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20819 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20820 	} else {
20821 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20822 	}
20823 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20824 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20825 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20826 
20827 	ire->ire_ob_pkt_count += obsegs;
20828 	if (ire->ire_ipif != NULL)
20829 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20830 	ire->ire_last_used_time = lbolt;
20831 
20832 	/* send it down */
20833 	putnext(ire->ire_stq, md_mp_head);
20834 
20835 	/* we're done for TCP/IPv4 */
20836 	if (tcp->tcp_ipversion == IPV4_VERSION)
20837 		return;
20838 
20839 	nce = ire->ire_nce;
20840 
20841 	ASSERT(nce != NULL);
20842 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20843 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20844 
20845 	/* reachability confirmation? */
20846 	if (*rconfirm) {
20847 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20848 		if (nce->nce_state != ND_REACHABLE) {
20849 			mutex_enter(&nce->nce_lock);
20850 			nce->nce_state = ND_REACHABLE;
20851 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20852 			mutex_exit(&nce->nce_lock);
20853 			(void) untimeout(nce->nce_timeout_id);
20854 			if (ip_debug > 2) {
20855 				/* ip1dbg */
20856 				pr_addr_dbg("tcp_multisend_data: state "
20857 				    "for %s changed to REACHABLE\n",
20858 				    AF_INET6, &ire->ire_addr_v6);
20859 			}
20860 		}
20861 		/* reset transport reachability confirmation */
20862 		*rconfirm = B_FALSE;
20863 	}
20864 
20865 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20866 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20867 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20868 
20869 	if (delta > (uint64_t)ill->ill_reachable_time) {
20870 		mutex_enter(&nce->nce_lock);
20871 		switch (nce->nce_state) {
20872 		case ND_REACHABLE:
20873 		case ND_STALE:
20874 			/*
20875 			 * ND_REACHABLE is identical to ND_STALE in this
20876 			 * specific case. If reachable time has expired for
20877 			 * this neighbor (delta is greater than reachable
20878 			 * time), conceptually, the neighbor cache is no
20879 			 * longer in REACHABLE state, but already in STALE
20880 			 * state.  So the correct transition here is to
20881 			 * ND_DELAY.
20882 			 */
20883 			nce->nce_state = ND_DELAY;
20884 			mutex_exit(&nce->nce_lock);
20885 			NDP_RESTART_TIMER(nce,
20886 			    ipst->ips_delay_first_probe_time);
20887 			if (ip_debug > 3) {
20888 				/* ip2dbg */
20889 				pr_addr_dbg("tcp_multisend_data: state "
20890 				    "for %s changed to DELAY\n",
20891 				    AF_INET6, &ire->ire_addr_v6);
20892 			}
20893 			break;
20894 		case ND_DELAY:
20895 		case ND_PROBE:
20896 			mutex_exit(&nce->nce_lock);
20897 			/* Timers have already started */
20898 			break;
20899 		case ND_UNREACHABLE:
20900 			/*
20901 			 * ndp timer has detected that this nce is
20902 			 * unreachable and initiated deleting this nce
20903 			 * and all its associated IREs. This is a race
20904 			 * where we found the ire before it was deleted
20905 			 * and have just sent out a packet using this
20906 			 * unreachable nce.
20907 			 */
20908 			mutex_exit(&nce->nce_lock);
20909 			break;
20910 		default:
20911 			ASSERT(0);
20912 		}
20913 	}
20914 }
20915 
20916 /*
20917  * Derived from tcp_send_data().
20918  */
20919 static void
20920 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20921     int num_lso_seg)
20922 {
20923 	ipha_t		*ipha;
20924 	mblk_t		*ire_fp_mp;
20925 	uint_t		ire_fp_mp_len;
20926 	uint32_t	hcksum_txflags = 0;
20927 	ipaddr_t	src;
20928 	ipaddr_t	dst;
20929 	uint32_t	cksum;
20930 	uint16_t	*up;
20931 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20932 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20933 
20934 	ASSERT(DB_TYPE(mp) == M_DATA);
20935 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20936 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20937 	ASSERT(tcp->tcp_connp != NULL);
20938 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20939 
20940 	ipha = (ipha_t *)mp->b_rptr;
20941 	src = ipha->ipha_src;
20942 	dst = ipha->ipha_dst;
20943 
20944 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20945 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20946 	    num_lso_seg);
20947 #ifndef _BIG_ENDIAN
20948 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20949 #endif
20950 	if (tcp->tcp_snd_zcopy_aware) {
20951 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20952 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20953 			mp = tcp_zcopy_disable(tcp, mp);
20954 	}
20955 
20956 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20957 		ASSERT(ill->ill_hcksum_capab != NULL);
20958 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20959 	}
20960 
20961 	/*
20962 	 * Since the TCP checksum should be recalculated by h/w, we can just
20963 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20964 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20965 	 * The partial pseudo-header excludes TCP length, that was calculated
20966 	 * in tcp_send(), so to zero *up before further processing.
20967 	 */
20968 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20969 
20970 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20971 	*up = 0;
20972 
20973 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20974 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20975 
20976 	/*
20977 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
20978 	 */
20979 	DB_LSOFLAGS(mp) |= HW_LSO;
20980 	DB_LSOMSS(mp) = mss;
20981 
20982 	ipha->ipha_fragment_offset_and_flags |=
20983 	    (uint32_t)htons(ire->ire_frag_flag);
20984 
20985 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20986 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20987 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20988 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20989 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20990 
20991 	UPDATE_OB_PKT_COUNT(ire);
20992 	ire->ire_last_used_time = lbolt;
20993 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20994 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20995 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20996 	    ntohs(ipha->ipha_length));
20997 
20998 	if (ILL_DLS_CAPABLE(ill)) {
20999 		/*
21000 		 * Send the packet directly to DLD, where it may be queued
21001 		 * depending on the availability of transmit resources at
21002 		 * the media layer.
21003 		 */
21004 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
21005 	} else {
21006 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
21007 		DTRACE_PROBE4(ip4__physical__out__start,
21008 		    ill_t *, NULL, ill_t *, out_ill,
21009 		    ipha_t *, ipha, mblk_t *, mp);
21010 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
21011 		    ipst->ips_ipv4firewall_physical_out,
21012 		    NULL, out_ill, ipha, mp, mp, ipst);
21013 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21014 		if (mp != NULL)
21015 			putnext(ire->ire_stq, mp);
21016 	}
21017 }
21018 
21019 /*
21020  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21021  * scheme, and returns one of the following:
21022  *
21023  * -1 = failed allocation.
21024  *  0 = success; burst count reached, or usable send window is too small,
21025  *      and that we'd rather wait until later before sending again.
21026  *  1 = success; we are called from tcp_multisend(), and both usable send
21027  *      window and tail_unsent are greater than the MDT threshold, and thus
21028  *      Multidata Transmit should be used instead.
21029  */
21030 static int
21031 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21032     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21033     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21034     const int mdt_thres)
21035 {
21036 	int num_burst_seg = tcp->tcp_snd_burst;
21037 	ire_t		*ire = NULL;
21038 	ill_t		*ill = NULL;
21039 	mblk_t		*ire_fp_mp = NULL;
21040 	uint_t		ire_fp_mp_len = 0;
21041 	int		num_lso_seg = 1;
21042 	uint_t		lso_usable;
21043 	boolean_t	do_lso_send = B_FALSE;
21044 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21045 
21046 	/*
21047 	 * Check LSO capability before any further work. And the similar check
21048 	 * need to be done in for(;;) loop.
21049 	 * LSO will be deployed when therer is more than one mss of available
21050 	 * data and a burst transmission is allowed.
21051 	 */
21052 	if (tcp->tcp_lso &&
21053 	    (tcp->tcp_valid_bits == 0 ||
21054 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21055 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21056 		/*
21057 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21058 		 */
21059 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21060 			/*
21061 			 * Enable LSO with this transmission.
21062 			 * Since IRE has been hold in
21063 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21064 			 * should be called before return.
21065 			 */
21066 			do_lso_send = B_TRUE;
21067 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21068 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21069 			/* Round up to multiple of 4 */
21070 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21071 		} else {
21072 			do_lso_send = B_FALSE;
21073 			ill = NULL;
21074 		}
21075 	}
21076 
21077 	for (;;) {
21078 		struct datab	*db;
21079 		tcph_t		*tcph;
21080 		uint32_t	sum;
21081 		mblk_t		*mp, *mp1;
21082 		uchar_t		*rptr;
21083 		int		len;
21084 
21085 		/*
21086 		 * If we're called by tcp_multisend(), and the amount of
21087 		 * sendable data as well as the size of current xmit_tail
21088 		 * is beyond the MDT threshold, return to the caller and
21089 		 * let the large data transmit be done using MDT.
21090 		 */
21091 		if (*usable > 0 && *usable > mdt_thres &&
21092 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21093 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21094 			ASSERT(tcp->tcp_mdt);
21095 			return (1);	/* success; do large send */
21096 		}
21097 
21098 		if (num_burst_seg == 0)
21099 			break;		/* success; burst count reached */
21100 
21101 		/*
21102 		 * Calculate the maximum payload length we can send in *one*
21103 		 * time.
21104 		 */
21105 		if (do_lso_send) {
21106 			/*
21107 			 * Check whether need to do LSO any more.
21108 			 */
21109 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21110 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21111 				lso_usable = MIN(lso_usable,
21112 				    num_burst_seg * mss);
21113 
21114 				num_lso_seg = lso_usable / mss;
21115 				if (lso_usable % mss) {
21116 					num_lso_seg++;
21117 					tcp->tcp_last_sent_len = (ushort_t)
21118 					    (lso_usable % mss);
21119 				} else {
21120 					tcp->tcp_last_sent_len = (ushort_t)mss;
21121 				}
21122 			} else {
21123 				do_lso_send = B_FALSE;
21124 				num_lso_seg = 1;
21125 				lso_usable = mss;
21126 			}
21127 		}
21128 
21129 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21130 
21131 		/*
21132 		 * Adjust num_burst_seg here.
21133 		 */
21134 		num_burst_seg -= num_lso_seg;
21135 
21136 		len = mss;
21137 		if (len > *usable) {
21138 			ASSERT(do_lso_send == B_FALSE);
21139 
21140 			len = *usable;
21141 			if (len <= 0) {
21142 				/* Terminate the loop */
21143 				break;	/* success; too small */
21144 			}
21145 			/*
21146 			 * Sender silly-window avoidance.
21147 			 * Ignore this if we are going to send a
21148 			 * zero window probe out.
21149 			 *
21150 			 * TODO: force data into microscopic window?
21151 			 *	==> (!pushed || (unsent > usable))
21152 			 */
21153 			if (len < (tcp->tcp_max_swnd >> 1) &&
21154 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21155 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21156 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21157 				/*
21158 				 * If the retransmit timer is not running
21159 				 * we start it so that we will retransmit
21160 				 * in the case when the the receiver has
21161 				 * decremented the window.
21162 				 */
21163 				if (*snxt == tcp->tcp_snxt &&
21164 				    *snxt == tcp->tcp_suna) {
21165 					/*
21166 					 * We are not supposed to send
21167 					 * anything.  So let's wait a little
21168 					 * bit longer before breaking SWS
21169 					 * avoidance.
21170 					 *
21171 					 * What should the value be?
21172 					 * Suggestion: MAX(init rexmit time,
21173 					 * tcp->tcp_rto)
21174 					 */
21175 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21176 				}
21177 				break;	/* success; too small */
21178 			}
21179 		}
21180 
21181 		tcph = tcp->tcp_tcph;
21182 
21183 		/*
21184 		 * The reason to adjust len here is that we need to set flags
21185 		 * and calculate checksum.
21186 		 */
21187 		if (do_lso_send)
21188 			len = lso_usable;
21189 
21190 		*usable -= len; /* Approximate - can be adjusted later */
21191 		if (*usable > 0)
21192 			tcph->th_flags[0] = TH_ACK;
21193 		else
21194 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21195 
21196 		/*
21197 		 * Prime pump for IP's checksumming on our behalf
21198 		 * Include the adjustment for a source route if any.
21199 		 */
21200 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21201 		sum = (sum >> 16) + (sum & 0xFFFF);
21202 		U16_TO_ABE16(sum, tcph->th_sum);
21203 
21204 		U32_TO_ABE32(*snxt, tcph->th_seq);
21205 
21206 		/*
21207 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21208 		 * set.  For the case when TCP_FSS_VALID is the only valid
21209 		 * bit (normal active close), branch off only when we think
21210 		 * that the FIN flag needs to be set.  Note for this case,
21211 		 * that (snxt + len) may not reflect the actual seg_len,
21212 		 * as len may be further reduced in tcp_xmit_mp().  If len
21213 		 * gets modified, we will end up here again.
21214 		 */
21215 		if (tcp->tcp_valid_bits != 0 &&
21216 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21217 		    ((*snxt + len) == tcp->tcp_fss))) {
21218 			uchar_t		*prev_rptr;
21219 			uint32_t	prev_snxt = tcp->tcp_snxt;
21220 
21221 			if (*tail_unsent == 0) {
21222 				ASSERT((*xmit_tail)->b_cont != NULL);
21223 				*xmit_tail = (*xmit_tail)->b_cont;
21224 				prev_rptr = (*xmit_tail)->b_rptr;
21225 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21226 				    (*xmit_tail)->b_rptr);
21227 			} else {
21228 				prev_rptr = (*xmit_tail)->b_rptr;
21229 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21230 				    *tail_unsent;
21231 			}
21232 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21233 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21234 			/* Restore tcp_snxt so we get amount sent right. */
21235 			tcp->tcp_snxt = prev_snxt;
21236 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21237 				/*
21238 				 * If the previous timestamp is still in use,
21239 				 * don't stomp on it.
21240 				 */
21241 				if ((*xmit_tail)->b_next == NULL) {
21242 					(*xmit_tail)->b_prev = local_time;
21243 					(*xmit_tail)->b_next =
21244 					    (mblk_t *)(uintptr_t)(*snxt);
21245 				}
21246 			} else
21247 				(*xmit_tail)->b_rptr = prev_rptr;
21248 
21249 			if (mp == NULL) {
21250 				if (ire != NULL)
21251 					IRE_REFRELE(ire);
21252 				return (-1);
21253 			}
21254 			mp1 = mp->b_cont;
21255 
21256 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21257 				tcp->tcp_last_sent_len = (ushort_t)len;
21258 			while (mp1->b_cont) {
21259 				*xmit_tail = (*xmit_tail)->b_cont;
21260 				(*xmit_tail)->b_prev = local_time;
21261 				(*xmit_tail)->b_next =
21262 				    (mblk_t *)(uintptr_t)(*snxt);
21263 				mp1 = mp1->b_cont;
21264 			}
21265 			*snxt += len;
21266 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21267 			BUMP_LOCAL(tcp->tcp_obsegs);
21268 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21269 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21270 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21271 			tcp_send_data(tcp, q, mp);
21272 			continue;
21273 		}
21274 
21275 		*snxt += len;	/* Adjust later if we don't send all of len */
21276 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21277 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21278 
21279 		if (*tail_unsent) {
21280 			/* Are the bytes above us in flight? */
21281 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21282 			if (rptr != (*xmit_tail)->b_rptr) {
21283 				*tail_unsent -= len;
21284 				if (len <= mss) /* LSO is unusable */
21285 					tcp->tcp_last_sent_len = (ushort_t)len;
21286 				len += tcp_hdr_len;
21287 				if (tcp->tcp_ipversion == IPV4_VERSION)
21288 					tcp->tcp_ipha->ipha_length = htons(len);
21289 				else
21290 					tcp->tcp_ip6h->ip6_plen =
21291 					    htons(len -
21292 					    ((char *)&tcp->tcp_ip6h[1] -
21293 					    tcp->tcp_iphc));
21294 				mp = dupb(*xmit_tail);
21295 				if (mp == NULL) {
21296 					if (ire != NULL)
21297 						IRE_REFRELE(ire);
21298 					return (-1);	/* out_of_mem */
21299 				}
21300 				mp->b_rptr = rptr;
21301 				/*
21302 				 * If the old timestamp is no longer in use,
21303 				 * sample a new timestamp now.
21304 				 */
21305 				if ((*xmit_tail)->b_next == NULL) {
21306 					(*xmit_tail)->b_prev = local_time;
21307 					(*xmit_tail)->b_next =
21308 					    (mblk_t *)(uintptr_t)(*snxt-len);
21309 				}
21310 				goto must_alloc;
21311 			}
21312 		} else {
21313 			*xmit_tail = (*xmit_tail)->b_cont;
21314 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21315 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21316 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21317 			    (*xmit_tail)->b_rptr);
21318 		}
21319 
21320 		(*xmit_tail)->b_prev = local_time;
21321 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21322 
21323 		*tail_unsent -= len;
21324 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21325 			tcp->tcp_last_sent_len = (ushort_t)len;
21326 
21327 		len += tcp_hdr_len;
21328 		if (tcp->tcp_ipversion == IPV4_VERSION)
21329 			tcp->tcp_ipha->ipha_length = htons(len);
21330 		else
21331 			tcp->tcp_ip6h->ip6_plen = htons(len -
21332 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21333 
21334 		mp = dupb(*xmit_tail);
21335 		if (mp == NULL) {
21336 			if (ire != NULL)
21337 				IRE_REFRELE(ire);
21338 			return (-1);	/* out_of_mem */
21339 		}
21340 
21341 		len = tcp_hdr_len;
21342 		/*
21343 		 * There are four reasons to allocate a new hdr mblk:
21344 		 *  1) The bytes above us are in use by another packet
21345 		 *  2) We don't have good alignment
21346 		 *  3) The mblk is being shared
21347 		 *  4) We don't have enough room for a header
21348 		 */
21349 		rptr = mp->b_rptr - len;
21350 		if (!OK_32PTR(rptr) ||
21351 		    ((db = mp->b_datap), db->db_ref != 2) ||
21352 		    rptr < db->db_base + ire_fp_mp_len) {
21353 			/* NOTE: we assume allocb returns an OK_32PTR */
21354 
21355 		must_alloc:;
21356 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21357 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21358 			if (mp1 == NULL) {
21359 				freemsg(mp);
21360 				if (ire != NULL)
21361 					IRE_REFRELE(ire);
21362 				return (-1);	/* out_of_mem */
21363 			}
21364 			mp1->b_cont = mp;
21365 			mp = mp1;
21366 			/* Leave room for Link Level header */
21367 			len = tcp_hdr_len;
21368 			rptr =
21369 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21370 			mp->b_wptr = &rptr[len];
21371 		}
21372 
21373 		/*
21374 		 * Fill in the header using the template header, and add
21375 		 * options such as time-stamp, ECN and/or SACK, as needed.
21376 		 */
21377 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21378 
21379 		mp->b_rptr = rptr;
21380 
21381 		if (*tail_unsent) {
21382 			int spill = *tail_unsent;
21383 
21384 			mp1 = mp->b_cont;
21385 			if (mp1 == NULL)
21386 				mp1 = mp;
21387 
21388 			/*
21389 			 * If we're a little short, tack on more mblks until
21390 			 * there is no more spillover.
21391 			 */
21392 			while (spill < 0) {
21393 				mblk_t *nmp;
21394 				int nmpsz;
21395 
21396 				nmp = (*xmit_tail)->b_cont;
21397 				nmpsz = MBLKL(nmp);
21398 
21399 				/*
21400 				 * Excess data in mblk; can we split it?
21401 				 * If MDT is enabled for the connection,
21402 				 * keep on splitting as this is a transient
21403 				 * send path.
21404 				 */
21405 				if (!do_lso_send && !tcp->tcp_mdt &&
21406 				    (spill + nmpsz > 0)) {
21407 					/*
21408 					 * Don't split if stream head was
21409 					 * told to break up larger writes
21410 					 * into smaller ones.
21411 					 */
21412 					if (tcp->tcp_maxpsz > 0)
21413 						break;
21414 
21415 					/*
21416 					 * Next mblk is less than SMSS/2
21417 					 * rounded up to nearest 64-byte;
21418 					 * let it get sent as part of the
21419 					 * next segment.
21420 					 */
21421 					if (tcp->tcp_localnet &&
21422 					    !tcp->tcp_cork &&
21423 					    (nmpsz < roundup((mss >> 1), 64)))
21424 						break;
21425 				}
21426 
21427 				*xmit_tail = nmp;
21428 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21429 				/* Stash for rtt use later */
21430 				(*xmit_tail)->b_prev = local_time;
21431 				(*xmit_tail)->b_next =
21432 				    (mblk_t *)(uintptr_t)(*snxt - len);
21433 				mp1->b_cont = dupb(*xmit_tail);
21434 				mp1 = mp1->b_cont;
21435 
21436 				spill += nmpsz;
21437 				if (mp1 == NULL) {
21438 					*tail_unsent = spill;
21439 					freemsg(mp);
21440 					if (ire != NULL)
21441 						IRE_REFRELE(ire);
21442 					return (-1);	/* out_of_mem */
21443 				}
21444 			}
21445 
21446 			/* Trim back any surplus on the last mblk */
21447 			if (spill >= 0) {
21448 				mp1->b_wptr -= spill;
21449 				*tail_unsent = spill;
21450 			} else {
21451 				/*
21452 				 * We did not send everything we could in
21453 				 * order to remain within the b_cont limit.
21454 				 */
21455 				*usable -= spill;
21456 				*snxt += spill;
21457 				tcp->tcp_last_sent_len += spill;
21458 				UPDATE_MIB(&tcps->tcps_mib,
21459 				    tcpOutDataBytes, spill);
21460 				/*
21461 				 * Adjust the checksum
21462 				 */
21463 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21464 				sum += spill;
21465 				sum = (sum >> 16) + (sum & 0xFFFF);
21466 				U16_TO_ABE16(sum, tcph->th_sum);
21467 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21468 					sum = ntohs(
21469 					    ((ipha_t *)rptr)->ipha_length) +
21470 					    spill;
21471 					((ipha_t *)rptr)->ipha_length =
21472 					    htons(sum);
21473 				} else {
21474 					sum = ntohs(
21475 					    ((ip6_t *)rptr)->ip6_plen) +
21476 					    spill;
21477 					((ip6_t *)rptr)->ip6_plen =
21478 					    htons(sum);
21479 				}
21480 				*tail_unsent = 0;
21481 			}
21482 		}
21483 		if (tcp->tcp_ip_forward_progress) {
21484 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21485 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21486 			tcp->tcp_ip_forward_progress = B_FALSE;
21487 		}
21488 
21489 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21490 		if (do_lso_send) {
21491 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21492 			    num_lso_seg);
21493 			tcp->tcp_obsegs += num_lso_seg;
21494 
21495 			TCP_STAT(tcps, tcp_lso_times);
21496 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21497 		} else {
21498 			tcp_send_data(tcp, q, mp);
21499 			BUMP_LOCAL(tcp->tcp_obsegs);
21500 		}
21501 	}
21502 
21503 	if (ire != NULL)
21504 		IRE_REFRELE(ire);
21505 	return (0);
21506 }
21507 
21508 /* Unlink and return any mblk that looks like it contains a MDT info */
21509 static mblk_t *
21510 tcp_mdt_info_mp(mblk_t *mp)
21511 {
21512 	mblk_t	*prev_mp;
21513 
21514 	for (;;) {
21515 		prev_mp = mp;
21516 		/* no more to process? */
21517 		if ((mp = mp->b_cont) == NULL)
21518 			break;
21519 
21520 		switch (DB_TYPE(mp)) {
21521 		case M_CTL:
21522 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21523 				continue;
21524 			ASSERT(prev_mp != NULL);
21525 			prev_mp->b_cont = mp->b_cont;
21526 			mp->b_cont = NULL;
21527 			return (mp);
21528 		default:
21529 			break;
21530 		}
21531 	}
21532 	return (mp);
21533 }
21534 
21535 /* MDT info update routine, called when IP notifies us about MDT */
21536 static void
21537 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21538 {
21539 	boolean_t prev_state;
21540 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21541 
21542 	/*
21543 	 * IP is telling us to abort MDT on this connection?  We know
21544 	 * this because the capability is only turned off when IP
21545 	 * encounters some pathological cases, e.g. link-layer change
21546 	 * where the new driver doesn't support MDT, or in situation
21547 	 * where MDT usage on the link-layer has been switched off.
21548 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21549 	 * if the link-layer doesn't support MDT, and if it does, it
21550 	 * will indicate that the feature is to be turned on.
21551 	 */
21552 	prev_state = tcp->tcp_mdt;
21553 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21554 	if (!tcp->tcp_mdt && !first) {
21555 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21556 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21557 		    (void *)tcp->tcp_connp));
21558 	}
21559 
21560 	/*
21561 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21562 	 * so disable MDT otherwise.  The checks are done here
21563 	 * and in tcp_wput_data().
21564 	 */
21565 	if (tcp->tcp_mdt &&
21566 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21567 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21568 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21569 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21570 		tcp->tcp_mdt = B_FALSE;
21571 
21572 	if (tcp->tcp_mdt) {
21573 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21574 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21575 			    "version (%d), expected version is %d",
21576 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21577 			tcp->tcp_mdt = B_FALSE;
21578 			return;
21579 		}
21580 
21581 		/*
21582 		 * We need the driver to be able to handle at least three
21583 		 * spans per packet in order for tcp MDT to be utilized.
21584 		 * The first is for the header portion, while the rest are
21585 		 * needed to handle a packet that straddles across two
21586 		 * virtually non-contiguous buffers; a typical tcp packet
21587 		 * therefore consists of only two spans.  Note that we take
21588 		 * a zero as "don't care".
21589 		 */
21590 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21591 		    mdt_capab->ill_mdt_span_limit < 3) {
21592 			tcp->tcp_mdt = B_FALSE;
21593 			return;
21594 		}
21595 
21596 		/* a zero means driver wants default value */
21597 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21598 		    tcps->tcps_mdt_max_pbufs);
21599 		if (tcp->tcp_mdt_max_pld == 0)
21600 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21601 
21602 		/* ensure 32-bit alignment */
21603 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21604 		    mdt_capab->ill_mdt_hdr_head), 4);
21605 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21606 		    mdt_capab->ill_mdt_hdr_tail), 4);
21607 
21608 		if (!first && !prev_state) {
21609 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21610 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21611 			    (void *)tcp->tcp_connp));
21612 		}
21613 	}
21614 }
21615 
21616 /* Unlink and return any mblk that looks like it contains a LSO info */
21617 static mblk_t *
21618 tcp_lso_info_mp(mblk_t *mp)
21619 {
21620 	mblk_t	*prev_mp;
21621 
21622 	for (;;) {
21623 		prev_mp = mp;
21624 		/* no more to process? */
21625 		if ((mp = mp->b_cont) == NULL)
21626 			break;
21627 
21628 		switch (DB_TYPE(mp)) {
21629 		case M_CTL:
21630 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21631 				continue;
21632 			ASSERT(prev_mp != NULL);
21633 			prev_mp->b_cont = mp->b_cont;
21634 			mp->b_cont = NULL;
21635 			return (mp);
21636 		default:
21637 			break;
21638 		}
21639 	}
21640 
21641 	return (mp);
21642 }
21643 
21644 /* LSO info update routine, called when IP notifies us about LSO */
21645 static void
21646 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21647 {
21648 	tcp_stack_t *tcps = tcp->tcp_tcps;
21649 
21650 	/*
21651 	 * IP is telling us to abort LSO on this connection?  We know
21652 	 * this because the capability is only turned off when IP
21653 	 * encounters some pathological cases, e.g. link-layer change
21654 	 * where the new NIC/driver doesn't support LSO, or in situation
21655 	 * where LSO usage on the link-layer has been switched off.
21656 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21657 	 * if the link-layer doesn't support LSO, and if it does, it
21658 	 * will indicate that the feature is to be turned on.
21659 	 */
21660 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21661 	TCP_STAT(tcps, tcp_lso_enabled);
21662 
21663 	/*
21664 	 * We currently only support LSO on simple TCP/IPv4,
21665 	 * so disable LSO otherwise.  The checks are done here
21666 	 * and in tcp_wput_data().
21667 	 */
21668 	if (tcp->tcp_lso &&
21669 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21670 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21671 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21672 		tcp->tcp_lso = B_FALSE;
21673 		TCP_STAT(tcps, tcp_lso_disabled);
21674 	} else {
21675 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21676 		    lso_capab->ill_lso_max);
21677 	}
21678 }
21679 
21680 static void
21681 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21682 {
21683 	conn_t *connp = tcp->tcp_connp;
21684 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21685 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21686 
21687 	ASSERT(ire != NULL);
21688 
21689 	/*
21690 	 * We may be in the fastpath here, and although we essentially do
21691 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21692 	 * we try to keep things as brief as possible.  After all, these
21693 	 * are only best-effort checks, and we do more thorough ones prior
21694 	 * to calling tcp_send()/tcp_multisend().
21695 	 */
21696 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21697 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21698 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21699 	    !(ire->ire_flags & RTF_MULTIRT) &&
21700 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21701 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21702 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21703 			/* Cache the result */
21704 			connp->conn_lso_ok = B_TRUE;
21705 
21706 			ASSERT(ill->ill_lso_capab != NULL);
21707 			if (!ill->ill_lso_capab->ill_lso_on) {
21708 				ill->ill_lso_capab->ill_lso_on = 1;
21709 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21710 				    "LSO for interface %s\n", (void *)connp,
21711 				    ill->ill_name));
21712 			}
21713 			tcp_lso_update(tcp, ill->ill_lso_capab);
21714 		} else if (ipst->ips_ip_multidata_outbound &&
21715 		    ILL_MDT_CAPABLE(ill)) {
21716 			/* Cache the result */
21717 			connp->conn_mdt_ok = B_TRUE;
21718 
21719 			ASSERT(ill->ill_mdt_capab != NULL);
21720 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21721 				ill->ill_mdt_capab->ill_mdt_on = 1;
21722 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21723 				    "MDT for interface %s\n", (void *)connp,
21724 				    ill->ill_name));
21725 			}
21726 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21727 		}
21728 	}
21729 
21730 	/*
21731 	 * The goal is to reduce the number of generated tcp segments by
21732 	 * setting the maxpsz multiplier to 0; this will have an affect on
21733 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21734 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21735 	 * of outbound segments and incoming ACKs, thus allowing for better
21736 	 * network and system performance.  In contrast the legacy behavior
21737 	 * may result in sending less than SMSS size, because the last mblk
21738 	 * for some packets may have more data than needed to make up SMSS,
21739 	 * and the legacy code refused to "split" it.
21740 	 *
21741 	 * We apply the new behavior on following situations:
21742 	 *
21743 	 *   1) Loopback connections,
21744 	 *   2) Connections in which the remote peer is not on local subnet,
21745 	 *   3) Local subnet connections over the bge interface (see below).
21746 	 *
21747 	 * Ideally, we would like this behavior to apply for interfaces other
21748 	 * than bge.  However, doing so would negatively impact drivers which
21749 	 * perform dynamic mapping and unmapping of DMA resources, which are
21750 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21751 	 * packet will be generated by tcp).  The bge driver does not suffer
21752 	 * from this, as it copies the mblks into pre-mapped buffers, and
21753 	 * therefore does not require more I/O resources than before.
21754 	 *
21755 	 * Otherwise, this behavior is present on all network interfaces when
21756 	 * the destination endpoint is non-local, since reducing the number
21757 	 * of packets in general is good for the network.
21758 	 *
21759 	 * TODO We need to remove this hard-coded conditional for bge once
21760 	 *	a better "self-tuning" mechanism, or a way to comprehend
21761 	 *	the driver transmit strategy is devised.  Until the solution
21762 	 *	is found and well understood, we live with this hack.
21763 	 */
21764 	if (!tcp_static_maxpsz &&
21765 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21766 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21767 		/* override the default value */
21768 		tcp->tcp_maxpsz = 0;
21769 
21770 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21771 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21772 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21773 	}
21774 
21775 	/* set the stream head parameters accordingly */
21776 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21777 }
21778 
21779 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21780 static void
21781 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21782 {
21783 	uchar_t	fval = *mp->b_rptr;
21784 	mblk_t	*tail;
21785 	queue_t	*q = tcp->tcp_wq;
21786 
21787 	/* TODO: How should flush interact with urgent data? */
21788 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21789 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21790 		/*
21791 		 * Flush only data that has not yet been put on the wire.  If
21792 		 * we flush data that we have already transmitted, life, as we
21793 		 * know it, may come to an end.
21794 		 */
21795 		tail = tcp->tcp_xmit_tail;
21796 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21797 		tcp->tcp_xmit_tail_unsent = 0;
21798 		tcp->tcp_unsent = 0;
21799 		if (tail->b_wptr != tail->b_rptr)
21800 			tail = tail->b_cont;
21801 		if (tail) {
21802 			mblk_t **excess = &tcp->tcp_xmit_head;
21803 			for (;;) {
21804 				mblk_t *mp1 = *excess;
21805 				if (mp1 == tail)
21806 					break;
21807 				tcp->tcp_xmit_tail = mp1;
21808 				tcp->tcp_xmit_last = mp1;
21809 				excess = &mp1->b_cont;
21810 			}
21811 			*excess = NULL;
21812 			tcp_close_mpp(&tail);
21813 			if (tcp->tcp_snd_zcopy_aware)
21814 				tcp_zcopy_notify(tcp);
21815 		}
21816 		/*
21817 		 * We have no unsent data, so unsent must be less than
21818 		 * tcp_xmit_lowater, so re-enable flow.
21819 		 */
21820 		mutex_enter(&tcp->tcp_non_sq_lock);
21821 		if (tcp->tcp_flow_stopped) {
21822 			tcp_clrqfull(tcp);
21823 		}
21824 		mutex_exit(&tcp->tcp_non_sq_lock);
21825 	}
21826 	/*
21827 	 * TODO: you can't just flush these, you have to increase rwnd for one
21828 	 * thing.  For another, how should urgent data interact?
21829 	 */
21830 	if (fval & FLUSHR) {
21831 		*mp->b_rptr = fval & ~FLUSHW;
21832 		/* XXX */
21833 		qreply(q, mp);
21834 		return;
21835 	}
21836 	freemsg(mp);
21837 }
21838 
21839 /*
21840  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21841  * messages.
21842  */
21843 static void
21844 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21845 {
21846 	mblk_t	*mp1;
21847 	STRUCT_HANDLE(strbuf, sb);
21848 	uint16_t port;
21849 	queue_t 	*q = tcp->tcp_wq;
21850 	in6_addr_t	v6addr;
21851 	ipaddr_t	v4addr;
21852 	uint32_t	flowinfo = 0;
21853 	int		addrlen;
21854 
21855 	/* Make sure it is one of ours. */
21856 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21857 	case TI_GETMYNAME:
21858 	case TI_GETPEERNAME:
21859 		break;
21860 	default:
21861 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21862 		return;
21863 	}
21864 	switch (mi_copy_state(q, mp, &mp1)) {
21865 	case -1:
21866 		return;
21867 	case MI_COPY_CASE(MI_COPY_IN, 1):
21868 		break;
21869 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21870 		/* Copy out the strbuf. */
21871 		mi_copyout(q, mp);
21872 		return;
21873 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21874 		/* All done. */
21875 		mi_copy_done(q, mp, 0);
21876 		return;
21877 	default:
21878 		mi_copy_done(q, mp, EPROTO);
21879 		return;
21880 	}
21881 	/* Check alignment of the strbuf */
21882 	if (!OK_32PTR(mp1->b_rptr)) {
21883 		mi_copy_done(q, mp, EINVAL);
21884 		return;
21885 	}
21886 
21887 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21888 	    (void *)mp1->b_rptr);
21889 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21890 
21891 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21892 		mi_copy_done(q, mp, EINVAL);
21893 		return;
21894 	}
21895 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21896 	case TI_GETMYNAME:
21897 		if (tcp->tcp_family == AF_INET) {
21898 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21899 				v4addr = tcp->tcp_ipha->ipha_src;
21900 			} else {
21901 				/* can't return an address in this case */
21902 				v4addr = 0;
21903 			}
21904 		} else {
21905 			/* tcp->tcp_family == AF_INET6 */
21906 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21907 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21908 				    &v6addr);
21909 			} else {
21910 				v6addr = tcp->tcp_ip6h->ip6_src;
21911 			}
21912 		}
21913 		port = tcp->tcp_lport;
21914 		break;
21915 	case TI_GETPEERNAME:
21916 		if (tcp->tcp_family == AF_INET) {
21917 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21918 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21919 				    v4addr);
21920 			} else {
21921 				/* can't return an address in this case */
21922 				v4addr = 0;
21923 			}
21924 		} else {
21925 			/* tcp->tcp_family == AF_INET6) */
21926 			v6addr = tcp->tcp_remote_v6;
21927 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21928 				/*
21929 				 * No flowinfo if tcp->tcp_ipversion is v4.
21930 				 *
21931 				 * flowinfo was already initialized to zero
21932 				 * where it was declared above, so only
21933 				 * set it if ipversion is v6.
21934 				 */
21935 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21936 				    ~IPV6_VERS_AND_FLOW_MASK;
21937 			}
21938 		}
21939 		port = tcp->tcp_fport;
21940 		break;
21941 	default:
21942 		mi_copy_done(q, mp, EPROTO);
21943 		return;
21944 	}
21945 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21946 	if (!mp1)
21947 		return;
21948 
21949 	if (tcp->tcp_family == AF_INET) {
21950 		sin_t *sin;
21951 
21952 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21953 		sin = (sin_t *)mp1->b_rptr;
21954 		mp1->b_wptr = (uchar_t *)&sin[1];
21955 		*sin = sin_null;
21956 		sin->sin_family = AF_INET;
21957 		sin->sin_addr.s_addr = v4addr;
21958 		sin->sin_port = port;
21959 	} else {
21960 		/* tcp->tcp_family == AF_INET6 */
21961 		sin6_t *sin6;
21962 
21963 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21964 		sin6 = (sin6_t *)mp1->b_rptr;
21965 		mp1->b_wptr = (uchar_t *)&sin6[1];
21966 		*sin6 = sin6_null;
21967 		sin6->sin6_family = AF_INET6;
21968 		sin6->sin6_flowinfo = flowinfo;
21969 		sin6->sin6_addr = v6addr;
21970 		sin6->sin6_port = port;
21971 	}
21972 	/* Copy out the address */
21973 	mi_copyout(q, mp);
21974 }
21975 
21976 /*
21977  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21978  * messages.
21979  */
21980 /* ARGSUSED */
21981 static void
21982 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21983 {
21984 	conn_t 	*connp = (conn_t *)arg;
21985 	tcp_t	*tcp = connp->conn_tcp;
21986 	queue_t	*q = tcp->tcp_wq;
21987 	struct iocblk	*iocp;
21988 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21989 
21990 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21991 	/*
21992 	 * Try and ASSERT the minimum possible references on the
21993 	 * conn early enough. Since we are executing on write side,
21994 	 * the connection is obviously not detached and that means
21995 	 * there is a ref each for TCP and IP. Since we are behind
21996 	 * the squeue, the minimum references needed are 3. If the
21997 	 * conn is in classifier hash list, there should be an
21998 	 * extra ref for that (we check both the possibilities).
21999 	 */
22000 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22001 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22002 
22003 	iocp = (struct iocblk *)mp->b_rptr;
22004 	switch (iocp->ioc_cmd) {
22005 	case TCP_IOC_DEFAULT_Q:
22006 		/* Wants to be the default wq. */
22007 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22008 			iocp->ioc_error = EPERM;
22009 			iocp->ioc_count = 0;
22010 			mp->b_datap->db_type = M_IOCACK;
22011 			qreply(q, mp);
22012 			return;
22013 		}
22014 		tcp_def_q_set(tcp, mp);
22015 		return;
22016 	case _SIOCSOCKFALLBACK:
22017 		/*
22018 		 * Either sockmod is about to be popped and the socket
22019 		 * would now be treated as a plain stream, or a module
22020 		 * is about to be pushed so we could no longer use read-
22021 		 * side synchronous streams for fused loopback tcp.
22022 		 * Drain any queued data and disable direct sockfs
22023 		 * interface from now on.
22024 		 */
22025 		if (!tcp->tcp_issocket) {
22026 			DB_TYPE(mp) = M_IOCNAK;
22027 			iocp->ioc_error = EINVAL;
22028 		} else {
22029 #ifdef	_ILP32
22030 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22031 #else
22032 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22033 #endif
22034 			/*
22035 			 * Insert this socket into the acceptor hash.
22036 			 * We might need it for T_CONN_RES message
22037 			 */
22038 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22039 
22040 			if (tcp->tcp_fused) {
22041 				/*
22042 				 * This is a fused loopback tcp; disable
22043 				 * read-side synchronous streams interface
22044 				 * and drain any queued data.  It is okay
22045 				 * to do this for non-synchronous streams
22046 				 * fused tcp as well.
22047 				 */
22048 				tcp_fuse_disable_pair(tcp, B_FALSE);
22049 			}
22050 			tcp->tcp_issocket = B_FALSE;
22051 			TCP_STAT(tcps, tcp_sock_fallback);
22052 
22053 			DB_TYPE(mp) = M_IOCACK;
22054 			iocp->ioc_error = 0;
22055 		}
22056 		iocp->ioc_count = 0;
22057 		iocp->ioc_rval = 0;
22058 		qreply(q, mp);
22059 		return;
22060 	}
22061 	CALL_IP_WPUT(connp, q, mp);
22062 }
22063 
22064 /*
22065  * This routine is called by tcp_wput() to handle all TPI requests.
22066  */
22067 /* ARGSUSED */
22068 static void
22069 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22070 {
22071 	conn_t 	*connp = (conn_t *)arg;
22072 	tcp_t	*tcp = connp->conn_tcp;
22073 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22074 	uchar_t *rptr;
22075 	t_scalar_t type;
22076 	int len;
22077 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22078 
22079 	/*
22080 	 * Try and ASSERT the minimum possible references on the
22081 	 * conn early enough. Since we are executing on write side,
22082 	 * the connection is obviously not detached and that means
22083 	 * there is a ref each for TCP and IP. Since we are behind
22084 	 * the squeue, the minimum references needed are 3. If the
22085 	 * conn is in classifier hash list, there should be an
22086 	 * extra ref for that (we check both the possibilities).
22087 	 */
22088 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22089 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22090 
22091 	rptr = mp->b_rptr;
22092 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22093 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22094 		type = ((union T_primitives *)rptr)->type;
22095 		if (type == T_EXDATA_REQ) {
22096 			uint32_t msize = msgdsize(mp->b_cont);
22097 
22098 			len = msize - 1;
22099 			if (len < 0) {
22100 				freemsg(mp);
22101 				return;
22102 			}
22103 			/*
22104 			 * Try to force urgent data out on the wire.
22105 			 * Even if we have unsent data this will
22106 			 * at least send the urgent flag.
22107 			 * XXX does not handle more flag correctly.
22108 			 */
22109 			len += tcp->tcp_unsent;
22110 			len += tcp->tcp_snxt;
22111 			tcp->tcp_urg = len;
22112 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22113 
22114 			/* Bypass tcp protocol for fused tcp loopback */
22115 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22116 				return;
22117 		} else if (type != T_DATA_REQ) {
22118 			goto non_urgent_data;
22119 		}
22120 		/* TODO: options, flags, ... from user */
22121 		/* Set length to zero for reclamation below */
22122 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22123 		freeb(mp);
22124 		return;
22125 	} else {
22126 		if (tcp->tcp_debug) {
22127 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22128 			    "tcp_wput_proto, dropping one...");
22129 		}
22130 		freemsg(mp);
22131 		return;
22132 	}
22133 
22134 non_urgent_data:
22135 
22136 	switch ((int)tprim->type) {
22137 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22138 		/*
22139 		 * save the kssl_ent_t from the next block, and convert this
22140 		 * back to a normal bind_req.
22141 		 */
22142 		if (mp->b_cont != NULL) {
22143 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22144 
22145 			if (tcp->tcp_kssl_ent != NULL) {
22146 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22147 				    KSSL_NO_PROXY);
22148 				tcp->tcp_kssl_ent = NULL;
22149 			}
22150 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22151 			    sizeof (kssl_ent_t));
22152 			kssl_hold_ent(tcp->tcp_kssl_ent);
22153 			freemsg(mp->b_cont);
22154 			mp->b_cont = NULL;
22155 		}
22156 		tprim->type = T_BIND_REQ;
22157 
22158 	/* FALLTHROUGH */
22159 	case O_T_BIND_REQ:	/* bind request */
22160 	case T_BIND_REQ:	/* new semantics bind request */
22161 		tcp_bind(tcp, mp);
22162 		break;
22163 	case T_UNBIND_REQ:	/* unbind request */
22164 		tcp_unbind(tcp, mp);
22165 		break;
22166 	case O_T_CONN_RES:	/* old connection response XXX */
22167 	case T_CONN_RES:	/* connection response */
22168 		tcp_accept(tcp, mp);
22169 		break;
22170 	case T_CONN_REQ:	/* connection request */
22171 		tcp_connect(tcp, mp);
22172 		break;
22173 	case T_DISCON_REQ:	/* disconnect request */
22174 		tcp_disconnect(tcp, mp);
22175 		break;
22176 	case T_CAPABILITY_REQ:
22177 		tcp_capability_req(tcp, mp);	/* capability request */
22178 		break;
22179 	case T_INFO_REQ:	/* information request */
22180 		tcp_info_req(tcp, mp);
22181 		break;
22182 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22183 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22184 		    &tcp_opt_obj, B_TRUE);
22185 		break;
22186 	case T_OPTMGMT_REQ:
22187 		/*
22188 		 * Note:  no support for snmpcom_req() through new
22189 		 * T_OPTMGMT_REQ. See comments in ip.c
22190 		 */
22191 		/* Only IP is allowed to return meaningful value */
22192 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22193 		    B_TRUE);
22194 		break;
22195 
22196 	case T_UNITDATA_REQ:	/* unitdata request */
22197 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22198 		break;
22199 	case T_ORDREL_REQ:	/* orderly release req */
22200 		freemsg(mp);
22201 
22202 		if (tcp->tcp_fused)
22203 			tcp_unfuse(tcp);
22204 
22205 		if (tcp_xmit_end(tcp) != 0) {
22206 			/*
22207 			 * We were crossing FINs and got a reset from
22208 			 * the other side. Just ignore it.
22209 			 */
22210 			if (tcp->tcp_debug) {
22211 				(void) strlog(TCP_MOD_ID, 0, 1,
22212 				    SL_ERROR|SL_TRACE,
22213 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22214 				    "state %s",
22215 				    tcp_display(tcp, NULL,
22216 				    DISP_ADDR_AND_PORT));
22217 			}
22218 		}
22219 		break;
22220 	case T_ADDR_REQ:
22221 		tcp_addr_req(tcp, mp);
22222 		break;
22223 	default:
22224 		if (tcp->tcp_debug) {
22225 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22226 			    "tcp_wput_proto, bogus TPI msg, type %d",
22227 			    tprim->type);
22228 		}
22229 		/*
22230 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22231 		 * to recover.
22232 		 */
22233 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22234 		break;
22235 	}
22236 }
22237 
22238 /*
22239  * The TCP write service routine should never be called...
22240  */
22241 /* ARGSUSED */
22242 static void
22243 tcp_wsrv(queue_t *q)
22244 {
22245 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22246 
22247 	TCP_STAT(tcps, tcp_wsrv_called);
22248 }
22249 
22250 /* Non overlapping byte exchanger */
22251 static void
22252 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22253 {
22254 	uchar_t	uch;
22255 
22256 	while (len-- > 0) {
22257 		uch = a[len];
22258 		a[len] = b[len];
22259 		b[len] = uch;
22260 	}
22261 }
22262 
22263 /*
22264  * Send out a control packet on the tcp connection specified.  This routine
22265  * is typically called where we need a simple ACK or RST generated.
22266  */
22267 static void
22268 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22269 {
22270 	uchar_t		*rptr;
22271 	tcph_t		*tcph;
22272 	ipha_t		*ipha = NULL;
22273 	ip6_t		*ip6h = NULL;
22274 	uint32_t	sum;
22275 	int		tcp_hdr_len;
22276 	int		tcp_ip_hdr_len;
22277 	mblk_t		*mp;
22278 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22279 
22280 	/*
22281 	 * Save sum for use in source route later.
22282 	 */
22283 	ASSERT(tcp != NULL);
22284 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22285 	tcp_hdr_len = tcp->tcp_hdr_len;
22286 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22287 
22288 	/* If a text string is passed in with the request, pass it to strlog. */
22289 	if (str != NULL && tcp->tcp_debug) {
22290 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22291 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22292 		    str, seq, ack, ctl);
22293 	}
22294 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22295 	    BPRI_MED);
22296 	if (mp == NULL) {
22297 		return;
22298 	}
22299 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22300 	mp->b_rptr = rptr;
22301 	mp->b_wptr = &rptr[tcp_hdr_len];
22302 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22303 
22304 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22305 		ipha = (ipha_t *)rptr;
22306 		ipha->ipha_length = htons(tcp_hdr_len);
22307 	} else {
22308 		ip6h = (ip6_t *)rptr;
22309 		ASSERT(tcp != NULL);
22310 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22311 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22312 	}
22313 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22314 	tcph->th_flags[0] = (uint8_t)ctl;
22315 	if (ctl & TH_RST) {
22316 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22317 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22318 		/*
22319 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22320 		 */
22321 		if (tcp->tcp_snd_ts_ok &&
22322 		    tcp->tcp_state > TCPS_SYN_SENT) {
22323 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22324 			*(mp->b_wptr) = TCPOPT_EOL;
22325 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22326 				ipha->ipha_length = htons(tcp_hdr_len -
22327 				    TCPOPT_REAL_TS_LEN);
22328 			} else {
22329 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22330 				    TCPOPT_REAL_TS_LEN);
22331 			}
22332 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22333 			sum -= TCPOPT_REAL_TS_LEN;
22334 		}
22335 	}
22336 	if (ctl & TH_ACK) {
22337 		if (tcp->tcp_snd_ts_ok) {
22338 			U32_TO_BE32(lbolt,
22339 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22340 			U32_TO_BE32(tcp->tcp_ts_recent,
22341 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22342 		}
22343 
22344 		/* Update the latest receive window size in TCP header. */
22345 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22346 		    tcph->th_win);
22347 		tcp->tcp_rack = ack;
22348 		tcp->tcp_rack_cnt = 0;
22349 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22350 	}
22351 	BUMP_LOCAL(tcp->tcp_obsegs);
22352 	U32_TO_BE32(seq, tcph->th_seq);
22353 	U32_TO_BE32(ack, tcph->th_ack);
22354 	/*
22355 	 * Include the adjustment for a source route if any.
22356 	 */
22357 	sum = (sum >> 16) + (sum & 0xFFFF);
22358 	U16_TO_BE16(sum, tcph->th_sum);
22359 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22360 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22361 }
22362 
22363 /*
22364  * If this routine returns B_TRUE, TCP can generate a RST in response
22365  * to a segment.  If it returns B_FALSE, TCP should not respond.
22366  */
22367 static boolean_t
22368 tcp_send_rst_chk(tcp_stack_t *tcps)
22369 {
22370 	clock_t	now;
22371 
22372 	/*
22373 	 * TCP needs to protect itself from generating too many RSTs.
22374 	 * This can be a DoS attack by sending us random segments
22375 	 * soliciting RSTs.
22376 	 *
22377 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22378 	 * in each 1 second interval.  In this way, TCP still generate
22379 	 * RSTs in normal cases but when under attack, the impact is
22380 	 * limited.
22381 	 */
22382 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22383 		now = lbolt;
22384 		/* lbolt can wrap around. */
22385 		if ((tcps->tcps_last_rst_intrvl > now) ||
22386 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22387 		    1*SECONDS)) {
22388 			tcps->tcps_last_rst_intrvl = now;
22389 			tcps->tcps_rst_cnt = 1;
22390 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22391 			return (B_FALSE);
22392 		}
22393 	}
22394 	return (B_TRUE);
22395 }
22396 
22397 /*
22398  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22399  */
22400 static void
22401 tcp_ip_ire_mark_advice(tcp_t *tcp)
22402 {
22403 	mblk_t *mp;
22404 	ipic_t *ipic;
22405 
22406 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22407 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22408 		    &ipic);
22409 	} else {
22410 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22411 		    &ipic);
22412 	}
22413 	if (mp == NULL)
22414 		return;
22415 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22416 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22417 }
22418 
22419 /*
22420  * Return an IP advice ioctl mblk and set ipic to be the pointer
22421  * to the advice structure.
22422  */
22423 static mblk_t *
22424 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22425 {
22426 	struct iocblk *ioc;
22427 	mblk_t *mp, *mp1;
22428 
22429 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22430 	if (mp == NULL)
22431 		return (NULL);
22432 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22433 	*ipic = (ipic_t *)mp->b_rptr;
22434 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22435 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22436 
22437 	bcopy(addr, *ipic + 1, addr_len);
22438 
22439 	(*ipic)->ipic_addr_length = addr_len;
22440 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22441 
22442 	mp1 = mkiocb(IP_IOCTL);
22443 	if (mp1 == NULL) {
22444 		freemsg(mp);
22445 		return (NULL);
22446 	}
22447 	mp1->b_cont = mp;
22448 	ioc = (struct iocblk *)mp1->b_rptr;
22449 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22450 
22451 	return (mp1);
22452 }
22453 
22454 /*
22455  * Generate a reset based on an inbound packet, connp is set by caller
22456  * when RST is in response to an unexpected inbound packet for which
22457  * there is active tcp state in the system.
22458  *
22459  * IPSEC NOTE : Try to send the reply with the same protection as it came
22460  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22461  * the packet will go out at the same level of protection as it came in by
22462  * converting the IPSEC_IN to IPSEC_OUT.
22463  */
22464 static void
22465 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22466     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22467     tcp_stack_t *tcps, conn_t *connp)
22468 {
22469 	ipha_t		*ipha = NULL;
22470 	ip6_t		*ip6h = NULL;
22471 	ushort_t	len;
22472 	tcph_t		*tcph;
22473 	int		i;
22474 	mblk_t		*ipsec_mp;
22475 	boolean_t	mctl_present;
22476 	ipic_t		*ipic;
22477 	ipaddr_t	v4addr;
22478 	in6_addr_t	v6addr;
22479 	int		addr_len;
22480 	void		*addr;
22481 	queue_t		*q = tcps->tcps_g_q;
22482 	tcp_t		*tcp;
22483 	cred_t		*cr;
22484 	mblk_t		*nmp;
22485 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22486 
22487 	if (tcps->tcps_g_q == NULL) {
22488 		/*
22489 		 * For non-zero stackids the default queue isn't created
22490 		 * until the first open, thus there can be a need to send
22491 		 * a reset before then. But we can't do that, hence we just
22492 		 * drop the packet. Later during boot, when the default queue
22493 		 * has been setup, a retransmitted packet from the peer
22494 		 * will result in a reset.
22495 		 */
22496 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22497 		    GLOBAL_NETSTACKID);
22498 		freemsg(mp);
22499 		return;
22500 	}
22501 
22502 	if (connp != NULL)
22503 		tcp = connp->conn_tcp;
22504 	else
22505 		tcp = Q_TO_TCP(q);
22506 
22507 	if (!tcp_send_rst_chk(tcps)) {
22508 		tcps->tcps_rst_unsent++;
22509 		freemsg(mp);
22510 		return;
22511 	}
22512 
22513 	if (mp->b_datap->db_type == M_CTL) {
22514 		ipsec_mp = mp;
22515 		mp = mp->b_cont;
22516 		mctl_present = B_TRUE;
22517 	} else {
22518 		ipsec_mp = mp;
22519 		mctl_present = B_FALSE;
22520 	}
22521 
22522 	if (str && q && tcps->tcps_dbg) {
22523 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22524 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22525 		    "flags 0x%x",
22526 		    str, seq, ack, ctl);
22527 	}
22528 	if (mp->b_datap->db_ref != 1) {
22529 		mblk_t *mp1 = copyb(mp);
22530 		freemsg(mp);
22531 		mp = mp1;
22532 		if (!mp) {
22533 			if (mctl_present)
22534 				freeb(ipsec_mp);
22535 			return;
22536 		} else {
22537 			if (mctl_present) {
22538 				ipsec_mp->b_cont = mp;
22539 			} else {
22540 				ipsec_mp = mp;
22541 			}
22542 		}
22543 	} else if (mp->b_cont) {
22544 		freemsg(mp->b_cont);
22545 		mp->b_cont = NULL;
22546 	}
22547 	/*
22548 	 * We skip reversing source route here.
22549 	 * (for now we replace all IP options with EOL)
22550 	 */
22551 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22552 		ipha = (ipha_t *)mp->b_rptr;
22553 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22554 			mp->b_rptr[i] = IPOPT_EOL;
22555 		/*
22556 		 * Make sure that src address isn't flagrantly invalid.
22557 		 * Not all broadcast address checking for the src address
22558 		 * is possible, since we don't know the netmask of the src
22559 		 * addr.  No check for destination address is done, since
22560 		 * IP will not pass up a packet with a broadcast dest
22561 		 * address to TCP.  Similar checks are done below for IPv6.
22562 		 */
22563 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22564 		    CLASSD(ipha->ipha_src)) {
22565 			freemsg(ipsec_mp);
22566 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22567 			return;
22568 		}
22569 	} else {
22570 		ip6h = (ip6_t *)mp->b_rptr;
22571 
22572 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22573 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22574 			freemsg(ipsec_mp);
22575 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22576 			return;
22577 		}
22578 
22579 		/* Remove any extension headers assuming partial overlay */
22580 		if (ip_hdr_len > IPV6_HDR_LEN) {
22581 			uint8_t *to;
22582 
22583 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22584 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22585 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22586 			ip_hdr_len = IPV6_HDR_LEN;
22587 			ip6h = (ip6_t *)mp->b_rptr;
22588 			ip6h->ip6_nxt = IPPROTO_TCP;
22589 		}
22590 	}
22591 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22592 	if (tcph->th_flags[0] & TH_RST) {
22593 		freemsg(ipsec_mp);
22594 		return;
22595 	}
22596 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22597 	len = ip_hdr_len + sizeof (tcph_t);
22598 	mp->b_wptr = &mp->b_rptr[len];
22599 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22600 		ipha->ipha_length = htons(len);
22601 		/* Swap addresses */
22602 		v4addr = ipha->ipha_src;
22603 		ipha->ipha_src = ipha->ipha_dst;
22604 		ipha->ipha_dst = v4addr;
22605 		ipha->ipha_ident = 0;
22606 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22607 		addr_len = IP_ADDR_LEN;
22608 		addr = &v4addr;
22609 	} else {
22610 		/* No ip6i_t in this case */
22611 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22612 		/* Swap addresses */
22613 		v6addr = ip6h->ip6_src;
22614 		ip6h->ip6_src = ip6h->ip6_dst;
22615 		ip6h->ip6_dst = v6addr;
22616 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22617 		addr_len = IPV6_ADDR_LEN;
22618 		addr = &v6addr;
22619 	}
22620 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22621 	U32_TO_BE32(ack, tcph->th_ack);
22622 	U32_TO_BE32(seq, tcph->th_seq);
22623 	U16_TO_BE16(0, tcph->th_win);
22624 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22625 	tcph->th_flags[0] = (uint8_t)ctl;
22626 	if (ctl & TH_RST) {
22627 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22628 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22629 	}
22630 
22631 	/* IP trusts us to set up labels when required. */
22632 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22633 	    crgetlabel(cr) != NULL) {
22634 		int err, adjust;
22635 
22636 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22637 			err = tsol_check_label(cr, &mp, &adjust,
22638 			    tcp->tcp_connp->conn_mac_exempt,
22639 			    tcps->tcps_netstack->netstack_ip);
22640 		else
22641 			err = tsol_check_label_v6(cr, &mp, &adjust,
22642 			    tcp->tcp_connp->conn_mac_exempt,
22643 			    tcps->tcps_netstack->netstack_ip);
22644 		if (mctl_present)
22645 			ipsec_mp->b_cont = mp;
22646 		else
22647 			ipsec_mp = mp;
22648 		if (err != 0) {
22649 			freemsg(ipsec_mp);
22650 			return;
22651 		}
22652 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22653 			ipha = (ipha_t *)mp->b_rptr;
22654 			adjust += ntohs(ipha->ipha_length);
22655 			ipha->ipha_length = htons(adjust);
22656 		} else {
22657 			ip6h = (ip6_t *)mp->b_rptr;
22658 		}
22659 	}
22660 
22661 	if (mctl_present) {
22662 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22663 
22664 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22665 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22666 			return;
22667 		}
22668 	}
22669 	if (zoneid == ALL_ZONES)
22670 		zoneid = GLOBAL_ZONEID;
22671 
22672 	/* Add the zoneid so ip_output routes it properly */
22673 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22674 		freemsg(ipsec_mp);
22675 		return;
22676 	}
22677 	ipsec_mp = nmp;
22678 
22679 	/*
22680 	 * NOTE:  one might consider tracing a TCP packet here, but
22681 	 * this function has no active TCP state and no tcp structure
22682 	 * that has a trace buffer.  If we traced here, we would have
22683 	 * to keep a local trace buffer in tcp_record_trace().
22684 	 *
22685 	 * TSol note: The mblk that contains the incoming packet was
22686 	 * reused by tcp_xmit_listener_reset, so it already contains
22687 	 * the right credentials and we don't need to call mblk_setcred.
22688 	 * Also the conn's cred is not right since it is associated
22689 	 * with tcps_g_q.
22690 	 */
22691 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22692 
22693 	/*
22694 	 * Tell IP to mark the IRE used for this destination temporary.
22695 	 * This way, we can limit our exposure to DoS attack because IP
22696 	 * creates an IRE for each destination.  If there are too many,
22697 	 * the time to do any routing lookup will be extremely long.  And
22698 	 * the lookup can be in interrupt context.
22699 	 *
22700 	 * Note that in normal circumstances, this marking should not
22701 	 * affect anything.  It would be nice if only 1 message is
22702 	 * needed to inform IP that the IRE created for this RST should
22703 	 * not be added to the cache table.  But there is currently
22704 	 * not such communication mechanism between TCP and IP.  So
22705 	 * the best we can do now is to send the advice ioctl to IP
22706 	 * to mark the IRE temporary.
22707 	 */
22708 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22709 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22710 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22711 	}
22712 }
22713 
22714 /*
22715  * Initiate closedown sequence on an active connection.  (May be called as
22716  * writer.)  Return value zero for OK return, non-zero for error return.
22717  */
22718 static int
22719 tcp_xmit_end(tcp_t *tcp)
22720 {
22721 	ipic_t	*ipic;
22722 	mblk_t	*mp;
22723 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22724 
22725 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22726 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22727 		/*
22728 		 * Invalid state, only states TCPS_SYN_RCVD,
22729 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22730 		 */
22731 		return (-1);
22732 	}
22733 
22734 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22735 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22736 	/*
22737 	 * If there is nothing more unsent, send the FIN now.
22738 	 * Otherwise, it will go out with the last segment.
22739 	 */
22740 	if (tcp->tcp_unsent == 0) {
22741 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22742 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22743 
22744 		if (mp) {
22745 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22746 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22747 		} else {
22748 			/*
22749 			 * Couldn't allocate msg.  Pretend we got it out.
22750 			 * Wait for rexmit timeout.
22751 			 */
22752 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22753 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22754 		}
22755 
22756 		/*
22757 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22758 		 * changed.
22759 		 */
22760 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22761 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22762 		}
22763 	} else {
22764 		/*
22765 		 * If tcp->tcp_cork is set, then the data will not get sent,
22766 		 * so we have to check that and unset it first.
22767 		 */
22768 		if (tcp->tcp_cork)
22769 			tcp->tcp_cork = B_FALSE;
22770 		tcp_wput_data(tcp, NULL, B_FALSE);
22771 	}
22772 
22773 	/*
22774 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22775 	 * is 0, don't update the cache.
22776 	 */
22777 	if (tcps->tcps_rtt_updates == 0 ||
22778 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22779 		return (0);
22780 
22781 	/*
22782 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22783 	 * different from the destination.
22784 	 */
22785 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22786 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22787 			return (0);
22788 		}
22789 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22790 		    &ipic);
22791 	} else {
22792 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22793 		    &tcp->tcp_ip6h->ip6_dst))) {
22794 			return (0);
22795 		}
22796 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22797 		    &ipic);
22798 	}
22799 
22800 	/* Record route attributes in the IRE for use by future connections. */
22801 	if (mp == NULL)
22802 		return (0);
22803 
22804 	/*
22805 	 * We do not have a good algorithm to update ssthresh at this time.
22806 	 * So don't do any update.
22807 	 */
22808 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22809 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22810 
22811 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22812 	return (0);
22813 }
22814 
22815 /*
22816  * Generate a "no listener here" RST in response to an "unknown" segment.
22817  * connp is set by caller when RST is in response to an unexpected
22818  * inbound packet for which there is active tcp state in the system.
22819  * Note that we are reusing the incoming mp to construct the outgoing RST.
22820  */
22821 void
22822 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22823     tcp_stack_t *tcps, conn_t *connp)
22824 {
22825 	uchar_t		*rptr;
22826 	uint32_t	seg_len;
22827 	tcph_t		*tcph;
22828 	uint32_t	seg_seq;
22829 	uint32_t	seg_ack;
22830 	uint_t		flags;
22831 	mblk_t		*ipsec_mp;
22832 	ipha_t 		*ipha;
22833 	ip6_t 		*ip6h;
22834 	boolean_t	mctl_present = B_FALSE;
22835 	boolean_t	check = B_TRUE;
22836 	boolean_t	policy_present;
22837 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22838 
22839 	TCP_STAT(tcps, tcp_no_listener);
22840 
22841 	ipsec_mp = mp;
22842 
22843 	if (mp->b_datap->db_type == M_CTL) {
22844 		ipsec_in_t *ii;
22845 
22846 		mctl_present = B_TRUE;
22847 		mp = mp->b_cont;
22848 
22849 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22850 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22851 		if (ii->ipsec_in_dont_check) {
22852 			check = B_FALSE;
22853 			if (!ii->ipsec_in_secure) {
22854 				freeb(ipsec_mp);
22855 				mctl_present = B_FALSE;
22856 				ipsec_mp = mp;
22857 			}
22858 		}
22859 	}
22860 
22861 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22862 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22863 		ipha = (ipha_t *)mp->b_rptr;
22864 		ip6h = NULL;
22865 	} else {
22866 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22867 		ipha = NULL;
22868 		ip6h = (ip6_t *)mp->b_rptr;
22869 	}
22870 
22871 	if (check && policy_present) {
22872 		/*
22873 		 * The conn_t parameter is NULL because we already know
22874 		 * nobody's home.
22875 		 */
22876 		ipsec_mp = ipsec_check_global_policy(
22877 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22878 		    tcps->tcps_netstack);
22879 		if (ipsec_mp == NULL)
22880 			return;
22881 	}
22882 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22883 		DTRACE_PROBE2(
22884 		    tx__ip__log__error__nolistener__tcp,
22885 		    char *, "Could not reply with RST to mp(1)",
22886 		    mblk_t *, mp);
22887 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22888 		freemsg(ipsec_mp);
22889 		return;
22890 	}
22891 
22892 	rptr = mp->b_rptr;
22893 
22894 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22895 	seg_seq = BE32_TO_U32(tcph->th_seq);
22896 	seg_ack = BE32_TO_U32(tcph->th_ack);
22897 	flags = tcph->th_flags[0];
22898 
22899 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22900 	if (flags & TH_RST) {
22901 		freemsg(ipsec_mp);
22902 	} else if (flags & TH_ACK) {
22903 		tcp_xmit_early_reset("no tcp, reset",
22904 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
22905 		    connp);
22906 	} else {
22907 		if (flags & TH_SYN) {
22908 			seg_len++;
22909 		} else {
22910 			/*
22911 			 * Here we violate the RFC.  Note that a normal
22912 			 * TCP will never send a segment without the ACK
22913 			 * flag, except for RST or SYN segment.  This
22914 			 * segment is neither.  Just drop it on the
22915 			 * floor.
22916 			 */
22917 			freemsg(ipsec_mp);
22918 			tcps->tcps_rst_unsent++;
22919 			return;
22920 		}
22921 
22922 		tcp_xmit_early_reset("no tcp, reset/ack",
22923 		    ipsec_mp, 0, seg_seq + seg_len,
22924 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
22925 	}
22926 }
22927 
22928 /*
22929  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22930  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22931  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22932  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22933  * otherwise it will dup partial mblks.)
22934  * Otherwise, an appropriate ACK packet will be generated.  This
22935  * routine is not usually called to send new data for the first time.  It
22936  * is mostly called out of the timer for retransmits, and to generate ACKs.
22937  *
22938  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22939  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22940  * of the original mblk chain will be returned in *offset and *end_mp.
22941  */
22942 mblk_t *
22943 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22944     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22945     boolean_t rexmit)
22946 {
22947 	int	data_length;
22948 	int32_t	off = 0;
22949 	uint_t	flags;
22950 	mblk_t	*mp1;
22951 	mblk_t	*mp2;
22952 	uchar_t	*rptr;
22953 	tcph_t	*tcph;
22954 	int32_t	num_sack_blk = 0;
22955 	int32_t	sack_opt_len = 0;
22956 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22957 
22958 	/* Allocate for our maximum TCP header + link-level */
22959 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22960 	    tcps->tcps_wroff_xtra, BPRI_MED);
22961 	if (!mp1)
22962 		return (NULL);
22963 	data_length = 0;
22964 
22965 	/*
22966 	 * Note that tcp_mss has been adjusted to take into account the
22967 	 * timestamp option if applicable.  Because SACK options do not
22968 	 * appear in every TCP segments and they are of variable lengths,
22969 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22970 	 * the actual segment length when we need to send a segment which
22971 	 * includes SACK options.
22972 	 */
22973 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22974 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22975 		    tcp->tcp_num_sack_blk);
22976 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22977 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22978 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22979 			max_to_send -= sack_opt_len;
22980 	}
22981 
22982 	if (offset != NULL) {
22983 		off = *offset;
22984 		/* We use offset as an indicator that end_mp is not NULL. */
22985 		*end_mp = NULL;
22986 	}
22987 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22988 		/* This could be faster with cooperation from downstream */
22989 		if (mp2 != mp1 && !sendall &&
22990 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22991 		    max_to_send)
22992 			/*
22993 			 * Don't send the next mblk since the whole mblk
22994 			 * does not fit.
22995 			 */
22996 			break;
22997 		mp2->b_cont = dupb(mp);
22998 		mp2 = mp2->b_cont;
22999 		if (!mp2) {
23000 			freemsg(mp1);
23001 			return (NULL);
23002 		}
23003 		mp2->b_rptr += off;
23004 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23005 		    (uintptr_t)INT_MAX);
23006 
23007 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23008 		if (data_length > max_to_send) {
23009 			mp2->b_wptr -= data_length - max_to_send;
23010 			data_length = max_to_send;
23011 			off = mp2->b_wptr - mp->b_rptr;
23012 			break;
23013 		} else {
23014 			off = 0;
23015 		}
23016 	}
23017 	if (offset != NULL) {
23018 		*offset = off;
23019 		*end_mp = mp;
23020 	}
23021 	if (seg_len != NULL) {
23022 		*seg_len = data_length;
23023 	}
23024 
23025 	/* Update the latest receive window size in TCP header. */
23026 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23027 	    tcp->tcp_tcph->th_win);
23028 
23029 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23030 	mp1->b_rptr = rptr;
23031 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23032 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23033 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23034 	U32_TO_ABE32(seq, tcph->th_seq);
23035 
23036 	/*
23037 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23038 	 * that this function was called from tcp_wput_data. Thus, when called
23039 	 * to retransmit data the setting of the PUSH bit may appear some
23040 	 * what random in that it might get set when it should not. This
23041 	 * should not pose any performance issues.
23042 	 */
23043 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23044 	    tcp->tcp_unsent == data_length)) {
23045 		flags = TH_ACK | TH_PUSH;
23046 	} else {
23047 		flags = TH_ACK;
23048 	}
23049 
23050 	if (tcp->tcp_ecn_ok) {
23051 		if (tcp->tcp_ecn_echo_on)
23052 			flags |= TH_ECE;
23053 
23054 		/*
23055 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23056 		 * There is no TCP flow control for non-data segments, and
23057 		 * only data segment is transmitted reliably.
23058 		 */
23059 		if (data_length > 0 && !rexmit) {
23060 			SET_ECT(tcp, rptr);
23061 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23062 				flags |= TH_CWR;
23063 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23064 			}
23065 		}
23066 	}
23067 
23068 	if (tcp->tcp_valid_bits) {
23069 		uint32_t u1;
23070 
23071 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23072 		    seq == tcp->tcp_iss) {
23073 			uchar_t	*wptr;
23074 
23075 			/*
23076 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23077 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23078 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23079 			 * our SYN is not ack'ed but the app closes this
23080 			 * TCP connection.
23081 			 */
23082 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23083 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23084 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23085 
23086 			/*
23087 			 * Tack on the MSS option.  It is always needed
23088 			 * for both active and passive open.
23089 			 *
23090 			 * MSS option value should be interface MTU - MIN
23091 			 * TCP/IP header according to RFC 793 as it means
23092 			 * the maximum segment size TCP can receive.  But
23093 			 * to get around some broken middle boxes/end hosts
23094 			 * out there, we allow the option value to be the
23095 			 * same as the MSS option size on the peer side.
23096 			 * In this way, the other side will not send
23097 			 * anything larger than they can receive.
23098 			 *
23099 			 * Note that for SYN_SENT state, the ndd param
23100 			 * tcp_use_smss_as_mss_opt has no effect as we
23101 			 * don't know the peer's MSS option value. So
23102 			 * the only case we need to take care of is in
23103 			 * SYN_RCVD state, which is done later.
23104 			 */
23105 			wptr = mp1->b_wptr;
23106 			wptr[0] = TCPOPT_MAXSEG;
23107 			wptr[1] = TCPOPT_MAXSEG_LEN;
23108 			wptr += 2;
23109 			u1 = tcp->tcp_if_mtu -
23110 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23111 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23112 			    TCP_MIN_HEADER_LENGTH;
23113 			U16_TO_BE16(u1, wptr);
23114 			mp1->b_wptr = wptr + 2;
23115 			/* Update the offset to cover the additional word */
23116 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23117 
23118 			/*
23119 			 * Note that the following way of filling in
23120 			 * TCP options are not optimal.  Some NOPs can
23121 			 * be saved.  But there is no need at this time
23122 			 * to optimize it.  When it is needed, we will
23123 			 * do it.
23124 			 */
23125 			switch (tcp->tcp_state) {
23126 			case TCPS_SYN_SENT:
23127 				flags = TH_SYN;
23128 
23129 				if (tcp->tcp_snd_ts_ok) {
23130 					uint32_t llbolt = (uint32_t)lbolt;
23131 
23132 					wptr = mp1->b_wptr;
23133 					wptr[0] = TCPOPT_NOP;
23134 					wptr[1] = TCPOPT_NOP;
23135 					wptr[2] = TCPOPT_TSTAMP;
23136 					wptr[3] = TCPOPT_TSTAMP_LEN;
23137 					wptr += 4;
23138 					U32_TO_BE32(llbolt, wptr);
23139 					wptr += 4;
23140 					ASSERT(tcp->tcp_ts_recent == 0);
23141 					U32_TO_BE32(0L, wptr);
23142 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23143 					tcph->th_offset_and_rsrvd[0] +=
23144 					    (3 << 4);
23145 				}
23146 
23147 				/*
23148 				 * Set up all the bits to tell other side
23149 				 * we are ECN capable.
23150 				 */
23151 				if (tcp->tcp_ecn_ok) {
23152 					flags |= (TH_ECE | TH_CWR);
23153 				}
23154 				break;
23155 			case TCPS_SYN_RCVD:
23156 				flags |= TH_SYN;
23157 
23158 				/*
23159 				 * Reset the MSS option value to be SMSS
23160 				 * We should probably add back the bytes
23161 				 * for timestamp option and IPsec.  We
23162 				 * don't do that as this is a workaround
23163 				 * for broken middle boxes/end hosts, it
23164 				 * is better for us to be more cautious.
23165 				 * They may not take these things into
23166 				 * account in their SMSS calculation.  Thus
23167 				 * the peer's calculated SMSS may be smaller
23168 				 * than what it can be.  This should be OK.
23169 				 */
23170 				if (tcps->tcps_use_smss_as_mss_opt) {
23171 					u1 = tcp->tcp_mss;
23172 					U16_TO_BE16(u1, wptr);
23173 				}
23174 
23175 				/*
23176 				 * If the other side is ECN capable, reply
23177 				 * that we are also ECN capable.
23178 				 */
23179 				if (tcp->tcp_ecn_ok)
23180 					flags |= TH_ECE;
23181 				break;
23182 			default:
23183 				/*
23184 				 * The above ASSERT() makes sure that this
23185 				 * must be FIN-WAIT-1 state.  Our SYN has
23186 				 * not been ack'ed so retransmit it.
23187 				 */
23188 				flags |= TH_SYN;
23189 				break;
23190 			}
23191 
23192 			if (tcp->tcp_snd_ws_ok) {
23193 				wptr = mp1->b_wptr;
23194 				wptr[0] =  TCPOPT_NOP;
23195 				wptr[1] =  TCPOPT_WSCALE;
23196 				wptr[2] =  TCPOPT_WS_LEN;
23197 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23198 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23199 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23200 			}
23201 
23202 			if (tcp->tcp_snd_sack_ok) {
23203 				wptr = mp1->b_wptr;
23204 				wptr[0] = TCPOPT_NOP;
23205 				wptr[1] = TCPOPT_NOP;
23206 				wptr[2] = TCPOPT_SACK_PERMITTED;
23207 				wptr[3] = TCPOPT_SACK_OK_LEN;
23208 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23209 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23210 			}
23211 
23212 			/* allocb() of adequate mblk assures space */
23213 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23214 			    (uintptr_t)INT_MAX);
23215 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23216 			/*
23217 			 * Get IP set to checksum on our behalf
23218 			 * Include the adjustment for a source route if any.
23219 			 */
23220 			u1 += tcp->tcp_sum;
23221 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23222 			U16_TO_BE16(u1, tcph->th_sum);
23223 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23224 		}
23225 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23226 		    (seq + data_length) == tcp->tcp_fss) {
23227 			if (!tcp->tcp_fin_acked) {
23228 				flags |= TH_FIN;
23229 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23230 			}
23231 			if (!tcp->tcp_fin_sent) {
23232 				tcp->tcp_fin_sent = B_TRUE;
23233 				switch (tcp->tcp_state) {
23234 				case TCPS_SYN_RCVD:
23235 				case TCPS_ESTABLISHED:
23236 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23237 					break;
23238 				case TCPS_CLOSE_WAIT:
23239 					tcp->tcp_state = TCPS_LAST_ACK;
23240 					break;
23241 				}
23242 				if (tcp->tcp_suna == tcp->tcp_snxt)
23243 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23244 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23245 			}
23246 		}
23247 		/*
23248 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23249 		 * is smaller than seq, u1 will become a very huge value.
23250 		 * So the comparison will fail.  Also note that tcp_urp
23251 		 * should be positive, see RFC 793 page 17.
23252 		 */
23253 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23254 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23255 		    u1 < (uint32_t)(64 * 1024)) {
23256 			flags |= TH_URG;
23257 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23258 			U32_TO_ABE16(u1, tcph->th_urp);
23259 		}
23260 	}
23261 	tcph->th_flags[0] = (uchar_t)flags;
23262 	tcp->tcp_rack = tcp->tcp_rnxt;
23263 	tcp->tcp_rack_cnt = 0;
23264 
23265 	if (tcp->tcp_snd_ts_ok) {
23266 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23267 			uint32_t llbolt = (uint32_t)lbolt;
23268 
23269 			U32_TO_BE32(llbolt,
23270 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23271 			U32_TO_BE32(tcp->tcp_ts_recent,
23272 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23273 		}
23274 	}
23275 
23276 	if (num_sack_blk > 0) {
23277 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23278 		sack_blk_t *tmp;
23279 		int32_t	i;
23280 
23281 		wptr[0] = TCPOPT_NOP;
23282 		wptr[1] = TCPOPT_NOP;
23283 		wptr[2] = TCPOPT_SACK;
23284 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23285 		    sizeof (sack_blk_t);
23286 		wptr += TCPOPT_REAL_SACK_LEN;
23287 
23288 		tmp = tcp->tcp_sack_list;
23289 		for (i = 0; i < num_sack_blk; i++) {
23290 			U32_TO_BE32(tmp[i].begin, wptr);
23291 			wptr += sizeof (tcp_seq);
23292 			U32_TO_BE32(tmp[i].end, wptr);
23293 			wptr += sizeof (tcp_seq);
23294 		}
23295 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23296 	}
23297 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23298 	data_length += (int)(mp1->b_wptr - rptr);
23299 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23300 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23301 	} else {
23302 		ip6_t *ip6 = (ip6_t *)(rptr +
23303 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23304 		    sizeof (ip6i_t) : 0));
23305 
23306 		ip6->ip6_plen = htons(data_length -
23307 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23308 	}
23309 
23310 	/*
23311 	 * Prime pump for IP
23312 	 * Include the adjustment for a source route if any.
23313 	 */
23314 	data_length -= tcp->tcp_ip_hdr_len;
23315 	data_length += tcp->tcp_sum;
23316 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23317 	U16_TO_ABE16(data_length, tcph->th_sum);
23318 	if (tcp->tcp_ip_forward_progress) {
23319 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23320 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23321 		tcp->tcp_ip_forward_progress = B_FALSE;
23322 	}
23323 	return (mp1);
23324 }
23325 
23326 /* This function handles the push timeout. */
23327 void
23328 tcp_push_timer(void *arg)
23329 {
23330 	conn_t	*connp = (conn_t *)arg;
23331 	tcp_t *tcp = connp->conn_tcp;
23332 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23333 
23334 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23335 
23336 	ASSERT(tcp->tcp_listener == NULL);
23337 
23338 	/*
23339 	 * We need to plug synchronous streams during our drain to prevent
23340 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23341 	 */
23342 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23343 	tcp->tcp_push_tid = 0;
23344 	if ((tcp->tcp_rcv_list != NULL) &&
23345 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
23346 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23347 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23348 }
23349 
23350 /*
23351  * This function handles delayed ACK timeout.
23352  */
23353 static void
23354 tcp_ack_timer(void *arg)
23355 {
23356 	conn_t	*connp = (conn_t *)arg;
23357 	tcp_t *tcp = connp->conn_tcp;
23358 	mblk_t *mp;
23359 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23360 
23361 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23362 
23363 	tcp->tcp_ack_tid = 0;
23364 
23365 	if (tcp->tcp_fused)
23366 		return;
23367 
23368 	/*
23369 	 * Do not send ACK if there is no outstanding unack'ed data.
23370 	 */
23371 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23372 		return;
23373 	}
23374 
23375 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23376 		/*
23377 		 * Make sure we don't allow deferred ACKs to result in
23378 		 * timer-based ACKing.  If we have held off an ACK
23379 		 * when there was more than an mss here, and the timer
23380 		 * goes off, we have to worry about the possibility
23381 		 * that the sender isn't doing slow-start, or is out
23382 		 * of step with us for some other reason.  We fall
23383 		 * permanently back in the direction of
23384 		 * ACK-every-other-packet as suggested in RFC 1122.
23385 		 */
23386 		if (tcp->tcp_rack_abs_max > 2)
23387 			tcp->tcp_rack_abs_max--;
23388 		tcp->tcp_rack_cur_max = 2;
23389 	}
23390 	mp = tcp_ack_mp(tcp);
23391 
23392 	if (mp != NULL) {
23393 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23394 		BUMP_LOCAL(tcp->tcp_obsegs);
23395 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23396 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23397 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23398 	}
23399 }
23400 
23401 
23402 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23403 static mblk_t *
23404 tcp_ack_mp(tcp_t *tcp)
23405 {
23406 	uint32_t	seq_no;
23407 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23408 
23409 	/*
23410 	 * There are a few cases to be considered while setting the sequence no.
23411 	 * Essentially, we can come here while processing an unacceptable pkt
23412 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23413 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23414 	 * If we are here for a zero window probe, stick with suna. In all
23415 	 * other cases, we check if suna + swnd encompasses snxt and set
23416 	 * the sequence number to snxt, if so. If snxt falls outside the
23417 	 * window (the receiver probably shrunk its window), we will go with
23418 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23419 	 * receiver.
23420 	 */
23421 	if (tcp->tcp_zero_win_probe) {
23422 		seq_no = tcp->tcp_suna;
23423 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23424 		ASSERT(tcp->tcp_swnd == 0);
23425 		seq_no = tcp->tcp_snxt;
23426 	} else {
23427 		seq_no = SEQ_GT(tcp->tcp_snxt,
23428 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23429 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23430 	}
23431 
23432 	if (tcp->tcp_valid_bits) {
23433 		/*
23434 		 * For the complex case where we have to send some
23435 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23436 		 */
23437 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23438 		    NULL, B_FALSE));
23439 	} else {
23440 		/* Generate a simple ACK */
23441 		int	data_length;
23442 		uchar_t	*rptr;
23443 		tcph_t	*tcph;
23444 		mblk_t	*mp1;
23445 		int32_t	tcp_hdr_len;
23446 		int32_t	tcp_tcp_hdr_len;
23447 		int32_t	num_sack_blk = 0;
23448 		int32_t sack_opt_len;
23449 
23450 		/*
23451 		 * Allocate space for TCP + IP headers
23452 		 * and link-level header
23453 		 */
23454 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23455 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23456 			    tcp->tcp_num_sack_blk);
23457 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23458 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23459 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23460 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23461 		} else {
23462 			tcp_hdr_len = tcp->tcp_hdr_len;
23463 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23464 		}
23465 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23466 		if (!mp1)
23467 			return (NULL);
23468 
23469 		/* Update the latest receive window size in TCP header. */
23470 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23471 		    tcp->tcp_tcph->th_win);
23472 		/* copy in prototype TCP + IP header */
23473 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23474 		mp1->b_rptr = rptr;
23475 		mp1->b_wptr = rptr + tcp_hdr_len;
23476 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23477 
23478 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23479 
23480 		/* Set the TCP sequence number. */
23481 		U32_TO_ABE32(seq_no, tcph->th_seq);
23482 
23483 		/* Set up the TCP flag field. */
23484 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23485 		if (tcp->tcp_ecn_echo_on)
23486 			tcph->th_flags[0] |= TH_ECE;
23487 
23488 		tcp->tcp_rack = tcp->tcp_rnxt;
23489 		tcp->tcp_rack_cnt = 0;
23490 
23491 		/* fill in timestamp option if in use */
23492 		if (tcp->tcp_snd_ts_ok) {
23493 			uint32_t llbolt = (uint32_t)lbolt;
23494 
23495 			U32_TO_BE32(llbolt,
23496 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23497 			U32_TO_BE32(tcp->tcp_ts_recent,
23498 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23499 		}
23500 
23501 		/* Fill in SACK options */
23502 		if (num_sack_blk > 0) {
23503 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23504 			sack_blk_t *tmp;
23505 			int32_t	i;
23506 
23507 			wptr[0] = TCPOPT_NOP;
23508 			wptr[1] = TCPOPT_NOP;
23509 			wptr[2] = TCPOPT_SACK;
23510 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23511 			    sizeof (sack_blk_t);
23512 			wptr += TCPOPT_REAL_SACK_LEN;
23513 
23514 			tmp = tcp->tcp_sack_list;
23515 			for (i = 0; i < num_sack_blk; i++) {
23516 				U32_TO_BE32(tmp[i].begin, wptr);
23517 				wptr += sizeof (tcp_seq);
23518 				U32_TO_BE32(tmp[i].end, wptr);
23519 				wptr += sizeof (tcp_seq);
23520 			}
23521 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23522 			    << 4);
23523 		}
23524 
23525 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23526 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23527 		} else {
23528 			/* Check for ip6i_t header in sticky hdrs */
23529 			ip6_t *ip6 = (ip6_t *)(rptr +
23530 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23531 			    sizeof (ip6i_t) : 0));
23532 
23533 			ip6->ip6_plen = htons(tcp_hdr_len -
23534 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23535 		}
23536 
23537 		/*
23538 		 * Prime pump for checksum calculation in IP.  Include the
23539 		 * adjustment for a source route if any.
23540 		 */
23541 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23542 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23543 		U16_TO_ABE16(data_length, tcph->th_sum);
23544 
23545 		if (tcp->tcp_ip_forward_progress) {
23546 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23547 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23548 			tcp->tcp_ip_forward_progress = B_FALSE;
23549 		}
23550 		return (mp1);
23551 	}
23552 }
23553 
23554 /*
23555  * To create a temporary tcp structure for inserting into bind hash list.
23556  * The parameter is assumed to be in network byte order, ready for use.
23557  */
23558 /* ARGSUSED */
23559 static tcp_t *
23560 tcp_alloc_temp_tcp(in_port_t port, tcp_stack_t *tcps)
23561 {
23562 	conn_t	*connp;
23563 	tcp_t	*tcp;
23564 
23565 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP, tcps->tcps_netstack);
23566 	if (connp == NULL)
23567 		return (NULL);
23568 
23569 	tcp = connp->conn_tcp;
23570 	tcp->tcp_tcps = tcps;
23571 	TCPS_REFHOLD(tcps);
23572 
23573 	/*
23574 	 * Only initialize the necessary info in those structures.  Note
23575 	 * that since INADDR_ANY is all 0, we do not need to set
23576 	 * tcp_bound_source to INADDR_ANY here.
23577 	 */
23578 	tcp->tcp_state = TCPS_BOUND;
23579 	tcp->tcp_lport = port;
23580 	tcp->tcp_exclbind = 1;
23581 	tcp->tcp_reserved_port = 1;
23582 
23583 	/* Just for place holding... */
23584 	tcp->tcp_ipversion = IPV4_VERSION;
23585 
23586 	return (tcp);
23587 }
23588 
23589 /*
23590  * To remove a port range specified by lo_port and hi_port from the
23591  * reserved port ranges.  This is one of the three public functions of
23592  * the reserved port interface.  Note that a port range has to be removed
23593  * as a whole.  Ports in a range cannot be removed individually.
23594  *
23595  * Params:
23596  *	in_port_t lo_port: the beginning port of the reserved port range to
23597  *		be deleted.
23598  *	in_port_t hi_port: the ending port of the reserved port range to
23599  *		be deleted.
23600  *
23601  * Return:
23602  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
23603  *
23604  * Assumes that nca is only for zoneid=0
23605  */
23606 boolean_t
23607 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
23608 {
23609 	int	i, j;
23610 	int	size;
23611 	tcp_t	**temp_tcp_array;
23612 	tcp_t	*tcp;
23613 	tcp_stack_t	*tcps;
23614 
23615 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23616 	ASSERT(tcps != NULL);
23617 
23618 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23619 
23620 	/* First make sure that the port ranage is indeed reserved. */
23621 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23622 		if (tcps->tcps_reserved_port[i].lo_port == lo_port) {
23623 			hi_port = tcps->tcps_reserved_port[i].hi_port;
23624 			temp_tcp_array =
23625 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23626 			break;
23627 		}
23628 	}
23629 	if (i == tcps->tcps_reserved_port_array_size) {
23630 		rw_exit(&tcps->tcps_reserved_port_lock);
23631 		netstack_rele(tcps->tcps_netstack);
23632 		return (B_FALSE);
23633 	}
23634 
23635 	/*
23636 	 * Remove the range from the array.  This simple loop is possible
23637 	 * because port ranges are inserted in ascending order.
23638 	 */
23639 	for (j = i; j < tcps->tcps_reserved_port_array_size - 1; j++) {
23640 		tcps->tcps_reserved_port[j].lo_port =
23641 		    tcps->tcps_reserved_port[j+1].lo_port;
23642 		tcps->tcps_reserved_port[j].hi_port =
23643 		    tcps->tcps_reserved_port[j+1].hi_port;
23644 		tcps->tcps_reserved_port[j].temp_tcp_array =
23645 		    tcps->tcps_reserved_port[j+1].temp_tcp_array;
23646 	}
23647 
23648 	/* Remove all the temporary tcp structures. */
23649 	size = hi_port - lo_port + 1;
23650 	while (size > 0) {
23651 		tcp = temp_tcp_array[size - 1];
23652 		ASSERT(tcp != NULL);
23653 		tcp_bind_hash_remove(tcp);
23654 		CONN_DEC_REF(tcp->tcp_connp);
23655 		size--;
23656 	}
23657 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
23658 	tcps->tcps_reserved_port_array_size--;
23659 	rw_exit(&tcps->tcps_reserved_port_lock);
23660 	netstack_rele(tcps->tcps_netstack);
23661 	return (B_TRUE);
23662 }
23663 
23664 /*
23665  * Macro to remove temporary tcp structure from the bind hash list.  The
23666  * first parameter is the list of tcp to be removed.  The second parameter
23667  * is the number of tcps in the array.
23668  */
23669 #define	TCP_TMP_TCP_REMOVE(tcp_array, num, tcps) \
23670 { \
23671 	while ((num) > 0) { \
23672 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
23673 		tf_t *tbf; \
23674 		tcp_t *tcpnext; \
23675 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
23676 		mutex_enter(&tbf->tf_lock); \
23677 		tcpnext = tcp->tcp_bind_hash; \
23678 		if (tcpnext) { \
23679 			tcpnext->tcp_ptpbhn = \
23680 				tcp->tcp_ptpbhn; \
23681 		} \
23682 		*tcp->tcp_ptpbhn = tcpnext; \
23683 		mutex_exit(&tbf->tf_lock); \
23684 		kmem_free(tcp, sizeof (tcp_t)); \
23685 		(tcp_array)[(num) - 1] = NULL; \
23686 		(num)--; \
23687 	} \
23688 }
23689 
23690 /*
23691  * The public interface for other modules to call to reserve a port range
23692  * in TCP.  The caller passes in how large a port range it wants.  TCP
23693  * will try to find a range and return it via lo_port and hi_port.  This is
23694  * used by NCA's nca_conn_init.
23695  * NCA can only be used in the global zone so this only affects the global
23696  * zone's ports.
23697  *
23698  * Params:
23699  *	int size: the size of the port range to be reserved.
23700  *	in_port_t *lo_port (referenced): returns the beginning port of the
23701  *		reserved port range added.
23702  *	in_port_t *hi_port (referenced): returns the ending port of the
23703  *		reserved port range added.
23704  *
23705  * Return:
23706  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
23707  *
23708  * Assumes that nca is only for zoneid=0
23709  */
23710 boolean_t
23711 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
23712 {
23713 	tcp_t		*tcp;
23714 	tcp_t		*tmp_tcp;
23715 	tcp_t		**temp_tcp_array;
23716 	tf_t		*tbf;
23717 	in_port_t	net_port;
23718 	in_port_t	port;
23719 	int32_t		cur_size;
23720 	int		i, j;
23721 	boolean_t	used;
23722 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
23723 	zoneid_t	zoneid = GLOBAL_ZONEID;
23724 	tcp_stack_t	*tcps;
23725 
23726 	/* Sanity check. */
23727 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
23728 		return (B_FALSE);
23729 	}
23730 
23731 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23732 	ASSERT(tcps != NULL);
23733 
23734 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23735 	if (tcps->tcps_reserved_port_array_size ==
23736 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
23737 		rw_exit(&tcps->tcps_reserved_port_lock);
23738 		netstack_rele(tcps->tcps_netstack);
23739 		return (B_FALSE);
23740 	}
23741 
23742 	/*
23743 	 * Find the starting port to try.  Since the port ranges are ordered
23744 	 * in the reserved port array, we can do a simple search here.
23745 	 */
23746 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
23747 	*hi_port = TCP_LARGEST_RESERVED_PORT;
23748 	for (i = 0; i < tcps->tcps_reserved_port_array_size;
23749 	    *lo_port = tcps->tcps_reserved_port[i].hi_port + 1, i++) {
23750 		if (tcps->tcps_reserved_port[i].lo_port - *lo_port >= size) {
23751 			*hi_port = tcps->tcps_reserved_port[i].lo_port - 1;
23752 			break;
23753 		}
23754 	}
23755 	/* No available port range. */
23756 	if (i == tcps->tcps_reserved_port_array_size &&
23757 	    *hi_port - *lo_port < size) {
23758 		rw_exit(&tcps->tcps_reserved_port_lock);
23759 		netstack_rele(tcps->tcps_netstack);
23760 		return (B_FALSE);
23761 	}
23762 
23763 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
23764 	if (temp_tcp_array == NULL) {
23765 		rw_exit(&tcps->tcps_reserved_port_lock);
23766 		netstack_rele(tcps->tcps_netstack);
23767 		return (B_FALSE);
23768 	}
23769 
23770 	/* Go thru the port range to see if some ports are already bound. */
23771 	for (port = *lo_port, cur_size = 0;
23772 	    cur_size < size && port <= *hi_port;
23773 	    cur_size++, port++) {
23774 		used = B_FALSE;
23775 		net_port = htons(port);
23776 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(net_port)];
23777 		mutex_enter(&tbf->tf_lock);
23778 		for (tcp = tbf->tf_tcp; tcp != NULL;
23779 		    tcp = tcp->tcp_bind_hash) {
23780 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
23781 			    net_port == tcp->tcp_lport) {
23782 				/*
23783 				 * A port is already bound.  Search again
23784 				 * starting from port + 1.  Release all
23785 				 * temporary tcps.
23786 				 */
23787 				mutex_exit(&tbf->tf_lock);
23788 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23789 				    tcps);
23790 				*lo_port = port + 1;
23791 				cur_size = -1;
23792 				used = B_TRUE;
23793 				break;
23794 			}
23795 		}
23796 		if (!used) {
23797 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port, tcps)) ==
23798 			    NULL) {
23799 				/*
23800 				 * Allocation failure.  Just fail the request.
23801 				 * Need to remove all those temporary tcp
23802 				 * structures.
23803 				 */
23804 				mutex_exit(&tbf->tf_lock);
23805 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23806 				    tcps);
23807 				rw_exit(&tcps->tcps_reserved_port_lock);
23808 				kmem_free(temp_tcp_array,
23809 				    (hi_port - lo_port + 1) *
23810 				    sizeof (tcp_t *));
23811 				netstack_rele(tcps->tcps_netstack);
23812 				return (B_FALSE);
23813 			}
23814 			temp_tcp_array[cur_size] = tmp_tcp;
23815 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
23816 			mutex_exit(&tbf->tf_lock);
23817 		}
23818 	}
23819 
23820 	/*
23821 	 * The current range is not large enough.  We can actually do another
23822 	 * search if this search is done between 2 reserved port ranges.  But
23823 	 * for first release, we just stop here and return saying that no port
23824 	 * range is available.
23825 	 */
23826 	if (cur_size < size) {
23827 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size, tcps);
23828 		rw_exit(&tcps->tcps_reserved_port_lock);
23829 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23830 		netstack_rele(tcps->tcps_netstack);
23831 		return (B_FALSE);
23832 	}
23833 	*hi_port = port - 1;
23834 
23835 	/*
23836 	 * Insert range into array in ascending order.  Since this function
23837 	 * must not be called often, we choose to use the simplest method.
23838 	 * The above array should not consume excessive stack space as
23839 	 * the size must be very small.  If in future releases, we find
23840 	 * that we should provide more reserved port ranges, this function
23841 	 * has to be modified to be more efficient.
23842 	 */
23843 	if (tcps->tcps_reserved_port_array_size == 0) {
23844 		tcps->tcps_reserved_port[0].lo_port = *lo_port;
23845 		tcps->tcps_reserved_port[0].hi_port = *hi_port;
23846 		tcps->tcps_reserved_port[0].temp_tcp_array = temp_tcp_array;
23847 	} else {
23848 		for (i = 0, j = 0; i < tcps->tcps_reserved_port_array_size;
23849 		    i++, j++) {
23850 			if (*lo_port < tcps->tcps_reserved_port[i].lo_port &&
23851 			    i == j) {
23852 				tmp_ports[j].lo_port = *lo_port;
23853 				tmp_ports[j].hi_port = *hi_port;
23854 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23855 				j++;
23856 			}
23857 			tmp_ports[j].lo_port =
23858 			    tcps->tcps_reserved_port[i].lo_port;
23859 			tmp_ports[j].hi_port =
23860 			    tcps->tcps_reserved_port[i].hi_port;
23861 			tmp_ports[j].temp_tcp_array =
23862 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23863 		}
23864 		if (j == i) {
23865 			tmp_ports[j].lo_port = *lo_port;
23866 			tmp_ports[j].hi_port = *hi_port;
23867 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23868 		}
23869 		bcopy(tmp_ports, tcps->tcps_reserved_port, sizeof (tmp_ports));
23870 	}
23871 	tcps->tcps_reserved_port_array_size++;
23872 	rw_exit(&tcps->tcps_reserved_port_lock);
23873 	netstack_rele(tcps->tcps_netstack);
23874 	return (B_TRUE);
23875 }
23876 
23877 /*
23878  * Check to see if a port is in any reserved port range.
23879  *
23880  * Params:
23881  *	in_port_t port: the port to be verified.
23882  *
23883  * Return:
23884  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23885  */
23886 boolean_t
23887 tcp_reserved_port_check(in_port_t port, tcp_stack_t *tcps)
23888 {
23889 	int i;
23890 
23891 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23892 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23893 		if (port >= tcps->tcps_reserved_port[i].lo_port ||
23894 		    port <= tcps->tcps_reserved_port[i].hi_port) {
23895 			rw_exit(&tcps->tcps_reserved_port_lock);
23896 			return (B_TRUE);
23897 		}
23898 	}
23899 	rw_exit(&tcps->tcps_reserved_port_lock);
23900 	return (B_FALSE);
23901 }
23902 
23903 /*
23904  * To list all reserved port ranges.  This is the function to handle
23905  * ndd tcp_reserved_port_list.
23906  */
23907 /* ARGSUSED */
23908 static int
23909 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23910 {
23911 	int i;
23912 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23913 
23914 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23915 	if (tcps->tcps_reserved_port_array_size > 0)
23916 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23917 	else
23918 		(void) mi_mpprintf(mp, "No port is reserved.");
23919 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23920 		(void) mi_mpprintf(mp, "%d-%d",
23921 		    tcps->tcps_reserved_port[i].lo_port,
23922 		    tcps->tcps_reserved_port[i].hi_port);
23923 	}
23924 	rw_exit(&tcps->tcps_reserved_port_lock);
23925 	return (0);
23926 }
23927 
23928 /*
23929  * Hash list insertion routine for tcp_t structures.
23930  * Inserts entries with the ones bound to a specific IP address first
23931  * followed by those bound to INADDR_ANY.
23932  */
23933 static void
23934 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23935 {
23936 	tcp_t	**tcpp;
23937 	tcp_t	*tcpnext;
23938 
23939 	if (tcp->tcp_ptpbhn != NULL) {
23940 		ASSERT(!caller_holds_lock);
23941 		tcp_bind_hash_remove(tcp);
23942 	}
23943 	tcpp = &tbf->tf_tcp;
23944 	if (!caller_holds_lock) {
23945 		mutex_enter(&tbf->tf_lock);
23946 	} else {
23947 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23948 	}
23949 	tcpnext = tcpp[0];
23950 	if (tcpnext) {
23951 		/*
23952 		 * If the new tcp bound to the INADDR_ANY address
23953 		 * and the first one in the list is not bound to
23954 		 * INADDR_ANY we skip all entries until we find the
23955 		 * first one bound to INADDR_ANY.
23956 		 * This makes sure that applications binding to a
23957 		 * specific address get preference over those binding to
23958 		 * INADDR_ANY.
23959 		 */
23960 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23961 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23962 			while ((tcpnext = tcpp[0]) != NULL &&
23963 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23964 				tcpp = &(tcpnext->tcp_bind_hash);
23965 			if (tcpnext)
23966 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23967 		} else
23968 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23969 	}
23970 	tcp->tcp_bind_hash = tcpnext;
23971 	tcp->tcp_ptpbhn = tcpp;
23972 	tcpp[0] = tcp;
23973 	if (!caller_holds_lock)
23974 		mutex_exit(&tbf->tf_lock);
23975 }
23976 
23977 /*
23978  * Hash list removal routine for tcp_t structures.
23979  */
23980 static void
23981 tcp_bind_hash_remove(tcp_t *tcp)
23982 {
23983 	tcp_t	*tcpnext;
23984 	kmutex_t *lockp;
23985 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23986 
23987 	if (tcp->tcp_ptpbhn == NULL)
23988 		return;
23989 
23990 	/*
23991 	 * Extract the lock pointer in case there are concurrent
23992 	 * hash_remove's for this instance.
23993 	 */
23994 	ASSERT(tcp->tcp_lport != 0);
23995 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23996 
23997 	ASSERT(lockp != NULL);
23998 	mutex_enter(lockp);
23999 	if (tcp->tcp_ptpbhn) {
24000 		tcpnext = tcp->tcp_bind_hash;
24001 		if (tcpnext) {
24002 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24003 			tcp->tcp_bind_hash = NULL;
24004 		}
24005 		*tcp->tcp_ptpbhn = tcpnext;
24006 		tcp->tcp_ptpbhn = NULL;
24007 	}
24008 	mutex_exit(lockp);
24009 }
24010 
24011 
24012 /*
24013  * Hash list lookup routine for tcp_t structures.
24014  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24015  */
24016 static tcp_t *
24017 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24018 {
24019 	tf_t	*tf;
24020 	tcp_t	*tcp;
24021 
24022 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24023 	mutex_enter(&tf->tf_lock);
24024 	for (tcp = tf->tf_tcp; tcp != NULL;
24025 	    tcp = tcp->tcp_acceptor_hash) {
24026 		if (tcp->tcp_acceptor_id == id) {
24027 			CONN_INC_REF(tcp->tcp_connp);
24028 			mutex_exit(&tf->tf_lock);
24029 			return (tcp);
24030 		}
24031 	}
24032 	mutex_exit(&tf->tf_lock);
24033 	return (NULL);
24034 }
24035 
24036 
24037 /*
24038  * Hash list insertion routine for tcp_t structures.
24039  */
24040 void
24041 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24042 {
24043 	tf_t	*tf;
24044 	tcp_t	**tcpp;
24045 	tcp_t	*tcpnext;
24046 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24047 
24048 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24049 
24050 	if (tcp->tcp_ptpahn != NULL)
24051 		tcp_acceptor_hash_remove(tcp);
24052 	tcpp = &tf->tf_tcp;
24053 	mutex_enter(&tf->tf_lock);
24054 	tcpnext = tcpp[0];
24055 	if (tcpnext)
24056 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24057 	tcp->tcp_acceptor_hash = tcpnext;
24058 	tcp->tcp_ptpahn = tcpp;
24059 	tcpp[0] = tcp;
24060 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24061 	mutex_exit(&tf->tf_lock);
24062 }
24063 
24064 /*
24065  * Hash list removal routine for tcp_t structures.
24066  */
24067 static void
24068 tcp_acceptor_hash_remove(tcp_t *tcp)
24069 {
24070 	tcp_t	*tcpnext;
24071 	kmutex_t *lockp;
24072 
24073 	/*
24074 	 * Extract the lock pointer in case there are concurrent
24075 	 * hash_remove's for this instance.
24076 	 */
24077 	lockp = tcp->tcp_acceptor_lockp;
24078 
24079 	if (tcp->tcp_ptpahn == NULL)
24080 		return;
24081 
24082 	ASSERT(lockp != NULL);
24083 	mutex_enter(lockp);
24084 	if (tcp->tcp_ptpahn) {
24085 		tcpnext = tcp->tcp_acceptor_hash;
24086 		if (tcpnext) {
24087 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24088 			tcp->tcp_acceptor_hash = NULL;
24089 		}
24090 		*tcp->tcp_ptpahn = tcpnext;
24091 		tcp->tcp_ptpahn = NULL;
24092 	}
24093 	mutex_exit(lockp);
24094 	tcp->tcp_acceptor_lockp = NULL;
24095 }
24096 
24097 /* ARGSUSED */
24098 static int
24099 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
24100 {
24101 	int error = 0;
24102 	int retval;
24103 	char *end;
24104 	tcp_hsp_t *hsp;
24105 	tcp_hsp_t *hspprev;
24106 	ipaddr_t addr = 0;		/* Address we're looking for */
24107 	in6_addr_t v6addr;		/* Address we're looking for */
24108 	uint32_t hash;			/* Hash of that address */
24109 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24110 
24111 	/*
24112 	 * If the following variables are still zero after parsing the input
24113 	 * string, the user didn't specify them and we don't change them in
24114 	 * the HSP.
24115 	 */
24116 
24117 	ipaddr_t mask = 0;		/* Subnet mask */
24118 	in6_addr_t v6mask;
24119 	long sendspace = 0;		/* Send buffer size */
24120 	long recvspace = 0;		/* Receive buffer size */
24121 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
24122 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
24123 
24124 	rw_enter(&tcps->tcps_hsp_lock, RW_WRITER);
24125 
24126 	/* Parse and validate address */
24127 	if (af == AF_INET) {
24128 		retval = inet_pton(af, value, &addr);
24129 		if (retval == 1)
24130 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
24131 	} else if (af == AF_INET6) {
24132 		retval = inet_pton(af, value, &v6addr);
24133 	} else {
24134 		error = EINVAL;
24135 		goto done;
24136 	}
24137 	if (retval == 0) {
24138 		error = EINVAL;
24139 		goto done;
24140 	}
24141 
24142 	while ((*value) && *value != ' ')
24143 		value++;
24144 
24145 	/* Parse individual keywords, set variables if found */
24146 	while (*value) {
24147 		/* Skip leading blanks */
24148 
24149 		while (*value == ' ' || *value == '\t')
24150 			value++;
24151 
24152 		/* If at end of string, we're done */
24153 
24154 		if (!*value)
24155 			break;
24156 
24157 		/* We have a word, figure out what it is */
24158 
24159 		if (strncmp("mask", value, 4) == 0) {
24160 			value += 4;
24161 			while (*value == ' ' || *value == '\t')
24162 				value++;
24163 			/* Parse subnet mask */
24164 			if (af == AF_INET) {
24165 				retval = inet_pton(af, value, &mask);
24166 				if (retval == 1) {
24167 					V4MASK_TO_V6(mask, v6mask);
24168 				}
24169 			} else if (af == AF_INET6) {
24170 				retval = inet_pton(af, value, &v6mask);
24171 			}
24172 			if (retval != 1) {
24173 				error = EINVAL;
24174 				goto done;
24175 			}
24176 			while ((*value) && *value != ' ')
24177 				value++;
24178 		} else if (strncmp("sendspace", value, 9) == 0) {
24179 			value += 9;
24180 
24181 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
24182 			    sendspace < TCP_XMIT_HIWATER ||
24183 			    sendspace >= (1L<<30)) {
24184 				error = EINVAL;
24185 				goto done;
24186 			}
24187 			value = end;
24188 		} else if (strncmp("recvspace", value, 9) == 0) {
24189 			value += 9;
24190 
24191 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
24192 			    recvspace < TCP_RECV_HIWATER ||
24193 			    recvspace >= (1L<<30)) {
24194 				error = EINVAL;
24195 				goto done;
24196 			}
24197 			value = end;
24198 		} else if (strncmp("timestamp", value, 9) == 0) {
24199 			value += 9;
24200 
24201 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
24202 			    timestamp < 0 || timestamp > 1) {
24203 				error = EINVAL;
24204 				goto done;
24205 			}
24206 
24207 			/*
24208 			 * We increment timestamp so we know it's been set;
24209 			 * this is undone when we put it in the HSP
24210 			 */
24211 			timestamp++;
24212 			value = end;
24213 		} else if (strncmp("delete", value, 6) == 0) {
24214 			value += 6;
24215 			delete = B_TRUE;
24216 		} else {
24217 			error = EINVAL;
24218 			goto done;
24219 		}
24220 	}
24221 
24222 	/* Hash address for lookup */
24223 
24224 	hash = TCP_HSP_HASH(addr);
24225 
24226 	if (delete) {
24227 		/*
24228 		 * Note that deletes don't return an error if the thing
24229 		 * we're trying to delete isn't there.
24230 		 */
24231 		if (tcps->tcps_hsp_hash == NULL)
24232 			goto done;
24233 		hsp = tcps->tcps_hsp_hash[hash];
24234 
24235 		if (hsp) {
24236 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24237 			    &v6addr)) {
24238 				tcps->tcps_hsp_hash[hash] = hsp->tcp_hsp_next;
24239 				mi_free((char *)hsp);
24240 			} else {
24241 				hspprev = hsp;
24242 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
24243 					if (IN6_ARE_ADDR_EQUAL(
24244 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
24245 						hspprev->tcp_hsp_next =
24246 						    hsp->tcp_hsp_next;
24247 						mi_free((char *)hsp);
24248 						break;
24249 					}
24250 					hspprev = hsp;
24251 				}
24252 			}
24253 		}
24254 	} else {
24255 		/*
24256 		 * We're adding/modifying an HSP.  If we haven't already done
24257 		 * so, allocate the hash table.
24258 		 */
24259 
24260 		if (!tcps->tcps_hsp_hash) {
24261 			tcps->tcps_hsp_hash = (tcp_hsp_t **)
24262 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
24263 			if (!tcps->tcps_hsp_hash) {
24264 				error = EINVAL;
24265 				goto done;
24266 			}
24267 		}
24268 
24269 		/* Get head of hash chain */
24270 
24271 		hsp = tcps->tcps_hsp_hash[hash];
24272 
24273 		/* Try to find pre-existing hsp on hash chain */
24274 		/* Doesn't handle CIDR prefixes. */
24275 		while (hsp) {
24276 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
24277 				break;
24278 			hsp = hsp->tcp_hsp_next;
24279 		}
24280 
24281 		/*
24282 		 * If we didn't, create one with default values and put it
24283 		 * at head of hash chain
24284 		 */
24285 
24286 		if (!hsp) {
24287 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
24288 			if (!hsp) {
24289 				error = EINVAL;
24290 				goto done;
24291 			}
24292 			hsp->tcp_hsp_next = tcps->tcps_hsp_hash[hash];
24293 			tcps->tcps_hsp_hash[hash] = hsp;
24294 		}
24295 
24296 		/* Set values that the user asked us to change */
24297 
24298 		hsp->tcp_hsp_addr_v6 = v6addr;
24299 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
24300 			hsp->tcp_hsp_vers = IPV4_VERSION;
24301 		else
24302 			hsp->tcp_hsp_vers = IPV6_VERSION;
24303 		hsp->tcp_hsp_subnet_v6 = v6mask;
24304 		if (sendspace > 0)
24305 			hsp->tcp_hsp_sendspace = sendspace;
24306 		if (recvspace > 0)
24307 			hsp->tcp_hsp_recvspace = recvspace;
24308 		if (timestamp > 0)
24309 			hsp->tcp_hsp_tstamp = timestamp - 1;
24310 	}
24311 
24312 done:
24313 	rw_exit(&tcps->tcps_hsp_lock);
24314 	return (error);
24315 }
24316 
24317 /* Set callback routine passed to nd_load by tcp_param_register. */
24318 /* ARGSUSED */
24319 static int
24320 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
24321 {
24322 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
24323 }
24324 /* ARGSUSED */
24325 static int
24326 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24327     cred_t *cr)
24328 {
24329 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
24330 }
24331 
24332 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
24333 /* ARGSUSED */
24334 static int
24335 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24336 {
24337 	tcp_hsp_t *hsp;
24338 	int i;
24339 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
24340 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24341 
24342 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24343 	(void) mi_mpprintf(mp,
24344 	    "Hash HSP     " MI_COL_HDRPAD_STR
24345 	    "Address         Subnet Mask     Send       Receive    TStamp");
24346 	if (tcps->tcps_hsp_hash) {
24347 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24348 			hsp = tcps->tcps_hsp_hash[i];
24349 			while (hsp) {
24350 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24351 					(void) inet_ntop(AF_INET,
24352 					    &hsp->tcp_hsp_addr,
24353 					    addrbuf, sizeof (addrbuf));
24354 					(void) inet_ntop(AF_INET,
24355 					    &hsp->tcp_hsp_subnet,
24356 					    subnetbuf, sizeof (subnetbuf));
24357 				} else {
24358 					(void) inet_ntop(AF_INET6,
24359 					    &hsp->tcp_hsp_addr_v6,
24360 					    addrbuf, sizeof (addrbuf));
24361 					(void) inet_ntop(AF_INET6,
24362 					    &hsp->tcp_hsp_subnet_v6,
24363 					    subnetbuf, sizeof (subnetbuf));
24364 				}
24365 				(void) mi_mpprintf(mp,
24366 				    " %03d " MI_COL_PTRFMT_STR
24367 				    "%s %s %010d %010d      %d",
24368 				    i,
24369 				    (void *)hsp,
24370 				    addrbuf,
24371 				    subnetbuf,
24372 				    hsp->tcp_hsp_sendspace,
24373 				    hsp->tcp_hsp_recvspace,
24374 				    hsp->tcp_hsp_tstamp);
24375 
24376 				hsp = hsp->tcp_hsp_next;
24377 			}
24378 		}
24379 	}
24380 	rw_exit(&tcps->tcps_hsp_lock);
24381 	return (0);
24382 }
24383 
24384 
24385 /* Data for fast netmask macro used by tcp_hsp_lookup */
24386 
24387 static ipaddr_t netmasks[] = {
24388 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24389 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24390 };
24391 
24392 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24393 
24394 /*
24395  * XXX This routine should go away and instead we should use the metrics
24396  * associated with the routes to determine the default sndspace and rcvspace.
24397  */
24398 static tcp_hsp_t *
24399 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24400 {
24401 	tcp_hsp_t *hsp = NULL;
24402 
24403 	/* Quick check without acquiring the lock. */
24404 	if (tcps->tcps_hsp_hash == NULL)
24405 		return (NULL);
24406 
24407 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24408 
24409 	/* This routine finds the best-matching HSP for address addr. */
24410 
24411 	if (tcps->tcps_hsp_hash) {
24412 		int i;
24413 		ipaddr_t srchaddr;
24414 		tcp_hsp_t *hsp_net;
24415 
24416 		/* We do three passes: host, network, and subnet. */
24417 
24418 		srchaddr = addr;
24419 
24420 		for (i = 1; i <= 3; i++) {
24421 			/* Look for exact match on srchaddr */
24422 
24423 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24424 			while (hsp) {
24425 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24426 				    hsp->tcp_hsp_addr == srchaddr)
24427 					break;
24428 				hsp = hsp->tcp_hsp_next;
24429 			}
24430 			ASSERT(hsp == NULL ||
24431 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24432 
24433 			/*
24434 			 * If this is the first pass:
24435 			 *   If we found a match, great, return it.
24436 			 *   If not, search for the network on the second pass.
24437 			 */
24438 
24439 			if (i == 1)
24440 				if (hsp)
24441 					break;
24442 				else
24443 				{
24444 					srchaddr = addr & netmask(addr);
24445 					continue;
24446 				}
24447 
24448 			/*
24449 			 * If this is the second pass:
24450 			 *   If we found a match, but there's a subnet mask,
24451 			 *    save the match but try again using the subnet
24452 			 *    mask on the third pass.
24453 			 *   Otherwise, return whatever we found.
24454 			 */
24455 
24456 			if (i == 2) {
24457 				if (hsp && hsp->tcp_hsp_subnet) {
24458 					hsp_net = hsp;
24459 					srchaddr = addr & hsp->tcp_hsp_subnet;
24460 					continue;
24461 				} else {
24462 					break;
24463 				}
24464 			}
24465 
24466 			/*
24467 			 * This must be the third pass.  If we didn't find
24468 			 * anything, return the saved network HSP instead.
24469 			 */
24470 
24471 			if (!hsp)
24472 				hsp = hsp_net;
24473 		}
24474 	}
24475 
24476 	rw_exit(&tcps->tcps_hsp_lock);
24477 	return (hsp);
24478 }
24479 
24480 /*
24481  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24482  * match lookup.
24483  */
24484 static tcp_hsp_t *
24485 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24486 {
24487 	tcp_hsp_t *hsp = NULL;
24488 
24489 	/* Quick check without acquiring the lock. */
24490 	if (tcps->tcps_hsp_hash == NULL)
24491 		return (NULL);
24492 
24493 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24494 
24495 	/* This routine finds the best-matching HSP for address addr. */
24496 
24497 	if (tcps->tcps_hsp_hash) {
24498 		int i;
24499 		in6_addr_t v6srchaddr;
24500 		tcp_hsp_t *hsp_net;
24501 
24502 		/* We do three passes: host, network, and subnet. */
24503 
24504 		v6srchaddr = *v6addr;
24505 
24506 		for (i = 1; i <= 3; i++) {
24507 			/* Look for exact match on srchaddr */
24508 
24509 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24510 			    V4_PART_OF_V6(v6srchaddr))];
24511 			while (hsp) {
24512 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24513 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24514 				    &v6srchaddr))
24515 					break;
24516 				hsp = hsp->tcp_hsp_next;
24517 			}
24518 
24519 			/*
24520 			 * If this is the first pass:
24521 			 *   If we found a match, great, return it.
24522 			 *   If not, search for the network on the second pass.
24523 			 */
24524 
24525 			if (i == 1)
24526 				if (hsp)
24527 					break;
24528 				else {
24529 					/* Assume a 64 bit mask */
24530 					v6srchaddr.s6_addr32[0] =
24531 					    v6addr->s6_addr32[0];
24532 					v6srchaddr.s6_addr32[1] =
24533 					    v6addr->s6_addr32[1];
24534 					v6srchaddr.s6_addr32[2] = 0;
24535 					v6srchaddr.s6_addr32[3] = 0;
24536 					continue;
24537 				}
24538 
24539 			/*
24540 			 * If this is the second pass:
24541 			 *   If we found a match, but there's a subnet mask,
24542 			 *    save the match but try again using the subnet
24543 			 *    mask on the third pass.
24544 			 *   Otherwise, return whatever we found.
24545 			 */
24546 
24547 			if (i == 2) {
24548 				ASSERT(hsp == NULL ||
24549 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24550 				if (hsp &&
24551 				    !IN6_IS_ADDR_UNSPECIFIED(
24552 				    &hsp->tcp_hsp_subnet_v6)) {
24553 					hsp_net = hsp;
24554 					V6_MASK_COPY(*v6addr,
24555 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24556 					continue;
24557 				} else {
24558 					break;
24559 				}
24560 			}
24561 
24562 			/*
24563 			 * This must be the third pass.  If we didn't find
24564 			 * anything, return the saved network HSP instead.
24565 			 */
24566 
24567 			if (!hsp)
24568 				hsp = hsp_net;
24569 		}
24570 	}
24571 
24572 	rw_exit(&tcps->tcps_hsp_lock);
24573 	return (hsp);
24574 }
24575 
24576 /*
24577  * Type three generator adapted from the random() function in 4.4 BSD:
24578  */
24579 
24580 /*
24581  * Copyright (c) 1983, 1993
24582  *	The Regents of the University of California.  All rights reserved.
24583  *
24584  * Redistribution and use in source and binary forms, with or without
24585  * modification, are permitted provided that the following conditions
24586  * are met:
24587  * 1. Redistributions of source code must retain the above copyright
24588  *    notice, this list of conditions and the following disclaimer.
24589  * 2. Redistributions in binary form must reproduce the above copyright
24590  *    notice, this list of conditions and the following disclaimer in the
24591  *    documentation and/or other materials provided with the distribution.
24592  * 3. All advertising materials mentioning features or use of this software
24593  *    must display the following acknowledgement:
24594  *	This product includes software developed by the University of
24595  *	California, Berkeley and its contributors.
24596  * 4. Neither the name of the University nor the names of its contributors
24597  *    may be used to endorse or promote products derived from this software
24598  *    without specific prior written permission.
24599  *
24600  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24601  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24602  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24603  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24604  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24605  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24606  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24607  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24608  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24609  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24610  * SUCH DAMAGE.
24611  */
24612 
24613 /* Type 3 -- x**31 + x**3 + 1 */
24614 #define	DEG_3		31
24615 #define	SEP_3		3
24616 
24617 
24618 /* Protected by tcp_random_lock */
24619 static int tcp_randtbl[DEG_3 + 1];
24620 
24621 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24622 static int *tcp_random_rptr = &tcp_randtbl[1];
24623 
24624 static int *tcp_random_state = &tcp_randtbl[1];
24625 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24626 
24627 kmutex_t tcp_random_lock;
24628 
24629 void
24630 tcp_random_init(void)
24631 {
24632 	int i;
24633 	hrtime_t hrt;
24634 	time_t wallclock;
24635 	uint64_t result;
24636 
24637 	/*
24638 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24639 	 * a longlong, which may contain resolution down to nanoseconds.
24640 	 * The current time will either be a 32-bit or a 64-bit quantity.
24641 	 * XOR the two together in a 64-bit result variable.
24642 	 * Convert the result to a 32-bit value by multiplying the high-order
24643 	 * 32-bits by the low-order 32-bits.
24644 	 */
24645 
24646 	hrt = gethrtime();
24647 	(void) drv_getparm(TIME, &wallclock);
24648 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24649 	mutex_enter(&tcp_random_lock);
24650 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24651 	    (result & 0xffffffff);
24652 
24653 	for (i = 1; i < DEG_3; i++)
24654 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24655 		    + 12345;
24656 	tcp_random_fptr = &tcp_random_state[SEP_3];
24657 	tcp_random_rptr = &tcp_random_state[0];
24658 	mutex_exit(&tcp_random_lock);
24659 	for (i = 0; i < 10 * DEG_3; i++)
24660 		(void) tcp_random();
24661 }
24662 
24663 /*
24664  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24665  * This range is selected to be approximately centered on TCP_ISS / 2,
24666  * and easy to compute. We get this value by generating a 32-bit random
24667  * number, selecting out the high-order 17 bits, and then adding one so
24668  * that we never return zero.
24669  */
24670 int
24671 tcp_random(void)
24672 {
24673 	int i;
24674 
24675 	mutex_enter(&tcp_random_lock);
24676 	*tcp_random_fptr += *tcp_random_rptr;
24677 
24678 	/*
24679 	 * The high-order bits are more random than the low-order bits,
24680 	 * so we select out the high-order 17 bits and add one so that
24681 	 * we never return zero.
24682 	 */
24683 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24684 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24685 		tcp_random_fptr = tcp_random_state;
24686 		++tcp_random_rptr;
24687 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24688 		tcp_random_rptr = tcp_random_state;
24689 
24690 	mutex_exit(&tcp_random_lock);
24691 	return (i);
24692 }
24693 
24694 /*
24695  * XXX This will go away when TPI is extended to send
24696  * info reqs to sockfs/timod .....
24697  * Given a queue, set the max packet size for the write
24698  * side of the queue below stream head.  This value is
24699  * cached on the stream head.
24700  * Returns 1 on success, 0 otherwise.
24701  */
24702 static int
24703 setmaxps(queue_t *q, int maxpsz)
24704 {
24705 	struct stdata	*stp;
24706 	queue_t		*wq;
24707 	stp = STREAM(q);
24708 
24709 	/*
24710 	 * At this point change of a queue parameter is not allowed
24711 	 * when a multiplexor is sitting on top.
24712 	 */
24713 	if (stp->sd_flag & STPLEX)
24714 		return (0);
24715 
24716 	claimstr(stp->sd_wrq);
24717 	wq = stp->sd_wrq->q_next;
24718 	ASSERT(wq != NULL);
24719 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24720 	releasestr(stp->sd_wrq);
24721 	return (1);
24722 }
24723 
24724 static int
24725 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24726     int *t_errorp, int *sys_errorp)
24727 {
24728 	int error;
24729 	int is_absreq_failure;
24730 	t_scalar_t *opt_lenp;
24731 	t_scalar_t opt_offset;
24732 	int prim_type;
24733 	struct T_conn_req *tcreqp;
24734 	struct T_conn_res *tcresp;
24735 	cred_t *cr;
24736 
24737 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24738 
24739 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24740 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24741 	    prim_type == T_CONN_RES);
24742 
24743 	switch (prim_type) {
24744 	case T_CONN_REQ:
24745 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24746 		opt_offset = tcreqp->OPT_offset;
24747 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24748 		break;
24749 	case O_T_CONN_RES:
24750 	case T_CONN_RES:
24751 		tcresp = (struct T_conn_res *)mp->b_rptr;
24752 		opt_offset = tcresp->OPT_offset;
24753 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24754 		break;
24755 	}
24756 
24757 	*t_errorp = 0;
24758 	*sys_errorp = 0;
24759 	*do_disconnectp = 0;
24760 
24761 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24762 	    opt_offset, cr, &tcp_opt_obj,
24763 	    NULL, &is_absreq_failure);
24764 
24765 	switch (error) {
24766 	case  0:		/* no error */
24767 		ASSERT(is_absreq_failure == 0);
24768 		return (0);
24769 	case ENOPROTOOPT:
24770 		*t_errorp = TBADOPT;
24771 		break;
24772 	case EACCES:
24773 		*t_errorp = TACCES;
24774 		break;
24775 	default:
24776 		*t_errorp = TSYSERR; *sys_errorp = error;
24777 		break;
24778 	}
24779 	if (is_absreq_failure != 0) {
24780 		/*
24781 		 * The connection request should get the local ack
24782 		 * T_OK_ACK and then a T_DISCON_IND.
24783 		 */
24784 		*do_disconnectp = 1;
24785 	}
24786 	return (-1);
24787 }
24788 
24789 /*
24790  * Split this function out so that if the secret changes, I'm okay.
24791  *
24792  * Initialize the tcp_iss_cookie and tcp_iss_key.
24793  */
24794 
24795 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24796 
24797 static void
24798 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24799 {
24800 	struct {
24801 		int32_t current_time;
24802 		uint32_t randnum;
24803 		uint16_t pad;
24804 		uint8_t ether[6];
24805 		uint8_t passwd[PASSWD_SIZE];
24806 	} tcp_iss_cookie;
24807 	time_t t;
24808 
24809 	/*
24810 	 * Start with the current absolute time.
24811 	 */
24812 	(void) drv_getparm(TIME, &t);
24813 	tcp_iss_cookie.current_time = t;
24814 
24815 	/*
24816 	 * XXX - Need a more random number per RFC 1750, not this crap.
24817 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24818 	 */
24819 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24820 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24821 
24822 	/*
24823 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24824 	 * as a good template.
24825 	 */
24826 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24827 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24828 
24829 	/*
24830 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24831 	 */
24832 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24833 
24834 	/*
24835 	 * See 4010593 if this section becomes a problem again,
24836 	 * but the local ethernet address is useful here.
24837 	 */
24838 	(void) localetheraddr(NULL,
24839 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24840 
24841 	/*
24842 	 * Hash 'em all together.  The MD5Final is called per-connection.
24843 	 */
24844 	mutex_enter(&tcps->tcps_iss_key_lock);
24845 	MD5Init(&tcps->tcps_iss_key);
24846 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24847 	    sizeof (tcp_iss_cookie));
24848 	mutex_exit(&tcps->tcps_iss_key_lock);
24849 }
24850 
24851 /*
24852  * Set the RFC 1948 pass phrase
24853  */
24854 /* ARGSUSED */
24855 static int
24856 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24857     cred_t *cr)
24858 {
24859 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24860 
24861 	/*
24862 	 * Basically, value contains a new pass phrase.  Pass it along!
24863 	 */
24864 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24865 	return (0);
24866 }
24867 
24868 /* ARGSUSED */
24869 static int
24870 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24871 {
24872 	bzero(buf, sizeof (tcp_sack_info_t));
24873 	return (0);
24874 }
24875 
24876 /* ARGSUSED */
24877 static int
24878 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24879 {
24880 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24881 	return (0);
24882 }
24883 
24884 /*
24885  * Make sure we wait until the default queue is setup, yet allow
24886  * tcp_g_q_create() to open a TCP stream.
24887  * We need to allow tcp_g_q_create() do do an open
24888  * of tcp, hence we compare curhread.
24889  * All others have to wait until the tcps_g_q has been
24890  * setup.
24891  */
24892 void
24893 tcp_g_q_setup(tcp_stack_t *tcps)
24894 {
24895 	mutex_enter(&tcps->tcps_g_q_lock);
24896 	if (tcps->tcps_g_q != NULL) {
24897 		mutex_exit(&tcps->tcps_g_q_lock);
24898 		return;
24899 	}
24900 	if (tcps->tcps_g_q_creator == NULL) {
24901 		/* This thread will set it up */
24902 		tcps->tcps_g_q_creator = curthread;
24903 		mutex_exit(&tcps->tcps_g_q_lock);
24904 		tcp_g_q_create(tcps);
24905 		mutex_enter(&tcps->tcps_g_q_lock);
24906 		ASSERT(tcps->tcps_g_q_creator == curthread);
24907 		tcps->tcps_g_q_creator = NULL;
24908 		cv_signal(&tcps->tcps_g_q_cv);
24909 		ASSERT(tcps->tcps_g_q != NULL);
24910 		mutex_exit(&tcps->tcps_g_q_lock);
24911 		return;
24912 	}
24913 	/* Everybody but the creator has to wait */
24914 	if (tcps->tcps_g_q_creator != curthread) {
24915 		while (tcps->tcps_g_q == NULL)
24916 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24917 	}
24918 	mutex_exit(&tcps->tcps_g_q_lock);
24919 }
24920 
24921 #define	IP	"ip"
24922 
24923 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24924 
24925 /*
24926  * Create a default tcp queue here instead of in strplumb
24927  */
24928 void
24929 tcp_g_q_create(tcp_stack_t *tcps)
24930 {
24931 	int error;
24932 	ldi_handle_t	lh = NULL;
24933 	ldi_ident_t	li = NULL;
24934 	int		rval;
24935 	cred_t		*cr;
24936 	major_t IP_MAJ;
24937 
24938 #ifdef NS_DEBUG
24939 	(void) printf("tcp_g_q_create()\n");
24940 #endif
24941 
24942 	IP_MAJ = ddi_name_to_major(IP);
24943 
24944 	ASSERT(tcps->tcps_g_q_creator == curthread);
24945 
24946 	error = ldi_ident_from_major(IP_MAJ, &li);
24947 	if (error) {
24948 #ifdef DEBUG
24949 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24950 		    error);
24951 #endif
24952 		return;
24953 	}
24954 
24955 	cr = zone_get_kcred(netstackid_to_zoneid(
24956 	    tcps->tcps_netstack->netstack_stackid));
24957 	ASSERT(cr != NULL);
24958 	/*
24959 	 * We set the tcp default queue to IPv6 because IPv4 falls
24960 	 * back to IPv6 when it can't find a client, but
24961 	 * IPv6 does not fall back to IPv4.
24962 	 */
24963 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24964 	if (error) {
24965 #ifdef DEBUG
24966 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24967 		    error);
24968 #endif
24969 		goto out;
24970 	}
24971 
24972 	/*
24973 	 * This ioctl causes the tcp framework to cache a pointer to
24974 	 * this stream, so we don't want to close the stream after
24975 	 * this operation.
24976 	 * Use the kernel credentials that are for the zone we're in.
24977 	 */
24978 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24979 	    (intptr_t)0, FKIOCTL, cr, &rval);
24980 	if (error) {
24981 #ifdef DEBUG
24982 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24983 		    "error %d\n", error);
24984 #endif
24985 		goto out;
24986 	}
24987 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24988 	lh = NULL;
24989 out:
24990 	/* Close layered handles */
24991 	if (li)
24992 		ldi_ident_release(li);
24993 	/* Keep cred around until _inactive needs it */
24994 	tcps->tcps_g_q_cr = cr;
24995 }
24996 
24997 /*
24998  * We keep tcp_g_q set until all other tcp_t's in the zone
24999  * has gone away, and then when tcp_g_q_inactive() is called
25000  * we clear it.
25001  */
25002 void
25003 tcp_g_q_destroy(tcp_stack_t *tcps)
25004 {
25005 #ifdef NS_DEBUG
25006 	(void) printf("tcp_g_q_destroy()for stack %d\n",
25007 	    tcps->tcps_netstack->netstack_stackid);
25008 #endif
25009 
25010 	if (tcps->tcps_g_q == NULL) {
25011 		return;	/* Nothing to cleanup */
25012 	}
25013 	/*
25014 	 * Drop reference corresponding to the default queue.
25015 	 * This reference was added from tcp_open when the default queue
25016 	 * was created, hence we compensate for this extra drop in
25017 	 * tcp_g_q_close. If the refcnt drops to zero here it means
25018 	 * the default queue was the last one to be open, in which
25019 	 * case, then tcp_g_q_inactive will be
25020 	 * called as a result of the refrele.
25021 	 */
25022 	TCPS_REFRELE(tcps);
25023 }
25024 
25025 /*
25026  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25027  * Run by tcp_q_q_inactive using a taskq.
25028  */
25029 static void
25030 tcp_g_q_close(void *arg)
25031 {
25032 	tcp_stack_t *tcps = arg;
25033 	int error;
25034 	ldi_handle_t	lh = NULL;
25035 	ldi_ident_t	li = NULL;
25036 	cred_t		*cr;
25037 	major_t IP_MAJ;
25038 
25039 	IP_MAJ = ddi_name_to_major(IP);
25040 
25041 #ifdef NS_DEBUG
25042 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
25043 	    tcps->tcps_netstack->netstack_stackid,
25044 	    tcps->tcps_netstack->netstack_refcnt);
25045 #endif
25046 	lh = tcps->tcps_g_q_lh;
25047 	if (lh == NULL)
25048 		return;	/* Nothing to cleanup */
25049 
25050 	ASSERT(tcps->tcps_refcnt == 1);
25051 	ASSERT(tcps->tcps_g_q != NULL);
25052 
25053 	error = ldi_ident_from_major(IP_MAJ, &li);
25054 	if (error) {
25055 #ifdef DEBUG
25056 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
25057 		    error);
25058 #endif
25059 		return;
25060 	}
25061 
25062 	cr = tcps->tcps_g_q_cr;
25063 	tcps->tcps_g_q_cr = NULL;
25064 	ASSERT(cr != NULL);
25065 
25066 	/*
25067 	 * Make sure we can break the recursion when tcp_close decrements
25068 	 * the reference count causing g_q_inactive to be called again.
25069 	 */
25070 	tcps->tcps_g_q_lh = NULL;
25071 
25072 	/* close the default queue */
25073 	(void) ldi_close(lh, FREAD|FWRITE, cr);
25074 	/*
25075 	 * At this point in time tcps and the rest of netstack_t might
25076 	 * have been deleted.
25077 	 */
25078 	tcps = NULL;
25079 
25080 	/* Close layered handles */
25081 	ldi_ident_release(li);
25082 	crfree(cr);
25083 }
25084 
25085 /*
25086  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25087  *
25088  * Have to ensure that the ldi routines are not used by an
25089  * interrupt thread by using a taskq.
25090  */
25091 void
25092 tcp_g_q_inactive(tcp_stack_t *tcps)
25093 {
25094 	if (tcps->tcps_g_q_lh == NULL)
25095 		return;	/* Nothing to cleanup */
25096 
25097 	ASSERT(tcps->tcps_refcnt == 0);
25098 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
25099 
25100 	if (servicing_interrupt()) {
25101 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
25102 		    (void *) tcps, TQ_SLEEP);
25103 	} else {
25104 		tcp_g_q_close(tcps);
25105 	}
25106 }
25107 
25108 /*
25109  * Called by IP when IP is loaded into the kernel
25110  */
25111 void
25112 tcp_ddi_g_init(void)
25113 {
25114 	tcp_timercache = kmem_cache_create("tcp_timercache",
25115 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
25116 	    NULL, NULL, NULL, NULL, NULL, 0);
25117 
25118 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
25119 	    sizeof (tcp_sack_info_t), 0,
25120 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
25121 
25122 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
25123 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
25124 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
25125 
25126 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
25127 
25128 	/* Initialize the random number generator */
25129 	tcp_random_init();
25130 
25131 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
25132 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
25133 
25134 	/* A single callback independently of how many netstacks we have */
25135 	ip_squeue_init(tcp_squeue_add);
25136 
25137 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
25138 
25139 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
25140 	    TASKQ_PREPOPULATE);
25141 
25142 	/*
25143 	 * We want to be informed each time a stack is created or
25144 	 * destroyed in the kernel, so we can maintain the
25145 	 * set of tcp_stack_t's.
25146 	 */
25147 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
25148 	    tcp_stack_fini);
25149 }
25150 
25151 
25152 /*
25153  * Initialize the TCP stack instance.
25154  */
25155 static void *
25156 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
25157 {
25158 	tcp_stack_t	*tcps;
25159 	tcpparam_t	*pa;
25160 	int		i;
25161 
25162 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
25163 	tcps->tcps_netstack = ns;
25164 
25165 	/* Initialize locks */
25166 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
25167 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
25168 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
25169 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
25170 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
25171 	rw_init(&tcps->tcps_reserved_port_lock, NULL, RW_DEFAULT, NULL);
25172 
25173 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
25174 	tcps->tcps_g_epriv_ports[0] = 2049;
25175 	tcps->tcps_g_epriv_ports[1] = 4045;
25176 	tcps->tcps_min_anonpriv_port = 512;
25177 
25178 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
25179 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
25180 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
25181 	    TCP_FANOUT_SIZE, KM_SLEEP);
25182 	tcps->tcps_reserved_port = kmem_zalloc(sizeof (tcp_rport_t) *
25183 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE, KM_SLEEP);
25184 
25185 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25186 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
25187 		    MUTEX_DEFAULT, NULL);
25188 	}
25189 
25190 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25191 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25192 		    MUTEX_DEFAULT, NULL);
25193 	}
25194 
25195 	/* TCP's IPsec code calls the packet dropper. */
25196 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25197 
25198 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25199 	tcps->tcps_params = pa;
25200 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25201 
25202 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25203 	    A_CNT(lcl_tcp_param_arr), tcps);
25204 
25205 	/*
25206 	 * Note: To really walk the device tree you need the devinfo
25207 	 * pointer to your device which is only available after probe/attach.
25208 	 * The following is safe only because it uses ddi_root_node()
25209 	 */
25210 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25211 	    tcp_opt_obj.odb_opt_arr_cnt);
25212 
25213 	/*
25214 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25215 	 * by the boot scripts.
25216 	 *
25217 	 * Use NULL name, as the name is caught by the new lockstats.
25218 	 *
25219 	 * Initialize with some random, non-guessable string, like the global
25220 	 * T_INFO_ACK.
25221 	 */
25222 
25223 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25224 	    sizeof (tcp_g_t_info_ack), tcps);
25225 
25226 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25227 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25228 
25229 	return (tcps);
25230 }
25231 
25232 /*
25233  * Called when the IP module is about to be unloaded.
25234  */
25235 void
25236 tcp_ddi_g_destroy(void)
25237 {
25238 	tcp_g_kstat_fini(tcp_g_kstat);
25239 	tcp_g_kstat = NULL;
25240 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25241 
25242 	mutex_destroy(&tcp_random_lock);
25243 
25244 	kmem_cache_destroy(tcp_timercache);
25245 	kmem_cache_destroy(tcp_sack_info_cache);
25246 	kmem_cache_destroy(tcp_iphc_cache);
25247 
25248 	netstack_unregister(NS_TCP);
25249 	taskq_destroy(tcp_taskq);
25250 }
25251 
25252 /*
25253  * Shut down the TCP stack instance.
25254  */
25255 /* ARGSUSED */
25256 static void
25257 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25258 {
25259 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25260 
25261 	tcp_g_q_destroy(tcps);
25262 }
25263 
25264 /*
25265  * Free the TCP stack instance.
25266  */
25267 static void
25268 tcp_stack_fini(netstackid_t stackid, void *arg)
25269 {
25270 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25271 	int i;
25272 
25273 	nd_free(&tcps->tcps_g_nd);
25274 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25275 	tcps->tcps_params = NULL;
25276 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25277 	tcps->tcps_wroff_xtra_param = NULL;
25278 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25279 	tcps->tcps_mdt_head_param = NULL;
25280 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25281 	tcps->tcps_mdt_tail_param = NULL;
25282 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25283 	tcps->tcps_mdt_max_pbufs_param = NULL;
25284 
25285 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25286 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25287 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25288 	}
25289 
25290 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25291 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25292 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25293 	}
25294 
25295 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25296 	tcps->tcps_bind_fanout = NULL;
25297 
25298 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25299 	tcps->tcps_acceptor_fanout = NULL;
25300 
25301 	kmem_free(tcps->tcps_reserved_port, sizeof (tcp_rport_t) *
25302 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE);
25303 	tcps->tcps_reserved_port = NULL;
25304 
25305 	mutex_destroy(&tcps->tcps_iss_key_lock);
25306 	rw_destroy(&tcps->tcps_hsp_lock);
25307 	mutex_destroy(&tcps->tcps_g_q_lock);
25308 	cv_destroy(&tcps->tcps_g_q_cv);
25309 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25310 	rw_destroy(&tcps->tcps_reserved_port_lock);
25311 
25312 	ip_drop_unregister(&tcps->tcps_dropper);
25313 
25314 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25315 	tcps->tcps_kstat = NULL;
25316 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25317 
25318 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25319 	tcps->tcps_mibkp = NULL;
25320 
25321 	kmem_free(tcps, sizeof (*tcps));
25322 }
25323 
25324 /*
25325  * Generate ISS, taking into account NDD changes may happen halfway through.
25326  * (If the iss is not zero, set it.)
25327  */
25328 
25329 static void
25330 tcp_iss_init(tcp_t *tcp)
25331 {
25332 	MD5_CTX context;
25333 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25334 	uint32_t answer[4];
25335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25336 
25337 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25338 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25339 	switch (tcps->tcps_strong_iss) {
25340 	case 2:
25341 		mutex_enter(&tcps->tcps_iss_key_lock);
25342 		context = tcps->tcps_iss_key;
25343 		mutex_exit(&tcps->tcps_iss_key_lock);
25344 		arg.ports = tcp->tcp_ports;
25345 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25346 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25347 			    &arg.src);
25348 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25349 			    &arg.dst);
25350 		} else {
25351 			arg.src = tcp->tcp_ip6h->ip6_src;
25352 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25353 		}
25354 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25355 		MD5Final((uchar_t *)answer, &context);
25356 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25357 		/*
25358 		 * Now that we've hashed into a unique per-connection sequence
25359 		 * space, add a random increment per strong_iss == 1.  So I
25360 		 * guess we'll have to...
25361 		 */
25362 		/* FALLTHRU */
25363 	case 1:
25364 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25365 		break;
25366 	default:
25367 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25368 		break;
25369 	}
25370 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25371 	tcp->tcp_fss = tcp->tcp_iss - 1;
25372 	tcp->tcp_suna = tcp->tcp_iss;
25373 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25374 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25375 	tcp->tcp_csuna = tcp->tcp_snxt;
25376 }
25377 
25378 /*
25379  * Exported routine for extracting active tcp connection status.
25380  *
25381  * This is used by the Solaris Cluster Networking software to
25382  * gather a list of connections that need to be forwarded to
25383  * specific nodes in the cluster when configuration changes occur.
25384  *
25385  * The callback is invoked for each tcp_t structure. Returning
25386  * non-zero from the callback routine terminates the search.
25387  */
25388 int
25389 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25390     void *arg)
25391 {
25392 	netstack_handle_t nh;
25393 	netstack_t *ns;
25394 	int ret = 0;
25395 
25396 	netstack_next_init(&nh);
25397 	while ((ns = netstack_next(&nh)) != NULL) {
25398 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25399 		    ns->netstack_tcp);
25400 		netstack_rele(ns);
25401 	}
25402 	netstack_next_fini(&nh);
25403 	return (ret);
25404 }
25405 
25406 static int
25407 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25408     tcp_stack_t *tcps)
25409 {
25410 	tcp_t *tcp;
25411 	cl_tcp_info_t	cl_tcpi;
25412 	connf_t	*connfp;
25413 	conn_t	*connp;
25414 	int	i;
25415 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25416 
25417 	ASSERT(callback != NULL);
25418 
25419 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25420 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25421 		connp = NULL;
25422 
25423 		while ((connp =
25424 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25425 
25426 			tcp = connp->conn_tcp;
25427 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25428 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25429 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25430 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25431 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25432 			/*
25433 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25434 			 * addresses. They are copied implicitly below as
25435 			 * mapped addresses.
25436 			 */
25437 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25438 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25439 				cl_tcpi.cl_tcpi_faddr =
25440 				    tcp->tcp_ipha->ipha_dst;
25441 			} else {
25442 				cl_tcpi.cl_tcpi_faddr_v6 =
25443 				    tcp->tcp_ip6h->ip6_dst;
25444 			}
25445 
25446 			/*
25447 			 * If the callback returns non-zero
25448 			 * we terminate the traversal.
25449 			 */
25450 			if ((*callback)(&cl_tcpi, arg) != 0) {
25451 				CONN_DEC_REF(tcp->tcp_connp);
25452 				return (1);
25453 			}
25454 		}
25455 	}
25456 
25457 	return (0);
25458 }
25459 
25460 /*
25461  * Macros used for accessing the different types of sockaddr
25462  * structures inside a tcp_ioc_abort_conn_t.
25463  */
25464 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25465 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25466 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25467 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25468 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25469 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25470 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25471 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25472 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25473 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25474 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25475 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25476 
25477 /*
25478  * Return the correct error code to mimic the behavior
25479  * of a connection reset.
25480  */
25481 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25482 		switch ((state)) {		\
25483 		case TCPS_SYN_SENT:		\
25484 		case TCPS_SYN_RCVD:		\
25485 			(err) = ECONNREFUSED;	\
25486 			break;			\
25487 		case TCPS_ESTABLISHED:		\
25488 		case TCPS_FIN_WAIT_1:		\
25489 		case TCPS_FIN_WAIT_2:		\
25490 		case TCPS_CLOSE_WAIT:		\
25491 			(err) = ECONNRESET;	\
25492 			break;			\
25493 		case TCPS_CLOSING:		\
25494 		case TCPS_LAST_ACK:		\
25495 		case TCPS_TIME_WAIT:		\
25496 			(err) = 0;		\
25497 			break;			\
25498 		default:			\
25499 			(err) = ENXIO;		\
25500 		}				\
25501 	}
25502 
25503 /*
25504  * Check if a tcp structure matches the info in acp.
25505  */
25506 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25507 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25508 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25509 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25510 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25511 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25512 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25513 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25514 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25515 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25516 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25517 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25518 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25519 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25520 	&(tcp)->tcp_ip_src_v6)) &&				\
25521 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25522 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25523 	&(tcp)->tcp_remote_v6)) &&				\
25524 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25525 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25526 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25527 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25528 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25529 	(acp)->ac_end >= (tcp)->tcp_state))
25530 
25531 #define	TCP_AC_MATCH(acp, tcp)					\
25532 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25533 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25534 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25535 
25536 /*
25537  * Build a message containing a tcp_ioc_abort_conn_t structure
25538  * which is filled in with information from acp and tp.
25539  */
25540 static mblk_t *
25541 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25542 {
25543 	mblk_t *mp;
25544 	tcp_ioc_abort_conn_t *tacp;
25545 
25546 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25547 	if (mp == NULL)
25548 		return (NULL);
25549 
25550 	mp->b_datap->db_type = M_CTL;
25551 
25552 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25553 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25554 	    sizeof (uint32_t));
25555 
25556 	tacp->ac_start = acp->ac_start;
25557 	tacp->ac_end = acp->ac_end;
25558 	tacp->ac_zoneid = acp->ac_zoneid;
25559 
25560 	if (acp->ac_local.ss_family == AF_INET) {
25561 		tacp->ac_local.ss_family = AF_INET;
25562 		tacp->ac_remote.ss_family = AF_INET;
25563 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25564 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25565 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25566 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25567 	} else {
25568 		tacp->ac_local.ss_family = AF_INET6;
25569 		tacp->ac_remote.ss_family = AF_INET6;
25570 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25571 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25572 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25573 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25574 	}
25575 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25576 	return (mp);
25577 }
25578 
25579 /*
25580  * Print a tcp_ioc_abort_conn_t structure.
25581  */
25582 static void
25583 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25584 {
25585 	char lbuf[128];
25586 	char rbuf[128];
25587 	sa_family_t af;
25588 	in_port_t lport, rport;
25589 	ushort_t logflags;
25590 
25591 	af = acp->ac_local.ss_family;
25592 
25593 	if (af == AF_INET) {
25594 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25595 		    lbuf, 128);
25596 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25597 		    rbuf, 128);
25598 		lport = ntohs(TCP_AC_V4LPORT(acp));
25599 		rport = ntohs(TCP_AC_V4RPORT(acp));
25600 	} else {
25601 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25602 		    lbuf, 128);
25603 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25604 		    rbuf, 128);
25605 		lport = ntohs(TCP_AC_V6LPORT(acp));
25606 		rport = ntohs(TCP_AC_V6RPORT(acp));
25607 	}
25608 
25609 	logflags = SL_TRACE | SL_NOTE;
25610 	/*
25611 	 * Don't print this message to the console if the operation was done
25612 	 * to a non-global zone.
25613 	 */
25614 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25615 		logflags |= SL_CONSOLE;
25616 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25617 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25618 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25619 	    acp->ac_start, acp->ac_end);
25620 }
25621 
25622 /*
25623  * Called inside tcp_rput when a message built using
25624  * tcp_ioctl_abort_build_msg is put into a queue.
25625  * Note that when we get here there is no wildcard in acp any more.
25626  */
25627 static void
25628 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25629 {
25630 	tcp_ioc_abort_conn_t *acp;
25631 
25632 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25633 	if (tcp->tcp_state <= acp->ac_end) {
25634 		/*
25635 		 * If we get here, we are already on the correct
25636 		 * squeue. This ioctl follows the following path
25637 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25638 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25639 		 * different squeue)
25640 		 */
25641 		int errcode;
25642 
25643 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25644 		(void) tcp_clean_death(tcp, errcode, 26);
25645 	}
25646 	freemsg(mp);
25647 }
25648 
25649 /*
25650  * Abort all matching connections on a hash chain.
25651  */
25652 static int
25653 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25654     boolean_t exact, tcp_stack_t *tcps)
25655 {
25656 	int nmatch, err = 0;
25657 	tcp_t *tcp;
25658 	MBLKP mp, last, listhead = NULL;
25659 	conn_t	*tconnp;
25660 	connf_t	*connfp;
25661 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25662 
25663 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25664 
25665 startover:
25666 	nmatch = 0;
25667 
25668 	mutex_enter(&connfp->connf_lock);
25669 	for (tconnp = connfp->connf_head; tconnp != NULL;
25670 	    tconnp = tconnp->conn_next) {
25671 		tcp = tconnp->conn_tcp;
25672 		if (TCP_AC_MATCH(acp, tcp)) {
25673 			CONN_INC_REF(tcp->tcp_connp);
25674 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25675 			if (mp == NULL) {
25676 				err = ENOMEM;
25677 				CONN_DEC_REF(tcp->tcp_connp);
25678 				break;
25679 			}
25680 			mp->b_prev = (mblk_t *)tcp;
25681 
25682 			if (listhead == NULL) {
25683 				listhead = mp;
25684 				last = mp;
25685 			} else {
25686 				last->b_next = mp;
25687 				last = mp;
25688 			}
25689 			nmatch++;
25690 			if (exact)
25691 				break;
25692 		}
25693 
25694 		/* Avoid holding lock for too long. */
25695 		if (nmatch >= 500)
25696 			break;
25697 	}
25698 	mutex_exit(&connfp->connf_lock);
25699 
25700 	/* Pass mp into the correct tcp */
25701 	while ((mp = listhead) != NULL) {
25702 		listhead = listhead->b_next;
25703 		tcp = (tcp_t *)mp->b_prev;
25704 		mp->b_next = mp->b_prev = NULL;
25705 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25706 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25707 	}
25708 
25709 	*count += nmatch;
25710 	if (nmatch >= 500 && err == 0)
25711 		goto startover;
25712 	return (err);
25713 }
25714 
25715 /*
25716  * Abort all connections that matches the attributes specified in acp.
25717  */
25718 static int
25719 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25720 {
25721 	sa_family_t af;
25722 	uint32_t  ports;
25723 	uint16_t *pports;
25724 	int err = 0, count = 0;
25725 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25726 	int index = -1;
25727 	ushort_t logflags;
25728 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25729 
25730 	af = acp->ac_local.ss_family;
25731 
25732 	if (af == AF_INET) {
25733 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25734 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25735 			pports = (uint16_t *)&ports;
25736 			pports[1] = TCP_AC_V4LPORT(acp);
25737 			pports[0] = TCP_AC_V4RPORT(acp);
25738 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25739 		}
25740 	} else {
25741 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25742 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25743 			pports = (uint16_t *)&ports;
25744 			pports[1] = TCP_AC_V6LPORT(acp);
25745 			pports[0] = TCP_AC_V6RPORT(acp);
25746 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25747 		}
25748 	}
25749 
25750 	/*
25751 	 * For cases where remote addr, local port, and remote port are non-
25752 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25753 	 */
25754 	if (index != -1) {
25755 		err = tcp_ioctl_abort_bucket(acp, index,
25756 		    &count, exact, tcps);
25757 	} else {
25758 		/*
25759 		 * loop through all entries for wildcard case
25760 		 */
25761 		for (index = 0;
25762 		    index < ipst->ips_ipcl_conn_fanout_size;
25763 		    index++) {
25764 			err = tcp_ioctl_abort_bucket(acp, index,
25765 			    &count, exact, tcps);
25766 			if (err != 0)
25767 				break;
25768 		}
25769 	}
25770 
25771 	logflags = SL_TRACE | SL_NOTE;
25772 	/*
25773 	 * Don't print this message to the console if the operation was done
25774 	 * to a non-global zone.
25775 	 */
25776 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25777 		logflags |= SL_CONSOLE;
25778 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25779 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25780 	if (err == 0 && count == 0)
25781 		err = ENOENT;
25782 	return (err);
25783 }
25784 
25785 /*
25786  * Process the TCP_IOC_ABORT_CONN ioctl request.
25787  */
25788 static void
25789 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25790 {
25791 	int	err;
25792 	IOCP    iocp;
25793 	MBLKP   mp1;
25794 	sa_family_t laf, raf;
25795 	tcp_ioc_abort_conn_t *acp;
25796 	zone_t		*zptr;
25797 	conn_t		*connp = Q_TO_CONN(q);
25798 	zoneid_t	zoneid = connp->conn_zoneid;
25799 	tcp_t		*tcp = connp->conn_tcp;
25800 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25801 
25802 	iocp = (IOCP)mp->b_rptr;
25803 
25804 	if ((mp1 = mp->b_cont) == NULL ||
25805 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25806 		err = EINVAL;
25807 		goto out;
25808 	}
25809 
25810 	/* check permissions */
25811 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25812 		err = EPERM;
25813 		goto out;
25814 	}
25815 
25816 	if (mp1->b_cont != NULL) {
25817 		freemsg(mp1->b_cont);
25818 		mp1->b_cont = NULL;
25819 	}
25820 
25821 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25822 	laf = acp->ac_local.ss_family;
25823 	raf = acp->ac_remote.ss_family;
25824 
25825 	/* check that a zone with the supplied zoneid exists */
25826 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25827 		zptr = zone_find_by_id(zoneid);
25828 		if (zptr != NULL) {
25829 			zone_rele(zptr);
25830 		} else {
25831 			err = EINVAL;
25832 			goto out;
25833 		}
25834 	}
25835 
25836 	/*
25837 	 * For exclusive stacks we set the zoneid to zero
25838 	 * to make TCP operate as if in the global zone.
25839 	 */
25840 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25841 		acp->ac_zoneid = GLOBAL_ZONEID;
25842 
25843 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25844 	    acp->ac_start > acp->ac_end || laf != raf ||
25845 	    (laf != AF_INET && laf != AF_INET6)) {
25846 		err = EINVAL;
25847 		goto out;
25848 	}
25849 
25850 	tcp_ioctl_abort_dump(acp);
25851 	err = tcp_ioctl_abort(acp, tcps);
25852 
25853 out:
25854 	if (mp1 != NULL) {
25855 		freemsg(mp1);
25856 		mp->b_cont = NULL;
25857 	}
25858 
25859 	if (err != 0)
25860 		miocnak(q, mp, 0, err);
25861 	else
25862 		miocack(q, mp, 0, 0);
25863 }
25864 
25865 /*
25866  * tcp_time_wait_processing() handles processing of incoming packets when
25867  * the tcp is in the TIME_WAIT state.
25868  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25869  * on the time wait list.
25870  */
25871 void
25872 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25873     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25874 {
25875 	int32_t		bytes_acked;
25876 	int32_t		gap;
25877 	int32_t		rgap;
25878 	tcp_opt_t	tcpopt;
25879 	uint_t		flags;
25880 	uint32_t	new_swnd = 0;
25881 	conn_t		*connp;
25882 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25883 
25884 	BUMP_LOCAL(tcp->tcp_ibsegs);
25885 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
25886 
25887 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25888 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25889 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25890 	if (tcp->tcp_snd_ts_ok) {
25891 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25892 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25893 			    tcp->tcp_rnxt, TH_ACK);
25894 			goto done;
25895 		}
25896 	}
25897 	gap = seg_seq - tcp->tcp_rnxt;
25898 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25899 	if (gap < 0) {
25900 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25901 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25902 		    (seg_len > -gap ? -gap : seg_len));
25903 		seg_len += gap;
25904 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25905 			if (flags & TH_RST) {
25906 				goto done;
25907 			}
25908 			if ((flags & TH_FIN) && seg_len == -1) {
25909 				/*
25910 				 * When TCP receives a duplicate FIN in
25911 				 * TIME_WAIT state, restart the 2 MSL timer.
25912 				 * See page 73 in RFC 793. Make sure this TCP
25913 				 * is already on the TIME_WAIT list. If not,
25914 				 * just restart the timer.
25915 				 */
25916 				if (TCP_IS_DETACHED(tcp)) {
25917 					if (tcp_time_wait_remove(tcp, NULL) ==
25918 					    B_TRUE) {
25919 						tcp_time_wait_append(tcp);
25920 						TCP_DBGSTAT(tcps,
25921 						    tcp_rput_time_wait);
25922 					}
25923 				} else {
25924 					ASSERT(tcp != NULL);
25925 					TCP_TIMER_RESTART(tcp,
25926 					    tcps->tcps_time_wait_interval);
25927 				}
25928 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25929 				    tcp->tcp_rnxt, TH_ACK);
25930 				goto done;
25931 			}
25932 			flags |=  TH_ACK_NEEDED;
25933 			seg_len = 0;
25934 			goto process_ack;
25935 		}
25936 
25937 		/* Fix seg_seq, and chew the gap off the front. */
25938 		seg_seq = tcp->tcp_rnxt;
25939 	}
25940 
25941 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25942 		/*
25943 		 * Make sure that when we accept the connection, pick
25944 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25945 		 * old connection.
25946 		 *
25947 		 * The next ISS generated is equal to tcp_iss_incr_extra
25948 		 * + ISS_INCR/2 + other components depending on the
25949 		 * value of tcp_strong_iss.  We pre-calculate the new
25950 		 * ISS here and compare with tcp_snxt to determine if
25951 		 * we need to make adjustment to tcp_iss_incr_extra.
25952 		 *
25953 		 * The above calculation is ugly and is a
25954 		 * waste of CPU cycles...
25955 		 */
25956 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25957 		int32_t adj;
25958 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25959 
25960 		switch (tcps->tcps_strong_iss) {
25961 		case 2: {
25962 			/* Add time and MD5 components. */
25963 			uint32_t answer[4];
25964 			struct {
25965 				uint32_t ports;
25966 				in6_addr_t src;
25967 				in6_addr_t dst;
25968 			} arg;
25969 			MD5_CTX context;
25970 
25971 			mutex_enter(&tcps->tcps_iss_key_lock);
25972 			context = tcps->tcps_iss_key;
25973 			mutex_exit(&tcps->tcps_iss_key_lock);
25974 			arg.ports = tcp->tcp_ports;
25975 			/* We use MAPPED addresses in tcp_iss_init */
25976 			arg.src = tcp->tcp_ip_src_v6;
25977 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25978 				IN6_IPADDR_TO_V4MAPPED(
25979 				    tcp->tcp_ipha->ipha_dst,
25980 				    &arg.dst);
25981 			} else {
25982 				arg.dst =
25983 				    tcp->tcp_ip6h->ip6_dst;
25984 			}
25985 			MD5Update(&context, (uchar_t *)&arg,
25986 			    sizeof (arg));
25987 			MD5Final((uchar_t *)answer, &context);
25988 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25989 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25990 			break;
25991 		}
25992 		case 1:
25993 			/* Add time component and min random (i.e. 1). */
25994 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25995 			break;
25996 		default:
25997 			/* Add only time component. */
25998 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25999 			break;
26000 		}
26001 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
26002 			/*
26003 			 * New ISS not guaranteed to be ISS_INCR/2
26004 			 * ahead of the current tcp_snxt, so add the
26005 			 * difference to tcp_iss_incr_extra.
26006 			 */
26007 			tcps->tcps_iss_incr_extra += adj;
26008 		}
26009 		/*
26010 		 * If tcp_clean_death() can not perform the task now,
26011 		 * drop the SYN packet and let the other side re-xmit.
26012 		 * Otherwise pass the SYN packet back in, since the
26013 		 * old tcp state has been cleaned up or freed.
26014 		 */
26015 		if (tcp_clean_death(tcp, 0, 27) == -1)
26016 			goto done;
26017 		/*
26018 		 * We will come back to tcp_rput_data
26019 		 * on the global queue. Packets destined
26020 		 * for the global queue will be checked
26021 		 * with global policy. But the policy for
26022 		 * this packet has already been checked as
26023 		 * this was destined for the detached
26024 		 * connection. We need to bypass policy
26025 		 * check this time by attaching a dummy
26026 		 * ipsec_in with ipsec_in_dont_check set.
26027 		 */
26028 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
26029 		if (connp != NULL) {
26030 			TCP_STAT(tcps, tcp_time_wait_syn_success);
26031 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
26032 			return;
26033 		}
26034 		goto done;
26035 	}
26036 
26037 	/*
26038 	 * rgap is the amount of stuff received out of window.  A negative
26039 	 * value is the amount out of window.
26040 	 */
26041 	if (rgap < 0) {
26042 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
26043 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
26044 		/* Fix seg_len and make sure there is something left. */
26045 		seg_len += rgap;
26046 		if (seg_len <= 0) {
26047 			if (flags & TH_RST) {
26048 				goto done;
26049 			}
26050 			flags |=  TH_ACK_NEEDED;
26051 			seg_len = 0;
26052 			goto process_ack;
26053 		}
26054 	}
26055 	/*
26056 	 * Check whether we can update tcp_ts_recent.  This test is
26057 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
26058 	 * Extensions for High Performance: An Update", Internet Draft.
26059 	 */
26060 	if (tcp->tcp_snd_ts_ok &&
26061 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
26062 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
26063 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
26064 		tcp->tcp_last_rcv_lbolt = lbolt64;
26065 	}
26066 
26067 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
26068 		/* Always ack out of order packets */
26069 		flags |= TH_ACK_NEEDED;
26070 		seg_len = 0;
26071 	} else if (seg_len > 0) {
26072 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
26073 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
26074 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
26075 	}
26076 	if (flags & TH_RST) {
26077 		(void) tcp_clean_death(tcp, 0, 28);
26078 		goto done;
26079 	}
26080 	if (flags & TH_SYN) {
26081 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
26082 		    TH_RST|TH_ACK);
26083 		/*
26084 		 * Do not delete the TCP structure if it is in
26085 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
26086 		 */
26087 		goto done;
26088 	}
26089 process_ack:
26090 	if (flags & TH_ACK) {
26091 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
26092 		if (bytes_acked <= 0) {
26093 			if (bytes_acked == 0 && seg_len == 0 &&
26094 			    new_swnd == tcp->tcp_swnd)
26095 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
26096 		} else {
26097 			/* Acks something not sent */
26098 			flags |= TH_ACK_NEEDED;
26099 		}
26100 	}
26101 	if (flags & TH_ACK_NEEDED) {
26102 		/*
26103 		 * Time to send an ack for some reason.
26104 		 */
26105 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26106 		    tcp->tcp_rnxt, TH_ACK);
26107 	}
26108 done:
26109 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26110 		DB_CKSUMSTART(mp) = 0;
26111 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
26112 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
26113 	}
26114 	freemsg(mp);
26115 }
26116 
26117 /*
26118  * Allocate a T_SVR4_OPTMGMT_REQ.
26119  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
26120  * that tcp_rput_other can drop the acks.
26121  */
26122 static mblk_t *
26123 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
26124 {
26125 	mblk_t *mp;
26126 	struct T_optmgmt_req *tor;
26127 	struct opthdr *oh;
26128 	uint_t size;
26129 	char *optptr;
26130 
26131 	size = sizeof (*tor) + sizeof (*oh) + optlen;
26132 	mp = allocb(size, BPRI_MED);
26133 	if (mp == NULL)
26134 		return (NULL);
26135 
26136 	mp->b_wptr += size;
26137 	mp->b_datap->db_type = M_PROTO;
26138 	tor = (struct T_optmgmt_req *)mp->b_rptr;
26139 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
26140 	tor->MGMT_flags = T_NEGOTIATE;
26141 	tor->OPT_length = sizeof (*oh) + optlen;
26142 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
26143 
26144 	oh = (struct opthdr *)&tor[1];
26145 	oh->level = level;
26146 	oh->name = cmd;
26147 	oh->len = optlen;
26148 	if (optlen != 0) {
26149 		optptr = (char *)&oh[1];
26150 		bcopy(opt, optptr, optlen);
26151 	}
26152 	return (mp);
26153 }
26154 
26155 /*
26156  * TCP Timers Implementation.
26157  */
26158 timeout_id_t
26159 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
26160 {
26161 	mblk_t *mp;
26162 	tcp_timer_t *tcpt;
26163 	tcp_t *tcp = connp->conn_tcp;
26164 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26165 
26166 	ASSERT(connp->conn_sqp != NULL);
26167 
26168 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
26169 
26170 	if (tcp->tcp_timercache == NULL) {
26171 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
26172 	} else {
26173 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
26174 		mp = tcp->tcp_timercache;
26175 		tcp->tcp_timercache = mp->b_next;
26176 		mp->b_next = NULL;
26177 		ASSERT(mp->b_wptr == NULL);
26178 	}
26179 
26180 	CONN_INC_REF(connp);
26181 	tcpt = (tcp_timer_t *)mp->b_rptr;
26182 	tcpt->connp = connp;
26183 	tcpt->tcpt_proc = f;
26184 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
26185 	return ((timeout_id_t)mp);
26186 }
26187 
26188 static void
26189 tcp_timer_callback(void *arg)
26190 {
26191 	mblk_t *mp = (mblk_t *)arg;
26192 	tcp_timer_t *tcpt;
26193 	conn_t	*connp;
26194 
26195 	tcpt = (tcp_timer_t *)mp->b_rptr;
26196 	connp = tcpt->connp;
26197 	squeue_fill(connp->conn_sqp, mp,
26198 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26199 }
26200 
26201 static void
26202 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26203 {
26204 	tcp_timer_t *tcpt;
26205 	conn_t *connp = (conn_t *)arg;
26206 	tcp_t *tcp = connp->conn_tcp;
26207 
26208 	tcpt = (tcp_timer_t *)mp->b_rptr;
26209 	ASSERT(connp == tcpt->connp);
26210 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26211 
26212 	/*
26213 	 * If the TCP has reached the closed state, don't proceed any
26214 	 * further. This TCP logically does not exist on the system.
26215 	 * tcpt_proc could for example access queues, that have already
26216 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26217 	 */
26218 	if (tcp->tcp_state != TCPS_CLOSED) {
26219 		(*tcpt->tcpt_proc)(connp);
26220 	} else {
26221 		tcp->tcp_timer_tid = 0;
26222 	}
26223 	tcp_timer_free(connp->conn_tcp, mp);
26224 }
26225 
26226 /*
26227  * There is potential race with untimeout and the handler firing at the same
26228  * time. The mblock may be freed by the handler while we are trying to use
26229  * it. But since both should execute on the same squeue, this race should not
26230  * occur.
26231  */
26232 clock_t
26233 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26234 {
26235 	mblk_t	*mp = (mblk_t *)id;
26236 	tcp_timer_t *tcpt;
26237 	clock_t delta;
26238 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26239 
26240 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26241 
26242 	if (mp == NULL)
26243 		return (-1);
26244 
26245 	tcpt = (tcp_timer_t *)mp->b_rptr;
26246 	ASSERT(tcpt->connp == connp);
26247 
26248 	delta = untimeout(tcpt->tcpt_tid);
26249 
26250 	if (delta >= 0) {
26251 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26252 		tcp_timer_free(connp->conn_tcp, mp);
26253 		CONN_DEC_REF(connp);
26254 	}
26255 
26256 	return (delta);
26257 }
26258 
26259 /*
26260  * Allocate space for the timer event. The allocation looks like mblk, but it is
26261  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26262  *
26263  * Dealing with failures: If we can't allocate from the timer cache we try
26264  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26265  * points to b_rptr.
26266  * If we can't allocate anything using allocb_tryhard(), we perform a last
26267  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26268  * save the actual allocation size in b_datap.
26269  */
26270 mblk_t *
26271 tcp_timermp_alloc(int kmflags)
26272 {
26273 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26274 	    kmflags & ~KM_PANIC);
26275 
26276 	if (mp != NULL) {
26277 		mp->b_next = mp->b_prev = NULL;
26278 		mp->b_rptr = (uchar_t *)(&mp[1]);
26279 		mp->b_wptr = NULL;
26280 		mp->b_datap = NULL;
26281 		mp->b_queue = NULL;
26282 		mp->b_cont = NULL;
26283 	} else if (kmflags & KM_PANIC) {
26284 		/*
26285 		 * Failed to allocate memory for the timer. Try allocating from
26286 		 * dblock caches.
26287 		 */
26288 		/* ipclassifier calls this from a constructor - hence no tcps */
26289 		TCP_G_STAT(tcp_timermp_allocfail);
26290 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26291 		if (mp == NULL) {
26292 			size_t size = 0;
26293 			/*
26294 			 * Memory is really low. Try tryhard allocation.
26295 			 *
26296 			 * ipclassifier calls this from a constructor -
26297 			 * hence no tcps
26298 			 */
26299 			TCP_G_STAT(tcp_timermp_allocdblfail);
26300 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26301 			    sizeof (tcp_timer_t), &size, kmflags);
26302 			mp->b_rptr = (uchar_t *)(&mp[1]);
26303 			mp->b_next = mp->b_prev = NULL;
26304 			mp->b_wptr = (uchar_t *)-1;
26305 			mp->b_datap = (dblk_t *)size;
26306 			mp->b_queue = NULL;
26307 			mp->b_cont = NULL;
26308 		}
26309 		ASSERT(mp->b_wptr != NULL);
26310 	}
26311 	/* ipclassifier calls this from a constructor - hence no tcps */
26312 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26313 
26314 	return (mp);
26315 }
26316 
26317 /*
26318  * Free per-tcp timer cache.
26319  * It can only contain entries from tcp_timercache.
26320  */
26321 void
26322 tcp_timermp_free(tcp_t *tcp)
26323 {
26324 	mblk_t *mp;
26325 
26326 	while ((mp = tcp->tcp_timercache) != NULL) {
26327 		ASSERT(mp->b_wptr == NULL);
26328 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26329 		kmem_cache_free(tcp_timercache, mp);
26330 	}
26331 }
26332 
26333 /*
26334  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26335  * events there already (currently at most two events are cached).
26336  * If the event is not allocated from the timer cache, free it right away.
26337  */
26338 static void
26339 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26340 {
26341 	mblk_t *mp1 = tcp->tcp_timercache;
26342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26343 
26344 	if (mp->b_wptr != NULL) {
26345 		/*
26346 		 * This allocation is not from a timer cache, free it right
26347 		 * away.
26348 		 */
26349 		if (mp->b_wptr != (uchar_t *)-1)
26350 			freeb(mp);
26351 		else
26352 			kmem_free(mp, (size_t)mp->b_datap);
26353 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26354 		/* Cache this timer block for future allocations */
26355 		mp->b_rptr = (uchar_t *)(&mp[1]);
26356 		mp->b_next = mp1;
26357 		tcp->tcp_timercache = mp;
26358 	} else {
26359 		kmem_cache_free(tcp_timercache, mp);
26360 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26361 	}
26362 }
26363 
26364 /*
26365  * End of TCP Timers implementation.
26366  */
26367 
26368 /*
26369  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26370  * on the specified backing STREAMS q. Note, the caller may make the
26371  * decision to call based on the tcp_t.tcp_flow_stopped value which
26372  * when check outside the q's lock is only an advisory check ...
26373  */
26374 
26375 void
26376 tcp_setqfull(tcp_t *tcp)
26377 {
26378 	queue_t *q = tcp->tcp_wq;
26379 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26380 
26381 	if (!(q->q_flag & QFULL)) {
26382 		mutex_enter(QLOCK(q));
26383 		if (!(q->q_flag & QFULL)) {
26384 			/* still need to set QFULL */
26385 			q->q_flag |= QFULL;
26386 			tcp->tcp_flow_stopped = B_TRUE;
26387 			mutex_exit(QLOCK(q));
26388 			TCP_STAT(tcps, tcp_flwctl_on);
26389 		} else {
26390 			mutex_exit(QLOCK(q));
26391 		}
26392 	}
26393 }
26394 
26395 void
26396 tcp_clrqfull(tcp_t *tcp)
26397 {
26398 	queue_t *q = tcp->tcp_wq;
26399 
26400 	if (q->q_flag & QFULL) {
26401 		mutex_enter(QLOCK(q));
26402 		if (q->q_flag & QFULL) {
26403 			q->q_flag &= ~QFULL;
26404 			tcp->tcp_flow_stopped = B_FALSE;
26405 			mutex_exit(QLOCK(q));
26406 			if (q->q_flag & QWANTW)
26407 				qbackenable(q, 0);
26408 		} else {
26409 			mutex_exit(QLOCK(q));
26410 		}
26411 	}
26412 }
26413 
26414 
26415 /*
26416  * kstats related to squeues i.e. not per IP instance
26417  */
26418 static void *
26419 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26420 {
26421 	kstat_t *ksp;
26422 
26423 	tcp_g_stat_t template = {
26424 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26425 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26426 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26427 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26428 	};
26429 
26430 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26431 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26432 	    KSTAT_FLAG_VIRTUAL);
26433 
26434 	if (ksp == NULL)
26435 		return (NULL);
26436 
26437 	bcopy(&template, tcp_g_statp, sizeof (template));
26438 	ksp->ks_data = (void *)tcp_g_statp;
26439 
26440 	kstat_install(ksp);
26441 	return (ksp);
26442 }
26443 
26444 static void
26445 tcp_g_kstat_fini(kstat_t *ksp)
26446 {
26447 	if (ksp != NULL) {
26448 		kstat_delete(ksp);
26449 	}
26450 }
26451 
26452 
26453 static void *
26454 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26455 {
26456 	kstat_t *ksp;
26457 
26458 	tcp_stat_t template = {
26459 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26460 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26461 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26462 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26463 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26464 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26465 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26466 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26467 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26468 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26469 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26470 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26471 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26472 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26473 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26474 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26475 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26476 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26477 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26478 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26479 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26480 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26481 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26482 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26483 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26484 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26485 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26486 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26487 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26488 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26489 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26490 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26491 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26492 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26493 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26494 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26495 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26496 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26497 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26498 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26499 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26500 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26501 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26502 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26503 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26504 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26505 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26506 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26507 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26508 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26509 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26510 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26511 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26512 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26513 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26514 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26515 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26516 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26517 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26518 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26519 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26520 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26521 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26522 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26523 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26524 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26525 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26526 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26527 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26528 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26529 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26530 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26531 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26532 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26533 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26534 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26535 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26536 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26537 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26538 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26539 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26540 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26541 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26542 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26543 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26544 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26545 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26546 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26547 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26548 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26549 	};
26550 
26551 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26552 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26553 	    KSTAT_FLAG_VIRTUAL, stackid);
26554 
26555 	if (ksp == NULL)
26556 		return (NULL);
26557 
26558 	bcopy(&template, tcps_statisticsp, sizeof (template));
26559 	ksp->ks_data = (void *)tcps_statisticsp;
26560 	ksp->ks_private = (void *)(uintptr_t)stackid;
26561 
26562 	kstat_install(ksp);
26563 	return (ksp);
26564 }
26565 
26566 static void
26567 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26568 {
26569 	if (ksp != NULL) {
26570 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26571 		kstat_delete_netstack(ksp, stackid);
26572 	}
26573 }
26574 
26575 /*
26576  * TCP Kstats implementation
26577  */
26578 static void *
26579 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26580 {
26581 	kstat_t	*ksp;
26582 
26583 	tcp_named_kstat_t template = {
26584 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26585 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26586 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26587 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26588 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26589 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26590 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26591 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26592 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26593 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26594 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26595 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26596 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26597 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26598 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26599 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26600 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26601 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26602 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26603 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26604 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26605 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26606 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26607 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26608 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26609 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26610 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26611 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26612 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26613 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26614 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26615 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26616 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26617 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26618 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26619 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26620 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26621 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26622 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26623 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26624 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26625 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26626 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26627 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26628 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26629 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26630 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26631 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26632 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26633 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26634 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26635 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26636 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26637 	};
26638 
26639 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26640 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26641 
26642 	if (ksp == NULL)
26643 		return (NULL);
26644 
26645 	template.rtoAlgorithm.value.ui32 = 4;
26646 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26647 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26648 	template.maxConn.value.i32 = -1;
26649 
26650 	bcopy(&template, ksp->ks_data, sizeof (template));
26651 	ksp->ks_update = tcp_kstat_update;
26652 	ksp->ks_private = (void *)(uintptr_t)stackid;
26653 
26654 	kstat_install(ksp);
26655 	return (ksp);
26656 }
26657 
26658 static void
26659 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26660 {
26661 	if (ksp != NULL) {
26662 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26663 		kstat_delete_netstack(ksp, stackid);
26664 	}
26665 }
26666 
26667 static int
26668 tcp_kstat_update(kstat_t *kp, int rw)
26669 {
26670 	tcp_named_kstat_t *tcpkp;
26671 	tcp_t		*tcp;
26672 	connf_t		*connfp;
26673 	conn_t		*connp;
26674 	int 		i;
26675 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26676 	netstack_t	*ns;
26677 	tcp_stack_t	*tcps;
26678 	ip_stack_t	*ipst;
26679 
26680 	if ((kp == NULL) || (kp->ks_data == NULL))
26681 		return (EIO);
26682 
26683 	if (rw == KSTAT_WRITE)
26684 		return (EACCES);
26685 
26686 	ns = netstack_find_by_stackid(stackid);
26687 	if (ns == NULL)
26688 		return (-1);
26689 	tcps = ns->netstack_tcp;
26690 	if (tcps == NULL) {
26691 		netstack_rele(ns);
26692 		return (-1);
26693 	}
26694 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26695 
26696 	tcpkp->currEstab.value.ui32 = 0;
26697 
26698 	ipst = ns->netstack_ip;
26699 
26700 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26701 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26702 		connp = NULL;
26703 		while ((connp =
26704 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26705 			tcp = connp->conn_tcp;
26706 			switch (tcp_snmp_state(tcp)) {
26707 			case MIB2_TCP_established:
26708 			case MIB2_TCP_closeWait:
26709 				tcpkp->currEstab.value.ui32++;
26710 				break;
26711 			}
26712 		}
26713 	}
26714 
26715 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26716 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26717 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26718 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26719 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26720 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26721 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26722 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26723 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26724 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26725 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26726 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26727 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26728 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26729 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26730 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26731 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26732 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26733 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26734 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26735 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26736 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26737 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26738 	tcpkp->inDataInorderSegs.value.ui32 =
26739 	    tcps->tcps_mib.tcpInDataInorderSegs;
26740 	tcpkp->inDataInorderBytes.value.ui32 =
26741 	    tcps->tcps_mib.tcpInDataInorderBytes;
26742 	tcpkp->inDataUnorderSegs.value.ui32 =
26743 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26744 	tcpkp->inDataUnorderBytes.value.ui32 =
26745 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26746 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26747 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26748 	tcpkp->inDataPartDupSegs.value.ui32 =
26749 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26750 	tcpkp->inDataPartDupBytes.value.ui32 =
26751 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26752 	tcpkp->inDataPastWinSegs.value.ui32 =
26753 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26754 	tcpkp->inDataPastWinBytes.value.ui32 =
26755 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26756 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26757 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26758 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26759 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26760 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26761 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26762 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26763 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26764 	tcpkp->timKeepaliveProbe.value.ui32 =
26765 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26766 	tcpkp->timKeepaliveDrop.value.ui32 =
26767 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26768 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26769 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26770 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26771 	tcpkp->outSackRetransSegs.value.ui32 =
26772 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26773 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26774 
26775 	netstack_rele(ns);
26776 	return (0);
26777 }
26778 
26779 void
26780 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26781 {
26782 	uint16_t	hdr_len;
26783 	ipha_t		*ipha;
26784 	uint8_t		*nexthdrp;
26785 	tcph_t		*tcph;
26786 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26787 
26788 	/* Already has an eager */
26789 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26790 		TCP_STAT(tcps, tcp_reinput_syn);
26791 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26792 		    connp, SQTAG_TCP_REINPUT_EAGER);
26793 		return;
26794 	}
26795 
26796 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26797 	case IPV4_VERSION:
26798 		ipha = (ipha_t *)mp->b_rptr;
26799 		hdr_len = IPH_HDR_LENGTH(ipha);
26800 		break;
26801 	case IPV6_VERSION:
26802 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26803 		    &hdr_len, &nexthdrp)) {
26804 			CONN_DEC_REF(connp);
26805 			freemsg(mp);
26806 			return;
26807 		}
26808 		break;
26809 	}
26810 
26811 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26812 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26813 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26814 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26815 	}
26816 
26817 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26818 	    SQTAG_TCP_REINPUT);
26819 }
26820 
26821 static squeue_func_t
26822 tcp_squeue_switch(int val)
26823 {
26824 	squeue_func_t rval = squeue_fill;
26825 
26826 	switch (val) {
26827 	case 1:
26828 		rval = squeue_enter_nodrain;
26829 		break;
26830 	case 2:
26831 		rval = squeue_enter;
26832 		break;
26833 	default:
26834 		break;
26835 	}
26836 	return (rval);
26837 }
26838 
26839 /*
26840  * This is called once for each squeue - globally for all stack
26841  * instances.
26842  */
26843 static void
26844 tcp_squeue_add(squeue_t *sqp)
26845 {
26846 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26847 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26848 
26849 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26850 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
26851 	    sqp, TCP_TIME_WAIT_DELAY);
26852 	if (tcp_free_list_max_cnt == 0) {
26853 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26854 		    max_ncpus : boot_max_ncpus);
26855 
26856 		/*
26857 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26858 		 */
26859 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26860 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26861 	}
26862 	tcp_time_wait->tcp_free_list_cnt = 0;
26863 }
26864