xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 46a7ef8aa64ee52c612c9b1b02ca19542a7a2e89)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
30 
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/sdt.h>
49 #include <sys/vtrace.h>
50 #include <sys/kmem.h>
51 #include <sys/ethernet.h>
52 #include <sys/cpuvar.h>
53 #include <sys/dlpi.h>
54 #include <sys/multidata.h>
55 #include <sys/multidata_impl.h>
56 #include <sys/pattr.h>
57 #include <sys/policy.h>
58 #include <sys/priv.h>
59 #include <sys/zone.h>
60 #include <sys/sunldi.h>
61 
62 #include <sys/errno.h>
63 #include <sys/signal.h>
64 #include <sys/socket.h>
65 #include <sys/sockio.h>
66 #include <sys/isa_defs.h>
67 #include <sys/md5.h>
68 #include <sys/random.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 #include <inet/ipsec_impl.h>
76 
77 #include <inet/common.h>
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip_ndp.h>
82 #include <inet/mi.h>
83 #include <inet/mib2.h>
84 #include <inet/nd.h>
85 #include <inet/optcom.h>
86 #include <inet/snmpcom.h>
87 #include <inet/kstatcom.h>
88 #include <inet/tcp.h>
89 #include <inet/tcp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 #include <inet/tcp_trace.h>
94 
95 #include <inet/ipclassifier.h>
96 #include <inet/ip_ire.h>
97 #include <inet/ip_ftable.h>
98 #include <inet/ip_if.h>
99 #include <inet/ipp_common.h>
100 #include <inet/ip_netinfo.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <sys/sdt.h>
106 #include <rpc/pmap_prot.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
130  * squeue_fill). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * IPsec notes :
221  *
222  * Since a packet is always executed on the correct TCP perimeter
223  * all IPsec processing is defered to IP including checking new
224  * connections and setting IPSEC policies for new connection. The
225  * only exception is tcp_xmit_listeners_reset() which is called
226  * directly from IP and needs to policy check to see if TH_RST
227  * can be sent out.
228  *
229  * PFHooks notes :
230  *
231  * For mdt case, one meta buffer contains multiple packets. Mblks for every
232  * packet are assembled and passed to the hooks. When packets are blocked,
233  * or boundary of any packet is changed, the mdt processing is stopped, and
234  * packets of the meta buffer are send to the IP path one by one.
235  */
236 
237 extern major_t TCP6_MAJ;
238 
239 /*
240  * Values for squeue switch:
241  * 1: squeue_enter_nodrain
242  * 2: squeue_enter
243  * 3: squeue_fill
244  */
245 int tcp_squeue_close = 2;	/* Setable in /etc/system */
246 int tcp_squeue_wput = 2;
247 
248 squeue_func_t tcp_squeue_close_proc;
249 squeue_func_t tcp_squeue_wput_proc;
250 
251 /*
252  * This controls how tiny a write must be before we try to copy it
253  * into the the mblk on the tail of the transmit queue.  Not much
254  * speedup is observed for values larger than sixteen.  Zero will
255  * disable the optimisation.
256  */
257 int tcp_tx_pull_len = 16;
258 
259 /*
260  * TCP Statistics.
261  *
262  * How TCP statistics work.
263  *
264  * There are two types of statistics invoked by two macros.
265  *
266  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
267  * supposed to be used in non MT-hot paths of the code.
268  *
269  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
270  * supposed to be used for DEBUG purposes and may be used on a hot path.
271  *
272  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
273  * (use "kstat tcp" to get them).
274  *
275  * There is also additional debugging facility that marks tcp_clean_death()
276  * instances and saves them in tcp_t structure. It is triggered by
277  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
278  * tcp_clean_death() calls that counts the number of times each tag was hit. It
279  * is triggered by TCP_CLD_COUNTERS define.
280  *
281  * How to add new counters.
282  *
283  * 1) Add a field in the tcp_stat structure describing your counter.
284  * 2) Add a line in the template in tcp_kstat2_init() with the name
285  *    of the counter.
286  *
287  *    IMPORTANT!! - make sure that both are in sync !!
288  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
289  *
290  * Please avoid using private counters which are not kstat-exported.
291  *
292  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
293  * in tcp_t structure.
294  *
295  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
296  */
297 
298 #ifndef TCP_DEBUG_COUNTER
299 #ifdef DEBUG
300 #define	TCP_DEBUG_COUNTER 1
301 #else
302 #define	TCP_DEBUG_COUNTER 0
303 #endif
304 #endif
305 
306 #define	TCP_CLD_COUNTERS 0
307 
308 #define	TCP_TAG_CLEAN_DEATH 1
309 #define	TCP_MAX_CLEAN_DEATH_TAG 32
310 
311 #ifdef lint
312 static int _lint_dummy_;
313 #endif
314 
315 #if TCP_CLD_COUNTERS
316 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
317 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
318 #elif defined(lint)
319 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
320 #else
321 #define	TCP_CLD_STAT(x)
322 #endif
323 
324 #if TCP_DEBUG_COUNTER
325 #define	TCP_DBGSTAT(tcps, x)	\
326 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
327 #define	TCP_G_DBGSTAT(x)	\
328 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
329 #elif defined(lint)
330 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
331 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
332 #else
333 #define	TCP_DBGSTAT(tcps, x)
334 #define	TCP_G_DBGSTAT(x)
335 #endif
336 
337 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
338 
339 tcp_g_stat_t	tcp_g_statistics;
340 kstat_t		*tcp_g_kstat;
341 
342 /*
343  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
344  * tcp write side.
345  */
346 #define	CALL_IP_WPUT(connp, q, mp) {					\
347 	tcp_stack_t	*tcps;						\
348 									\
349 	tcps = connp->conn_netstack->netstack_tcp;			\
350 	ASSERT(((q)->q_flag & QREADR) == 0);				\
351 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
352 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
353 }
354 
355 /* Macros for timestamp comparisons */
356 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
357 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
358 
359 /*
360  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
361  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
362  * by adding three components: a time component which grows by 1 every 4096
363  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
364  * a per-connection component which grows by 125000 for every new connection;
365  * and an "extra" component that grows by a random amount centered
366  * approximately on 64000.  This causes the the ISS generator to cycle every
367  * 4.89 hours if no TCP connections are made, and faster if connections are
368  * made.
369  *
370  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
371  * components: a time component which grows by 250000 every second; and
372  * a per-connection component which grows by 125000 for every new connections.
373  *
374  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
375  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
376  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
377  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
378  * password.
379  */
380 #define	ISS_INCR	250000
381 #define	ISS_NSEC_SHT	12
382 
383 static sin_t	sin_null;	/* Zero address for quick clears */
384 static sin6_t	sin6_null;	/* Zero address for quick clears */
385 
386 /*
387  * This implementation follows the 4.3BSD interpretation of the urgent
388  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
389  * incompatible changes in protocols like telnet and rlogin.
390  */
391 #define	TCP_OLD_URP_INTERPRETATION	1
392 
393 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
394 	(TCP_IS_DETACHED(tcp) && \
395 	    (!(tcp)->tcp_hard_binding))
396 
397 /*
398  * TCP reassembly macros.  We hide starting and ending sequence numbers in
399  * b_next and b_prev of messages on the reassembly queue.  The messages are
400  * chained using b_cont.  These macros are used in tcp_reass() so we don't
401  * have to see the ugly casts and assignments.
402  */
403 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
404 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
405 					(mblk_t *)(uintptr_t)(u))
406 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
407 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
408 					(mblk_t *)(uintptr_t)(u))
409 
410 /*
411  * Implementation of TCP Timers.
412  * =============================
413  *
414  * INTERFACE:
415  *
416  * There are two basic functions dealing with tcp timers:
417  *
418  *	timeout_id_t	tcp_timeout(connp, func, time)
419  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
420  *	TCP_TIMER_RESTART(tcp, intvl)
421  *
422  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
423  * after 'time' ticks passed. The function called by timeout() must adhere to
424  * the same restrictions as a driver soft interrupt handler - it must not sleep
425  * or call other functions that might sleep. The value returned is the opaque
426  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
427  * cancel the request. The call to tcp_timeout() may fail in which case it
428  * returns zero. This is different from the timeout(9F) function which never
429  * fails.
430  *
431  * The call-back function 'func' always receives 'connp' as its single
432  * argument. It is always executed in the squeue corresponding to the tcp
433  * structure. The tcp structure is guaranteed to be present at the time the
434  * call-back is called.
435  *
436  * NOTE: The call-back function 'func' is never called if tcp is in
437  * 	the TCPS_CLOSED state.
438  *
439  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
440  * request. locks acquired by the call-back routine should not be held across
441  * the call to tcp_timeout_cancel() or a deadlock may result.
442  *
443  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
444  * Otherwise, it returns an integer value greater than or equal to 0. In
445  * particular, if the call-back function is already placed on the squeue, it can
446  * not be canceled.
447  *
448  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
449  * 	within squeue context corresponding to the tcp instance. Since the
450  *	call-back is also called via the same squeue, there are no race
451  *	conditions described in untimeout(9F) manual page since all calls are
452  *	strictly serialized.
453  *
454  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
455  *	stored in tcp_timer_tid and starts a new one using
456  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
457  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
458  *	field.
459  *
460  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
461  *	call-back may still be called, so it is possible tcp_timer() will be
462  *	called several times. This should not be a problem since tcp_timer()
463  *	should always check the tcp instance state.
464  *
465  *
466  * IMPLEMENTATION:
467  *
468  * TCP timers are implemented using three-stage process. The call to
469  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
470  * when the timer expires. The tcp_timer_callback() arranges the call of the
471  * tcp_timer_handler() function via squeue corresponding to the tcp
472  * instance. The tcp_timer_handler() calls actual requested timeout call-back
473  * and passes tcp instance as an argument to it. Information is passed between
474  * stages using the tcp_timer_t structure which contains the connp pointer, the
475  * tcp call-back to call and the timeout id returned by the timeout(9F).
476  *
477  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
478  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
479  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
480  * returns the pointer to this mblk.
481  *
482  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
483  * looks like a normal mblk without actual dblk attached to it.
484  *
485  * To optimize performance each tcp instance holds a small cache of timer
486  * mblocks. In the current implementation it caches up to two timer mblocks per
487  * tcp instance. The cache is preserved over tcp frees and is only freed when
488  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
489  * timer processing happens on a corresponding squeue, the cache manipulation
490  * does not require any locks. Experiments show that majority of timer mblocks
491  * allocations are satisfied from the tcp cache and do not involve kmem calls.
492  *
493  * The tcp_timeout() places a refhold on the connp instance which guarantees
494  * that it will be present at the time the call-back function fires. The
495  * tcp_timer_handler() drops the reference after calling the call-back, so the
496  * call-back function does not need to manipulate the references explicitly.
497  */
498 
499 typedef struct tcp_timer_s {
500 	conn_t	*connp;
501 	void 	(*tcpt_proc)(void *);
502 	timeout_id_t   tcpt_tid;
503 } tcp_timer_t;
504 
505 static kmem_cache_t *tcp_timercache;
506 kmem_cache_t	*tcp_sack_info_cache;
507 kmem_cache_t	*tcp_iphc_cache;
508 
509 /*
510  * For scalability, we must not run a timer for every TCP connection
511  * in TIME_WAIT state.  To see why, consider (for time wait interval of
512  * 4 minutes):
513  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
514  *
515  * This list is ordered by time, so you need only delete from the head
516  * until you get to entries which aren't old enough to delete yet.
517  * The list consists of only the detached TIME_WAIT connections.
518  *
519  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
520  * becomes detached TIME_WAIT (either by changing the state and already
521  * being detached or the other way around). This means that the TIME_WAIT
522  * state can be extended (up to doubled) if the connection doesn't become
523  * detached for a long time.
524  *
525  * The list manipulations (including tcp_time_wait_next/prev)
526  * are protected by the tcp_time_wait_lock. The content of the
527  * detached TIME_WAIT connections is protected by the normal perimeters.
528  *
529  * This list is per squeue and squeues are shared across the tcp_stack_t's.
530  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
531  * and conn_netstack.
532  * The tcp_t's that are added to tcp_free_list are disassociated and
533  * have NULL tcp_tcps and conn_netstack pointers.
534  */
535 typedef struct tcp_squeue_priv_s {
536 	kmutex_t	tcp_time_wait_lock;
537 	timeout_id_t	tcp_time_wait_tid;
538 	tcp_t		*tcp_time_wait_head;
539 	tcp_t		*tcp_time_wait_tail;
540 	tcp_t		*tcp_free_list;
541 	uint_t		tcp_free_list_cnt;
542 } tcp_squeue_priv_t;
543 
544 /*
545  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
546  * Running it every 5 seconds seems to give the best results.
547  */
548 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
549 
550 /*
551  * To prevent memory hog, limit the number of entries in tcp_free_list
552  * to 1% of available memory / number of cpus
553  */
554 uint_t tcp_free_list_max_cnt = 0;
555 
556 #define	TCP_XMIT_LOWATER	4096
557 #define	TCP_XMIT_HIWATER	49152
558 #define	TCP_RECV_LOWATER	2048
559 #define	TCP_RECV_HIWATER	49152
560 
561 /*
562  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
563  */
564 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
565 
566 #define	TIDUSZ	4096	/* transport interface data unit size */
567 
568 /*
569  * Bind hash list size and has function.  It has to be a power of 2 for
570  * hashing.
571  */
572 #define	TCP_BIND_FANOUT_SIZE	512
573 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
574 /*
575  * Size of listen and acceptor hash list.  It has to be a power of 2 for
576  * hashing.
577  */
578 #define	TCP_FANOUT_SIZE		256
579 
580 #ifdef	_ILP32
581 #define	TCP_ACCEPTOR_HASH(accid)					\
582 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
583 #else
584 #define	TCP_ACCEPTOR_HASH(accid)					\
585 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
586 #endif	/* _ILP32 */
587 
588 #define	IP_ADDR_CACHE_SIZE	2048
589 #define	IP_ADDR_CACHE_HASH(faddr)					\
590 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
591 
592 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
593 #define	TCP_HSP_HASH_SIZE 256
594 
595 #define	TCP_HSP_HASH(addr)					\
596 	(((addr>>24) ^ (addr >>16) ^			\
597 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
598 
599 /*
600  * TCP options struct returned from tcp_parse_options.
601  */
602 typedef struct tcp_opt_s {
603 	uint32_t	tcp_opt_mss;
604 	uint32_t	tcp_opt_wscale;
605 	uint32_t	tcp_opt_ts_val;
606 	uint32_t	tcp_opt_ts_ecr;
607 	tcp_t		*tcp;
608 } tcp_opt_t;
609 
610 /*
611  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
612  */
613 
614 #ifdef _BIG_ENDIAN
615 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
616 	(TCPOPT_TSTAMP << 8) | 10)
617 #else
618 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
619 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
620 #endif
621 
622 /*
623  * Flags returned from tcp_parse_options.
624  */
625 #define	TCP_OPT_MSS_PRESENT	1
626 #define	TCP_OPT_WSCALE_PRESENT	2
627 #define	TCP_OPT_TSTAMP_PRESENT	4
628 #define	TCP_OPT_SACK_OK_PRESENT	8
629 #define	TCP_OPT_SACK_PRESENT	16
630 
631 /* TCP option length */
632 #define	TCPOPT_NOP_LEN		1
633 #define	TCPOPT_MAXSEG_LEN	4
634 #define	TCPOPT_WS_LEN		3
635 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
636 #define	TCPOPT_TSTAMP_LEN	10
637 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
638 #define	TCPOPT_SACK_OK_LEN	2
639 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
640 #define	TCPOPT_REAL_SACK_LEN	4
641 #define	TCPOPT_MAX_SACK_LEN	36
642 #define	TCPOPT_HEADER_LEN	2
643 
644 /* TCP cwnd burst factor. */
645 #define	TCP_CWND_INFINITE	65535
646 #define	TCP_CWND_SS		3
647 #define	TCP_CWND_NORMAL		5
648 
649 /* Maximum TCP initial cwin (start/restart). */
650 #define	TCP_MAX_INIT_CWND	8
651 
652 /*
653  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
654  * either tcp_slow_start_initial or tcp_slow_start_after idle
655  * depending on the caller.  If the upper layer has not used the
656  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
657  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
658  * If the upper layer has changed set the tcp_init_cwnd, just use
659  * it to calculate the tcp_cwnd.
660  */
661 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
662 {									\
663 	if ((tcp)->tcp_init_cwnd == 0) {				\
664 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
665 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
666 	} else {							\
667 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
668 	}								\
669 	tcp->tcp_cwnd_cnt = 0;						\
670 }
671 
672 /* TCP Timer control structure */
673 typedef struct tcpt_s {
674 	pfv_t	tcpt_pfv;	/* The routine we are to call */
675 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
676 } tcpt_t;
677 
678 /* Host Specific Parameter structure */
679 typedef struct tcp_hsp {
680 	struct tcp_hsp	*tcp_hsp_next;
681 	in6_addr_t	tcp_hsp_addr_v6;
682 	in6_addr_t	tcp_hsp_subnet_v6;
683 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
684 	int32_t		tcp_hsp_sendspace;
685 	int32_t		tcp_hsp_recvspace;
686 	int32_t		tcp_hsp_tstamp;
687 } tcp_hsp_t;
688 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
689 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
690 
691 /*
692  * Functions called directly via squeue having a prototype of edesc_t.
693  */
694 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
695 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
696 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
697 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
698 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
699 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
700 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
701 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
702 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
703 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
704 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
705 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
706 
707 
708 /* Prototype for TCP functions */
709 static void	tcp_random_init(void);
710 int		tcp_random(void);
711 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
712 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
713 		    tcp_t *eager);
714 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
715 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
716     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
717     boolean_t user_specified);
718 static void	tcp_closei_local(tcp_t *tcp);
719 static void	tcp_close_detached(tcp_t *tcp);
720 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
721 			mblk_t *idmp, mblk_t **defermp);
722 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
723 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
724 		    in_port_t dstport, uint_t srcid);
725 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
726 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
727 		    uint32_t scope_id);
728 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
729 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
730 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
731 static char	*tcp_display(tcp_t *tcp, char *, char);
732 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
733 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
734 static void	tcp_eager_unlink(tcp_t *tcp);
735 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
736 		    int unixerr);
737 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
738 		    int tlierr, int unixerr);
739 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
740 		    cred_t *cr);
741 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
742 		    char *value, caddr_t cp, cred_t *cr);
743 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
744 		    char *value, caddr_t cp, cred_t *cr);
745 static int	tcp_tpistate(tcp_t *tcp);
746 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
747     int caller_holds_lock);
748 static void	tcp_bind_hash_remove(tcp_t *tcp);
749 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
750 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
751 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
752 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
753 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
754 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
755 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
756 void		tcp_g_q_setup(tcp_stack_t *);
757 void		tcp_g_q_create(tcp_stack_t *);
758 void		tcp_g_q_destroy(tcp_stack_t *);
759 static int	tcp_header_init_ipv4(tcp_t *tcp);
760 static int	tcp_header_init_ipv6(tcp_t *tcp);
761 int		tcp_init(tcp_t *tcp, queue_t *q);
762 static int	tcp_init_values(tcp_t *tcp);
763 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
764 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
765 		    t_scalar_t addr_length);
766 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
767 static void	tcp_ip_notify(tcp_t *tcp);
768 static mblk_t	*tcp_ire_mp(mblk_t *mp);
769 static void	tcp_iss_init(tcp_t *tcp);
770 static void	tcp_keepalive_killer(void *arg);
771 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
772 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
773 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
774 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
775 static boolean_t tcp_allow_connopt_set(int level, int name);
776 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
777 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
778 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
779 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
780 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
781 		    mblk_t *mblk);
782 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
783 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
784 		    uchar_t *ptr, uint_t len);
785 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
786 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
787     tcp_stack_t *);
788 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
789 		    caddr_t cp, cred_t *cr);
790 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
791 		    caddr_t cp, cred_t *cr);
792 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
793 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
794 		    caddr_t cp, cred_t *cr);
795 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
796 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
797 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
798 static void	tcp_reinit(tcp_t *tcp);
799 static void	tcp_reinit_values(tcp_t *tcp);
800 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
801 		    tcp_t *thisstream, cred_t *cr);
802 
803 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
804 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
805 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
806 static void	tcp_ss_rexmit(tcp_t *tcp);
807 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
808 static void	tcp_process_options(tcp_t *, tcph_t *);
809 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
810 static void	tcp_rsrv(queue_t *q);
811 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
812 static int	tcp_snmp_state(tcp_t *tcp);
813 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
814 		    cred_t *cr);
815 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
816 		    cred_t *cr);
817 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
818 		    cred_t *cr);
819 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
820 		    cred_t *cr);
821 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
822 		    cred_t *cr);
823 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
824 		    caddr_t cp, cred_t *cr);
825 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
826 		    caddr_t cp, cred_t *cr);
827 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
828 		    cred_t *cr);
829 static void	tcp_timer(void *arg);
830 static void	tcp_timer_callback(void *);
831 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
832     boolean_t random);
833 static in_port_t tcp_get_next_priv_port(const tcp_t *);
834 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
835 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
836 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
837 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
838 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
839 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
840 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
841 		    const int num_sack_blk, int *usable, uint_t *snxt,
842 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
843 		    const int mdt_thres);
844 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
845 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
846 		    const int num_sack_blk, int *usable, uint_t *snxt,
847 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
848 		    const int mdt_thres);
849 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
850 		    int num_sack_blk);
851 static void	tcp_wsrv(queue_t *q);
852 static int	tcp_xmit_end(tcp_t *tcp);
853 static void	tcp_ack_timer(void *arg);
854 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
855 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
856 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
857 		    zoneid_t zoneid, tcp_stack_t *);
858 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
859 		    uint32_t ack, int ctl);
860 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
861 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
862 static int	setmaxps(queue_t *q, int maxpsz);
863 static void	tcp_set_rto(tcp_t *, time_t);
864 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
865 		    boolean_t, boolean_t);
866 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
867 		    boolean_t ipsec_mctl);
868 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
869 		    char *opt, int optlen);
870 static int	tcp_build_hdrs(queue_t *, tcp_t *);
871 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
872 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
873 		    tcph_t *tcph);
874 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
875 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
876 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
877 boolean_t	tcp_reserved_port_check(in_port_t, tcp_stack_t *);
878 static tcp_t	*tcp_alloc_temp_tcp(in_port_t, tcp_stack_t *);
879 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
880 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
881 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
882 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
883 		    const boolean_t, const uint32_t, const uint32_t,
884 		    const uint32_t, const uint32_t, tcp_stack_t *);
885 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
886 		    const uint_t, const uint_t, boolean_t *);
887 static mblk_t	*tcp_lso_info_mp(mblk_t *);
888 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
889 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
890 extern mblk_t	*tcp_timermp_alloc(int);
891 extern void	tcp_timermp_free(tcp_t *);
892 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
893 static void	tcp_stop_lingering(tcp_t *tcp);
894 static void	tcp_close_linger_timeout(void *arg);
895 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
896 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
897 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
898 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
899 static void	tcp_g_kstat_fini(kstat_t *);
900 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
901 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
902 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
903 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
904 static int	tcp_kstat_update(kstat_t *kp, int rw);
905 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
906 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
907 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
908 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
909 			tcph_t *tcph, mblk_t *idmp);
910 static squeue_func_t tcp_squeue_switch(int);
911 
912 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
913 static int	tcp_close(queue_t *, int);
914 static int	tcpclose_accept(queue_t *);
915 static int	tcp_modclose(queue_t *);
916 static void	tcp_wput_mod(queue_t *, mblk_t *);
917 
918 static void	tcp_squeue_add(squeue_t *);
919 static boolean_t tcp_zcopy_check(tcp_t *);
920 static void	tcp_zcopy_notify(tcp_t *);
921 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
922 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
923 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
924 
925 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
926 
927 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
928 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
929 
930 /*
931  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
932  *
933  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
934  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
935  * (defined in tcp.h) needs to be filled in and passed into the kernel
936  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
937  * structure contains the four-tuple of a TCP connection and a range of TCP
938  * states (specified by ac_start and ac_end). The use of wildcard addresses
939  * and ports is allowed. Connections with a matching four tuple and a state
940  * within the specified range will be aborted. The valid states for the
941  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
942  * inclusive.
943  *
944  * An application which has its connection aborted by this ioctl will receive
945  * an error that is dependent on the connection state at the time of the abort.
946  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
947  * though a RST packet has been received.  If the connection state is equal to
948  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
949  * and all resources associated with the connection will be freed.
950  */
951 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
952 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
953 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
954 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
955 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
956 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
957     boolean_t, tcp_stack_t *);
958 
959 static struct module_info tcp_rinfo =  {
960 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
961 };
962 
963 static struct module_info tcp_winfo =  {
964 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
965 };
966 
967 /*
968  * Entry points for TCP as a module. It only allows SNMP requests
969  * to pass through.
970  */
971 struct qinit tcp_mod_rinit = {
972 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
973 };
974 
975 struct qinit tcp_mod_winit = {
976 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
977 	&tcp_rinfo
978 };
979 
980 /*
981  * Entry points for TCP as a device. The normal case which supports
982  * the TCP functionality.
983  */
984 struct qinit tcp_rinit = {
985 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
986 };
987 
988 struct qinit tcp_winit = {
989 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
990 };
991 
992 /* Initial entry point for TCP in socket mode. */
993 struct qinit tcp_sock_winit = {
994 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
995 };
996 
997 /*
998  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
999  * an accept. Avoid allocating data structures since eager has already
1000  * been created.
1001  */
1002 struct qinit tcp_acceptor_rinit = {
1003 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1004 };
1005 
1006 struct qinit tcp_acceptor_winit = {
1007 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1008 };
1009 
1010 /*
1011  * Entry points for TCP loopback (read side only)
1012  */
1013 struct qinit tcp_loopback_rinit = {
1014 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1015 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1016 };
1017 
1018 struct streamtab tcpinfo = {
1019 	&tcp_rinit, &tcp_winit
1020 };
1021 
1022 /*
1023  * Have to ensure that tcp_g_q_close is not done by an
1024  * interrupt thread.
1025  */
1026 static taskq_t *tcp_taskq;
1027 
1028 /*
1029  * TCP has a private interface for other kernel modules to reserve a
1030  * port range for them to use.  Once reserved, TCP will not use any ports
1031  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1032  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1033  * has to be verified.
1034  *
1035  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1036  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1037  * range is [port a, port b] inclusive.  And each port range is between
1038  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1039  *
1040  * Note that the default anonymous port range starts from 32768.  There is
1041  * no port "collision" between that and the reserved port range.  If there
1042  * is port collision (because the default smallest anonymous port is lowered
1043  * or some apps specifically bind to ports in the reserved port range), the
1044  * system may not be able to reserve a port range even there are enough
1045  * unbound ports as a reserved port range contains consecutive ports .
1046  */
1047 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1048 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1049 #define	TCP_SMALLEST_RESERVED_PORT		10240
1050 #define	TCP_LARGEST_RESERVED_PORT		20480
1051 
1052 /* Structure to represent those reserved port ranges. */
1053 typedef struct tcp_rport_s {
1054 	in_port_t	lo_port;
1055 	in_port_t	hi_port;
1056 	tcp_t		**temp_tcp_array;
1057 } tcp_rport_t;
1058 
1059 /* Setable only in /etc/system. Move to ndd? */
1060 boolean_t tcp_icmp_source_quench = B_FALSE;
1061 
1062 /*
1063  * Following assumes TPI alignment requirements stay along 32 bit
1064  * boundaries
1065  */
1066 #define	ROUNDUP32(x) \
1067 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1068 
1069 /* Template for response to info request. */
1070 static struct T_info_ack tcp_g_t_info_ack = {
1071 	T_INFO_ACK,		/* PRIM_type */
1072 	0,			/* TSDU_size */
1073 	T_INFINITE,		/* ETSDU_size */
1074 	T_INVALID,		/* CDATA_size */
1075 	T_INVALID,		/* DDATA_size */
1076 	sizeof (sin_t),		/* ADDR_size */
1077 	0,			/* OPT_size - not initialized here */
1078 	TIDUSZ,			/* TIDU_size */
1079 	T_COTS_ORD,		/* SERV_type */
1080 	TCPS_IDLE,		/* CURRENT_state */
1081 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1082 };
1083 
1084 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1085 	T_INFO_ACK,		/* PRIM_type */
1086 	0,			/* TSDU_size */
1087 	T_INFINITE,		/* ETSDU_size */
1088 	T_INVALID,		/* CDATA_size */
1089 	T_INVALID,		/* DDATA_size */
1090 	sizeof (sin6_t),	/* ADDR_size */
1091 	0,			/* OPT_size - not initialized here */
1092 	TIDUSZ,		/* TIDU_size */
1093 	T_COTS_ORD,		/* SERV_type */
1094 	TCPS_IDLE,		/* CURRENT_state */
1095 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1096 };
1097 
1098 #define	MS	1L
1099 #define	SECONDS	(1000 * MS)
1100 #define	MINUTES	(60 * SECONDS)
1101 #define	HOURS	(60 * MINUTES)
1102 #define	DAYS	(24 * HOURS)
1103 
1104 #define	PARAM_MAX (~(uint32_t)0)
1105 
1106 /* Max size IP datagram is 64k - 1 */
1107 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1108 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1109 /* Max of the above */
1110 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1111 
1112 /* Largest TCP port number */
1113 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1114 
1115 /*
1116  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1117  * layer header.  It has to be a multiple of 4.
1118  */
1119 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1120 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1121 
1122 /*
1123  * All of these are alterable, within the min/max values given, at run time.
1124  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1125  * per the TCP spec.
1126  */
1127 /* BEGIN CSTYLED */
1128 static tcpparam_t	lcl_tcp_param_arr[] = {
1129  /*min		max		value		name */
1130  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1131  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1132  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1133  { 1,		1024,		1,		"tcp_conn_req_min" },
1134  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1135  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1136  { 0,		10,		0,		"tcp_debug" },
1137  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1138  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1139  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1140  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1141  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1142  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1143  { 1,		255,		64,		"tcp_ipv4_ttl"},
1144  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1145  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1146  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1147  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1148  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1149  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1150  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1151  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1152  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1153  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1154  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1155  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1156  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1157  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1158  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1159  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1160  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1161  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1162  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1163  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1164  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1165  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1166  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1167  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1168 /*
1169  * Question:  What default value should I set for tcp_strong_iss?
1170  */
1171  { 0,		2,		1,		"tcp_strong_iss"},
1172  { 0,		65536,		20,		"tcp_rtt_updates"},
1173  { 0,		1,		1,		"tcp_wscale_always"},
1174  { 0,		1,		0,		"tcp_tstamp_always"},
1175  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1176  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1177  { 0,		16,		2,		"tcp_deferred_acks_max"},
1178  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1179  { 1,		4,		4,		"tcp_slow_start_initial"},
1180  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1181  { 0,		2,		2,		"tcp_sack_permitted"},
1182  { 0,		1,		0,		"tcp_trace"},
1183  { 0,		1,		1,		"tcp_compression_enabled"},
1184  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1185  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1186  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1187  { 0,		1,		0,		"tcp_rev_src_routes"},
1188  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1189  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1190  { 0,		16,		8,		"tcp_local_dacks_max"},
1191  { 0,		2,		1,		"tcp_ecn_permitted"},
1192  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1193  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1194  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1195  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1196  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1197 };
1198 /* END CSTYLED */
1199 
1200 /*
1201  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1202  * each header fragment in the header buffer.  Each parameter value has
1203  * to be a multiple of 4 (32-bit aligned).
1204  */
1205 static tcpparam_t lcl_tcp_mdt_head_param =
1206 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1207 static tcpparam_t lcl_tcp_mdt_tail_param =
1208 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1209 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1210 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1211 
1212 /*
1213  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1214  * the maximum number of payload buffers associated per Multidata.
1215  */
1216 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1217 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1218 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1219 
1220 /* Round up the value to the nearest mss. */
1221 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1222 
1223 /*
1224  * Set ECN capable transport (ECT) code point in IP header.
1225  *
1226  * Note that there are 2 ECT code points '01' and '10', which are called
1227  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1228  * point ECT(0) for TCP as described in RFC 2481.
1229  */
1230 #define	SET_ECT(tcp, iph) \
1231 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1232 		/* We need to clear the code point first. */ \
1233 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1234 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1235 	} else { \
1236 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1237 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1238 	}
1239 
1240 /*
1241  * The format argument to pass to tcp_display().
1242  * DISP_PORT_ONLY means that the returned string has only port info.
1243  * DISP_ADDR_AND_PORT means that the returned string also contains the
1244  * remote and local IP address.
1245  */
1246 #define	DISP_PORT_ONLY		1
1247 #define	DISP_ADDR_AND_PORT	2
1248 
1249 #define	NDD_TOO_QUICK_MSG \
1250 	"ndd get info rate too high for non-privileged users, try again " \
1251 	"later.\n"
1252 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1253 
1254 #define	IS_VMLOANED_MBLK(mp) \
1255 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1256 
1257 
1258 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1259 boolean_t tcp_mdt_chain = B_TRUE;
1260 
1261 /*
1262  * MDT threshold in the form of effective send MSS multiplier; we take
1263  * the MDT path if the amount of unsent data exceeds the threshold value
1264  * (default threshold is 1*SMSS).
1265  */
1266 uint_t tcp_mdt_smss_threshold = 1;
1267 
1268 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1269 
1270 /*
1271  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1272  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1273  * determined dynamically during tcp_adapt_ire(), which is the default.
1274  */
1275 boolean_t tcp_static_maxpsz = B_FALSE;
1276 
1277 /* Setable in /etc/system */
1278 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1279 uint32_t tcp_random_anon_port = 1;
1280 
1281 /*
1282  * To reach to an eager in Q0 which can be dropped due to an incoming
1283  * new SYN request when Q0 is full, a new doubly linked list is
1284  * introduced. This list allows to select an eager from Q0 in O(1) time.
1285  * This is needed to avoid spending too much time walking through the
1286  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1287  * this new list has to be a member of Q0.
1288  * This list is headed by listener's tcp_t. When the list is empty,
1289  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1290  * of listener's tcp_t point to listener's tcp_t itself.
1291  *
1292  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1293  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1294  * These macros do not affect the eager's membership to Q0.
1295  */
1296 
1297 
1298 #define	MAKE_DROPPABLE(listener, eager)					\
1299 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1300 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1301 		    = (eager);						\
1302 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1303 		(eager)->tcp_eager_next_drop_q0 =			\
1304 		    (listener)->tcp_eager_next_drop_q0;			\
1305 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1306 	}
1307 
1308 #define	MAKE_UNDROPPABLE(eager)						\
1309 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1310 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1311 		    = (eager)->tcp_eager_prev_drop_q0;			\
1312 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1313 		    = (eager)->tcp_eager_next_drop_q0;			\
1314 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1315 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1316 	}
1317 
1318 /*
1319  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1320  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1321  * data, TCP will not respond with an ACK.  RFC 793 requires that
1322  * TCP responds with an ACK for such a bogus ACK.  By not following
1323  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1324  * an attacker successfully spoofs an acceptable segment to our
1325  * peer; or when our peer is "confused."
1326  */
1327 uint32_t tcp_drop_ack_unsent_cnt = 10;
1328 
1329 /*
1330  * Hook functions to enable cluster networking
1331  * On non-clustered systems these vectors must always be NULL.
1332  */
1333 
1334 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1335 			    uint8_t *laddrp, in_port_t lport) = NULL;
1336 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1337 			    uint8_t *laddrp, in_port_t lport) = NULL;
1338 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1339 			    uint8_t *laddrp, in_port_t lport,
1340 			    uint8_t *faddrp, in_port_t fport) = NULL;
1341 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1342 			    uint8_t *laddrp, in_port_t lport,
1343 			    uint8_t *faddrp, in_port_t fport) = NULL;
1344 
1345 /*
1346  * The following are defined in ip.c
1347  */
1348 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1349 				uint8_t *laddrp);
1350 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1351 				uint8_t *laddrp, uint8_t *faddrp);
1352 
1353 #define	CL_INET_CONNECT(tcp)		{			\
1354 	if (cl_inet_connect != NULL) {				\
1355 		/*						\
1356 		 * Running in cluster mode - register active connection	\
1357 		 * information						\
1358 		 */							\
1359 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1360 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1361 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1362 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1363 				    (in_port_t)(tcp)->tcp_lport,	\
1364 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1365 				    (in_port_t)(tcp)->tcp_fport);	\
1366 			}						\
1367 		} else {						\
1368 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1369 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1370 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1371 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1372 				    (in_port_t)(tcp)->tcp_lport,	\
1373 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1374 				    (in_port_t)(tcp)->tcp_fport);	\
1375 			}						\
1376 		}							\
1377 	}								\
1378 }
1379 
1380 #define	CL_INET_DISCONNECT(tcp)	{				\
1381 	if (cl_inet_disconnect != NULL) {				\
1382 		/*							\
1383 		 * Running in cluster mode - deregister active		\
1384 		 * connection information				\
1385 		 */							\
1386 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1387 			if ((tcp)->tcp_ip_src != 0) {			\
1388 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1389 				    AF_INET,				\
1390 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1391 				    (in_port_t)(tcp)->tcp_lport,	\
1392 				    (uint8_t *)				\
1393 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1394 				    (in_port_t)(tcp)->tcp_fport);	\
1395 			}						\
1396 		} else {						\
1397 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1398 			    &(tcp)->tcp_ip_src_v6)) {			\
1399 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1400 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1401 				    (in_port_t)(tcp)->tcp_lport,	\
1402 				    (uint8_t *)				\
1403 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1404 				    (in_port_t)(tcp)->tcp_fport);	\
1405 			}						\
1406 		}							\
1407 	}								\
1408 }
1409 
1410 /*
1411  * Cluster networking hook for traversing current connection list.
1412  * This routine is used to extract the current list of live connections
1413  * which must continue to to be dispatched to this node.
1414  */
1415 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1416 
1417 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1418     void *arg, tcp_stack_t *tcps);
1419 
1420 /*
1421  * Figure out the value of window scale opton.  Note that the rwnd is
1422  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1423  * We cannot find the scale value and then do a round up of tcp_rwnd
1424  * because the scale value may not be correct after that.
1425  *
1426  * Set the compiler flag to make this function inline.
1427  */
1428 static void
1429 tcp_set_ws_value(tcp_t *tcp)
1430 {
1431 	int i;
1432 	uint32_t rwnd = tcp->tcp_rwnd;
1433 
1434 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1435 	    i++, rwnd >>= 1)
1436 		;
1437 	tcp->tcp_rcv_ws = i;
1438 }
1439 
1440 /*
1441  * Remove a connection from the list of detached TIME_WAIT connections.
1442  * It returns B_FALSE if it can't remove the connection from the list
1443  * as the connection has already been removed from the list due to an
1444  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1445  */
1446 static boolean_t
1447 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1448 {
1449 	boolean_t	locked = B_FALSE;
1450 
1451 	if (tcp_time_wait == NULL) {
1452 		tcp_time_wait = *((tcp_squeue_priv_t **)
1453 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1454 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1455 		locked = B_TRUE;
1456 	} else {
1457 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1458 	}
1459 
1460 	if (tcp->tcp_time_wait_expire == 0) {
1461 		ASSERT(tcp->tcp_time_wait_next == NULL);
1462 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1463 		if (locked)
1464 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1465 		return (B_FALSE);
1466 	}
1467 	ASSERT(TCP_IS_DETACHED(tcp));
1468 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1469 
1470 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1471 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1472 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1473 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1474 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1475 			    NULL;
1476 		} else {
1477 			tcp_time_wait->tcp_time_wait_tail = NULL;
1478 		}
1479 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1480 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1481 		ASSERT(tcp->tcp_time_wait_next == NULL);
1482 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1483 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1484 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1485 	} else {
1486 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1487 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1488 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1489 		    tcp->tcp_time_wait_next;
1490 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1491 		    tcp->tcp_time_wait_prev;
1492 	}
1493 	tcp->tcp_time_wait_next = NULL;
1494 	tcp->tcp_time_wait_prev = NULL;
1495 	tcp->tcp_time_wait_expire = 0;
1496 
1497 	if (locked)
1498 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1499 	return (B_TRUE);
1500 }
1501 
1502 /*
1503  * Add a connection to the list of detached TIME_WAIT connections
1504  * and set its time to expire.
1505  */
1506 static void
1507 tcp_time_wait_append(tcp_t *tcp)
1508 {
1509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1510 	tcp_squeue_priv_t *tcp_time_wait =
1511 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1512 		SQPRIVATE_TCP));
1513 
1514 	tcp_timers_stop(tcp);
1515 
1516 	/* Freed above */
1517 	ASSERT(tcp->tcp_timer_tid == 0);
1518 	ASSERT(tcp->tcp_ack_tid == 0);
1519 
1520 	/* must have happened at the time of detaching the tcp */
1521 	ASSERT(tcp->tcp_ptpahn == NULL);
1522 	ASSERT(tcp->tcp_flow_stopped == 0);
1523 	ASSERT(tcp->tcp_time_wait_next == NULL);
1524 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1525 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1526 	ASSERT(tcp->tcp_listener == NULL);
1527 
1528 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1529 	/*
1530 	 * The value computed below in tcp->tcp_time_wait_expire may
1531 	 * appear negative or wrap around. That is ok since our
1532 	 * interest is only in the difference between the current lbolt
1533 	 * value and tcp->tcp_time_wait_expire. But the value should not
1534 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1535 	 * The corresponding comparison in tcp_time_wait_collector() uses
1536 	 * modular arithmetic.
1537 	 */
1538 	tcp->tcp_time_wait_expire +=
1539 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1540 	if (tcp->tcp_time_wait_expire == 0)
1541 		tcp->tcp_time_wait_expire = 1;
1542 
1543 	ASSERT(TCP_IS_DETACHED(tcp));
1544 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1545 	ASSERT(tcp->tcp_time_wait_next == NULL);
1546 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1547 	TCP_DBGSTAT(tcps, tcp_time_wait);
1548 
1549 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1550 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1551 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1552 		tcp_time_wait->tcp_time_wait_head = tcp;
1553 	} else {
1554 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1555 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1556 		    TCPS_TIME_WAIT);
1557 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1558 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1559 	}
1560 	tcp_time_wait->tcp_time_wait_tail = tcp;
1561 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1562 }
1563 
1564 /* ARGSUSED */
1565 void
1566 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1567 {
1568 	conn_t	*connp = (conn_t *)arg;
1569 	tcp_t	*tcp = connp->conn_tcp;
1570 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1571 
1572 	ASSERT(tcp != NULL);
1573 	if (tcp->tcp_state == TCPS_CLOSED) {
1574 		return;
1575 	}
1576 
1577 	ASSERT((tcp->tcp_family == AF_INET &&
1578 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1579 	    (tcp->tcp_family == AF_INET6 &&
1580 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1581 	    tcp->tcp_ipversion == IPV6_VERSION)));
1582 	ASSERT(!tcp->tcp_listener);
1583 
1584 	TCP_STAT(tcps, tcp_time_wait_reap);
1585 	ASSERT(TCP_IS_DETACHED(tcp));
1586 
1587 	/*
1588 	 * Because they have no upstream client to rebind or tcp_close()
1589 	 * them later, we axe the connection here and now.
1590 	 */
1591 	tcp_close_detached(tcp);
1592 }
1593 
1594 /*
1595  * Remove cached/latched IPsec references.
1596  */
1597 void
1598 tcp_ipsec_cleanup(tcp_t *tcp)
1599 {
1600 	conn_t		*connp = tcp->tcp_connp;
1601 
1602 	if (connp->conn_flags & IPCL_TCPCONN) {
1603 		if (connp->conn_latch != NULL) {
1604 			IPLATCH_REFRELE(connp->conn_latch,
1605 			    connp->conn_netstack);
1606 			connp->conn_latch = NULL;
1607 		}
1608 		if (connp->conn_policy != NULL) {
1609 			IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1610 			connp->conn_policy = NULL;
1611 		}
1612 	}
1613 }
1614 
1615 /*
1616  * Cleaup before placing on free list.
1617  * Disassociate from the netstack/tcp_stack_t since the freelist
1618  * is per squeue and not per netstack.
1619  */
1620 void
1621 tcp_cleanup(tcp_t *tcp)
1622 {
1623 	mblk_t		*mp;
1624 	char		*tcp_iphc;
1625 	int		tcp_iphc_len;
1626 	int		tcp_hdr_grown;
1627 	tcp_sack_info_t	*tcp_sack_info;
1628 	conn_t		*connp = tcp->tcp_connp;
1629 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1630 	netstack_t	*ns = tcps->tcps_netstack;
1631 
1632 	tcp_bind_hash_remove(tcp);
1633 
1634 	/* Cleanup that which needs the netstack first */
1635 	tcp_ipsec_cleanup(tcp);
1636 
1637 	tcp_free(tcp);
1638 
1639 	/* Release any SSL context */
1640 	if (tcp->tcp_kssl_ent != NULL) {
1641 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1642 		tcp->tcp_kssl_ent = NULL;
1643 	}
1644 
1645 	if (tcp->tcp_kssl_ctx != NULL) {
1646 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1647 		tcp->tcp_kssl_ctx = NULL;
1648 	}
1649 	tcp->tcp_kssl_pending = B_FALSE;
1650 
1651 	conn_delete_ire(connp, NULL);
1652 
1653 	/*
1654 	 * Since we will bzero the entire structure, we need to
1655 	 * remove it and reinsert it in global hash list. We
1656 	 * know the walkers can't get to this conn because we
1657 	 * had set CONDEMNED flag earlier and checked reference
1658 	 * under conn_lock so walker won't pick it and when we
1659 	 * go the ipcl_globalhash_remove() below, no walker
1660 	 * can get to it.
1661 	 */
1662 	ipcl_globalhash_remove(connp);
1663 
1664 	/*
1665 	 * Now it is safe to decrement the reference counts.
1666 	 * This might be the last reference on the netstack and TCPS
1667 	 * in which case it will cause the tcp_g_q_close and
1668 	 * the freeing of the IP Instance.
1669 	 */
1670 	connp->conn_netstack = NULL;
1671 	netstack_rele(ns);
1672 	ASSERT(tcps != NULL);
1673 	tcp->tcp_tcps = NULL;
1674 	TCPS_REFRELE(tcps);
1675 
1676 	/* Save some state */
1677 	mp = tcp->tcp_timercache;
1678 
1679 	tcp_sack_info = tcp->tcp_sack_info;
1680 	tcp_iphc = tcp->tcp_iphc;
1681 	tcp_iphc_len = tcp->tcp_iphc_len;
1682 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1683 
1684 	if (connp->conn_cred != NULL)
1685 		crfree(connp->conn_cred);
1686 	if (connp->conn_peercred != NULL)
1687 		crfree(connp->conn_peercred);
1688 	bzero(connp, sizeof (conn_t));
1689 	bzero(tcp, sizeof (tcp_t));
1690 
1691 	/* restore the state */
1692 	tcp->tcp_timercache = mp;
1693 
1694 	tcp->tcp_sack_info = tcp_sack_info;
1695 	tcp->tcp_iphc = tcp_iphc;
1696 	tcp->tcp_iphc_len = tcp_iphc_len;
1697 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1698 
1699 
1700 	tcp->tcp_connp = connp;
1701 
1702 	connp->conn_tcp = tcp;
1703 	connp->conn_flags = IPCL_TCPCONN;
1704 	connp->conn_state_flags = CONN_INCIPIENT;
1705 	connp->conn_ulp = IPPROTO_TCP;
1706 	connp->conn_ref = 1;
1707 }
1708 
1709 /*
1710  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1711  * is done forwards from the head.
1712  * This walks all stack instances since
1713  * tcp_time_wait remains global across all stacks.
1714  */
1715 /* ARGSUSED */
1716 void
1717 tcp_time_wait_collector(void *arg)
1718 {
1719 	tcp_t *tcp;
1720 	clock_t now;
1721 	mblk_t *mp;
1722 	conn_t *connp;
1723 	kmutex_t *lock;
1724 	boolean_t removed;
1725 
1726 	squeue_t *sqp = (squeue_t *)arg;
1727 	tcp_squeue_priv_t *tcp_time_wait =
1728 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1729 
1730 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1731 	tcp_time_wait->tcp_time_wait_tid = 0;
1732 
1733 	if (tcp_time_wait->tcp_free_list != NULL &&
1734 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1735 		TCP_G_STAT(tcp_freelist_cleanup);
1736 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1737 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1738 			tcp->tcp_time_wait_next = NULL;
1739 			tcp_time_wait->tcp_free_list_cnt--;
1740 			ASSERT(tcp->tcp_tcps == NULL);
1741 			CONN_DEC_REF(tcp->tcp_connp);
1742 		}
1743 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1744 	}
1745 
1746 	/*
1747 	 * In order to reap time waits reliably, we should use a
1748 	 * source of time that is not adjustable by the user -- hence
1749 	 * the call to ddi_get_lbolt().
1750 	 */
1751 	now = ddi_get_lbolt();
1752 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1753 		/*
1754 		 * Compare times using modular arithmetic, since
1755 		 * lbolt can wrapover.
1756 		 */
1757 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1758 			break;
1759 		}
1760 
1761 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1762 		ASSERT(removed);
1763 
1764 		connp = tcp->tcp_connp;
1765 		ASSERT(connp->conn_fanout != NULL);
1766 		lock = &connp->conn_fanout->connf_lock;
1767 		/*
1768 		 * This is essentially a TW reclaim fast path optimization for
1769 		 * performance where the timewait collector checks under the
1770 		 * fanout lock (so that no one else can get access to the
1771 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1772 		 * the classifier hash list. If ref count is indeed 2, we can
1773 		 * just remove the conn under the fanout lock and avoid
1774 		 * cleaning up the conn under the squeue, provided that
1775 		 * clustering callbacks are not enabled. If clustering is
1776 		 * enabled, we need to make the clustering callback before
1777 		 * setting the CONDEMNED flag and after dropping all locks and
1778 		 * so we forego this optimization and fall back to the slow
1779 		 * path. Also please see the comments in tcp_closei_local
1780 		 * regarding the refcnt logic.
1781 		 *
1782 		 * Since we are holding the tcp_time_wait_lock, its better
1783 		 * not to block on the fanout_lock because other connections
1784 		 * can't add themselves to time_wait list. So we do a
1785 		 * tryenter instead of mutex_enter.
1786 		 */
1787 		if (mutex_tryenter(lock)) {
1788 			mutex_enter(&connp->conn_lock);
1789 			if ((connp->conn_ref == 2) &&
1790 			    (cl_inet_disconnect == NULL)) {
1791 				ipcl_hash_remove_locked(connp,
1792 				    connp->conn_fanout);
1793 				/*
1794 				 * Set the CONDEMNED flag now itself so that
1795 				 * the refcnt cannot increase due to any
1796 				 * walker. But we have still not cleaned up
1797 				 * conn_ire_cache. This is still ok since
1798 				 * we are going to clean it up in tcp_cleanup
1799 				 * immediately and any interface unplumb
1800 				 * thread will wait till the ire is blown away
1801 				 */
1802 				connp->conn_state_flags |= CONN_CONDEMNED;
1803 				mutex_exit(lock);
1804 				mutex_exit(&connp->conn_lock);
1805 				if (tcp_time_wait->tcp_free_list_cnt <
1806 				    tcp_free_list_max_cnt) {
1807 					/* Add to head of tcp_free_list */
1808 					mutex_exit(
1809 					    &tcp_time_wait->tcp_time_wait_lock);
1810 					tcp_cleanup(tcp);
1811 					ASSERT(connp->conn_latch == NULL);
1812 					ASSERT(connp->conn_policy == NULL);
1813 					ASSERT(tcp->tcp_tcps == NULL);
1814 					ASSERT(connp->conn_netstack == NULL);
1815 
1816 					mutex_enter(
1817 					    &tcp_time_wait->tcp_time_wait_lock);
1818 					tcp->tcp_time_wait_next =
1819 					    tcp_time_wait->tcp_free_list;
1820 					tcp_time_wait->tcp_free_list = tcp;
1821 					tcp_time_wait->tcp_free_list_cnt++;
1822 					continue;
1823 				} else {
1824 					/* Do not add to tcp_free_list */
1825 					mutex_exit(
1826 					    &tcp_time_wait->tcp_time_wait_lock);
1827 					tcp_bind_hash_remove(tcp);
1828 					conn_delete_ire(tcp->tcp_connp, NULL);
1829 					tcp_ipsec_cleanup(tcp);
1830 					CONN_DEC_REF(tcp->tcp_connp);
1831 				}
1832 			} else {
1833 				CONN_INC_REF_LOCKED(connp);
1834 				mutex_exit(lock);
1835 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1836 				mutex_exit(&connp->conn_lock);
1837 				/*
1838 				 * We can reuse the closemp here since conn has
1839 				 * detached (otherwise we wouldn't even be in
1840 				 * time_wait list). tcp_closemp_used can safely
1841 				 * be changed without taking a lock as no other
1842 				 * thread can concurrently access it at this
1843 				 * point in the connection lifecycle.
1844 				 */
1845 
1846 				if (tcp->tcp_closemp.b_prev == NULL)
1847 					tcp->tcp_closemp_used = B_TRUE;
1848 				else
1849 					cmn_err(CE_PANIC,
1850 					    "tcp_timewait_collector: "
1851 					    "concurrent use of tcp_closemp: "
1852 					    "connp %p tcp %p\n", (void *)connp,
1853 					    (void *)tcp);
1854 
1855 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1856 				mp = &tcp->tcp_closemp;
1857 				squeue_fill(connp->conn_sqp, mp,
1858 				    tcp_timewait_output, connp,
1859 				    SQTAG_TCP_TIMEWAIT);
1860 			}
1861 		} else {
1862 			mutex_enter(&connp->conn_lock);
1863 			CONN_INC_REF_LOCKED(connp);
1864 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1865 			mutex_exit(&connp->conn_lock);
1866 			/*
1867 			 * We can reuse the closemp here since conn has
1868 			 * detached (otherwise we wouldn't even be in
1869 			 * time_wait list). tcp_closemp_used can safely
1870 			 * be changed without taking a lock as no other
1871 			 * thread can concurrently access it at this
1872 			 * point in the connection lifecycle.
1873 			 */
1874 
1875 			if (tcp->tcp_closemp.b_prev == NULL)
1876 				tcp->tcp_closemp_used = B_TRUE;
1877 			else
1878 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1879 				    "concurrent use of tcp_closemp: "
1880 				    "connp %p tcp %p\n", (void *)connp,
1881 				    (void *)tcp);
1882 
1883 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1884 			mp = &tcp->tcp_closemp;
1885 			squeue_fill(connp->conn_sqp, mp,
1886 			    tcp_timewait_output, connp, 0);
1887 		}
1888 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1889 	}
1890 
1891 	if (tcp_time_wait->tcp_free_list != NULL)
1892 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1893 
1894 	tcp_time_wait->tcp_time_wait_tid =
1895 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1896 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1897 }
1898 /*
1899  * Reply to a clients T_CONN_RES TPI message. This function
1900  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1901  * on the acceptor STREAM and processed in tcp_wput_accept().
1902  * Read the block comment on top of tcp_conn_request().
1903  */
1904 static void
1905 tcp_accept(tcp_t *listener, mblk_t *mp)
1906 {
1907 	tcp_t	*acceptor;
1908 	tcp_t	*eager;
1909 	tcp_t   *tcp;
1910 	struct T_conn_res	*tcr;
1911 	t_uscalar_t	acceptor_id;
1912 	t_scalar_t	seqnum;
1913 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1914 	mblk_t	*ok_mp;
1915 	mblk_t	*mp1;
1916 	tcp_stack_t	*tcps = listener->tcp_tcps;
1917 
1918 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1919 		tcp_err_ack(listener, mp, TPROTO, 0);
1920 		return;
1921 	}
1922 	tcr = (struct T_conn_res *)mp->b_rptr;
1923 
1924 	/*
1925 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1926 	 * read side queue of the streams device underneath us i.e. the
1927 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1928 	 * look it up in the queue_hash.  Under LP64 it sends down the
1929 	 * minor_t of the accepting endpoint.
1930 	 *
1931 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1932 	 * fanout hash lock is held.
1933 	 * This prevents any thread from entering the acceptor queue from
1934 	 * below (since it has not been hard bound yet i.e. any inbound
1935 	 * packets will arrive on the listener or default tcp queue and
1936 	 * go through tcp_lookup).
1937 	 * The CONN_INC_REF will prevent the acceptor from closing.
1938 	 *
1939 	 * XXX It is still possible for a tli application to send down data
1940 	 * on the accepting stream while another thread calls t_accept.
1941 	 * This should not be a problem for well-behaved applications since
1942 	 * the T_OK_ACK is sent after the queue swapping is completed.
1943 	 *
1944 	 * If the accepting fd is the same as the listening fd, avoid
1945 	 * queue hash lookup since that will return an eager listener in a
1946 	 * already established state.
1947 	 */
1948 	acceptor_id = tcr->ACCEPTOR_id;
1949 	mutex_enter(&listener->tcp_eager_lock);
1950 	if (listener->tcp_acceptor_id == acceptor_id) {
1951 		eager = listener->tcp_eager_next_q;
1952 		/* only count how many T_CONN_INDs so don't count q0 */
1953 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1954 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1955 			mutex_exit(&listener->tcp_eager_lock);
1956 			tcp_err_ack(listener, mp, TBADF, 0);
1957 			return;
1958 		}
1959 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1960 			/* Throw away all the eagers on q0. */
1961 			tcp_eager_cleanup(listener, 1);
1962 		}
1963 		if (listener->tcp_syn_defense) {
1964 			listener->tcp_syn_defense = B_FALSE;
1965 			if (listener->tcp_ip_addr_cache != NULL) {
1966 				kmem_free(listener->tcp_ip_addr_cache,
1967 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1968 				listener->tcp_ip_addr_cache = NULL;
1969 			}
1970 		}
1971 		/*
1972 		 * Transfer tcp_conn_req_max to the eager so that when
1973 		 * a disconnect occurs we can revert the endpoint to the
1974 		 * listen state.
1975 		 */
1976 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1977 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1978 		/*
1979 		 * Get a reference on the acceptor just like the
1980 		 * tcp_acceptor_hash_lookup below.
1981 		 */
1982 		acceptor = listener;
1983 		CONN_INC_REF(acceptor->tcp_connp);
1984 	} else {
1985 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1986 		if (acceptor == NULL) {
1987 			if (listener->tcp_debug) {
1988 				(void) strlog(TCP_MOD_ID, 0, 1,
1989 				    SL_ERROR|SL_TRACE,
1990 				    "tcp_accept: did not find acceptor 0x%x\n",
1991 				    acceptor_id);
1992 			}
1993 			mutex_exit(&listener->tcp_eager_lock);
1994 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1995 			return;
1996 		}
1997 		/*
1998 		 * Verify acceptor state. The acceptable states for an acceptor
1999 		 * include TCPS_IDLE and TCPS_BOUND.
2000 		 */
2001 		switch (acceptor->tcp_state) {
2002 		case TCPS_IDLE:
2003 			/* FALLTHRU */
2004 		case TCPS_BOUND:
2005 			break;
2006 		default:
2007 			CONN_DEC_REF(acceptor->tcp_connp);
2008 			mutex_exit(&listener->tcp_eager_lock);
2009 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2010 			return;
2011 		}
2012 	}
2013 
2014 	/* The listener must be in TCPS_LISTEN */
2015 	if (listener->tcp_state != TCPS_LISTEN) {
2016 		CONN_DEC_REF(acceptor->tcp_connp);
2017 		mutex_exit(&listener->tcp_eager_lock);
2018 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2019 		return;
2020 	}
2021 
2022 	/*
2023 	 * Rendezvous with an eager connection request packet hanging off
2024 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2025 	 * tcp structure when the connection packet arrived in
2026 	 * tcp_conn_request().
2027 	 */
2028 	seqnum = tcr->SEQ_number;
2029 	eager = listener;
2030 	do {
2031 		eager = eager->tcp_eager_next_q;
2032 		if (eager == NULL) {
2033 			CONN_DEC_REF(acceptor->tcp_connp);
2034 			mutex_exit(&listener->tcp_eager_lock);
2035 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2036 			return;
2037 		}
2038 	} while (eager->tcp_conn_req_seqnum != seqnum);
2039 	mutex_exit(&listener->tcp_eager_lock);
2040 
2041 	/*
2042 	 * At this point, both acceptor and listener have 2 ref
2043 	 * that they begin with. Acceptor has one additional ref
2044 	 * we placed in lookup while listener has 3 additional
2045 	 * ref for being behind the squeue (tcp_accept() is
2046 	 * done on listener's squeue); being in classifier hash;
2047 	 * and eager's ref on listener.
2048 	 */
2049 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2050 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2051 
2052 	/*
2053 	 * The eager at this point is set in its own squeue and
2054 	 * could easily have been killed (tcp_accept_finish will
2055 	 * deal with that) because of a TH_RST so we can only
2056 	 * ASSERT for a single ref.
2057 	 */
2058 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2059 
2060 	/* Pre allocate the stroptions mblk also */
2061 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2062 	if (opt_mp == NULL) {
2063 		CONN_DEC_REF(acceptor->tcp_connp);
2064 		CONN_DEC_REF(eager->tcp_connp);
2065 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2066 		return;
2067 	}
2068 	DB_TYPE(opt_mp) = M_SETOPTS;
2069 	opt_mp->b_wptr += sizeof (struct stroptions);
2070 
2071 	/*
2072 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2073 	 * from listener to acceptor. The message is chained on opt_mp
2074 	 * which will be sent onto eager's squeue.
2075 	 */
2076 	if (listener->tcp_bound_if != 0) {
2077 		/* allocate optmgmt req */
2078 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2079 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2080 		    sizeof (int));
2081 		if (mp1 != NULL)
2082 			linkb(opt_mp, mp1);
2083 	}
2084 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2085 		uint_t on = 1;
2086 
2087 		/* allocate optmgmt req */
2088 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2089 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2090 		if (mp1 != NULL)
2091 			linkb(opt_mp, mp1);
2092 	}
2093 
2094 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2095 	if ((mp1 = copymsg(mp)) == NULL) {
2096 		CONN_DEC_REF(acceptor->tcp_connp);
2097 		CONN_DEC_REF(eager->tcp_connp);
2098 		freemsg(opt_mp);
2099 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2100 		return;
2101 	}
2102 
2103 	tcr = (struct T_conn_res *)mp1->b_rptr;
2104 
2105 	/*
2106 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2107 	 * which allocates a larger mblk and appends the new
2108 	 * local address to the ok_ack.  The address is copied by
2109 	 * soaccept() for getsockname().
2110 	 */
2111 	{
2112 		int extra;
2113 
2114 		extra = (eager->tcp_family == AF_INET) ?
2115 		    sizeof (sin_t) : sizeof (sin6_t);
2116 
2117 		/*
2118 		 * Try to re-use mp, if possible.  Otherwise, allocate
2119 		 * an mblk and return it as ok_mp.  In any case, mp
2120 		 * is no longer usable upon return.
2121 		 */
2122 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2123 			CONN_DEC_REF(acceptor->tcp_connp);
2124 			CONN_DEC_REF(eager->tcp_connp);
2125 			freemsg(opt_mp);
2126 			/* Original mp has been freed by now, so use mp1 */
2127 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2128 			return;
2129 		}
2130 
2131 		mp = NULL;	/* We should never use mp after this point */
2132 
2133 		switch (extra) {
2134 		case sizeof (sin_t): {
2135 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2136 
2137 				ok_mp->b_wptr += extra;
2138 				sin->sin_family = AF_INET;
2139 				sin->sin_port = eager->tcp_lport;
2140 				sin->sin_addr.s_addr =
2141 				    eager->tcp_ipha->ipha_src;
2142 				break;
2143 			}
2144 		case sizeof (sin6_t): {
2145 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2146 
2147 				ok_mp->b_wptr += extra;
2148 				sin6->sin6_family = AF_INET6;
2149 				sin6->sin6_port = eager->tcp_lport;
2150 				if (eager->tcp_ipversion == IPV4_VERSION) {
2151 					sin6->sin6_flowinfo = 0;
2152 					IN6_IPADDR_TO_V4MAPPED(
2153 					    eager->tcp_ipha->ipha_src,
2154 					    &sin6->sin6_addr);
2155 				} else {
2156 					ASSERT(eager->tcp_ip6h != NULL);
2157 					sin6->sin6_flowinfo =
2158 					    eager->tcp_ip6h->ip6_vcf &
2159 					    ~IPV6_VERS_AND_FLOW_MASK;
2160 					sin6->sin6_addr =
2161 					    eager->tcp_ip6h->ip6_src;
2162 				}
2163 				sin6->sin6_scope_id = 0;
2164 				sin6->__sin6_src_id = 0;
2165 				break;
2166 			}
2167 		default:
2168 			break;
2169 		}
2170 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2171 	}
2172 
2173 	/*
2174 	 * If there are no options we know that the T_CONN_RES will
2175 	 * succeed. However, we can't send the T_OK_ACK upstream until
2176 	 * the tcp_accept_swap is done since it would be dangerous to
2177 	 * let the application start using the new fd prior to the swap.
2178 	 */
2179 	tcp_accept_swap(listener, acceptor, eager);
2180 
2181 	/*
2182 	 * tcp_accept_swap unlinks eager from listener but does not drop
2183 	 * the eager's reference on the listener.
2184 	 */
2185 	ASSERT(eager->tcp_listener == NULL);
2186 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2187 
2188 	/*
2189 	 * The eager is now associated with its own queue. Insert in
2190 	 * the hash so that the connection can be reused for a future
2191 	 * T_CONN_RES.
2192 	 */
2193 	tcp_acceptor_hash_insert(acceptor_id, eager);
2194 
2195 	/*
2196 	 * We now do the processing of options with T_CONN_RES.
2197 	 * We delay till now since we wanted to have queue to pass to
2198 	 * option processing routines that points back to the right
2199 	 * instance structure which does not happen until after
2200 	 * tcp_accept_swap().
2201 	 *
2202 	 * Note:
2203 	 * The sanity of the logic here assumes that whatever options
2204 	 * are appropriate to inherit from listner=>eager are done
2205 	 * before this point, and whatever were to be overridden (or not)
2206 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2207 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2208 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2209 	 * This may not be true at this point in time but can be fixed
2210 	 * independently. This option processing code starts with
2211 	 * the instantiated acceptor instance and the final queue at
2212 	 * this point.
2213 	 */
2214 
2215 	if (tcr->OPT_length != 0) {
2216 		/* Options to process */
2217 		int t_error = 0;
2218 		int sys_error = 0;
2219 		int do_disconnect = 0;
2220 
2221 		if (tcp_conprim_opt_process(eager, mp1,
2222 		    &do_disconnect, &t_error, &sys_error) < 0) {
2223 			eager->tcp_accept_error = 1;
2224 			if (do_disconnect) {
2225 				/*
2226 				 * An option failed which does not allow
2227 				 * connection to be accepted.
2228 				 *
2229 				 * We allow T_CONN_RES to succeed and
2230 				 * put a T_DISCON_IND on the eager queue.
2231 				 */
2232 				ASSERT(t_error == 0 && sys_error == 0);
2233 				eager->tcp_send_discon_ind = 1;
2234 			} else {
2235 				ASSERT(t_error != 0);
2236 				freemsg(ok_mp);
2237 				/*
2238 				 * Original mp was either freed or set
2239 				 * to ok_mp above, so use mp1 instead.
2240 				 */
2241 				tcp_err_ack(listener, mp1, t_error, sys_error);
2242 				goto finish;
2243 			}
2244 		}
2245 		/*
2246 		 * Most likely success in setting options (except if
2247 		 * eager->tcp_send_discon_ind set).
2248 		 * mp1 option buffer represented by OPT_length/offset
2249 		 * potentially modified and contains results of setting
2250 		 * options at this point
2251 		 */
2252 	}
2253 
2254 	/* We no longer need mp1, since all options processing has passed */
2255 	freemsg(mp1);
2256 
2257 	putnext(listener->tcp_rq, ok_mp);
2258 
2259 	mutex_enter(&listener->tcp_eager_lock);
2260 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2261 		tcp_t	*tail;
2262 		mblk_t	*conn_ind;
2263 
2264 		/*
2265 		 * This path should not be executed if listener and
2266 		 * acceptor streams are the same.
2267 		 */
2268 		ASSERT(listener != acceptor);
2269 
2270 		tcp = listener->tcp_eager_prev_q0;
2271 		/*
2272 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2273 		 * deferred T_conn_ind queue. We need to get to the head of
2274 		 * the queue in order to send up T_conn_ind the same order as
2275 		 * how the 3WHS is completed.
2276 		 */
2277 		while (tcp != listener) {
2278 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2279 				break;
2280 			else
2281 				tcp = tcp->tcp_eager_prev_q0;
2282 		}
2283 		ASSERT(tcp != listener);
2284 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2285 		ASSERT(conn_ind != NULL);
2286 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2287 
2288 		/* Move from q0 to q */
2289 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2290 		listener->tcp_conn_req_cnt_q0--;
2291 		listener->tcp_conn_req_cnt_q++;
2292 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2293 		    tcp->tcp_eager_prev_q0;
2294 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2295 		    tcp->tcp_eager_next_q0;
2296 		tcp->tcp_eager_prev_q0 = NULL;
2297 		tcp->tcp_eager_next_q0 = NULL;
2298 		tcp->tcp_conn_def_q0 = B_FALSE;
2299 
2300 		/* Make sure the tcp isn't in the list of droppables */
2301 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2302 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2303 
2304 		/*
2305 		 * Insert at end of the queue because sockfs sends
2306 		 * down T_CONN_RES in chronological order. Leaving
2307 		 * the older conn indications at front of the queue
2308 		 * helps reducing search time.
2309 		 */
2310 		tail = listener->tcp_eager_last_q;
2311 		if (tail != NULL)
2312 			tail->tcp_eager_next_q = tcp;
2313 		else
2314 			listener->tcp_eager_next_q = tcp;
2315 		listener->tcp_eager_last_q = tcp;
2316 		tcp->tcp_eager_next_q = NULL;
2317 		mutex_exit(&listener->tcp_eager_lock);
2318 		putnext(tcp->tcp_rq, conn_ind);
2319 	} else {
2320 		mutex_exit(&listener->tcp_eager_lock);
2321 	}
2322 
2323 	/*
2324 	 * Done with the acceptor - free it
2325 	 *
2326 	 * Note: from this point on, no access to listener should be made
2327 	 * as listener can be equal to acceptor.
2328 	 */
2329 finish:
2330 	ASSERT(acceptor->tcp_detached);
2331 	ASSERT(tcps->tcps_g_q != NULL);
2332 	acceptor->tcp_rq = tcps->tcps_g_q;
2333 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2334 	(void) tcp_clean_death(acceptor, 0, 2);
2335 	CONN_DEC_REF(acceptor->tcp_connp);
2336 
2337 	/*
2338 	 * In case we already received a FIN we have to make tcp_rput send
2339 	 * the ordrel_ind. This will also send up a window update if the window
2340 	 * has opened up.
2341 	 *
2342 	 * In the normal case of a successful connection acceptance
2343 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2344 	 * indication that this was just accepted. This tells tcp_rput to
2345 	 * pass up any data queued in tcp_rcv_list.
2346 	 *
2347 	 * In the fringe case where options sent with T_CONN_RES failed and
2348 	 * we required, we would be indicating a T_DISCON_IND to blow
2349 	 * away this connection.
2350 	 */
2351 
2352 	/*
2353 	 * XXX: we currently have a problem if XTI application closes the
2354 	 * acceptor stream in between. This problem exists in on10-gate also
2355 	 * and is well know but nothing can be done short of major rewrite
2356 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2357 	 * eager same squeue as listener (we can distinguish non socket
2358 	 * listeners at the time of handling a SYN in tcp_conn_request)
2359 	 * and do most of the work that tcp_accept_finish does here itself
2360 	 * and then get behind the acceptor squeue to access the acceptor
2361 	 * queue.
2362 	 */
2363 	/*
2364 	 * We already have a ref on tcp so no need to do one before squeue_fill
2365 	 */
2366 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2367 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2368 }
2369 
2370 /*
2371  * Swap information between the eager and acceptor for a TLI/XTI client.
2372  * The sockfs accept is done on the acceptor stream and control goes
2373  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2374  * called. In either case, both the eager and listener are in their own
2375  * perimeter (squeue) and the code has to deal with potential race.
2376  *
2377  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2378  */
2379 static void
2380 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2381 {
2382 	conn_t	*econnp, *aconnp;
2383 
2384 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2385 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2386 	ASSERT(!eager->tcp_hard_bound);
2387 	ASSERT(!TCP_IS_SOCKET(acceptor));
2388 	ASSERT(!TCP_IS_SOCKET(eager));
2389 	ASSERT(!TCP_IS_SOCKET(listener));
2390 
2391 	acceptor->tcp_detached = B_TRUE;
2392 	/*
2393 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2394 	 * the acceptor id.
2395 	 */
2396 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2397 
2398 	/* remove eager from listen list... */
2399 	mutex_enter(&listener->tcp_eager_lock);
2400 	tcp_eager_unlink(eager);
2401 	ASSERT(eager->tcp_eager_next_q == NULL &&
2402 	    eager->tcp_eager_last_q == NULL);
2403 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2404 	    eager->tcp_eager_prev_q0 == NULL);
2405 	mutex_exit(&listener->tcp_eager_lock);
2406 	eager->tcp_rq = acceptor->tcp_rq;
2407 	eager->tcp_wq = acceptor->tcp_wq;
2408 
2409 	econnp = eager->tcp_connp;
2410 	aconnp = acceptor->tcp_connp;
2411 
2412 	eager->tcp_rq->q_ptr = econnp;
2413 	eager->tcp_wq->q_ptr = econnp;
2414 
2415 	/*
2416 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2417 	 * which might be a different squeue from our peer TCP instance.
2418 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2419 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2420 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2421 	 * above reach global visibility prior to the clearing of tcp_detached.
2422 	 */
2423 	membar_producer();
2424 	eager->tcp_detached = B_FALSE;
2425 
2426 	ASSERT(eager->tcp_ack_tid == 0);
2427 
2428 	econnp->conn_dev = aconnp->conn_dev;
2429 	if (eager->tcp_cred != NULL)
2430 		crfree(eager->tcp_cred);
2431 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2432 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2433 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2434 
2435 	aconnp->conn_cred = NULL;
2436 
2437 	econnp->conn_zoneid = aconnp->conn_zoneid;
2438 	econnp->conn_allzones = aconnp->conn_allzones;
2439 
2440 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2441 	aconnp->conn_mac_exempt = B_FALSE;
2442 
2443 	ASSERT(aconnp->conn_peercred == NULL);
2444 
2445 	/* Do the IPC initialization */
2446 	CONN_INC_REF(econnp);
2447 
2448 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2449 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2450 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2451 	econnp->conn_ulp = aconnp->conn_ulp;
2452 
2453 	/* Done with old IPC. Drop its ref on its connp */
2454 	CONN_DEC_REF(aconnp);
2455 }
2456 
2457 
2458 /*
2459  * Adapt to the information, such as rtt and rtt_sd, provided from the
2460  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2461  *
2462  * Checks for multicast and broadcast destination address.
2463  * Returns zero on failure; non-zero if ok.
2464  *
2465  * Note that the MSS calculation here is based on the info given in
2466  * the IRE.  We do not do any calculation based on TCP options.  They
2467  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2468  * knows which options to use.
2469  *
2470  * Note on how TCP gets its parameters for a connection.
2471  *
2472  * When a tcp_t structure is allocated, it gets all the default parameters.
2473  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2474  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2475  * default.  But if there is an associated tcp_host_param, it will override
2476  * the metrics.
2477  *
2478  * An incoming SYN with a multicast or broadcast destination address, is dropped
2479  * in 1 of 2 places.
2480  *
2481  * 1. If the packet was received over the wire it is dropped in
2482  * ip_rput_process_broadcast()
2483  *
2484  * 2. If the packet was received through internal IP loopback, i.e. the packet
2485  * was generated and received on the same machine, it is dropped in
2486  * ip_wput_local()
2487  *
2488  * An incoming SYN with a multicast or broadcast source address is always
2489  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2490  * reject an attempt to connect to a broadcast or multicast (destination)
2491  * address.
2492  */
2493 static int
2494 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2495 {
2496 	tcp_hsp_t	*hsp;
2497 	ire_t		*ire;
2498 	ire_t		*sire = NULL;
2499 	iulp_t		*ire_uinfo = NULL;
2500 	uint32_t	mss_max;
2501 	uint32_t	mss;
2502 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2503 	conn_t		*connp = tcp->tcp_connp;
2504 	boolean_t	ire_cacheable = B_FALSE;
2505 	zoneid_t	zoneid = connp->conn_zoneid;
2506 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2507 			    MATCH_IRE_SECATTR;
2508 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2509 	ill_t		*ill = NULL;
2510 	boolean_t	incoming = (ire_mp == NULL);
2511 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2512 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2513 
2514 	ASSERT(connp->conn_ire_cache == NULL);
2515 
2516 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2517 
2518 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2519 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2520 			return (0);
2521 		}
2522 		/*
2523 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2524 		 * for the destination with the nexthop as gateway.
2525 		 * ire_ctable_lookup() is used because this particular
2526 		 * ire, if it exists, will be marked private.
2527 		 * If that is not available, use the interface ire
2528 		 * for the nexthop.
2529 		 *
2530 		 * TSol: tcp_update_label will detect label mismatches based
2531 		 * only on the destination's label, but that would not
2532 		 * detect label mismatches based on the security attributes
2533 		 * of routes or next hop gateway. Hence we need to pass the
2534 		 * label to ire_ftable_lookup below in order to locate the
2535 		 * right prefix (and/or) ire cache. Similarly we also need
2536 		 * pass the label to the ire_cache_lookup below to locate
2537 		 * the right ire that also matches on the label.
2538 		 */
2539 		if (tcp->tcp_connp->conn_nexthop_set) {
2540 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2541 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2542 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2543 			    ipst);
2544 			if (ire == NULL) {
2545 				ire = ire_ftable_lookup(
2546 				    tcp->tcp_connp->conn_nexthop_v4,
2547 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2548 				    tsl, match_flags, ipst);
2549 				if (ire == NULL)
2550 					return (0);
2551 			} else {
2552 				ire_uinfo = &ire->ire_uinfo;
2553 			}
2554 		} else {
2555 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2556 			    zoneid, tsl, ipst);
2557 			if (ire != NULL) {
2558 				ire_cacheable = B_TRUE;
2559 				ire_uinfo = (ire_mp != NULL) ?
2560 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2561 				    &ire->ire_uinfo;
2562 
2563 			} else {
2564 				if (ire_mp == NULL) {
2565 					ire = ire_ftable_lookup(
2566 					    tcp->tcp_connp->conn_rem,
2567 					    0, 0, 0, NULL, &sire, zoneid, 0,
2568 					    tsl, (MATCH_IRE_RECURSIVE |
2569 					    MATCH_IRE_DEFAULT), ipst);
2570 					if (ire == NULL)
2571 						return (0);
2572 					ire_uinfo = (sire != NULL) ?
2573 					    &sire->ire_uinfo :
2574 					    &ire->ire_uinfo;
2575 				} else {
2576 					ire = (ire_t *)ire_mp->b_rptr;
2577 					ire_uinfo =
2578 					    &((ire_t *)
2579 					    ire_mp->b_rptr)->ire_uinfo;
2580 				}
2581 			}
2582 		}
2583 		ASSERT(ire != NULL);
2584 
2585 		if ((ire->ire_src_addr == INADDR_ANY) ||
2586 		    (ire->ire_type & IRE_BROADCAST)) {
2587 			/*
2588 			 * ire->ire_mp is non null when ire_mp passed in is used
2589 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2590 			 */
2591 			if (ire->ire_mp == NULL)
2592 				ire_refrele(ire);
2593 			if (sire != NULL)
2594 				ire_refrele(sire);
2595 			return (0);
2596 		}
2597 
2598 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2599 			ipaddr_t src_addr;
2600 
2601 			/*
2602 			 * ip_bind_connected() has stored the correct source
2603 			 * address in conn_src.
2604 			 */
2605 			src_addr = tcp->tcp_connp->conn_src;
2606 			tcp->tcp_ipha->ipha_src = src_addr;
2607 			/*
2608 			 * Copy of the src addr. in tcp_t is needed
2609 			 * for the lookup funcs.
2610 			 */
2611 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2612 		}
2613 		/*
2614 		 * Set the fragment bit so that IP will tell us if the MTU
2615 		 * should change. IP tells us the latest setting of
2616 		 * ip_path_mtu_discovery through ire_frag_flag.
2617 		 */
2618 		if (ipst->ips_ip_path_mtu_discovery) {
2619 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2620 			    htons(IPH_DF);
2621 		}
2622 		/*
2623 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2624 		 * for IP_NEXTHOP. No cache ire has been found for the
2625 		 * destination and we are working with the nexthop's
2626 		 * interface ire. Since we need to forward all packets
2627 		 * to the nexthop first, we "blindly" set tcp_localnet
2628 		 * to false, eventhough the destination may also be
2629 		 * onlink.
2630 		 */
2631 		if (ire_uinfo == NULL)
2632 			tcp->tcp_localnet = 0;
2633 		else
2634 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2635 	} else {
2636 		/*
2637 		 * For incoming connection ire_mp = NULL
2638 		 * For outgoing connection ire_mp != NULL
2639 		 * Technically we should check conn_incoming_ill
2640 		 * when ire_mp is NULL and conn_outgoing_ill when
2641 		 * ire_mp is non-NULL. But this is performance
2642 		 * critical path and for IPV*_BOUND_IF, outgoing
2643 		 * and incoming ill are always set to the same value.
2644 		 */
2645 		ill_t	*dst_ill = NULL;
2646 		ipif_t  *dst_ipif = NULL;
2647 
2648 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2649 
2650 		if (connp->conn_outgoing_ill != NULL) {
2651 			/* Outgoing or incoming path */
2652 			int   err;
2653 
2654 			dst_ill = conn_get_held_ill(connp,
2655 			    &connp->conn_outgoing_ill, &err);
2656 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2657 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2658 				return (0);
2659 			}
2660 			match_flags |= MATCH_IRE_ILL;
2661 			dst_ipif = dst_ill->ill_ipif;
2662 		}
2663 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2664 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2665 
2666 		if (ire != NULL) {
2667 			ire_cacheable = B_TRUE;
2668 			ire_uinfo = (ire_mp != NULL) ?
2669 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2670 			    &ire->ire_uinfo;
2671 		} else {
2672 			if (ire_mp == NULL) {
2673 				ire = ire_ftable_lookup_v6(
2674 				    &tcp->tcp_connp->conn_remv6,
2675 				    0, 0, 0, dst_ipif, &sire, zoneid,
2676 				    0, tsl, match_flags, ipst);
2677 				if (ire == NULL) {
2678 					if (dst_ill != NULL)
2679 						ill_refrele(dst_ill);
2680 					return (0);
2681 				}
2682 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2683 				    &ire->ire_uinfo;
2684 			} else {
2685 				ire = (ire_t *)ire_mp->b_rptr;
2686 				ire_uinfo =
2687 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2688 			}
2689 		}
2690 		if (dst_ill != NULL)
2691 			ill_refrele(dst_ill);
2692 
2693 		ASSERT(ire != NULL);
2694 		ASSERT(ire_uinfo != NULL);
2695 
2696 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2697 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2698 			/*
2699 			 * ire->ire_mp is non null when ire_mp passed in is used
2700 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2701 			 */
2702 			if (ire->ire_mp == NULL)
2703 				ire_refrele(ire);
2704 			if (sire != NULL)
2705 				ire_refrele(sire);
2706 			return (0);
2707 		}
2708 
2709 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2710 			in6_addr_t	src_addr;
2711 
2712 			/*
2713 			 * ip_bind_connected_v6() has stored the correct source
2714 			 * address per IPv6 addr. selection policy in
2715 			 * conn_src_v6.
2716 			 */
2717 			src_addr = tcp->tcp_connp->conn_srcv6;
2718 
2719 			tcp->tcp_ip6h->ip6_src = src_addr;
2720 			/*
2721 			 * Copy of the src addr. in tcp_t is needed
2722 			 * for the lookup funcs.
2723 			 */
2724 			tcp->tcp_ip_src_v6 = src_addr;
2725 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2726 			    &connp->conn_srcv6));
2727 		}
2728 		tcp->tcp_localnet =
2729 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2730 	}
2731 
2732 	/*
2733 	 * This allows applications to fail quickly when connections are made
2734 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2735 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2736 	 */
2737 	if ((ire->ire_flags & RTF_REJECT) &&
2738 	    (ire->ire_flags & RTF_PRIVATE))
2739 		goto error;
2740 
2741 	/*
2742 	 * Make use of the cached rtt and rtt_sd values to calculate the
2743 	 * initial RTO.  Note that they are already initialized in
2744 	 * tcp_init_values().
2745 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2746 	 * IP_NEXTHOP, but instead are using the interface ire for the
2747 	 * nexthop, then we do not use the ire_uinfo from that ire to
2748 	 * do any initializations.
2749 	 */
2750 	if (ire_uinfo != NULL) {
2751 		if (ire_uinfo->iulp_rtt != 0) {
2752 			clock_t	rto;
2753 
2754 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2755 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2756 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2757 			    tcps->tcps_rexmit_interval_extra +
2758 			    (tcp->tcp_rtt_sa >> 5);
2759 
2760 			if (rto > tcps->tcps_rexmit_interval_max) {
2761 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2762 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2763 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2764 			} else {
2765 				tcp->tcp_rto = rto;
2766 			}
2767 		}
2768 		if (ire_uinfo->iulp_ssthresh != 0)
2769 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2770 		else
2771 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2772 		if (ire_uinfo->iulp_spipe > 0) {
2773 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2774 			    tcps->tcps_max_buf);
2775 			if (tcps->tcps_snd_lowat_fraction != 0)
2776 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2777 				    tcps->tcps_snd_lowat_fraction;
2778 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2779 		}
2780 		/*
2781 		 * Note that up till now, acceptor always inherits receive
2782 		 * window from the listener.  But if there is a metrics
2783 		 * associated with a host, we should use that instead of
2784 		 * inheriting it from listener. Thus we need to pass this
2785 		 * info back to the caller.
2786 		 */
2787 		if (ire_uinfo->iulp_rpipe > 0) {
2788 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2789 					    tcps->tcps_max_buf);
2790 		}
2791 
2792 		if (ire_uinfo->iulp_rtomax > 0) {
2793 			tcp->tcp_second_timer_threshold =
2794 			    ire_uinfo->iulp_rtomax;
2795 		}
2796 
2797 		/*
2798 		 * Use the metric option settings, iulp_tstamp_ok and
2799 		 * iulp_wscale_ok, only for active open. What this means
2800 		 * is that if the other side uses timestamp or window
2801 		 * scale option, TCP will also use those options. That
2802 		 * is for passive open.  If the application sets a
2803 		 * large window, window scale is enabled regardless of
2804 		 * the value in iulp_wscale_ok.  This is the behavior
2805 		 * since 2.6.  So we keep it.
2806 		 * The only case left in passive open processing is the
2807 		 * check for SACK.
2808 		 * For ECN, it should probably be like SACK.  But the
2809 		 * current value is binary, so we treat it like the other
2810 		 * cases.  The metric only controls active open.For passive
2811 		 * open, the ndd param, tcp_ecn_permitted, controls the
2812 		 * behavior.
2813 		 */
2814 		if (!tcp_detached) {
2815 			/*
2816 			 * The if check means that the following can only
2817 			 * be turned on by the metrics only IRE, but not off.
2818 			 */
2819 			if (ire_uinfo->iulp_tstamp_ok)
2820 				tcp->tcp_snd_ts_ok = B_TRUE;
2821 			if (ire_uinfo->iulp_wscale_ok)
2822 				tcp->tcp_snd_ws_ok = B_TRUE;
2823 			if (ire_uinfo->iulp_sack == 2)
2824 				tcp->tcp_snd_sack_ok = B_TRUE;
2825 			if (ire_uinfo->iulp_ecn_ok)
2826 				tcp->tcp_ecn_ok = B_TRUE;
2827 		} else {
2828 			/*
2829 			 * Passive open.
2830 			 *
2831 			 * As above, the if check means that SACK can only be
2832 			 * turned on by the metric only IRE.
2833 			 */
2834 			if (ire_uinfo->iulp_sack > 0) {
2835 				tcp->tcp_snd_sack_ok = B_TRUE;
2836 			}
2837 		}
2838 	}
2839 
2840 
2841 	/*
2842 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2843 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2844 	 * length of all those options exceeds 28 bytes.  But because
2845 	 * of the tcp_mss_min check below, we may not have a problem if
2846 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2847 	 * the negative problem still exists.  And the check defeats PMTUd.
2848 	 * In fact, if PMTUd finds that the MSS should be smaller than
2849 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2850 	 * value.
2851 	 *
2852 	 * We do not deal with that now.  All those problems related to
2853 	 * PMTUd will be fixed later.
2854 	 */
2855 	ASSERT(ire->ire_max_frag != 0);
2856 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2857 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2858 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2859 			mss = MIN(mss, IPV6_MIN_MTU);
2860 		}
2861 	}
2862 
2863 	/* Sanity check for MSS value. */
2864 	if (tcp->tcp_ipversion == IPV4_VERSION)
2865 		mss_max = tcps->tcps_mss_max_ipv4;
2866 	else
2867 		mss_max = tcps->tcps_mss_max_ipv6;
2868 
2869 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2870 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2871 		/*
2872 		 * After receiving an ICMPv6 "packet too big" message with a
2873 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2874 		 * will insert a 8-byte fragment header in every packet; we
2875 		 * reduce the MSS by that amount here.
2876 		 */
2877 		mss -= sizeof (ip6_frag_t);
2878 	}
2879 
2880 	if (tcp->tcp_ipsec_overhead == 0)
2881 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2882 
2883 	mss -= tcp->tcp_ipsec_overhead;
2884 
2885 	if (mss < tcps->tcps_mss_min)
2886 		mss = tcps->tcps_mss_min;
2887 	if (mss > mss_max)
2888 		mss = mss_max;
2889 
2890 	/* Note that this is the maximum MSS, excluding all options. */
2891 	tcp->tcp_mss = mss;
2892 
2893 	/*
2894 	 * Initialize the ISS here now that we have the full connection ID.
2895 	 * The RFC 1948 method of initial sequence number generation requires
2896 	 * knowledge of the full connection ID before setting the ISS.
2897 	 */
2898 
2899 	tcp_iss_init(tcp);
2900 
2901 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2902 		tcp->tcp_loopback = B_TRUE;
2903 
2904 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2905 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2906 	} else {
2907 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2908 	}
2909 
2910 	if (hsp != NULL) {
2911 		/* Only modify if we're going to make them bigger */
2912 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2913 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2914 			if (tcps->tcps_snd_lowat_fraction != 0)
2915 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2916 					tcps->tcps_snd_lowat_fraction;
2917 		}
2918 
2919 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2920 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2921 		}
2922 
2923 		/* Copy timestamp flag only for active open */
2924 		if (!tcp_detached)
2925 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2926 	}
2927 
2928 	if (sire != NULL)
2929 		IRE_REFRELE(sire);
2930 
2931 	/*
2932 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2933 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2934 	 */
2935 	if (tcp->tcp_loopback ||
2936 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2937 		/*
2938 		 * For incoming, see if this tcp may be MDT-capable.  For
2939 		 * outgoing, this process has been taken care of through
2940 		 * tcp_rput_other.
2941 		 */
2942 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2943 		tcp->tcp_ire_ill_check_done = B_TRUE;
2944 	}
2945 
2946 	mutex_enter(&connp->conn_lock);
2947 	/*
2948 	 * Make sure that conn is not marked incipient
2949 	 * for incoming connections. A blind
2950 	 * removal of incipient flag is cheaper than
2951 	 * check and removal.
2952 	 */
2953 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2954 
2955 	/*
2956 	 * Must not cache forwarding table routes
2957 	 * or recache an IRE after the conn_t has
2958 	 * had conn_ire_cache cleared and is flagged
2959 	 * unusable, (see the CONN_CACHE_IRE() macro).
2960 	 */
2961 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2962 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2963 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2964 			connp->conn_ire_cache = ire;
2965 			IRE_UNTRACE_REF(ire);
2966 			rw_exit(&ire->ire_bucket->irb_lock);
2967 			mutex_exit(&connp->conn_lock);
2968 			return (1);
2969 		}
2970 		rw_exit(&ire->ire_bucket->irb_lock);
2971 	}
2972 	mutex_exit(&connp->conn_lock);
2973 
2974 	if (ire->ire_mp == NULL)
2975 		ire_refrele(ire);
2976 	return (1);
2977 
2978 error:
2979 	if (ire->ire_mp == NULL)
2980 		ire_refrele(ire);
2981 	if (sire != NULL)
2982 		ire_refrele(sire);
2983 	return (0);
2984 }
2985 
2986 /*
2987  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2988  * O_T_BIND_REQ/T_BIND_REQ message.
2989  */
2990 static void
2991 tcp_bind(tcp_t *tcp, mblk_t *mp)
2992 {
2993 	sin_t	*sin;
2994 	sin6_t	*sin6;
2995 	mblk_t	*mp1;
2996 	in_port_t requested_port;
2997 	in_port_t allocated_port;
2998 	struct T_bind_req *tbr;
2999 	boolean_t	bind_to_req_port_only;
3000 	boolean_t	backlog_update = B_FALSE;
3001 	boolean_t	user_specified;
3002 	in6_addr_t	v6addr;
3003 	ipaddr_t	v4addr;
3004 	uint_t	origipversion;
3005 	int	err;
3006 	queue_t *q = tcp->tcp_wq;
3007 	conn_t	*connp;
3008 	mlp_type_t addrtype, mlptype;
3009 	zone_t	*zone;
3010 	cred_t	*cr;
3011 	in_port_t mlp_port;
3012 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3013 
3014 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3015 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3016 		if (tcp->tcp_debug) {
3017 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3018 			    "tcp_bind: bad req, len %u",
3019 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3020 		}
3021 		tcp_err_ack(tcp, mp, TPROTO, 0);
3022 		return;
3023 	}
3024 	/* Make sure the largest address fits */
3025 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3026 	if (mp1 == NULL) {
3027 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3028 		return;
3029 	}
3030 	mp = mp1;
3031 	tbr = (struct T_bind_req *)mp->b_rptr;
3032 	if (tcp->tcp_state >= TCPS_BOUND) {
3033 		if ((tcp->tcp_state == TCPS_BOUND ||
3034 		    tcp->tcp_state == TCPS_LISTEN) &&
3035 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3036 		    tbr->CONIND_number > 0) {
3037 			/*
3038 			 * Handle listen() increasing CONIND_number.
3039 			 * This is more "liberal" then what the TPI spec
3040 			 * requires but is needed to avoid a t_unbind
3041 			 * when handling listen() since the port number
3042 			 * might be "stolen" between the unbind and bind.
3043 			 */
3044 			backlog_update = B_TRUE;
3045 			goto do_bind;
3046 		}
3047 		if (tcp->tcp_debug) {
3048 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3049 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3050 		}
3051 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3052 		return;
3053 	}
3054 	origipversion = tcp->tcp_ipversion;
3055 
3056 	switch (tbr->ADDR_length) {
3057 	case 0:			/* request for a generic port */
3058 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3059 		if (tcp->tcp_family == AF_INET) {
3060 			tbr->ADDR_length = sizeof (sin_t);
3061 			sin = (sin_t *)&tbr[1];
3062 			*sin = sin_null;
3063 			sin->sin_family = AF_INET;
3064 			mp->b_wptr = (uchar_t *)&sin[1];
3065 			tcp->tcp_ipversion = IPV4_VERSION;
3066 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3067 		} else {
3068 			ASSERT(tcp->tcp_family == AF_INET6);
3069 			tbr->ADDR_length = sizeof (sin6_t);
3070 			sin6 = (sin6_t *)&tbr[1];
3071 			*sin6 = sin6_null;
3072 			sin6->sin6_family = AF_INET6;
3073 			mp->b_wptr = (uchar_t *)&sin6[1];
3074 			tcp->tcp_ipversion = IPV6_VERSION;
3075 			V6_SET_ZERO(v6addr);
3076 		}
3077 		requested_port = 0;
3078 		break;
3079 
3080 	case sizeof (sin_t):	/* Complete IPv4 address */
3081 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3082 		    sizeof (sin_t));
3083 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3084 			if (tcp->tcp_debug) {
3085 				(void) strlog(TCP_MOD_ID, 0, 1,
3086 				    SL_ERROR|SL_TRACE,
3087 				    "tcp_bind: bad address parameter, "
3088 				    "offset %d, len %d",
3089 				    tbr->ADDR_offset, tbr->ADDR_length);
3090 			}
3091 			tcp_err_ack(tcp, mp, TPROTO, 0);
3092 			return;
3093 		}
3094 		/*
3095 		 * With sockets sockfs will accept bogus sin_family in
3096 		 * bind() and replace it with the family used in the socket
3097 		 * call.
3098 		 */
3099 		if (sin->sin_family != AF_INET ||
3100 		    tcp->tcp_family != AF_INET) {
3101 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3102 			return;
3103 		}
3104 		requested_port = ntohs(sin->sin_port);
3105 		tcp->tcp_ipversion = IPV4_VERSION;
3106 		v4addr = sin->sin_addr.s_addr;
3107 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3108 		break;
3109 
3110 	case sizeof (sin6_t): /* Complete IPv6 address */
3111 		sin6 = (sin6_t *)mi_offset_param(mp,
3112 		    tbr->ADDR_offset, sizeof (sin6_t));
3113 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3114 			if (tcp->tcp_debug) {
3115 				(void) strlog(TCP_MOD_ID, 0, 1,
3116 				    SL_ERROR|SL_TRACE,
3117 				    "tcp_bind: bad IPv6 address parameter, "
3118 				    "offset %d, len %d", tbr->ADDR_offset,
3119 				    tbr->ADDR_length);
3120 			}
3121 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3122 			return;
3123 		}
3124 		if (sin6->sin6_family != AF_INET6 ||
3125 		    tcp->tcp_family != AF_INET6) {
3126 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3127 			return;
3128 		}
3129 		requested_port = ntohs(sin6->sin6_port);
3130 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3131 		    IPV4_VERSION : IPV6_VERSION;
3132 		v6addr = sin6->sin6_addr;
3133 		break;
3134 
3135 	default:
3136 		if (tcp->tcp_debug) {
3137 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3138 			    "tcp_bind: bad address length, %d",
3139 			    tbr->ADDR_length);
3140 		}
3141 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3142 		return;
3143 	}
3144 	tcp->tcp_bound_source_v6 = v6addr;
3145 
3146 	/* Check for change in ipversion */
3147 	if (origipversion != tcp->tcp_ipversion) {
3148 		ASSERT(tcp->tcp_family == AF_INET6);
3149 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3150 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3151 		if (err) {
3152 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3153 			return;
3154 		}
3155 	}
3156 
3157 	/*
3158 	 * Initialize family specific fields. Copy of the src addr.
3159 	 * in tcp_t is needed for the lookup funcs.
3160 	 */
3161 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3162 		tcp->tcp_ip6h->ip6_src = v6addr;
3163 	} else {
3164 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3165 	}
3166 	tcp->tcp_ip_src_v6 = v6addr;
3167 
3168 	/*
3169 	 * For O_T_BIND_REQ:
3170 	 * Verify that the target port/addr is available, or choose
3171 	 * another.
3172 	 * For  T_BIND_REQ:
3173 	 * Verify that the target port/addr is available or fail.
3174 	 * In both cases when it succeeds the tcp is inserted in the
3175 	 * bind hash table. This ensures that the operation is atomic
3176 	 * under the lock on the hash bucket.
3177 	 */
3178 	bind_to_req_port_only = requested_port != 0 &&
3179 	    tbr->PRIM_type != O_T_BIND_REQ;
3180 	/*
3181 	 * Get a valid port (within the anonymous range and should not
3182 	 * be a privileged one) to use if the user has not given a port.
3183 	 * If multiple threads are here, they may all start with
3184 	 * with the same initial port. But, it should be fine as long as
3185 	 * tcp_bindi will ensure that no two threads will be assigned
3186 	 * the same port.
3187 	 *
3188 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3189 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3190 	 * unless TCP_ANONPRIVBIND option is set.
3191 	 */
3192 	mlptype = mlptSingle;
3193 	mlp_port = requested_port;
3194 	if (requested_port == 0) {
3195 		requested_port = tcp->tcp_anon_priv_bind ?
3196 		    tcp_get_next_priv_port(tcp) :
3197 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3198 			tcp, B_TRUE);
3199 		if (requested_port == 0) {
3200 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3201 			return;
3202 		}
3203 		user_specified = B_FALSE;
3204 
3205 		/*
3206 		 * If the user went through one of the RPC interfaces to create
3207 		 * this socket and RPC is MLP in this zone, then give him an
3208 		 * anonymous MLP.
3209 		 */
3210 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3211 		connp = tcp->tcp_connp;
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 		connp = tcp->tcp_connp;
3265 		if (is_system_labeled()) {
3266 			zone = crgetzone(cr);
3267 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3268 			    IPV6_VERSION, &v6addr,
3269 			    tcps->tcps_netstack->netstack_ip);
3270 			if (addrtype == mlptSingle) {
3271 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3272 				return;
3273 			}
3274 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3275 			    requested_port, addrtype);
3276 		}
3277 	}
3278 
3279 	if (mlptype != mlptSingle) {
3280 		if (secpolicy_net_bindmlp(cr) != 0) {
3281 			if (tcp->tcp_debug) {
3282 				(void) strlog(TCP_MOD_ID, 0, 1,
3283 				    SL_ERROR|SL_TRACE,
3284 				    "tcp_bind: no priv for multilevel port %d",
3285 				    requested_port);
3286 			}
3287 			tcp_err_ack(tcp, mp, TACCES, 0);
3288 			return;
3289 		}
3290 
3291 		/*
3292 		 * If we're specifically binding a shared IP address and the
3293 		 * port is MLP on shared addresses, then check to see if this
3294 		 * zone actually owns the MLP.  Reject if not.
3295 		 */
3296 		if (mlptype == mlptShared && addrtype == mlptShared) {
3297 			/*
3298 			 * No need to handle exclusive-stack zones since
3299 			 * ALL_ZONES only applies to the shared stack.
3300 			 */
3301 			zoneid_t mlpzone;
3302 
3303 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3304 			    htons(mlp_port));
3305 			if (connp->conn_zoneid != mlpzone) {
3306 				if (tcp->tcp_debug) {
3307 					(void) strlog(TCP_MOD_ID, 0, 1,
3308 					    SL_ERROR|SL_TRACE,
3309 					    "tcp_bind: attempt to bind port "
3310 					    "%d on shared addr in zone %d "
3311 					    "(should be %d)",
3312 					    mlp_port, connp->conn_zoneid,
3313 					    mlpzone);
3314 				}
3315 				tcp_err_ack(tcp, mp, TACCES, 0);
3316 				return;
3317 			}
3318 		}
3319 
3320 		if (!user_specified) {
3321 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3322 			    requested_port, B_TRUE);
3323 			if (err != 0) {
3324 				if (tcp->tcp_debug) {
3325 					(void) strlog(TCP_MOD_ID, 0, 1,
3326 					    SL_ERROR|SL_TRACE,
3327 					    "tcp_bind: cannot establish anon "
3328 					    "MLP for port %d",
3329 					    requested_port);
3330 				}
3331 				tcp_err_ack(tcp, mp, TSYSERR, err);
3332 				return;
3333 			}
3334 			connp->conn_anon_port = B_TRUE;
3335 		}
3336 		connp->conn_mlp_type = mlptype;
3337 	}
3338 
3339 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3340 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3341 
3342 	if (allocated_port == 0) {
3343 		connp->conn_mlp_type = mlptSingle;
3344 		if (connp->conn_anon_port) {
3345 			connp->conn_anon_port = B_FALSE;
3346 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3347 			    requested_port, B_FALSE);
3348 		}
3349 		if (bind_to_req_port_only) {
3350 			if (tcp->tcp_debug) {
3351 				(void) strlog(TCP_MOD_ID, 0, 1,
3352 				    SL_ERROR|SL_TRACE,
3353 				    "tcp_bind: requested addr busy");
3354 			}
3355 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3356 		} else {
3357 			/* If we are out of ports, fail the bind. */
3358 			if (tcp->tcp_debug) {
3359 				(void) strlog(TCP_MOD_ID, 0, 1,
3360 				    SL_ERROR|SL_TRACE,
3361 				    "tcp_bind: out of ports?");
3362 			}
3363 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3364 		}
3365 		return;
3366 	}
3367 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3368 do_bind:
3369 	if (!backlog_update) {
3370 		if (tcp->tcp_family == AF_INET)
3371 			sin->sin_port = htons(allocated_port);
3372 		else
3373 			sin6->sin6_port = htons(allocated_port);
3374 	}
3375 	if (tcp->tcp_family == AF_INET) {
3376 		if (tbr->CONIND_number != 0) {
3377 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3378 			    sizeof (sin_t));
3379 		} else {
3380 			/* Just verify the local IP address */
3381 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3382 		}
3383 	} else {
3384 		if (tbr->CONIND_number != 0) {
3385 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3386 			    sizeof (sin6_t));
3387 		} else {
3388 			/* Just verify the local IP address */
3389 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3390 			    IPV6_ADDR_LEN);
3391 		}
3392 	}
3393 	if (mp1 == NULL) {
3394 		if (connp->conn_anon_port) {
3395 			connp->conn_anon_port = B_FALSE;
3396 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3397 			    requested_port, B_FALSE);
3398 		}
3399 		connp->conn_mlp_type = mlptSingle;
3400 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3401 		return;
3402 	}
3403 
3404 	tbr->PRIM_type = T_BIND_ACK;
3405 	mp->b_datap->db_type = M_PCPROTO;
3406 
3407 	/* Chain in the reply mp for tcp_rput() */
3408 	mp1->b_cont = mp;
3409 	mp = mp1;
3410 
3411 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3412 	if (tcp->tcp_conn_req_max) {
3413 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3414 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3415 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3416 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3417 		/*
3418 		 * If this is a listener, do not reset the eager list
3419 		 * and other stuffs.  Note that we don't check if the
3420 		 * existing eager list meets the new tcp_conn_req_max
3421 		 * requirement.
3422 		 */
3423 		if (tcp->tcp_state != TCPS_LISTEN) {
3424 			tcp->tcp_state = TCPS_LISTEN;
3425 			/* Initialize the chain. Don't need the eager_lock */
3426 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3427 			tcp->tcp_eager_next_drop_q0 = tcp;
3428 			tcp->tcp_eager_prev_drop_q0 = tcp;
3429 			tcp->tcp_second_ctimer_threshold =
3430 			    tcps->tcps_ip_abort_linterval;
3431 		}
3432 	}
3433 
3434 	/*
3435 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3436 	 * processing continues in tcp_rput_other().
3437 	 */
3438 	if (tcp->tcp_family == AF_INET6) {
3439 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3440 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3441 	} else {
3442 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3443 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3444 	}
3445 	/*
3446 	 * If the bind cannot complete immediately
3447 	 * IP will arrange to call tcp_rput_other
3448 	 * when the bind completes.
3449 	 */
3450 	if (mp != NULL) {
3451 		tcp_rput_other(tcp, mp);
3452 	} else {
3453 		/*
3454 		 * Bind will be resumed later. Need to ensure
3455 		 * that conn doesn't disappear when that happens.
3456 		 * This will be decremented in ip_resume_tcp_bind().
3457 		 */
3458 		CONN_INC_REF(tcp->tcp_connp);
3459 	}
3460 }
3461 
3462 
3463 /*
3464  * If the "bind_to_req_port_only" parameter is set, if the requested port
3465  * number is available, return it, If not return 0
3466  *
3467  * If "bind_to_req_port_only" parameter is not set and
3468  * If the requested port number is available, return it.  If not, return
3469  * the first anonymous port we happen across.  If no anonymous ports are
3470  * available, return 0. addr is the requested local address, if any.
3471  *
3472  * In either case, when succeeding update the tcp_t to record the port number
3473  * and insert it in the bind hash table.
3474  *
3475  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3476  * without setting SO_REUSEADDR. This is needed so that they
3477  * can be viewed as two independent transport protocols.
3478  */
3479 static in_port_t
3480 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3481     int reuseaddr, boolean_t quick_connect,
3482     boolean_t bind_to_req_port_only, boolean_t user_specified)
3483 {
3484 	/* number of times we have run around the loop */
3485 	int count = 0;
3486 	/* maximum number of times to run around the loop */
3487 	int loopmax;
3488 	conn_t *connp = tcp->tcp_connp;
3489 	zoneid_t zoneid = connp->conn_zoneid;
3490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3491 
3492 	/*
3493 	 * Lookup for free addresses is done in a loop and "loopmax"
3494 	 * influences how long we spin in the loop
3495 	 */
3496 	if (bind_to_req_port_only) {
3497 		/*
3498 		 * If the requested port is busy, don't bother to look
3499 		 * for a new one. Setting loop maximum count to 1 has
3500 		 * that effect.
3501 		 */
3502 		loopmax = 1;
3503 	} else {
3504 		/*
3505 		 * If the requested port is busy, look for a free one
3506 		 * in the anonymous port range.
3507 		 * Set loopmax appropriately so that one does not look
3508 		 * forever in the case all of the anonymous ports are in use.
3509 		 */
3510 		if (tcp->tcp_anon_priv_bind) {
3511 			/*
3512 			 * loopmax =
3513 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3514 			 */
3515 			loopmax = IPPORT_RESERVED -
3516 			    tcps->tcps_min_anonpriv_port;
3517 		} else {
3518 			loopmax = (tcps->tcps_largest_anon_port -
3519 			    tcps->tcps_smallest_anon_port + 1);
3520 		}
3521 	}
3522 	do {
3523 		uint16_t	lport;
3524 		tf_t		*tbf;
3525 		tcp_t		*ltcp;
3526 		conn_t		*lconnp;
3527 
3528 		lport = htons(port);
3529 
3530 		/*
3531 		 * Ensure that the tcp_t is not currently in the bind hash.
3532 		 * Hold the lock on the hash bucket to ensure that
3533 		 * the duplicate check plus the insertion is an atomic
3534 		 * operation.
3535 		 *
3536 		 * This function does an inline lookup on the bind hash list
3537 		 * Make sure that we access only members of tcp_t
3538 		 * and that we don't look at tcp_tcp, since we are not
3539 		 * doing a CONN_INC_REF.
3540 		 */
3541 		tcp_bind_hash_remove(tcp);
3542 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3543 		mutex_enter(&tbf->tf_lock);
3544 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3545 		    ltcp = ltcp->tcp_bind_hash) {
3546 			boolean_t not_socket;
3547 			boolean_t exclbind;
3548 
3549 			if (lport != ltcp->tcp_lport)
3550 				continue;
3551 
3552 			lconnp = ltcp->tcp_connp;
3553 
3554 			/*
3555 			 * On a labeled system, we must treat bindings to ports
3556 			 * on shared IP addresses by sockets with MAC exemption
3557 			 * privilege as being in all zones, as there's
3558 			 * otherwise no way to identify the right receiver.
3559 			 */
3560 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3561 			    IPCL_ZONE_MATCH(connp,
3562 			    ltcp->tcp_connp->conn_zoneid)) &&
3563 			    !lconnp->conn_mac_exempt &&
3564 			    !connp->conn_mac_exempt)
3565 				continue;
3566 
3567 			/*
3568 			 * If TCP_EXCLBIND is set for either the bound or
3569 			 * binding endpoint, the semantics of bind
3570 			 * is changed according to the following.
3571 			 *
3572 			 * spec = specified address (v4 or v6)
3573 			 * unspec = unspecified address (v4 or v6)
3574 			 * A = specified addresses are different for endpoints
3575 			 *
3576 			 * bound	bind to		allowed
3577 			 * -------------------------------------
3578 			 * unspec	unspec		no
3579 			 * unspec	spec		no
3580 			 * spec		unspec		no
3581 			 * spec		spec		yes if A
3582 			 *
3583 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3584 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3585 			 *
3586 			 * Note:
3587 			 *
3588 			 * 1. Because of TLI semantics, an endpoint can go
3589 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3590 			 * TCPS_BOUND, depending on whether it is originally
3591 			 * a listener or not.  That is why we need to check
3592 			 * for states greater than or equal to TCPS_BOUND
3593 			 * here.
3594 			 *
3595 			 * 2. Ideally, we should only check for state equals
3596 			 * to TCPS_LISTEN. And the following check should be
3597 			 * added.
3598 			 *
3599 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3600 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3601 			 *		...
3602 			 * }
3603 			 *
3604 			 * The semantics will be changed to this.  If the
3605 			 * endpoint on the list is in state not equal to
3606 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3607 			 * set, let the bind succeed.
3608 			 *
3609 			 * Because of (1), we cannot do that for TLI
3610 			 * endpoints.  But we can do that for socket endpoints.
3611 			 * If in future, we can change this going back
3612 			 * semantics, we can use the above check for TLI also.
3613 			 */
3614 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3615 			    TCP_IS_SOCKET(tcp));
3616 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3617 
3618 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3619 			    (exclbind && (not_socket ||
3620 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3621 				if (V6_OR_V4_INADDR_ANY(
3622 				    ltcp->tcp_bound_source_v6) ||
3623 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3624 				    IN6_ARE_ADDR_EQUAL(laddr,
3625 				    &ltcp->tcp_bound_source_v6)) {
3626 					break;
3627 				}
3628 				continue;
3629 			}
3630 
3631 			/*
3632 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3633 			 * have disjoint port number spaces, if *_EXCLBIND
3634 			 * is not set and only if the application binds to a
3635 			 * specific port. We use the same autoassigned port
3636 			 * number space for IPv4 and IPv6 sockets.
3637 			 */
3638 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3639 			    bind_to_req_port_only)
3640 				continue;
3641 
3642 			/*
3643 			 * Ideally, we should make sure that the source
3644 			 * address, remote address, and remote port in the
3645 			 * four tuple for this tcp-connection is unique.
3646 			 * However, trying to find out the local source
3647 			 * address would require too much code duplication
3648 			 * with IP, since IP needs needs to have that code
3649 			 * to support userland TCP implementations.
3650 			 */
3651 			if (quick_connect &&
3652 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3653 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3654 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3655 				    &ltcp->tcp_remote_v6)))
3656 				continue;
3657 
3658 			if (!reuseaddr) {
3659 				/*
3660 				 * No socket option SO_REUSEADDR.
3661 				 * If existing port is bound to
3662 				 * a non-wildcard IP address
3663 				 * and the requesting stream is
3664 				 * bound to a distinct
3665 				 * different IP addresses
3666 				 * (non-wildcard, also), keep
3667 				 * going.
3668 				 */
3669 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3670 				    !V6_OR_V4_INADDR_ANY(
3671 				    ltcp->tcp_bound_source_v6) &&
3672 				    !IN6_ARE_ADDR_EQUAL(laddr,
3673 					&ltcp->tcp_bound_source_v6))
3674 					continue;
3675 				if (ltcp->tcp_state >= TCPS_BOUND) {
3676 					/*
3677 					 * This port is being used and
3678 					 * its state is >= TCPS_BOUND,
3679 					 * so we can't bind to it.
3680 					 */
3681 					break;
3682 				}
3683 			} else {
3684 				/*
3685 				 * socket option SO_REUSEADDR is set on the
3686 				 * binding tcp_t.
3687 				 *
3688 				 * If two streams are bound to
3689 				 * same IP address or both addr
3690 				 * and bound source are wildcards
3691 				 * (INADDR_ANY), we want to stop
3692 				 * searching.
3693 				 * We have found a match of IP source
3694 				 * address and source port, which is
3695 				 * refused regardless of the
3696 				 * SO_REUSEADDR setting, so we break.
3697 				 */
3698 				if (IN6_ARE_ADDR_EQUAL(laddr,
3699 				    &ltcp->tcp_bound_source_v6) &&
3700 				    (ltcp->tcp_state == TCPS_LISTEN ||
3701 					ltcp->tcp_state == TCPS_BOUND))
3702 					break;
3703 			}
3704 		}
3705 		if (ltcp != NULL) {
3706 			/* The port number is busy */
3707 			mutex_exit(&tbf->tf_lock);
3708 		} else {
3709 			/*
3710 			 * This port is ours. Insert in fanout and mark as
3711 			 * bound to prevent others from getting the port
3712 			 * number.
3713 			 */
3714 			tcp->tcp_state = TCPS_BOUND;
3715 			tcp->tcp_lport = htons(port);
3716 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3717 
3718 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3719 			    tcp->tcp_lport)] == tbf);
3720 			tcp_bind_hash_insert(tbf, tcp, 1);
3721 
3722 			mutex_exit(&tbf->tf_lock);
3723 
3724 			/*
3725 			 * We don't want tcp_next_port_to_try to "inherit"
3726 			 * a port number supplied by the user in a bind.
3727 			 */
3728 			if (user_specified)
3729 				return (port);
3730 
3731 			/*
3732 			 * This is the only place where tcp_next_port_to_try
3733 			 * is updated. After the update, it may or may not
3734 			 * be in the valid range.
3735 			 */
3736 			if (!tcp->tcp_anon_priv_bind)
3737 				tcps->tcps_next_port_to_try = port + 1;
3738 			return (port);
3739 		}
3740 
3741 		if (tcp->tcp_anon_priv_bind) {
3742 			port = tcp_get_next_priv_port(tcp);
3743 		} else {
3744 			if (count == 0 && user_specified) {
3745 				/*
3746 				 * We may have to return an anonymous port. So
3747 				 * get one to start with.
3748 				 */
3749 				port =
3750 				    tcp_update_next_port(
3751 					tcps->tcps_next_port_to_try,
3752 					tcp, B_TRUE);
3753 				user_specified = B_FALSE;
3754 			} else {
3755 				port = tcp_update_next_port(port + 1, tcp,
3756 				    B_FALSE);
3757 			}
3758 		}
3759 		if (port == 0)
3760 			break;
3761 
3762 		/*
3763 		 * Don't let this loop run forever in the case where
3764 		 * all of the anonymous ports are in use.
3765 		 */
3766 	} while (++count < loopmax);
3767 	return (0);
3768 }
3769 
3770 /*
3771  * tcp_clean_death / tcp_close_detached must not be called more than once
3772  * on a tcp. Thus every function that potentially calls tcp_clean_death
3773  * must check for the tcp state before calling tcp_clean_death.
3774  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3775  * tcp_timer_handler, all check for the tcp state.
3776  */
3777 /* ARGSUSED */
3778 void
3779 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3780 {
3781 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3782 
3783 	freemsg(mp);
3784 	if (tcp->tcp_state > TCPS_BOUND)
3785 	    (void) tcp_clean_death(((conn_t *)arg)->conn_tcp, ETIMEDOUT, 5);
3786 }
3787 
3788 /*
3789  * We are dying for some reason.  Try to do it gracefully.  (May be called
3790  * as writer.)
3791  *
3792  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3793  * done by a service procedure).
3794  * TBD - Should the return value distinguish between the tcp_t being
3795  * freed and it being reinitialized?
3796  */
3797 static int
3798 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3799 {
3800 	mblk_t	*mp;
3801 	queue_t	*q;
3802 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3803 
3804 	TCP_CLD_STAT(tag);
3805 
3806 #if TCP_TAG_CLEAN_DEATH
3807 	tcp->tcp_cleandeathtag = tag;
3808 #endif
3809 
3810 	if (tcp->tcp_fused)
3811 		tcp_unfuse(tcp);
3812 
3813 	if (tcp->tcp_linger_tid != 0 &&
3814 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3815 		tcp_stop_lingering(tcp);
3816 	}
3817 
3818 	ASSERT(tcp != NULL);
3819 	ASSERT((tcp->tcp_family == AF_INET &&
3820 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3821 	    (tcp->tcp_family == AF_INET6 &&
3822 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3823 	    tcp->tcp_ipversion == IPV6_VERSION)));
3824 
3825 	if (TCP_IS_DETACHED(tcp)) {
3826 		if (tcp->tcp_hard_binding) {
3827 			/*
3828 			 * Its an eager that we are dealing with. We close the
3829 			 * eager but in case a conn_ind has already gone to the
3830 			 * listener, let tcp_accept_finish() send a discon_ind
3831 			 * to the listener and drop the last reference. If the
3832 			 * listener doesn't even know about the eager i.e. the
3833 			 * conn_ind hasn't gone up, blow away the eager and drop
3834 			 * the last reference as well. If the conn_ind has gone
3835 			 * up, state should be BOUND. tcp_accept_finish
3836 			 * will figure out that the connection has received a
3837 			 * RST and will send a DISCON_IND to the application.
3838 			 */
3839 			tcp_closei_local(tcp);
3840 			if (!tcp->tcp_tconnind_started) {
3841 				CONN_DEC_REF(tcp->tcp_connp);
3842 			} else {
3843 				tcp->tcp_state = TCPS_BOUND;
3844 			}
3845 		} else {
3846 			tcp_close_detached(tcp);
3847 		}
3848 		return (0);
3849 	}
3850 
3851 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3852 
3853 	/*
3854 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3855 	 * is run) postpone cleaning up the endpoint until service routine
3856 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3857 	 * client_errno since tcp_close uses the client_errno field.
3858 	 */
3859 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3860 		if (err != 0)
3861 			tcp->tcp_client_errno = err;
3862 
3863 		tcp->tcp_deferred_clean_death = B_TRUE;
3864 		return (-1);
3865 	}
3866 
3867 	q = tcp->tcp_rq;
3868 
3869 	/* Trash all inbound data */
3870 	flushq(q, FLUSHALL);
3871 
3872 	/*
3873 	 * If we are at least part way open and there is error
3874 	 * (err==0 implies no error)
3875 	 * notify our client by a T_DISCON_IND.
3876 	 */
3877 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3878 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3879 		    !TCP_IS_SOCKET(tcp)) {
3880 			/*
3881 			 * Send M_FLUSH according to TPI. Because sockets will
3882 			 * (and must) ignore FLUSHR we do that only for TPI
3883 			 * endpoints and sockets in STREAMS mode.
3884 			 */
3885 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3886 		}
3887 		if (tcp->tcp_debug) {
3888 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3889 			    "tcp_clean_death: discon err %d", err);
3890 		}
3891 		mp = mi_tpi_discon_ind(NULL, err, 0);
3892 		if (mp != NULL) {
3893 			putnext(q, mp);
3894 		} else {
3895 			if (tcp->tcp_debug) {
3896 				(void) strlog(TCP_MOD_ID, 0, 1,
3897 				    SL_ERROR|SL_TRACE,
3898 				    "tcp_clean_death, sending M_ERROR");
3899 			}
3900 			(void) putnextctl1(q, M_ERROR, EPROTO);
3901 		}
3902 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3903 			/* SYN_SENT or SYN_RCVD */
3904 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3905 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3906 			/* ESTABLISHED or CLOSE_WAIT */
3907 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3908 		}
3909 	}
3910 
3911 	tcp_reinit(tcp);
3912 	return (-1);
3913 }
3914 
3915 /*
3916  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3917  * to expire, stop the wait and finish the close.
3918  */
3919 static void
3920 tcp_stop_lingering(tcp_t *tcp)
3921 {
3922 	clock_t	delta = 0;
3923 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3924 
3925 	tcp->tcp_linger_tid = 0;
3926 	if (tcp->tcp_state > TCPS_LISTEN) {
3927 		tcp_acceptor_hash_remove(tcp);
3928 		mutex_enter(&tcp->tcp_non_sq_lock);
3929 		if (tcp->tcp_flow_stopped) {
3930 			tcp_clrqfull(tcp);
3931 		}
3932 		mutex_exit(&tcp->tcp_non_sq_lock);
3933 
3934 		if (tcp->tcp_timer_tid != 0) {
3935 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3936 			tcp->tcp_timer_tid = 0;
3937 		}
3938 		/*
3939 		 * Need to cancel those timers which will not be used when
3940 		 * TCP is detached.  This has to be done before the tcp_wq
3941 		 * is set to the global queue.
3942 		 */
3943 		tcp_timers_stop(tcp);
3944 
3945 
3946 		tcp->tcp_detached = B_TRUE;
3947 		ASSERT(tcps->tcps_g_q != NULL);
3948 		tcp->tcp_rq = tcps->tcps_g_q;
3949 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3950 
3951 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3952 			tcp_time_wait_append(tcp);
3953 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3954 			goto finish;
3955 		}
3956 
3957 		/*
3958 		 * If delta is zero the timer event wasn't executed and was
3959 		 * successfully canceled. In this case we need to restart it
3960 		 * with the minimal delta possible.
3961 		 */
3962 		if (delta >= 0) {
3963 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3964 			    delta ? delta : 1);
3965 		}
3966 	} else {
3967 		tcp_closei_local(tcp);
3968 		CONN_DEC_REF(tcp->tcp_connp);
3969 	}
3970 finish:
3971 	/* Signal closing thread that it can complete close */
3972 	mutex_enter(&tcp->tcp_closelock);
3973 	tcp->tcp_detached = B_TRUE;
3974 	ASSERT(tcps->tcps_g_q != NULL);
3975 	tcp->tcp_rq = tcps->tcps_g_q;
3976 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3977 	tcp->tcp_closed = 1;
3978 	cv_signal(&tcp->tcp_closecv);
3979 	mutex_exit(&tcp->tcp_closelock);
3980 }
3981 
3982 /*
3983  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3984  * expires.
3985  */
3986 static void
3987 tcp_close_linger_timeout(void *arg)
3988 {
3989 	conn_t	*connp = (conn_t *)arg;
3990 	tcp_t 	*tcp = connp->conn_tcp;
3991 
3992 	tcp->tcp_client_errno = ETIMEDOUT;
3993 	tcp_stop_lingering(tcp);
3994 }
3995 
3996 static int
3997 tcp_close(queue_t *q, int flags)
3998 {
3999 	conn_t		*connp = Q_TO_CONN(q);
4000 	tcp_t		*tcp = connp->conn_tcp;
4001 	mblk_t 		*mp = &tcp->tcp_closemp;
4002 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4003 	boolean_t	linger_interrupted = B_FALSE;
4004 	mblk_t		*bp;
4005 
4006 	ASSERT(WR(q)->q_next == NULL);
4007 	ASSERT(connp->conn_ref >= 2);
4008 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
4009 
4010 	/*
4011 	 * We are being closed as /dev/tcp or /dev/tcp6.
4012 	 *
4013 	 * Mark the conn as closing. ill_pending_mp_add will not
4014 	 * add any mp to the pending mp list, after this conn has
4015 	 * started closing. Same for sq_pending_mp_add
4016 	 */
4017 	mutex_enter(&connp->conn_lock);
4018 	connp->conn_state_flags |= CONN_CLOSING;
4019 	if (connp->conn_oper_pending_ill != NULL)
4020 		conn_ioctl_cleanup_reqd = B_TRUE;
4021 	CONN_INC_REF_LOCKED(connp);
4022 	mutex_exit(&connp->conn_lock);
4023 	tcp->tcp_closeflags = (uint8_t)flags;
4024 	ASSERT(connp->conn_ref >= 3);
4025 
4026 	/*
4027 	 * tcp_closemp_used is used below without any protection of a lock
4028 	 * as we don't expect any one else to use it concurrently at this
4029 	 * point otherwise it would be a major defect.
4030 	 */
4031 
4032 	if (mp->b_prev == NULL)
4033 		tcp->tcp_closemp_used = B_TRUE;
4034 	else
4035 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4036 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4037 
4038 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4039 
4040 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4041 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4042 
4043 	mutex_enter(&tcp->tcp_closelock);
4044 	while (!tcp->tcp_closed) {
4045 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4046 			/*
4047 			 * We got interrupted. Check if we are lingering,
4048 			 * if yes, post a message to stop and wait until
4049 			 * tcp_closed is set. If we aren't lingering,
4050 			 * just go back around.
4051 			 */
4052 			if (tcp->tcp_linger &&
4053 			    tcp->tcp_lingertime > 0 &&
4054 			    !linger_interrupted) {
4055 				mutex_exit(&tcp->tcp_closelock);
4056 				/* Entering squeue, bump ref count. */
4057 				CONN_INC_REF(connp);
4058 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4059 				squeue_enter(connp->conn_sqp, bp,
4060 				    tcp_linger_interrupted, connp,
4061 				    SQTAG_IP_TCP_CLOSE);
4062 				linger_interrupted = B_TRUE;
4063 				mutex_enter(&tcp->tcp_closelock);
4064 			}
4065 		}
4066 	}
4067 	mutex_exit(&tcp->tcp_closelock);
4068 
4069 	/*
4070 	 * In the case of listener streams that have eagers in the q or q0
4071 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4072 	 * tcp_wq of the eagers point to our queues. By waiting for the
4073 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4074 	 * up their queue pointers and also dropped their references to us.
4075 	 */
4076 	if (tcp->tcp_wait_for_eagers) {
4077 		mutex_enter(&connp->conn_lock);
4078 		while (connp->conn_ref != 1) {
4079 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4080 		}
4081 		mutex_exit(&connp->conn_lock);
4082 	}
4083 	/*
4084 	 * ioctl cleanup. The mp is queued in the
4085 	 * ill_pending_mp or in the sq_pending_mp.
4086 	 */
4087 	if (conn_ioctl_cleanup_reqd)
4088 		conn_ioctl_cleanup(connp);
4089 
4090 	qprocsoff(q);
4091 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4092 
4093 	tcp->tcp_cpid = -1;
4094 
4095 	/*
4096 	 * Drop IP's reference on the conn. This is the last reference
4097 	 * on the connp if the state was less than established. If the
4098 	 * connection has gone into timewait state, then we will have
4099 	 * one ref for the TCP and one more ref (total of two) for the
4100 	 * classifier connected hash list (a timewait connections stays
4101 	 * in connected hash till closed).
4102 	 *
4103 	 * We can't assert the references because there might be other
4104 	 * transient reference places because of some walkers or queued
4105 	 * packets in squeue for the timewait state.
4106 	 */
4107 	CONN_DEC_REF(connp);
4108 	q->q_ptr = WR(q)->q_ptr = NULL;
4109 	return (0);
4110 }
4111 
4112 static int
4113 tcpclose_accept(queue_t *q)
4114 {
4115 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4116 
4117 	/*
4118 	 * We had opened an acceptor STREAM for sockfs which is
4119 	 * now being closed due to some error.
4120 	 */
4121 	qprocsoff(q);
4122 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4123 	q->q_ptr = WR(q)->q_ptr = NULL;
4124 	return (0);
4125 }
4126 
4127 /*
4128  * Called by tcp_close() routine via squeue when lingering is
4129  * interrupted by a signal.
4130  */
4131 
4132 /* ARGSUSED */
4133 static void
4134 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4135 {
4136 	conn_t	*connp = (conn_t *)arg;
4137 	tcp_t	*tcp = connp->conn_tcp;
4138 
4139 	freeb(mp);
4140 	if (tcp->tcp_linger_tid != 0 &&
4141 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4142 		tcp_stop_lingering(tcp);
4143 		tcp->tcp_client_errno = EINTR;
4144 	}
4145 }
4146 
4147 /*
4148  * Called by streams close routine via squeues when our client blows off her
4149  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4150  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4151  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4152  * acked.
4153  *
4154  * NOTE: tcp_close potentially returns error when lingering.
4155  * However, the stream head currently does not pass these errors
4156  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4157  * errors to the application (from tsleep()) and not errors
4158  * like ECONNRESET caused by receiving a reset packet.
4159  */
4160 
4161 /* ARGSUSED */
4162 static void
4163 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4164 {
4165 	char	*msg;
4166 	conn_t	*connp = (conn_t *)arg;
4167 	tcp_t	*tcp = connp->conn_tcp;
4168 	clock_t	delta = 0;
4169 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4170 
4171 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4172 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4173 
4174 	/* Cancel any pending timeout */
4175 	if (tcp->tcp_ordrelid != 0) {
4176 		if (tcp->tcp_timeout) {
4177 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4178 		}
4179 		tcp->tcp_ordrelid = 0;
4180 		tcp->tcp_timeout = B_FALSE;
4181 	}
4182 
4183 	mutex_enter(&tcp->tcp_eager_lock);
4184 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4185 		/* Cleanup for listener */
4186 		tcp_eager_cleanup(tcp, 0);
4187 		tcp->tcp_wait_for_eagers = 1;
4188 	}
4189 	mutex_exit(&tcp->tcp_eager_lock);
4190 
4191 	connp->conn_mdt_ok = B_FALSE;
4192 	tcp->tcp_mdt = B_FALSE;
4193 
4194 	connp->conn_lso_ok = B_FALSE;
4195 	tcp->tcp_lso = B_FALSE;
4196 
4197 	msg = NULL;
4198 	switch (tcp->tcp_state) {
4199 	case TCPS_CLOSED:
4200 	case TCPS_IDLE:
4201 	case TCPS_BOUND:
4202 	case TCPS_LISTEN:
4203 		break;
4204 	case TCPS_SYN_SENT:
4205 		msg = "tcp_close, during connect";
4206 		break;
4207 	case TCPS_SYN_RCVD:
4208 		/*
4209 		 * Close during the connect 3-way handshake
4210 		 * but here there may or may not be pending data
4211 		 * already on queue. Process almost same as in
4212 		 * the ESTABLISHED state.
4213 		 */
4214 		/* FALLTHRU */
4215 	default:
4216 		if (tcp->tcp_fused)
4217 			tcp_unfuse(tcp);
4218 
4219 		/*
4220 		 * If SO_LINGER has set a zero linger time, abort the
4221 		 * connection with a reset.
4222 		 */
4223 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4224 			msg = "tcp_close, zero lingertime";
4225 			break;
4226 		}
4227 
4228 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4229 		/*
4230 		 * Abort connection if there is unread data queued.
4231 		 */
4232 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4233 			msg = "tcp_close, unread data";
4234 			break;
4235 		}
4236 		/*
4237 		 * tcp_hard_bound is now cleared thus all packets go through
4238 		 * tcp_lookup. This fact is used by tcp_detach below.
4239 		 *
4240 		 * We have done a qwait() above which could have possibly
4241 		 * drained more messages in turn causing transition to a
4242 		 * different state. Check whether we have to do the rest
4243 		 * of the processing or not.
4244 		 */
4245 		if (tcp->tcp_state <= TCPS_LISTEN)
4246 			break;
4247 
4248 		/*
4249 		 * Transmit the FIN before detaching the tcp_t.
4250 		 * After tcp_detach returns this queue/perimeter
4251 		 * no longer owns the tcp_t thus others can modify it.
4252 		 */
4253 		(void) tcp_xmit_end(tcp);
4254 
4255 		/*
4256 		 * If lingering on close then wait until the fin is acked,
4257 		 * the SO_LINGER time passes, or a reset is sent/received.
4258 		 */
4259 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4260 		    !(tcp->tcp_fin_acked) &&
4261 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4262 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4263 				tcp->tcp_client_errno = EWOULDBLOCK;
4264 			} else if (tcp->tcp_client_errno == 0) {
4265 
4266 				ASSERT(tcp->tcp_linger_tid == 0);
4267 
4268 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4269 				    tcp_close_linger_timeout,
4270 				    tcp->tcp_lingertime * hz);
4271 
4272 				/* tcp_close_linger_timeout will finish close */
4273 				if (tcp->tcp_linger_tid == 0)
4274 					tcp->tcp_client_errno = ENOSR;
4275 				else
4276 					return;
4277 			}
4278 
4279 			/*
4280 			 * Check if we need to detach or just close
4281 			 * the instance.
4282 			 */
4283 			if (tcp->tcp_state <= TCPS_LISTEN)
4284 				break;
4285 		}
4286 
4287 		/*
4288 		 * Make sure that no other thread will access the tcp_rq of
4289 		 * this instance (through lookups etc.) as tcp_rq will go
4290 		 * away shortly.
4291 		 */
4292 		tcp_acceptor_hash_remove(tcp);
4293 
4294 		mutex_enter(&tcp->tcp_non_sq_lock);
4295 		if (tcp->tcp_flow_stopped) {
4296 			tcp_clrqfull(tcp);
4297 		}
4298 		mutex_exit(&tcp->tcp_non_sq_lock);
4299 
4300 		if (tcp->tcp_timer_tid != 0) {
4301 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4302 			tcp->tcp_timer_tid = 0;
4303 		}
4304 		/*
4305 		 * Need to cancel those timers which will not be used when
4306 		 * TCP is detached.  This has to be done before the tcp_wq
4307 		 * is set to the global queue.
4308 		 */
4309 		tcp_timers_stop(tcp);
4310 
4311 		tcp->tcp_detached = B_TRUE;
4312 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4313 			tcp_time_wait_append(tcp);
4314 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4315 			ASSERT(connp->conn_ref >= 3);
4316 			goto finish;
4317 		}
4318 
4319 		/*
4320 		 * If delta is zero the timer event wasn't executed and was
4321 		 * successfully canceled. In this case we need to restart it
4322 		 * with the minimal delta possible.
4323 		 */
4324 		if (delta >= 0)
4325 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4326 			    delta ? delta : 1);
4327 
4328 		ASSERT(connp->conn_ref >= 3);
4329 		goto finish;
4330 	}
4331 
4332 	/* Detach did not complete. Still need to remove q from stream. */
4333 	if (msg) {
4334 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4335 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4336 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4337 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4338 		    tcp->tcp_state == TCPS_SYN_RCVD)
4339 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4340 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4341 	}
4342 
4343 	tcp_closei_local(tcp);
4344 	CONN_DEC_REF(connp);
4345 	ASSERT(connp->conn_ref >= 2);
4346 
4347 finish:
4348 	/*
4349 	 * Although packets are always processed on the correct
4350 	 * tcp's perimeter and access is serialized via squeue's,
4351 	 * IP still needs a queue when sending packets in time_wait
4352 	 * state so use WR(tcps_g_q) till ip_output() can be
4353 	 * changed to deal with just connp. For read side, we
4354 	 * could have set tcp_rq to NULL but there are some cases
4355 	 * in tcp_rput_data() from early days of this code which
4356 	 * do a putnext without checking if tcp is closed. Those
4357 	 * need to be identified before both tcp_rq and tcp_wq
4358 	 * can be set to NULL and tcps_g_q can disappear forever.
4359 	 */
4360 	mutex_enter(&tcp->tcp_closelock);
4361 	/*
4362 	 * Don't change the queues in the case of a listener that has
4363 	 * eagers in its q or q0. It could surprise the eagers.
4364 	 * Instead wait for the eagers outside the squeue.
4365 	 */
4366 	if (!tcp->tcp_wait_for_eagers) {
4367 		tcp->tcp_detached = B_TRUE;
4368 		/*
4369 		 * When default queue is closing we set tcps_g_q to NULL
4370 		 * after the close is done.
4371 		 */
4372 		ASSERT(tcps->tcps_g_q != NULL);
4373 		tcp->tcp_rq = tcps->tcps_g_q;
4374 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4375 	}
4376 
4377 	/* Signal tcp_close() to finish closing. */
4378 	tcp->tcp_closed = 1;
4379 	cv_signal(&tcp->tcp_closecv);
4380 	mutex_exit(&tcp->tcp_closelock);
4381 }
4382 
4383 
4384 /*
4385  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4386  * Some stream heads get upset if they see these later on as anything but NULL.
4387  */
4388 static void
4389 tcp_close_mpp(mblk_t **mpp)
4390 {
4391 	mblk_t	*mp;
4392 
4393 	if ((mp = *mpp) != NULL) {
4394 		do {
4395 			mp->b_next = NULL;
4396 			mp->b_prev = NULL;
4397 		} while ((mp = mp->b_cont) != NULL);
4398 
4399 		mp = *mpp;
4400 		*mpp = NULL;
4401 		freemsg(mp);
4402 	}
4403 }
4404 
4405 /* Do detached close. */
4406 static void
4407 tcp_close_detached(tcp_t *tcp)
4408 {
4409 	if (tcp->tcp_fused)
4410 		tcp_unfuse(tcp);
4411 
4412 	/*
4413 	 * Clustering code serializes TCP disconnect callbacks and
4414 	 * cluster tcp list walks by blocking a TCP disconnect callback
4415 	 * if a cluster tcp list walk is in progress. This ensures
4416 	 * accurate accounting of TCPs in the cluster code even though
4417 	 * the TCP list walk itself is not atomic.
4418 	 */
4419 	tcp_closei_local(tcp);
4420 	CONN_DEC_REF(tcp->tcp_connp);
4421 }
4422 
4423 /*
4424  * Stop all TCP timers, and free the timer mblks if requested.
4425  */
4426 void
4427 tcp_timers_stop(tcp_t *tcp)
4428 {
4429 	if (tcp->tcp_timer_tid != 0) {
4430 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4431 		tcp->tcp_timer_tid = 0;
4432 	}
4433 	if (tcp->tcp_ka_tid != 0) {
4434 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4435 		tcp->tcp_ka_tid = 0;
4436 	}
4437 	if (tcp->tcp_ack_tid != 0) {
4438 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4439 		tcp->tcp_ack_tid = 0;
4440 	}
4441 	if (tcp->tcp_push_tid != 0) {
4442 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4443 		tcp->tcp_push_tid = 0;
4444 	}
4445 }
4446 
4447 /*
4448  * The tcp_t is going away. Remove it from all lists and set it
4449  * to TCPS_CLOSED. The freeing up of memory is deferred until
4450  * tcp_inactive. This is needed since a thread in tcp_rput might have
4451  * done a CONN_INC_REF on this structure before it was removed from the
4452  * hashes.
4453  */
4454 static void
4455 tcp_closei_local(tcp_t *tcp)
4456 {
4457 	ire_t 	*ire;
4458 	conn_t	*connp = tcp->tcp_connp;
4459 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4460 
4461 	if (!TCP_IS_SOCKET(tcp))
4462 		tcp_acceptor_hash_remove(tcp);
4463 
4464 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4465 	tcp->tcp_ibsegs = 0;
4466 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4467 	tcp->tcp_obsegs = 0;
4468 
4469 	/*
4470 	 * If we are an eager connection hanging off a listener that
4471 	 * hasn't formally accepted the connection yet, get off his
4472 	 * list and blow off any data that we have accumulated.
4473 	 */
4474 	if (tcp->tcp_listener != NULL) {
4475 		tcp_t	*listener = tcp->tcp_listener;
4476 		mutex_enter(&listener->tcp_eager_lock);
4477 		/*
4478 		 * tcp_tconnind_started == B_TRUE means that the
4479 		 * conn_ind has already gone to listener. At
4480 		 * this point, eager will be closed but we
4481 		 * leave it in listeners eager list so that
4482 		 * if listener decides to close without doing
4483 		 * accept, we can clean this up. In tcp_wput_accept
4484 		 * we take care of the case of accept on closed
4485 		 * eager.
4486 		 */
4487 		if (!tcp->tcp_tconnind_started) {
4488 			tcp_eager_unlink(tcp);
4489 			mutex_exit(&listener->tcp_eager_lock);
4490 			/*
4491 			 * We don't want to have any pointers to the
4492 			 * listener queue, after we have released our
4493 			 * reference on the listener
4494 			 */
4495 			ASSERT(tcps->tcps_g_q != NULL);
4496 			tcp->tcp_rq = tcps->tcps_g_q;
4497 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4498 			CONN_DEC_REF(listener->tcp_connp);
4499 		} else {
4500 			mutex_exit(&listener->tcp_eager_lock);
4501 		}
4502 	}
4503 
4504 	/* Stop all the timers */
4505 	tcp_timers_stop(tcp);
4506 
4507 	if (tcp->tcp_state == TCPS_LISTEN) {
4508 		if (tcp->tcp_ip_addr_cache) {
4509 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4510 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4511 			tcp->tcp_ip_addr_cache = NULL;
4512 		}
4513 	}
4514 	mutex_enter(&tcp->tcp_non_sq_lock);
4515 	if (tcp->tcp_flow_stopped)
4516 		tcp_clrqfull(tcp);
4517 	mutex_exit(&tcp->tcp_non_sq_lock);
4518 
4519 	tcp_bind_hash_remove(tcp);
4520 	/*
4521 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4522 	 * is trying to remove this tcp from the time wait list, we will
4523 	 * block in tcp_time_wait_remove while trying to acquire the
4524 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4525 	 * requires the ipcl_hash_remove to be ordered after the
4526 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4527 	 */
4528 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4529 		(void) tcp_time_wait_remove(tcp, NULL);
4530 	CL_INET_DISCONNECT(tcp);
4531 	ipcl_hash_remove(connp);
4532 
4533 	/*
4534 	 * Delete the cached ire in conn_ire_cache and also mark
4535 	 * the conn as CONDEMNED
4536 	 */
4537 	mutex_enter(&connp->conn_lock);
4538 	connp->conn_state_flags |= CONN_CONDEMNED;
4539 	ire = connp->conn_ire_cache;
4540 	connp->conn_ire_cache = NULL;
4541 	mutex_exit(&connp->conn_lock);
4542 	if (ire != NULL)
4543 		IRE_REFRELE_NOTR(ire);
4544 
4545 	/* Need to cleanup any pending ioctls */
4546 	ASSERT(tcp->tcp_time_wait_next == NULL);
4547 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4548 	ASSERT(tcp->tcp_time_wait_expire == 0);
4549 	tcp->tcp_state = TCPS_CLOSED;
4550 
4551 	/* Release any SSL context */
4552 	if (tcp->tcp_kssl_ent != NULL) {
4553 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4554 		tcp->tcp_kssl_ent = NULL;
4555 	}
4556 	if (tcp->tcp_kssl_ctx != NULL) {
4557 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4558 		tcp->tcp_kssl_ctx = NULL;
4559 	}
4560 	tcp->tcp_kssl_pending = B_FALSE;
4561 
4562 	tcp_ipsec_cleanup(tcp);
4563 }
4564 
4565 /*
4566  * tcp is dying (called from ipcl_conn_destroy and error cases).
4567  * Free the tcp_t in either case.
4568  */
4569 void
4570 tcp_free(tcp_t *tcp)
4571 {
4572 	mblk_t	*mp;
4573 	ip6_pkt_t	*ipp;
4574 
4575 	ASSERT(tcp != NULL);
4576 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4577 
4578 	tcp->tcp_rq = NULL;
4579 	tcp->tcp_wq = NULL;
4580 
4581 	tcp_close_mpp(&tcp->tcp_xmit_head);
4582 	tcp_close_mpp(&tcp->tcp_reass_head);
4583 	if (tcp->tcp_rcv_list != NULL) {
4584 		/* Free b_next chain */
4585 		tcp_close_mpp(&tcp->tcp_rcv_list);
4586 	}
4587 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4588 		freemsg(mp);
4589 	}
4590 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4591 		freemsg(mp);
4592 	}
4593 
4594 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4595 		freeb(tcp->tcp_fused_sigurg_mp);
4596 		tcp->tcp_fused_sigurg_mp = NULL;
4597 	}
4598 
4599 	if (tcp->tcp_sack_info != NULL) {
4600 		if (tcp->tcp_notsack_list != NULL) {
4601 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4602 		}
4603 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4604 	}
4605 
4606 	if (tcp->tcp_hopopts != NULL) {
4607 		mi_free(tcp->tcp_hopopts);
4608 		tcp->tcp_hopopts = NULL;
4609 		tcp->tcp_hopoptslen = 0;
4610 	}
4611 	ASSERT(tcp->tcp_hopoptslen == 0);
4612 	if (tcp->tcp_dstopts != NULL) {
4613 		mi_free(tcp->tcp_dstopts);
4614 		tcp->tcp_dstopts = NULL;
4615 		tcp->tcp_dstoptslen = 0;
4616 	}
4617 	ASSERT(tcp->tcp_dstoptslen == 0);
4618 	if (tcp->tcp_rtdstopts != NULL) {
4619 		mi_free(tcp->tcp_rtdstopts);
4620 		tcp->tcp_rtdstopts = NULL;
4621 		tcp->tcp_rtdstoptslen = 0;
4622 	}
4623 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4624 	if (tcp->tcp_rthdr != NULL) {
4625 		mi_free(tcp->tcp_rthdr);
4626 		tcp->tcp_rthdr = NULL;
4627 		tcp->tcp_rthdrlen = 0;
4628 	}
4629 	ASSERT(tcp->tcp_rthdrlen == 0);
4630 
4631 	ipp = &tcp->tcp_sticky_ipp;
4632 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4633 	    IPPF_RTHDR))
4634 		ip6_pkt_free(ipp);
4635 
4636 	/*
4637 	 * Free memory associated with the tcp/ip header template.
4638 	 */
4639 
4640 	if (tcp->tcp_iphc != NULL)
4641 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4642 
4643 	/*
4644 	 * Following is really a blowing away a union.
4645 	 * It happens to have exactly two members of identical size
4646 	 * the following code is enough.
4647 	 */
4648 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4649 
4650 	if (tcp->tcp_tracebuf != NULL) {
4651 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4652 		tcp->tcp_tracebuf = NULL;
4653 	}
4654 }
4655 
4656 
4657 /*
4658  * Put a connection confirmation message upstream built from the
4659  * address information within 'iph' and 'tcph'.  Report our success or failure.
4660  */
4661 static boolean_t
4662 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4663     mblk_t **defermp)
4664 {
4665 	sin_t	sin;
4666 	sin6_t	sin6;
4667 	mblk_t	*mp;
4668 	char	*optp = NULL;
4669 	int	optlen = 0;
4670 	cred_t	*cr;
4671 
4672 	if (defermp != NULL)
4673 		*defermp = NULL;
4674 
4675 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4676 		/*
4677 		 * Return in T_CONN_CON results of option negotiation through
4678 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4679 		 * negotiation, then what is received from remote end needs
4680 		 * to be taken into account but there is no such thing (yet?)
4681 		 * in our TCP/IP.
4682 		 * Note: We do not use mi_offset_param() here as
4683 		 * tcp_opts_conn_req contents do not directly come from
4684 		 * an application and are either generated in kernel or
4685 		 * from user input that was already verified.
4686 		 */
4687 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4688 		optp = (char *)(mp->b_rptr +
4689 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4690 		optlen = (int)
4691 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4692 	}
4693 
4694 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4695 		ipha_t *ipha = (ipha_t *)iphdr;
4696 
4697 		/* packet is IPv4 */
4698 		if (tcp->tcp_family == AF_INET) {
4699 			sin = sin_null;
4700 			sin.sin_addr.s_addr = ipha->ipha_src;
4701 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4702 			sin.sin_family = AF_INET;
4703 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4704 			    (int)sizeof (sin_t), optp, optlen);
4705 		} else {
4706 			sin6 = sin6_null;
4707 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4708 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4709 			sin6.sin6_family = AF_INET6;
4710 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4711 			    (int)sizeof (sin6_t), optp, optlen);
4712 
4713 		}
4714 	} else {
4715 		ip6_t	*ip6h = (ip6_t *)iphdr;
4716 
4717 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4718 		ASSERT(tcp->tcp_family == AF_INET6);
4719 		sin6 = sin6_null;
4720 		sin6.sin6_addr = ip6h->ip6_src;
4721 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4722 		sin6.sin6_family = AF_INET6;
4723 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4724 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4725 		    (int)sizeof (sin6_t), optp, optlen);
4726 	}
4727 
4728 	if (!mp)
4729 		return (B_FALSE);
4730 
4731 	if ((cr = DB_CRED(idmp)) != NULL) {
4732 		mblk_setcred(mp, cr);
4733 		DB_CPID(mp) = DB_CPID(idmp);
4734 	}
4735 
4736 	if (defermp == NULL)
4737 		putnext(tcp->tcp_rq, mp);
4738 	else
4739 		*defermp = mp;
4740 
4741 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4742 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4743 	return (B_TRUE);
4744 }
4745 
4746 /*
4747  * Defense for the SYN attack -
4748  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4749  *    one from the list of droppable eagers. This list is a subset of q0.
4750  *    see comments before the definition of MAKE_DROPPABLE().
4751  * 2. Don't drop a SYN request before its first timeout. This gives every
4752  *    request at least til the first timeout to complete its 3-way handshake.
4753  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4754  *    requests currently on the queue that has timed out. This will be used
4755  *    as an indicator of whether an attack is under way, so that appropriate
4756  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4757  *    either when eager goes into ESTABLISHED, or gets freed up.)
4758  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4759  *    # of timeout drops back to <= q0len/32 => SYN alert off
4760  */
4761 static boolean_t
4762 tcp_drop_q0(tcp_t *tcp)
4763 {
4764 	tcp_t	*eager;
4765 	mblk_t	*mp;
4766 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4767 
4768 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4769 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4770 
4771 	/* Pick oldest eager from the list of droppable eagers */
4772 	eager = tcp->tcp_eager_prev_drop_q0;
4773 
4774 	/* If list is empty. return B_FALSE */
4775 	if (eager == tcp) {
4776 		return (B_FALSE);
4777 	}
4778 
4779 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4780 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4781 		return (B_FALSE);
4782 
4783 	/*
4784 	 * Take this eager out from the list of droppable eagers since we are
4785 	 * going to drop it.
4786 	 */
4787 	MAKE_UNDROPPABLE(eager);
4788 
4789 	if (tcp->tcp_debug) {
4790 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4791 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4792 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4793 		    tcp->tcp_conn_req_cnt_q0,
4794 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4795 	}
4796 
4797 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4798 
4799 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4800 	CONN_INC_REF(eager->tcp_connp);
4801 
4802 	/* Mark the IRE created for this SYN request temporary */
4803 	tcp_ip_ire_mark_advice(eager);
4804 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4805 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4806 
4807 	return (B_TRUE);
4808 }
4809 
4810 int
4811 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4812     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4813 {
4814 	tcp_t 		*ltcp = lconnp->conn_tcp;
4815 	tcp_t		*tcp = connp->conn_tcp;
4816 	mblk_t		*tpi_mp;
4817 	ipha_t		*ipha;
4818 	ip6_t		*ip6h;
4819 	sin6_t 		sin6;
4820 	in6_addr_t 	v6dst;
4821 	int		err;
4822 	int		ifindex = 0;
4823 	cred_t		*cr;
4824 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4825 
4826 	if (ipvers == IPV4_VERSION) {
4827 		ipha = (ipha_t *)mp->b_rptr;
4828 
4829 		connp->conn_send = ip_output;
4830 		connp->conn_recv = tcp_input;
4831 
4832 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4833 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4834 
4835 		sin6 = sin6_null;
4836 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4837 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4838 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4839 		sin6.sin6_family = AF_INET6;
4840 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4841 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4842 		if (tcp->tcp_recvdstaddr) {
4843 			sin6_t	sin6d;
4844 
4845 			sin6d = sin6_null;
4846 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4847 			    &sin6d.sin6_addr);
4848 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4849 			sin6d.sin6_family = AF_INET;
4850 			tpi_mp = mi_tpi_extconn_ind(NULL,
4851 			    (char *)&sin6d, sizeof (sin6_t),
4852 			    (char *)&tcp,
4853 			    (t_scalar_t)sizeof (intptr_t),
4854 			    (char *)&sin6d, sizeof (sin6_t),
4855 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4856 		} else {
4857 			tpi_mp = mi_tpi_conn_ind(NULL,
4858 			    (char *)&sin6, sizeof (sin6_t),
4859 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4860 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4861 		}
4862 	} else {
4863 		ip6h = (ip6_t *)mp->b_rptr;
4864 
4865 		connp->conn_send = ip_output_v6;
4866 		connp->conn_recv = tcp_input;
4867 
4868 		connp->conn_srcv6 = ip6h->ip6_dst;
4869 		connp->conn_remv6 = ip6h->ip6_src;
4870 
4871 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4872 		ifindex = (int)DB_CKSUMSTUFF(mp);
4873 		DB_CKSUMSTUFF(mp) = 0;
4874 
4875 		sin6 = sin6_null;
4876 		sin6.sin6_addr = ip6h->ip6_src;
4877 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4878 		sin6.sin6_family = AF_INET6;
4879 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4880 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4881 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4882 
4883 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4884 			/* Pass up the scope_id of remote addr */
4885 			sin6.sin6_scope_id = ifindex;
4886 		} else {
4887 			sin6.sin6_scope_id = 0;
4888 		}
4889 		if (tcp->tcp_recvdstaddr) {
4890 			sin6_t	sin6d;
4891 
4892 			sin6d = sin6_null;
4893 			sin6.sin6_addr = ip6h->ip6_dst;
4894 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4895 			sin6d.sin6_family = AF_INET;
4896 			tpi_mp = mi_tpi_extconn_ind(NULL,
4897 			    (char *)&sin6d, sizeof (sin6_t),
4898 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4899 			    (char *)&sin6d, sizeof (sin6_t),
4900 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4901 		} else {
4902 			tpi_mp = mi_tpi_conn_ind(NULL,
4903 			    (char *)&sin6, sizeof (sin6_t),
4904 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4905 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4906 		}
4907 	}
4908 
4909 	if (tpi_mp == NULL)
4910 		return (ENOMEM);
4911 
4912 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4913 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4914 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4915 	connp->conn_fully_bound = B_FALSE;
4916 
4917 	if (tcps->tcps_trace)
4918 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4919 
4920 	/* Inherit information from the "parent" */
4921 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4922 	tcp->tcp_family = ltcp->tcp_family;
4923 	tcp->tcp_wq = ltcp->tcp_wq;
4924 	tcp->tcp_rq = ltcp->tcp_rq;
4925 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4926 	tcp->tcp_detached = B_TRUE;
4927 	if ((err = tcp_init_values(tcp)) != 0) {
4928 		freemsg(tpi_mp);
4929 		return (err);
4930 	}
4931 
4932 	if (ipvers == IPV4_VERSION) {
4933 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4934 			freemsg(tpi_mp);
4935 			return (err);
4936 		}
4937 		ASSERT(tcp->tcp_ipha != NULL);
4938 	} else {
4939 		/* ifindex must be already set */
4940 		ASSERT(ifindex != 0);
4941 
4942 		if (ltcp->tcp_bound_if != 0) {
4943 			/*
4944 			 * Set newtcp's bound_if equal to
4945 			 * listener's value. If ifindex is
4946 			 * not the same as ltcp->tcp_bound_if,
4947 			 * it must be a packet for the ipmp group
4948 			 * of interfaces
4949 			 */
4950 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4951 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4952 			tcp->tcp_bound_if = ifindex;
4953 		}
4954 
4955 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4956 		tcp->tcp_recvifindex = 0;
4957 		tcp->tcp_recvhops = 0xffffffffU;
4958 		ASSERT(tcp->tcp_ip6h != NULL);
4959 	}
4960 
4961 	tcp->tcp_lport = ltcp->tcp_lport;
4962 
4963 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4964 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4965 			/*
4966 			 * Listener had options of some sort; eager inherits.
4967 			 * Free up the eager template and allocate one
4968 			 * of the right size.
4969 			 */
4970 			if (tcp->tcp_hdr_grown) {
4971 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4972 			} else {
4973 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4974 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4975 			}
4976 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4977 			    KM_NOSLEEP);
4978 			if (tcp->tcp_iphc == NULL) {
4979 				tcp->tcp_iphc_len = 0;
4980 				freemsg(tpi_mp);
4981 				return (ENOMEM);
4982 			}
4983 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4984 			tcp->tcp_hdr_grown = B_TRUE;
4985 		}
4986 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4987 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4988 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4989 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4990 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4991 
4992 		/*
4993 		 * Copy the IP+TCP header template from listener to eager
4994 		 */
4995 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4996 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4997 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4998 			    IPPROTO_RAW) {
4999 				tcp->tcp_ip6h =
5000 				    (ip6_t *)(tcp->tcp_iphc +
5001 					sizeof (ip6i_t));
5002 			} else {
5003 				tcp->tcp_ip6h =
5004 				    (ip6_t *)(tcp->tcp_iphc);
5005 			}
5006 			tcp->tcp_ipha = NULL;
5007 		} else {
5008 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5009 			tcp->tcp_ip6h = NULL;
5010 		}
5011 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5012 		    tcp->tcp_ip_hdr_len);
5013 	} else {
5014 		/*
5015 		 * only valid case when ipversion of listener and
5016 		 * eager differ is when listener is IPv6 and
5017 		 * eager is IPv4.
5018 		 * Eager header template has been initialized to the
5019 		 * maximum v4 header sizes, which includes space for
5020 		 * TCP and IP options.
5021 		 */
5022 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5023 		    (tcp->tcp_ipversion == IPV4_VERSION));
5024 		ASSERT(tcp->tcp_iphc_len >=
5025 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5026 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5027 		/* copy IP header fields individually */
5028 		tcp->tcp_ipha->ipha_ttl =
5029 		    ltcp->tcp_ip6h->ip6_hops;
5030 		bcopy(ltcp->tcp_tcph->th_lport,
5031 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5032 	}
5033 
5034 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5035 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5036 	    sizeof (in_port_t));
5037 
5038 	if (ltcp->tcp_lport == 0) {
5039 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5040 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5041 		    sizeof (in_port_t));
5042 	}
5043 
5044 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5045 		ASSERT(ipha != NULL);
5046 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5047 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5048 
5049 		/* Source routing option copyover (reverse it) */
5050 		if (tcps->tcps_rev_src_routes)
5051 			tcp_opt_reverse(tcp, ipha);
5052 	} else {
5053 		ASSERT(ip6h != NULL);
5054 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5055 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5056 	}
5057 
5058 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5059 	ASSERT(!tcp->tcp_tconnind_started);
5060 	/*
5061 	 * If the SYN contains a credential, it's a loopback packet; attach
5062 	 * the credential to the TPI message.
5063 	 */
5064 	if ((cr = DB_CRED(idmp)) != NULL) {
5065 		mblk_setcred(tpi_mp, cr);
5066 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5067 	}
5068 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5069 
5070 	/* Inherit the listener's SSL protection state */
5071 
5072 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5073 		kssl_hold_ent(tcp->tcp_kssl_ent);
5074 		tcp->tcp_kssl_pending = B_TRUE;
5075 	}
5076 
5077 	return (0);
5078 }
5079 
5080 
5081 int
5082 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5083     tcph_t *tcph, mblk_t *idmp)
5084 {
5085 	tcp_t 		*ltcp = lconnp->conn_tcp;
5086 	tcp_t		*tcp = connp->conn_tcp;
5087 	sin_t		sin;
5088 	mblk_t		*tpi_mp = NULL;
5089 	int		err;
5090 	cred_t		*cr;
5091 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5092 
5093 	sin = sin_null;
5094 	sin.sin_addr.s_addr = ipha->ipha_src;
5095 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5096 	sin.sin_family = AF_INET;
5097 	if (ltcp->tcp_recvdstaddr) {
5098 		sin_t	sind;
5099 
5100 		sind = sin_null;
5101 		sind.sin_addr.s_addr = ipha->ipha_dst;
5102 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5103 		sind.sin_family = AF_INET;
5104 		tpi_mp = mi_tpi_extconn_ind(NULL,
5105 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5106 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5107 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5108 	} else {
5109 		tpi_mp = mi_tpi_conn_ind(NULL,
5110 		    (char *)&sin, sizeof (sin_t),
5111 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5112 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5113 	}
5114 
5115 	if (tpi_mp == NULL) {
5116 		return (ENOMEM);
5117 	}
5118 
5119 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5120 	connp->conn_send = ip_output;
5121 	connp->conn_recv = tcp_input;
5122 	connp->conn_fully_bound = B_FALSE;
5123 
5124 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5125 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5126 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5127 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5128 
5129 	if (tcps->tcps_trace) {
5130 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5131 	}
5132 
5133 	/* Inherit information from the "parent" */
5134 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5135 	tcp->tcp_family = ltcp->tcp_family;
5136 	tcp->tcp_wq = ltcp->tcp_wq;
5137 	tcp->tcp_rq = ltcp->tcp_rq;
5138 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5139 	tcp->tcp_detached = B_TRUE;
5140 	if ((err = tcp_init_values(tcp)) != 0) {
5141 		freemsg(tpi_mp);
5142 		return (err);
5143 	}
5144 
5145 	/*
5146 	 * Let's make sure that eager tcp template has enough space to
5147 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5148 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5149 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5150 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5151 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5152 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5153 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5154 	 */
5155 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5156 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5157 
5158 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5159 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5160 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5161 	tcp->tcp_ttl = ltcp->tcp_ttl;
5162 	tcp->tcp_tos = ltcp->tcp_tos;
5163 
5164 	/* Copy the IP+TCP header template from listener to eager */
5165 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5166 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5167 	tcp->tcp_ip6h = NULL;
5168 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5169 	    tcp->tcp_ip_hdr_len);
5170 
5171 	/* Initialize the IP addresses and Ports */
5172 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5173 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5174 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5175 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5176 
5177 	/* Source routing option copyover (reverse it) */
5178 	if (tcps->tcps_rev_src_routes)
5179 		tcp_opt_reverse(tcp, ipha);
5180 
5181 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5182 	ASSERT(!tcp->tcp_tconnind_started);
5183 
5184 	/*
5185 	 * If the SYN contains a credential, it's a loopback packet; attach
5186 	 * the credential to the TPI message.
5187 	 */
5188 	if ((cr = DB_CRED(idmp)) != NULL) {
5189 		mblk_setcred(tpi_mp, cr);
5190 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5191 	}
5192 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5193 
5194 	/* Inherit the listener's SSL protection state */
5195 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5196 		kssl_hold_ent(tcp->tcp_kssl_ent);
5197 		tcp->tcp_kssl_pending = B_TRUE;
5198 	}
5199 
5200 	return (0);
5201 }
5202 
5203 /*
5204  * sets up conn for ipsec.
5205  * if the first mblk is M_CTL it is consumed and mpp is updated.
5206  * in case of error mpp is freed.
5207  */
5208 conn_t *
5209 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5210 {
5211 	conn_t 		*connp = tcp->tcp_connp;
5212 	conn_t 		*econnp;
5213 	squeue_t 	*new_sqp;
5214 	mblk_t 		*first_mp = *mpp;
5215 	mblk_t		*mp = *mpp;
5216 	boolean_t	mctl_present = B_FALSE;
5217 	uint_t		ipvers;
5218 
5219 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5220 	if (econnp == NULL) {
5221 		freemsg(first_mp);
5222 		return (NULL);
5223 	}
5224 	if (DB_TYPE(mp) == M_CTL) {
5225 		if (mp->b_cont == NULL ||
5226 		    mp->b_cont->b_datap->db_type != M_DATA) {
5227 			freemsg(first_mp);
5228 			return (NULL);
5229 		}
5230 		mp = mp->b_cont;
5231 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5232 			freemsg(first_mp);
5233 			return (NULL);
5234 		}
5235 
5236 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5237 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5238 		mctl_present = B_TRUE;
5239 	} else {
5240 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5241 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5242 	}
5243 
5244 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5245 	DB_CKSUMSTART(mp) = 0;
5246 
5247 	ASSERT(OK_32PTR(mp->b_rptr));
5248 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5249 	if (ipvers == IPV4_VERSION) {
5250 		uint16_t  	*up;
5251 		uint32_t	ports;
5252 		ipha_t		*ipha;
5253 
5254 		ipha = (ipha_t *)mp->b_rptr;
5255 		up = (uint16_t *)((uchar_t *)ipha +
5256 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5257 		ports = *(uint32_t *)up;
5258 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5259 		    ipha->ipha_dst, ipha->ipha_src, ports);
5260 	} else {
5261 		uint16_t  	*up;
5262 		uint32_t	ports;
5263 		uint16_t	ip_hdr_len;
5264 		uint8_t		*nexthdrp;
5265 		ip6_t 		*ip6h;
5266 		tcph_t		*tcph;
5267 
5268 		ip6h = (ip6_t *)mp->b_rptr;
5269 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5270 			ip_hdr_len = IPV6_HDR_LEN;
5271 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5272 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5273 			CONN_DEC_REF(econnp);
5274 			freemsg(first_mp);
5275 			return (NULL);
5276 		}
5277 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5278 		up = (uint16_t *)tcph->th_lport;
5279 		ports = *(uint32_t *)up;
5280 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5281 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5282 	}
5283 
5284 	/*
5285 	 * The caller already ensured that there is a sqp present.
5286 	 */
5287 	econnp->conn_sqp = new_sqp;
5288 
5289 	if (connp->conn_policy != NULL) {
5290 		ipsec_in_t *ii;
5291 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5292 		ASSERT(ii->ipsec_in_policy == NULL);
5293 		IPPH_REFHOLD(connp->conn_policy);
5294 		ii->ipsec_in_policy = connp->conn_policy;
5295 
5296 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5297 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5298 			CONN_DEC_REF(econnp);
5299 			freemsg(first_mp);
5300 			return (NULL);
5301 		}
5302 	}
5303 
5304 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5305 		CONN_DEC_REF(econnp);
5306 		freemsg(first_mp);
5307 		return (NULL);
5308 	}
5309 
5310 	/*
5311 	 * If we know we have some policy, pass the "IPSEC"
5312 	 * options size TCP uses this adjust the MSS.
5313 	 */
5314 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5315 	if (mctl_present) {
5316 		freeb(first_mp);
5317 		*mpp = mp;
5318 	}
5319 
5320 	return (econnp);
5321 }
5322 
5323 /*
5324  * tcp_get_conn/tcp_free_conn
5325  *
5326  * tcp_get_conn is used to get a clean tcp connection structure.
5327  * It tries to reuse the connections put on the freelist by the
5328  * time_wait_collector failing which it goes to kmem_cache. This
5329  * way has two benefits compared to just allocating from and
5330  * freeing to kmem_cache.
5331  * 1) The time_wait_collector can free (which includes the cleanup)
5332  * outside the squeue. So when the interrupt comes, we have a clean
5333  * connection sitting in the freelist. Obviously, this buys us
5334  * performance.
5335  *
5336  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5337  * has multiple disadvantages - tying up the squeue during alloc, and the
5338  * fact that IPSec policy initialization has to happen here which
5339  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5340  * But allocating the conn/tcp in IP land is also not the best since
5341  * we can't check the 'q' and 'q0' which are protected by squeue and
5342  * blindly allocate memory which might have to be freed here if we are
5343  * not allowed to accept the connection. By using the freelist and
5344  * putting the conn/tcp back in freelist, we don't pay a penalty for
5345  * allocating memory without checking 'q/q0' and freeing it if we can't
5346  * accept the connection.
5347  *
5348  * Care should be taken to put the conn back in the same squeue's freelist
5349  * from which it was allocated. Best results are obtained if conn is
5350  * allocated from listener's squeue and freed to the same. Time wait
5351  * collector will free up the freelist is the connection ends up sitting
5352  * there for too long.
5353  */
5354 void *
5355 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5356 {
5357 	tcp_t			*tcp = NULL;
5358 	conn_t			*connp = NULL;
5359 	squeue_t		*sqp = (squeue_t *)arg;
5360 	tcp_squeue_priv_t 	*tcp_time_wait;
5361 	netstack_t		*ns;
5362 
5363 	tcp_time_wait =
5364 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5365 
5366 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5367 	tcp = tcp_time_wait->tcp_free_list;
5368 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5369 	if (tcp != NULL) {
5370 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5371 		tcp_time_wait->tcp_free_list_cnt--;
5372 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5373 		tcp->tcp_time_wait_next = NULL;
5374 		connp = tcp->tcp_connp;
5375 		connp->conn_flags |= IPCL_REUSED;
5376 
5377 		ASSERT(tcp->tcp_tcps == NULL);
5378 		ASSERT(connp->conn_netstack == NULL);
5379 		ns = tcps->tcps_netstack;
5380 		netstack_hold(ns);
5381 		connp->conn_netstack = ns;
5382 		tcp->tcp_tcps = tcps;
5383 		TCPS_REFHOLD(tcps);
5384 		ipcl_globalhash_insert(connp);
5385 		return ((void *)connp);
5386 	}
5387 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5388 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5389 		    tcps->tcps_netstack)) == NULL)
5390 		return (NULL);
5391 	tcp = connp->conn_tcp;
5392 	tcp->tcp_tcps = tcps;
5393 	TCPS_REFHOLD(tcps);
5394 	return ((void *)connp);
5395 }
5396 
5397 /*
5398  * Update the cached label for the given tcp_t.  This should be called once per
5399  * connection, and before any packets are sent or tcp_process_options is
5400  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5401  */
5402 static boolean_t
5403 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5404 {
5405 	conn_t *connp = tcp->tcp_connp;
5406 
5407 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5408 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5409 		int added;
5410 
5411 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5412 		    connp->conn_mac_exempt,
5413 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5414 			return (B_FALSE);
5415 
5416 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5417 		if (added == -1)
5418 			return (B_FALSE);
5419 		tcp->tcp_hdr_len += added;
5420 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5421 		tcp->tcp_ip_hdr_len += added;
5422 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5423 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5424 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5425 			    tcp->tcp_hdr_len);
5426 			if (added == -1)
5427 				return (B_FALSE);
5428 			tcp->tcp_hdr_len += added;
5429 			tcp->tcp_tcph = (tcph_t *)
5430 			    ((uchar_t *)tcp->tcp_tcph + added);
5431 			tcp->tcp_ip_hdr_len += added;
5432 		}
5433 	} else {
5434 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5435 
5436 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5437 		    connp->conn_mac_exempt,
5438 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5439 			return (B_FALSE);
5440 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5441 		    &tcp->tcp_label_len, optbuf) != 0)
5442 			return (B_FALSE);
5443 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5444 			return (B_FALSE);
5445 	}
5446 
5447 	connp->conn_ulp_labeled = 1;
5448 
5449 	return (B_TRUE);
5450 }
5451 
5452 /* BEGIN CSTYLED */
5453 /*
5454  *
5455  * The sockfs ACCEPT path:
5456  * =======================
5457  *
5458  * The eager is now established in its own perimeter as soon as SYN is
5459  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5460  * completes the accept processing on the acceptor STREAM. The sending
5461  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5462  * listener but a TLI/XTI listener completes the accept processing
5463  * on the listener perimeter.
5464  *
5465  * Common control flow for 3 way handshake:
5466  * ----------------------------------------
5467  *
5468  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5469  *					-> tcp_conn_request()
5470  *
5471  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5472  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5473  *
5474  * Sockfs ACCEPT Path:
5475  * -------------------
5476  *
5477  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5478  * as STREAM entry point)
5479  *
5480  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5481  *
5482  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5483  * association (we are not behind eager's squeue but sockfs is protecting us
5484  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5485  * is changed to point at tcp_wput().
5486  *
5487  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5488  * listener (done on listener's perimeter).
5489  *
5490  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5491  * accept.
5492  *
5493  * TLI/XTI client ACCEPT path:
5494  * ---------------------------
5495  *
5496  * soaccept() sends T_CONN_RES on the listener STREAM.
5497  *
5498  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5499  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5500  *
5501  * Locks:
5502  * ======
5503  *
5504  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5505  * and listeners->tcp_eager_next_q.
5506  *
5507  * Referencing:
5508  * ============
5509  *
5510  * 1) We start out in tcp_conn_request by eager placing a ref on
5511  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5512  *
5513  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5514  * doing so we place a ref on the eager. This ref is finally dropped at the
5515  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5516  * reference is dropped by the squeue framework.
5517  *
5518  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5519  *
5520  * The reference must be released by the same entity that added the reference
5521  * In the above scheme, the eager is the entity that adds and releases the
5522  * references. Note that tcp_accept_finish executes in the squeue of the eager
5523  * (albeit after it is attached to the acceptor stream). Though 1. executes
5524  * in the listener's squeue, the eager is nascent at this point and the
5525  * reference can be considered to have been added on behalf of the eager.
5526  *
5527  * Eager getting a Reset or listener closing:
5528  * ==========================================
5529  *
5530  * Once the listener and eager are linked, the listener never does the unlink.
5531  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5532  * a message on all eager perimeter. The eager then does the unlink, clears
5533  * any pointers to the listener's queue and drops the reference to the
5534  * listener. The listener waits in tcp_close outside the squeue until its
5535  * refcount has dropped to 1. This ensures that the listener has waited for
5536  * all eagers to clear their association with the listener.
5537  *
5538  * Similarly, if eager decides to go away, it can unlink itself and close.
5539  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5540  * the reference to eager is still valid because of the extra ref we put
5541  * in tcp_send_conn_ind.
5542  *
5543  * Listener can always locate the eager under the protection
5544  * of the listener->tcp_eager_lock, and then do a refhold
5545  * on the eager during the accept processing.
5546  *
5547  * The acceptor stream accesses the eager in the accept processing
5548  * based on the ref placed on eager before sending T_conn_ind.
5549  * The only entity that can negate this refhold is a listener close
5550  * which is mutually exclusive with an active acceptor stream.
5551  *
5552  * Eager's reference on the listener
5553  * ===================================
5554  *
5555  * If the accept happens (even on a closed eager) the eager drops its
5556  * reference on the listener at the start of tcp_accept_finish. If the
5557  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5558  * the reference is dropped in tcp_closei_local. If the listener closes,
5559  * the reference is dropped in tcp_eager_kill. In all cases the reference
5560  * is dropped while executing in the eager's context (squeue).
5561  */
5562 /* END CSTYLED */
5563 
5564 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5565 
5566 /*
5567  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5568  * tcp_rput_data will not see any SYN packets.
5569  */
5570 /* ARGSUSED */
5571 void
5572 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5573 {
5574 	tcph_t		*tcph;
5575 	uint32_t	seg_seq;
5576 	tcp_t		*eager;
5577 	uint_t		ipvers;
5578 	ipha_t		*ipha;
5579 	ip6_t		*ip6h;
5580 	int		err;
5581 	conn_t		*econnp = NULL;
5582 	squeue_t	*new_sqp;
5583 	mblk_t		*mp1;
5584 	uint_t 		ip_hdr_len;
5585 	conn_t		*connp = (conn_t *)arg;
5586 	tcp_t		*tcp = connp->conn_tcp;
5587 	cred_t		*credp;
5588 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5589 	ip_stack_t	*ipst;
5590 
5591 	if (tcp->tcp_state != TCPS_LISTEN)
5592 		goto error2;
5593 
5594 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5595 
5596 	mutex_enter(&tcp->tcp_eager_lock);
5597 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5598 		mutex_exit(&tcp->tcp_eager_lock);
5599 		TCP_STAT(tcps, tcp_listendrop);
5600 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5601 		if (tcp->tcp_debug) {
5602 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5603 			    "tcp_conn_request: listen backlog (max=%d) "
5604 			    "overflow (%d pending) on %s",
5605 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5606 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5607 		}
5608 		goto error2;
5609 	}
5610 
5611 	if (tcp->tcp_conn_req_cnt_q0 >=
5612 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5613 		/*
5614 		 * Q0 is full. Drop a pending half-open req from the queue
5615 		 * to make room for the new SYN req. Also mark the time we
5616 		 * drop a SYN.
5617 		 *
5618 		 * A more aggressive defense against SYN attack will
5619 		 * be to set the "tcp_syn_defense" flag now.
5620 		 */
5621 		TCP_STAT(tcps, tcp_listendropq0);
5622 		tcp->tcp_last_rcv_lbolt = lbolt64;
5623 		if (!tcp_drop_q0(tcp)) {
5624 			mutex_exit(&tcp->tcp_eager_lock);
5625 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5626 			if (tcp->tcp_debug) {
5627 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5628 				    "tcp_conn_request: listen half-open queue "
5629 				    "(max=%d) full (%d pending) on %s",
5630 				    tcps->tcps_conn_req_max_q0,
5631 				    tcp->tcp_conn_req_cnt_q0,
5632 				    tcp_display(tcp, NULL,
5633 				    DISP_PORT_ONLY));
5634 			}
5635 			goto error2;
5636 		}
5637 	}
5638 	mutex_exit(&tcp->tcp_eager_lock);
5639 
5640 	/*
5641 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5642 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5643 	 * link local address.  If IPSec is enabled, db_struioflag has
5644 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5645 	 * otherwise an error case if neither of them is set.
5646 	 */
5647 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5648 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5649 		DB_CKSUMSTART(mp) = 0;
5650 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5651 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5652 		if (econnp == NULL)
5653 			goto error2;
5654 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5655 		econnp->conn_sqp = new_sqp;
5656 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5657 		/*
5658 		 * mp is updated in tcp_get_ipsec_conn().
5659 		 */
5660 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5661 		if (econnp == NULL) {
5662 			/*
5663 			 * mp freed by tcp_get_ipsec_conn.
5664 			 */
5665 			return;
5666 		}
5667 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5668 	} else {
5669 		goto error2;
5670 	}
5671 
5672 	ASSERT(DB_TYPE(mp) == M_DATA);
5673 
5674 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5675 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5676 	ASSERT(OK_32PTR(mp->b_rptr));
5677 	if (ipvers == IPV4_VERSION) {
5678 		ipha = (ipha_t *)mp->b_rptr;
5679 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5680 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5681 	} else {
5682 		ip6h = (ip6_t *)mp->b_rptr;
5683 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5684 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5685 	}
5686 
5687 	if (tcp->tcp_family == AF_INET) {
5688 		ASSERT(ipvers == IPV4_VERSION);
5689 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5690 	} else {
5691 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5692 	}
5693 
5694 	if (err)
5695 		goto error3;
5696 
5697 	eager = econnp->conn_tcp;
5698 
5699 	/* Inherit various TCP parameters from the listener */
5700 	eager->tcp_naglim = tcp->tcp_naglim;
5701 	eager->tcp_first_timer_threshold =
5702 	    tcp->tcp_first_timer_threshold;
5703 	eager->tcp_second_timer_threshold =
5704 	    tcp->tcp_second_timer_threshold;
5705 
5706 	eager->tcp_first_ctimer_threshold =
5707 	    tcp->tcp_first_ctimer_threshold;
5708 	eager->tcp_second_ctimer_threshold =
5709 	    tcp->tcp_second_ctimer_threshold;
5710 
5711 	/*
5712 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5713 	 * If it does not, the eager's receive window will be set to the
5714 	 * listener's receive window later in this function.
5715 	 */
5716 	eager->tcp_rwnd = 0;
5717 
5718 	/*
5719 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5720 	 * calling tcp_process_options() where tcp_mss_set() is called
5721 	 * to set the initial cwnd.
5722 	 */
5723 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5724 
5725 	/*
5726 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5727 	 * zone id before the accept is completed in tcp_wput_accept().
5728 	 */
5729 	econnp->conn_zoneid = connp->conn_zoneid;
5730 	econnp->conn_allzones = connp->conn_allzones;
5731 
5732 	/* Copy nexthop information from listener to eager */
5733 	if (connp->conn_nexthop_set) {
5734 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5735 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5736 	}
5737 
5738 	/*
5739 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5740 	 * eager is accepted
5741 	 */
5742 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5743 	crhold(credp);
5744 
5745 	/*
5746 	 * If the caller has the process-wide flag set, then default to MAC
5747 	 * exempt mode.  This allows read-down to unlabeled hosts.
5748 	 */
5749 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5750 		econnp->conn_mac_exempt = B_TRUE;
5751 
5752 	if (is_system_labeled()) {
5753 		cred_t *cr;
5754 
5755 		if (connp->conn_mlp_type != mlptSingle) {
5756 			cr = econnp->conn_peercred = DB_CRED(mp);
5757 			if (cr != NULL)
5758 				crhold(cr);
5759 			else
5760 				cr = econnp->conn_cred;
5761 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5762 			    econnp, cred_t *, cr)
5763 		} else {
5764 			cr = econnp->conn_cred;
5765 			DTRACE_PROBE2(syn_accept, conn_t *,
5766 			    econnp, cred_t *, cr)
5767 		}
5768 
5769 		if (!tcp_update_label(eager, cr)) {
5770 			DTRACE_PROBE3(
5771 			    tx__ip__log__error__connrequest__tcp,
5772 			    char *, "eager connp(1) label on SYN mp(2) failed",
5773 			    conn_t *, econnp, mblk_t *, mp);
5774 			goto error3;
5775 		}
5776 	}
5777 
5778 	eager->tcp_hard_binding = B_TRUE;
5779 
5780 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5781 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5782 
5783 	CL_INET_CONNECT(eager);
5784 
5785 	/*
5786 	 * No need to check for multicast destination since ip will only pass
5787 	 * up multicasts to those that have expressed interest
5788 	 * TODO: what about rejecting broadcasts?
5789 	 * Also check that source is not a multicast or broadcast address.
5790 	 */
5791 	eager->tcp_state = TCPS_SYN_RCVD;
5792 
5793 
5794 	/*
5795 	 * There should be no ire in the mp as we are being called after
5796 	 * receiving the SYN.
5797 	 */
5798 	ASSERT(tcp_ire_mp(mp) == NULL);
5799 
5800 	/*
5801 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5802 	 */
5803 
5804 	if (tcp_adapt_ire(eager, NULL) == 0) {
5805 		/* Undo the bind_hash_insert */
5806 		tcp_bind_hash_remove(eager);
5807 		goto error3;
5808 	}
5809 
5810 	/* Process all TCP options. */
5811 	tcp_process_options(eager, tcph);
5812 
5813 	/* Is the other end ECN capable? */
5814 	if (tcps->tcps_ecn_permitted >= 1 &&
5815 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5816 		eager->tcp_ecn_ok = B_TRUE;
5817 	}
5818 
5819 	/*
5820 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5821 	 * window size changed via SO_RCVBUF option.  First round up the
5822 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5823 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5824 	 * setting.
5825 	 *
5826 	 * Note if there is a rpipe metric associated with the remote host,
5827 	 * we should not inherit receive window size from listener.
5828 	 */
5829 	eager->tcp_rwnd = MSS_ROUNDUP(
5830 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5831 	    eager->tcp_rwnd), eager->tcp_mss);
5832 	if (eager->tcp_snd_ws_ok)
5833 		tcp_set_ws_value(eager);
5834 	/*
5835 	 * Note that this is the only place tcp_rwnd_set() is called for
5836 	 * accepting a connection.  We need to call it here instead of
5837 	 * after the 3-way handshake because we need to tell the other
5838 	 * side our rwnd in the SYN-ACK segment.
5839 	 */
5840 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5841 
5842 	/*
5843 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5844 	 * via soaccept()->soinheritoptions() which essentially applies
5845 	 * all the listener options to the new STREAM. The options that we
5846 	 * need to take care of are:
5847 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5848 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5849 	 * SO_SNDBUF, SO_RCVBUF.
5850 	 *
5851 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5852 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5853 	 *		tcp_maxpsz_set() gets called later from
5854 	 *		tcp_accept_finish(), the option takes effect.
5855 	 *
5856 	 */
5857 	/* Set the TCP options */
5858 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5859 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5860 	eager->tcp_oobinline = tcp->tcp_oobinline;
5861 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5862 	eager->tcp_broadcast = tcp->tcp_broadcast;
5863 	eager->tcp_useloopback = tcp->tcp_useloopback;
5864 	eager->tcp_dontroute = tcp->tcp_dontroute;
5865 	eager->tcp_linger = tcp->tcp_linger;
5866 	eager->tcp_lingertime = tcp->tcp_lingertime;
5867 	if (tcp->tcp_ka_enabled)
5868 		eager->tcp_ka_enabled = 1;
5869 
5870 	/* Set the IP options */
5871 	econnp->conn_broadcast = connp->conn_broadcast;
5872 	econnp->conn_loopback = connp->conn_loopback;
5873 	econnp->conn_dontroute = connp->conn_dontroute;
5874 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5875 
5876 	/* Put a ref on the listener for the eager. */
5877 	CONN_INC_REF(connp);
5878 	mutex_enter(&tcp->tcp_eager_lock);
5879 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5880 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5881 	tcp->tcp_eager_next_q0 = eager;
5882 	eager->tcp_eager_prev_q0 = tcp;
5883 
5884 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5885 	eager->tcp_listener = tcp;
5886 	eager->tcp_saved_listener = tcp;
5887 
5888 	/*
5889 	 * Tag this detached tcp vector for later retrieval
5890 	 * by our listener client in tcp_accept().
5891 	 */
5892 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5893 	tcp->tcp_conn_req_cnt_q0++;
5894 	if (++tcp->tcp_conn_req_seqnum == -1) {
5895 		/*
5896 		 * -1 is "special" and defined in TPI as something
5897 		 * that should never be used in T_CONN_IND
5898 		 */
5899 		++tcp->tcp_conn_req_seqnum;
5900 	}
5901 	mutex_exit(&tcp->tcp_eager_lock);
5902 
5903 	if (tcp->tcp_syn_defense) {
5904 		/* Don't drop the SYN that comes from a good IP source */
5905 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5906 		if (addr_cache != NULL && eager->tcp_remote ==
5907 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5908 			eager->tcp_dontdrop = B_TRUE;
5909 		}
5910 	}
5911 
5912 	/*
5913 	 * We need to insert the eager in its own perimeter but as soon
5914 	 * as we do that, we expose the eager to the classifier and
5915 	 * should not touch any field outside the eager's perimeter.
5916 	 * So do all the work necessary before inserting the eager
5917 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5918 	 * will succeed but undo everything if it fails.
5919 	 */
5920 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5921 	eager->tcp_irs = seg_seq;
5922 	eager->tcp_rack = seg_seq;
5923 	eager->tcp_rnxt = seg_seq + 1;
5924 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5925 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5926 	eager->tcp_state = TCPS_SYN_RCVD;
5927 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5928 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5929 	if (mp1 == NULL) {
5930 		/*
5931 		 * Increment the ref count as we are going to
5932 		 * enqueueing an mp in squeue
5933 		 */
5934 		CONN_INC_REF(econnp);
5935 		goto error;
5936 	}
5937 	DB_CPID(mp1) = tcp->tcp_cpid;
5938 	eager->tcp_cpid = tcp->tcp_cpid;
5939 	eager->tcp_open_time = lbolt64;
5940 
5941 	/*
5942 	 * We need to start the rto timer. In normal case, we start
5943 	 * the timer after sending the packet on the wire (or at
5944 	 * least believing that packet was sent by waiting for
5945 	 * CALL_IP_WPUT() to return). Since this is the first packet
5946 	 * being sent on the wire for the eager, our initial tcp_rto
5947 	 * is at least tcp_rexmit_interval_min which is a fairly
5948 	 * large value to allow the algorithm to adjust slowly to large
5949 	 * fluctuations of RTT during first few transmissions.
5950 	 *
5951 	 * Starting the timer first and then sending the packet in this
5952 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5953 	 * is of the order of several 100ms and starting the timer
5954 	 * first and then sending the packet will result in difference
5955 	 * of few micro seconds.
5956 	 *
5957 	 * Without this optimization, we are forced to hold the fanout
5958 	 * lock across the ipcl_bind_insert() and sending the packet
5959 	 * so that we don't race against an incoming packet (maybe RST)
5960 	 * for this eager.
5961 	 *
5962 	 * It is necessary to acquire an extra reference on the eager
5963 	 * at this point and hold it until after tcp_send_data() to
5964 	 * ensure against an eager close race.
5965 	 */
5966 
5967 	CONN_INC_REF(eager->tcp_connp);
5968 
5969 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5970 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5971 
5972 
5973 	/*
5974 	 * Insert the eager in its own perimeter now. We are ready to deal
5975 	 * with any packets on eager.
5976 	 */
5977 	if (eager->tcp_ipversion == IPV4_VERSION) {
5978 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5979 			goto error;
5980 		}
5981 	} else {
5982 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5983 			goto error;
5984 		}
5985 	}
5986 
5987 	/* mark conn as fully-bound */
5988 	econnp->conn_fully_bound = B_TRUE;
5989 
5990 	/* Send the SYN-ACK */
5991 	tcp_send_data(eager, eager->tcp_wq, mp1);
5992 	CONN_DEC_REF(eager->tcp_connp);
5993 	freemsg(mp);
5994 
5995 	return;
5996 error:
5997 	freemsg(mp1);
5998 	eager->tcp_closemp_used = B_TRUE;
5999 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6000 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6001 	    econnp, SQTAG_TCP_CONN_REQ_2);
6002 
6003 	/*
6004 	 * If a connection already exists, send the mp to that connections so
6005 	 * that it can be appropriately dealt with.
6006 	 */
6007 	ipst = tcps->tcps_netstack->netstack_ip;
6008 
6009 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6010 		if (!IPCL_IS_CONNECTED(econnp)) {
6011 			/*
6012 			 * Something bad happened. ipcl_conn_insert()
6013 			 * failed because a connection already existed
6014 			 * in connected hash but we can't find it
6015 			 * anymore (someone blew it away). Just
6016 			 * free this message and hopefully remote
6017 			 * will retransmit at which time the SYN can be
6018 			 * treated as a new connection or dealth with
6019 			 * a TH_RST if a connection already exists.
6020 			 */
6021 			CONN_DEC_REF(econnp);
6022 			freemsg(mp);
6023 		} else {
6024 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6025 			    econnp, SQTAG_TCP_CONN_REQ_1);
6026 		}
6027 	} else {
6028 		/* Nobody wants this packet */
6029 		freemsg(mp);
6030 	}
6031 	return;
6032 error3:
6033 	CONN_DEC_REF(econnp);
6034 error2:
6035 	freemsg(mp);
6036 }
6037 
6038 /*
6039  * In an ideal case of vertical partition in NUMA architecture, its
6040  * beneficial to have the listener and all the incoming connections
6041  * tied to the same squeue. The other constraint is that incoming
6042  * connections should be tied to the squeue attached to interrupted
6043  * CPU for obvious locality reason so this leaves the listener to
6044  * be tied to the same squeue. Our only problem is that when listener
6045  * is binding, the CPU that will get interrupted by the NIC whose
6046  * IP address the listener is binding to is not even known. So
6047  * the code below allows us to change that binding at the time the
6048  * CPU is interrupted by virtue of incoming connection's squeue.
6049  *
6050  * This is usefull only in case of a listener bound to a specific IP
6051  * address. For other kind of listeners, they get bound the
6052  * very first time and there is no attempt to rebind them.
6053  */
6054 void
6055 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6056 {
6057 	conn_t		*connp = (conn_t *)arg;
6058 	squeue_t	*sqp = (squeue_t *)arg2;
6059 	squeue_t	*new_sqp;
6060 	uint32_t	conn_flags;
6061 
6062 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6063 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6064 	} else {
6065 		goto done;
6066 	}
6067 
6068 	if (connp->conn_fanout == NULL)
6069 		goto done;
6070 
6071 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6072 		mutex_enter(&connp->conn_fanout->connf_lock);
6073 		mutex_enter(&connp->conn_lock);
6074 		/*
6075 		 * No one from read or write side can access us now
6076 		 * except for already queued packets on this squeue.
6077 		 * But since we haven't changed the squeue yet, they
6078 		 * can't execute. If they are processed after we have
6079 		 * changed the squeue, they are sent back to the
6080 		 * correct squeue down below.
6081 		 * But a listner close can race with processing of
6082 		 * incoming SYN. If incoming SYN processing changes
6083 		 * the squeue then the listener close which is waiting
6084 		 * to enter the squeue would operate on the wrong
6085 		 * squeue. Hence we don't change the squeue here unless
6086 		 * the refcount is exactly the minimum refcount. The
6087 		 * minimum refcount of 4 is counted as - 1 each for
6088 		 * TCP and IP, 1 for being in the classifier hash, and
6089 		 * 1 for the mblk being processed.
6090 		 */
6091 
6092 		if (connp->conn_ref != 4 ||
6093 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6094 			mutex_exit(&connp->conn_lock);
6095 			mutex_exit(&connp->conn_fanout->connf_lock);
6096 			goto done;
6097 		}
6098 		if (connp->conn_sqp != new_sqp) {
6099 			while (connp->conn_sqp != new_sqp)
6100 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6101 		}
6102 
6103 		do {
6104 			conn_flags = connp->conn_flags;
6105 			conn_flags |= IPCL_FULLY_BOUND;
6106 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6107 			    conn_flags);
6108 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6109 
6110 		mutex_exit(&connp->conn_fanout->connf_lock);
6111 		mutex_exit(&connp->conn_lock);
6112 	}
6113 
6114 done:
6115 	if (connp->conn_sqp != sqp) {
6116 		CONN_INC_REF(connp);
6117 		squeue_fill(connp->conn_sqp, mp,
6118 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6119 	} else {
6120 		tcp_conn_request(connp, mp, sqp);
6121 	}
6122 }
6123 
6124 /*
6125  * Successful connect request processing begins when our client passes
6126  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6127  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6128  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6129  *   upstream <- tcp_rput()                <- IP
6130  * After various error checks are completed, tcp_connect() lays
6131  * the target address and port into the composite header template,
6132  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6133  * request followed by an IRE request, and passes the three mblk message
6134  * down to IP looking like this:
6135  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6136  * Processing continues in tcp_rput() when we receive the following message:
6137  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6138  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6139  * to fire off the connection request, and then passes the T_OK_ACK mblk
6140  * upstream that we filled in below.  There are, of course, numerous
6141  * error conditions along the way which truncate the processing described
6142  * above.
6143  */
6144 static void
6145 tcp_connect(tcp_t *tcp, mblk_t *mp)
6146 {
6147 	sin_t		*sin;
6148 	sin6_t		*sin6;
6149 	queue_t		*q = tcp->tcp_wq;
6150 	struct T_conn_req	*tcr;
6151 	ipaddr_t	*dstaddrp;
6152 	in_port_t	dstport;
6153 	uint_t		srcid;
6154 
6155 	tcr = (struct T_conn_req *)mp->b_rptr;
6156 
6157 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6158 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6159 		tcp_err_ack(tcp, mp, TPROTO, 0);
6160 		return;
6161 	}
6162 
6163 	/*
6164 	 * Determine packet type based on type of address passed in
6165 	 * the request should contain an IPv4 or IPv6 address.
6166 	 * Make sure that address family matches the type of
6167 	 * family of the the address passed down
6168 	 */
6169 	switch (tcr->DEST_length) {
6170 	default:
6171 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6172 		return;
6173 
6174 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6175 		/*
6176 		 * XXX: The check for valid DEST_length was not there
6177 		 * in earlier releases and some buggy
6178 		 * TLI apps (e.g Sybase) got away with not feeding
6179 		 * in sin_zero part of address.
6180 		 * We allow that bug to keep those buggy apps humming.
6181 		 * Test suites require the check on DEST_length.
6182 		 * We construct a new mblk with valid DEST_length
6183 		 * free the original so the rest of the code does
6184 		 * not have to keep track of this special shorter
6185 		 * length address case.
6186 		 */
6187 		mblk_t *nmp;
6188 		struct T_conn_req *ntcr;
6189 		sin_t *nsin;
6190 
6191 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6192 		    tcr->OPT_length, BPRI_HI);
6193 		if (nmp == NULL) {
6194 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6195 			return;
6196 		}
6197 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6198 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6199 		ntcr->PRIM_type = T_CONN_REQ;
6200 		ntcr->DEST_length = sizeof (sin_t);
6201 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6202 
6203 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6204 		*nsin = sin_null;
6205 		/* Get pointer to shorter address to copy from original mp */
6206 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6207 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6208 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6209 			freemsg(nmp);
6210 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6211 			return;
6212 		}
6213 		nsin->sin_family = sin->sin_family;
6214 		nsin->sin_port = sin->sin_port;
6215 		nsin->sin_addr = sin->sin_addr;
6216 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6217 		nmp->b_wptr = (uchar_t *)&nsin[1];
6218 		if (tcr->OPT_length != 0) {
6219 			ntcr->OPT_length = tcr->OPT_length;
6220 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6221 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6222 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6223 			    tcr->OPT_length);
6224 			nmp->b_wptr += tcr->OPT_length;
6225 		}
6226 		freemsg(mp);	/* original mp freed */
6227 		mp = nmp;	/* re-initialize original variables */
6228 		tcr = ntcr;
6229 	}
6230 	/* FALLTHRU */
6231 
6232 	case sizeof (sin_t):
6233 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6234 		    sizeof (sin_t));
6235 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6236 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6237 			return;
6238 		}
6239 		if (tcp->tcp_family != AF_INET ||
6240 		    sin->sin_family != AF_INET) {
6241 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6242 			return;
6243 		}
6244 		if (sin->sin_port == 0) {
6245 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6246 			return;
6247 		}
6248 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6249 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6250 			return;
6251 		}
6252 
6253 		break;
6254 
6255 	case sizeof (sin6_t):
6256 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6257 		    sizeof (sin6_t));
6258 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6259 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6260 			return;
6261 		}
6262 		if (tcp->tcp_family != AF_INET6 ||
6263 		    sin6->sin6_family != AF_INET6) {
6264 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6265 			return;
6266 		}
6267 		if (sin6->sin6_port == 0) {
6268 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6269 			return;
6270 		}
6271 		break;
6272 	}
6273 	/*
6274 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6275 	 * should key on their sequence number and cut them loose.
6276 	 */
6277 
6278 	/*
6279 	 * If options passed in, feed it for verification and handling
6280 	 */
6281 	if (tcr->OPT_length != 0) {
6282 		mblk_t	*ok_mp;
6283 		mblk_t	*discon_mp;
6284 		mblk_t  *conn_opts_mp;
6285 		int t_error, sys_error, do_disconnect;
6286 
6287 		conn_opts_mp = NULL;
6288 
6289 		if (tcp_conprim_opt_process(tcp, mp,
6290 			&do_disconnect, &t_error, &sys_error) < 0) {
6291 			if (do_disconnect) {
6292 				ASSERT(t_error == 0 && sys_error == 0);
6293 				discon_mp = mi_tpi_discon_ind(NULL,
6294 				    ECONNREFUSED, 0);
6295 				if (!discon_mp) {
6296 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6297 					    TSYSERR, ENOMEM);
6298 					return;
6299 				}
6300 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6301 				if (!ok_mp) {
6302 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6303 					    TSYSERR, ENOMEM);
6304 					return;
6305 				}
6306 				qreply(q, ok_mp);
6307 				qreply(q, discon_mp); /* no flush! */
6308 			} else {
6309 				ASSERT(t_error != 0);
6310 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6311 				    sys_error);
6312 			}
6313 			return;
6314 		}
6315 		/*
6316 		 * Success in setting options, the mp option buffer represented
6317 		 * by OPT_length/offset has been potentially modified and
6318 		 * contains results of option processing. We copy it in
6319 		 * another mp to save it for potentially influencing returning
6320 		 * it in T_CONN_CONN.
6321 		 */
6322 		if (tcr->OPT_length != 0) { /* there are resulting options */
6323 			conn_opts_mp = copyb(mp);
6324 			if (!conn_opts_mp) {
6325 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6326 				    TSYSERR, ENOMEM);
6327 				return;
6328 			}
6329 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6330 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6331 			/*
6332 			 * Note:
6333 			 * These resulting option negotiation can include any
6334 			 * end-to-end negotiation options but there no such
6335 			 * thing (yet?) in our TCP/IP.
6336 			 */
6337 		}
6338 	}
6339 
6340 	/*
6341 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6342 	 * make sure that the template IP header in the tcp structure is an
6343 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6344 	 * need to this before we call tcp_bindi() so that the port lookup
6345 	 * code will look for ports in the correct port space (IPv4 and
6346 	 * IPv6 have separate port spaces).
6347 	 */
6348 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6349 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6350 		int err = 0;
6351 
6352 		err = tcp_header_init_ipv4(tcp);
6353 		if (err != 0) {
6354 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6355 			goto connect_failed;
6356 		}
6357 		if (tcp->tcp_lport != 0)
6358 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6359 	}
6360 
6361 	switch (tcp->tcp_state) {
6362 	case TCPS_IDLE:
6363 		/*
6364 		 * We support quick connect, refer to comments in
6365 		 * tcp_connect_*()
6366 		 */
6367 		/* FALLTHRU */
6368 	case TCPS_BOUND:
6369 	case TCPS_LISTEN:
6370 		if (tcp->tcp_family == AF_INET6) {
6371 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6372 				tcp_connect_ipv6(tcp, mp,
6373 				    &sin6->sin6_addr,
6374 				    sin6->sin6_port, sin6->sin6_flowinfo,
6375 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6376 				return;
6377 			}
6378 			/*
6379 			 * Destination adress is mapped IPv6 address.
6380 			 * Source bound address should be unspecified or
6381 			 * IPv6 mapped address as well.
6382 			 */
6383 			if (!IN6_IS_ADDR_UNSPECIFIED(
6384 			    &tcp->tcp_bound_source_v6) &&
6385 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6386 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6387 				    EADDRNOTAVAIL);
6388 				break;
6389 			}
6390 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6391 			dstport = sin6->sin6_port;
6392 			srcid = sin6->__sin6_src_id;
6393 		} else {
6394 			dstaddrp = &sin->sin_addr.s_addr;
6395 			dstport = sin->sin_port;
6396 			srcid = 0;
6397 		}
6398 
6399 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6400 		return;
6401 	default:
6402 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6403 		break;
6404 	}
6405 	/*
6406 	 * Note: Code below is the "failure" case
6407 	 */
6408 	/* return error ack and blow away saved option results if any */
6409 connect_failed:
6410 	if (mp != NULL)
6411 		putnext(tcp->tcp_rq, mp);
6412 	else {
6413 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6414 		    TSYSERR, ENOMEM);
6415 	}
6416 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6417 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6418 }
6419 
6420 /*
6421  * Handle connect to IPv4 destinations, including connections for AF_INET6
6422  * sockets connecting to IPv4 mapped IPv6 destinations.
6423  */
6424 static void
6425 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6426     uint_t srcid)
6427 {
6428 	tcph_t	*tcph;
6429 	mblk_t	*mp1;
6430 	ipaddr_t dstaddr = *dstaddrp;
6431 	int32_t	oldstate;
6432 	uint16_t lport;
6433 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6434 
6435 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6436 
6437 	/* Check for attempt to connect to INADDR_ANY */
6438 	if (dstaddr == INADDR_ANY)  {
6439 		/*
6440 		 * SunOS 4.x and 4.3 BSD allow an application
6441 		 * to connect a TCP socket to INADDR_ANY.
6442 		 * When they do this, the kernel picks the
6443 		 * address of one interface and uses it
6444 		 * instead.  The kernel usually ends up
6445 		 * picking the address of the loopback
6446 		 * interface.  This is an undocumented feature.
6447 		 * However, we provide the same thing here
6448 		 * in order to have source and binary
6449 		 * compatibility with SunOS 4.x.
6450 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6451 		 * generate the T_CONN_CON.
6452 		 */
6453 		dstaddr = htonl(INADDR_LOOPBACK);
6454 		*dstaddrp = dstaddr;
6455 	}
6456 
6457 	/* Handle __sin6_src_id if socket not bound to an IP address */
6458 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6459 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6460 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6461 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6462 		    tcp->tcp_ipha->ipha_src);
6463 	}
6464 
6465 	/*
6466 	 * Don't let an endpoint connect to itself.  Note that
6467 	 * the test here does not catch the case where the
6468 	 * source IP addr was left unspecified by the user. In
6469 	 * this case, the source addr is set in tcp_adapt_ire()
6470 	 * using the reply to the T_BIND message that we send
6471 	 * down to IP here and the check is repeated in tcp_rput_other.
6472 	 */
6473 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6474 	    dstport == tcp->tcp_lport) {
6475 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6476 		goto failed;
6477 	}
6478 
6479 	tcp->tcp_ipha->ipha_dst = dstaddr;
6480 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6481 
6482 	/*
6483 	 * Massage a source route if any putting the first hop
6484 	 * in iph_dst. Compute a starting value for the checksum which
6485 	 * takes into account that the original iph_dst should be
6486 	 * included in the checksum but that ip will include the
6487 	 * first hop in the source route in the tcp checksum.
6488 	 */
6489 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6490 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6491 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6492 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6493 	if ((int)tcp->tcp_sum < 0)
6494 		tcp->tcp_sum--;
6495 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6496 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6497 	    (tcp->tcp_sum >> 16));
6498 	tcph = tcp->tcp_tcph;
6499 	*(uint16_t *)tcph->th_fport = dstport;
6500 	tcp->tcp_fport = dstport;
6501 
6502 	oldstate = tcp->tcp_state;
6503 	/*
6504 	 * At this point the remote destination address and remote port fields
6505 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6506 	 * have to see which state tcp was in so we can take apropriate action.
6507 	 */
6508 	if (oldstate == TCPS_IDLE) {
6509 		/*
6510 		 * We support a quick connect capability here, allowing
6511 		 * clients to transition directly from IDLE to SYN_SENT
6512 		 * tcp_bindi will pick an unused port, insert the connection
6513 		 * in the bind hash and transition to BOUND state.
6514 		 */
6515 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6516 		    tcp, B_TRUE);
6517 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6518 		    B_FALSE, B_FALSE);
6519 		if (lport == 0) {
6520 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6521 			goto failed;
6522 		}
6523 	}
6524 	tcp->tcp_state = TCPS_SYN_SENT;
6525 
6526 	/*
6527 	 * TODO: allow data with connect requests
6528 	 * by unlinking M_DATA trailers here and
6529 	 * linking them in behind the T_OK_ACK mblk.
6530 	 * The tcp_rput() bind ack handler would then
6531 	 * feed them to tcp_wput_data() rather than call
6532 	 * tcp_timer().
6533 	 */
6534 	mp = mi_tpi_ok_ack_alloc(mp);
6535 	if (!mp) {
6536 		tcp->tcp_state = oldstate;
6537 		goto failed;
6538 	}
6539 	if (tcp->tcp_family == AF_INET) {
6540 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6541 		    sizeof (ipa_conn_t));
6542 	} else {
6543 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6544 		    sizeof (ipa6_conn_t));
6545 	}
6546 	if (mp1) {
6547 		/* Hang onto the T_OK_ACK for later. */
6548 		linkb(mp1, mp);
6549 		mblk_setcred(mp1, tcp->tcp_cred);
6550 		if (tcp->tcp_family == AF_INET)
6551 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6552 		else {
6553 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6554 			    &tcp->tcp_sticky_ipp);
6555 		}
6556 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6557 		tcp->tcp_active_open = 1;
6558 		/*
6559 		 * If the bind cannot complete immediately
6560 		 * IP will arrange to call tcp_rput_other
6561 		 * when the bind completes.
6562 		 */
6563 		if (mp1 != NULL)
6564 			tcp_rput_other(tcp, mp1);
6565 		return;
6566 	}
6567 	/* Error case */
6568 	tcp->tcp_state = oldstate;
6569 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6570 
6571 failed:
6572 	/* return error ack and blow away saved option results if any */
6573 	if (mp != NULL)
6574 		putnext(tcp->tcp_rq, mp);
6575 	else {
6576 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6577 		    TSYSERR, ENOMEM);
6578 	}
6579 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6580 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6581 
6582 }
6583 
6584 /*
6585  * Handle connect to IPv6 destinations.
6586  */
6587 static void
6588 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6589     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6590 {
6591 	tcph_t	*tcph;
6592 	mblk_t	*mp1;
6593 	ip6_rthdr_t *rth;
6594 	int32_t  oldstate;
6595 	uint16_t lport;
6596 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6597 
6598 	ASSERT(tcp->tcp_family == AF_INET6);
6599 
6600 	/*
6601 	 * If we're here, it means that the destination address is a native
6602 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6603 	 * reason why it might not be IPv6 is if the socket was bound to an
6604 	 * IPv4-mapped IPv6 address.
6605 	 */
6606 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6607 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6608 		goto failed;
6609 	}
6610 
6611 	/*
6612 	 * Interpret a zero destination to mean loopback.
6613 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6614 	 * generate the T_CONN_CON.
6615 	 */
6616 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6617 		*dstaddrp = ipv6_loopback;
6618 	}
6619 
6620 	/* Handle __sin6_src_id if socket not bound to an IP address */
6621 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6622 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6623 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6624 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6625 	}
6626 
6627 	/*
6628 	 * Take care of the scope_id now and add ip6i_t
6629 	 * if ip6i_t is not already allocated through TCP
6630 	 * sticky options. At this point tcp_ip6h does not
6631 	 * have dst info, thus use dstaddrp.
6632 	 */
6633 	if (scope_id != 0 &&
6634 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6635 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6636 		ip6i_t  *ip6i;
6637 
6638 		ipp->ipp_ifindex = scope_id;
6639 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6640 
6641 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6642 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6643 			/* Already allocated */
6644 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6645 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6646 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6647 		} else {
6648 			int reterr;
6649 
6650 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6651 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6652 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6653 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6654 			if (reterr != 0)
6655 				goto failed;
6656 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6657 		}
6658 	}
6659 
6660 	/*
6661 	 * Don't let an endpoint connect to itself.  Note that
6662 	 * the test here does not catch the case where the
6663 	 * source IP addr was left unspecified by the user. In
6664 	 * this case, the source addr is set in tcp_adapt_ire()
6665 	 * using the reply to the T_BIND message that we send
6666 	 * down to IP here and the check is repeated in tcp_rput_other.
6667 	 */
6668 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6669 	    (dstport == tcp->tcp_lport)) {
6670 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6671 		goto failed;
6672 	}
6673 
6674 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6675 	tcp->tcp_remote_v6 = *dstaddrp;
6676 	tcp->tcp_ip6h->ip6_vcf =
6677 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6678 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6679 
6680 
6681 	/*
6682 	 * Massage a routing header (if present) putting the first hop
6683 	 * in ip6_dst. Compute a starting value for the checksum which
6684 	 * takes into account that the original ip6_dst should be
6685 	 * included in the checksum but that ip will include the
6686 	 * first hop in the source route in the tcp checksum.
6687 	 */
6688 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6689 	if (rth != NULL) {
6690 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6691 		    tcps->tcps_netstack);
6692 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6693 		    (tcp->tcp_sum >> 16));
6694 	} else {
6695 		tcp->tcp_sum = 0;
6696 	}
6697 
6698 	tcph = tcp->tcp_tcph;
6699 	*(uint16_t *)tcph->th_fport = dstport;
6700 	tcp->tcp_fport = dstport;
6701 
6702 	oldstate = tcp->tcp_state;
6703 	/*
6704 	 * At this point the remote destination address and remote port fields
6705 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6706 	 * have to see which state tcp was in so we can take apropriate action.
6707 	 */
6708 	if (oldstate == TCPS_IDLE) {
6709 		/*
6710 		 * We support a quick connect capability here, allowing
6711 		 * clients to transition directly from IDLE to SYN_SENT
6712 		 * tcp_bindi will pick an unused port, insert the connection
6713 		 * in the bind hash and transition to BOUND state.
6714 		 */
6715 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6716 		    tcp, B_TRUE);
6717 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6718 		    B_FALSE, B_FALSE);
6719 		if (lport == 0) {
6720 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6721 			goto failed;
6722 		}
6723 	}
6724 	tcp->tcp_state = TCPS_SYN_SENT;
6725 	/*
6726 	 * TODO: allow data with connect requests
6727 	 * by unlinking M_DATA trailers here and
6728 	 * linking them in behind the T_OK_ACK mblk.
6729 	 * The tcp_rput() bind ack handler would then
6730 	 * feed them to tcp_wput_data() rather than call
6731 	 * tcp_timer().
6732 	 */
6733 	mp = mi_tpi_ok_ack_alloc(mp);
6734 	if (!mp) {
6735 		tcp->tcp_state = oldstate;
6736 		goto failed;
6737 	}
6738 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6739 	if (mp1) {
6740 		/* Hang onto the T_OK_ACK for later. */
6741 		linkb(mp1, mp);
6742 		mblk_setcred(mp1, tcp->tcp_cred);
6743 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6744 		    &tcp->tcp_sticky_ipp);
6745 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6746 		tcp->tcp_active_open = 1;
6747 		/* ip_bind_v6() may return ACK or ERROR */
6748 		if (mp1 != NULL)
6749 			tcp_rput_other(tcp, mp1);
6750 		return;
6751 	}
6752 	/* Error case */
6753 	tcp->tcp_state = oldstate;
6754 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6755 
6756 failed:
6757 	/* return error ack and blow away saved option results if any */
6758 	if (mp != NULL)
6759 		putnext(tcp->tcp_rq, mp);
6760 	else {
6761 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6762 		    TSYSERR, ENOMEM);
6763 	}
6764 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6765 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6766 }
6767 
6768 /*
6769  * We need a stream q for detached closing tcp connections
6770  * to use.  Our client hereby indicates that this q is the
6771  * one to use.
6772  */
6773 static void
6774 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6775 {
6776 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6777 	queue_t	*q = tcp->tcp_wq;
6778 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6779 
6780 #ifdef NS_DEBUG
6781 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6782 	    tcps->tcps_netstack->netstack_stackid);
6783 #endif
6784 	mp->b_datap->db_type = M_IOCACK;
6785 	iocp->ioc_count = 0;
6786 	mutex_enter(&tcps->tcps_g_q_lock);
6787 	if (tcps->tcps_g_q != NULL) {
6788 		mutex_exit(&tcps->tcps_g_q_lock);
6789 		iocp->ioc_error = EALREADY;
6790 	} else {
6791 		mblk_t *mp1;
6792 
6793 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6794 		if (mp1 == NULL) {
6795 			mutex_exit(&tcps->tcps_g_q_lock);
6796 			iocp->ioc_error = ENOMEM;
6797 		} else {
6798 			tcps->tcps_g_q = tcp->tcp_rq;
6799 			mutex_exit(&tcps->tcps_g_q_lock);
6800 			iocp->ioc_error = 0;
6801 			iocp->ioc_rval = 0;
6802 			/*
6803 			 * We are passing tcp_sticky_ipp as NULL
6804 			 * as it is not useful for tcp_default queue
6805 			 */
6806 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6807 			if (mp1 != NULL)
6808 				tcp_rput_other(tcp, mp1);
6809 		}
6810 	}
6811 	qreply(q, mp);
6812 }
6813 
6814 /*
6815  * Our client hereby directs us to reject the connection request
6816  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6817  * of sending the appropriate RST, not an ICMP error.
6818  */
6819 static void
6820 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6821 {
6822 	tcp_t	*ltcp = NULL;
6823 	t_scalar_t seqnum;
6824 	conn_t	*connp;
6825 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6826 
6827 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6828 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6829 		tcp_err_ack(tcp, mp, TPROTO, 0);
6830 		return;
6831 	}
6832 
6833 	/*
6834 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6835 	 * when the stream is in BOUND state. Do not send a reset,
6836 	 * since the destination IP address is not valid, and it can
6837 	 * be the initialized value of all zeros (broadcast address).
6838 	 *
6839 	 * If TCP has sent down a bind request to IP and has not
6840 	 * received the reply, reject the request.  Otherwise, TCP
6841 	 * will be confused.
6842 	 */
6843 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6844 		if (tcp->tcp_debug) {
6845 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6846 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6847 		}
6848 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6849 		return;
6850 	}
6851 
6852 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6853 
6854 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6855 
6856 		/*
6857 		 * According to TPI, for non-listeners, ignore seqnum
6858 		 * and disconnect.
6859 		 * Following interpretation of -1 seqnum is historical
6860 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6861 		 * a valid seqnum should not be -1).
6862 		 *
6863 		 *	-1 means disconnect everything
6864 		 *	regardless even on a listener.
6865 		 */
6866 
6867 		int old_state = tcp->tcp_state;
6868 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6869 
6870 		/*
6871 		 * The connection can't be on the tcp_time_wait_head list
6872 		 * since it is not detached.
6873 		 */
6874 		ASSERT(tcp->tcp_time_wait_next == NULL);
6875 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6876 		ASSERT(tcp->tcp_time_wait_expire == 0);
6877 		ltcp = NULL;
6878 		/*
6879 		 * If it used to be a listener, check to make sure no one else
6880 		 * has taken the port before switching back to LISTEN state.
6881 		 */
6882 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6883 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6884 			    tcp->tcp_ipha->ipha_src,
6885 			    tcp->tcp_connp->conn_zoneid, ipst);
6886 			if (connp != NULL)
6887 				ltcp = connp->conn_tcp;
6888 		} else {
6889 			/* Allow tcp_bound_if listeners? */
6890 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6891 			    &tcp->tcp_ip6h->ip6_src, 0,
6892 			    tcp->tcp_connp->conn_zoneid, ipst);
6893 			if (connp != NULL)
6894 				ltcp = connp->conn_tcp;
6895 		}
6896 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6897 			tcp->tcp_state = TCPS_LISTEN;
6898 		} else if (old_state > TCPS_BOUND) {
6899 			tcp->tcp_conn_req_max = 0;
6900 			tcp->tcp_state = TCPS_BOUND;
6901 		}
6902 		if (ltcp != NULL)
6903 			CONN_DEC_REF(ltcp->tcp_connp);
6904 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6905 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6906 		} else if (old_state == TCPS_ESTABLISHED ||
6907 		    old_state == TCPS_CLOSE_WAIT) {
6908 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6909 		}
6910 
6911 		if (tcp->tcp_fused)
6912 			tcp_unfuse(tcp);
6913 
6914 		mutex_enter(&tcp->tcp_eager_lock);
6915 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6916 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6917 			tcp_eager_cleanup(tcp, 0);
6918 		}
6919 		mutex_exit(&tcp->tcp_eager_lock);
6920 
6921 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6922 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6923 
6924 		tcp_reinit(tcp);
6925 
6926 		if (old_state >= TCPS_ESTABLISHED) {
6927 			/* Send M_FLUSH according to TPI */
6928 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6929 		}
6930 		mp = mi_tpi_ok_ack_alloc(mp);
6931 		if (mp)
6932 			putnext(tcp->tcp_rq, mp);
6933 		return;
6934 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6935 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6936 		return;
6937 	}
6938 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6939 		/* Send M_FLUSH according to TPI */
6940 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6941 	}
6942 	mp = mi_tpi_ok_ack_alloc(mp);
6943 	if (mp)
6944 		putnext(tcp->tcp_rq, mp);
6945 }
6946 
6947 /*
6948  * Diagnostic routine used to return a string associated with the tcp state.
6949  * Note that if the caller does not supply a buffer, it will use an internal
6950  * static string.  This means that if multiple threads call this function at
6951  * the same time, output can be corrupted...  Note also that this function
6952  * does not check the size of the supplied buffer.  The caller has to make
6953  * sure that it is big enough.
6954  */
6955 static char *
6956 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6957 {
6958 	char		buf1[30];
6959 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6960 	char		*buf;
6961 	char		*cp;
6962 	in6_addr_t	local, remote;
6963 	char		local_addrbuf[INET6_ADDRSTRLEN];
6964 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6965 
6966 	if (sup_buf != NULL)
6967 		buf = sup_buf;
6968 	else
6969 		buf = priv_buf;
6970 
6971 	if (tcp == NULL)
6972 		return ("NULL_TCP");
6973 	switch (tcp->tcp_state) {
6974 	case TCPS_CLOSED:
6975 		cp = "TCP_CLOSED";
6976 		break;
6977 	case TCPS_IDLE:
6978 		cp = "TCP_IDLE";
6979 		break;
6980 	case TCPS_BOUND:
6981 		cp = "TCP_BOUND";
6982 		break;
6983 	case TCPS_LISTEN:
6984 		cp = "TCP_LISTEN";
6985 		break;
6986 	case TCPS_SYN_SENT:
6987 		cp = "TCP_SYN_SENT";
6988 		break;
6989 	case TCPS_SYN_RCVD:
6990 		cp = "TCP_SYN_RCVD";
6991 		break;
6992 	case TCPS_ESTABLISHED:
6993 		cp = "TCP_ESTABLISHED";
6994 		break;
6995 	case TCPS_CLOSE_WAIT:
6996 		cp = "TCP_CLOSE_WAIT";
6997 		break;
6998 	case TCPS_FIN_WAIT_1:
6999 		cp = "TCP_FIN_WAIT_1";
7000 		break;
7001 	case TCPS_CLOSING:
7002 		cp = "TCP_CLOSING";
7003 		break;
7004 	case TCPS_LAST_ACK:
7005 		cp = "TCP_LAST_ACK";
7006 		break;
7007 	case TCPS_FIN_WAIT_2:
7008 		cp = "TCP_FIN_WAIT_2";
7009 		break;
7010 	case TCPS_TIME_WAIT:
7011 		cp = "TCP_TIME_WAIT";
7012 		break;
7013 	default:
7014 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7015 		cp = buf1;
7016 		break;
7017 	}
7018 	switch (format) {
7019 	case DISP_ADDR_AND_PORT:
7020 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7021 			/*
7022 			 * Note that we use the remote address in the tcp_b
7023 			 * structure.  This means that it will print out
7024 			 * the real destination address, not the next hop's
7025 			 * address if source routing is used.
7026 			 */
7027 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7028 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7029 
7030 		} else {
7031 			local = tcp->tcp_ip_src_v6;
7032 			remote = tcp->tcp_remote_v6;
7033 		}
7034 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7035 		    sizeof (local_addrbuf));
7036 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7037 		    sizeof (remote_addrbuf));
7038 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7039 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7040 		    ntohs(tcp->tcp_fport), cp);
7041 		break;
7042 	case DISP_PORT_ONLY:
7043 	default:
7044 		(void) mi_sprintf(buf, "[%u, %u] %s",
7045 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7046 		break;
7047 	}
7048 
7049 	return (buf);
7050 }
7051 
7052 /*
7053  * Called via squeue to get on to eager's perimeter. It sends a
7054  * TH_RST if eager is in the fanout table. The listener wants the
7055  * eager to disappear either by means of tcp_eager_blowoff() or
7056  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7057  * called (via squeue) if the eager cannot be inserted in the
7058  * fanout table in tcp_conn_request().
7059  */
7060 /* ARGSUSED */
7061 void
7062 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7063 {
7064 	conn_t	*econnp = (conn_t *)arg;
7065 	tcp_t	*eager = econnp->conn_tcp;
7066 	tcp_t	*listener = eager->tcp_listener;
7067 	tcp_stack_t	*tcps = eager->tcp_tcps;
7068 
7069 	/*
7070 	 * We could be called because listener is closing. Since
7071 	 * the eager is using listener's queue's, its not safe.
7072 	 * Better use the default queue just to send the TH_RST
7073 	 * out.
7074 	 */
7075 	ASSERT(tcps->tcps_g_q != NULL);
7076 	eager->tcp_rq = tcps->tcps_g_q;
7077 	eager->tcp_wq = WR(tcps->tcps_g_q);
7078 
7079 	/*
7080 	 * An eager's conn_fanout will be NULL if it's a duplicate
7081 	 * for an existing 4-tuples in the conn fanout table.
7082 	 * We don't want to send an RST out in such case.
7083 	 */
7084 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7085 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7086 		    eager, eager->tcp_snxt, 0, TH_RST);
7087 	}
7088 
7089 	/* We are here because listener wants this eager gone */
7090 	if (listener != NULL) {
7091 		mutex_enter(&listener->tcp_eager_lock);
7092 		tcp_eager_unlink(eager);
7093 		if (eager->tcp_tconnind_started) {
7094 			/*
7095 			 * The eager has sent a conn_ind up to the
7096 			 * listener but listener decides to close
7097 			 * instead. We need to drop the extra ref
7098 			 * placed on eager in tcp_rput_data() before
7099 			 * sending the conn_ind to listener.
7100 			 */
7101 			CONN_DEC_REF(econnp);
7102 		}
7103 		mutex_exit(&listener->tcp_eager_lock);
7104 		CONN_DEC_REF(listener->tcp_connp);
7105 	}
7106 
7107 	if (eager->tcp_state > TCPS_BOUND)
7108 		tcp_close_detached(eager);
7109 }
7110 
7111 /*
7112  * Reset any eager connection hanging off this listener marked
7113  * with 'seqnum' and then reclaim it's resources.
7114  */
7115 static boolean_t
7116 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7117 {
7118 	tcp_t	*eager;
7119 	mblk_t 	*mp;
7120 	tcp_stack_t	*tcps = listener->tcp_tcps;
7121 
7122 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7123 	eager = listener;
7124 	mutex_enter(&listener->tcp_eager_lock);
7125 	do {
7126 		eager = eager->tcp_eager_next_q;
7127 		if (eager == NULL) {
7128 			mutex_exit(&listener->tcp_eager_lock);
7129 			return (B_FALSE);
7130 		}
7131 	} while (eager->tcp_conn_req_seqnum != seqnum);
7132 
7133 	if (eager->tcp_closemp_used) {
7134 		mutex_exit(&listener->tcp_eager_lock);
7135 		return (B_TRUE);
7136 	}
7137 	eager->tcp_closemp_used = B_TRUE;
7138 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7139 	CONN_INC_REF(eager->tcp_connp);
7140 	mutex_exit(&listener->tcp_eager_lock);
7141 	mp = &eager->tcp_closemp;
7142 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7143 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7144 	return (B_TRUE);
7145 }
7146 
7147 /*
7148  * Reset any eager connection hanging off this listener
7149  * and then reclaim it's resources.
7150  */
7151 static void
7152 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7153 {
7154 	tcp_t	*eager;
7155 	mblk_t	*mp;
7156 	tcp_stack_t	*tcps = listener->tcp_tcps;
7157 
7158 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7159 
7160 	if (!q0_only) {
7161 		/* First cleanup q */
7162 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7163 		eager = listener->tcp_eager_next_q;
7164 		while (eager != NULL) {
7165 			if (!eager->tcp_closemp_used) {
7166 				eager->tcp_closemp_used = B_TRUE;
7167 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7168 				CONN_INC_REF(eager->tcp_connp);
7169 				mp = &eager->tcp_closemp;
7170 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7171 				    tcp_eager_kill, eager->tcp_connp,
7172 				    SQTAG_TCP_EAGER_CLEANUP);
7173 			}
7174 			eager = eager->tcp_eager_next_q;
7175 		}
7176 	}
7177 	/* Then cleanup q0 */
7178 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7179 	eager = listener->tcp_eager_next_q0;
7180 	while (eager != listener) {
7181 		if (!eager->tcp_closemp_used) {
7182 			eager->tcp_closemp_used = B_TRUE;
7183 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7184 			CONN_INC_REF(eager->tcp_connp);
7185 			mp = &eager->tcp_closemp;
7186 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7187 			    tcp_eager_kill, eager->tcp_connp,
7188 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7189 		}
7190 		eager = eager->tcp_eager_next_q0;
7191 	}
7192 }
7193 
7194 /*
7195  * If we are an eager connection hanging off a listener that hasn't
7196  * formally accepted the connection yet, get off his list and blow off
7197  * any data that we have accumulated.
7198  */
7199 static void
7200 tcp_eager_unlink(tcp_t *tcp)
7201 {
7202 	tcp_t	*listener = tcp->tcp_listener;
7203 
7204 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7205 	ASSERT(listener != NULL);
7206 	if (tcp->tcp_eager_next_q0 != NULL) {
7207 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7208 
7209 		/* Remove the eager tcp from q0 */
7210 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7211 		    tcp->tcp_eager_prev_q0;
7212 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7213 		    tcp->tcp_eager_next_q0;
7214 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7215 		listener->tcp_conn_req_cnt_q0--;
7216 
7217 		tcp->tcp_eager_next_q0 = NULL;
7218 		tcp->tcp_eager_prev_q0 = NULL;
7219 
7220 		/*
7221 		 * Take the eager out, if it is in the list of droppable
7222 		 * eagers.
7223 		 */
7224 		MAKE_UNDROPPABLE(tcp);
7225 
7226 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7227 			/* we have timed out before */
7228 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7229 			listener->tcp_syn_rcvd_timeout--;
7230 		}
7231 	} else {
7232 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7233 		tcp_t	*prev = NULL;
7234 
7235 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7236 			if (tcpp[0] == tcp) {
7237 				if (listener->tcp_eager_last_q == tcp) {
7238 					/*
7239 					 * If we are unlinking the last
7240 					 * element on the list, adjust
7241 					 * tail pointer. Set tail pointer
7242 					 * to nil when list is empty.
7243 					 */
7244 					ASSERT(tcp->tcp_eager_next_q == NULL);
7245 					if (listener->tcp_eager_last_q ==
7246 					    listener->tcp_eager_next_q) {
7247 						listener->tcp_eager_last_q =
7248 						NULL;
7249 					} else {
7250 						/*
7251 						 * We won't get here if there
7252 						 * is only one eager in the
7253 						 * list.
7254 						 */
7255 						ASSERT(prev != NULL);
7256 						listener->tcp_eager_last_q =
7257 						    prev;
7258 					}
7259 				}
7260 				tcpp[0] = tcp->tcp_eager_next_q;
7261 				tcp->tcp_eager_next_q = NULL;
7262 				tcp->tcp_eager_last_q = NULL;
7263 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7264 				listener->tcp_conn_req_cnt_q--;
7265 				break;
7266 			}
7267 			prev = tcpp[0];
7268 		}
7269 	}
7270 	tcp->tcp_listener = NULL;
7271 }
7272 
7273 /* Shorthand to generate and send TPI error acks to our client */
7274 static void
7275 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7276 {
7277 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7278 		putnext(tcp->tcp_rq, mp);
7279 }
7280 
7281 /* Shorthand to generate and send TPI error acks to our client */
7282 static void
7283 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7284     int t_error, int sys_error)
7285 {
7286 	struct T_error_ack	*teackp;
7287 
7288 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7289 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7290 		teackp = (struct T_error_ack *)mp->b_rptr;
7291 		teackp->ERROR_prim = primitive;
7292 		teackp->TLI_error = t_error;
7293 		teackp->UNIX_error = sys_error;
7294 		putnext(tcp->tcp_rq, mp);
7295 	}
7296 }
7297 
7298 /*
7299  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7300  * but instead the code relies on:
7301  * - the fact that the address of the array and its size never changes
7302  * - the atomic assignment of the elements of the array
7303  */
7304 /* ARGSUSED */
7305 static int
7306 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7307 {
7308 	int i;
7309 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7310 
7311 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7312 		if (tcps->tcps_g_epriv_ports[i] != 0)
7313 			(void) mi_mpprintf(mp, "%d ",
7314 			    tcps->tcps_g_epriv_ports[i]);
7315 	}
7316 	return (0);
7317 }
7318 
7319 /*
7320  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7321  * threads from changing it at the same time.
7322  */
7323 /* ARGSUSED */
7324 static int
7325 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7326     cred_t *cr)
7327 {
7328 	long	new_value;
7329 	int	i;
7330 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7331 
7332 	/*
7333 	 * Fail the request if the new value does not lie within the
7334 	 * port number limits.
7335 	 */
7336 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7337 	    new_value <= 0 || new_value >= 65536) {
7338 		return (EINVAL);
7339 	}
7340 
7341 	mutex_enter(&tcps->tcps_epriv_port_lock);
7342 	/* Check if the value is already in the list */
7343 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7344 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7345 			mutex_exit(&tcps->tcps_epriv_port_lock);
7346 			return (EEXIST);
7347 		}
7348 	}
7349 	/* Find an empty slot */
7350 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7351 		if (tcps->tcps_g_epriv_ports[i] == 0)
7352 			break;
7353 	}
7354 	if (i == tcps->tcps_g_num_epriv_ports) {
7355 		mutex_exit(&tcps->tcps_epriv_port_lock);
7356 		return (EOVERFLOW);
7357 	}
7358 	/* Set the new value */
7359 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7360 	mutex_exit(&tcps->tcps_epriv_port_lock);
7361 	return (0);
7362 }
7363 
7364 /*
7365  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7366  * threads from changing it at the same time.
7367  */
7368 /* ARGSUSED */
7369 static int
7370 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7371     cred_t *cr)
7372 {
7373 	long	new_value;
7374 	int	i;
7375 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7376 
7377 	/*
7378 	 * Fail the request if the new value does not lie within the
7379 	 * port number limits.
7380 	 */
7381 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7382 	    new_value >= 65536) {
7383 		return (EINVAL);
7384 	}
7385 
7386 	mutex_enter(&tcps->tcps_epriv_port_lock);
7387 	/* Check that the value is already in the list */
7388 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7389 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7390 			break;
7391 	}
7392 	if (i == tcps->tcps_g_num_epriv_ports) {
7393 		mutex_exit(&tcps->tcps_epriv_port_lock);
7394 		return (ESRCH);
7395 	}
7396 	/* Clear the value */
7397 	tcps->tcps_g_epriv_ports[i] = 0;
7398 	mutex_exit(&tcps->tcps_epriv_port_lock);
7399 	return (0);
7400 }
7401 
7402 /* Return the TPI/TLI equivalent of our current tcp_state */
7403 static int
7404 tcp_tpistate(tcp_t *tcp)
7405 {
7406 	switch (tcp->tcp_state) {
7407 	case TCPS_IDLE:
7408 		return (TS_UNBND);
7409 	case TCPS_LISTEN:
7410 		/*
7411 		 * Return whether there are outstanding T_CONN_IND waiting
7412 		 * for the matching T_CONN_RES. Therefore don't count q0.
7413 		 */
7414 		if (tcp->tcp_conn_req_cnt_q > 0)
7415 			return (TS_WRES_CIND);
7416 		else
7417 			return (TS_IDLE);
7418 	case TCPS_BOUND:
7419 		return (TS_IDLE);
7420 	case TCPS_SYN_SENT:
7421 		return (TS_WCON_CREQ);
7422 	case TCPS_SYN_RCVD:
7423 		/*
7424 		 * Note: assumption: this has to the active open SYN_RCVD.
7425 		 * The passive instance is detached in SYN_RCVD stage of
7426 		 * incoming connection processing so we cannot get request
7427 		 * for T_info_ack on it.
7428 		 */
7429 		return (TS_WACK_CRES);
7430 	case TCPS_ESTABLISHED:
7431 		return (TS_DATA_XFER);
7432 	case TCPS_CLOSE_WAIT:
7433 		return (TS_WREQ_ORDREL);
7434 	case TCPS_FIN_WAIT_1:
7435 		return (TS_WIND_ORDREL);
7436 	case TCPS_FIN_WAIT_2:
7437 		return (TS_WIND_ORDREL);
7438 
7439 	case TCPS_CLOSING:
7440 	case TCPS_LAST_ACK:
7441 	case TCPS_TIME_WAIT:
7442 	case TCPS_CLOSED:
7443 		/*
7444 		 * Following TS_WACK_DREQ7 is a rendition of "not
7445 		 * yet TS_IDLE" TPI state. There is no best match to any
7446 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7447 		 * choose a value chosen that will map to TLI/XTI level
7448 		 * state of TSTATECHNG (state is process of changing) which
7449 		 * captures what this dummy state represents.
7450 		 */
7451 		return (TS_WACK_DREQ7);
7452 	default:
7453 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7454 		    tcp->tcp_state, tcp_display(tcp, NULL,
7455 		    DISP_PORT_ONLY));
7456 		return (TS_UNBND);
7457 	}
7458 }
7459 
7460 static void
7461 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7462 {
7463 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7464 
7465 	if (tcp->tcp_family == AF_INET6)
7466 		*tia = tcp_g_t_info_ack_v6;
7467 	else
7468 		*tia = tcp_g_t_info_ack;
7469 	tia->CURRENT_state = tcp_tpistate(tcp);
7470 	tia->OPT_size = tcp_max_optsize;
7471 	if (tcp->tcp_mss == 0) {
7472 		/* Not yet set - tcp_open does not set mss */
7473 		if (tcp->tcp_ipversion == IPV4_VERSION)
7474 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7475 		else
7476 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7477 	} else {
7478 		tia->TIDU_size = tcp->tcp_mss;
7479 	}
7480 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7481 }
7482 
7483 /*
7484  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7485  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7486  * tcp_g_t_info_ack.  The current state of the stream is copied from
7487  * tcp_state.
7488  */
7489 static void
7490 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7491 {
7492 	t_uscalar_t		cap_bits1;
7493 	struct T_capability_ack	*tcap;
7494 
7495 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7496 		freemsg(mp);
7497 		return;
7498 	}
7499 
7500 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7501 
7502 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7503 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7504 	if (mp == NULL)
7505 		return;
7506 
7507 	tcap = (struct T_capability_ack *)mp->b_rptr;
7508 	tcap->CAP_bits1 = 0;
7509 
7510 	if (cap_bits1 & TC1_INFO) {
7511 		tcp_copy_info(&tcap->INFO_ack, tcp);
7512 		tcap->CAP_bits1 |= TC1_INFO;
7513 	}
7514 
7515 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7516 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7517 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7518 	}
7519 
7520 	putnext(tcp->tcp_rq, mp);
7521 }
7522 
7523 /*
7524  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7525  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7526  * The current state of the stream is copied from tcp_state.
7527  */
7528 static void
7529 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7530 {
7531 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7532 	    T_INFO_ACK);
7533 	if (!mp) {
7534 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7535 		return;
7536 	}
7537 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7538 	putnext(tcp->tcp_rq, mp);
7539 }
7540 
7541 /* Respond to the TPI addr request */
7542 static void
7543 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7544 {
7545 	sin_t	*sin;
7546 	mblk_t	*ackmp;
7547 	struct T_addr_ack *taa;
7548 
7549 	/* Make it large enough for worst case */
7550 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7551 	    2 * sizeof (sin6_t), 1);
7552 	if (ackmp == NULL) {
7553 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7554 		return;
7555 	}
7556 
7557 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7558 		tcp_addr_req_ipv6(tcp, ackmp);
7559 		return;
7560 	}
7561 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7562 
7563 	bzero(taa, sizeof (struct T_addr_ack));
7564 	ackmp->b_wptr = (uchar_t *)&taa[1];
7565 
7566 	taa->PRIM_type = T_ADDR_ACK;
7567 	ackmp->b_datap->db_type = M_PCPROTO;
7568 
7569 	/*
7570 	 * Note: Following code assumes 32 bit alignment of basic
7571 	 * data structures like sin_t and struct T_addr_ack.
7572 	 */
7573 	if (tcp->tcp_state >= TCPS_BOUND) {
7574 		/*
7575 		 * Fill in local address
7576 		 */
7577 		taa->LOCADDR_length = sizeof (sin_t);
7578 		taa->LOCADDR_offset = sizeof (*taa);
7579 
7580 		sin = (sin_t *)&taa[1];
7581 
7582 		/* Fill zeroes and then intialize non-zero fields */
7583 		*sin = sin_null;
7584 
7585 		sin->sin_family = AF_INET;
7586 
7587 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7588 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7589 
7590 		ackmp->b_wptr = (uchar_t *)&sin[1];
7591 
7592 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7593 			/*
7594 			 * Fill in Remote address
7595 			 */
7596 			taa->REMADDR_length = sizeof (sin_t);
7597 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7598 						taa->LOCADDR_length);
7599 
7600 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7601 			*sin = sin_null;
7602 			sin->sin_family = AF_INET;
7603 			sin->sin_addr.s_addr = tcp->tcp_remote;
7604 			sin->sin_port = tcp->tcp_fport;
7605 
7606 			ackmp->b_wptr = (uchar_t *)&sin[1];
7607 		}
7608 	}
7609 	putnext(tcp->tcp_rq, ackmp);
7610 }
7611 
7612 /* Assumes that tcp_addr_req gets enough space and alignment */
7613 static void
7614 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7615 {
7616 	sin6_t	*sin6;
7617 	struct T_addr_ack *taa;
7618 
7619 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7620 	ASSERT(OK_32PTR(ackmp->b_rptr));
7621 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7622 	    2 * sizeof (sin6_t));
7623 
7624 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7625 
7626 	bzero(taa, sizeof (struct T_addr_ack));
7627 	ackmp->b_wptr = (uchar_t *)&taa[1];
7628 
7629 	taa->PRIM_type = T_ADDR_ACK;
7630 	ackmp->b_datap->db_type = M_PCPROTO;
7631 
7632 	/*
7633 	 * Note: Following code assumes 32 bit alignment of basic
7634 	 * data structures like sin6_t and struct T_addr_ack.
7635 	 */
7636 	if (tcp->tcp_state >= TCPS_BOUND) {
7637 		/*
7638 		 * Fill in local address
7639 		 */
7640 		taa->LOCADDR_length = sizeof (sin6_t);
7641 		taa->LOCADDR_offset = sizeof (*taa);
7642 
7643 		sin6 = (sin6_t *)&taa[1];
7644 		*sin6 = sin6_null;
7645 
7646 		sin6->sin6_family = AF_INET6;
7647 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7648 		sin6->sin6_port = tcp->tcp_lport;
7649 
7650 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7651 
7652 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7653 			/*
7654 			 * Fill in Remote address
7655 			 */
7656 			taa->REMADDR_length = sizeof (sin6_t);
7657 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7658 						taa->LOCADDR_length);
7659 
7660 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7661 			*sin6 = sin6_null;
7662 			sin6->sin6_family = AF_INET6;
7663 			sin6->sin6_flowinfo =
7664 			    tcp->tcp_ip6h->ip6_vcf &
7665 			    ~IPV6_VERS_AND_FLOW_MASK;
7666 			sin6->sin6_addr = tcp->tcp_remote_v6;
7667 			sin6->sin6_port = tcp->tcp_fport;
7668 
7669 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7670 		}
7671 	}
7672 	putnext(tcp->tcp_rq, ackmp);
7673 }
7674 
7675 /*
7676  * Handle reinitialization of a tcp structure.
7677  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7678  */
7679 static void
7680 tcp_reinit(tcp_t *tcp)
7681 {
7682 	mblk_t	*mp;
7683 	int 	err;
7684 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7685 
7686 	TCP_STAT(tcps, tcp_reinit_calls);
7687 
7688 	/* tcp_reinit should never be called for detached tcp_t's */
7689 	ASSERT(tcp->tcp_listener == NULL);
7690 	ASSERT((tcp->tcp_family == AF_INET &&
7691 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7692 	    (tcp->tcp_family == AF_INET6 &&
7693 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7694 	    tcp->tcp_ipversion == IPV6_VERSION)));
7695 
7696 	/* Cancel outstanding timers */
7697 	tcp_timers_stop(tcp);
7698 
7699 	/*
7700 	 * Reset everything in the state vector, after updating global
7701 	 * MIB data from instance counters.
7702 	 */
7703 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7704 	tcp->tcp_ibsegs = 0;
7705 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7706 	tcp->tcp_obsegs = 0;
7707 
7708 	tcp_close_mpp(&tcp->tcp_xmit_head);
7709 	if (tcp->tcp_snd_zcopy_aware)
7710 		tcp_zcopy_notify(tcp);
7711 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7712 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7713 	mutex_enter(&tcp->tcp_non_sq_lock);
7714 	if (tcp->tcp_flow_stopped &&
7715 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7716 		tcp_clrqfull(tcp);
7717 	}
7718 	mutex_exit(&tcp->tcp_non_sq_lock);
7719 	tcp_close_mpp(&tcp->tcp_reass_head);
7720 	tcp->tcp_reass_tail = NULL;
7721 	if (tcp->tcp_rcv_list != NULL) {
7722 		/* Free b_next chain */
7723 		tcp_close_mpp(&tcp->tcp_rcv_list);
7724 		tcp->tcp_rcv_last_head = NULL;
7725 		tcp->tcp_rcv_last_tail = NULL;
7726 		tcp->tcp_rcv_cnt = 0;
7727 	}
7728 	tcp->tcp_rcv_last_tail = NULL;
7729 
7730 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7731 		freemsg(mp);
7732 		tcp->tcp_urp_mp = NULL;
7733 	}
7734 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7735 		freemsg(mp);
7736 		tcp->tcp_urp_mark_mp = NULL;
7737 	}
7738 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7739 		freeb(tcp->tcp_fused_sigurg_mp);
7740 		tcp->tcp_fused_sigurg_mp = NULL;
7741 	}
7742 
7743 	/*
7744 	 * Following is a union with two members which are
7745 	 * identical types and size so the following cleanup
7746 	 * is enough.
7747 	 */
7748 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7749 
7750 	CL_INET_DISCONNECT(tcp);
7751 
7752 	/*
7753 	 * The connection can't be on the tcp_time_wait_head list
7754 	 * since it is not detached.
7755 	 */
7756 	ASSERT(tcp->tcp_time_wait_next == NULL);
7757 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7758 	ASSERT(tcp->tcp_time_wait_expire == 0);
7759 
7760 	if (tcp->tcp_kssl_pending) {
7761 		tcp->tcp_kssl_pending = B_FALSE;
7762 
7763 		/* Don't reset if the initialized by bind. */
7764 		if (tcp->tcp_kssl_ent != NULL) {
7765 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7766 			    KSSL_NO_PROXY);
7767 		}
7768 	}
7769 	if (tcp->tcp_kssl_ctx != NULL) {
7770 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7771 		tcp->tcp_kssl_ctx = NULL;
7772 	}
7773 
7774 	/*
7775 	 * Reset/preserve other values
7776 	 */
7777 	tcp_reinit_values(tcp);
7778 	ipcl_hash_remove(tcp->tcp_connp);
7779 	conn_delete_ire(tcp->tcp_connp, NULL);
7780 	tcp_ipsec_cleanup(tcp);
7781 
7782 	if (tcp->tcp_conn_req_max != 0) {
7783 		/*
7784 		 * This is the case when a TLI program uses the same
7785 		 * transport end point to accept a connection.  This
7786 		 * makes the TCP both a listener and acceptor.  When
7787 		 * this connection is closed, we need to set the state
7788 		 * back to TCPS_LISTEN.  Make sure that the eager list
7789 		 * is reinitialized.
7790 		 *
7791 		 * Note that this stream is still bound to the four
7792 		 * tuples of the previous connection in IP.  If a new
7793 		 * SYN with different foreign address comes in, IP will
7794 		 * not find it and will send it to the global queue.  In
7795 		 * the global queue, TCP will do a tcp_lookup_listener()
7796 		 * to find this stream.  This works because this stream
7797 		 * is only removed from connected hash.
7798 		 *
7799 		 */
7800 		tcp->tcp_state = TCPS_LISTEN;
7801 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7802 		tcp->tcp_eager_next_drop_q0 = tcp;
7803 		tcp->tcp_eager_prev_drop_q0 = tcp;
7804 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7805 		if (tcp->tcp_family == AF_INET6) {
7806 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7807 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7808 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7809 		} else {
7810 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7811 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7812 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7813 		}
7814 	} else {
7815 		tcp->tcp_state = TCPS_BOUND;
7816 	}
7817 
7818 	/*
7819 	 * Initialize to default values
7820 	 * Can't fail since enough header template space already allocated
7821 	 * at open().
7822 	 */
7823 	err = tcp_init_values(tcp);
7824 	ASSERT(err == 0);
7825 	/* Restore state in tcp_tcph */
7826 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7827 	if (tcp->tcp_ipversion == IPV4_VERSION)
7828 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7829 	else
7830 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7831 	/*
7832 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7833 	 * since the lookup funcs can only lookup on tcp_t
7834 	 */
7835 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7836 
7837 	ASSERT(tcp->tcp_ptpbhn != NULL);
7838 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7839 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7840 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7841 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7842 }
7843 
7844 /*
7845  * Force values to zero that need be zero.
7846  * Do not touch values asociated with the BOUND or LISTEN state
7847  * since the connection will end up in that state after the reinit.
7848  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7849  * structure!
7850  */
7851 static void
7852 tcp_reinit_values(tcp)
7853 	tcp_t *tcp;
7854 {
7855 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7856 
7857 #ifndef	lint
7858 #define	DONTCARE(x)
7859 #define	PRESERVE(x)
7860 #else
7861 #define	DONTCARE(x)	((x) = (x))
7862 #define	PRESERVE(x)	((x) = (x))
7863 #endif	/* lint */
7864 
7865 	PRESERVE(tcp->tcp_bind_hash);
7866 	PRESERVE(tcp->tcp_ptpbhn);
7867 	PRESERVE(tcp->tcp_acceptor_hash);
7868 	PRESERVE(tcp->tcp_ptpahn);
7869 
7870 	/* Should be ASSERT NULL on these with new code! */
7871 	ASSERT(tcp->tcp_time_wait_next == NULL);
7872 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7873 	ASSERT(tcp->tcp_time_wait_expire == 0);
7874 	PRESERVE(tcp->tcp_state);
7875 	PRESERVE(tcp->tcp_rq);
7876 	PRESERVE(tcp->tcp_wq);
7877 
7878 	ASSERT(tcp->tcp_xmit_head == NULL);
7879 	ASSERT(tcp->tcp_xmit_last == NULL);
7880 	ASSERT(tcp->tcp_unsent == 0);
7881 	ASSERT(tcp->tcp_xmit_tail == NULL);
7882 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7883 
7884 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7885 	tcp->tcp_suna = 0;			/* Displayed in mib */
7886 	tcp->tcp_swnd = 0;
7887 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7888 
7889 	ASSERT(tcp->tcp_ibsegs == 0);
7890 	ASSERT(tcp->tcp_obsegs == 0);
7891 
7892 	if (tcp->tcp_iphc != NULL) {
7893 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7894 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7895 	}
7896 
7897 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7898 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7899 	DONTCARE(tcp->tcp_ipha);
7900 	DONTCARE(tcp->tcp_ip6h);
7901 	DONTCARE(tcp->tcp_ip_hdr_len);
7902 	DONTCARE(tcp->tcp_tcph);
7903 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7904 	tcp->tcp_valid_bits = 0;
7905 
7906 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7907 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7908 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7909 	tcp->tcp_last_rcv_lbolt = 0;
7910 
7911 	tcp->tcp_init_cwnd = 0;
7912 
7913 	tcp->tcp_urp_last_valid = 0;
7914 	tcp->tcp_hard_binding = 0;
7915 	tcp->tcp_hard_bound = 0;
7916 	PRESERVE(tcp->tcp_cred);
7917 	PRESERVE(tcp->tcp_cpid);
7918 	PRESERVE(tcp->tcp_open_time);
7919 	PRESERVE(tcp->tcp_exclbind);
7920 
7921 	tcp->tcp_fin_acked = 0;
7922 	tcp->tcp_fin_rcvd = 0;
7923 	tcp->tcp_fin_sent = 0;
7924 	tcp->tcp_ordrel_done = 0;
7925 
7926 	tcp->tcp_debug = 0;
7927 	tcp->tcp_dontroute = 0;
7928 	tcp->tcp_broadcast = 0;
7929 
7930 	tcp->tcp_useloopback = 0;
7931 	tcp->tcp_reuseaddr = 0;
7932 	tcp->tcp_oobinline = 0;
7933 	tcp->tcp_dgram_errind = 0;
7934 
7935 	tcp->tcp_detached = 0;
7936 	tcp->tcp_bind_pending = 0;
7937 	tcp->tcp_unbind_pending = 0;
7938 	tcp->tcp_deferred_clean_death = 0;
7939 
7940 	tcp->tcp_snd_ws_ok = B_FALSE;
7941 	tcp->tcp_snd_ts_ok = B_FALSE;
7942 	tcp->tcp_linger = 0;
7943 	tcp->tcp_ka_enabled = 0;
7944 	tcp->tcp_zero_win_probe = 0;
7945 
7946 	tcp->tcp_loopback = 0;
7947 	tcp->tcp_localnet = 0;
7948 	tcp->tcp_syn_defense = 0;
7949 	tcp->tcp_set_timer = 0;
7950 
7951 	tcp->tcp_active_open = 0;
7952 	ASSERT(tcp->tcp_timeout == B_FALSE);
7953 	tcp->tcp_rexmit = B_FALSE;
7954 	tcp->tcp_xmit_zc_clean = B_FALSE;
7955 
7956 	tcp->tcp_snd_sack_ok = B_FALSE;
7957 	PRESERVE(tcp->tcp_recvdstaddr);
7958 	tcp->tcp_hwcksum = B_FALSE;
7959 
7960 	tcp->tcp_ire_ill_check_done = B_FALSE;
7961 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7962 
7963 	tcp->tcp_mdt = B_FALSE;
7964 	tcp->tcp_mdt_hdr_head = 0;
7965 	tcp->tcp_mdt_hdr_tail = 0;
7966 
7967 	tcp->tcp_conn_def_q0 = 0;
7968 	tcp->tcp_ip_forward_progress = B_FALSE;
7969 	tcp->tcp_anon_priv_bind = 0;
7970 	tcp->tcp_ecn_ok = B_FALSE;
7971 
7972 	tcp->tcp_cwr = B_FALSE;
7973 	tcp->tcp_ecn_echo_on = B_FALSE;
7974 
7975 	if (tcp->tcp_sack_info != NULL) {
7976 		if (tcp->tcp_notsack_list != NULL) {
7977 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7978 		}
7979 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7980 		tcp->tcp_sack_info = NULL;
7981 	}
7982 
7983 	tcp->tcp_rcv_ws = 0;
7984 	tcp->tcp_snd_ws = 0;
7985 	tcp->tcp_ts_recent = 0;
7986 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7987 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7988 	tcp->tcp_if_mtu = 0;
7989 
7990 	ASSERT(tcp->tcp_reass_head == NULL);
7991 	ASSERT(tcp->tcp_reass_tail == NULL);
7992 
7993 	tcp->tcp_cwnd_cnt = 0;
7994 
7995 	ASSERT(tcp->tcp_rcv_list == NULL);
7996 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7997 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7998 	ASSERT(tcp->tcp_rcv_cnt == 0);
7999 
8000 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8001 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8002 	tcp->tcp_csuna = 0;
8003 
8004 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8005 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8006 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8007 	tcp->tcp_rtt_update = 0;
8008 
8009 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8010 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8011 
8012 	tcp->tcp_rack = 0;			/* Displayed in mib */
8013 	tcp->tcp_rack_cnt = 0;
8014 	tcp->tcp_rack_cur_max = 0;
8015 	tcp->tcp_rack_abs_max = 0;
8016 
8017 	tcp->tcp_max_swnd = 0;
8018 
8019 	ASSERT(tcp->tcp_listener == NULL);
8020 
8021 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8022 
8023 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8024 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8025 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8026 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8027 
8028 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8029 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8030 	PRESERVE(tcp->tcp_conn_req_max);
8031 	PRESERVE(tcp->tcp_conn_req_seqnum);
8032 
8033 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8034 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8035 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8036 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8037 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8038 
8039 	tcp->tcp_lingertime = 0;
8040 
8041 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8042 	ASSERT(tcp->tcp_urp_mp == NULL);
8043 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8044 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8045 
8046 	ASSERT(tcp->tcp_eager_next_q == NULL);
8047 	ASSERT(tcp->tcp_eager_last_q == NULL);
8048 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8049 	    tcp->tcp_eager_prev_q0 == NULL) ||
8050 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8051 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8052 
8053 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8054 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8055 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8056 
8057 	tcp->tcp_client_errno = 0;
8058 
8059 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8060 
8061 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8062 
8063 	PRESERVE(tcp->tcp_bound_source_v6);
8064 	tcp->tcp_last_sent_len = 0;
8065 	tcp->tcp_dupack_cnt = 0;
8066 
8067 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8068 	PRESERVE(tcp->tcp_lport);
8069 
8070 	PRESERVE(tcp->tcp_acceptor_lockp);
8071 
8072 	ASSERT(tcp->tcp_ordrelid == 0);
8073 	PRESERVE(tcp->tcp_acceptor_id);
8074 	DONTCARE(tcp->tcp_ipsec_overhead);
8075 
8076 	/*
8077 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8078 	 * in tcp structure and now tracing), Re-initialize all
8079 	 * members of tcp_traceinfo.
8080 	 */
8081 	if (tcp->tcp_tracebuf != NULL) {
8082 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8083 	}
8084 
8085 	PRESERVE(tcp->tcp_family);
8086 	if (tcp->tcp_family == AF_INET6) {
8087 		tcp->tcp_ipversion = IPV6_VERSION;
8088 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8089 	} else {
8090 		tcp->tcp_ipversion = IPV4_VERSION;
8091 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8092 	}
8093 
8094 	tcp->tcp_bound_if = 0;
8095 	tcp->tcp_ipv6_recvancillary = 0;
8096 	tcp->tcp_recvifindex = 0;
8097 	tcp->tcp_recvhops = 0;
8098 	tcp->tcp_closed = 0;
8099 	tcp->tcp_cleandeathtag = 0;
8100 	if (tcp->tcp_hopopts != NULL) {
8101 		mi_free(tcp->tcp_hopopts);
8102 		tcp->tcp_hopopts = NULL;
8103 		tcp->tcp_hopoptslen = 0;
8104 	}
8105 	ASSERT(tcp->tcp_hopoptslen == 0);
8106 	if (tcp->tcp_dstopts != NULL) {
8107 		mi_free(tcp->tcp_dstopts);
8108 		tcp->tcp_dstopts = NULL;
8109 		tcp->tcp_dstoptslen = 0;
8110 	}
8111 	ASSERT(tcp->tcp_dstoptslen == 0);
8112 	if (tcp->tcp_rtdstopts != NULL) {
8113 		mi_free(tcp->tcp_rtdstopts);
8114 		tcp->tcp_rtdstopts = NULL;
8115 		tcp->tcp_rtdstoptslen = 0;
8116 	}
8117 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8118 	if (tcp->tcp_rthdr != NULL) {
8119 		mi_free(tcp->tcp_rthdr);
8120 		tcp->tcp_rthdr = NULL;
8121 		tcp->tcp_rthdrlen = 0;
8122 	}
8123 	ASSERT(tcp->tcp_rthdrlen == 0);
8124 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8125 
8126 	/* Reset fusion-related fields */
8127 	tcp->tcp_fused = B_FALSE;
8128 	tcp->tcp_unfusable = B_FALSE;
8129 	tcp->tcp_fused_sigurg = B_FALSE;
8130 	tcp->tcp_direct_sockfs = B_FALSE;
8131 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8132 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8133 	tcp->tcp_loopback_peer = NULL;
8134 	tcp->tcp_fuse_rcv_hiwater = 0;
8135 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8136 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8137 
8138 	tcp->tcp_lso = B_FALSE;
8139 
8140 	tcp->tcp_in_ack_unsent = 0;
8141 	tcp->tcp_cork = B_FALSE;
8142 	tcp->tcp_tconnind_started = B_FALSE;
8143 
8144 	PRESERVE(tcp->tcp_squeue_bytes);
8145 
8146 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8147 	ASSERT(!tcp->tcp_kssl_pending);
8148 	PRESERVE(tcp->tcp_kssl_ent);
8149 
8150 	tcp->tcp_closemp_used = B_FALSE;
8151 
8152 #ifdef DEBUG
8153 	DONTCARE(tcp->tcmp_stk[0]);
8154 #endif
8155 
8156 
8157 #undef	DONTCARE
8158 #undef	PRESERVE
8159 }
8160 
8161 /*
8162  * Allocate necessary resources and initialize state vector.
8163  * Guaranteed not to fail so that when an error is returned,
8164  * the caller doesn't need to do any additional cleanup.
8165  */
8166 int
8167 tcp_init(tcp_t *tcp, queue_t *q)
8168 {
8169 	int	err;
8170 
8171 	tcp->tcp_rq = q;
8172 	tcp->tcp_wq = WR(q);
8173 	tcp->tcp_state = TCPS_IDLE;
8174 	if ((err = tcp_init_values(tcp)) != 0)
8175 		tcp_timers_stop(tcp);
8176 	return (err);
8177 }
8178 
8179 static int
8180 tcp_init_values(tcp_t *tcp)
8181 {
8182 	int	err;
8183 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8184 
8185 	ASSERT((tcp->tcp_family == AF_INET &&
8186 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8187 	    (tcp->tcp_family == AF_INET6 &&
8188 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8189 	    tcp->tcp_ipversion == IPV6_VERSION)));
8190 
8191 	/*
8192 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8193 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8194 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8195 	 * during first few transmissions of a connection as seen in slow
8196 	 * links.
8197 	 */
8198 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8199 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8200 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8201 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8202 	    tcps->tcps_conn_grace_period;
8203 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8204 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8205 	tcp->tcp_timer_backoff = 0;
8206 	tcp->tcp_ms_we_have_waited = 0;
8207 	tcp->tcp_last_recv_time = lbolt;
8208 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8209 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8210 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8211 
8212 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8213 
8214 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8215 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8216 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8217 	/*
8218 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8219 	 * passive open.
8220 	 */
8221 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8222 
8223 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8224 
8225 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8226 
8227 	tcp->tcp_mdt_hdr_head = 0;
8228 	tcp->tcp_mdt_hdr_tail = 0;
8229 
8230 	/* Reset fusion-related fields */
8231 	tcp->tcp_fused = B_FALSE;
8232 	tcp->tcp_unfusable = B_FALSE;
8233 	tcp->tcp_fused_sigurg = B_FALSE;
8234 	tcp->tcp_direct_sockfs = B_FALSE;
8235 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8236 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8237 	tcp->tcp_loopback_peer = NULL;
8238 	tcp->tcp_fuse_rcv_hiwater = 0;
8239 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8240 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8241 
8242 	/* Initialize the header template */
8243 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8244 		err = tcp_header_init_ipv4(tcp);
8245 	} else {
8246 		err = tcp_header_init_ipv6(tcp);
8247 	}
8248 	if (err)
8249 		return (err);
8250 
8251 	/*
8252 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8253 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8254 	 */
8255 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8256 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8257 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8258 
8259 	tcp->tcp_cork = B_FALSE;
8260 	/*
8261 	 * Init the tcp_debug option.  This value determines whether TCP
8262 	 * calls strlog() to print out debug messages.  Doing this
8263 	 * initialization here means that this value is not inherited thru
8264 	 * tcp_reinit().
8265 	 */
8266 	tcp->tcp_debug = tcps->tcps_dbg;
8267 
8268 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8269 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8270 
8271 	return (0);
8272 }
8273 
8274 /*
8275  * Initialize the IPv4 header. Loses any record of any IP options.
8276  */
8277 static int
8278 tcp_header_init_ipv4(tcp_t *tcp)
8279 {
8280 	tcph_t		*tcph;
8281 	uint32_t	sum;
8282 	conn_t		*connp;
8283 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8284 
8285 	/*
8286 	 * This is a simple initialization. If there's
8287 	 * already a template, it should never be too small,
8288 	 * so reuse it.  Otherwise, allocate space for the new one.
8289 	 */
8290 	if (tcp->tcp_iphc == NULL) {
8291 		ASSERT(tcp->tcp_iphc_len == 0);
8292 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8293 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8294 		if (tcp->tcp_iphc == NULL) {
8295 			tcp->tcp_iphc_len = 0;
8296 			return (ENOMEM);
8297 		}
8298 	}
8299 
8300 	/* options are gone; may need a new label */
8301 	connp = tcp->tcp_connp;
8302 	connp->conn_mlp_type = mlptSingle;
8303 	connp->conn_ulp_labeled = !is_system_labeled();
8304 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8305 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8306 	tcp->tcp_ip6h = NULL;
8307 	tcp->tcp_ipversion = IPV4_VERSION;
8308 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8309 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8310 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8311 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8312 	tcp->tcp_ipha->ipha_version_and_hdr_length
8313 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8314 	tcp->tcp_ipha->ipha_ident = 0;
8315 
8316 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8317 	tcp->tcp_tos = 0;
8318 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8319 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8320 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8321 
8322 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8323 	tcp->tcp_tcph = tcph;
8324 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8325 	/*
8326 	 * IP wants our header length in the checksum field to
8327 	 * allow it to perform a single pseudo-header+checksum
8328 	 * calculation on behalf of TCP.
8329 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8330 	 */
8331 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8332 	sum = (sum >> 16) + (sum & 0xFFFF);
8333 	U16_TO_ABE16(sum, tcph->th_sum);
8334 	return (0);
8335 }
8336 
8337 /*
8338  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8339  */
8340 static int
8341 tcp_header_init_ipv6(tcp_t *tcp)
8342 {
8343 	tcph_t	*tcph;
8344 	uint32_t	sum;
8345 	conn_t	*connp;
8346 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8347 
8348 	/*
8349 	 * This is a simple initialization. If there's
8350 	 * already a template, it should never be too small,
8351 	 * so reuse it. Otherwise, allocate space for the new one.
8352 	 * Ensure that there is enough space to "downgrade" the tcp_t
8353 	 * to an IPv4 tcp_t. This requires having space for a full load
8354 	 * of IPv4 options, as well as a full load of TCP options
8355 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8356 	 * than a v6 header and a TCP header with a full load of TCP options
8357 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8358 	 * We want to avoid reallocation in the "downgraded" case when
8359 	 * processing outbound IPv4 options.
8360 	 */
8361 	if (tcp->tcp_iphc == NULL) {
8362 		ASSERT(tcp->tcp_iphc_len == 0);
8363 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8364 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8365 		if (tcp->tcp_iphc == NULL) {
8366 			tcp->tcp_iphc_len = 0;
8367 			return (ENOMEM);
8368 		}
8369 	}
8370 
8371 	/* options are gone; may need a new label */
8372 	connp = tcp->tcp_connp;
8373 	connp->conn_mlp_type = mlptSingle;
8374 	connp->conn_ulp_labeled = !is_system_labeled();
8375 
8376 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8377 	tcp->tcp_ipversion = IPV6_VERSION;
8378 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8379 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8380 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8381 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8382 	tcp->tcp_ipha = NULL;
8383 
8384 	/* Initialize the header template */
8385 
8386 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8387 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8388 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8389 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8390 
8391 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8392 	tcp->tcp_tcph = tcph;
8393 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8394 	/*
8395 	 * IP wants our header length in the checksum field to
8396 	 * allow it to perform a single psuedo-header+checksum
8397 	 * calculation on behalf of TCP.
8398 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8399 	 */
8400 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8401 	sum = (sum >> 16) + (sum & 0xFFFF);
8402 	U16_TO_ABE16(sum, tcph->th_sum);
8403 	return (0);
8404 }
8405 
8406 /* At minimum we need 8 bytes in the TCP header for the lookup */
8407 #define	ICMP_MIN_TCP_HDR	8
8408 
8409 /*
8410  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8411  * passed up by IP. The message is always received on the correct tcp_t.
8412  * Assumes that IP has pulled up everything up to and including the ICMP header.
8413  */
8414 void
8415 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8416 {
8417 	icmph_t *icmph;
8418 	ipha_t	*ipha;
8419 	int	iph_hdr_length;
8420 	tcph_t	*tcph;
8421 	boolean_t ipsec_mctl = B_FALSE;
8422 	boolean_t secure;
8423 	mblk_t *first_mp = mp;
8424 	uint32_t new_mss;
8425 	uint32_t ratio;
8426 	size_t mp_size = MBLKL(mp);
8427 	uint32_t seg_seq;
8428 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8429 
8430 	/* Assume IP provides aligned packets - otherwise toss */
8431 	if (!OK_32PTR(mp->b_rptr)) {
8432 		freemsg(mp);
8433 		return;
8434 	}
8435 
8436 	/*
8437 	 * Since ICMP errors are normal data marked with M_CTL when sent
8438 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8439 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8440 	 */
8441 	if ((mp_size == sizeof (ipsec_info_t)) &&
8442 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8443 		ASSERT(mp->b_cont != NULL);
8444 		mp = mp->b_cont;
8445 		/* IP should have done this */
8446 		ASSERT(OK_32PTR(mp->b_rptr));
8447 		mp_size = MBLKL(mp);
8448 		ipsec_mctl = B_TRUE;
8449 	}
8450 
8451 	/*
8452 	 * Verify that we have a complete outer IP header. If not, drop it.
8453 	 */
8454 	if (mp_size < sizeof (ipha_t)) {
8455 noticmpv4:
8456 		freemsg(first_mp);
8457 		return;
8458 	}
8459 
8460 	ipha = (ipha_t *)mp->b_rptr;
8461 	/*
8462 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8463 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8464 	 */
8465 	switch (IPH_HDR_VERSION(ipha)) {
8466 	case IPV6_VERSION:
8467 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8468 		return;
8469 	case IPV4_VERSION:
8470 		break;
8471 	default:
8472 		goto noticmpv4;
8473 	}
8474 
8475 	/* Skip past the outer IP and ICMP headers */
8476 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8477 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8478 	/*
8479 	 * If we don't have the correct outer IP header length or if the ULP
8480 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8481 	 * send it upstream.
8482 	 */
8483 	if (iph_hdr_length < sizeof (ipha_t) ||
8484 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8485 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8486 		goto noticmpv4;
8487 	}
8488 	ipha = (ipha_t *)&icmph[1];
8489 
8490 	/* Skip past the inner IP and find the ULP header */
8491 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8492 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8493 	/*
8494 	 * If we don't have the correct inner IP header length or if the ULP
8495 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8496 	 * bytes of TCP header, drop it.
8497 	 */
8498 	if (iph_hdr_length < sizeof (ipha_t) ||
8499 	    ipha->ipha_protocol != IPPROTO_TCP ||
8500 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8501 		goto noticmpv4;
8502 	}
8503 
8504 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8505 		if (ipsec_mctl) {
8506 			secure = ipsec_in_is_secure(first_mp);
8507 		} else {
8508 			secure = B_FALSE;
8509 		}
8510 		if (secure) {
8511 			/*
8512 			 * If we are willing to accept this in clear
8513 			 * we don't have to verify policy.
8514 			 */
8515 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8516 				if (!tcp_check_policy(tcp, first_mp,
8517 				    ipha, NULL, secure, ipsec_mctl)) {
8518 					/*
8519 					 * tcp_check_policy called
8520 					 * ip_drop_packet() on failure.
8521 					 */
8522 					return;
8523 				}
8524 			}
8525 		}
8526 	} else if (ipsec_mctl) {
8527 		/*
8528 		 * This is a hard_bound connection. IP has already
8529 		 * verified policy. We don't have to do it again.
8530 		 */
8531 		freeb(first_mp);
8532 		first_mp = mp;
8533 		ipsec_mctl = B_FALSE;
8534 	}
8535 
8536 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8537 	/*
8538 	 * TCP SHOULD check that the TCP sequence number contained in
8539 	 * payload of the ICMP error message is within the range
8540 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8541 	 */
8542 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8543 		/*
8544 		 * If the ICMP message is bogus, should we kill the
8545 		 * connection, or should we just drop the bogus ICMP
8546 		 * message? It would probably make more sense to just
8547 		 * drop the message so that if this one managed to get
8548 		 * in, the real connection should not suffer.
8549 		 */
8550 		goto noticmpv4;
8551 	}
8552 
8553 	switch (icmph->icmph_type) {
8554 	case ICMP_DEST_UNREACHABLE:
8555 		switch (icmph->icmph_code) {
8556 		case ICMP_FRAGMENTATION_NEEDED:
8557 			/*
8558 			 * Reduce the MSS based on the new MTU.  This will
8559 			 * eliminate any fragmentation locally.
8560 			 * N.B.  There may well be some funny side-effects on
8561 			 * the local send policy and the remote receive policy.
8562 			 * Pending further research, we provide
8563 			 * tcp_ignore_path_mtu just in case this proves
8564 			 * disastrous somewhere.
8565 			 *
8566 			 * After updating the MSS, retransmit part of the
8567 			 * dropped segment using the new mss by calling
8568 			 * tcp_wput_data().  Need to adjust all those
8569 			 * params to make sure tcp_wput_data() work properly.
8570 			 */
8571 			if (tcps->tcps_ignore_path_mtu)
8572 				break;
8573 
8574 			/*
8575 			 * Decrease the MSS by time stamp options
8576 			 * IP options and IPSEC options. tcp_hdr_len
8577 			 * includes time stamp option and IP option
8578 			 * length.
8579 			 */
8580 
8581 			new_mss = ntohs(icmph->icmph_du_mtu) -
8582 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8583 
8584 			/*
8585 			 * Only update the MSS if the new one is
8586 			 * smaller than the previous one.  This is
8587 			 * to avoid problems when getting multiple
8588 			 * ICMP errors for the same MTU.
8589 			 */
8590 			if (new_mss >= tcp->tcp_mss)
8591 				break;
8592 
8593 			/*
8594 			 * Stop doing PMTU if new_mss is less than 68
8595 			 * or less than tcp_mss_min.
8596 			 * The value 68 comes from rfc 1191.
8597 			 */
8598 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8599 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8600 				    0;
8601 
8602 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8603 			ASSERT(ratio >= 1);
8604 			tcp_mss_set(tcp, new_mss, B_TRUE);
8605 
8606 			/*
8607 			 * Make sure we have something to
8608 			 * send.
8609 			 */
8610 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8611 			    (tcp->tcp_xmit_head != NULL)) {
8612 				/*
8613 				 * Shrink tcp_cwnd in
8614 				 * proportion to the old MSS/new MSS.
8615 				 */
8616 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8617 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8618 				    (tcp->tcp_unsent == 0)) {
8619 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8620 				} else {
8621 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8622 				}
8623 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8624 				tcp->tcp_rexmit = B_TRUE;
8625 				tcp->tcp_dupack_cnt = 0;
8626 				tcp->tcp_snd_burst = TCP_CWND_SS;
8627 				tcp_ss_rexmit(tcp);
8628 			}
8629 			break;
8630 		case ICMP_PORT_UNREACHABLE:
8631 		case ICMP_PROTOCOL_UNREACHABLE:
8632 			switch (tcp->tcp_state) {
8633 			case TCPS_SYN_SENT:
8634 			case TCPS_SYN_RCVD:
8635 				/*
8636 				 * ICMP can snipe away incipient
8637 				 * TCP connections as long as
8638 				 * seq number is same as initial
8639 				 * send seq number.
8640 				 */
8641 				if (seg_seq == tcp->tcp_iss) {
8642 					(void) tcp_clean_death(tcp,
8643 					    ECONNREFUSED, 6);
8644 				}
8645 				break;
8646 			}
8647 			break;
8648 		case ICMP_HOST_UNREACHABLE:
8649 		case ICMP_NET_UNREACHABLE:
8650 			/* Record the error in case we finally time out. */
8651 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8652 				tcp->tcp_client_errno = EHOSTUNREACH;
8653 			else
8654 				tcp->tcp_client_errno = ENETUNREACH;
8655 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8656 				if (tcp->tcp_listener != NULL &&
8657 				    tcp->tcp_listener->tcp_syn_defense) {
8658 					/*
8659 					 * Ditch the half-open connection if we
8660 					 * suspect a SYN attack is under way.
8661 					 */
8662 					tcp_ip_ire_mark_advice(tcp);
8663 					(void) tcp_clean_death(tcp,
8664 					    tcp->tcp_client_errno, 7);
8665 				}
8666 			}
8667 			break;
8668 		default:
8669 			break;
8670 		}
8671 		break;
8672 	case ICMP_SOURCE_QUENCH: {
8673 		/*
8674 		 * use a global boolean to control
8675 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8676 		 * The default is false.
8677 		 */
8678 		if (tcp_icmp_source_quench) {
8679 			/*
8680 			 * Reduce the sending rate as if we got a
8681 			 * retransmit timeout
8682 			 */
8683 			uint32_t npkt;
8684 
8685 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8686 			    tcp->tcp_mss;
8687 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8688 			tcp->tcp_cwnd = tcp->tcp_mss;
8689 			tcp->tcp_cwnd_cnt = 0;
8690 		}
8691 		break;
8692 	}
8693 	}
8694 	freemsg(first_mp);
8695 }
8696 
8697 /*
8698  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8699  * error messages passed up by IP.
8700  * Assumes that IP has pulled up all the extension headers as well
8701  * as the ICMPv6 header.
8702  */
8703 static void
8704 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8705 {
8706 	icmp6_t *icmp6;
8707 	ip6_t	*ip6h;
8708 	uint16_t	iph_hdr_length;
8709 	tcpha_t	*tcpha;
8710 	uint8_t	*nexthdrp;
8711 	uint32_t new_mss;
8712 	uint32_t ratio;
8713 	boolean_t secure;
8714 	mblk_t *first_mp = mp;
8715 	size_t mp_size;
8716 	uint32_t seg_seq;
8717 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8718 
8719 	/*
8720 	 * The caller has determined if this is an IPSEC_IN packet and
8721 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8722 	 */
8723 	if (ipsec_mctl)
8724 		mp = mp->b_cont;
8725 
8726 	mp_size = MBLKL(mp);
8727 
8728 	/*
8729 	 * Verify that we have a complete IP header. If not, send it upstream.
8730 	 */
8731 	if (mp_size < sizeof (ip6_t)) {
8732 noticmpv6:
8733 		freemsg(first_mp);
8734 		return;
8735 	}
8736 
8737 	/*
8738 	 * Verify this is an ICMPV6 packet, else send it upstream.
8739 	 */
8740 	ip6h = (ip6_t *)mp->b_rptr;
8741 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8742 		iph_hdr_length = IPV6_HDR_LEN;
8743 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8744 	    &nexthdrp) ||
8745 	    *nexthdrp != IPPROTO_ICMPV6) {
8746 		goto noticmpv6;
8747 	}
8748 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8749 	ip6h = (ip6_t *)&icmp6[1];
8750 	/*
8751 	 * Verify if we have a complete ICMP and inner IP header.
8752 	 */
8753 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8754 		goto noticmpv6;
8755 
8756 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8757 		goto noticmpv6;
8758 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8759 	/*
8760 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8761 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8762 	 * packet.
8763 	 */
8764 	if ((*nexthdrp != IPPROTO_TCP) ||
8765 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8766 		goto noticmpv6;
8767 	}
8768 
8769 	/*
8770 	 * ICMP errors come on the right queue or come on
8771 	 * listener/global queue for detached connections and
8772 	 * get switched to the right queue. If it comes on the
8773 	 * right queue, policy check has already been done by IP
8774 	 * and thus free the first_mp without verifying the policy.
8775 	 * If it has come for a non-hard bound connection, we need
8776 	 * to verify policy as IP may not have done it.
8777 	 */
8778 	if (!tcp->tcp_hard_bound) {
8779 		if (ipsec_mctl) {
8780 			secure = ipsec_in_is_secure(first_mp);
8781 		} else {
8782 			secure = B_FALSE;
8783 		}
8784 		if (secure) {
8785 			/*
8786 			 * If we are willing to accept this in clear
8787 			 * we don't have to verify policy.
8788 			 */
8789 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8790 				if (!tcp_check_policy(tcp, first_mp,
8791 				    NULL, ip6h, secure, ipsec_mctl)) {
8792 					/*
8793 					 * tcp_check_policy called
8794 					 * ip_drop_packet() on failure.
8795 					 */
8796 					return;
8797 				}
8798 			}
8799 		}
8800 	} else if (ipsec_mctl) {
8801 		/*
8802 		 * This is a hard_bound connection. IP has already
8803 		 * verified policy. We don't have to do it again.
8804 		 */
8805 		freeb(first_mp);
8806 		first_mp = mp;
8807 		ipsec_mctl = B_FALSE;
8808 	}
8809 
8810 	seg_seq = ntohl(tcpha->tha_seq);
8811 	/*
8812 	 * TCP SHOULD check that the TCP sequence number contained in
8813 	 * payload of the ICMP error message is within the range
8814 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8815 	 */
8816 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8817 		/*
8818 		 * If the ICMP message is bogus, should we kill the
8819 		 * connection, or should we just drop the bogus ICMP
8820 		 * message? It would probably make more sense to just
8821 		 * drop the message so that if this one managed to get
8822 		 * in, the real connection should not suffer.
8823 		 */
8824 		goto noticmpv6;
8825 	}
8826 
8827 	switch (icmp6->icmp6_type) {
8828 	case ICMP6_PACKET_TOO_BIG:
8829 		/*
8830 		 * Reduce the MSS based on the new MTU.  This will
8831 		 * eliminate any fragmentation locally.
8832 		 * N.B.  There may well be some funny side-effects on
8833 		 * the local send policy and the remote receive policy.
8834 		 * Pending further research, we provide
8835 		 * tcp_ignore_path_mtu just in case this proves
8836 		 * disastrous somewhere.
8837 		 *
8838 		 * After updating the MSS, retransmit part of the
8839 		 * dropped segment using the new mss by calling
8840 		 * tcp_wput_data().  Need to adjust all those
8841 		 * params to make sure tcp_wput_data() work properly.
8842 		 */
8843 		if (tcps->tcps_ignore_path_mtu)
8844 			break;
8845 
8846 		/*
8847 		 * Decrease the MSS by time stamp options
8848 		 * IP options and IPSEC options. tcp_hdr_len
8849 		 * includes time stamp option and IP option
8850 		 * length.
8851 		 */
8852 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8853 			    tcp->tcp_ipsec_overhead;
8854 
8855 		/*
8856 		 * Only update the MSS if the new one is
8857 		 * smaller than the previous one.  This is
8858 		 * to avoid problems when getting multiple
8859 		 * ICMP errors for the same MTU.
8860 		 */
8861 		if (new_mss >= tcp->tcp_mss)
8862 			break;
8863 
8864 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8865 		ASSERT(ratio >= 1);
8866 		tcp_mss_set(tcp, new_mss, B_TRUE);
8867 
8868 		/*
8869 		 * Make sure we have something to
8870 		 * send.
8871 		 */
8872 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8873 		    (tcp->tcp_xmit_head != NULL)) {
8874 			/*
8875 			 * Shrink tcp_cwnd in
8876 			 * proportion to the old MSS/new MSS.
8877 			 */
8878 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8879 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8880 			    (tcp->tcp_unsent == 0)) {
8881 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8882 			} else {
8883 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8884 			}
8885 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8886 			tcp->tcp_rexmit = B_TRUE;
8887 			tcp->tcp_dupack_cnt = 0;
8888 			tcp->tcp_snd_burst = TCP_CWND_SS;
8889 			tcp_ss_rexmit(tcp);
8890 		}
8891 		break;
8892 
8893 	case ICMP6_DST_UNREACH:
8894 		switch (icmp6->icmp6_code) {
8895 		case ICMP6_DST_UNREACH_NOPORT:
8896 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8897 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8898 			    (seg_seq == tcp->tcp_iss)) {
8899 				(void) tcp_clean_death(tcp,
8900 				    ECONNREFUSED, 8);
8901 			}
8902 			break;
8903 
8904 		case ICMP6_DST_UNREACH_ADMIN:
8905 		case ICMP6_DST_UNREACH_NOROUTE:
8906 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8907 		case ICMP6_DST_UNREACH_ADDR:
8908 			/* Record the error in case we finally time out. */
8909 			tcp->tcp_client_errno = EHOSTUNREACH;
8910 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8911 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8912 			    (seg_seq == tcp->tcp_iss)) {
8913 				if (tcp->tcp_listener != NULL &&
8914 				    tcp->tcp_listener->tcp_syn_defense) {
8915 					/*
8916 					 * Ditch the half-open connection if we
8917 					 * suspect a SYN attack is under way.
8918 					 */
8919 					tcp_ip_ire_mark_advice(tcp);
8920 					(void) tcp_clean_death(tcp,
8921 					    tcp->tcp_client_errno, 9);
8922 				}
8923 			}
8924 
8925 
8926 			break;
8927 		default:
8928 			break;
8929 		}
8930 		break;
8931 
8932 	case ICMP6_PARAM_PROB:
8933 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8934 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8935 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8936 		    (uchar_t *)nexthdrp) {
8937 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8938 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8939 				(void) tcp_clean_death(tcp,
8940 				    ECONNREFUSED, 10);
8941 			}
8942 			break;
8943 		}
8944 		break;
8945 
8946 	case ICMP6_TIME_EXCEEDED:
8947 	default:
8948 		break;
8949 	}
8950 	freemsg(first_mp);
8951 }
8952 
8953 /*
8954  * IP recognizes seven kinds of bind requests:
8955  *
8956  * - A zero-length address binds only to the protocol number.
8957  *
8958  * - A 4-byte address is treated as a request to
8959  * validate that the address is a valid local IPv4
8960  * address, appropriate for an application to bind to.
8961  * IP does the verification, but does not make any note
8962  * of the address at this time.
8963  *
8964  * - A 16-byte address contains is treated as a request
8965  * to validate a local IPv6 address, as the 4-byte
8966  * address case above.
8967  *
8968  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8969  * use it for the inbound fanout of packets.
8970  *
8971  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8972  * use it for the inbound fanout of packets.
8973  *
8974  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8975  * information consisting of local and remote addresses
8976  * and ports.  In this case, the addresses are both
8977  * validated as appropriate for this operation, and, if
8978  * so, the information is retained for use in the
8979  * inbound fanout.
8980  *
8981  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8982  * fanout information, like the 12-byte case above.
8983  *
8984  * IP will also fill in the IRE request mblk with information
8985  * regarding our peer.  In all cases, we notify IP of our protocol
8986  * type by appending a single protocol byte to the bind request.
8987  */
8988 static mblk_t *
8989 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8990 {
8991 	char	*cp;
8992 	mblk_t	*mp;
8993 	struct T_bind_req *tbr;
8994 	ipa_conn_t	*ac;
8995 	ipa6_conn_t	*ac6;
8996 	sin_t		*sin;
8997 	sin6_t		*sin6;
8998 
8999 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9000 	ASSERT((tcp->tcp_family == AF_INET &&
9001 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9002 	    (tcp->tcp_family == AF_INET6 &&
9003 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9004 	    tcp->tcp_ipversion == IPV6_VERSION)));
9005 
9006 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9007 	if (!mp)
9008 		return (mp);
9009 	mp->b_datap->db_type = M_PROTO;
9010 	tbr = (struct T_bind_req *)mp->b_rptr;
9011 	tbr->PRIM_type = bind_prim;
9012 	tbr->ADDR_offset = sizeof (*tbr);
9013 	tbr->CONIND_number = 0;
9014 	tbr->ADDR_length = addr_length;
9015 	cp = (char *)&tbr[1];
9016 	switch (addr_length) {
9017 	case sizeof (ipa_conn_t):
9018 		ASSERT(tcp->tcp_family == AF_INET);
9019 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9020 
9021 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9022 		if (mp->b_cont == NULL) {
9023 			freemsg(mp);
9024 			return (NULL);
9025 		}
9026 		mp->b_cont->b_wptr += sizeof (ire_t);
9027 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9028 
9029 		/* cp known to be 32 bit aligned */
9030 		ac = (ipa_conn_t *)cp;
9031 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9032 		ac->ac_faddr = tcp->tcp_remote;
9033 		ac->ac_fport = tcp->tcp_fport;
9034 		ac->ac_lport = tcp->tcp_lport;
9035 		tcp->tcp_hard_binding = 1;
9036 		break;
9037 
9038 	case sizeof (ipa6_conn_t):
9039 		ASSERT(tcp->tcp_family == AF_INET6);
9040 
9041 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9042 		if (mp->b_cont == NULL) {
9043 			freemsg(mp);
9044 			return (NULL);
9045 		}
9046 		mp->b_cont->b_wptr += sizeof (ire_t);
9047 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9048 
9049 		/* cp known to be 32 bit aligned */
9050 		ac6 = (ipa6_conn_t *)cp;
9051 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9052 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9053 			    &ac6->ac6_laddr);
9054 		} else {
9055 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9056 		}
9057 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9058 		ac6->ac6_fport = tcp->tcp_fport;
9059 		ac6->ac6_lport = tcp->tcp_lport;
9060 		tcp->tcp_hard_binding = 1;
9061 		break;
9062 
9063 	case sizeof (sin_t):
9064 		/*
9065 		 * NOTE: IPV6_ADDR_LEN also has same size.
9066 		 * Use family to discriminate.
9067 		 */
9068 		if (tcp->tcp_family == AF_INET) {
9069 			sin = (sin_t *)cp;
9070 
9071 			*sin = sin_null;
9072 			sin->sin_family = AF_INET;
9073 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9074 			sin->sin_port = tcp->tcp_lport;
9075 			break;
9076 		} else {
9077 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9078 		}
9079 		break;
9080 
9081 	case sizeof (sin6_t):
9082 		ASSERT(tcp->tcp_family == AF_INET6);
9083 		sin6 = (sin6_t *)cp;
9084 
9085 		*sin6 = sin6_null;
9086 		sin6->sin6_family = AF_INET6;
9087 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9088 		sin6->sin6_port = tcp->tcp_lport;
9089 		break;
9090 
9091 	case IP_ADDR_LEN:
9092 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9093 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9094 		break;
9095 
9096 	}
9097 	/* Add protocol number to end */
9098 	cp[addr_length] = (char)IPPROTO_TCP;
9099 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9100 	return (mp);
9101 }
9102 
9103 /*
9104  * Notify IP that we are having trouble with this connection.  IP should
9105  * blow the IRE away and start over.
9106  */
9107 static void
9108 tcp_ip_notify(tcp_t *tcp)
9109 {
9110 	struct iocblk	*iocp;
9111 	ipid_t	*ipid;
9112 	mblk_t	*mp;
9113 
9114 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9115 	if (tcp->tcp_ipversion == IPV6_VERSION)
9116 		return;
9117 
9118 	mp = mkiocb(IP_IOCTL);
9119 	if (mp == NULL)
9120 		return;
9121 
9122 	iocp = (struct iocblk *)mp->b_rptr;
9123 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9124 
9125 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9126 	if (!mp->b_cont) {
9127 		freeb(mp);
9128 		return;
9129 	}
9130 
9131 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9132 	mp->b_cont->b_wptr += iocp->ioc_count;
9133 	bzero(ipid, sizeof (*ipid));
9134 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9135 	ipid->ipid_ire_type = IRE_CACHE;
9136 	ipid->ipid_addr_offset = sizeof (ipid_t);
9137 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9138 	/*
9139 	 * Note: in the case of source routing we want to blow away the
9140 	 * route to the first source route hop.
9141 	 */
9142 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9143 	    sizeof (tcp->tcp_ipha->ipha_dst));
9144 
9145 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9146 }
9147 
9148 /* Unlink and return any mblk that looks like it contains an ire */
9149 static mblk_t *
9150 tcp_ire_mp(mblk_t *mp)
9151 {
9152 	mblk_t	*prev_mp;
9153 
9154 	for (;;) {
9155 		prev_mp = mp;
9156 		mp = mp->b_cont;
9157 		if (mp == NULL)
9158 			break;
9159 		switch (DB_TYPE(mp)) {
9160 		case IRE_DB_TYPE:
9161 		case IRE_DB_REQ_TYPE:
9162 			if (prev_mp != NULL)
9163 				prev_mp->b_cont = mp->b_cont;
9164 			mp->b_cont = NULL;
9165 			return (mp);
9166 		default:
9167 			break;
9168 		}
9169 	}
9170 	return (mp);
9171 }
9172 
9173 /*
9174  * Timer callback routine for keepalive probe.  We do a fake resend of
9175  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9176  * check to see if we have heard anything from the other end for the last
9177  * RTO period.  If we have, set the timer to expire for another
9178  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9179  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9180  * the timeout if we have not heard from the other side.  If for more than
9181  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9182  * kill the connection unless the keepalive abort threshold is 0.  In
9183  * that case, we will probe "forever."
9184  */
9185 static void
9186 tcp_keepalive_killer(void *arg)
9187 {
9188 	mblk_t	*mp;
9189 	conn_t	*connp = (conn_t *)arg;
9190 	tcp_t  	*tcp = connp->conn_tcp;
9191 	int32_t	firetime;
9192 	int32_t	idletime;
9193 	int32_t	ka_intrvl;
9194 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9195 
9196 	tcp->tcp_ka_tid = 0;
9197 
9198 	if (tcp->tcp_fused)
9199 		return;
9200 
9201 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9202 	ka_intrvl = tcp->tcp_ka_interval;
9203 
9204 	/*
9205 	 * Keepalive probe should only be sent if the application has not
9206 	 * done a close on the connection.
9207 	 */
9208 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9209 		return;
9210 	}
9211 	/* Timer fired too early, restart it. */
9212 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9213 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9214 		    MSEC_TO_TICK(ka_intrvl));
9215 		return;
9216 	}
9217 
9218 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9219 	/*
9220 	 * If we have not heard from the other side for a long
9221 	 * time, kill the connection unless the keepalive abort
9222 	 * threshold is 0.  In that case, we will probe "forever."
9223 	 */
9224 	if (tcp->tcp_ka_abort_thres != 0 &&
9225 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9226 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9227 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9228 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9229 		return;
9230 	}
9231 
9232 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9233 	    idletime >= ka_intrvl) {
9234 		/* Fake resend of last ACKed byte. */
9235 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9236 
9237 		if (mp1 != NULL) {
9238 			*mp1->b_wptr++ = '\0';
9239 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9240 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9241 			freeb(mp1);
9242 			/*
9243 			 * if allocation failed, fall through to start the
9244 			 * timer back.
9245 			 */
9246 			if (mp != NULL) {
9247 				TCP_RECORD_TRACE(tcp, mp,
9248 				    TCP_TRACE_SEND_PKT);
9249 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9250 				BUMP_MIB(&tcps->tcps_mib,
9251 				    tcpTimKeepaliveProbe);
9252 				if (tcp->tcp_ka_last_intrvl != 0) {
9253 					int max;
9254 					/*
9255 					 * We should probe again at least
9256 					 * in ka_intrvl, but not more than
9257 					 * tcp_rexmit_interval_max.
9258 					 */
9259 					max = tcps->tcps_rexmit_interval_max;
9260 					firetime = MIN(ka_intrvl - 1,
9261 					    tcp->tcp_ka_last_intrvl << 1);
9262 					if (firetime > max)
9263 						firetime = max;
9264 				} else {
9265 					firetime = tcp->tcp_rto;
9266 				}
9267 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9268 				    tcp_keepalive_killer,
9269 				    MSEC_TO_TICK(firetime));
9270 				tcp->tcp_ka_last_intrvl = firetime;
9271 				return;
9272 			}
9273 		}
9274 	} else {
9275 		tcp->tcp_ka_last_intrvl = 0;
9276 	}
9277 
9278 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9279 	if ((firetime = ka_intrvl - idletime) < 0) {
9280 		firetime = ka_intrvl;
9281 	}
9282 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9283 	    MSEC_TO_TICK(firetime));
9284 }
9285 
9286 int
9287 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9288 {
9289 	queue_t	*q = tcp->tcp_rq;
9290 	int32_t	mss = tcp->tcp_mss;
9291 	int	maxpsz;
9292 
9293 	if (TCP_IS_DETACHED(tcp))
9294 		return (mss);
9295 
9296 	if (tcp->tcp_fused) {
9297 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9298 		mss = INFPSZ;
9299 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9300 		/*
9301 		 * Set the sd_qn_maxpsz according to the socket send buffer
9302 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9303 		 * instruct the stream head to copyin user data into contiguous
9304 		 * kernel-allocated buffers without breaking it up into smaller
9305 		 * chunks.  We round up the buffer size to the nearest SMSS.
9306 		 */
9307 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9308 		if (tcp->tcp_kssl_ctx == NULL)
9309 			mss = INFPSZ;
9310 		else
9311 			mss = SSL3_MAX_RECORD_LEN;
9312 	} else {
9313 		/*
9314 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9315 		 * (and a multiple of the mss).  This instructs the stream
9316 		 * head to break down larger than SMSS writes into SMSS-
9317 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9318 		 */
9319 		maxpsz = tcp->tcp_maxpsz * mss;
9320 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9321 			maxpsz = tcp->tcp_xmit_hiwater/2;
9322 			/* Round up to nearest mss */
9323 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9324 		}
9325 	}
9326 	(void) setmaxps(q, maxpsz);
9327 	tcp->tcp_wq->q_maxpsz = maxpsz;
9328 
9329 	if (set_maxblk)
9330 		(void) mi_set_sth_maxblk(q, mss);
9331 
9332 	return (mss);
9333 }
9334 
9335 /*
9336  * Extract option values from a tcp header.  We put any found values into the
9337  * tcpopt struct and return a bitmask saying which options were found.
9338  */
9339 static int
9340 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9341 {
9342 	uchar_t		*endp;
9343 	int		len;
9344 	uint32_t	mss;
9345 	uchar_t		*up = (uchar_t *)tcph;
9346 	int		found = 0;
9347 	int32_t		sack_len;
9348 	tcp_seq		sack_begin, sack_end;
9349 	tcp_t		*tcp;
9350 
9351 	endp = up + TCP_HDR_LENGTH(tcph);
9352 	up += TCP_MIN_HEADER_LENGTH;
9353 	while (up < endp) {
9354 		len = endp - up;
9355 		switch (*up) {
9356 		case TCPOPT_EOL:
9357 			break;
9358 
9359 		case TCPOPT_NOP:
9360 			up++;
9361 			continue;
9362 
9363 		case TCPOPT_MAXSEG:
9364 			if (len < TCPOPT_MAXSEG_LEN ||
9365 			    up[1] != TCPOPT_MAXSEG_LEN)
9366 				break;
9367 
9368 			mss = BE16_TO_U16(up+2);
9369 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9370 			tcpopt->tcp_opt_mss = mss;
9371 			found |= TCP_OPT_MSS_PRESENT;
9372 
9373 			up += TCPOPT_MAXSEG_LEN;
9374 			continue;
9375 
9376 		case TCPOPT_WSCALE:
9377 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9378 				break;
9379 
9380 			if (up[2] > TCP_MAX_WINSHIFT)
9381 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9382 			else
9383 				tcpopt->tcp_opt_wscale = up[2];
9384 			found |= TCP_OPT_WSCALE_PRESENT;
9385 
9386 			up += TCPOPT_WS_LEN;
9387 			continue;
9388 
9389 		case TCPOPT_SACK_PERMITTED:
9390 			if (len < TCPOPT_SACK_OK_LEN ||
9391 			    up[1] != TCPOPT_SACK_OK_LEN)
9392 				break;
9393 			found |= TCP_OPT_SACK_OK_PRESENT;
9394 			up += TCPOPT_SACK_OK_LEN;
9395 			continue;
9396 
9397 		case TCPOPT_SACK:
9398 			if (len <= 2 || up[1] <= 2 || len < up[1])
9399 				break;
9400 
9401 			/* If TCP is not interested in SACK blks... */
9402 			if ((tcp = tcpopt->tcp) == NULL) {
9403 				up += up[1];
9404 				continue;
9405 			}
9406 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9407 			up += TCPOPT_HEADER_LEN;
9408 
9409 			/*
9410 			 * If the list is empty, allocate one and assume
9411 			 * nothing is sack'ed.
9412 			 */
9413 			ASSERT(tcp->tcp_sack_info != NULL);
9414 			if (tcp->tcp_notsack_list == NULL) {
9415 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9416 				    tcp->tcp_suna, tcp->tcp_snxt,
9417 				    &(tcp->tcp_num_notsack_blk),
9418 				    &(tcp->tcp_cnt_notsack_list));
9419 
9420 				/*
9421 				 * Make sure tcp_notsack_list is not NULL.
9422 				 * This happens when kmem_alloc(KM_NOSLEEP)
9423 				 * returns NULL.
9424 				 */
9425 				if (tcp->tcp_notsack_list == NULL) {
9426 					up += sack_len;
9427 					continue;
9428 				}
9429 				tcp->tcp_fack = tcp->tcp_suna;
9430 			}
9431 
9432 			while (sack_len > 0) {
9433 				if (up + 8 > endp) {
9434 					up = endp;
9435 					break;
9436 				}
9437 				sack_begin = BE32_TO_U32(up);
9438 				up += 4;
9439 				sack_end = BE32_TO_U32(up);
9440 				up += 4;
9441 				sack_len -= 8;
9442 				/*
9443 				 * Bounds checking.  Make sure the SACK
9444 				 * info is within tcp_suna and tcp_snxt.
9445 				 * If this SACK blk is out of bound, ignore
9446 				 * it but continue to parse the following
9447 				 * blks.
9448 				 */
9449 				if (SEQ_LEQ(sack_end, sack_begin) ||
9450 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9451 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9452 					continue;
9453 				}
9454 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9455 				    sack_begin, sack_end,
9456 				    &(tcp->tcp_num_notsack_blk),
9457 				    &(tcp->tcp_cnt_notsack_list));
9458 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9459 					tcp->tcp_fack = sack_end;
9460 				}
9461 			}
9462 			found |= TCP_OPT_SACK_PRESENT;
9463 			continue;
9464 
9465 		case TCPOPT_TSTAMP:
9466 			if (len < TCPOPT_TSTAMP_LEN ||
9467 			    up[1] != TCPOPT_TSTAMP_LEN)
9468 				break;
9469 
9470 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9471 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9472 
9473 			found |= TCP_OPT_TSTAMP_PRESENT;
9474 
9475 			up += TCPOPT_TSTAMP_LEN;
9476 			continue;
9477 
9478 		default:
9479 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9480 				break;
9481 			up += up[1];
9482 			continue;
9483 		}
9484 		break;
9485 	}
9486 	return (found);
9487 }
9488 
9489 /*
9490  * Set the mss associated with a particular tcp based on its current value,
9491  * and a new one passed in. Observe minimums and maximums, and reset
9492  * other state variables that we want to view as multiples of mss.
9493  *
9494  * This function is called in various places mainly because
9495  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9496  *    other side's SYN/SYN-ACK packet arrives.
9497  * 2) PMTUd may get us a new MSS.
9498  * 3) If the other side stops sending us timestamp option, we need to
9499  *    increase the MSS size to use the extra bytes available.
9500  *
9501  * do_ss is used to control whether we will be doing slow start or
9502  * not if there is a change in the mss. Note that for some events like
9503  * tcp_paws_check() we allow the tcp_cwnd to adjust to the new mss but
9504  * do not perform a slow start specifically.
9505  */
9506 static void
9507 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9508 {
9509 	uint32_t	mss_max;
9510 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9511 
9512 	if (tcp->tcp_ipversion == IPV4_VERSION)
9513 		mss_max = tcps->tcps_mss_max_ipv4;
9514 	else
9515 		mss_max = tcps->tcps_mss_max_ipv6;
9516 
9517 	if (mss < tcps->tcps_mss_min)
9518 		mss = tcps->tcps_mss_min;
9519 	if (mss > mss_max)
9520 		mss = mss_max;
9521 	/*
9522 	 * Unless naglim has been set by our client to
9523 	 * a non-mss value, force naglim to track mss.
9524 	 * This can help to aggregate small writes.
9525 	 */
9526 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9527 		tcp->tcp_naglim = mss;
9528 	/*
9529 	 * TCP should be able to buffer at least 4 MSS data for obvious
9530 	 * performance reason.
9531 	 */
9532 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9533 		tcp->tcp_xmit_hiwater = mss << 2;
9534 
9535 	/*
9536 	 * Check if we need to apply the tcp_init_cwnd here.  If
9537 	 * it is set and the MSS gets bigger (should not happen
9538 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9539 	 * The new tcp_cwnd should not get bigger.
9540 	 */
9541 	/*
9542 	 * We need to avoid setting tcp_cwnd to its slow start value
9543 	 * unnecessarily. However we have to let the tcp_cwnd adjust
9544 	 * to the modified mss.
9545 	 */
9546 	if (tcp->tcp_init_cwnd == 0 && do_ss) {
9547 		tcp->tcp_cwnd = MIN(tcps->tcps_slow_start_initial *
9548 		    mss, MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9549 	} else {
9550 		if (tcp->tcp_mss < mss) {
9551 			tcp->tcp_cwnd = MAX(1,
9552 			    (tcp->tcp_init_cwnd * tcp->tcp_mss /
9553 			    mss)) * mss;
9554 		} else {
9555 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9556 		}
9557 	}
9558 	tcp->tcp_mss = mss;
9559 	tcp->tcp_cwnd_cnt = 0;
9560 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9561 }
9562 
9563 static int
9564 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9565 {
9566 	tcp_t		*tcp = NULL;
9567 	conn_t		*connp;
9568 	int		err;
9569 	dev_t		conn_dev;
9570 	zoneid_t	zoneid;
9571 	tcp_stack_t	*tcps = NULL;
9572 
9573 	if (q->q_ptr != NULL)
9574 		return (0);
9575 
9576 	if (!(flag & SO_ACCEPTOR)) {
9577 		/*
9578 		 * Special case for install: miniroot needs to be able to
9579 		 * access files via NFS as though it were always in the
9580 		 * global zone.
9581 		 */
9582 		if (credp == kcred && nfs_global_client_only != 0) {
9583 			zoneid = GLOBAL_ZONEID;
9584 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9585 			    netstack_tcp;
9586 			ASSERT(tcps != NULL);
9587 		} else {
9588 			netstack_t *ns;
9589 
9590 			ns = netstack_find_by_cred(credp);
9591 			ASSERT(ns != NULL);
9592 			tcps = ns->netstack_tcp;
9593 			ASSERT(tcps != NULL);
9594 
9595 			/*
9596 			 * For exclusive stacks we set the zoneid to zero
9597 			 * to make TCP operate as if in the global zone.
9598 			 */
9599 			if (tcps->tcps_netstack->netstack_stackid !=
9600 			    GLOBAL_NETSTACKID)
9601 				zoneid = GLOBAL_ZONEID;
9602 			else
9603 				zoneid = crgetzoneid(credp);
9604 		}
9605 		/*
9606 		 * For stackid zero this is done from strplumb.c, but
9607 		 * non-zero stackids are handled here.
9608 		 */
9609 		if (tcps->tcps_g_q == NULL &&
9610 		    tcps->tcps_netstack->netstack_stackid !=
9611 		    GLOBAL_NETSTACKID) {
9612 			tcp_g_q_setup(tcps);
9613 		}
9614 	}
9615 	if (sflag == MODOPEN) {
9616 		/*
9617 		 * This is a special case. The purpose of a modopen
9618 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9619 		 * through for MIB browsers. Everything else is failed.
9620 		 */
9621 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9622 		/* tcp_get_conn incremented refcnt */
9623 		netstack_rele(tcps->tcps_netstack);
9624 
9625 		if (connp == NULL)
9626 			return (ENOMEM);
9627 
9628 		connp->conn_flags |= IPCL_TCPMOD;
9629 		connp->conn_cred = credp;
9630 		connp->conn_zoneid = zoneid;
9631 		ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9632 		ASSERT(connp->conn_netstack->netstack_tcp == tcps);
9633 		q->q_ptr = WR(q)->q_ptr = connp;
9634 		crhold(credp);
9635 		q->q_qinfo = &tcp_mod_rinit;
9636 		WR(q)->q_qinfo = &tcp_mod_winit;
9637 		qprocson(q);
9638 		return (0);
9639 	}
9640 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9641 		if (tcps != NULL)
9642 			netstack_rele(tcps->tcps_netstack);
9643 		return (EBUSY);
9644 	}
9645 
9646 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9647 
9648 	if (flag & SO_ACCEPTOR) {
9649 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9650 		ASSERT(tcps == NULL);
9651 		q->q_qinfo = &tcp_acceptor_rinit;
9652 		q->q_ptr = (void *)conn_dev;
9653 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9654 		WR(q)->q_ptr = (void *)conn_dev;
9655 		qprocson(q);
9656 		return (0);
9657 	}
9658 
9659 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9660 	/*
9661 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9662 	 * so we drop it by one.
9663 	 */
9664 	netstack_rele(tcps->tcps_netstack);
9665 	if (connp == NULL) {
9666 		inet_minor_free(ip_minor_arena, conn_dev);
9667 		q->q_ptr = NULL;
9668 		return (ENOSR);
9669 	}
9670 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9671 	tcp = connp->conn_tcp;
9672 
9673 	q->q_ptr = WR(q)->q_ptr = connp;
9674 	if (getmajor(*devp) == TCP6_MAJ) {
9675 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9676 		connp->conn_send = ip_output_v6;
9677 		connp->conn_af_isv6 = B_TRUE;
9678 		connp->conn_pkt_isv6 = B_TRUE;
9679 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9680 		tcp->tcp_ipversion = IPV6_VERSION;
9681 		tcp->tcp_family = AF_INET6;
9682 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9683 	} else {
9684 		connp->conn_flags |= IPCL_TCP4;
9685 		connp->conn_send = ip_output;
9686 		connp->conn_af_isv6 = B_FALSE;
9687 		connp->conn_pkt_isv6 = B_FALSE;
9688 		tcp->tcp_ipversion = IPV4_VERSION;
9689 		tcp->tcp_family = AF_INET;
9690 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9691 	}
9692 
9693 	/*
9694 	 * TCP keeps a copy of cred for cache locality reasons but
9695 	 * we put a reference only once. If connp->conn_cred
9696 	 * becomes invalid, tcp_cred should also be set to NULL.
9697 	 */
9698 	tcp->tcp_cred = connp->conn_cred = credp;
9699 	crhold(connp->conn_cred);
9700 	tcp->tcp_cpid = curproc->p_pid;
9701 	tcp->tcp_open_time = lbolt64;
9702 	connp->conn_zoneid = zoneid;
9703 	connp->conn_mlp_type = mlptSingle;
9704 	connp->conn_ulp_labeled = !is_system_labeled();
9705 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9706 	ASSERT(tcp->tcp_tcps == tcps);
9707 
9708 	/*
9709 	 * If the caller has the process-wide flag set, then default to MAC
9710 	 * exempt mode.  This allows read-down to unlabeled hosts.
9711 	 */
9712 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9713 		connp->conn_mac_exempt = B_TRUE;
9714 
9715 	connp->conn_dev = conn_dev;
9716 
9717 	ASSERT(q->q_qinfo == &tcp_rinit);
9718 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9719 
9720 	if (flag & SO_SOCKSTR) {
9721 		/*
9722 		 * No need to insert a socket in tcp acceptor hash.
9723 		 * If it was a socket acceptor stream, we dealt with
9724 		 * it above. A socket listener can never accept a
9725 		 * connection and doesn't need acceptor_id.
9726 		 */
9727 		connp->conn_flags |= IPCL_SOCKET;
9728 		tcp->tcp_issocket = 1;
9729 		WR(q)->q_qinfo = &tcp_sock_winit;
9730 	} else {
9731 #ifdef	_ILP32
9732 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9733 #else
9734 		tcp->tcp_acceptor_id = conn_dev;
9735 #endif	/* _ILP32 */
9736 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9737 	}
9738 
9739 	if (tcps->tcps_trace)
9740 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9741 
9742 	err = tcp_init(tcp, q);
9743 	if (err != 0) {
9744 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9745 		tcp_acceptor_hash_remove(tcp);
9746 		CONN_DEC_REF(connp);
9747 		q->q_ptr = WR(q)->q_ptr = NULL;
9748 		return (err);
9749 	}
9750 
9751 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9752 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9753 
9754 	/* Non-zero default values */
9755 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9756 	/*
9757 	 * Put the ref for TCP. Ref for IP was already put
9758 	 * by ipcl_conn_create. Also Make the conn_t globally
9759 	 * visible to walkers
9760 	 */
9761 	mutex_enter(&connp->conn_lock);
9762 	CONN_INC_REF_LOCKED(connp);
9763 	ASSERT(connp->conn_ref == 2);
9764 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9765 	mutex_exit(&connp->conn_lock);
9766 
9767 	qprocson(q);
9768 	return (0);
9769 }
9770 
9771 /*
9772  * Some TCP options can be "set" by requesting them in the option
9773  * buffer. This is needed for XTI feature test though we do not
9774  * allow it in general. We interpret that this mechanism is more
9775  * applicable to OSI protocols and need not be allowed in general.
9776  * This routine filters out options for which it is not allowed (most)
9777  * and lets through those (few) for which it is. [ The XTI interface
9778  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9779  * ever implemented will have to be allowed here ].
9780  */
9781 static boolean_t
9782 tcp_allow_connopt_set(int level, int name)
9783 {
9784 
9785 	switch (level) {
9786 	case IPPROTO_TCP:
9787 		switch (name) {
9788 		case TCP_NODELAY:
9789 			return (B_TRUE);
9790 		default:
9791 			return (B_FALSE);
9792 		}
9793 		/*NOTREACHED*/
9794 	default:
9795 		return (B_FALSE);
9796 	}
9797 	/*NOTREACHED*/
9798 }
9799 
9800 /*
9801  * This routine gets default values of certain options whose default
9802  * values are maintained by protocol specific code
9803  */
9804 /* ARGSUSED */
9805 int
9806 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9807 {
9808 	int32_t	*i1 = (int32_t *)ptr;
9809 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9810 
9811 	switch (level) {
9812 	case IPPROTO_TCP:
9813 		switch (name) {
9814 		case TCP_NOTIFY_THRESHOLD:
9815 			*i1 = tcps->tcps_ip_notify_interval;
9816 			break;
9817 		case TCP_ABORT_THRESHOLD:
9818 			*i1 = tcps->tcps_ip_abort_interval;
9819 			break;
9820 		case TCP_CONN_NOTIFY_THRESHOLD:
9821 			*i1 = tcps->tcps_ip_notify_cinterval;
9822 			break;
9823 		case TCP_CONN_ABORT_THRESHOLD:
9824 			*i1 = tcps->tcps_ip_abort_cinterval;
9825 			break;
9826 		default:
9827 			return (-1);
9828 		}
9829 		break;
9830 	case IPPROTO_IP:
9831 		switch (name) {
9832 		case IP_TTL:
9833 			*i1 = tcps->tcps_ipv4_ttl;
9834 			break;
9835 		default:
9836 			return (-1);
9837 		}
9838 		break;
9839 	case IPPROTO_IPV6:
9840 		switch (name) {
9841 		case IPV6_UNICAST_HOPS:
9842 			*i1 = tcps->tcps_ipv6_hoplimit;
9843 			break;
9844 		default:
9845 			return (-1);
9846 		}
9847 		break;
9848 	default:
9849 		return (-1);
9850 	}
9851 	return (sizeof (int));
9852 }
9853 
9854 
9855 /*
9856  * TCP routine to get the values of options.
9857  */
9858 int
9859 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9860 {
9861 	int		*i1 = (int *)ptr;
9862 	conn_t		*connp = Q_TO_CONN(q);
9863 	tcp_t		*tcp = connp->conn_tcp;
9864 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9865 
9866 	switch (level) {
9867 	case SOL_SOCKET:
9868 		switch (name) {
9869 		case SO_LINGER:	{
9870 			struct linger *lgr = (struct linger *)ptr;
9871 
9872 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9873 			lgr->l_linger = tcp->tcp_lingertime;
9874 			}
9875 			return (sizeof (struct linger));
9876 		case SO_DEBUG:
9877 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9878 			break;
9879 		case SO_KEEPALIVE:
9880 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9881 			break;
9882 		case SO_DONTROUTE:
9883 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9884 			break;
9885 		case SO_USELOOPBACK:
9886 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9887 			break;
9888 		case SO_BROADCAST:
9889 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9890 			break;
9891 		case SO_REUSEADDR:
9892 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9893 			break;
9894 		case SO_OOBINLINE:
9895 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9896 			break;
9897 		case SO_DGRAM_ERRIND:
9898 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9899 			break;
9900 		case SO_TYPE:
9901 			*i1 = SOCK_STREAM;
9902 			break;
9903 		case SO_SNDBUF:
9904 			*i1 = tcp->tcp_xmit_hiwater;
9905 			break;
9906 		case SO_RCVBUF:
9907 			*i1 = RD(q)->q_hiwat;
9908 			break;
9909 		case SO_SND_COPYAVOID:
9910 			*i1 = tcp->tcp_snd_zcopy_on ?
9911 			    SO_SND_COPYAVOID : 0;
9912 			break;
9913 		case SO_ALLZONES:
9914 			*i1 = connp->conn_allzones ? 1 : 0;
9915 			break;
9916 		case SO_ANON_MLP:
9917 			*i1 = connp->conn_anon_mlp;
9918 			break;
9919 		case SO_MAC_EXEMPT:
9920 			*i1 = connp->conn_mac_exempt;
9921 			break;
9922 		case SO_EXCLBIND:
9923 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9924 			break;
9925 		case SO_PROTOTYPE:
9926 			*i1 = IPPROTO_TCP;
9927 			break;
9928 		case SO_DOMAIN:
9929 			*i1 = tcp->tcp_family;
9930 			break;
9931 		default:
9932 			return (-1);
9933 		}
9934 		break;
9935 	case IPPROTO_TCP:
9936 		switch (name) {
9937 		case TCP_NODELAY:
9938 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9939 			break;
9940 		case TCP_MAXSEG:
9941 			*i1 = tcp->tcp_mss;
9942 			break;
9943 		case TCP_NOTIFY_THRESHOLD:
9944 			*i1 = (int)tcp->tcp_first_timer_threshold;
9945 			break;
9946 		case TCP_ABORT_THRESHOLD:
9947 			*i1 = tcp->tcp_second_timer_threshold;
9948 			break;
9949 		case TCP_CONN_NOTIFY_THRESHOLD:
9950 			*i1 = tcp->tcp_first_ctimer_threshold;
9951 			break;
9952 		case TCP_CONN_ABORT_THRESHOLD:
9953 			*i1 = tcp->tcp_second_ctimer_threshold;
9954 			break;
9955 		case TCP_RECVDSTADDR:
9956 			*i1 = tcp->tcp_recvdstaddr;
9957 			break;
9958 		case TCP_ANONPRIVBIND:
9959 			*i1 = tcp->tcp_anon_priv_bind;
9960 			break;
9961 		case TCP_EXCLBIND:
9962 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9963 			break;
9964 		case TCP_INIT_CWND:
9965 			*i1 = tcp->tcp_init_cwnd;
9966 			break;
9967 		case TCP_KEEPALIVE_THRESHOLD:
9968 			*i1 = tcp->tcp_ka_interval;
9969 			break;
9970 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9971 			*i1 = tcp->tcp_ka_abort_thres;
9972 			break;
9973 		case TCP_CORK:
9974 			*i1 = tcp->tcp_cork;
9975 			break;
9976 		default:
9977 			return (-1);
9978 		}
9979 		break;
9980 	case IPPROTO_IP:
9981 		if (tcp->tcp_family != AF_INET)
9982 			return (-1);
9983 		switch (name) {
9984 		case IP_OPTIONS:
9985 		case T_IP_OPTIONS: {
9986 			/*
9987 			 * This is compatible with BSD in that in only return
9988 			 * the reverse source route with the final destination
9989 			 * as the last entry. The first 4 bytes of the option
9990 			 * will contain the final destination.
9991 			 */
9992 			int	opt_len;
9993 
9994 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9995 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9996 			ASSERT(opt_len >= 0);
9997 			/* Caller ensures enough space */
9998 			if (opt_len > 0) {
9999 				/*
10000 				 * TODO: Do we have to handle getsockopt on an
10001 				 * initiator as well?
10002 				 */
10003 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10004 			}
10005 			return (0);
10006 			}
10007 		case IP_TOS:
10008 		case T_IP_TOS:
10009 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10010 			break;
10011 		case IP_TTL:
10012 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10013 			break;
10014 		case IP_NEXTHOP:
10015 			/* Handled at IP level */
10016 			return (-EINVAL);
10017 		default:
10018 			return (-1);
10019 		}
10020 		break;
10021 	case IPPROTO_IPV6:
10022 		/*
10023 		 * IPPROTO_IPV6 options are only supported for sockets
10024 		 * that are using IPv6 on the wire.
10025 		 */
10026 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10027 			return (-1);
10028 		}
10029 		switch (name) {
10030 		case IPV6_UNICAST_HOPS:
10031 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10032 			break;	/* goto sizeof (int) option return */
10033 		case IPV6_BOUND_IF:
10034 			/* Zero if not set */
10035 			*i1 = tcp->tcp_bound_if;
10036 			break;	/* goto sizeof (int) option return */
10037 		case IPV6_RECVPKTINFO:
10038 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10039 				*i1 = 1;
10040 			else
10041 				*i1 = 0;
10042 			break;	/* goto sizeof (int) option return */
10043 		case IPV6_RECVTCLASS:
10044 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10045 				*i1 = 1;
10046 			else
10047 				*i1 = 0;
10048 			break;	/* goto sizeof (int) option return */
10049 		case IPV6_RECVHOPLIMIT:
10050 			if (tcp->tcp_ipv6_recvancillary &
10051 			    TCP_IPV6_RECVHOPLIMIT)
10052 				*i1 = 1;
10053 			else
10054 				*i1 = 0;
10055 			break;	/* goto sizeof (int) option return */
10056 		case IPV6_RECVHOPOPTS:
10057 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10058 				*i1 = 1;
10059 			else
10060 				*i1 = 0;
10061 			break;	/* goto sizeof (int) option return */
10062 		case IPV6_RECVDSTOPTS:
10063 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10064 				*i1 = 1;
10065 			else
10066 				*i1 = 0;
10067 			break;	/* goto sizeof (int) option return */
10068 		case _OLD_IPV6_RECVDSTOPTS:
10069 			if (tcp->tcp_ipv6_recvancillary &
10070 			    TCP_OLD_IPV6_RECVDSTOPTS)
10071 				*i1 = 1;
10072 			else
10073 				*i1 = 0;
10074 			break;	/* goto sizeof (int) option return */
10075 		case IPV6_RECVRTHDR:
10076 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10077 				*i1 = 1;
10078 			else
10079 				*i1 = 0;
10080 			break;	/* goto sizeof (int) option return */
10081 		case IPV6_RECVRTHDRDSTOPTS:
10082 			if (tcp->tcp_ipv6_recvancillary &
10083 			    TCP_IPV6_RECVRTDSTOPTS)
10084 				*i1 = 1;
10085 			else
10086 				*i1 = 0;
10087 			break;	/* goto sizeof (int) option return */
10088 		case IPV6_PKTINFO: {
10089 			/* XXX assumes that caller has room for max size! */
10090 			struct in6_pktinfo *pkti;
10091 
10092 			pkti = (struct in6_pktinfo *)ptr;
10093 			if (ipp->ipp_fields & IPPF_IFINDEX)
10094 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10095 			else
10096 				pkti->ipi6_ifindex = 0;
10097 			if (ipp->ipp_fields & IPPF_ADDR)
10098 				pkti->ipi6_addr = ipp->ipp_addr;
10099 			else
10100 				pkti->ipi6_addr = ipv6_all_zeros;
10101 			return (sizeof (struct in6_pktinfo));
10102 		}
10103 		case IPV6_TCLASS:
10104 			if (ipp->ipp_fields & IPPF_TCLASS)
10105 				*i1 = ipp->ipp_tclass;
10106 			else
10107 				*i1 = IPV6_FLOW_TCLASS(
10108 				    IPV6_DEFAULT_VERS_AND_FLOW);
10109 			break;	/* goto sizeof (int) option return */
10110 		case IPV6_NEXTHOP: {
10111 			sin6_t *sin6 = (sin6_t *)ptr;
10112 
10113 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10114 				return (0);
10115 			*sin6 = sin6_null;
10116 			sin6->sin6_family = AF_INET6;
10117 			sin6->sin6_addr = ipp->ipp_nexthop;
10118 			return (sizeof (sin6_t));
10119 		}
10120 		case IPV6_HOPOPTS:
10121 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10122 				return (0);
10123 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10124 				return (0);
10125 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10126 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10127 			if (tcp->tcp_label_len > 0) {
10128 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10129 				ptr[1] = (ipp->ipp_hopoptslen -
10130 				    tcp->tcp_label_len + 7) / 8 - 1;
10131 			}
10132 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10133 		case IPV6_RTHDRDSTOPTS:
10134 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10135 				return (0);
10136 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10137 			return (ipp->ipp_rtdstoptslen);
10138 		case IPV6_RTHDR:
10139 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10140 				return (0);
10141 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10142 			return (ipp->ipp_rthdrlen);
10143 		case IPV6_DSTOPTS:
10144 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10145 				return (0);
10146 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10147 			return (ipp->ipp_dstoptslen);
10148 		case IPV6_SRC_PREFERENCES:
10149 			return (ip6_get_src_preferences(connp,
10150 			    (uint32_t *)ptr));
10151 		case IPV6_PATHMTU: {
10152 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10153 
10154 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10155 				return (-1);
10156 
10157 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10158 				connp->conn_fport, mtuinfo,
10159 				connp->conn_netstack));
10160 		}
10161 		default:
10162 			return (-1);
10163 		}
10164 		break;
10165 	default:
10166 		return (-1);
10167 	}
10168 	return (sizeof (int));
10169 }
10170 
10171 /*
10172  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10173  * Parameters are assumed to be verified by the caller.
10174  */
10175 /* ARGSUSED */
10176 int
10177 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10178     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10179     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10180 {
10181 	conn_t	*connp = Q_TO_CONN(q);
10182 	tcp_t	*tcp = connp->conn_tcp;
10183 	int	*i1 = (int *)invalp;
10184 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10185 	boolean_t checkonly;
10186 	int	reterr;
10187 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10188 
10189 	switch (optset_context) {
10190 	case SETFN_OPTCOM_CHECKONLY:
10191 		checkonly = B_TRUE;
10192 		/*
10193 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10194 		 * inlen != 0 implies value supplied and
10195 		 * 	we have to "pretend" to set it.
10196 		 * inlen == 0 implies that there is no
10197 		 * 	value part in T_CHECK request and just validation
10198 		 * done elsewhere should be enough, we just return here.
10199 		 */
10200 		if (inlen == 0) {
10201 			*outlenp = 0;
10202 			return (0);
10203 		}
10204 		break;
10205 	case SETFN_OPTCOM_NEGOTIATE:
10206 		checkonly = B_FALSE;
10207 		break;
10208 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10209 	case SETFN_CONN_NEGOTIATE:
10210 		checkonly = B_FALSE;
10211 		/*
10212 		 * Negotiating local and "association-related" options
10213 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10214 		 * primitives is allowed by XTI, but we choose
10215 		 * to not implement this style negotiation for Internet
10216 		 * protocols (We interpret it is a must for OSI world but
10217 		 * optional for Internet protocols) for all options.
10218 		 * [ Will do only for the few options that enable test
10219 		 * suites that our XTI implementation of this feature
10220 		 * works for transports that do allow it ]
10221 		 */
10222 		if (!tcp_allow_connopt_set(level, name)) {
10223 			*outlenp = 0;
10224 			return (EINVAL);
10225 		}
10226 		break;
10227 	default:
10228 		/*
10229 		 * We should never get here
10230 		 */
10231 		*outlenp = 0;
10232 		return (EINVAL);
10233 	}
10234 
10235 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10236 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10237 
10238 	/*
10239 	 * For TCP, we should have no ancillary data sent down
10240 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10241 	 * has to be zero.
10242 	 */
10243 	ASSERT(thisdg_attrs == NULL);
10244 
10245 	/*
10246 	 * For fixed length options, no sanity check
10247 	 * of passed in length is done. It is assumed *_optcom_req()
10248 	 * routines do the right thing.
10249 	 */
10250 
10251 	switch (level) {
10252 	case SOL_SOCKET:
10253 		switch (name) {
10254 		case SO_LINGER: {
10255 			struct linger *lgr = (struct linger *)invalp;
10256 
10257 			if (!checkonly) {
10258 				if (lgr->l_onoff) {
10259 					tcp->tcp_linger = 1;
10260 					tcp->tcp_lingertime = lgr->l_linger;
10261 				} else {
10262 					tcp->tcp_linger = 0;
10263 					tcp->tcp_lingertime = 0;
10264 				}
10265 				/* struct copy */
10266 				*(struct linger *)outvalp = *lgr;
10267 			} else {
10268 				if (!lgr->l_onoff) {
10269 				    ((struct linger *)outvalp)->l_onoff = 0;
10270 				    ((struct linger *)outvalp)->l_linger = 0;
10271 				} else {
10272 				    /* struct copy */
10273 				    *(struct linger *)outvalp = *lgr;
10274 				}
10275 			}
10276 			*outlenp = sizeof (struct linger);
10277 			return (0);
10278 		}
10279 		case SO_DEBUG:
10280 			if (!checkonly)
10281 				tcp->tcp_debug = onoff;
10282 			break;
10283 		case SO_KEEPALIVE:
10284 			if (checkonly) {
10285 				/* T_CHECK case */
10286 				break;
10287 			}
10288 
10289 			if (!onoff) {
10290 				if (tcp->tcp_ka_enabled) {
10291 					if (tcp->tcp_ka_tid != 0) {
10292 						(void) TCP_TIMER_CANCEL(tcp,
10293 						    tcp->tcp_ka_tid);
10294 						tcp->tcp_ka_tid = 0;
10295 					}
10296 					tcp->tcp_ka_enabled = 0;
10297 				}
10298 				break;
10299 			}
10300 			if (!tcp->tcp_ka_enabled) {
10301 				/* Crank up the keepalive timer */
10302 				tcp->tcp_ka_last_intrvl = 0;
10303 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10304 				    tcp_keepalive_killer,
10305 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10306 				tcp->tcp_ka_enabled = 1;
10307 			}
10308 			break;
10309 		case SO_DONTROUTE:
10310 			/*
10311 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10312 			 * only of interest to IP.  We track them here only so
10313 			 * that we can report their current value.
10314 			 */
10315 			if (!checkonly) {
10316 				tcp->tcp_dontroute = onoff;
10317 				tcp->tcp_connp->conn_dontroute = onoff;
10318 			}
10319 			break;
10320 		case SO_USELOOPBACK:
10321 			if (!checkonly) {
10322 				tcp->tcp_useloopback = onoff;
10323 				tcp->tcp_connp->conn_loopback = onoff;
10324 			}
10325 			break;
10326 		case SO_BROADCAST:
10327 			if (!checkonly) {
10328 				tcp->tcp_broadcast = onoff;
10329 				tcp->tcp_connp->conn_broadcast = onoff;
10330 			}
10331 			break;
10332 		case SO_REUSEADDR:
10333 			if (!checkonly) {
10334 				tcp->tcp_reuseaddr = onoff;
10335 				tcp->tcp_connp->conn_reuseaddr = onoff;
10336 			}
10337 			break;
10338 		case SO_OOBINLINE:
10339 			if (!checkonly)
10340 				tcp->tcp_oobinline = onoff;
10341 			break;
10342 		case SO_DGRAM_ERRIND:
10343 			if (!checkonly)
10344 				tcp->tcp_dgram_errind = onoff;
10345 			break;
10346 		case SO_SNDBUF: {
10347 			if (*i1 > tcps->tcps_max_buf) {
10348 				*outlenp = 0;
10349 				return (ENOBUFS);
10350 			}
10351 			if (checkonly)
10352 				break;
10353 
10354 			tcp->tcp_xmit_hiwater = *i1;
10355 			if (tcps->tcps_snd_lowat_fraction != 0)
10356 				tcp->tcp_xmit_lowater =
10357 				    tcp->tcp_xmit_hiwater /
10358 				    tcps->tcps_snd_lowat_fraction;
10359 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10360 			/*
10361 			 * If we are flow-controlled, recheck the condition.
10362 			 * There are apps that increase SO_SNDBUF size when
10363 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10364 			 * control condition to be lifted right away.
10365 			 */
10366 			mutex_enter(&tcp->tcp_non_sq_lock);
10367 			if (tcp->tcp_flow_stopped &&
10368 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10369 				tcp_clrqfull(tcp);
10370 			}
10371 			mutex_exit(&tcp->tcp_non_sq_lock);
10372 			break;
10373 		}
10374 		case SO_RCVBUF:
10375 			if (*i1 > tcps->tcps_max_buf) {
10376 				*outlenp = 0;
10377 				return (ENOBUFS);
10378 			}
10379 			/* Silently ignore zero */
10380 			if (!checkonly && *i1 != 0) {
10381 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10382 				(void) tcp_rwnd_set(tcp, *i1);
10383 			}
10384 			/*
10385 			 * XXX should we return the rwnd here
10386 			 * and tcp_opt_get ?
10387 			 */
10388 			break;
10389 		case SO_SND_COPYAVOID:
10390 			if (!checkonly) {
10391 				/* we only allow enable at most once for now */
10392 				if (tcp->tcp_loopback ||
10393 				    (!tcp->tcp_snd_zcopy_aware &&
10394 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10395 					*outlenp = 0;
10396 					return (EOPNOTSUPP);
10397 				}
10398 				tcp->tcp_snd_zcopy_aware = 1;
10399 			}
10400 			break;
10401 		case SO_ALLZONES:
10402 			/* Handled at the IP level */
10403 			return (-EINVAL);
10404 		case SO_ANON_MLP:
10405 			if (!checkonly) {
10406 				mutex_enter(&connp->conn_lock);
10407 				connp->conn_anon_mlp = onoff;
10408 				mutex_exit(&connp->conn_lock);
10409 			}
10410 			break;
10411 		case SO_MAC_EXEMPT:
10412 			if (secpolicy_net_mac_aware(cr) != 0 ||
10413 			    IPCL_IS_BOUND(connp))
10414 				return (EACCES);
10415 			if (!checkonly) {
10416 				mutex_enter(&connp->conn_lock);
10417 				connp->conn_mac_exempt = onoff;
10418 				mutex_exit(&connp->conn_lock);
10419 			}
10420 			break;
10421 		case SO_EXCLBIND:
10422 			if (!checkonly)
10423 				tcp->tcp_exclbind = onoff;
10424 			break;
10425 		default:
10426 			*outlenp = 0;
10427 			return (EINVAL);
10428 		}
10429 		break;
10430 	case IPPROTO_TCP:
10431 		switch (name) {
10432 		case TCP_NODELAY:
10433 			if (!checkonly)
10434 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10435 			break;
10436 		case TCP_NOTIFY_THRESHOLD:
10437 			if (!checkonly)
10438 				tcp->tcp_first_timer_threshold = *i1;
10439 			break;
10440 		case TCP_ABORT_THRESHOLD:
10441 			if (!checkonly)
10442 				tcp->tcp_second_timer_threshold = *i1;
10443 			break;
10444 		case TCP_CONN_NOTIFY_THRESHOLD:
10445 			if (!checkonly)
10446 				tcp->tcp_first_ctimer_threshold = *i1;
10447 			break;
10448 		case TCP_CONN_ABORT_THRESHOLD:
10449 			if (!checkonly)
10450 				tcp->tcp_second_ctimer_threshold = *i1;
10451 			break;
10452 		case TCP_RECVDSTADDR:
10453 			if (tcp->tcp_state > TCPS_LISTEN)
10454 				return (EOPNOTSUPP);
10455 			if (!checkonly)
10456 				tcp->tcp_recvdstaddr = onoff;
10457 			break;
10458 		case TCP_ANONPRIVBIND:
10459 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10460 				*outlenp = 0;
10461 				return (reterr);
10462 			}
10463 			if (!checkonly) {
10464 				tcp->tcp_anon_priv_bind = onoff;
10465 			}
10466 			break;
10467 		case TCP_EXCLBIND:
10468 			if (!checkonly)
10469 				tcp->tcp_exclbind = onoff;
10470 			break;	/* goto sizeof (int) option return */
10471 		case TCP_INIT_CWND: {
10472 			uint32_t init_cwnd = *((uint32_t *)invalp);
10473 
10474 			if (checkonly)
10475 				break;
10476 
10477 			/*
10478 			 * Only allow socket with network configuration
10479 			 * privilege to set the initial cwnd to be larger
10480 			 * than allowed by RFC 3390.
10481 			 */
10482 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10483 				tcp->tcp_init_cwnd = init_cwnd;
10484 				break;
10485 			}
10486 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10487 				*outlenp = 0;
10488 				return (reterr);
10489 			}
10490 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10491 				*outlenp = 0;
10492 				return (EINVAL);
10493 			}
10494 			tcp->tcp_init_cwnd = init_cwnd;
10495 			break;
10496 		}
10497 		case TCP_KEEPALIVE_THRESHOLD:
10498 			if (checkonly)
10499 				break;
10500 
10501 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10502 			    *i1 > tcps->tcps_keepalive_interval_high) {
10503 				*outlenp = 0;
10504 				return (EINVAL);
10505 			}
10506 			if (*i1 != tcp->tcp_ka_interval) {
10507 				tcp->tcp_ka_interval = *i1;
10508 				/*
10509 				 * Check if we need to restart the
10510 				 * keepalive timer.
10511 				 */
10512 				if (tcp->tcp_ka_tid != 0) {
10513 					ASSERT(tcp->tcp_ka_enabled);
10514 					(void) TCP_TIMER_CANCEL(tcp,
10515 					    tcp->tcp_ka_tid);
10516 					tcp->tcp_ka_last_intrvl = 0;
10517 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10518 					    tcp_keepalive_killer,
10519 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10520 				}
10521 			}
10522 			break;
10523 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10524 			if (!checkonly) {
10525 				if (*i1 <
10526 				    tcps->tcps_keepalive_abort_interval_low ||
10527 				    *i1 >
10528 				    tcps->tcps_keepalive_abort_interval_high) {
10529 					*outlenp = 0;
10530 					return (EINVAL);
10531 				}
10532 				tcp->tcp_ka_abort_thres = *i1;
10533 			}
10534 			break;
10535 		case TCP_CORK:
10536 			if (!checkonly) {
10537 				/*
10538 				 * if tcp->tcp_cork was set and is now
10539 				 * being unset, we have to make sure that
10540 				 * the remaining data gets sent out. Also
10541 				 * unset tcp->tcp_cork so that tcp_wput_data()
10542 				 * can send data even if it is less than mss
10543 				 */
10544 				if (tcp->tcp_cork && onoff == 0 &&
10545 				    tcp->tcp_unsent > 0) {
10546 					tcp->tcp_cork = B_FALSE;
10547 					tcp_wput_data(tcp, NULL, B_FALSE);
10548 				}
10549 				tcp->tcp_cork = onoff;
10550 			}
10551 			break;
10552 		default:
10553 			*outlenp = 0;
10554 			return (EINVAL);
10555 		}
10556 		break;
10557 	case IPPROTO_IP:
10558 		if (tcp->tcp_family != AF_INET) {
10559 			*outlenp = 0;
10560 			return (ENOPROTOOPT);
10561 		}
10562 		switch (name) {
10563 		case IP_OPTIONS:
10564 		case T_IP_OPTIONS:
10565 			reterr = tcp_opt_set_header(tcp, checkonly,
10566 			    invalp, inlen);
10567 			if (reterr) {
10568 				*outlenp = 0;
10569 				return (reterr);
10570 			}
10571 			/* OK return - copy input buffer into output buffer */
10572 			if (invalp != outvalp) {
10573 				/* don't trust bcopy for identical src/dst */
10574 				bcopy(invalp, outvalp, inlen);
10575 			}
10576 			*outlenp = inlen;
10577 			return (0);
10578 		case IP_TOS:
10579 		case T_IP_TOS:
10580 			if (!checkonly) {
10581 				tcp->tcp_ipha->ipha_type_of_service =
10582 				    (uchar_t)*i1;
10583 				tcp->tcp_tos = (uchar_t)*i1;
10584 			}
10585 			break;
10586 		case IP_TTL:
10587 			if (!checkonly) {
10588 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10589 				tcp->tcp_ttl = (uchar_t)*i1;
10590 			}
10591 			break;
10592 		case IP_BOUND_IF:
10593 		case IP_NEXTHOP:
10594 			/* Handled at the IP level */
10595 			return (-EINVAL);
10596 		case IP_SEC_OPT:
10597 			/*
10598 			 * We should not allow policy setting after
10599 			 * we start listening for connections.
10600 			 */
10601 			if (tcp->tcp_state == TCPS_LISTEN) {
10602 				return (EINVAL);
10603 			} else {
10604 				/* Handled at the IP level */
10605 				return (-EINVAL);
10606 			}
10607 		default:
10608 			*outlenp = 0;
10609 			return (EINVAL);
10610 		}
10611 		break;
10612 	case IPPROTO_IPV6: {
10613 		ip6_pkt_t		*ipp;
10614 
10615 		/*
10616 		 * IPPROTO_IPV6 options are only supported for sockets
10617 		 * that are using IPv6 on the wire.
10618 		 */
10619 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10620 			*outlenp = 0;
10621 			return (ENOPROTOOPT);
10622 		}
10623 		/*
10624 		 * Only sticky options; no ancillary data
10625 		 */
10626 		ASSERT(thisdg_attrs == NULL);
10627 		ipp = &tcp->tcp_sticky_ipp;
10628 
10629 		switch (name) {
10630 		case IPV6_UNICAST_HOPS:
10631 			/* -1 means use default */
10632 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10633 				*outlenp = 0;
10634 				return (EINVAL);
10635 			}
10636 			if (!checkonly) {
10637 				if (*i1 == -1) {
10638 					tcp->tcp_ip6h->ip6_hops =
10639 					    ipp->ipp_unicast_hops =
10640 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10641 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10642 					/* Pass modified value to IP. */
10643 					*i1 = tcp->tcp_ip6h->ip6_hops;
10644 				} else {
10645 					tcp->tcp_ip6h->ip6_hops =
10646 					    ipp->ipp_unicast_hops =
10647 					    (uint8_t)*i1;
10648 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10649 				}
10650 				reterr = tcp_build_hdrs(q, tcp);
10651 				if (reterr != 0)
10652 					return (reterr);
10653 			}
10654 			break;
10655 		case IPV6_BOUND_IF:
10656 			if (!checkonly) {
10657 				int error = 0;
10658 
10659 				tcp->tcp_bound_if = *i1;
10660 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10661 				    B_TRUE, checkonly, level, name, mblk);
10662 				if (error != 0) {
10663 					*outlenp = 0;
10664 					return (error);
10665 				}
10666 			}
10667 			break;
10668 		/*
10669 		 * Set boolean switches for ancillary data delivery
10670 		 */
10671 		case IPV6_RECVPKTINFO:
10672 			if (!checkonly) {
10673 				if (onoff)
10674 					tcp->tcp_ipv6_recvancillary |=
10675 					    TCP_IPV6_RECVPKTINFO;
10676 				else
10677 					tcp->tcp_ipv6_recvancillary &=
10678 					    ~TCP_IPV6_RECVPKTINFO;
10679 				/* Force it to be sent up with the next msg */
10680 				tcp->tcp_recvifindex = 0;
10681 			}
10682 			break;
10683 		case IPV6_RECVTCLASS:
10684 			if (!checkonly) {
10685 				if (onoff)
10686 					tcp->tcp_ipv6_recvancillary |=
10687 					    TCP_IPV6_RECVTCLASS;
10688 				else
10689 					tcp->tcp_ipv6_recvancillary &=
10690 					    ~TCP_IPV6_RECVTCLASS;
10691 			}
10692 			break;
10693 		case IPV6_RECVHOPLIMIT:
10694 			if (!checkonly) {
10695 				if (onoff)
10696 					tcp->tcp_ipv6_recvancillary |=
10697 					    TCP_IPV6_RECVHOPLIMIT;
10698 				else
10699 					tcp->tcp_ipv6_recvancillary &=
10700 					    ~TCP_IPV6_RECVHOPLIMIT;
10701 				/* Force it to be sent up with the next msg */
10702 				tcp->tcp_recvhops = 0xffffffffU;
10703 			}
10704 			break;
10705 		case IPV6_RECVHOPOPTS:
10706 			if (!checkonly) {
10707 				if (onoff)
10708 					tcp->tcp_ipv6_recvancillary |=
10709 					    TCP_IPV6_RECVHOPOPTS;
10710 				else
10711 					tcp->tcp_ipv6_recvancillary &=
10712 					    ~TCP_IPV6_RECVHOPOPTS;
10713 			}
10714 			break;
10715 		case IPV6_RECVDSTOPTS:
10716 			if (!checkonly) {
10717 				if (onoff)
10718 					tcp->tcp_ipv6_recvancillary |=
10719 					    TCP_IPV6_RECVDSTOPTS;
10720 				else
10721 					tcp->tcp_ipv6_recvancillary &=
10722 					    ~TCP_IPV6_RECVDSTOPTS;
10723 			}
10724 			break;
10725 		case _OLD_IPV6_RECVDSTOPTS:
10726 			if (!checkonly) {
10727 				if (onoff)
10728 					tcp->tcp_ipv6_recvancillary |=
10729 					    TCP_OLD_IPV6_RECVDSTOPTS;
10730 				else
10731 					tcp->tcp_ipv6_recvancillary &=
10732 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10733 			}
10734 			break;
10735 		case IPV6_RECVRTHDR:
10736 			if (!checkonly) {
10737 				if (onoff)
10738 					tcp->tcp_ipv6_recvancillary |=
10739 					    TCP_IPV6_RECVRTHDR;
10740 				else
10741 					tcp->tcp_ipv6_recvancillary &=
10742 					    ~TCP_IPV6_RECVRTHDR;
10743 			}
10744 			break;
10745 		case IPV6_RECVRTHDRDSTOPTS:
10746 			if (!checkonly) {
10747 				if (onoff)
10748 					tcp->tcp_ipv6_recvancillary |=
10749 					    TCP_IPV6_RECVRTDSTOPTS;
10750 				else
10751 					tcp->tcp_ipv6_recvancillary &=
10752 					    ~TCP_IPV6_RECVRTDSTOPTS;
10753 			}
10754 			break;
10755 		case IPV6_PKTINFO:
10756 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10757 				return (EINVAL);
10758 			if (checkonly)
10759 				break;
10760 
10761 			if (inlen == 0) {
10762 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10763 			} else {
10764 				struct in6_pktinfo *pkti;
10765 
10766 				pkti = (struct in6_pktinfo *)invalp;
10767 				/*
10768 				 * RFC 3542 states that ipi6_addr must be
10769 				 * the unspecified address when setting the
10770 				 * IPV6_PKTINFO sticky socket option on a
10771 				 * TCP socket.
10772 				 */
10773 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10774 					return (EINVAL);
10775 				/*
10776 				 * ip6_set_pktinfo() validates the source
10777 				 * address and interface index.
10778 				 */
10779 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10780 				    pkti, mblk);
10781 				if (reterr != 0)
10782 					return (reterr);
10783 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10784 				ipp->ipp_addr = pkti->ipi6_addr;
10785 				if (ipp->ipp_ifindex != 0)
10786 					ipp->ipp_fields |= IPPF_IFINDEX;
10787 				else
10788 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10789 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10790 					ipp->ipp_fields |= IPPF_ADDR;
10791 				else
10792 					ipp->ipp_fields &= ~IPPF_ADDR;
10793 			}
10794 			reterr = tcp_build_hdrs(q, tcp);
10795 			if (reterr != 0)
10796 				return (reterr);
10797 			break;
10798 		case IPV6_TCLASS:
10799 			if (inlen != 0 && inlen != sizeof (int))
10800 				return (EINVAL);
10801 			if (checkonly)
10802 				break;
10803 
10804 			if (inlen == 0) {
10805 				ipp->ipp_fields &= ~IPPF_TCLASS;
10806 			} else {
10807 				if (*i1 > 255 || *i1 < -1)
10808 					return (EINVAL);
10809 				if (*i1 == -1) {
10810 					ipp->ipp_tclass = 0;
10811 					*i1 = 0;
10812 				} else {
10813 					ipp->ipp_tclass = *i1;
10814 				}
10815 				ipp->ipp_fields |= IPPF_TCLASS;
10816 			}
10817 			reterr = tcp_build_hdrs(q, tcp);
10818 			if (reterr != 0)
10819 				return (reterr);
10820 			break;
10821 		case IPV6_NEXTHOP:
10822 			/*
10823 			 * IP will verify that the nexthop is reachable
10824 			 * and fail for sticky options.
10825 			 */
10826 			if (inlen != 0 && inlen != sizeof (sin6_t))
10827 				return (EINVAL);
10828 			if (checkonly)
10829 				break;
10830 
10831 			if (inlen == 0) {
10832 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10833 			} else {
10834 				sin6_t *sin6 = (sin6_t *)invalp;
10835 
10836 				if (sin6->sin6_family != AF_INET6)
10837 					return (EAFNOSUPPORT);
10838 				if (IN6_IS_ADDR_V4MAPPED(
10839 				    &sin6->sin6_addr))
10840 					return (EADDRNOTAVAIL);
10841 				ipp->ipp_nexthop = sin6->sin6_addr;
10842 				if (!IN6_IS_ADDR_UNSPECIFIED(
10843 				    &ipp->ipp_nexthop))
10844 					ipp->ipp_fields |= IPPF_NEXTHOP;
10845 				else
10846 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10847 			}
10848 			reterr = tcp_build_hdrs(q, tcp);
10849 			if (reterr != 0)
10850 				return (reterr);
10851 			break;
10852 		case IPV6_HOPOPTS: {
10853 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10854 
10855 			/*
10856 			 * Sanity checks - minimum size, size a multiple of
10857 			 * eight bytes, and matching size passed in.
10858 			 */
10859 			if (inlen != 0 &&
10860 			    inlen != (8 * (hopts->ip6h_len + 1)))
10861 				return (EINVAL);
10862 
10863 			if (checkonly)
10864 				break;
10865 
10866 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10867 			    (uchar_t **)&ipp->ipp_hopopts,
10868 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10869 			if (reterr != 0)
10870 				return (reterr);
10871 			if (ipp->ipp_hopoptslen == 0)
10872 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10873 			else
10874 				ipp->ipp_fields |= IPPF_HOPOPTS;
10875 			reterr = tcp_build_hdrs(q, tcp);
10876 			if (reterr != 0)
10877 				return (reterr);
10878 			break;
10879 		}
10880 		case IPV6_RTHDRDSTOPTS: {
10881 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10882 
10883 			/*
10884 			 * Sanity checks - minimum size, size a multiple of
10885 			 * eight bytes, and matching size passed in.
10886 			 */
10887 			if (inlen != 0 &&
10888 			    inlen != (8 * (dopts->ip6d_len + 1)))
10889 				return (EINVAL);
10890 
10891 			if (checkonly)
10892 				break;
10893 
10894 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10895 			    (uchar_t **)&ipp->ipp_rtdstopts,
10896 			    &ipp->ipp_rtdstoptslen, 0);
10897 			if (reterr != 0)
10898 				return (reterr);
10899 			if (ipp->ipp_rtdstoptslen == 0)
10900 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10901 			else
10902 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10903 			reterr = tcp_build_hdrs(q, tcp);
10904 			if (reterr != 0)
10905 				return (reterr);
10906 			break;
10907 		}
10908 		case IPV6_DSTOPTS: {
10909 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10910 
10911 			/*
10912 			 * Sanity checks - minimum size, size a multiple of
10913 			 * eight bytes, and matching size passed in.
10914 			 */
10915 			if (inlen != 0 &&
10916 			    inlen != (8 * (dopts->ip6d_len + 1)))
10917 				return (EINVAL);
10918 
10919 			if (checkonly)
10920 				break;
10921 
10922 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10923 			    (uchar_t **)&ipp->ipp_dstopts,
10924 			    &ipp->ipp_dstoptslen, 0);
10925 			if (reterr != 0)
10926 				return (reterr);
10927 			if (ipp->ipp_dstoptslen == 0)
10928 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10929 			else
10930 				ipp->ipp_fields |= IPPF_DSTOPTS;
10931 			reterr = tcp_build_hdrs(q, tcp);
10932 			if (reterr != 0)
10933 				return (reterr);
10934 			break;
10935 		}
10936 		case IPV6_RTHDR: {
10937 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10938 
10939 			/*
10940 			 * Sanity checks - minimum size, size a multiple of
10941 			 * eight bytes, and matching size passed in.
10942 			 */
10943 			if (inlen != 0 &&
10944 			    inlen != (8 * (rt->ip6r_len + 1)))
10945 				return (EINVAL);
10946 
10947 			if (checkonly)
10948 				break;
10949 
10950 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10951 			    (uchar_t **)&ipp->ipp_rthdr,
10952 			    &ipp->ipp_rthdrlen, 0);
10953 			if (reterr != 0)
10954 				return (reterr);
10955 			if (ipp->ipp_rthdrlen == 0)
10956 				ipp->ipp_fields &= ~IPPF_RTHDR;
10957 			else
10958 				ipp->ipp_fields |= IPPF_RTHDR;
10959 			reterr = tcp_build_hdrs(q, tcp);
10960 			if (reterr != 0)
10961 				return (reterr);
10962 			break;
10963 		}
10964 		case IPV6_V6ONLY:
10965 			if (!checkonly)
10966 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10967 			break;
10968 		case IPV6_USE_MIN_MTU:
10969 			if (inlen != sizeof (int))
10970 				return (EINVAL);
10971 
10972 			if (*i1 < -1 || *i1 > 1)
10973 				return (EINVAL);
10974 
10975 			if (checkonly)
10976 				break;
10977 
10978 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10979 			ipp->ipp_use_min_mtu = *i1;
10980 			break;
10981 		case IPV6_BOUND_PIF:
10982 			/* Handled at the IP level */
10983 			return (-EINVAL);
10984 		case IPV6_SEC_OPT:
10985 			/*
10986 			 * We should not allow policy setting after
10987 			 * we start listening for connections.
10988 			 */
10989 			if (tcp->tcp_state == TCPS_LISTEN) {
10990 				return (EINVAL);
10991 			} else {
10992 				/* Handled at the IP level */
10993 				return (-EINVAL);
10994 			}
10995 		case IPV6_SRC_PREFERENCES:
10996 			if (inlen != sizeof (uint32_t))
10997 				return (EINVAL);
10998 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10999 			    *(uint32_t *)invalp);
11000 			if (reterr != 0) {
11001 				*outlenp = 0;
11002 				return (reterr);
11003 			}
11004 			break;
11005 		default:
11006 			*outlenp = 0;
11007 			return (EINVAL);
11008 		}
11009 		break;
11010 	}		/* end IPPROTO_IPV6 */
11011 	default:
11012 		*outlenp = 0;
11013 		return (EINVAL);
11014 	}
11015 	/*
11016 	 * Common case of OK return with outval same as inval
11017 	 */
11018 	if (invalp != outvalp) {
11019 		/* don't trust bcopy for identical src/dst */
11020 		(void) bcopy(invalp, outvalp, inlen);
11021 	}
11022 	*outlenp = inlen;
11023 	return (0);
11024 }
11025 
11026 /*
11027  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11028  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11029  * headers, and the maximum size tcp header (to avoid reallocation
11030  * on the fly for additional tcp options).
11031  * Returns failure if can't allocate memory.
11032  */
11033 static int
11034 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11035 {
11036 	char	*hdrs;
11037 	uint_t	hdrs_len;
11038 	ip6i_t	*ip6i;
11039 	char	buf[TCP_MAX_HDR_LENGTH];
11040 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11041 	in6_addr_t src, dst;
11042 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11043 
11044 	/*
11045 	 * save the existing tcp header and source/dest IP addresses
11046 	 */
11047 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11048 	src = tcp->tcp_ip6h->ip6_src;
11049 	dst = tcp->tcp_ip6h->ip6_dst;
11050 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11051 	ASSERT(hdrs_len != 0);
11052 	if (hdrs_len > tcp->tcp_iphc_len) {
11053 		/* Need to reallocate */
11054 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11055 		if (hdrs == NULL)
11056 			return (ENOMEM);
11057 		if (tcp->tcp_iphc != NULL) {
11058 			if (tcp->tcp_hdr_grown) {
11059 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11060 			} else {
11061 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11062 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11063 			}
11064 			tcp->tcp_iphc_len = 0;
11065 		}
11066 		ASSERT(tcp->tcp_iphc_len == 0);
11067 		tcp->tcp_iphc = hdrs;
11068 		tcp->tcp_iphc_len = hdrs_len;
11069 		tcp->tcp_hdr_grown = B_TRUE;
11070 	}
11071 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11072 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11073 
11074 	/* Set header fields not in ipp */
11075 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11076 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11077 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11078 	} else {
11079 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11080 	}
11081 	/*
11082 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11083 	 *
11084 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11085 	 */
11086 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11087 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11088 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11089 
11090 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11091 
11092 	tcp->tcp_ip6h->ip6_src = src;
11093 	tcp->tcp_ip6h->ip6_dst = dst;
11094 
11095 	/*
11096 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11097 	 * the default value for TCP.
11098 	 */
11099 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11100 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11101 
11102 	/*
11103 	 * If we're setting extension headers after a connection
11104 	 * has been established, and if we have a routing header
11105 	 * among the extension headers, call ip_massage_options_v6 to
11106 	 * manipulate the routing header/ip6_dst set the checksum
11107 	 * difference in the tcp header template.
11108 	 * (This happens in tcp_connect_ipv6 if the routing header
11109 	 * is set prior to the connect.)
11110 	 * Set the tcp_sum to zero first in case we've cleared a
11111 	 * routing header or don't have one at all.
11112 	 */
11113 	tcp->tcp_sum = 0;
11114 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11115 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11116 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11117 		    (uint8_t *)tcp->tcp_tcph);
11118 		if (rth != NULL) {
11119 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11120 			    rth, tcps->tcps_netstack);
11121 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11122 			    (tcp->tcp_sum >> 16));
11123 		}
11124 	}
11125 
11126 	/* Try to get everything in a single mblk */
11127 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11128 	return (0);
11129 }
11130 
11131 /*
11132  * Transfer any source route option from ipha to buf/dst in reversed form.
11133  */
11134 static int
11135 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11136 {
11137 	ipoptp_t	opts;
11138 	uchar_t		*opt;
11139 	uint8_t		optval;
11140 	uint8_t		optlen;
11141 	uint32_t	len = 0;
11142 
11143 	for (optval = ipoptp_first(&opts, ipha);
11144 	    optval != IPOPT_EOL;
11145 	    optval = ipoptp_next(&opts)) {
11146 		opt = opts.ipoptp_cur;
11147 		optlen = opts.ipoptp_len;
11148 		switch (optval) {
11149 			int	off1, off2;
11150 		case IPOPT_SSRR:
11151 		case IPOPT_LSRR:
11152 
11153 			/* Reverse source route */
11154 			/*
11155 			 * First entry should be the next to last one in the
11156 			 * current source route (the last entry is our
11157 			 * address.)
11158 			 * The last entry should be the final destination.
11159 			 */
11160 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11161 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11162 			off1 = IPOPT_MINOFF_SR - 1;
11163 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11164 			if (off2 < 0) {
11165 				/* No entries in source route */
11166 				break;
11167 			}
11168 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11169 			/*
11170 			 * Note: use src since ipha has not had its src
11171 			 * and dst reversed (it is in the state it was
11172 			 * received.
11173 			 */
11174 			bcopy(&ipha->ipha_src, buf + off2,
11175 			    IP_ADDR_LEN);
11176 			off2 -= IP_ADDR_LEN;
11177 
11178 			while (off2 > 0) {
11179 				bcopy(opt + off2, buf + off1,
11180 				    IP_ADDR_LEN);
11181 				off1 += IP_ADDR_LEN;
11182 				off2 -= IP_ADDR_LEN;
11183 			}
11184 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11185 			buf += optlen;
11186 			len += optlen;
11187 			break;
11188 		}
11189 	}
11190 done:
11191 	/* Pad the resulting options */
11192 	while (len & 0x3) {
11193 		*buf++ = IPOPT_EOL;
11194 		len++;
11195 	}
11196 	return (len);
11197 }
11198 
11199 
11200 /*
11201  * Extract and revert a source route from ipha (if any)
11202  * and then update the relevant fields in both tcp_t and the standard header.
11203  */
11204 static void
11205 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11206 {
11207 	char	buf[TCP_MAX_HDR_LENGTH];
11208 	uint_t	tcph_len;
11209 	int	len;
11210 
11211 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11212 	len = IPH_HDR_LENGTH(ipha);
11213 	if (len == IP_SIMPLE_HDR_LENGTH)
11214 		/* Nothing to do */
11215 		return;
11216 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11217 	    (len & 0x3))
11218 		return;
11219 
11220 	tcph_len = tcp->tcp_tcp_hdr_len;
11221 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11222 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11223 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11224 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11225 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11226 	len += IP_SIMPLE_HDR_LENGTH;
11227 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11228 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11229 	if ((int)tcp->tcp_sum < 0)
11230 		tcp->tcp_sum--;
11231 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11232 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11233 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11234 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11235 	tcp->tcp_ip_hdr_len = len;
11236 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11237 	    (IP_VERSION << 4) | (len >> 2);
11238 	len += tcph_len;
11239 	tcp->tcp_hdr_len = len;
11240 }
11241 
11242 /*
11243  * Copy the standard header into its new location,
11244  * lay in the new options and then update the relevant
11245  * fields in both tcp_t and the standard header.
11246  */
11247 static int
11248 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11249 {
11250 	uint_t	tcph_len;
11251 	uint8_t	*ip_optp;
11252 	tcph_t	*new_tcph;
11253 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11254 
11255 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11256 		return (EINVAL);
11257 
11258 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11259 		return (EINVAL);
11260 
11261 	if (checkonly) {
11262 		/*
11263 		 * do not really set, just pretend to - T_CHECK
11264 		 */
11265 		return (0);
11266 	}
11267 
11268 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11269 	if (tcp->tcp_label_len > 0) {
11270 		int padlen;
11271 		uint8_t opt;
11272 
11273 		/* convert list termination to no-ops */
11274 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11275 		ip_optp += ip_optp[IPOPT_OLEN];
11276 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11277 		while (--padlen >= 0)
11278 			*ip_optp++ = opt;
11279 	}
11280 	tcph_len = tcp->tcp_tcp_hdr_len;
11281 	new_tcph = (tcph_t *)(ip_optp + len);
11282 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11283 	tcp->tcp_tcph = new_tcph;
11284 	bcopy(ptr, ip_optp, len);
11285 
11286 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11287 
11288 	tcp->tcp_ip_hdr_len = len;
11289 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11290 	    (IP_VERSION << 4) | (len >> 2);
11291 	tcp->tcp_hdr_len = len + tcph_len;
11292 	if (!TCP_IS_DETACHED(tcp)) {
11293 		/* Always allocate room for all options. */
11294 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11295 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11296 	}
11297 	return (0);
11298 }
11299 
11300 /* Get callback routine passed to nd_load by tcp_param_register */
11301 /* ARGSUSED */
11302 static int
11303 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11304 {
11305 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11306 
11307 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11308 	return (0);
11309 }
11310 
11311 /*
11312  * Walk through the param array specified registering each element with the
11313  * named dispatch handler.
11314  */
11315 static boolean_t
11316 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11317 {
11318 	for (; cnt-- > 0; tcppa++) {
11319 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11320 			if (!nd_load(ndp, tcppa->tcp_param_name,
11321 			    tcp_param_get, tcp_param_set,
11322 			    (caddr_t)tcppa)) {
11323 				nd_free(ndp);
11324 				return (B_FALSE);
11325 			}
11326 		}
11327 	}
11328 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11329 	    KM_SLEEP);
11330 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11331 	    sizeof (tcpparam_t));
11332 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11333 	    tcp_param_get, tcp_param_set_aligned,
11334 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11335 		nd_free(ndp);
11336 		return (B_FALSE);
11337 	}
11338 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11339 	    KM_SLEEP);
11340 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11341 	    sizeof (tcpparam_t));
11342 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11343 	    tcp_param_get, tcp_param_set_aligned,
11344 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11345 		nd_free(ndp);
11346 		return (B_FALSE);
11347 	}
11348 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11349 	    KM_SLEEP);
11350 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11351 	    sizeof (tcpparam_t));
11352 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11353 	    tcp_param_get, tcp_param_set_aligned,
11354 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11355 		nd_free(ndp);
11356 		return (B_FALSE);
11357 	}
11358 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11359 	    KM_SLEEP);
11360 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11361 	    sizeof (tcpparam_t));
11362 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11363 	    tcp_param_get, tcp_param_set_aligned,
11364 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11365 		nd_free(ndp);
11366 		return (B_FALSE);
11367 	}
11368 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11369 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11370 		nd_free(ndp);
11371 		return (B_FALSE);
11372 	}
11373 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11374 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11375 		nd_free(ndp);
11376 		return (B_FALSE);
11377 	}
11378 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11379 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11380 		nd_free(ndp);
11381 		return (B_FALSE);
11382 	}
11383 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11384 	    NULL)) {
11385 		nd_free(ndp);
11386 		return (B_FALSE);
11387 	}
11388 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11389 	    NULL, NULL)) {
11390 		nd_free(ndp);
11391 		return (B_FALSE);
11392 	}
11393 	if (!nd_load(ndp, "tcp_listen_hash",
11394 	    tcp_listen_hash_report, NULL, NULL)) {
11395 		nd_free(ndp);
11396 		return (B_FALSE);
11397 	}
11398 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11399 	    NULL, NULL)) {
11400 		nd_free(ndp);
11401 		return (B_FALSE);
11402 	}
11403 	if (!nd_load(ndp, "tcp_acceptor_hash",
11404 	    tcp_acceptor_hash_report, NULL, NULL)) {
11405 		nd_free(ndp);
11406 		return (B_FALSE);
11407 	}
11408 	if (!nd_load(ndp, "tcp_host_param", tcp_host_param_report,
11409 	    tcp_host_param_set, NULL)) {
11410 		nd_free(ndp);
11411 		return (B_FALSE);
11412 	}
11413 	if (!nd_load(ndp, "tcp_host_param_ipv6",
11414 	    tcp_host_param_report, tcp_host_param_set_ipv6, NULL)) {
11415 		nd_free(ndp);
11416 		return (B_FALSE);
11417 	}
11418 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11419 	    tcp_1948_phrase_set, NULL)) {
11420 		nd_free(ndp);
11421 		return (B_FALSE);
11422 	}
11423 	if (!nd_load(ndp, "tcp_reserved_port_list",
11424 	    tcp_reserved_port_list, NULL, NULL)) {
11425 		nd_free(ndp);
11426 		return (B_FALSE);
11427 	}
11428 	/*
11429 	 * Dummy ndd variables - only to convey obsolescence information
11430 	 * through printing of their name (no get or set routines)
11431 	 * XXX Remove in future releases ?
11432 	 */
11433 	if (!nd_load(ndp,
11434 	    "tcp_close_wait_interval(obsoleted - "
11435 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11436 		nd_free(ndp);
11437 		return (B_FALSE);
11438 	}
11439 	return (B_TRUE);
11440 }
11441 
11442 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11443 /* ARGSUSED */
11444 static int
11445 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11446     cred_t *cr)
11447 {
11448 	long new_value;
11449 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11450 
11451 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11452 	    new_value < tcppa->tcp_param_min ||
11453 	    new_value > tcppa->tcp_param_max) {
11454 		return (EINVAL);
11455 	}
11456 	/*
11457 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11458 	 * round it up.  For future 64 bit requirement, we actually make it
11459 	 * a multiple of 8.
11460 	 */
11461 	if (new_value & 0x7) {
11462 		new_value = (new_value & ~0x7) + 0x8;
11463 	}
11464 	tcppa->tcp_param_val = new_value;
11465 	return (0);
11466 }
11467 
11468 /* Set callback routine passed to nd_load by tcp_param_register */
11469 /* ARGSUSED */
11470 static int
11471 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11472 {
11473 	long	new_value;
11474 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11475 
11476 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11477 	    new_value < tcppa->tcp_param_min ||
11478 	    new_value > tcppa->tcp_param_max) {
11479 		return (EINVAL);
11480 	}
11481 	tcppa->tcp_param_val = new_value;
11482 	return (0);
11483 }
11484 
11485 /*
11486  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11487  * is filled, return as much as we can.  The message passed in may be
11488  * multi-part, chained using b_cont.  "start" is the starting sequence
11489  * number for this piece.
11490  */
11491 static mblk_t *
11492 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11493 {
11494 	uint32_t	end;
11495 	mblk_t		*mp1;
11496 	mblk_t		*mp2;
11497 	mblk_t		*next_mp;
11498 	uint32_t	u1;
11499 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11500 
11501 	/* Walk through all the new pieces. */
11502 	do {
11503 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11504 		    (uintptr_t)INT_MAX);
11505 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11506 		next_mp = mp->b_cont;
11507 		if (start == end) {
11508 			/* Empty.  Blast it. */
11509 			freeb(mp);
11510 			continue;
11511 		}
11512 		mp->b_cont = NULL;
11513 		TCP_REASS_SET_SEQ(mp, start);
11514 		TCP_REASS_SET_END(mp, end);
11515 		mp1 = tcp->tcp_reass_tail;
11516 		if (!mp1) {
11517 			tcp->tcp_reass_tail = mp;
11518 			tcp->tcp_reass_head = mp;
11519 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11520 			UPDATE_MIB(&tcps->tcps_mib,
11521 			    tcpInDataUnorderBytes, end - start);
11522 			continue;
11523 		}
11524 		/* New stuff completely beyond tail? */
11525 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11526 			/* Link it on end. */
11527 			mp1->b_cont = mp;
11528 			tcp->tcp_reass_tail = mp;
11529 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11530 			UPDATE_MIB(&tcps->tcps_mib,
11531 			    tcpInDataUnorderBytes, end - start);
11532 			continue;
11533 		}
11534 		mp1 = tcp->tcp_reass_head;
11535 		u1 = TCP_REASS_SEQ(mp1);
11536 		/* New stuff at the front? */
11537 		if (SEQ_LT(start, u1)) {
11538 			/* Yes... Check for overlap. */
11539 			mp->b_cont = mp1;
11540 			tcp->tcp_reass_head = mp;
11541 			tcp_reass_elim_overlap(tcp, mp);
11542 			continue;
11543 		}
11544 		/*
11545 		 * The new piece fits somewhere between the head and tail.
11546 		 * We find our slot, where mp1 precedes us and mp2 trails.
11547 		 */
11548 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11549 			u1 = TCP_REASS_SEQ(mp2);
11550 			if (SEQ_LEQ(start, u1))
11551 				break;
11552 		}
11553 		/* Link ourselves in */
11554 		mp->b_cont = mp2;
11555 		mp1->b_cont = mp;
11556 
11557 		/* Trim overlap with following mblk(s) first */
11558 		tcp_reass_elim_overlap(tcp, mp);
11559 
11560 		/* Trim overlap with preceding mblk */
11561 		tcp_reass_elim_overlap(tcp, mp1);
11562 
11563 	} while (start = end, mp = next_mp);
11564 	mp1 = tcp->tcp_reass_head;
11565 	/* Anything ready to go? */
11566 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11567 		return (NULL);
11568 	/* Eat what we can off the queue */
11569 	for (;;) {
11570 		mp = mp1->b_cont;
11571 		end = TCP_REASS_END(mp1);
11572 		TCP_REASS_SET_SEQ(mp1, 0);
11573 		TCP_REASS_SET_END(mp1, 0);
11574 		if (!mp) {
11575 			tcp->tcp_reass_tail = NULL;
11576 			break;
11577 		}
11578 		if (end != TCP_REASS_SEQ(mp)) {
11579 			mp1->b_cont = NULL;
11580 			break;
11581 		}
11582 		mp1 = mp;
11583 	}
11584 	mp1 = tcp->tcp_reass_head;
11585 	tcp->tcp_reass_head = mp;
11586 	return (mp1);
11587 }
11588 
11589 /* Eliminate any overlap that mp may have over later mblks */
11590 static void
11591 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11592 {
11593 	uint32_t	end;
11594 	mblk_t		*mp1;
11595 	uint32_t	u1;
11596 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11597 
11598 	end = TCP_REASS_END(mp);
11599 	while ((mp1 = mp->b_cont) != NULL) {
11600 		u1 = TCP_REASS_SEQ(mp1);
11601 		if (!SEQ_GT(end, u1))
11602 			break;
11603 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11604 			mp->b_wptr -= end - u1;
11605 			TCP_REASS_SET_END(mp, u1);
11606 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11607 			UPDATE_MIB(&tcps->tcps_mib,
11608 			    tcpInDataPartDupBytes, end - u1);
11609 			break;
11610 		}
11611 		mp->b_cont = mp1->b_cont;
11612 		TCP_REASS_SET_SEQ(mp1, 0);
11613 		TCP_REASS_SET_END(mp1, 0);
11614 		freeb(mp1);
11615 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11616 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11617 	}
11618 	if (!mp1)
11619 		tcp->tcp_reass_tail = mp;
11620 }
11621 
11622 /*
11623  * Send up all messages queued on tcp_rcv_list.
11624  */
11625 static uint_t
11626 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11627 {
11628 	mblk_t *mp;
11629 	uint_t ret = 0;
11630 	uint_t thwin;
11631 #ifdef DEBUG
11632 	uint_t cnt = 0;
11633 #endif
11634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11635 
11636 	/* Can't drain on an eager connection */
11637 	if (tcp->tcp_listener != NULL)
11638 		return (ret);
11639 
11640 	/*
11641 	 * Handle two cases here: we are currently fused or we were
11642 	 * previously fused and have some urgent data to be delivered
11643 	 * upstream.  The latter happens because we either ran out of
11644 	 * memory or were detached and therefore sending the SIGURG was
11645 	 * deferred until this point.  In either case we pass control
11646 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11647 	 * some work.
11648 	 */
11649 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11650 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11651 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11652 		    &tcp->tcp_fused_sigurg_mp))
11653 			return (ret);
11654 	}
11655 
11656 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11657 		tcp->tcp_rcv_list = mp->b_next;
11658 		mp->b_next = NULL;
11659 #ifdef DEBUG
11660 		cnt += msgdsize(mp);
11661 #endif
11662 		/* Does this need SSL processing first? */
11663 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11664 			tcp_kssl_input(tcp, mp);
11665 			continue;
11666 		}
11667 		putnext(q, mp);
11668 	}
11669 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11670 	tcp->tcp_rcv_last_head = NULL;
11671 	tcp->tcp_rcv_last_tail = NULL;
11672 	tcp->tcp_rcv_cnt = 0;
11673 
11674 	/* Learn the latest rwnd information that we sent to the other side. */
11675 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11676 	    << tcp->tcp_rcv_ws;
11677 	/* This is peer's calculated send window (our receive window). */
11678 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11679 	/*
11680 	 * Increase the receive window to max.  But we need to do receiver
11681 	 * SWS avoidance.  This means that we need to check the increase of
11682 	 * of receive window is at least 1 MSS.
11683 	 */
11684 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11685 		/*
11686 		 * If the window that the other side knows is less than max
11687 		 * deferred acks segments, send an update immediately.
11688 		 */
11689 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11690 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11691 			ret = TH_ACK_NEEDED;
11692 		}
11693 		tcp->tcp_rwnd = q->q_hiwat;
11694 	}
11695 	/* No need for the push timer now. */
11696 	if (tcp->tcp_push_tid != 0) {
11697 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11698 		tcp->tcp_push_tid = 0;
11699 	}
11700 	return (ret);
11701 }
11702 
11703 /*
11704  * Queue data on tcp_rcv_list which is a b_next chain.
11705  * tcp_rcv_last_head/tail is the last element of this chain.
11706  * Each element of the chain is a b_cont chain.
11707  *
11708  * M_DATA messages are added to the current element.
11709  * Other messages are added as new (b_next) elements.
11710  */
11711 void
11712 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11713 {
11714 	ASSERT(seg_len == msgdsize(mp));
11715 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11716 
11717 	if (tcp->tcp_rcv_list == NULL) {
11718 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11719 		tcp->tcp_rcv_list = mp;
11720 		tcp->tcp_rcv_last_head = mp;
11721 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11722 		tcp->tcp_rcv_last_tail->b_cont = mp;
11723 	} else {
11724 		tcp->tcp_rcv_last_head->b_next = mp;
11725 		tcp->tcp_rcv_last_head = mp;
11726 	}
11727 
11728 	while (mp->b_cont)
11729 		mp = mp->b_cont;
11730 
11731 	tcp->tcp_rcv_last_tail = mp;
11732 	tcp->tcp_rcv_cnt += seg_len;
11733 	tcp->tcp_rwnd -= seg_len;
11734 }
11735 
11736 /*
11737  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11738  *
11739  * This is the default entry function into TCP on the read side. TCP is
11740  * always entered via squeue i.e. using squeue's for mutual exclusion.
11741  * When classifier does a lookup to find the tcp, it also puts a reference
11742  * on the conn structure associated so the tcp is guaranteed to exist
11743  * when we come here. We still need to check the state because it might
11744  * as well has been closed. The squeue processing function i.e. squeue_enter,
11745  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11746  * CONN_DEC_REF.
11747  *
11748  * Apart from the default entry point, IP also sends packets directly to
11749  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11750  * connections.
11751  */
11752 void
11753 tcp_input(void *arg, mblk_t *mp, void *arg2)
11754 {
11755 	conn_t	*connp = (conn_t *)arg;
11756 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11757 
11758 	/* arg2 is the sqp */
11759 	ASSERT(arg2 != NULL);
11760 	ASSERT(mp != NULL);
11761 
11762 	/*
11763 	 * Don't accept any input on a closed tcp as this TCP logically does
11764 	 * not exist on the system. Don't proceed further with this TCP.
11765 	 * For eg. this packet could trigger another close of this tcp
11766 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11767 	 * tcp_clean_death / tcp_closei_local must be called at most once
11768 	 * on a TCP. In this case we need to refeed the packet into the
11769 	 * classifier and figure out where the packet should go. Need to
11770 	 * preserve the recv_ill somehow. Until we figure that out, for
11771 	 * now just drop the packet if we can't classify the packet.
11772 	 */
11773 	if (tcp->tcp_state == TCPS_CLOSED ||
11774 	    tcp->tcp_state == TCPS_BOUND) {
11775 		conn_t	*new_connp;
11776 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11777 
11778 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11779 		if (new_connp != NULL) {
11780 			tcp_reinput(new_connp, mp, arg2);
11781 			return;
11782 		}
11783 		/* We failed to classify. For now just drop the packet */
11784 		freemsg(mp);
11785 		return;
11786 	}
11787 
11788 	if (DB_TYPE(mp) == M_DATA)
11789 		tcp_rput_data(connp, mp, arg2);
11790 	else
11791 		tcp_rput_common(tcp, mp);
11792 }
11793 
11794 /*
11795  * The read side put procedure.
11796  * The packets passed up by ip are assume to be aligned according to
11797  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11798  */
11799 static void
11800 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11801 {
11802 	/*
11803 	 * tcp_rput_data() does not expect M_CTL except for the case
11804 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11805 	 * type. Need to make sure that any other M_CTLs don't make
11806 	 * it to tcp_rput_data since it is not expecting any and doesn't
11807 	 * check for it.
11808 	 */
11809 	if (DB_TYPE(mp) == M_CTL) {
11810 		switch (*(uint32_t *)(mp->b_rptr)) {
11811 		case TCP_IOC_ABORT_CONN:
11812 			/*
11813 			 * Handle connection abort request.
11814 			 */
11815 			tcp_ioctl_abort_handler(tcp, mp);
11816 			return;
11817 		case IPSEC_IN:
11818 			/*
11819 			 * Only secure icmp arrive in TCP and they
11820 			 * don't go through data path.
11821 			 */
11822 			tcp_icmp_error(tcp, mp);
11823 			return;
11824 		case IN_PKTINFO:
11825 			/*
11826 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11827 			 * sockets that are receiving IPv4 traffic. tcp
11828 			 */
11829 			ASSERT(tcp->tcp_family == AF_INET6);
11830 			ASSERT(tcp->tcp_ipv6_recvancillary &
11831 			    TCP_IPV6_RECVPKTINFO);
11832 			tcp_rput_data(tcp->tcp_connp, mp,
11833 			    tcp->tcp_connp->conn_sqp);
11834 			return;
11835 		case MDT_IOC_INFO_UPDATE:
11836 			/*
11837 			 * Handle Multidata information update; the
11838 			 * following routine will free the message.
11839 			 */
11840 			if (tcp->tcp_connp->conn_mdt_ok) {
11841 				tcp_mdt_update(tcp,
11842 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11843 				    B_FALSE);
11844 			}
11845 			freemsg(mp);
11846 			return;
11847 		case LSO_IOC_INFO_UPDATE:
11848 			/*
11849 			 * Handle LSO information update; the following
11850 			 * routine will free the message.
11851 			 */
11852 			if (tcp->tcp_connp->conn_lso_ok) {
11853 				tcp_lso_update(tcp,
11854 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11855 			}
11856 			freemsg(mp);
11857 			return;
11858 		default:
11859 			/*
11860 			 * tcp_icmp_err() will process the M_CTL packets.
11861 			 * Non-ICMP packets, if any, will be discarded in
11862 			 * tcp_icmp_err(). We will process the ICMP packet
11863 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11864 			 * incoming ICMP packet may result in changing
11865 			 * the tcp_mss, which we would need if we have
11866 			 * packets to retransmit.
11867 			 */
11868 			tcp_icmp_error(tcp, mp);
11869 			return;
11870 		}
11871 	}
11872 
11873 	/* No point processing the message if tcp is already closed */
11874 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11875 		freemsg(mp);
11876 		return;
11877 	}
11878 
11879 	tcp_rput_other(tcp, mp);
11880 }
11881 
11882 
11883 /* The minimum of smoothed mean deviation in RTO calculation. */
11884 #define	TCP_SD_MIN	400
11885 
11886 /*
11887  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11888  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11889  * are the same as those in Appendix A.2 of that paper.
11890  *
11891  * m = new measurement
11892  * sa = smoothed RTT average (8 * average estimates).
11893  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11894  */
11895 static void
11896 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11897 {
11898 	long m = TICK_TO_MSEC(rtt);
11899 	clock_t sa = tcp->tcp_rtt_sa;
11900 	clock_t sv = tcp->tcp_rtt_sd;
11901 	clock_t rto;
11902 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11903 
11904 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11905 	tcp->tcp_rtt_update++;
11906 
11907 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11908 	if (sa != 0) {
11909 		/*
11910 		 * Update average estimator:
11911 		 *	new rtt = 7/8 old rtt + 1/8 Error
11912 		 */
11913 
11914 		/* m is now Error in estimate. */
11915 		m -= sa >> 3;
11916 		if ((sa += m) <= 0) {
11917 			/*
11918 			 * Don't allow the smoothed average to be negative.
11919 			 * We use 0 to denote reinitialization of the
11920 			 * variables.
11921 			 */
11922 			sa = 1;
11923 		}
11924 
11925 		/*
11926 		 * Update deviation estimator:
11927 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11928 		 */
11929 		if (m < 0)
11930 			m = -m;
11931 		m -= sv >> 2;
11932 		sv += m;
11933 	} else {
11934 		/*
11935 		 * This follows BSD's implementation.  So the reinitialized
11936 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11937 		 * link is bandwidth dominated, doubling the window size
11938 		 * during slow start means doubling the RTT.  We want to be
11939 		 * more conservative when we reinitialize our estimates.  3
11940 		 * is just a convenient number.
11941 		 */
11942 		sa = m << 3;
11943 		sv = m << 1;
11944 	}
11945 	if (sv < TCP_SD_MIN) {
11946 		/*
11947 		 * We do not know that if sa captures the delay ACK
11948 		 * effect as in a long train of segments, a receiver
11949 		 * does not delay its ACKs.  So set the minimum of sv
11950 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11951 		 * of BSD DATO.  That means the minimum of mean
11952 		 * deviation is 100 ms.
11953 		 *
11954 		 */
11955 		sv = TCP_SD_MIN;
11956 	}
11957 	tcp->tcp_rtt_sa = sa;
11958 	tcp->tcp_rtt_sd = sv;
11959 	/*
11960 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11961 	 *
11962 	 * Add tcp_rexmit_interval extra in case of extreme environment
11963 	 * where the algorithm fails to work.  The default value of
11964 	 * tcp_rexmit_interval_extra should be 0.
11965 	 *
11966 	 * As we use a finer grained clock than BSD and update
11967 	 * RTO for every ACKs, add in another .25 of RTT to the
11968 	 * deviation of RTO to accomodate burstiness of 1/4 of
11969 	 * window size.
11970 	 */
11971 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
11972 
11973 	if (rto > tcps->tcps_rexmit_interval_max) {
11974 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
11975 	} else if (rto < tcps->tcps_rexmit_interval_min) {
11976 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
11977 	} else {
11978 		tcp->tcp_rto = rto;
11979 	}
11980 
11981 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11982 	tcp->tcp_timer_backoff = 0;
11983 }
11984 
11985 /*
11986  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11987  * send queue which starts at the given seq. no.
11988  *
11989  * Parameters:
11990  *	tcp_t *tcp: the tcp instance pointer.
11991  *	uint32_t seq: the starting seq. no of the requested segment.
11992  *	int32_t *off: after the execution, *off will be the offset to
11993  *		the returned mblk which points to the requested seq no.
11994  *		It is the caller's responsibility to send in a non-null off.
11995  *
11996  * Return:
11997  *	A mblk_t pointer pointing to the requested segment in send queue.
11998  */
11999 static mblk_t *
12000 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12001 {
12002 	int32_t	cnt;
12003 	mblk_t	*mp;
12004 
12005 	/* Defensive coding.  Make sure we don't send incorrect data. */
12006 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12007 		return (NULL);
12008 
12009 	cnt = seq - tcp->tcp_suna;
12010 	mp = tcp->tcp_xmit_head;
12011 	while (cnt > 0 && mp != NULL) {
12012 		cnt -= mp->b_wptr - mp->b_rptr;
12013 		if (cnt < 0) {
12014 			cnt += mp->b_wptr - mp->b_rptr;
12015 			break;
12016 		}
12017 		mp = mp->b_cont;
12018 	}
12019 	ASSERT(mp != NULL);
12020 	*off = cnt;
12021 	return (mp);
12022 }
12023 
12024 /*
12025  * This function handles all retransmissions if SACK is enabled for this
12026  * connection.  First it calculates how many segments can be retransmitted
12027  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12028  * segments.  A segment is eligible if sack_cnt for that segment is greater
12029  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12030  * all eligible segments, it checks to see if TCP can send some new segments
12031  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12032  *
12033  * Parameters:
12034  *	tcp_t *tcp: the tcp structure of the connection.
12035  *	uint_t *flags: in return, appropriate value will be set for
12036  *	tcp_rput_data().
12037  */
12038 static void
12039 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12040 {
12041 	notsack_blk_t	*notsack_blk;
12042 	int32_t		usable_swnd;
12043 	int32_t		mss;
12044 	uint32_t	seg_len;
12045 	mblk_t		*xmit_mp;
12046 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12047 
12048 	ASSERT(tcp->tcp_sack_info != NULL);
12049 	ASSERT(tcp->tcp_notsack_list != NULL);
12050 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12051 
12052 	/* Defensive coding in case there is a bug... */
12053 	if (tcp->tcp_notsack_list == NULL) {
12054 		return;
12055 	}
12056 	notsack_blk = tcp->tcp_notsack_list;
12057 	mss = tcp->tcp_mss;
12058 
12059 	/*
12060 	 * Limit the num of outstanding data in the network to be
12061 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12062 	 */
12063 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12064 
12065 	/* At least retransmit 1 MSS of data. */
12066 	if (usable_swnd <= 0) {
12067 		usable_swnd = mss;
12068 	}
12069 
12070 	/* Make sure no new RTT samples will be taken. */
12071 	tcp->tcp_csuna = tcp->tcp_snxt;
12072 
12073 	notsack_blk = tcp->tcp_notsack_list;
12074 	while (usable_swnd > 0) {
12075 		mblk_t		*snxt_mp, *tmp_mp;
12076 		tcp_seq		begin = tcp->tcp_sack_snxt;
12077 		tcp_seq		end;
12078 		int32_t		off;
12079 
12080 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12081 			if (SEQ_GT(notsack_blk->end, begin) &&
12082 			    (notsack_blk->sack_cnt >=
12083 			    tcps->tcps_dupack_fast_retransmit)) {
12084 				end = notsack_blk->end;
12085 				if (SEQ_LT(begin, notsack_blk->begin)) {
12086 					begin = notsack_blk->begin;
12087 				}
12088 				break;
12089 			}
12090 		}
12091 		/*
12092 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12093 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12094 		 * set to tcp_cwnd_ssthresh.
12095 		 */
12096 		if (notsack_blk == NULL) {
12097 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12098 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12099 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12100 				ASSERT(tcp->tcp_cwnd > 0);
12101 				return;
12102 			} else {
12103 				usable_swnd = usable_swnd / mss;
12104 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12105 				    MAX(usable_swnd * mss, mss);
12106 				*flags |= TH_XMIT_NEEDED;
12107 				return;
12108 			}
12109 		}
12110 
12111 		/*
12112 		 * Note that we may send more than usable_swnd allows here
12113 		 * because of round off, but no more than 1 MSS of data.
12114 		 */
12115 		seg_len = end - begin;
12116 		if (seg_len > mss)
12117 			seg_len = mss;
12118 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12119 		ASSERT(snxt_mp != NULL);
12120 		/* This should not happen.  Defensive coding again... */
12121 		if (snxt_mp == NULL) {
12122 			return;
12123 		}
12124 
12125 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12126 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12127 		if (xmit_mp == NULL)
12128 			return;
12129 
12130 		usable_swnd -= seg_len;
12131 		tcp->tcp_pipe += seg_len;
12132 		tcp->tcp_sack_snxt = begin + seg_len;
12133 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12134 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12135 
12136 		/*
12137 		 * Update the send timestamp to avoid false retransmission.
12138 		 */
12139 		snxt_mp->b_prev = (mblk_t *)lbolt;
12140 
12141 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12142 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12143 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12144 		/*
12145 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12146 		 * This happens when new data sent during fast recovery is
12147 		 * also lost.  If TCP retransmits those new data, it needs
12148 		 * to extend SACK recover phase to avoid starting another
12149 		 * fast retransmit/recovery unnecessarily.
12150 		 */
12151 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12152 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12153 		}
12154 	}
12155 }
12156 
12157 /*
12158  * This function handles policy checking at TCP level for non-hard_bound/
12159  * detached connections.
12160  */
12161 static boolean_t
12162 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12163     boolean_t secure, boolean_t mctl_present)
12164 {
12165 	ipsec_latch_t *ipl = NULL;
12166 	ipsec_action_t *act = NULL;
12167 	mblk_t *data_mp;
12168 	ipsec_in_t *ii;
12169 	const char *reason;
12170 	kstat_named_t *counter;
12171 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12172 	ipsec_stack_t	*ipss;
12173 	ip_stack_t	*ipst;
12174 
12175 	ASSERT(mctl_present || !secure);
12176 
12177 	ASSERT((ipha == NULL && ip6h != NULL) ||
12178 	    (ip6h == NULL && ipha != NULL));
12179 
12180 	/*
12181 	 * We don't necessarily have an ipsec_in_act action to verify
12182 	 * policy because of assymetrical policy where we have only
12183 	 * outbound policy and no inbound policy (possible with global
12184 	 * policy).
12185 	 */
12186 	if (!secure) {
12187 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12188 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12189 			return (B_TRUE);
12190 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12191 		    "tcp_check_policy", ipha, ip6h, secure,
12192 		    tcps->tcps_netstack);
12193 		ipss = tcps->tcps_netstack->netstack_ipsec;
12194 
12195 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12196 		    DROPPER(ipss, ipds_tcp_clear),
12197 		    &tcps->tcps_dropper);
12198 		return (B_FALSE);
12199 	}
12200 
12201 	/*
12202 	 * We have a secure packet.
12203 	 */
12204 	if (act == NULL) {
12205 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12206 		    "tcp_check_policy", ipha, ip6h, secure,
12207 		    tcps->tcps_netstack);
12208 		ipss = tcps->tcps_netstack->netstack_ipsec;
12209 
12210 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12211 		    DROPPER(ipss, ipds_tcp_secure),
12212 		    &tcps->tcps_dropper);
12213 		return (B_FALSE);
12214 	}
12215 
12216 	/*
12217 	 * XXX This whole routine is currently incorrect.  ipl should
12218 	 * be set to the latch pointer, but is currently not set, so
12219 	 * we initialize it to NULL to avoid picking up random garbage.
12220 	 */
12221 	if (ipl == NULL)
12222 		return (B_TRUE);
12223 
12224 	data_mp = first_mp->b_cont;
12225 
12226 	ii = (ipsec_in_t *)first_mp->b_rptr;
12227 
12228 	ipst = tcps->tcps_netstack->netstack_ip;
12229 
12230 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12231 	    &counter, tcp->tcp_connp)) {
12232 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12233 		return (B_TRUE);
12234 	}
12235 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12236 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12237 	    reason);
12238 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12239 
12240 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12241 	    &tcps->tcps_dropper);
12242 	return (B_FALSE);
12243 }
12244 
12245 /*
12246  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12247  * retransmission after a timeout.
12248  *
12249  * To limit the number of duplicate segments, we limit the number of segment
12250  * to be sent in one time to tcp_snd_burst, the burst variable.
12251  */
12252 static void
12253 tcp_ss_rexmit(tcp_t *tcp)
12254 {
12255 	uint32_t	snxt;
12256 	uint32_t	smax;
12257 	int32_t		win;
12258 	int32_t		mss;
12259 	int32_t		off;
12260 	int32_t		burst = tcp->tcp_snd_burst;
12261 	mblk_t		*snxt_mp;
12262 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12263 
12264 	/*
12265 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12266 	 * all unack'ed segments.
12267 	 */
12268 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12269 		smax = tcp->tcp_rexmit_max;
12270 		snxt = tcp->tcp_rexmit_nxt;
12271 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12272 			snxt = tcp->tcp_suna;
12273 		}
12274 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12275 		win -= snxt - tcp->tcp_suna;
12276 		mss = tcp->tcp_mss;
12277 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12278 
12279 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12280 		    (burst > 0) && (snxt_mp != NULL)) {
12281 			mblk_t	*xmit_mp;
12282 			mblk_t	*old_snxt_mp = snxt_mp;
12283 			uint32_t cnt = mss;
12284 
12285 			if (win < cnt) {
12286 				cnt = win;
12287 			}
12288 			if (SEQ_GT(snxt + cnt, smax)) {
12289 				cnt = smax - snxt;
12290 			}
12291 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12292 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12293 			if (xmit_mp == NULL)
12294 				return;
12295 
12296 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12297 
12298 			snxt += cnt;
12299 			win -= cnt;
12300 			/*
12301 			 * Update the send timestamp to avoid false
12302 			 * retransmission.
12303 			 */
12304 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12305 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12306 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12307 
12308 			tcp->tcp_rexmit_nxt = snxt;
12309 			burst--;
12310 		}
12311 		/*
12312 		 * If we have transmitted all we have at the time
12313 		 * we started the retranmission, we can leave
12314 		 * the rest of the job to tcp_wput_data().  But we
12315 		 * need to check the send window first.  If the
12316 		 * win is not 0, go on with tcp_wput_data().
12317 		 */
12318 		if (SEQ_LT(snxt, smax) || win == 0) {
12319 			return;
12320 		}
12321 	}
12322 	/* Only call tcp_wput_data() if there is data to be sent. */
12323 	if (tcp->tcp_unsent) {
12324 		tcp_wput_data(tcp, NULL, B_FALSE);
12325 	}
12326 }
12327 
12328 /*
12329  * Process all TCP option in SYN segment.  Note that this function should
12330  * be called after tcp_adapt_ire() is called so that the necessary info
12331  * from IRE is already set in the tcp structure.
12332  *
12333  * This function sets up the correct tcp_mss value according to the
12334  * MSS option value and our header size.  It also sets up the window scale
12335  * and timestamp values, and initialize SACK info blocks.  But it does not
12336  * change receive window size after setting the tcp_mss value.  The caller
12337  * should do the appropriate change.
12338  */
12339 void
12340 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12341 {
12342 	int options;
12343 	tcp_opt_t tcpopt;
12344 	uint32_t mss_max;
12345 	char *tmp_tcph;
12346 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12347 
12348 	tcpopt.tcp = NULL;
12349 	options = tcp_parse_options(tcph, &tcpopt);
12350 
12351 	/*
12352 	 * Process MSS option.  Note that MSS option value does not account
12353 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12354 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12355 	 * IPv6.
12356 	 */
12357 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12358 		if (tcp->tcp_ipversion == IPV4_VERSION)
12359 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12360 		else
12361 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12362 	} else {
12363 		if (tcp->tcp_ipversion == IPV4_VERSION)
12364 			mss_max = tcps->tcps_mss_max_ipv4;
12365 		else
12366 			mss_max = tcps->tcps_mss_max_ipv6;
12367 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12368 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12369 		else if (tcpopt.tcp_opt_mss > mss_max)
12370 			tcpopt.tcp_opt_mss = mss_max;
12371 	}
12372 
12373 	/* Process Window Scale option. */
12374 	if (options & TCP_OPT_WSCALE_PRESENT) {
12375 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12376 		tcp->tcp_snd_ws_ok = B_TRUE;
12377 	} else {
12378 		tcp->tcp_snd_ws = B_FALSE;
12379 		tcp->tcp_snd_ws_ok = B_FALSE;
12380 		tcp->tcp_rcv_ws = B_FALSE;
12381 	}
12382 
12383 	/* Process Timestamp option. */
12384 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12385 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12386 		tmp_tcph = (char *)tcp->tcp_tcph;
12387 
12388 		tcp->tcp_snd_ts_ok = B_TRUE;
12389 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12390 		tcp->tcp_last_rcv_lbolt = lbolt64;
12391 		ASSERT(OK_32PTR(tmp_tcph));
12392 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12393 
12394 		/* Fill in our template header with basic timestamp option. */
12395 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12396 		tmp_tcph[0] = TCPOPT_NOP;
12397 		tmp_tcph[1] = TCPOPT_NOP;
12398 		tmp_tcph[2] = TCPOPT_TSTAMP;
12399 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12400 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12401 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12402 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12403 	} else {
12404 		tcp->tcp_snd_ts_ok = B_FALSE;
12405 	}
12406 
12407 	/*
12408 	 * Process SACK options.  If SACK is enabled for this connection,
12409 	 * then allocate the SACK info structure.  Note the following ways
12410 	 * when tcp_snd_sack_ok is set to true.
12411 	 *
12412 	 * For active connection: in tcp_adapt_ire() called in
12413 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12414 	 * is checked.
12415 	 *
12416 	 * For passive connection: in tcp_adapt_ire() called in
12417 	 * tcp_accept_comm().
12418 	 *
12419 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12420 	 * That check makes sure that if we did not send a SACK OK option,
12421 	 * we will not enable SACK for this connection even though the other
12422 	 * side sends us SACK OK option.  For active connection, the SACK
12423 	 * info structure has already been allocated.  So we need to free
12424 	 * it if SACK is disabled.
12425 	 */
12426 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12427 	    (tcp->tcp_snd_sack_ok ||
12428 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12429 		/* This should be true only in the passive case. */
12430 		if (tcp->tcp_sack_info == NULL) {
12431 			ASSERT(TCP_IS_DETACHED(tcp));
12432 			tcp->tcp_sack_info =
12433 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12434 		}
12435 		if (tcp->tcp_sack_info == NULL) {
12436 			tcp->tcp_snd_sack_ok = B_FALSE;
12437 		} else {
12438 			tcp->tcp_snd_sack_ok = B_TRUE;
12439 			if (tcp->tcp_snd_ts_ok) {
12440 				tcp->tcp_max_sack_blk = 3;
12441 			} else {
12442 				tcp->tcp_max_sack_blk = 4;
12443 			}
12444 		}
12445 	} else {
12446 		/*
12447 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12448 		 * no SACK info will be used for this
12449 		 * connection.  This assumes that SACK usage
12450 		 * permission is negotiated.  This may need
12451 		 * to be changed once this is clarified.
12452 		 */
12453 		if (tcp->tcp_sack_info != NULL) {
12454 			ASSERT(tcp->tcp_notsack_list == NULL);
12455 			kmem_cache_free(tcp_sack_info_cache,
12456 			    tcp->tcp_sack_info);
12457 			tcp->tcp_sack_info = NULL;
12458 		}
12459 		tcp->tcp_snd_sack_ok = B_FALSE;
12460 	}
12461 
12462 	/*
12463 	 * Now we know the exact TCP/IP header length, subtract
12464 	 * that from tcp_mss to get our side's MSS.
12465 	 */
12466 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12467 	/*
12468 	 * Here we assume that the other side's header size will be equal to
12469 	 * our header size.  We calculate the real MSS accordingly.  Need to
12470 	 * take into additional stuffs IPsec puts in.
12471 	 *
12472 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12473 	 */
12474 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12475 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12476 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12477 
12478 	/*
12479 	 * Set MSS to the smaller one of both ends of the connection.
12480 	 * We should not have called tcp_mss_set() before, but our
12481 	 * side of the MSS should have been set to a proper value
12482 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12483 	 * STREAM head parameters properly.
12484 	 *
12485 	 * If we have a larger-than-16-bit window but the other side
12486 	 * didn't want to do window scale, tcp_rwnd_set() will take
12487 	 * care of that.
12488 	 */
12489 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12490 }
12491 
12492 /*
12493  * Sends the T_CONN_IND to the listener. The caller calls this
12494  * functions via squeue to get inside the listener's perimeter
12495  * once the 3 way hand shake is done a T_CONN_IND needs to be
12496  * sent. As an optimization, the caller can call this directly
12497  * if listener's perimeter is same as eager's.
12498  */
12499 /* ARGSUSED */
12500 void
12501 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12502 {
12503 	conn_t			*lconnp = (conn_t *)arg;
12504 	tcp_t			*listener = lconnp->conn_tcp;
12505 	tcp_t			*tcp;
12506 	struct T_conn_ind	*conn_ind;
12507 	ipaddr_t 		*addr_cache;
12508 	boolean_t		need_send_conn_ind = B_FALSE;
12509 	tcp_stack_t		*tcps = listener->tcp_tcps;
12510 
12511 	/* retrieve the eager */
12512 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12513 	ASSERT(conn_ind->OPT_offset != 0 &&
12514 	    conn_ind->OPT_length == sizeof (intptr_t));
12515 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12516 		conn_ind->OPT_length);
12517 
12518 	/*
12519 	 * TLI/XTI applications will get confused by
12520 	 * sending eager as an option since it violates
12521 	 * the option semantics. So remove the eager as
12522 	 * option since TLI/XTI app doesn't need it anyway.
12523 	 */
12524 	if (!TCP_IS_SOCKET(listener)) {
12525 		conn_ind->OPT_length = 0;
12526 		conn_ind->OPT_offset = 0;
12527 	}
12528 	if (listener->tcp_state == TCPS_CLOSED ||
12529 	    TCP_IS_DETACHED(listener)) {
12530 		/*
12531 		 * If listener has closed, it would have caused a
12532 		 * a cleanup/blowoff to happen for the eager. We
12533 		 * just need to return.
12534 		 */
12535 		freemsg(mp);
12536 		return;
12537 	}
12538 
12539 
12540 	/*
12541 	 * if the conn_req_q is full defer passing up the
12542 	 * T_CONN_IND until space is availabe after t_accept()
12543 	 * processing
12544 	 */
12545 	mutex_enter(&listener->tcp_eager_lock);
12546 
12547 	/*
12548 	 * Take the eager out, if it is in the list of droppable eagers
12549 	 * as we are here because the 3W handshake is over.
12550 	 */
12551 	MAKE_UNDROPPABLE(tcp);
12552 
12553 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12554 		tcp_t *tail;
12555 
12556 		/*
12557 		 * The eager already has an extra ref put in tcp_rput_data
12558 		 * so that it stays till accept comes back even though it
12559 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12560 		 */
12561 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12562 		listener->tcp_conn_req_cnt_q0--;
12563 		listener->tcp_conn_req_cnt_q++;
12564 
12565 		/* Move from SYN_RCVD to ESTABLISHED list  */
12566 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12567 		    tcp->tcp_eager_prev_q0;
12568 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12569 		    tcp->tcp_eager_next_q0;
12570 		tcp->tcp_eager_prev_q0 = NULL;
12571 		tcp->tcp_eager_next_q0 = NULL;
12572 
12573 		/*
12574 		 * Insert at end of the queue because sockfs
12575 		 * sends down T_CONN_RES in chronological
12576 		 * order. Leaving the older conn indications
12577 		 * at front of the queue helps reducing search
12578 		 * time.
12579 		 */
12580 		tail = listener->tcp_eager_last_q;
12581 		if (tail != NULL)
12582 			tail->tcp_eager_next_q = tcp;
12583 		else
12584 			listener->tcp_eager_next_q = tcp;
12585 		listener->tcp_eager_last_q = tcp;
12586 		tcp->tcp_eager_next_q = NULL;
12587 		/*
12588 		 * Delay sending up the T_conn_ind until we are
12589 		 * done with the eager. Once we have have sent up
12590 		 * the T_conn_ind, the accept can potentially complete
12591 		 * any time and release the refhold we have on the eager.
12592 		 */
12593 		need_send_conn_ind = B_TRUE;
12594 	} else {
12595 		/*
12596 		 * Defer connection on q0 and set deferred
12597 		 * connection bit true
12598 		 */
12599 		tcp->tcp_conn_def_q0 = B_TRUE;
12600 
12601 		/* take tcp out of q0 ... */
12602 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12603 		    tcp->tcp_eager_next_q0;
12604 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12605 		    tcp->tcp_eager_prev_q0;
12606 
12607 		/* ... and place it at the end of q0 */
12608 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12609 		tcp->tcp_eager_next_q0 = listener;
12610 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12611 		listener->tcp_eager_prev_q0 = tcp;
12612 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12613 	}
12614 
12615 	/* we have timed out before */
12616 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12617 		tcp->tcp_syn_rcvd_timeout = 0;
12618 		listener->tcp_syn_rcvd_timeout--;
12619 		if (listener->tcp_syn_defense &&
12620 		    listener->tcp_syn_rcvd_timeout <=
12621 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12622 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12623 			listener->tcp_last_rcv_lbolt)) {
12624 			/*
12625 			 * Turn off the defense mode if we
12626 			 * believe the SYN attack is over.
12627 			 */
12628 			listener->tcp_syn_defense = B_FALSE;
12629 			if (listener->tcp_ip_addr_cache) {
12630 				kmem_free((void *)listener->tcp_ip_addr_cache,
12631 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12632 				listener->tcp_ip_addr_cache = NULL;
12633 			}
12634 		}
12635 	}
12636 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12637 	if (addr_cache != NULL) {
12638 		/*
12639 		 * We have finished a 3-way handshake with this
12640 		 * remote host. This proves the IP addr is good.
12641 		 * Cache it!
12642 		 */
12643 		addr_cache[IP_ADDR_CACHE_HASH(
12644 			tcp->tcp_remote)] = tcp->tcp_remote;
12645 	}
12646 	mutex_exit(&listener->tcp_eager_lock);
12647 	if (need_send_conn_ind)
12648 		putnext(listener->tcp_rq, mp);
12649 }
12650 
12651 mblk_t *
12652 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12653     uint_t *ifindexp, ip6_pkt_t *ippp)
12654 {
12655 	ip_pktinfo_t	*pinfo;
12656 	ip6_t		*ip6h;
12657 	uchar_t		*rptr;
12658 	mblk_t		*first_mp = mp;
12659 	boolean_t	mctl_present = B_FALSE;
12660 	uint_t 		ifindex = 0;
12661 	ip6_pkt_t	ipp;
12662 	uint_t		ipvers;
12663 	uint_t		ip_hdr_len;
12664 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12665 
12666 	rptr = mp->b_rptr;
12667 	ASSERT(OK_32PTR(rptr));
12668 	ASSERT(tcp != NULL);
12669 	ipp.ipp_fields = 0;
12670 
12671 	switch DB_TYPE(mp) {
12672 	case M_CTL:
12673 		mp = mp->b_cont;
12674 		if (mp == NULL) {
12675 			freemsg(first_mp);
12676 			return (NULL);
12677 		}
12678 		if (DB_TYPE(mp) != M_DATA) {
12679 			freemsg(first_mp);
12680 			return (NULL);
12681 		}
12682 		mctl_present = B_TRUE;
12683 		break;
12684 	case M_DATA:
12685 		break;
12686 	default:
12687 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12688 		freemsg(mp);
12689 		return (NULL);
12690 	}
12691 	ipvers = IPH_HDR_VERSION(rptr);
12692 	if (ipvers == IPV4_VERSION) {
12693 		if (tcp == NULL) {
12694 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12695 			goto done;
12696 		}
12697 
12698 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12699 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12700 
12701 		/*
12702 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12703 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12704 		 */
12705 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12706 		    mctl_present) {
12707 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12708 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12709 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12710 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12711 				ipp.ipp_fields |= IPPF_IFINDEX;
12712 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12713 				ifindex = pinfo->ip_pkt_ifindex;
12714 			}
12715 			freeb(first_mp);
12716 			mctl_present = B_FALSE;
12717 		}
12718 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12719 	} else {
12720 		ip6h = (ip6_t *)rptr;
12721 
12722 		ASSERT(ipvers == IPV6_VERSION);
12723 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12724 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12725 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12726 
12727 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12728 			uint8_t	nexthdrp;
12729 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12730 
12731 			/* Look for ifindex information */
12732 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12733 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12734 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12735 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12736 					freemsg(first_mp);
12737 					return (NULL);
12738 				}
12739 
12740 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12741 					ASSERT(ip6i->ip6i_ifindex != 0);
12742 					ipp.ipp_fields |= IPPF_IFINDEX;
12743 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12744 					ifindex = ip6i->ip6i_ifindex;
12745 				}
12746 				rptr = (uchar_t *)&ip6i[1];
12747 				mp->b_rptr = rptr;
12748 				if (rptr == mp->b_wptr) {
12749 					mblk_t *mp1;
12750 					mp1 = mp->b_cont;
12751 					freeb(mp);
12752 					mp = mp1;
12753 					rptr = mp->b_rptr;
12754 				}
12755 				if (MBLKL(mp) < IPV6_HDR_LEN +
12756 				    sizeof (tcph_t)) {
12757 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12758 					freemsg(first_mp);
12759 					return (NULL);
12760 				}
12761 				ip6h = (ip6_t *)rptr;
12762 			}
12763 
12764 			/*
12765 			 * Find any potentially interesting extension headers
12766 			 * as well as the length of the IPv6 + extension
12767 			 * headers.
12768 			 */
12769 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12770 			/* Verify if this is a TCP packet */
12771 			if (nexthdrp != IPPROTO_TCP) {
12772 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12773 				freemsg(first_mp);
12774 				return (NULL);
12775 			}
12776 		} else {
12777 			ip_hdr_len = IPV6_HDR_LEN;
12778 		}
12779 	}
12780 
12781 done:
12782 	if (ipversp != NULL)
12783 		*ipversp = ipvers;
12784 	if (ip_hdr_lenp != NULL)
12785 		*ip_hdr_lenp = ip_hdr_len;
12786 	if (ippp != NULL)
12787 		*ippp = ipp;
12788 	if (ifindexp != NULL)
12789 		*ifindexp = ifindex;
12790 	if (mctl_present) {
12791 		freeb(first_mp);
12792 	}
12793 	return (mp);
12794 }
12795 
12796 /*
12797  * Handle M_DATA messages from IP. Its called directly from IP via
12798  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12799  * in this path.
12800  *
12801  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12802  * v4 and v6), we are called through tcp_input() and a M_CTL can
12803  * be present for options but tcp_find_pktinfo() deals with it. We
12804  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12805  *
12806  * The first argument is always the connp/tcp to which the mp belongs.
12807  * There are no exceptions to this rule. The caller has already put
12808  * a reference on this connp/tcp and once tcp_rput_data() returns,
12809  * the squeue will do the refrele.
12810  *
12811  * The TH_SYN for the listener directly go to tcp_conn_request via
12812  * squeue.
12813  *
12814  * sqp: NULL = recursive, sqp != NULL means called from squeue
12815  */
12816 void
12817 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12818 {
12819 	int32_t		bytes_acked;
12820 	int32_t		gap;
12821 	mblk_t		*mp1;
12822 	uint_t		flags;
12823 	uint32_t	new_swnd = 0;
12824 	uchar_t		*iphdr;
12825 	uchar_t		*rptr;
12826 	int32_t		rgap;
12827 	uint32_t	seg_ack;
12828 	int		seg_len;
12829 	uint_t		ip_hdr_len;
12830 	uint32_t	seg_seq;
12831 	tcph_t		*tcph;
12832 	int		urp;
12833 	tcp_opt_t	tcpopt;
12834 	uint_t		ipvers;
12835 	ip6_pkt_t	ipp;
12836 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12837 	uint32_t	cwnd;
12838 	uint32_t	add;
12839 	int		npkt;
12840 	int		mss;
12841 	conn_t		*connp = (conn_t *)arg;
12842 	squeue_t	*sqp = (squeue_t *)arg2;
12843 	tcp_t		*tcp = connp->conn_tcp;
12844 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12845 
12846 	/*
12847 	 * RST from fused tcp loopback peer should trigger an unfuse.
12848 	 */
12849 	if (tcp->tcp_fused) {
12850 		TCP_STAT(tcps, tcp_fusion_aborted);
12851 		tcp_unfuse(tcp);
12852 	}
12853 
12854 	iphdr = mp->b_rptr;
12855 	rptr = mp->b_rptr;
12856 	ASSERT(OK_32PTR(rptr));
12857 
12858 	/*
12859 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12860 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12861 	 * necessary information.
12862 	 */
12863 	if (IPCL_IS_TCP4(connp)) {
12864 		ipvers = IPV4_VERSION;
12865 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12866 	} else {
12867 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12868 		    NULL, &ipp);
12869 		if (mp == NULL) {
12870 			TCP_STAT(tcps, tcp_rput_v6_error);
12871 			return;
12872 		}
12873 		iphdr = mp->b_rptr;
12874 		rptr = mp->b_rptr;
12875 	}
12876 	ASSERT(DB_TYPE(mp) == M_DATA);
12877 
12878 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12879 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12880 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12881 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12882 	seg_len = (int)(mp->b_wptr - rptr) -
12883 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12884 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12885 		do {
12886 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12887 			    (uintptr_t)INT_MAX);
12888 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12889 		} while ((mp1 = mp1->b_cont) != NULL &&
12890 		    mp1->b_datap->db_type == M_DATA);
12891 	}
12892 
12893 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12894 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12895 		    seg_len, tcph);
12896 		return;
12897 	}
12898 
12899 	if (sqp != NULL) {
12900 		/*
12901 		 * This is the correct place to update tcp_last_recv_time. Note
12902 		 * that it is also updated for tcp structure that belongs to
12903 		 * global and listener queues which do not really need updating.
12904 		 * But that should not cause any harm.  And it is updated for
12905 		 * all kinds of incoming segments, not only for data segments.
12906 		 */
12907 		tcp->tcp_last_recv_time = lbolt;
12908 	}
12909 
12910 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12911 
12912 	BUMP_LOCAL(tcp->tcp_ibsegs);
12913 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12914 
12915 	if ((flags & TH_URG) && sqp != NULL) {
12916 		/*
12917 		 * TCP can't handle urgent pointers that arrive before
12918 		 * the connection has been accept()ed since it can't
12919 		 * buffer OOB data.  Discard segment if this happens.
12920 		 *
12921 		 * We can't just rely on a non-null tcp_listener to indicate
12922 		 * that the accept() has completed since unlinking of the
12923 		 * eager and completion of the accept are not atomic.
12924 		 * tcp_detached, when it is not set (B_FALSE) indicates
12925 		 * that the accept() has completed.
12926 		 *
12927 		 * Nor can it reassemble urgent pointers, so discard
12928 		 * if it's not the next segment expected.
12929 		 *
12930 		 * Otherwise, collapse chain into one mblk (discard if
12931 		 * that fails).  This makes sure the headers, retransmitted
12932 		 * data, and new data all are in the same mblk.
12933 		 */
12934 		ASSERT(mp != NULL);
12935 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12936 			freemsg(mp);
12937 			return;
12938 		}
12939 		/* Update pointers into message */
12940 		iphdr = rptr = mp->b_rptr;
12941 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12942 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12943 			/*
12944 			 * Since we can't handle any data with this urgent
12945 			 * pointer that is out of sequence, we expunge
12946 			 * the data.  This allows us to still register
12947 			 * the urgent mark and generate the M_PCSIG,
12948 			 * which we can do.
12949 			 */
12950 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12951 			seg_len = 0;
12952 		}
12953 	}
12954 
12955 	switch (tcp->tcp_state) {
12956 	case TCPS_SYN_SENT:
12957 		if (flags & TH_ACK) {
12958 			/*
12959 			 * Note that our stack cannot send data before a
12960 			 * connection is established, therefore the
12961 			 * following check is valid.  Otherwise, it has
12962 			 * to be changed.
12963 			 */
12964 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12965 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12966 				freemsg(mp);
12967 				if (flags & TH_RST)
12968 					return;
12969 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12970 				    tcp, seg_ack, 0, TH_RST);
12971 				return;
12972 			}
12973 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12974 		}
12975 		if (flags & TH_RST) {
12976 			freemsg(mp);
12977 			if (flags & TH_ACK)
12978 				(void) tcp_clean_death(tcp,
12979 				    ECONNREFUSED, 13);
12980 			return;
12981 		}
12982 		if (!(flags & TH_SYN)) {
12983 			freemsg(mp);
12984 			return;
12985 		}
12986 
12987 		/* Process all TCP options. */
12988 		tcp_process_options(tcp, tcph);
12989 		/*
12990 		 * The following changes our rwnd to be a multiple of the
12991 		 * MIN(peer MSS, our MSS) for performance reason.
12992 		 */
12993 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12994 		    tcp->tcp_mss));
12995 
12996 		/* Is the other end ECN capable? */
12997 		if (tcp->tcp_ecn_ok) {
12998 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12999 				tcp->tcp_ecn_ok = B_FALSE;
13000 			}
13001 		}
13002 		/*
13003 		 * Clear ECN flags because it may interfere with later
13004 		 * processing.
13005 		 */
13006 		flags &= ~(TH_ECE|TH_CWR);
13007 
13008 		tcp->tcp_irs = seg_seq;
13009 		tcp->tcp_rack = seg_seq;
13010 		tcp->tcp_rnxt = seg_seq + 1;
13011 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13012 		if (!TCP_IS_DETACHED(tcp)) {
13013 			/* Allocate room for SACK options if needed. */
13014 			if (tcp->tcp_snd_sack_ok) {
13015 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13016 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13017 				    (tcp->tcp_loopback ? 0 :
13018 				    tcps->tcps_wroff_xtra));
13019 			} else {
13020 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13021 				    tcp->tcp_hdr_len +
13022 				    (tcp->tcp_loopback ? 0 :
13023 				    tcps->tcps_wroff_xtra));
13024 			}
13025 		}
13026 		if (flags & TH_ACK) {
13027 			/*
13028 			 * If we can't get the confirmation upstream, pretend
13029 			 * we didn't even see this one.
13030 			 *
13031 			 * XXX: how can we pretend we didn't see it if we
13032 			 * have updated rnxt et. al.
13033 			 *
13034 			 * For loopback we defer sending up the T_CONN_CON
13035 			 * until after some checks below.
13036 			 */
13037 			mp1 = NULL;
13038 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13039 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13040 				freemsg(mp);
13041 				return;
13042 			}
13043 			/* SYN was acked - making progress */
13044 			if (tcp->tcp_ipversion == IPV6_VERSION)
13045 				tcp->tcp_ip_forward_progress = B_TRUE;
13046 
13047 			/* One for the SYN */
13048 			tcp->tcp_suna = tcp->tcp_iss + 1;
13049 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13050 			tcp->tcp_state = TCPS_ESTABLISHED;
13051 
13052 			/*
13053 			 * If SYN was retransmitted, need to reset all
13054 			 * retransmission info.  This is because this
13055 			 * segment will be treated as a dup ACK.
13056 			 */
13057 			if (tcp->tcp_rexmit) {
13058 				tcp->tcp_rexmit = B_FALSE;
13059 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13060 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13061 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13062 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13063 				tcp->tcp_ms_we_have_waited = 0;
13064 
13065 				/*
13066 				 * Set tcp_cwnd back to 1 MSS, per
13067 				 * recommendation from
13068 				 * draft-floyd-incr-init-win-01.txt,
13069 				 * Increasing TCP's Initial Window.
13070 				 */
13071 				tcp->tcp_cwnd = tcp->tcp_mss;
13072 			}
13073 
13074 			tcp->tcp_swl1 = seg_seq;
13075 			tcp->tcp_swl2 = seg_ack;
13076 
13077 			new_swnd = BE16_TO_U16(tcph->th_win);
13078 			tcp->tcp_swnd = new_swnd;
13079 			if (new_swnd > tcp->tcp_max_swnd)
13080 				tcp->tcp_max_swnd = new_swnd;
13081 
13082 			/*
13083 			 * Always send the three-way handshake ack immediately
13084 			 * in order to make the connection complete as soon as
13085 			 * possible on the accepting host.
13086 			 */
13087 			flags |= TH_ACK_NEEDED;
13088 
13089 			/*
13090 			 * Special case for loopback.  At this point we have
13091 			 * received SYN-ACK from the remote endpoint.  In
13092 			 * order to ensure that both endpoints reach the
13093 			 * fused state prior to any data exchange, the final
13094 			 * ACK needs to be sent before we indicate T_CONN_CON
13095 			 * to the module upstream.
13096 			 */
13097 			if (tcp->tcp_loopback) {
13098 				mblk_t *ack_mp;
13099 
13100 				ASSERT(!tcp->tcp_unfusable);
13101 				ASSERT(mp1 != NULL);
13102 				/*
13103 				 * For loopback, we always get a pure SYN-ACK
13104 				 * and only need to send back the final ACK
13105 				 * with no data (this is because the other
13106 				 * tcp is ours and we don't do T/TCP).  This
13107 				 * final ACK triggers the passive side to
13108 				 * perform fusion in ESTABLISHED state.
13109 				 */
13110 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13111 					if (tcp->tcp_ack_tid != 0) {
13112 						(void) TCP_TIMER_CANCEL(tcp,
13113 						    tcp->tcp_ack_tid);
13114 						tcp->tcp_ack_tid = 0;
13115 					}
13116 					TCP_RECORD_TRACE(tcp, ack_mp,
13117 					    TCP_TRACE_SEND_PKT);
13118 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13119 					BUMP_LOCAL(tcp->tcp_obsegs);
13120 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13121 
13122 					/* Send up T_CONN_CON */
13123 					putnext(tcp->tcp_rq, mp1);
13124 
13125 					freemsg(mp);
13126 					return;
13127 				}
13128 				/*
13129 				 * Forget fusion; we need to handle more
13130 				 * complex cases below.  Send the deferred
13131 				 * T_CONN_CON message upstream and proceed
13132 				 * as usual.  Mark this tcp as not capable
13133 				 * of fusion.
13134 				 */
13135 				TCP_STAT(tcps, tcp_fusion_unfusable);
13136 				tcp->tcp_unfusable = B_TRUE;
13137 				putnext(tcp->tcp_rq, mp1);
13138 			}
13139 
13140 			/*
13141 			 * Check to see if there is data to be sent.  If
13142 			 * yes, set the transmit flag.  Then check to see
13143 			 * if received data processing needs to be done.
13144 			 * If not, go straight to xmit_check.  This short
13145 			 * cut is OK as we don't support T/TCP.
13146 			 */
13147 			if (tcp->tcp_unsent)
13148 				flags |= TH_XMIT_NEEDED;
13149 
13150 			if (seg_len == 0 && !(flags & TH_URG)) {
13151 				freemsg(mp);
13152 				goto xmit_check;
13153 			}
13154 
13155 			flags &= ~TH_SYN;
13156 			seg_seq++;
13157 			break;
13158 		}
13159 		tcp->tcp_state = TCPS_SYN_RCVD;
13160 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13161 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13162 		if (mp1) {
13163 			DB_CPID(mp1) = tcp->tcp_cpid;
13164 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13165 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13166 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13167 		}
13168 		freemsg(mp);
13169 		return;
13170 	case TCPS_SYN_RCVD:
13171 		if (flags & TH_ACK) {
13172 			/*
13173 			 * In this state, a SYN|ACK packet is either bogus
13174 			 * because the other side must be ACKing our SYN which
13175 			 * indicates it has seen the ACK for their SYN and
13176 			 * shouldn't retransmit it or we're crossing SYNs
13177 			 * on active open.
13178 			 */
13179 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13180 				freemsg(mp);
13181 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13182 				    tcp, seg_ack, 0, TH_RST);
13183 				return;
13184 			}
13185 			/*
13186 			 * NOTE: RFC 793 pg. 72 says this should be
13187 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13188 			 * but that would mean we have an ack that ignored
13189 			 * our SYN.
13190 			 */
13191 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13192 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13193 				freemsg(mp);
13194 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13195 				    tcp, seg_ack, 0, TH_RST);
13196 				return;
13197 			}
13198 		}
13199 		break;
13200 	case TCPS_LISTEN:
13201 		/*
13202 		 * Only a TLI listener can come through this path when a
13203 		 * acceptor is going back to be a listener and a packet
13204 		 * for the acceptor hits the classifier. For a socket
13205 		 * listener, this can never happen because a listener
13206 		 * can never accept connection on itself and hence a
13207 		 * socket acceptor can not go back to being a listener.
13208 		 */
13209 		ASSERT(!TCP_IS_SOCKET(tcp));
13210 		/*FALLTHRU*/
13211 	case TCPS_CLOSED:
13212 	case TCPS_BOUND: {
13213 		conn_t	*new_connp;
13214 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13215 
13216 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13217 		if (new_connp != NULL) {
13218 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13219 			return;
13220 		}
13221 		/* We failed to classify. For now just drop the packet */
13222 		freemsg(mp);
13223 		return;
13224 	}
13225 	case TCPS_IDLE:
13226 		/*
13227 		 * Handle the case where the tcp_clean_death() has happened
13228 		 * on a connection (application hasn't closed yet) but a packet
13229 		 * was already queued on squeue before tcp_clean_death()
13230 		 * was processed. Calling tcp_clean_death() twice on same
13231 		 * connection can result in weird behaviour.
13232 		 */
13233 		freemsg(mp);
13234 		return;
13235 	default:
13236 		break;
13237 	}
13238 
13239 	/*
13240 	 * Already on the correct queue/perimeter.
13241 	 * If this is a detached connection and not an eager
13242 	 * connection hanging off a listener then new data
13243 	 * (past the FIN) will cause a reset.
13244 	 * We do a special check here where it
13245 	 * is out of the main line, rather than check
13246 	 * if we are detached every time we see new
13247 	 * data down below.
13248 	 */
13249 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13250 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13251 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13252 		TCP_RECORD_TRACE(tcp,
13253 		    mp, TCP_TRACE_RECV_PKT);
13254 
13255 		freemsg(mp);
13256 		/*
13257 		 * This could be an SSL closure alert. We're detached so just
13258 		 * acknowledge it this last time.
13259 		 */
13260 		if (tcp->tcp_kssl_ctx != NULL) {
13261 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13262 			tcp->tcp_kssl_ctx = NULL;
13263 
13264 			tcp->tcp_rnxt += seg_len;
13265 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13266 			flags |= TH_ACK_NEEDED;
13267 			goto ack_check;
13268 		}
13269 
13270 		tcp_xmit_ctl("new data when detached", tcp,
13271 		    tcp->tcp_snxt, 0, TH_RST);
13272 		(void) tcp_clean_death(tcp, EPROTO, 12);
13273 		return;
13274 	}
13275 
13276 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13277 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13278 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13279 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13280 
13281 	if (tcp->tcp_snd_ts_ok) {
13282 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13283 			/*
13284 			 * This segment is not acceptable.
13285 			 * Drop it and send back an ACK.
13286 			 */
13287 			freemsg(mp);
13288 			flags |= TH_ACK_NEEDED;
13289 			goto ack_check;
13290 		}
13291 	} else if (tcp->tcp_snd_sack_ok) {
13292 		ASSERT(tcp->tcp_sack_info != NULL);
13293 		tcpopt.tcp = tcp;
13294 		/*
13295 		 * SACK info in already updated in tcp_parse_options.  Ignore
13296 		 * all other TCP options...
13297 		 */
13298 		(void) tcp_parse_options(tcph, &tcpopt);
13299 	}
13300 try_again:;
13301 	mss = tcp->tcp_mss;
13302 	gap = seg_seq - tcp->tcp_rnxt;
13303 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13304 	/*
13305 	 * gap is the amount of sequence space between what we expect to see
13306 	 * and what we got for seg_seq.  A positive value for gap means
13307 	 * something got lost.  A negative value means we got some old stuff.
13308 	 */
13309 	if (gap < 0) {
13310 		/* Old stuff present.  Is the SYN in there? */
13311 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13312 		    (seg_len != 0)) {
13313 			flags &= ~TH_SYN;
13314 			seg_seq++;
13315 			urp--;
13316 			/* Recompute the gaps after noting the SYN. */
13317 			goto try_again;
13318 		}
13319 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13320 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13321 		    (seg_len > -gap ? -gap : seg_len));
13322 		/* Remove the old stuff from seg_len. */
13323 		seg_len += gap;
13324 		/*
13325 		 * Anything left?
13326 		 * Make sure to check for unack'd FIN when rest of data
13327 		 * has been previously ack'd.
13328 		 */
13329 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13330 			/*
13331 			 * Resets are only valid if they lie within our offered
13332 			 * window.  If the RST bit is set, we just ignore this
13333 			 * segment.
13334 			 */
13335 			if (flags & TH_RST) {
13336 				freemsg(mp);
13337 				return;
13338 			}
13339 
13340 			/*
13341 			 * The arriving of dup data packets indicate that we
13342 			 * may have postponed an ack for too long, or the other
13343 			 * side's RTT estimate is out of shape. Start acking
13344 			 * more often.
13345 			 */
13346 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13347 			    tcp->tcp_rack_cnt >= 1 &&
13348 			    tcp->tcp_rack_abs_max > 2) {
13349 				tcp->tcp_rack_abs_max--;
13350 			}
13351 			tcp->tcp_rack_cur_max = 1;
13352 
13353 			/*
13354 			 * This segment is "unacceptable".  None of its
13355 			 * sequence space lies within our advertized window.
13356 			 *
13357 			 * Adjust seg_len to the original value for tracing.
13358 			 */
13359 			seg_len -= gap;
13360 			if (tcp->tcp_debug) {
13361 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13362 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13363 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13364 				    "seg_len %d, rnxt %u, snxt %u, %s",
13365 				    gap, rgap, flags, seg_seq, seg_ack,
13366 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13367 				    tcp_display(tcp, NULL,
13368 				    DISP_ADDR_AND_PORT));
13369 			}
13370 
13371 			/*
13372 			 * Arrange to send an ACK in response to the
13373 			 * unacceptable segment per RFC 793 page 69. There
13374 			 * is only one small difference between ours and the
13375 			 * acceptability test in the RFC - we accept ACK-only
13376 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13377 			 * will be generated.
13378 			 *
13379 			 * Note that we have to ACK an ACK-only packet at least
13380 			 * for stacks that send 0-length keep-alives with
13381 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13382 			 * section 4.2.3.6. As long as we don't ever generate
13383 			 * an unacceptable packet in response to an incoming
13384 			 * packet that is unacceptable, it should not cause
13385 			 * "ACK wars".
13386 			 */
13387 			flags |=  TH_ACK_NEEDED;
13388 
13389 			/*
13390 			 * Continue processing this segment in order to use the
13391 			 * ACK information it contains, but skip all other
13392 			 * sequence-number processing.	Processing the ACK
13393 			 * information is necessary in order to
13394 			 * re-synchronize connections that may have lost
13395 			 * synchronization.
13396 			 *
13397 			 * We clear seg_len and flag fields related to
13398 			 * sequence number processing as they are not
13399 			 * to be trusted for an unacceptable segment.
13400 			 */
13401 			seg_len = 0;
13402 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13403 			goto process_ack;
13404 		}
13405 
13406 		/* Fix seg_seq, and chew the gap off the front. */
13407 		seg_seq = tcp->tcp_rnxt;
13408 		urp += gap;
13409 		do {
13410 			mblk_t	*mp2;
13411 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13412 			    (uintptr_t)UINT_MAX);
13413 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13414 			if (gap > 0) {
13415 				mp->b_rptr = mp->b_wptr - gap;
13416 				break;
13417 			}
13418 			mp2 = mp;
13419 			mp = mp->b_cont;
13420 			freeb(mp2);
13421 		} while (gap < 0);
13422 		/*
13423 		 * If the urgent data has already been acknowledged, we
13424 		 * should ignore TH_URG below
13425 		 */
13426 		if (urp < 0)
13427 			flags &= ~TH_URG;
13428 	}
13429 	/*
13430 	 * rgap is the amount of stuff received out of window.  A negative
13431 	 * value is the amount out of window.
13432 	 */
13433 	if (rgap < 0) {
13434 		mblk_t	*mp2;
13435 
13436 		if (tcp->tcp_rwnd == 0) {
13437 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13438 		} else {
13439 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13440 			UPDATE_MIB(&tcps->tcps_mib,
13441 			    tcpInDataPastWinBytes, -rgap);
13442 		}
13443 
13444 		/*
13445 		 * seg_len does not include the FIN, so if more than
13446 		 * just the FIN is out of window, we act like we don't
13447 		 * see it.  (If just the FIN is out of window, rgap
13448 		 * will be zero and we will go ahead and acknowledge
13449 		 * the FIN.)
13450 		 */
13451 		flags &= ~TH_FIN;
13452 
13453 		/* Fix seg_len and make sure there is something left. */
13454 		seg_len += rgap;
13455 		if (seg_len <= 0) {
13456 			/*
13457 			 * Resets are only valid if they lie within our offered
13458 			 * window.  If the RST bit is set, we just ignore this
13459 			 * segment.
13460 			 */
13461 			if (flags & TH_RST) {
13462 				freemsg(mp);
13463 				return;
13464 			}
13465 
13466 			/* Per RFC 793, we need to send back an ACK. */
13467 			flags |= TH_ACK_NEEDED;
13468 
13469 			/*
13470 			 * Send SIGURG as soon as possible i.e. even
13471 			 * if the TH_URG was delivered in a window probe
13472 			 * packet (which will be unacceptable).
13473 			 *
13474 			 * We generate a signal if none has been generated
13475 			 * for this connection or if this is a new urgent
13476 			 * byte. Also send a zero-length "unmarked" message
13477 			 * to inform SIOCATMARK that this is not the mark.
13478 			 *
13479 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13480 			 * is sent up. This plus the check for old data
13481 			 * (gap >= 0) handles the wraparound of the sequence
13482 			 * number space without having to always track the
13483 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13484 			 * this max in its rcv_up variable).
13485 			 *
13486 			 * This prevents duplicate SIGURGS due to a "late"
13487 			 * zero-window probe when the T_EXDATA_IND has already
13488 			 * been sent up.
13489 			 */
13490 			if ((flags & TH_URG) &&
13491 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13492 			    tcp->tcp_urp_last))) {
13493 				mp1 = allocb(0, BPRI_MED);
13494 				if (mp1 == NULL) {
13495 					freemsg(mp);
13496 					return;
13497 				}
13498 				if (!TCP_IS_DETACHED(tcp) &&
13499 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13500 				    SIGURG)) {
13501 					/* Try again on the rexmit. */
13502 					freemsg(mp1);
13503 					freemsg(mp);
13504 					return;
13505 				}
13506 				/*
13507 				 * If the next byte would be the mark
13508 				 * then mark with MARKNEXT else mark
13509 				 * with NOTMARKNEXT.
13510 				 */
13511 				if (gap == 0 && urp == 0)
13512 					mp1->b_flag |= MSGMARKNEXT;
13513 				else
13514 					mp1->b_flag |= MSGNOTMARKNEXT;
13515 				freemsg(tcp->tcp_urp_mark_mp);
13516 				tcp->tcp_urp_mark_mp = mp1;
13517 				flags |= TH_SEND_URP_MARK;
13518 				tcp->tcp_urp_last_valid = B_TRUE;
13519 				tcp->tcp_urp_last = urp + seg_seq;
13520 			}
13521 			/*
13522 			 * If this is a zero window probe, continue to
13523 			 * process the ACK part.  But we need to set seg_len
13524 			 * to 0 to avoid data processing.  Otherwise just
13525 			 * drop the segment and send back an ACK.
13526 			 */
13527 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13528 				flags &= ~(TH_SYN | TH_URG);
13529 				seg_len = 0;
13530 				goto process_ack;
13531 			} else {
13532 				freemsg(mp);
13533 				goto ack_check;
13534 			}
13535 		}
13536 		/* Pitch out of window stuff off the end. */
13537 		rgap = seg_len;
13538 		mp2 = mp;
13539 		do {
13540 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13541 			    (uintptr_t)INT_MAX);
13542 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13543 			if (rgap < 0) {
13544 				mp2->b_wptr += rgap;
13545 				if ((mp1 = mp2->b_cont) != NULL) {
13546 					mp2->b_cont = NULL;
13547 					freemsg(mp1);
13548 				}
13549 				break;
13550 			}
13551 		} while ((mp2 = mp2->b_cont) != NULL);
13552 	}
13553 ok:;
13554 	/*
13555 	 * TCP should check ECN info for segments inside the window only.
13556 	 * Therefore the check should be done here.
13557 	 */
13558 	if (tcp->tcp_ecn_ok) {
13559 		if (flags & TH_CWR) {
13560 			tcp->tcp_ecn_echo_on = B_FALSE;
13561 		}
13562 		/*
13563 		 * Note that both ECN_CE and CWR can be set in the
13564 		 * same segment.  In this case, we once again turn
13565 		 * on ECN_ECHO.
13566 		 */
13567 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13568 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13569 
13570 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13571 				tcp->tcp_ecn_echo_on = B_TRUE;
13572 			}
13573 		} else {
13574 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13575 
13576 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13577 			    htonl(IPH_ECN_CE << 20)) {
13578 				tcp->tcp_ecn_echo_on = B_TRUE;
13579 			}
13580 		}
13581 	}
13582 
13583 	/*
13584 	 * Check whether we can update tcp_ts_recent.  This test is
13585 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13586 	 * Extensions for High Performance: An Update", Internet Draft.
13587 	 */
13588 	if (tcp->tcp_snd_ts_ok &&
13589 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13590 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13591 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13592 		tcp->tcp_last_rcv_lbolt = lbolt64;
13593 	}
13594 
13595 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13596 		/*
13597 		 * FIN in an out of order segment.  We record this in
13598 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13599 		 * Clear the FIN so that any check on FIN flag will fail.
13600 		 * Remember that FIN also counts in the sequence number
13601 		 * space.  So we need to ack out of order FIN only segments.
13602 		 */
13603 		if (flags & TH_FIN) {
13604 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13605 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13606 			flags &= ~TH_FIN;
13607 			flags |= TH_ACK_NEEDED;
13608 		}
13609 		if (seg_len > 0) {
13610 			/* Fill in the SACK blk list. */
13611 			if (tcp->tcp_snd_sack_ok) {
13612 				ASSERT(tcp->tcp_sack_info != NULL);
13613 				tcp_sack_insert(tcp->tcp_sack_list,
13614 				    seg_seq, seg_seq + seg_len,
13615 				    &(tcp->tcp_num_sack_blk));
13616 			}
13617 
13618 			/*
13619 			 * Attempt reassembly and see if we have something
13620 			 * ready to go.
13621 			 */
13622 			mp = tcp_reass(tcp, mp, seg_seq);
13623 			/* Always ack out of order packets */
13624 			flags |= TH_ACK_NEEDED | TH_PUSH;
13625 			if (mp) {
13626 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13627 				    (uintptr_t)INT_MAX);
13628 				seg_len = mp->b_cont ? msgdsize(mp) :
13629 					(int)(mp->b_wptr - mp->b_rptr);
13630 				seg_seq = tcp->tcp_rnxt;
13631 				/*
13632 				 * A gap is filled and the seq num and len
13633 				 * of the gap match that of a previously
13634 				 * received FIN, put the FIN flag back in.
13635 				 */
13636 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13637 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13638 					flags |= TH_FIN;
13639 					tcp->tcp_valid_bits &=
13640 					    ~TCP_OFO_FIN_VALID;
13641 				}
13642 			} else {
13643 				/*
13644 				 * Keep going even with NULL mp.
13645 				 * There may be a useful ACK or something else
13646 				 * we don't want to miss.
13647 				 *
13648 				 * But TCP should not perform fast retransmit
13649 				 * because of the ack number.  TCP uses
13650 				 * seg_len == 0 to determine if it is a pure
13651 				 * ACK.  And this is not a pure ACK.
13652 				 */
13653 				seg_len = 0;
13654 				ofo_seg = B_TRUE;
13655 			}
13656 		}
13657 	} else if (seg_len > 0) {
13658 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13659 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13660 		/*
13661 		 * If an out of order FIN was received before, and the seq
13662 		 * num and len of the new segment match that of the FIN,
13663 		 * put the FIN flag back in.
13664 		 */
13665 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13666 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13667 			flags |= TH_FIN;
13668 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13669 		}
13670 	}
13671 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13672 	if (flags & TH_RST) {
13673 		freemsg(mp);
13674 		switch (tcp->tcp_state) {
13675 		case TCPS_SYN_RCVD:
13676 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13677 			break;
13678 		case TCPS_ESTABLISHED:
13679 		case TCPS_FIN_WAIT_1:
13680 		case TCPS_FIN_WAIT_2:
13681 		case TCPS_CLOSE_WAIT:
13682 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13683 			break;
13684 		case TCPS_CLOSING:
13685 		case TCPS_LAST_ACK:
13686 			(void) tcp_clean_death(tcp, 0, 16);
13687 			break;
13688 		default:
13689 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13690 			(void) tcp_clean_death(tcp, ENXIO, 17);
13691 			break;
13692 		}
13693 		return;
13694 	}
13695 	if (flags & TH_SYN) {
13696 		/*
13697 		 * See RFC 793, Page 71
13698 		 *
13699 		 * The seq number must be in the window as it should
13700 		 * be "fixed" above.  If it is outside window, it should
13701 		 * be already rejected.  Note that we allow seg_seq to be
13702 		 * rnxt + rwnd because we want to accept 0 window probe.
13703 		 */
13704 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13705 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13706 		freemsg(mp);
13707 		/*
13708 		 * If the ACK flag is not set, just use our snxt as the
13709 		 * seq number of the RST segment.
13710 		 */
13711 		if (!(flags & TH_ACK)) {
13712 			seg_ack = tcp->tcp_snxt;
13713 		}
13714 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13715 		    TH_RST|TH_ACK);
13716 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13717 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13718 		return;
13719 	}
13720 	/*
13721 	 * urp could be -1 when the urp field in the packet is 0
13722 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13723 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13724 	 */
13725 	if (flags & TH_URG && urp >= 0) {
13726 		if (!tcp->tcp_urp_last_valid ||
13727 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13728 			/*
13729 			 * If we haven't generated the signal yet for this
13730 			 * urgent pointer value, do it now.  Also, send up a
13731 			 * zero-length M_DATA indicating whether or not this is
13732 			 * the mark. The latter is not needed when a
13733 			 * T_EXDATA_IND is sent up. However, if there are
13734 			 * allocation failures this code relies on the sender
13735 			 * retransmitting and the socket code for determining
13736 			 * the mark should not block waiting for the peer to
13737 			 * transmit. Thus, for simplicity we always send up the
13738 			 * mark indication.
13739 			 */
13740 			mp1 = allocb(0, BPRI_MED);
13741 			if (mp1 == NULL) {
13742 				freemsg(mp);
13743 				return;
13744 			}
13745 			if (!TCP_IS_DETACHED(tcp) &&
13746 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13747 				/* Try again on the rexmit. */
13748 				freemsg(mp1);
13749 				freemsg(mp);
13750 				return;
13751 			}
13752 			/*
13753 			 * Mark with NOTMARKNEXT for now.
13754 			 * The code below will change this to MARKNEXT
13755 			 * if we are at the mark.
13756 			 *
13757 			 * If there are allocation failures (e.g. in dupmsg
13758 			 * below) the next time tcp_rput_data sees the urgent
13759 			 * segment it will send up the MSG*MARKNEXT message.
13760 			 */
13761 			mp1->b_flag |= MSGNOTMARKNEXT;
13762 			freemsg(tcp->tcp_urp_mark_mp);
13763 			tcp->tcp_urp_mark_mp = mp1;
13764 			flags |= TH_SEND_URP_MARK;
13765 #ifdef DEBUG
13766 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13767 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13768 			    "last %x, %s",
13769 			    seg_seq, urp, tcp->tcp_urp_last,
13770 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13771 #endif /* DEBUG */
13772 			tcp->tcp_urp_last_valid = B_TRUE;
13773 			tcp->tcp_urp_last = urp + seg_seq;
13774 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13775 			/*
13776 			 * An allocation failure prevented the previous
13777 			 * tcp_rput_data from sending up the allocated
13778 			 * MSG*MARKNEXT message - send it up this time
13779 			 * around.
13780 			 */
13781 			flags |= TH_SEND_URP_MARK;
13782 		}
13783 
13784 		/*
13785 		 * If the urgent byte is in this segment, make sure that it is
13786 		 * all by itself.  This makes it much easier to deal with the
13787 		 * possibility of an allocation failure on the T_exdata_ind.
13788 		 * Note that seg_len is the number of bytes in the segment, and
13789 		 * urp is the offset into the segment of the urgent byte.
13790 		 * urp < seg_len means that the urgent byte is in this segment.
13791 		 */
13792 		if (urp < seg_len) {
13793 			if (seg_len != 1) {
13794 				uint32_t  tmp_rnxt;
13795 				/*
13796 				 * Break it up and feed it back in.
13797 				 * Re-attach the IP header.
13798 				 */
13799 				mp->b_rptr = iphdr;
13800 				if (urp > 0) {
13801 					/*
13802 					 * There is stuff before the urgent
13803 					 * byte.
13804 					 */
13805 					mp1 = dupmsg(mp);
13806 					if (!mp1) {
13807 						/*
13808 						 * Trim from urgent byte on.
13809 						 * The rest will come back.
13810 						 */
13811 						(void) adjmsg(mp,
13812 						    urp - seg_len);
13813 						tcp_rput_data(connp,
13814 						    mp, NULL);
13815 						return;
13816 					}
13817 					(void) adjmsg(mp1, urp - seg_len);
13818 					/* Feed this piece back in. */
13819 					tmp_rnxt = tcp->tcp_rnxt;
13820 					tcp_rput_data(connp, mp1, NULL);
13821 					/*
13822 					 * If the data passed back in was not
13823 					 * processed (ie: bad ACK) sending
13824 					 * the remainder back in will cause a
13825 					 * loop. In this case, drop the
13826 					 * packet and let the sender try
13827 					 * sending a good packet.
13828 					 */
13829 					if (tmp_rnxt == tcp->tcp_rnxt) {
13830 						freemsg(mp);
13831 						return;
13832 					}
13833 				}
13834 				if (urp != seg_len - 1) {
13835 					uint32_t  tmp_rnxt;
13836 					/*
13837 					 * There is stuff after the urgent
13838 					 * byte.
13839 					 */
13840 					mp1 = dupmsg(mp);
13841 					if (!mp1) {
13842 						/*
13843 						 * Trim everything beyond the
13844 						 * urgent byte.  The rest will
13845 						 * come back.
13846 						 */
13847 						(void) adjmsg(mp,
13848 						    urp + 1 - seg_len);
13849 						tcp_rput_data(connp,
13850 						    mp, NULL);
13851 						return;
13852 					}
13853 					(void) adjmsg(mp1, urp + 1 - seg_len);
13854 					tmp_rnxt = tcp->tcp_rnxt;
13855 					tcp_rput_data(connp, mp1, NULL);
13856 					/*
13857 					 * If the data passed back in was not
13858 					 * processed (ie: bad ACK) sending
13859 					 * the remainder back in will cause a
13860 					 * loop. In this case, drop the
13861 					 * packet and let the sender try
13862 					 * sending a good packet.
13863 					 */
13864 					if (tmp_rnxt == tcp->tcp_rnxt) {
13865 						freemsg(mp);
13866 						return;
13867 					}
13868 				}
13869 				tcp_rput_data(connp, mp, NULL);
13870 				return;
13871 			}
13872 			/*
13873 			 * This segment contains only the urgent byte.  We
13874 			 * have to allocate the T_exdata_ind, if we can.
13875 			 */
13876 			if (!tcp->tcp_urp_mp) {
13877 				struct T_exdata_ind *tei;
13878 				mp1 = allocb(sizeof (struct T_exdata_ind),
13879 				    BPRI_MED);
13880 				if (!mp1) {
13881 					/*
13882 					 * Sigh... It'll be back.
13883 					 * Generate any MSG*MARK message now.
13884 					 */
13885 					freemsg(mp);
13886 					seg_len = 0;
13887 					if (flags & TH_SEND_URP_MARK) {
13888 
13889 
13890 						ASSERT(tcp->tcp_urp_mark_mp);
13891 						tcp->tcp_urp_mark_mp->b_flag &=
13892 							~MSGNOTMARKNEXT;
13893 						tcp->tcp_urp_mark_mp->b_flag |=
13894 							MSGMARKNEXT;
13895 					}
13896 					goto ack_check;
13897 				}
13898 				mp1->b_datap->db_type = M_PROTO;
13899 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13900 				tei->PRIM_type = T_EXDATA_IND;
13901 				tei->MORE_flag = 0;
13902 				mp1->b_wptr = (uchar_t *)&tei[1];
13903 				tcp->tcp_urp_mp = mp1;
13904 #ifdef DEBUG
13905 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13906 				    "tcp_rput: allocated exdata_ind %s",
13907 				    tcp_display(tcp, NULL,
13908 				    DISP_PORT_ONLY));
13909 #endif /* DEBUG */
13910 				/*
13911 				 * There is no need to send a separate MSG*MARK
13912 				 * message since the T_EXDATA_IND will be sent
13913 				 * now.
13914 				 */
13915 				flags &= ~TH_SEND_URP_MARK;
13916 				freemsg(tcp->tcp_urp_mark_mp);
13917 				tcp->tcp_urp_mark_mp = NULL;
13918 			}
13919 			/*
13920 			 * Now we are all set.  On the next putnext upstream,
13921 			 * tcp_urp_mp will be non-NULL and will get prepended
13922 			 * to what has to be this piece containing the urgent
13923 			 * byte.  If for any reason we abort this segment below,
13924 			 * if it comes back, we will have this ready, or it
13925 			 * will get blown off in close.
13926 			 */
13927 		} else if (urp == seg_len) {
13928 			/*
13929 			 * The urgent byte is the next byte after this sequence
13930 			 * number. If there is data it is marked with
13931 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13932 			 * since it is not needed. Otherwise, if the code
13933 			 * above just allocated a zero-length tcp_urp_mark_mp
13934 			 * message, that message is tagged with MSGMARKNEXT.
13935 			 * Sending up these MSGMARKNEXT messages makes
13936 			 * SIOCATMARK work correctly even though
13937 			 * the T_EXDATA_IND will not be sent up until the
13938 			 * urgent byte arrives.
13939 			 */
13940 			if (seg_len != 0) {
13941 				flags |= TH_MARKNEXT_NEEDED;
13942 				freemsg(tcp->tcp_urp_mark_mp);
13943 				tcp->tcp_urp_mark_mp = NULL;
13944 				flags &= ~TH_SEND_URP_MARK;
13945 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13946 				flags |= TH_SEND_URP_MARK;
13947 				tcp->tcp_urp_mark_mp->b_flag &=
13948 					~MSGNOTMARKNEXT;
13949 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13950 			}
13951 #ifdef DEBUG
13952 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13953 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13954 			    seg_len, flags,
13955 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13956 #endif /* DEBUG */
13957 		} else {
13958 			/* Data left until we hit mark */
13959 #ifdef DEBUG
13960 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13961 			    "tcp_rput: URP %d bytes left, %s",
13962 			    urp - seg_len, tcp_display(tcp, NULL,
13963 			    DISP_PORT_ONLY));
13964 #endif /* DEBUG */
13965 		}
13966 	}
13967 
13968 process_ack:
13969 	if (!(flags & TH_ACK)) {
13970 		freemsg(mp);
13971 		goto xmit_check;
13972 	}
13973 	}
13974 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13975 
13976 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13977 		tcp->tcp_ip_forward_progress = B_TRUE;
13978 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13979 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13980 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13981 			/* 3-way handshake complete - pass up the T_CONN_IND */
13982 			tcp_t	*listener = tcp->tcp_listener;
13983 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13984 
13985 			tcp->tcp_tconnind_started = B_TRUE;
13986 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13987 			/*
13988 			 * We are here means eager is fine but it can
13989 			 * get a TH_RST at any point between now and till
13990 			 * accept completes and disappear. We need to
13991 			 * ensure that reference to eager is valid after
13992 			 * we get out of eager's perimeter. So we do
13993 			 * an extra refhold.
13994 			 */
13995 			CONN_INC_REF(connp);
13996 
13997 			/*
13998 			 * The listener also exists because of the refhold
13999 			 * done in tcp_conn_request. Its possible that it
14000 			 * might have closed. We will check that once we
14001 			 * get inside listeners context.
14002 			 */
14003 			CONN_INC_REF(listener->tcp_connp);
14004 			if (listener->tcp_connp->conn_sqp ==
14005 			    connp->conn_sqp) {
14006 				tcp_send_conn_ind(listener->tcp_connp, mp,
14007 				    listener->tcp_connp->conn_sqp);
14008 				CONN_DEC_REF(listener->tcp_connp);
14009 			} else if (!tcp->tcp_loopback) {
14010 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14011 				    tcp_send_conn_ind,
14012 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14013 			} else {
14014 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14015 				    tcp_send_conn_ind, listener->tcp_connp,
14016 				    SQTAG_TCP_CONN_IND);
14017 			}
14018 		}
14019 
14020 		if (tcp->tcp_active_open) {
14021 			/*
14022 			 * We are seeing the final ack in the three way
14023 			 * hand shake of a active open'ed connection
14024 			 * so we must send up a T_CONN_CON
14025 			 */
14026 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14027 				freemsg(mp);
14028 				return;
14029 			}
14030 			/*
14031 			 * Don't fuse the loopback endpoints for
14032 			 * simultaneous active opens.
14033 			 */
14034 			if (tcp->tcp_loopback) {
14035 				TCP_STAT(tcps, tcp_fusion_unfusable);
14036 				tcp->tcp_unfusable = B_TRUE;
14037 			}
14038 		}
14039 
14040 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14041 		bytes_acked--;
14042 		/* SYN was acked - making progress */
14043 		if (tcp->tcp_ipversion == IPV6_VERSION)
14044 			tcp->tcp_ip_forward_progress = B_TRUE;
14045 
14046 		/*
14047 		 * If SYN was retransmitted, need to reset all
14048 		 * retransmission info as this segment will be
14049 		 * treated as a dup ACK.
14050 		 */
14051 		if (tcp->tcp_rexmit) {
14052 			tcp->tcp_rexmit = B_FALSE;
14053 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14054 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14055 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14056 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14057 			tcp->tcp_ms_we_have_waited = 0;
14058 			tcp->tcp_cwnd = mss;
14059 		}
14060 
14061 		/*
14062 		 * We set the send window to zero here.
14063 		 * This is needed if there is data to be
14064 		 * processed already on the queue.
14065 		 * Later (at swnd_update label), the
14066 		 * "new_swnd > tcp_swnd" condition is satisfied
14067 		 * the XMIT_NEEDED flag is set in the current
14068 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14069 		 * called if there is already data on queue in
14070 		 * this state.
14071 		 */
14072 		tcp->tcp_swnd = 0;
14073 
14074 		if (new_swnd > tcp->tcp_max_swnd)
14075 			tcp->tcp_max_swnd = new_swnd;
14076 		tcp->tcp_swl1 = seg_seq;
14077 		tcp->tcp_swl2 = seg_ack;
14078 		tcp->tcp_state = TCPS_ESTABLISHED;
14079 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14080 
14081 		/* Fuse when both sides are in ESTABLISHED state */
14082 		if (tcp->tcp_loopback && do_tcp_fusion)
14083 			tcp_fuse(tcp, iphdr, tcph);
14084 
14085 	}
14086 	/* This code follows 4.4BSD-Lite2 mostly. */
14087 	if (bytes_acked < 0)
14088 		goto est;
14089 
14090 	/*
14091 	 * If TCP is ECN capable and the congestion experience bit is
14092 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14093 	 * done once per window (or more loosely, per RTT).
14094 	 */
14095 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14096 		tcp->tcp_cwr = B_FALSE;
14097 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14098 		if (!tcp->tcp_cwr) {
14099 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14100 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14101 			tcp->tcp_cwnd = npkt * mss;
14102 			/*
14103 			 * If the cwnd is 0, use the timer to clock out
14104 			 * new segments.  This is required by the ECN spec.
14105 			 */
14106 			if (npkt == 0) {
14107 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14108 				/*
14109 				 * This makes sure that when the ACK comes
14110 				 * back, we will increase tcp_cwnd by 1 MSS.
14111 				 */
14112 				tcp->tcp_cwnd_cnt = 0;
14113 			}
14114 			tcp->tcp_cwr = B_TRUE;
14115 			/*
14116 			 * This marks the end of the current window of in
14117 			 * flight data.  That is why we don't use
14118 			 * tcp_suna + tcp_swnd.  Only data in flight can
14119 			 * provide ECN info.
14120 			 */
14121 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14122 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14123 		}
14124 	}
14125 
14126 	mp1 = tcp->tcp_xmit_head;
14127 	if (bytes_acked == 0) {
14128 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14129 			int dupack_cnt;
14130 
14131 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14132 			/*
14133 			 * Fast retransmit.  When we have seen exactly three
14134 			 * identical ACKs while we have unacked data
14135 			 * outstanding we take it as a hint that our peer
14136 			 * dropped something.
14137 			 *
14138 			 * If TCP is retransmitting, don't do fast retransmit.
14139 			 */
14140 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14141 			    ! tcp->tcp_rexmit) {
14142 				/* Do Limited Transmit */
14143 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14144 				    tcps->tcps_dupack_fast_retransmit) {
14145 					/*
14146 					 * RFC 3042
14147 					 *
14148 					 * What we need to do is temporarily
14149 					 * increase tcp_cwnd so that new
14150 					 * data can be sent if it is allowed
14151 					 * by the receive window (tcp_rwnd).
14152 					 * tcp_wput_data() will take care of
14153 					 * the rest.
14154 					 *
14155 					 * If the connection is SACK capable,
14156 					 * only do limited xmit when there
14157 					 * is SACK info.
14158 					 *
14159 					 * Note how tcp_cwnd is incremented.
14160 					 * The first dup ACK will increase
14161 					 * it by 1 MSS.  The second dup ACK
14162 					 * will increase it by 2 MSS.  This
14163 					 * means that only 1 new segment will
14164 					 * be sent for each dup ACK.
14165 					 */
14166 					if (tcp->tcp_unsent > 0 &&
14167 					    (!tcp->tcp_snd_sack_ok ||
14168 					    (tcp->tcp_snd_sack_ok &&
14169 					    tcp->tcp_notsack_list != NULL))) {
14170 						tcp->tcp_cwnd += mss <<
14171 						    (tcp->tcp_dupack_cnt - 1);
14172 						flags |= TH_LIMIT_XMIT;
14173 					}
14174 				} else if (dupack_cnt ==
14175 				    tcps->tcps_dupack_fast_retransmit) {
14176 
14177 				/*
14178 				 * If we have reduced tcp_ssthresh
14179 				 * because of ECN, do not reduce it again
14180 				 * unless it is already one window of data
14181 				 * away.  After one window of data, tcp_cwr
14182 				 * should then be cleared.  Note that
14183 				 * for non ECN capable connection, tcp_cwr
14184 				 * should always be false.
14185 				 *
14186 				 * Adjust cwnd since the duplicate
14187 				 * ack indicates that a packet was
14188 				 * dropped (due to congestion.)
14189 				 */
14190 				if (!tcp->tcp_cwr) {
14191 					npkt = ((tcp->tcp_snxt -
14192 					    tcp->tcp_suna) >> 1) / mss;
14193 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14194 					    mss;
14195 					tcp->tcp_cwnd = (npkt +
14196 					    tcp->tcp_dupack_cnt) * mss;
14197 				}
14198 				if (tcp->tcp_ecn_ok) {
14199 					tcp->tcp_cwr = B_TRUE;
14200 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14201 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14202 				}
14203 
14204 				/*
14205 				 * We do Hoe's algorithm.  Refer to her
14206 				 * paper "Improving the Start-up Behavior
14207 				 * of a Congestion Control Scheme for TCP,"
14208 				 * appeared in SIGCOMM'96.
14209 				 *
14210 				 * Save highest seq no we have sent so far.
14211 				 * Be careful about the invisible FIN byte.
14212 				 */
14213 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14214 				    (tcp->tcp_unsent == 0)) {
14215 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14216 				} else {
14217 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14218 				}
14219 
14220 				/*
14221 				 * Do not allow bursty traffic during.
14222 				 * fast recovery.  Refer to Fall and Floyd's
14223 				 * paper "Simulation-based Comparisons of
14224 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14225 				 * This is a best current practise.
14226 				 */
14227 				tcp->tcp_snd_burst = TCP_CWND_SS;
14228 
14229 				/*
14230 				 * For SACK:
14231 				 * Calculate tcp_pipe, which is the
14232 				 * estimated number of bytes in
14233 				 * network.
14234 				 *
14235 				 * tcp_fack is the highest sack'ed seq num
14236 				 * TCP has received.
14237 				 *
14238 				 * tcp_pipe is explained in the above quoted
14239 				 * Fall and Floyd's paper.  tcp_fack is
14240 				 * explained in Mathis and Mahdavi's
14241 				 * "Forward Acknowledgment: Refining TCP
14242 				 * Congestion Control" in SIGCOMM '96.
14243 				 */
14244 				if (tcp->tcp_snd_sack_ok) {
14245 					ASSERT(tcp->tcp_sack_info != NULL);
14246 					if (tcp->tcp_notsack_list != NULL) {
14247 						tcp->tcp_pipe = tcp->tcp_snxt -
14248 						    tcp->tcp_fack;
14249 						tcp->tcp_sack_snxt = seg_ack;
14250 						flags |= TH_NEED_SACK_REXMIT;
14251 					} else {
14252 						/*
14253 						 * Always initialize tcp_pipe
14254 						 * even though we don't have
14255 						 * any SACK info.  If later
14256 						 * we get SACK info and
14257 						 * tcp_pipe is not initialized,
14258 						 * funny things will happen.
14259 						 */
14260 						tcp->tcp_pipe =
14261 						    tcp->tcp_cwnd_ssthresh;
14262 					}
14263 				} else {
14264 					flags |= TH_REXMIT_NEEDED;
14265 				} /* tcp_snd_sack_ok */
14266 
14267 				} else {
14268 					/*
14269 					 * Here we perform congestion
14270 					 * avoidance, but NOT slow start.
14271 					 * This is known as the Fast
14272 					 * Recovery Algorithm.
14273 					 */
14274 					if (tcp->tcp_snd_sack_ok &&
14275 					    tcp->tcp_notsack_list != NULL) {
14276 						flags |= TH_NEED_SACK_REXMIT;
14277 						tcp->tcp_pipe -= mss;
14278 						if (tcp->tcp_pipe < 0)
14279 							tcp->tcp_pipe = 0;
14280 					} else {
14281 					/*
14282 					 * We know that one more packet has
14283 					 * left the pipe thus we can update
14284 					 * cwnd.
14285 					 */
14286 					cwnd = tcp->tcp_cwnd + mss;
14287 					if (cwnd > tcp->tcp_cwnd_max)
14288 						cwnd = tcp->tcp_cwnd_max;
14289 					tcp->tcp_cwnd = cwnd;
14290 					if (tcp->tcp_unsent > 0)
14291 						flags |= TH_XMIT_NEEDED;
14292 					}
14293 				}
14294 			}
14295 		} else if (tcp->tcp_zero_win_probe) {
14296 			/*
14297 			 * If the window has opened, need to arrange
14298 			 * to send additional data.
14299 			 */
14300 			if (new_swnd != 0) {
14301 				/* tcp_suna != tcp_snxt */
14302 				/* Packet contains a window update */
14303 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14304 				tcp->tcp_zero_win_probe = 0;
14305 				tcp->tcp_timer_backoff = 0;
14306 				tcp->tcp_ms_we_have_waited = 0;
14307 
14308 				/*
14309 				 * Transmit starting with tcp_suna since
14310 				 * the one byte probe is not ack'ed.
14311 				 * If TCP has sent more than one identical
14312 				 * probe, tcp_rexmit will be set.  That means
14313 				 * tcp_ss_rexmit() will send out the one
14314 				 * byte along with new data.  Otherwise,
14315 				 * fake the retransmission.
14316 				 */
14317 				flags |= TH_XMIT_NEEDED;
14318 				if (!tcp->tcp_rexmit) {
14319 					tcp->tcp_rexmit = B_TRUE;
14320 					tcp->tcp_dupack_cnt = 0;
14321 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14322 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14323 				}
14324 			}
14325 		}
14326 		goto swnd_update;
14327 	}
14328 
14329 	/*
14330 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14331 	 * If the ACK value acks something that we have not yet sent, it might
14332 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14333 	 * other side.
14334 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14335 	 * state is handled above, so we can always just drop the segment and
14336 	 * send an ACK here.
14337 	 *
14338 	 * Should we send ACKs in response to ACK only segments?
14339 	 */
14340 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14341 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14342 		/* drop the received segment */
14343 		freemsg(mp);
14344 
14345 		/*
14346 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14347 		 * greater than 0, check if the number of such
14348 		 * bogus ACks is greater than that count.  If yes,
14349 		 * don't send back any ACK.  This prevents TCP from
14350 		 * getting into an ACK storm if somehow an attacker
14351 		 * successfully spoofs an acceptable segment to our
14352 		 * peer.
14353 		 */
14354 		if (tcp_drop_ack_unsent_cnt > 0 &&
14355 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14356 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14357 			return;
14358 		}
14359 		mp = tcp_ack_mp(tcp);
14360 		if (mp != NULL) {
14361 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14362 			BUMP_LOCAL(tcp->tcp_obsegs);
14363 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14364 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14365 		}
14366 		return;
14367 	}
14368 
14369 	/*
14370 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14371 	 * blocks that are covered by this ACK.
14372 	 */
14373 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14374 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14375 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14376 	}
14377 
14378 	/*
14379 	 * If we got an ACK after fast retransmit, check to see
14380 	 * if it is a partial ACK.  If it is not and the congestion
14381 	 * window was inflated to account for the other side's
14382 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14383 	 */
14384 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14385 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14386 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14387 			tcp->tcp_dupack_cnt = 0;
14388 			/*
14389 			 * Restore the orig tcp_cwnd_ssthresh after
14390 			 * fast retransmit phase.
14391 			 */
14392 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14393 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14394 			}
14395 			tcp->tcp_rexmit_max = seg_ack;
14396 			tcp->tcp_cwnd_cnt = 0;
14397 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14398 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14399 
14400 			/*
14401 			 * Remove all notsack info to avoid confusion with
14402 			 * the next fast retrasnmit/recovery phase.
14403 			 */
14404 			if (tcp->tcp_snd_sack_ok &&
14405 			    tcp->tcp_notsack_list != NULL) {
14406 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14407 			}
14408 		} else {
14409 			if (tcp->tcp_snd_sack_ok &&
14410 			    tcp->tcp_notsack_list != NULL) {
14411 				flags |= TH_NEED_SACK_REXMIT;
14412 				tcp->tcp_pipe -= mss;
14413 				if (tcp->tcp_pipe < 0)
14414 					tcp->tcp_pipe = 0;
14415 			} else {
14416 				/*
14417 				 * Hoe's algorithm:
14418 				 *
14419 				 * Retransmit the unack'ed segment and
14420 				 * restart fast recovery.  Note that we
14421 				 * need to scale back tcp_cwnd to the
14422 				 * original value when we started fast
14423 				 * recovery.  This is to prevent overly
14424 				 * aggressive behaviour in sending new
14425 				 * segments.
14426 				 */
14427 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14428 				    tcps->tcps_dupack_fast_retransmit * mss;
14429 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14430 				flags |= TH_REXMIT_NEEDED;
14431 			}
14432 		}
14433 	} else {
14434 		tcp->tcp_dupack_cnt = 0;
14435 		if (tcp->tcp_rexmit) {
14436 			/*
14437 			 * TCP is retranmitting.  If the ACK ack's all
14438 			 * outstanding data, update tcp_rexmit_max and
14439 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14440 			 * to the correct value.
14441 			 *
14442 			 * Note that SEQ_LEQ() is used.  This is to avoid
14443 			 * unnecessary fast retransmit caused by dup ACKs
14444 			 * received when TCP does slow start retransmission
14445 			 * after a time out.  During this phase, TCP may
14446 			 * send out segments which are already received.
14447 			 * This causes dup ACKs to be sent back.
14448 			 */
14449 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14450 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14451 					tcp->tcp_rexmit_nxt = seg_ack;
14452 				}
14453 				if (seg_ack != tcp->tcp_rexmit_max) {
14454 					flags |= TH_XMIT_NEEDED;
14455 				}
14456 			} else {
14457 				tcp->tcp_rexmit = B_FALSE;
14458 				tcp->tcp_xmit_zc_clean = B_FALSE;
14459 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14460 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14461 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14462 			}
14463 			tcp->tcp_ms_we_have_waited = 0;
14464 		}
14465 	}
14466 
14467 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14468 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14469 	tcp->tcp_suna = seg_ack;
14470 	if (tcp->tcp_zero_win_probe != 0) {
14471 		tcp->tcp_zero_win_probe = 0;
14472 		tcp->tcp_timer_backoff = 0;
14473 	}
14474 
14475 	/*
14476 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14477 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14478 	 * will not reach here.
14479 	 */
14480 	if (mp1 == NULL) {
14481 		goto fin_acked;
14482 	}
14483 
14484 	/*
14485 	 * Update the congestion window.
14486 	 *
14487 	 * If TCP is not ECN capable or TCP is ECN capable but the
14488 	 * congestion experience bit is not set, increase the tcp_cwnd as
14489 	 * usual.
14490 	 */
14491 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14492 		cwnd = tcp->tcp_cwnd;
14493 		add = mss;
14494 
14495 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14496 			/*
14497 			 * This is to prevent an increase of less than 1 MSS of
14498 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14499 			 * may send out tinygrams in order to preserve mblk
14500 			 * boundaries.
14501 			 *
14502 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14503 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14504 			 * increased by 1 MSS for every RTTs.
14505 			 */
14506 			if (tcp->tcp_cwnd_cnt <= 0) {
14507 				tcp->tcp_cwnd_cnt = cwnd + add;
14508 			} else {
14509 				tcp->tcp_cwnd_cnt -= add;
14510 				add = 0;
14511 			}
14512 		}
14513 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14514 	}
14515 
14516 	/* See if the latest urgent data has been acknowledged */
14517 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14518 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14519 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14520 
14521 	/* Can we update the RTT estimates? */
14522 	if (tcp->tcp_snd_ts_ok) {
14523 		/* Ignore zero timestamp echo-reply. */
14524 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14525 			tcp_set_rto(tcp, (int32_t)lbolt -
14526 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14527 		}
14528 
14529 		/* If needed, restart the timer. */
14530 		if (tcp->tcp_set_timer == 1) {
14531 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14532 			tcp->tcp_set_timer = 0;
14533 		}
14534 		/*
14535 		 * Update tcp_csuna in case the other side stops sending
14536 		 * us timestamps.
14537 		 */
14538 		tcp->tcp_csuna = tcp->tcp_snxt;
14539 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14540 		/*
14541 		 * An ACK sequence we haven't seen before, so get the RTT
14542 		 * and update the RTO. But first check if the timestamp is
14543 		 * valid to use.
14544 		 */
14545 		if ((mp1->b_next != NULL) &&
14546 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14547 			tcp_set_rto(tcp, (int32_t)lbolt -
14548 			    (int32_t)(intptr_t)mp1->b_prev);
14549 		else
14550 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14551 
14552 		/* Remeber the last sequence to be ACKed */
14553 		tcp->tcp_csuna = seg_ack;
14554 		if (tcp->tcp_set_timer == 1) {
14555 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14556 			tcp->tcp_set_timer = 0;
14557 		}
14558 	} else {
14559 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14560 	}
14561 
14562 	/* Eat acknowledged bytes off the xmit queue. */
14563 	for (;;) {
14564 		mblk_t	*mp2;
14565 		uchar_t	*wptr;
14566 
14567 		wptr = mp1->b_wptr;
14568 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14569 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14570 		if (bytes_acked < 0) {
14571 			mp1->b_rptr = wptr + bytes_acked;
14572 			/*
14573 			 * Set a new timestamp if all the bytes timed by the
14574 			 * old timestamp have been ack'ed.
14575 			 */
14576 			if (SEQ_GT(seg_ack,
14577 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14578 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14579 				mp1->b_next = NULL;
14580 			}
14581 			break;
14582 		}
14583 		mp1->b_next = NULL;
14584 		mp1->b_prev = NULL;
14585 		mp2 = mp1;
14586 		mp1 = mp1->b_cont;
14587 
14588 		/*
14589 		 * This notification is required for some zero-copy
14590 		 * clients to maintain a copy semantic. After the data
14591 		 * is ack'ed, client is safe to modify or reuse the buffer.
14592 		 */
14593 		if (tcp->tcp_snd_zcopy_aware &&
14594 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14595 			tcp_zcopy_notify(tcp);
14596 		freeb(mp2);
14597 		if (bytes_acked == 0) {
14598 			if (mp1 == NULL) {
14599 				/* Everything is ack'ed, clear the tail. */
14600 				tcp->tcp_xmit_tail = NULL;
14601 				/*
14602 				 * Cancel the timer unless we are still
14603 				 * waiting for an ACK for the FIN packet.
14604 				 */
14605 				if (tcp->tcp_timer_tid != 0 &&
14606 				    tcp->tcp_snxt == tcp->tcp_suna) {
14607 					(void) TCP_TIMER_CANCEL(tcp,
14608 					    tcp->tcp_timer_tid);
14609 					tcp->tcp_timer_tid = 0;
14610 				}
14611 				goto pre_swnd_update;
14612 			}
14613 			if (mp2 != tcp->tcp_xmit_tail)
14614 				break;
14615 			tcp->tcp_xmit_tail = mp1;
14616 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14617 			    (uintptr_t)INT_MAX);
14618 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14619 			    mp1->b_rptr);
14620 			break;
14621 		}
14622 		if (mp1 == NULL) {
14623 			/*
14624 			 * More was acked but there is nothing more
14625 			 * outstanding.  This means that the FIN was
14626 			 * just acked or that we're talking to a clown.
14627 			 */
14628 fin_acked:
14629 			ASSERT(tcp->tcp_fin_sent);
14630 			tcp->tcp_xmit_tail = NULL;
14631 			if (tcp->tcp_fin_sent) {
14632 				/* FIN was acked - making progress */
14633 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14634 				    !tcp->tcp_fin_acked)
14635 					tcp->tcp_ip_forward_progress = B_TRUE;
14636 				tcp->tcp_fin_acked = B_TRUE;
14637 				if (tcp->tcp_linger_tid != 0 &&
14638 				    TCP_TIMER_CANCEL(tcp,
14639 					tcp->tcp_linger_tid) >= 0) {
14640 					tcp_stop_lingering(tcp);
14641 					freemsg(mp);
14642 					mp = NULL;
14643 				}
14644 			} else {
14645 				/*
14646 				 * We should never get here because
14647 				 * we have already checked that the
14648 				 * number of bytes ack'ed should be
14649 				 * smaller than or equal to what we
14650 				 * have sent so far (it is the
14651 				 * acceptability check of the ACK).
14652 				 * We can only get here if the send
14653 				 * queue is corrupted.
14654 				 *
14655 				 * Terminate the connection and
14656 				 * panic the system.  It is better
14657 				 * for us to panic instead of
14658 				 * continuing to avoid other disaster.
14659 				 */
14660 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14661 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14662 				panic("Memory corruption "
14663 				    "detected for connection %s.",
14664 				    tcp_display(tcp, NULL,
14665 					DISP_ADDR_AND_PORT));
14666 				/*NOTREACHED*/
14667 			}
14668 			goto pre_swnd_update;
14669 		}
14670 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14671 	}
14672 	if (tcp->tcp_unsent) {
14673 		flags |= TH_XMIT_NEEDED;
14674 	}
14675 pre_swnd_update:
14676 	tcp->tcp_xmit_head = mp1;
14677 swnd_update:
14678 	/*
14679 	 * The following check is different from most other implementations.
14680 	 * For bi-directional transfer, when segments are dropped, the
14681 	 * "normal" check will not accept a window update in those
14682 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14683 	 * segments which are outside receiver's window.  As TCP accepts
14684 	 * the ack in those retransmitted segments, if the window update in
14685 	 * the same segment is not accepted, TCP will incorrectly calculates
14686 	 * that it can send more segments.  This can create a deadlock
14687 	 * with the receiver if its window becomes zero.
14688 	 */
14689 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14690 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14691 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14692 		/*
14693 		 * The criteria for update is:
14694 		 *
14695 		 * 1. the segment acknowledges some data.  Or
14696 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14697 		 * 3. the segment is not old and the advertised window is
14698 		 * larger than the previous advertised window.
14699 		 */
14700 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14701 			flags |= TH_XMIT_NEEDED;
14702 		tcp->tcp_swnd = new_swnd;
14703 		if (new_swnd > tcp->tcp_max_swnd)
14704 			tcp->tcp_max_swnd = new_swnd;
14705 		tcp->tcp_swl1 = seg_seq;
14706 		tcp->tcp_swl2 = seg_ack;
14707 	}
14708 est:
14709 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14710 
14711 		switch (tcp->tcp_state) {
14712 		case TCPS_FIN_WAIT_1:
14713 			if (tcp->tcp_fin_acked) {
14714 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14715 				/*
14716 				 * We implement the non-standard BSD/SunOS
14717 				 * FIN_WAIT_2 flushing algorithm.
14718 				 * If there is no user attached to this
14719 				 * TCP endpoint, then this TCP struct
14720 				 * could hang around forever in FIN_WAIT_2
14721 				 * state if the peer forgets to send us
14722 				 * a FIN.  To prevent this, we wait only
14723 				 * 2*MSL (a convenient time value) for
14724 				 * the FIN to arrive.  If it doesn't show up,
14725 				 * we flush the TCP endpoint.  This algorithm,
14726 				 * though a violation of RFC-793, has worked
14727 				 * for over 10 years in BSD systems.
14728 				 * Note: SunOS 4.x waits 675 seconds before
14729 				 * flushing the FIN_WAIT_2 connection.
14730 				 */
14731 				TCP_TIMER_RESTART(tcp,
14732 				    tcps->tcps_fin_wait_2_flush_interval);
14733 			}
14734 			break;
14735 		case TCPS_FIN_WAIT_2:
14736 			break;	/* Shutdown hook? */
14737 		case TCPS_LAST_ACK:
14738 			freemsg(mp);
14739 			if (tcp->tcp_fin_acked) {
14740 				(void) tcp_clean_death(tcp, 0, 19);
14741 				return;
14742 			}
14743 			goto xmit_check;
14744 		case TCPS_CLOSING:
14745 			if (tcp->tcp_fin_acked) {
14746 				tcp->tcp_state = TCPS_TIME_WAIT;
14747 				/*
14748 				 * Unconditionally clear the exclusive binding
14749 				 * bit so this TIME-WAIT connection won't
14750 				 * interfere with new ones.
14751 				 */
14752 				tcp->tcp_exclbind = 0;
14753 				if (!TCP_IS_DETACHED(tcp)) {
14754 					TCP_TIMER_RESTART(tcp,
14755 					    tcps->tcps_time_wait_interval);
14756 				} else {
14757 					tcp_time_wait_append(tcp);
14758 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14759 				}
14760 			}
14761 			/*FALLTHRU*/
14762 		case TCPS_CLOSE_WAIT:
14763 			freemsg(mp);
14764 			goto xmit_check;
14765 		default:
14766 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14767 			break;
14768 		}
14769 	}
14770 	if (flags & TH_FIN) {
14771 		/* Make sure we ack the fin */
14772 		flags |= TH_ACK_NEEDED;
14773 		if (!tcp->tcp_fin_rcvd) {
14774 			tcp->tcp_fin_rcvd = B_TRUE;
14775 			tcp->tcp_rnxt++;
14776 			tcph = tcp->tcp_tcph;
14777 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14778 
14779 			/*
14780 			 * Generate the ordrel_ind at the end unless we
14781 			 * are an eager guy.
14782 			 * In the eager case tcp_rsrv will do this when run
14783 			 * after tcp_accept is done.
14784 			 */
14785 			if (tcp->tcp_listener == NULL &&
14786 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14787 				flags |= TH_ORDREL_NEEDED;
14788 			switch (tcp->tcp_state) {
14789 			case TCPS_SYN_RCVD:
14790 			case TCPS_ESTABLISHED:
14791 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14792 				/* Keepalive? */
14793 				break;
14794 			case TCPS_FIN_WAIT_1:
14795 				if (!tcp->tcp_fin_acked) {
14796 					tcp->tcp_state = TCPS_CLOSING;
14797 					break;
14798 				}
14799 				/* FALLTHRU */
14800 			case TCPS_FIN_WAIT_2:
14801 				tcp->tcp_state = TCPS_TIME_WAIT;
14802 				/*
14803 				 * Unconditionally clear the exclusive binding
14804 				 * bit so this TIME-WAIT connection won't
14805 				 * interfere with new ones.
14806 				 */
14807 				tcp->tcp_exclbind = 0;
14808 				if (!TCP_IS_DETACHED(tcp)) {
14809 					TCP_TIMER_RESTART(tcp,
14810 					    tcps->tcps_time_wait_interval);
14811 				} else {
14812 					tcp_time_wait_append(tcp);
14813 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14814 				}
14815 				if (seg_len) {
14816 					/*
14817 					 * implies data piggybacked on FIN.
14818 					 * break to handle data.
14819 					 */
14820 					break;
14821 				}
14822 				freemsg(mp);
14823 				goto ack_check;
14824 			}
14825 		}
14826 	}
14827 	if (mp == NULL)
14828 		goto xmit_check;
14829 	if (seg_len == 0) {
14830 		freemsg(mp);
14831 		goto xmit_check;
14832 	}
14833 	if (mp->b_rptr == mp->b_wptr) {
14834 		/*
14835 		 * The header has been consumed, so we remove the
14836 		 * zero-length mblk here.
14837 		 */
14838 		mp1 = mp;
14839 		mp = mp->b_cont;
14840 		freeb(mp1);
14841 	}
14842 	tcph = tcp->tcp_tcph;
14843 	tcp->tcp_rack_cnt++;
14844 	{
14845 		uint32_t cur_max;
14846 
14847 		cur_max = tcp->tcp_rack_cur_max;
14848 		if (tcp->tcp_rack_cnt >= cur_max) {
14849 			/*
14850 			 * We have more unacked data than we should - send
14851 			 * an ACK now.
14852 			 */
14853 			flags |= TH_ACK_NEEDED;
14854 			cur_max++;
14855 			if (cur_max > tcp->tcp_rack_abs_max)
14856 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14857 			else
14858 				tcp->tcp_rack_cur_max = cur_max;
14859 		} else if (TCP_IS_DETACHED(tcp)) {
14860 			/* We don't have an ACK timer for detached TCP. */
14861 			flags |= TH_ACK_NEEDED;
14862 		} else if (seg_len < mss) {
14863 			/*
14864 			 * If we get a segment that is less than an mss, and we
14865 			 * already have unacknowledged data, and the amount
14866 			 * unacknowledged is not a multiple of mss, then we
14867 			 * better generate an ACK now.  Otherwise, this may be
14868 			 * the tail piece of a transaction, and we would rather
14869 			 * wait for the response.
14870 			 */
14871 			uint32_t udif;
14872 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14873 			    (uintptr_t)INT_MAX);
14874 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14875 			if (udif && (udif % mss))
14876 				flags |= TH_ACK_NEEDED;
14877 			else
14878 				flags |= TH_ACK_TIMER_NEEDED;
14879 		} else {
14880 			/* Start delayed ack timer */
14881 			flags |= TH_ACK_TIMER_NEEDED;
14882 		}
14883 	}
14884 	tcp->tcp_rnxt += seg_len;
14885 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14886 
14887 	/* Update SACK list */
14888 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14889 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14890 		    &(tcp->tcp_num_sack_blk));
14891 	}
14892 
14893 	if (tcp->tcp_urp_mp) {
14894 		tcp->tcp_urp_mp->b_cont = mp;
14895 		mp = tcp->tcp_urp_mp;
14896 		tcp->tcp_urp_mp = NULL;
14897 		/* Ready for a new signal. */
14898 		tcp->tcp_urp_last_valid = B_FALSE;
14899 #ifdef DEBUG
14900 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14901 		    "tcp_rput: sending exdata_ind %s",
14902 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14903 #endif /* DEBUG */
14904 	}
14905 
14906 	/*
14907 	 * Check for ancillary data changes compared to last segment.
14908 	 */
14909 	if (tcp->tcp_ipv6_recvancillary != 0) {
14910 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14911 		if (mp == NULL)
14912 			return;
14913 	}
14914 
14915 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14916 		/*
14917 		 * Side queue inbound data until the accept happens.
14918 		 * tcp_accept/tcp_rput drains this when the accept happens.
14919 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14920 		 * T_EXDATA_IND) it is queued on b_next.
14921 		 * XXX Make urgent data use this. Requires:
14922 		 *	Removing tcp_listener check for TH_URG
14923 		 *	Making M_PCPROTO and MARK messages skip the eager case
14924 		 */
14925 
14926 		if (tcp->tcp_kssl_pending) {
14927 			tcp_kssl_input(tcp, mp);
14928 		} else {
14929 			tcp_rcv_enqueue(tcp, mp, seg_len);
14930 		}
14931 	} else {
14932 		if (mp->b_datap->db_type != M_DATA ||
14933 		    (flags & TH_MARKNEXT_NEEDED)) {
14934 			if (tcp->tcp_rcv_list != NULL) {
14935 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14936 			}
14937 			ASSERT(tcp->tcp_rcv_list == NULL ||
14938 			    tcp->tcp_fused_sigurg);
14939 			if (flags & TH_MARKNEXT_NEEDED) {
14940 #ifdef DEBUG
14941 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14942 				    "tcp_rput: sending MSGMARKNEXT %s",
14943 				    tcp_display(tcp, NULL,
14944 				    DISP_PORT_ONLY));
14945 #endif /* DEBUG */
14946 				mp->b_flag |= MSGMARKNEXT;
14947 				flags &= ~TH_MARKNEXT_NEEDED;
14948 			}
14949 
14950 			/* Does this need SSL processing first? */
14951 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14952 			    (DB_TYPE(mp) == M_DATA)) {
14953 				tcp_kssl_input(tcp, mp);
14954 			} else {
14955 				putnext(tcp->tcp_rq, mp);
14956 				if (!canputnext(tcp->tcp_rq))
14957 					tcp->tcp_rwnd -= seg_len;
14958 			}
14959 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14960 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14961 			if (tcp->tcp_rcv_list != NULL) {
14962 				/*
14963 				 * Enqueue the new segment first and then
14964 				 * call tcp_rcv_drain() to send all data
14965 				 * up.  The other way to do this is to
14966 				 * send all queued data up and then call
14967 				 * putnext() to send the new segment up.
14968 				 * This way can remove the else part later
14969 				 * on.
14970 				 *
14971 				 * We don't this to avoid one more call to
14972 				 * canputnext() as tcp_rcv_drain() needs to
14973 				 * call canputnext().
14974 				 */
14975 				tcp_rcv_enqueue(tcp, mp, seg_len);
14976 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14977 			} else {
14978 				/* Does this need SSL processing first? */
14979 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14980 				    (DB_TYPE(mp) == M_DATA)) {
14981 					tcp_kssl_input(tcp, mp);
14982 				} else {
14983 					putnext(tcp->tcp_rq, mp);
14984 					if (!canputnext(tcp->tcp_rq))
14985 						tcp->tcp_rwnd -= seg_len;
14986 				}
14987 			}
14988 		} else {
14989 			/*
14990 			 * Enqueue all packets when processing an mblk
14991 			 * from the co queue and also enqueue normal packets.
14992 			 * For packets which belong to SSL stream do SSL
14993 			 * processing first.
14994 			 */
14995 			if ((tcp->tcp_kssl_ctx != NULL) &&
14996 			    (DB_TYPE(mp) == M_DATA)) {
14997 				tcp_kssl_input(tcp, mp);
14998 			} else {
14999 				tcp_rcv_enqueue(tcp, mp, seg_len);
15000 			}
15001 		}
15002 		/*
15003 		 * Make sure the timer is running if we have data waiting
15004 		 * for a push bit. This provides resiliency against
15005 		 * implementations that do not correctly generate push bits.
15006 		 */
15007 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
15008 			/*
15009 			 * The connection may be closed at this point, so don't
15010 			 * do anything for a detached tcp.
15011 			 */
15012 			if (!TCP_IS_DETACHED(tcp))
15013 			    tcp->tcp_push_tid = TCP_TIMER(tcp,
15014 				tcp_push_timer,
15015 				MSEC_TO_TICK(tcps->tcps_push_timer_interval));
15016 		}
15017 	}
15018 xmit_check:
15019 	/* Is there anything left to do? */
15020 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15021 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15022 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15023 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15024 		goto done;
15025 
15026 	/* Any transmit work to do and a non-zero window? */
15027 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15028 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15029 		if (flags & TH_REXMIT_NEEDED) {
15030 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15031 
15032 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15033 			if (snd_size > mss)
15034 				snd_size = mss;
15035 			if (snd_size > tcp->tcp_swnd)
15036 				snd_size = tcp->tcp_swnd;
15037 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15038 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15039 			    B_TRUE);
15040 
15041 			if (mp1 != NULL) {
15042 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15043 				tcp->tcp_csuna = tcp->tcp_snxt;
15044 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15045 				UPDATE_MIB(&tcps->tcps_mib,
15046 				    tcpRetransBytes, snd_size);
15047 				TCP_RECORD_TRACE(tcp, mp1,
15048 				    TCP_TRACE_SEND_PKT);
15049 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15050 			}
15051 		}
15052 		if (flags & TH_NEED_SACK_REXMIT) {
15053 			tcp_sack_rxmit(tcp, &flags);
15054 		}
15055 		/*
15056 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15057 		 * out new segment.  Note that tcp_rexmit should not be
15058 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15059 		 */
15060 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15061 			if (!tcp->tcp_rexmit) {
15062 				tcp_wput_data(tcp, NULL, B_FALSE);
15063 			} else {
15064 				tcp_ss_rexmit(tcp);
15065 			}
15066 		}
15067 		/*
15068 		 * Adjust tcp_cwnd back to normal value after sending
15069 		 * new data segments.
15070 		 */
15071 		if (flags & TH_LIMIT_XMIT) {
15072 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15073 			/*
15074 			 * This will restart the timer.  Restarting the
15075 			 * timer is used to avoid a timeout before the
15076 			 * limited transmitted segment's ACK gets back.
15077 			 */
15078 			if (tcp->tcp_xmit_head != NULL)
15079 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15080 		}
15081 
15082 		/* Anything more to do? */
15083 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15084 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15085 			goto done;
15086 	}
15087 ack_check:
15088 	if (flags & TH_SEND_URP_MARK) {
15089 		ASSERT(tcp->tcp_urp_mark_mp);
15090 		/*
15091 		 * Send up any queued data and then send the mark message
15092 		 */
15093 		if (tcp->tcp_rcv_list != NULL) {
15094 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15095 		}
15096 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15097 
15098 		mp1 = tcp->tcp_urp_mark_mp;
15099 		tcp->tcp_urp_mark_mp = NULL;
15100 #ifdef DEBUG
15101 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15102 		    "tcp_rput: sending zero-length %s %s",
15103 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15104 		    "MSGNOTMARKNEXT"),
15105 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15106 #endif /* DEBUG */
15107 		putnext(tcp->tcp_rq, mp1);
15108 		flags &= ~TH_SEND_URP_MARK;
15109 	}
15110 	if (flags & TH_ACK_NEEDED) {
15111 		/*
15112 		 * Time to send an ack for some reason.
15113 		 */
15114 		mp1 = tcp_ack_mp(tcp);
15115 
15116 		if (mp1 != NULL) {
15117 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15118 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15119 			BUMP_LOCAL(tcp->tcp_obsegs);
15120 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15121 		}
15122 		if (tcp->tcp_ack_tid != 0) {
15123 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15124 			tcp->tcp_ack_tid = 0;
15125 		}
15126 	}
15127 	if (flags & TH_ACK_TIMER_NEEDED) {
15128 		/*
15129 		 * Arrange for deferred ACK or push wait timeout.
15130 		 * Start timer if it is not already running.
15131 		 */
15132 		if (tcp->tcp_ack_tid == 0) {
15133 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15134 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15135 			    (clock_t)tcps->tcps_local_dack_interval :
15136 			    (clock_t)tcps->tcps_deferred_ack_interval));
15137 		}
15138 	}
15139 	if (flags & TH_ORDREL_NEEDED) {
15140 		/*
15141 		 * Send up the ordrel_ind unless we are an eager guy.
15142 		 * In the eager case tcp_rsrv will do this when run
15143 		 * after tcp_accept is done.
15144 		 */
15145 		ASSERT(tcp->tcp_listener == NULL);
15146 		if (tcp->tcp_rcv_list != NULL) {
15147 			/*
15148 			 * Push any mblk(s) enqueued from co processing.
15149 			 */
15150 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15151 		}
15152 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15153 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15154 			tcp->tcp_ordrel_done = B_TRUE;
15155 			putnext(tcp->tcp_rq, mp1);
15156 			if (tcp->tcp_deferred_clean_death) {
15157 				/*
15158 				 * tcp_clean_death was deferred
15159 				 * for T_ORDREL_IND - do it now
15160 				 */
15161 				(void) tcp_clean_death(tcp,
15162 				    tcp->tcp_client_errno, 20);
15163 				tcp->tcp_deferred_clean_death =	B_FALSE;
15164 			}
15165 		} else {
15166 			/*
15167 			 * Run the orderly release in the
15168 			 * service routine.
15169 			 */
15170 			qenable(tcp->tcp_rq);
15171 			/*
15172 			 * Caveat(XXX): The machine may be so
15173 			 * overloaded that tcp_rsrv() is not scheduled
15174 			 * until after the endpoint has transitioned
15175 			 * to TCPS_TIME_WAIT
15176 			 * and tcp_time_wait_interval expires. Then
15177 			 * tcp_timer() will blow away state in tcp_t
15178 			 * and T_ORDREL_IND will never be delivered
15179 			 * upstream. Unlikely but potentially
15180 			 * a problem.
15181 			 */
15182 		}
15183 	}
15184 done:
15185 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15186 }
15187 
15188 /*
15189  * This function does PAWS protection check. Returns B_TRUE if the
15190  * segment passes the PAWS test, else returns B_FALSE.
15191  */
15192 boolean_t
15193 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15194 {
15195 	uint8_t	flags;
15196 	int	options;
15197 	uint8_t *up;
15198 
15199 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15200 	/*
15201 	 * If timestamp option is aligned nicely, get values inline,
15202 	 * otherwise call general routine to parse.  Only do that
15203 	 * if timestamp is the only option.
15204 	 */
15205 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15206 	    TCPOPT_REAL_TS_LEN &&
15207 	    OK_32PTR((up = ((uint8_t *)tcph) +
15208 	    TCP_MIN_HEADER_LENGTH)) &&
15209 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15210 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15211 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15212 
15213 		options = TCP_OPT_TSTAMP_PRESENT;
15214 	} else {
15215 		if (tcp->tcp_snd_sack_ok) {
15216 			tcpoptp->tcp = tcp;
15217 		} else {
15218 			tcpoptp->tcp = NULL;
15219 		}
15220 		options = tcp_parse_options(tcph, tcpoptp);
15221 	}
15222 
15223 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15224 		/*
15225 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15226 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15227 		 */
15228 		if ((flags & TH_RST) == 0 &&
15229 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15230 		    tcp->tcp_ts_recent)) {
15231 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15232 			    PAWS_TIMEOUT)) {
15233 				/* This segment is not acceptable. */
15234 				return (B_FALSE);
15235 			} else {
15236 				/*
15237 				 * Connection has been idle for
15238 				 * too long.  Reset the timestamp
15239 				 * and assume the segment is valid.
15240 				 */
15241 				tcp->tcp_ts_recent =
15242 				    tcpoptp->tcp_opt_ts_val;
15243 			}
15244 		}
15245 	} else {
15246 		/*
15247 		 * If we don't get a timestamp on every packet, we
15248 		 * figure we can't really trust 'em, so we stop sending
15249 		 * and parsing them.
15250 		 */
15251 		tcp->tcp_snd_ts_ok = B_FALSE;
15252 
15253 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15254 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15255 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15256 		/*
15257 		 * Adjust the tcp_mss accordingly. We also need to
15258 		 * adjust tcp_cwnd here in accordance with the new mss.
15259 		 * But we avoid doing a slow start here so as to not
15260 		 * to lose on the transfer rate built up so far.
15261 		 */
15262 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15263 		if (tcp->tcp_snd_sack_ok) {
15264 			ASSERT(tcp->tcp_sack_info != NULL);
15265 			tcp->tcp_max_sack_blk = 4;
15266 		}
15267 	}
15268 	return (B_TRUE);
15269 }
15270 
15271 /*
15272  * Attach ancillary data to a received TCP segments for the
15273  * ancillary pieces requested by the application that are
15274  * different than they were in the previous data segment.
15275  *
15276  * Save the "current" values once memory allocation is ok so that
15277  * when memory allocation fails we can just wait for the next data segment.
15278  */
15279 static mblk_t *
15280 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15281 {
15282 	struct T_optdata_ind *todi;
15283 	int optlen;
15284 	uchar_t *optptr;
15285 	struct T_opthdr *toh;
15286 	uint_t addflag;	/* Which pieces to add */
15287 	mblk_t *mp1;
15288 
15289 	optlen = 0;
15290 	addflag = 0;
15291 	/* If app asked for pktinfo and the index has changed ... */
15292 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15293 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15294 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15295 		optlen += sizeof (struct T_opthdr) +
15296 		    sizeof (struct in6_pktinfo);
15297 		addflag |= TCP_IPV6_RECVPKTINFO;
15298 	}
15299 	/* If app asked for hoplimit and it has changed ... */
15300 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15301 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15302 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15303 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15304 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15305 	}
15306 	/* If app asked for tclass and it has changed ... */
15307 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15308 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15309 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15310 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15311 		addflag |= TCP_IPV6_RECVTCLASS;
15312 	}
15313 	/*
15314 	 * If app asked for hopbyhop headers and it has changed ...
15315 	 * For security labels, note that (1) security labels can't change on
15316 	 * a connected socket at all, (2) we're connected to at most one peer,
15317 	 * (3) if anything changes, then it must be some other extra option.
15318 	 */
15319 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15320 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15321 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15322 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15323 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15324 		    tcp->tcp_label_len;
15325 		addflag |= TCP_IPV6_RECVHOPOPTS;
15326 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15327 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15328 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15329 			return (mp);
15330 	}
15331 	/* If app asked for dst headers before routing headers ... */
15332 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15333 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15334 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15335 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15336 		optlen += sizeof (struct T_opthdr) +
15337 		    ipp->ipp_rtdstoptslen;
15338 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15339 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15340 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15341 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15342 			return (mp);
15343 	}
15344 	/* If app asked for routing headers and it has changed ... */
15345 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15346 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15347 	    (ipp->ipp_fields & IPPF_RTHDR),
15348 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15349 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15350 		addflag |= TCP_IPV6_RECVRTHDR;
15351 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15352 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15353 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15354 			return (mp);
15355 	}
15356 	/* If app asked for dest headers and it has changed ... */
15357 	if ((tcp->tcp_ipv6_recvancillary &
15358 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15359 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15360 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15361 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15362 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15363 		addflag |= TCP_IPV6_RECVDSTOPTS;
15364 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15365 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15366 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15367 			return (mp);
15368 	}
15369 
15370 	if (optlen == 0) {
15371 		/* Nothing to add */
15372 		return (mp);
15373 	}
15374 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15375 	if (mp1 == NULL) {
15376 		/*
15377 		 * Defer sending ancillary data until the next TCP segment
15378 		 * arrives.
15379 		 */
15380 		return (mp);
15381 	}
15382 	mp1->b_cont = mp;
15383 	mp = mp1;
15384 	mp->b_wptr += sizeof (*todi) + optlen;
15385 	mp->b_datap->db_type = M_PROTO;
15386 	todi = (struct T_optdata_ind *)mp->b_rptr;
15387 	todi->PRIM_type = T_OPTDATA_IND;
15388 	todi->DATA_flag = 1;	/* MORE data */
15389 	todi->OPT_length = optlen;
15390 	todi->OPT_offset = sizeof (*todi);
15391 	optptr = (uchar_t *)&todi[1];
15392 	/*
15393 	 * If app asked for pktinfo and the index has changed ...
15394 	 * Note that the local address never changes for the connection.
15395 	 */
15396 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15397 		struct in6_pktinfo *pkti;
15398 
15399 		toh = (struct T_opthdr *)optptr;
15400 		toh->level = IPPROTO_IPV6;
15401 		toh->name = IPV6_PKTINFO;
15402 		toh->len = sizeof (*toh) + sizeof (*pkti);
15403 		toh->status = 0;
15404 		optptr += sizeof (*toh);
15405 		pkti = (struct in6_pktinfo *)optptr;
15406 		if (tcp->tcp_ipversion == IPV6_VERSION)
15407 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15408 		else
15409 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15410 			    &pkti->ipi6_addr);
15411 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15412 		optptr += sizeof (*pkti);
15413 		ASSERT(OK_32PTR(optptr));
15414 		/* Save as "last" value */
15415 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15416 	}
15417 	/* If app asked for hoplimit and it has changed ... */
15418 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15419 		toh = (struct T_opthdr *)optptr;
15420 		toh->level = IPPROTO_IPV6;
15421 		toh->name = IPV6_HOPLIMIT;
15422 		toh->len = sizeof (*toh) + sizeof (uint_t);
15423 		toh->status = 0;
15424 		optptr += sizeof (*toh);
15425 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15426 		optptr += sizeof (uint_t);
15427 		ASSERT(OK_32PTR(optptr));
15428 		/* Save as "last" value */
15429 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15430 	}
15431 	/* If app asked for tclass and it has changed ... */
15432 	if (addflag & TCP_IPV6_RECVTCLASS) {
15433 		toh = (struct T_opthdr *)optptr;
15434 		toh->level = IPPROTO_IPV6;
15435 		toh->name = IPV6_TCLASS;
15436 		toh->len = sizeof (*toh) + sizeof (uint_t);
15437 		toh->status = 0;
15438 		optptr += sizeof (*toh);
15439 		*(uint_t *)optptr = ipp->ipp_tclass;
15440 		optptr += sizeof (uint_t);
15441 		ASSERT(OK_32PTR(optptr));
15442 		/* Save as "last" value */
15443 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15444 	}
15445 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15446 		toh = (struct T_opthdr *)optptr;
15447 		toh->level = IPPROTO_IPV6;
15448 		toh->name = IPV6_HOPOPTS;
15449 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15450 		    tcp->tcp_label_len;
15451 		toh->status = 0;
15452 		optptr += sizeof (*toh);
15453 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15454 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15455 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15456 		ASSERT(OK_32PTR(optptr));
15457 		/* Save as last value */
15458 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15459 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15460 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15461 	}
15462 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15463 		toh = (struct T_opthdr *)optptr;
15464 		toh->level = IPPROTO_IPV6;
15465 		toh->name = IPV6_RTHDRDSTOPTS;
15466 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15467 		toh->status = 0;
15468 		optptr += sizeof (*toh);
15469 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15470 		optptr += ipp->ipp_rtdstoptslen;
15471 		ASSERT(OK_32PTR(optptr));
15472 		/* Save as last value */
15473 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15474 		    &tcp->tcp_rtdstoptslen,
15475 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15476 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15477 	}
15478 	if (addflag & TCP_IPV6_RECVRTHDR) {
15479 		toh = (struct T_opthdr *)optptr;
15480 		toh->level = IPPROTO_IPV6;
15481 		toh->name = IPV6_RTHDR;
15482 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15483 		toh->status = 0;
15484 		optptr += sizeof (*toh);
15485 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15486 		optptr += ipp->ipp_rthdrlen;
15487 		ASSERT(OK_32PTR(optptr));
15488 		/* Save as last value */
15489 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15490 		    (ipp->ipp_fields & IPPF_RTHDR),
15491 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15492 	}
15493 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15494 		toh = (struct T_opthdr *)optptr;
15495 		toh->level = IPPROTO_IPV6;
15496 		toh->name = IPV6_DSTOPTS;
15497 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15498 		toh->status = 0;
15499 		optptr += sizeof (*toh);
15500 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15501 		optptr += ipp->ipp_dstoptslen;
15502 		ASSERT(OK_32PTR(optptr));
15503 		/* Save as last value */
15504 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15505 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15506 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15507 	}
15508 	ASSERT(optptr == mp->b_wptr);
15509 	return (mp);
15510 }
15511 
15512 
15513 /*
15514  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15515  * or a "bad" IRE detected by tcp_adapt_ire.
15516  * We can't tell if the failure was due to the laddr or the faddr
15517  * thus we clear out all addresses and ports.
15518  */
15519 static void
15520 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15521 {
15522 	queue_t	*q = tcp->tcp_rq;
15523 	tcph_t	*tcph;
15524 	struct T_error_ack *tea;
15525 	conn_t	*connp = tcp->tcp_connp;
15526 
15527 
15528 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15529 
15530 	if (mp->b_cont) {
15531 		freemsg(mp->b_cont);
15532 		mp->b_cont = NULL;
15533 	}
15534 	tea = (struct T_error_ack *)mp->b_rptr;
15535 	switch (tea->PRIM_type) {
15536 	case T_BIND_ACK:
15537 		/*
15538 		 * Need to unbind with classifier since we were just told that
15539 		 * our bind succeeded.
15540 		 */
15541 		tcp->tcp_hard_bound = B_FALSE;
15542 		tcp->tcp_hard_binding = B_FALSE;
15543 
15544 		ipcl_hash_remove(connp);
15545 		/* Reuse the mblk if possible */
15546 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15547 			sizeof (*tea));
15548 		mp->b_rptr = mp->b_datap->db_base;
15549 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15550 		tea = (struct T_error_ack *)mp->b_rptr;
15551 		tea->PRIM_type = T_ERROR_ACK;
15552 		tea->TLI_error = TSYSERR;
15553 		tea->UNIX_error = error;
15554 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15555 			tea->ERROR_prim = T_CONN_REQ;
15556 		} else {
15557 			tea->ERROR_prim = O_T_BIND_REQ;
15558 		}
15559 		break;
15560 
15561 	case T_ERROR_ACK:
15562 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15563 			tea->ERROR_prim = T_CONN_REQ;
15564 		break;
15565 	default:
15566 		panic("tcp_bind_failed: unexpected TPI type");
15567 		/*NOTREACHED*/
15568 	}
15569 
15570 	tcp->tcp_state = TCPS_IDLE;
15571 	if (tcp->tcp_ipversion == IPV4_VERSION)
15572 		tcp->tcp_ipha->ipha_src = 0;
15573 	else
15574 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15575 	/*
15576 	 * Copy of the src addr. in tcp_t is needed since
15577 	 * the lookup funcs. can only look at tcp_t
15578 	 */
15579 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15580 
15581 	tcph = tcp->tcp_tcph;
15582 	tcph->th_lport[0] = 0;
15583 	tcph->th_lport[1] = 0;
15584 	tcp_bind_hash_remove(tcp);
15585 	bzero(&connp->u_port, sizeof (connp->u_port));
15586 	/* blow away saved option results if any */
15587 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15588 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15589 
15590 	conn_delete_ire(tcp->tcp_connp, NULL);
15591 	putnext(q, mp);
15592 }
15593 
15594 /*
15595  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15596  * messages.
15597  */
15598 void
15599 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15600 {
15601 	mblk_t	*mp1;
15602 	uchar_t	*rptr = mp->b_rptr;
15603 	queue_t	*q = tcp->tcp_rq;
15604 	struct T_error_ack *tea;
15605 	uint32_t mss;
15606 	mblk_t *syn_mp;
15607 	mblk_t *mdti;
15608 	mblk_t *lsoi;
15609 	int	retval;
15610 	mblk_t *ire_mp;
15611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15612 
15613 	switch (mp->b_datap->db_type) {
15614 	case M_PROTO:
15615 	case M_PCPROTO:
15616 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15617 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15618 			break;
15619 		tea = (struct T_error_ack *)rptr;
15620 		switch (tea->PRIM_type) {
15621 		case T_BIND_ACK:
15622 			/*
15623 			 * Adapt Multidata information, if any.  The
15624 			 * following tcp_mdt_update routine will free
15625 			 * the message.
15626 			 */
15627 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15628 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15629 				    b_rptr)->mdt_capab, B_TRUE);
15630 				freemsg(mdti);
15631 			}
15632 
15633 			/*
15634 			 * Check to update LSO information with tcp, and
15635 			 * tcp_lso_update routine will free the message.
15636 			 */
15637 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15638 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15639 				    b_rptr)->lso_capab);
15640 				freemsg(lsoi);
15641 			}
15642 
15643 			/* Get the IRE, if we had requested for it */
15644 			ire_mp = tcp_ire_mp(mp);
15645 
15646 			if (tcp->tcp_hard_binding) {
15647 				tcp->tcp_hard_binding = B_FALSE;
15648 				tcp->tcp_hard_bound = B_TRUE;
15649 				CL_INET_CONNECT(tcp);
15650 			} else {
15651 				if (ire_mp != NULL)
15652 					freeb(ire_mp);
15653 				goto after_syn_sent;
15654 			}
15655 
15656 			retval = tcp_adapt_ire(tcp, ire_mp);
15657 			if (ire_mp != NULL)
15658 				freeb(ire_mp);
15659 			if (retval == 0) {
15660 				tcp_bind_failed(tcp, mp,
15661 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15662 				    ENETUNREACH : EADDRNOTAVAIL));
15663 				return;
15664 			}
15665 			/*
15666 			 * Don't let an endpoint connect to itself.
15667 			 * Also checked in tcp_connect() but that
15668 			 * check can't handle the case when the
15669 			 * local IP address is INADDR_ANY.
15670 			 */
15671 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15672 				if ((tcp->tcp_ipha->ipha_dst ==
15673 				    tcp->tcp_ipha->ipha_src) &&
15674 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15675 				    tcp->tcp_tcph->th_fport))) {
15676 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15677 					return;
15678 				}
15679 			} else {
15680 				if (IN6_ARE_ADDR_EQUAL(
15681 				    &tcp->tcp_ip6h->ip6_dst,
15682 				    &tcp->tcp_ip6h->ip6_src) &&
15683 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15684 				    tcp->tcp_tcph->th_fport))) {
15685 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15686 					return;
15687 				}
15688 			}
15689 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15690 			/*
15691 			 * This should not be possible!  Just for
15692 			 * defensive coding...
15693 			 */
15694 			if (tcp->tcp_state != TCPS_SYN_SENT)
15695 				goto after_syn_sent;
15696 
15697 			if (is_system_labeled() &&
15698 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15699 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15700 				return;
15701 			}
15702 
15703 			ASSERT(q == tcp->tcp_rq);
15704 			/*
15705 			 * tcp_adapt_ire() does not adjust
15706 			 * for TCP/IP header length.
15707 			 */
15708 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15709 
15710 			/*
15711 			 * Just make sure our rwnd is at
15712 			 * least tcp_recv_hiwat_mss * MSS
15713 			 * large, and round up to the nearest
15714 			 * MSS.
15715 			 *
15716 			 * We do the round up here because
15717 			 * we need to get the interface
15718 			 * MTU first before we can do the
15719 			 * round up.
15720 			 */
15721 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15722 			    tcps->tcps_recv_hiwat_minmss * mss);
15723 			q->q_hiwat = tcp->tcp_rwnd;
15724 			tcp_set_ws_value(tcp);
15725 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15726 			    tcp->tcp_tcph->th_win);
15727 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
15728 				tcp->tcp_snd_ws_ok = B_TRUE;
15729 
15730 			/*
15731 			 * Set tcp_snd_ts_ok to true
15732 			 * so that tcp_xmit_mp will
15733 			 * include the timestamp
15734 			 * option in the SYN segment.
15735 			 */
15736 			if (tcps->tcps_tstamp_always ||
15737 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
15738 				tcp->tcp_snd_ts_ok = B_TRUE;
15739 			}
15740 
15741 			/*
15742 			 * tcp_snd_sack_ok can be set in
15743 			 * tcp_adapt_ire() if the sack metric
15744 			 * is set.  So check it here also.
15745 			 */
15746 			if (tcps->tcps_sack_permitted == 2 ||
15747 			    tcp->tcp_snd_sack_ok) {
15748 				if (tcp->tcp_sack_info == NULL) {
15749 					tcp->tcp_sack_info =
15750 					kmem_cache_alloc(tcp_sack_info_cache,
15751 					    KM_SLEEP);
15752 				}
15753 				tcp->tcp_snd_sack_ok = B_TRUE;
15754 			}
15755 
15756 			/*
15757 			 * Should we use ECN?  Note that the current
15758 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15759 			 * is 1.  The reason for doing this is that there
15760 			 * are equipments out there that will drop ECN
15761 			 * enabled IP packets.  Setting it to 1 avoids
15762 			 * compatibility problems.
15763 			 */
15764 			if (tcps->tcps_ecn_permitted == 2)
15765 				tcp->tcp_ecn_ok = B_TRUE;
15766 
15767 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15768 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15769 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15770 			if (syn_mp) {
15771 				cred_t *cr;
15772 				pid_t pid;
15773 
15774 				/*
15775 				 * Obtain the credential from the
15776 				 * thread calling connect(); the credential
15777 				 * lives on in the second mblk which
15778 				 * originated from T_CONN_REQ and is echoed
15779 				 * with the T_BIND_ACK from ip.  If none
15780 				 * can be found, default to the creator
15781 				 * of the socket.
15782 				 */
15783 				if (mp->b_cont == NULL ||
15784 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15785 					cr = tcp->tcp_cred;
15786 					pid = tcp->tcp_cpid;
15787 				} else {
15788 					pid = DB_CPID(mp->b_cont);
15789 				}
15790 
15791 				TCP_RECORD_TRACE(tcp, syn_mp,
15792 				    TCP_TRACE_SEND_PKT);
15793 				mblk_setcred(syn_mp, cr);
15794 				DB_CPID(syn_mp) = pid;
15795 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15796 			}
15797 		after_syn_sent:
15798 			/*
15799 			 * A trailer mblk indicates a waiting client upstream.
15800 			 * We complete here the processing begun in
15801 			 * either tcp_bind() or tcp_connect() by passing
15802 			 * upstream the reply message they supplied.
15803 			 */
15804 			mp1 = mp;
15805 			mp = mp->b_cont;
15806 			freeb(mp1);
15807 			if (mp)
15808 				break;
15809 			return;
15810 		case T_ERROR_ACK:
15811 			if (tcp->tcp_debug) {
15812 				(void) strlog(TCP_MOD_ID, 0, 1,
15813 				    SL_TRACE|SL_ERROR,
15814 				    "tcp_rput_other: case T_ERROR_ACK, "
15815 				    "ERROR_prim == %d",
15816 				    tea->ERROR_prim);
15817 			}
15818 			switch (tea->ERROR_prim) {
15819 			case O_T_BIND_REQ:
15820 			case T_BIND_REQ:
15821 				tcp_bind_failed(tcp, mp,
15822 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15823 				    ENETUNREACH : EADDRNOTAVAIL));
15824 				return;
15825 			case T_UNBIND_REQ:
15826 				tcp->tcp_hard_binding = B_FALSE;
15827 				tcp->tcp_hard_bound = B_FALSE;
15828 				if (mp->b_cont) {
15829 					freemsg(mp->b_cont);
15830 					mp->b_cont = NULL;
15831 				}
15832 				if (tcp->tcp_unbind_pending)
15833 					tcp->tcp_unbind_pending = 0;
15834 				else {
15835 					/* From tcp_ip_unbind() - free */
15836 					freemsg(mp);
15837 					return;
15838 				}
15839 				break;
15840 			case T_SVR4_OPTMGMT_REQ:
15841 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15842 					/* T_OPTMGMT_REQ generated by TCP */
15843 					printf("T_SVR4_OPTMGMT_REQ failed "
15844 					    "%d/%d - dropped (cnt %d)\n",
15845 					    tea->TLI_error, tea->UNIX_error,
15846 					    tcp->tcp_drop_opt_ack_cnt);
15847 					freemsg(mp);
15848 					tcp->tcp_drop_opt_ack_cnt--;
15849 					return;
15850 				}
15851 				break;
15852 			}
15853 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15854 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15855 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15856 				    "- dropped (cnt %d)\n",
15857 				    tea->TLI_error, tea->UNIX_error,
15858 				    tcp->tcp_drop_opt_ack_cnt);
15859 				freemsg(mp);
15860 				tcp->tcp_drop_opt_ack_cnt--;
15861 				return;
15862 			}
15863 			break;
15864 		case T_OPTMGMT_ACK:
15865 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15866 				/* T_OPTMGMT_REQ generated by TCP */
15867 				freemsg(mp);
15868 				tcp->tcp_drop_opt_ack_cnt--;
15869 				return;
15870 			}
15871 			break;
15872 		default:
15873 			break;
15874 		}
15875 		break;
15876 	case M_FLUSH:
15877 		if (*rptr & FLUSHR)
15878 			flushq(q, FLUSHDATA);
15879 		break;
15880 	default:
15881 		/* M_CTL will be directly sent to tcp_icmp_error() */
15882 		ASSERT(DB_TYPE(mp) != M_CTL);
15883 		break;
15884 	}
15885 	/*
15886 	 * Make sure we set this bit before sending the ACK for
15887 	 * bind. Otherwise accept could possibly run and free
15888 	 * this tcp struct.
15889 	 */
15890 	putnext(q, mp);
15891 }
15892 
15893 /*
15894  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15895  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15896  * tcp_rsrv() try again.
15897  */
15898 static void
15899 tcp_ordrel_kick(void *arg)
15900 {
15901 	conn_t 	*connp = (conn_t *)arg;
15902 	tcp_t	*tcp = connp->conn_tcp;
15903 
15904 	tcp->tcp_ordrelid = 0;
15905 	tcp->tcp_timeout = B_FALSE;
15906 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15907 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15908 		qenable(tcp->tcp_rq);
15909 	}
15910 }
15911 
15912 /* ARGSUSED */
15913 static void
15914 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15915 {
15916 	conn_t	*connp = (conn_t *)arg;
15917 	tcp_t	*tcp = connp->conn_tcp;
15918 	queue_t	*q = tcp->tcp_rq;
15919 	uint_t	thwin;
15920 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15921 
15922 	freeb(mp);
15923 
15924 	TCP_STAT(tcps, tcp_rsrv_calls);
15925 
15926 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15927 		return;
15928 	}
15929 
15930 	if (tcp->tcp_fused) {
15931 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15932 
15933 		ASSERT(tcp->tcp_fused);
15934 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15935 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15936 		ASSERT(!TCP_IS_DETACHED(tcp));
15937 		ASSERT(tcp->tcp_connp->conn_sqp ==
15938 		    peer_tcp->tcp_connp->conn_sqp);
15939 
15940 		/*
15941 		 * Normally we would not get backenabled in synchronous
15942 		 * streams mode, but in case this happens, we need to plug
15943 		 * synchronous streams during our drain to prevent a race
15944 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15945 		 */
15946 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15947 		if (tcp->tcp_rcv_list != NULL)
15948 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15949 
15950 		if (peer_tcp > tcp) {
15951 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15952 			mutex_enter(&tcp->tcp_non_sq_lock);
15953 		} else {
15954 			mutex_enter(&tcp->tcp_non_sq_lock);
15955 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15956 		}
15957 
15958 		if (peer_tcp->tcp_flow_stopped &&
15959 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15960 		    peer_tcp->tcp_xmit_lowater)) {
15961 			tcp_clrqfull(peer_tcp);
15962 		}
15963 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15964 		mutex_exit(&tcp->tcp_non_sq_lock);
15965 
15966 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15967 		TCP_STAT(tcps, tcp_fusion_backenabled);
15968 		return;
15969 	}
15970 
15971 	if (canputnext(q)) {
15972 		tcp->tcp_rwnd = q->q_hiwat;
15973 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15974 		    << tcp->tcp_rcv_ws;
15975 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15976 		/*
15977 		 * Send back a window update immediately if TCP is above
15978 		 * ESTABLISHED state and the increase of the rcv window
15979 		 * that the other side knows is at least 1 MSS after flow
15980 		 * control is lifted.
15981 		 */
15982 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15983 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15984 			tcp_xmit_ctl(NULL, tcp,
15985 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15986 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15987 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
15988 		}
15989 	}
15990 	/* Handle a failure to allocate a T_ORDREL_IND here */
15991 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15992 		ASSERT(tcp->tcp_listener == NULL);
15993 		if (tcp->tcp_rcv_list != NULL) {
15994 			(void) tcp_rcv_drain(q, tcp);
15995 		}
15996 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15997 		mp = mi_tpi_ordrel_ind();
15998 		if (mp) {
15999 			tcp->tcp_ordrel_done = B_TRUE;
16000 			putnext(q, mp);
16001 			if (tcp->tcp_deferred_clean_death) {
16002 				/*
16003 				 * tcp_clean_death was deferred for
16004 				 * T_ORDREL_IND - do it now
16005 				 */
16006 				tcp->tcp_deferred_clean_death = B_FALSE;
16007 				(void) tcp_clean_death(tcp,
16008 				    tcp->tcp_client_errno, 22);
16009 			}
16010 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16011 			/*
16012 			 * If there isn't already a timer running
16013 			 * start one.  Use a 4 second
16014 			 * timer as a fallback since it can't fail.
16015 			 */
16016 			tcp->tcp_timeout = B_TRUE;
16017 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16018 			    MSEC_TO_TICK(4000));
16019 		}
16020 	}
16021 }
16022 
16023 /*
16024  * The read side service routine is called mostly when we get back-enabled as a
16025  * result of flow control relief.  Since we don't actually queue anything in
16026  * TCP, we have no data to send out of here.  What we do is clear the receive
16027  * window, and send out a window update.
16028  * This routine is also called to drive an orderly release message upstream
16029  * if the attempt in tcp_rput failed.
16030  */
16031 static void
16032 tcp_rsrv(queue_t *q)
16033 {
16034 	conn_t *connp = Q_TO_CONN(q);
16035 	tcp_t	*tcp = connp->conn_tcp;
16036 	mblk_t	*mp;
16037 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16038 
16039 	/* No code does a putq on the read side */
16040 	ASSERT(q->q_first == NULL);
16041 
16042 	/* Nothing to do for the default queue */
16043 	if (q == tcps->tcps_g_q) {
16044 		return;
16045 	}
16046 
16047 	mp = allocb(0, BPRI_HI);
16048 	if (mp == NULL) {
16049 		/*
16050 		 * We are under memory pressure. Return for now and we
16051 		 * we will be called again later.
16052 		 */
16053 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16054 			/*
16055 			 * If there isn't already a timer running
16056 			 * start one.  Use a 4 second
16057 			 * timer as a fallback since it can't fail.
16058 			 */
16059 			tcp->tcp_timeout = B_TRUE;
16060 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16061 			    MSEC_TO_TICK(4000));
16062 		}
16063 		return;
16064 	}
16065 	CONN_INC_REF(connp);
16066 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16067 	    SQTAG_TCP_RSRV);
16068 }
16069 
16070 /*
16071  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16072  * We do not allow the receive window to shrink.  After setting rwnd,
16073  * set the flow control hiwat of the stream.
16074  *
16075  * This function is called in 2 cases:
16076  *
16077  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16078  *    connection (passive open) and in tcp_rput_data() for active connect.
16079  *    This is called after tcp_mss_set() when the desired MSS value is known.
16080  *    This makes sure that our window size is a mutiple of the other side's
16081  *    MSS.
16082  * 2) Handling SO_RCVBUF option.
16083  *
16084  * It is ASSUMED that the requested size is a multiple of the current MSS.
16085  *
16086  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16087  * user requests so.
16088  */
16089 static int
16090 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16091 {
16092 	uint32_t	mss = tcp->tcp_mss;
16093 	uint32_t	old_max_rwnd;
16094 	uint32_t	max_transmittable_rwnd;
16095 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16096 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16097 
16098 	if (tcp->tcp_fused) {
16099 		size_t sth_hiwat;
16100 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16101 
16102 		ASSERT(peer_tcp != NULL);
16103 		/*
16104 		 * Record the stream head's high water mark for
16105 		 * this endpoint; this is used for flow-control
16106 		 * purposes in tcp_fuse_output().
16107 		 */
16108 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16109 		if (!tcp_detached)
16110 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16111 
16112 		/*
16113 		 * In the fusion case, the maxpsz stream head value of
16114 		 * our peer is set according to its send buffer size
16115 		 * and our receive buffer size; since the latter may
16116 		 * have changed we need to update the peer's maxpsz.
16117 		 */
16118 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16119 		return (rwnd);
16120 	}
16121 
16122 	if (tcp_detached)
16123 		old_max_rwnd = tcp->tcp_rwnd;
16124 	else
16125 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16126 
16127 	/*
16128 	 * Insist on a receive window that is at least
16129 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16130 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16131 	 * and delayed acknowledgement.
16132 	 */
16133 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16134 
16135 	/*
16136 	 * If window size info has already been exchanged, TCP should not
16137 	 * shrink the window.  Shrinking window is doable if done carefully.
16138 	 * We may add that support later.  But so far there is not a real
16139 	 * need to do that.
16140 	 */
16141 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16142 		/* MSS may have changed, do a round up again. */
16143 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16144 	}
16145 
16146 	/*
16147 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16148 	 * can be applied even before the window scale option is decided.
16149 	 */
16150 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16151 	if (rwnd > max_transmittable_rwnd) {
16152 		rwnd = max_transmittable_rwnd -
16153 		    (max_transmittable_rwnd % mss);
16154 		if (rwnd < mss)
16155 			rwnd = max_transmittable_rwnd;
16156 		/*
16157 		 * If we're over the limit we may have to back down tcp_rwnd.
16158 		 * The increment below won't work for us. So we set all three
16159 		 * here and the increment below will have no effect.
16160 		 */
16161 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16162 	}
16163 	if (tcp->tcp_localnet) {
16164 		tcp->tcp_rack_abs_max =
16165 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16166 	} else {
16167 		/*
16168 		 * For a remote host on a different subnet (through a router),
16169 		 * we ack every other packet to be conforming to RFC1122.
16170 		 * tcp_deferred_acks_max is default to 2.
16171 		 */
16172 		tcp->tcp_rack_abs_max =
16173 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16174 	}
16175 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16176 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16177 	else
16178 		tcp->tcp_rack_cur_max = 0;
16179 	/*
16180 	 * Increment the current rwnd by the amount the maximum grew (we
16181 	 * can not overwrite it since we might be in the middle of a
16182 	 * connection.)
16183 	 */
16184 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16185 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16186 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16187 		tcp->tcp_cwnd_max = rwnd;
16188 
16189 	if (tcp_detached)
16190 		return (rwnd);
16191 	/*
16192 	 * We set the maximum receive window into rq->q_hiwat.
16193 	 * This is not actually used for flow control.
16194 	 */
16195 	tcp->tcp_rq->q_hiwat = rwnd;
16196 	/*
16197 	 * Set the Stream head high water mark. This doesn't have to be
16198 	 * here, since we are simply using default values, but we would
16199 	 * prefer to choose these values algorithmically, with a likely
16200 	 * relationship to rwnd.
16201 	 */
16202 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16203 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16204 	return (rwnd);
16205 }
16206 
16207 /*
16208  * Return SNMP stuff in buffer in mpdata.
16209  */
16210 int
16211 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16212 {
16213 	mblk_t			*mpdata;
16214 	mblk_t			*mp_conn_ctl = NULL;
16215 	mblk_t			*mp_conn_tail;
16216 	mblk_t			*mp_attr_ctl = NULL;
16217 	mblk_t			*mp_attr_tail;
16218 	mblk_t			*mp6_conn_ctl = NULL;
16219 	mblk_t			*mp6_conn_tail;
16220 	mblk_t			*mp6_attr_ctl = NULL;
16221 	mblk_t			*mp6_attr_tail;
16222 	struct opthdr		*optp;
16223 	mib2_tcpConnEntry_t	tce;
16224 	mib2_tcp6ConnEntry_t	tce6;
16225 	mib2_transportMLPEntry_t mlp;
16226 	connf_t			*connfp;
16227 	conn_t			*connp;
16228 	int			i;
16229 	boolean_t 		ispriv;
16230 	zoneid_t 		zoneid;
16231 	int			v4_conn_idx;
16232 	int			v6_conn_idx;
16233 	tcp_stack_t		*tcps = Q_TO_TCP(q)->tcp_tcps;
16234 	ip_stack_t	*ipst;
16235 
16236 	if (mpctl == NULL ||
16237 	    (mpdata = mpctl->b_cont) == NULL ||
16238 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16239 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16240 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16241 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16242 		freemsg(mp_conn_ctl);
16243 		freemsg(mp_attr_ctl);
16244 		freemsg(mp6_conn_ctl);
16245 		freemsg(mp6_attr_ctl);
16246 		return (0);
16247 	}
16248 
16249 	/* build table of connections -- need count in fixed part */
16250 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16251 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16252 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16253 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16254 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16255 
16256 	ispriv =
16257 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16258 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16259 
16260 	v4_conn_idx = v6_conn_idx = 0;
16261 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16262 
16263 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16264 		ipst = tcps->tcps_netstack->netstack_ip;
16265 
16266 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16267 
16268 		connp = NULL;
16269 
16270 		while ((connp =
16271 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16272 			tcp_t *tcp;
16273 			boolean_t needattr;
16274 
16275 			if (connp->conn_zoneid != zoneid)
16276 				continue;	/* not in this zone */
16277 
16278 			tcp = connp->conn_tcp;
16279 			UPDATE_MIB(&tcps->tcps_mib,
16280 			    tcpHCInSegs, tcp->tcp_ibsegs);
16281 			tcp->tcp_ibsegs = 0;
16282 			UPDATE_MIB(&tcps->tcps_mib,
16283 			    tcpHCOutSegs, tcp->tcp_obsegs);
16284 			tcp->tcp_obsegs = 0;
16285 
16286 			tce6.tcp6ConnState = tce.tcpConnState =
16287 			    tcp_snmp_state(tcp);
16288 			if (tce.tcpConnState == MIB2_TCP_established ||
16289 			    tce.tcpConnState == MIB2_TCP_closeWait)
16290 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16291 
16292 			needattr = B_FALSE;
16293 			bzero(&mlp, sizeof (mlp));
16294 			if (connp->conn_mlp_type != mlptSingle) {
16295 				if (connp->conn_mlp_type == mlptShared ||
16296 				    connp->conn_mlp_type == mlptBoth)
16297 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16298 				if (connp->conn_mlp_type == mlptPrivate ||
16299 				    connp->conn_mlp_type == mlptBoth)
16300 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16301 				needattr = B_TRUE;
16302 			}
16303 			if (connp->conn_peercred != NULL) {
16304 				ts_label_t *tsl;
16305 
16306 				tsl = crgetlabel(connp->conn_peercred);
16307 				mlp.tme_doi = label2doi(tsl);
16308 				mlp.tme_label = *label2bslabel(tsl);
16309 				needattr = B_TRUE;
16310 			}
16311 
16312 			/* Create a message to report on IPv6 entries */
16313 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16314 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16315 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16316 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16317 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16318 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16319 			/* Don't want just anybody seeing these... */
16320 			if (ispriv) {
16321 				tce6.tcp6ConnEntryInfo.ce_snxt =
16322 				    tcp->tcp_snxt;
16323 				tce6.tcp6ConnEntryInfo.ce_suna =
16324 				    tcp->tcp_suna;
16325 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16326 				    tcp->tcp_rnxt;
16327 				tce6.tcp6ConnEntryInfo.ce_rack =
16328 				    tcp->tcp_rack;
16329 			} else {
16330 				/*
16331 				 * Netstat, unfortunately, uses this to
16332 				 * get send/receive queue sizes.  How to fix?
16333 				 * Why not compute the difference only?
16334 				 */
16335 				tce6.tcp6ConnEntryInfo.ce_snxt =
16336 				    tcp->tcp_snxt - tcp->tcp_suna;
16337 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16338 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16339 				    tcp->tcp_rnxt - tcp->tcp_rack;
16340 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16341 			}
16342 
16343 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16344 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16345 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16346 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16347 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16348 
16349 			tce6.tcp6ConnCreationProcess =
16350 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16351 			    tcp->tcp_cpid;
16352 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16353 
16354 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16355 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16356 
16357 			mlp.tme_connidx = v6_conn_idx++;
16358 			if (needattr)
16359 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16360 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16361 			}
16362 			/*
16363 			 * Create an IPv4 table entry for IPv4 entries and also
16364 			 * for IPv6 entries which are bound to in6addr_any
16365 			 * but don't have IPV6_V6ONLY set.
16366 			 * (i.e. anything an IPv4 peer could connect to)
16367 			 */
16368 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16369 			    (tcp->tcp_state <= TCPS_LISTEN &&
16370 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16371 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16372 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16373 					tce.tcpConnRemAddress = INADDR_ANY;
16374 					tce.tcpConnLocalAddress = INADDR_ANY;
16375 				} else {
16376 					tce.tcpConnRemAddress =
16377 					    tcp->tcp_remote;
16378 					tce.tcpConnLocalAddress =
16379 					    tcp->tcp_ip_src;
16380 				}
16381 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16382 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16383 				/* Don't want just anybody seeing these... */
16384 				if (ispriv) {
16385 					tce.tcpConnEntryInfo.ce_snxt =
16386 					    tcp->tcp_snxt;
16387 					tce.tcpConnEntryInfo.ce_suna =
16388 					    tcp->tcp_suna;
16389 					tce.tcpConnEntryInfo.ce_rnxt =
16390 					    tcp->tcp_rnxt;
16391 					tce.tcpConnEntryInfo.ce_rack =
16392 					    tcp->tcp_rack;
16393 				} else {
16394 					/*
16395 					 * Netstat, unfortunately, uses this to
16396 					 * get send/receive queue sizes.  How
16397 					 * to fix?
16398 					 * Why not compute the difference only?
16399 					 */
16400 					tce.tcpConnEntryInfo.ce_snxt =
16401 					    tcp->tcp_snxt - tcp->tcp_suna;
16402 					tce.tcpConnEntryInfo.ce_suna = 0;
16403 					tce.tcpConnEntryInfo.ce_rnxt =
16404 					    tcp->tcp_rnxt - tcp->tcp_rack;
16405 					tce.tcpConnEntryInfo.ce_rack = 0;
16406 				}
16407 
16408 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16409 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16410 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16411 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16412 				tce.tcpConnEntryInfo.ce_state =
16413 				    tcp->tcp_state;
16414 
16415 				tce.tcpConnCreationProcess =
16416 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16417 				    tcp->tcp_cpid;
16418 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16419 
16420 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16421 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16422 
16423 				mlp.tme_connidx = v4_conn_idx++;
16424 				if (needattr)
16425 					(void) snmp_append_data2(
16426 					    mp_attr_ctl->b_cont,
16427 					    &mp_attr_tail, (char *)&mlp,
16428 					    sizeof (mlp));
16429 			}
16430 		}
16431 	}
16432 
16433 	/* fixed length structure for IPv4 and IPv6 counters */
16434 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16435 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16436 	    sizeof (mib2_tcp6ConnEntry_t));
16437 	/* synchronize 32- and 64-bit counters */
16438 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16439 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16440 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16441 	optp->level = MIB2_TCP;
16442 	optp->name = 0;
16443 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16444 	    sizeof (tcps->tcps_mib));
16445 	optp->len = msgdsize(mpdata);
16446 	qreply(q, mpctl);
16447 
16448 	/* table of connections... */
16449 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16450 	    sizeof (struct T_optmgmt_ack)];
16451 	optp->level = MIB2_TCP;
16452 	optp->name = MIB2_TCP_CONN;
16453 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16454 	qreply(q, mp_conn_ctl);
16455 
16456 	/* table of MLP attributes... */
16457 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16458 	    sizeof (struct T_optmgmt_ack)];
16459 	optp->level = MIB2_TCP;
16460 	optp->name = EXPER_XPORT_MLP;
16461 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16462 	if (optp->len == 0)
16463 		freemsg(mp_attr_ctl);
16464 	else
16465 		qreply(q, mp_attr_ctl);
16466 
16467 	/* table of IPv6 connections... */
16468 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16469 	    sizeof (struct T_optmgmt_ack)];
16470 	optp->level = MIB2_TCP6;
16471 	optp->name = MIB2_TCP6_CONN;
16472 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16473 	qreply(q, mp6_conn_ctl);
16474 
16475 	/* table of IPv6 MLP attributes... */
16476 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16477 	    sizeof (struct T_optmgmt_ack)];
16478 	optp->level = MIB2_TCP6;
16479 	optp->name = EXPER_XPORT_MLP;
16480 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16481 	if (optp->len == 0)
16482 		freemsg(mp6_attr_ctl);
16483 	else
16484 		qreply(q, mp6_attr_ctl);
16485 	return (1);
16486 }
16487 
16488 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16489 /* ARGSUSED */
16490 int
16491 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16492 {
16493 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16494 
16495 	switch (level) {
16496 	case MIB2_TCP:
16497 		switch (name) {
16498 		case 13:
16499 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16500 				return (0);
16501 			/* TODO: delete entry defined by tce */
16502 			return (1);
16503 		default:
16504 			return (0);
16505 		}
16506 	default:
16507 		return (1);
16508 	}
16509 }
16510 
16511 /* Translate TCP state to MIB2 TCP state. */
16512 static int
16513 tcp_snmp_state(tcp_t *tcp)
16514 {
16515 	if (tcp == NULL)
16516 		return (0);
16517 
16518 	switch (tcp->tcp_state) {
16519 	case TCPS_CLOSED:
16520 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16521 	case TCPS_BOUND:
16522 		return (MIB2_TCP_closed);
16523 	case TCPS_LISTEN:
16524 		return (MIB2_TCP_listen);
16525 	case TCPS_SYN_SENT:
16526 		return (MIB2_TCP_synSent);
16527 	case TCPS_SYN_RCVD:
16528 		return (MIB2_TCP_synReceived);
16529 	case TCPS_ESTABLISHED:
16530 		return (MIB2_TCP_established);
16531 	case TCPS_CLOSE_WAIT:
16532 		return (MIB2_TCP_closeWait);
16533 	case TCPS_FIN_WAIT_1:
16534 		return (MIB2_TCP_finWait1);
16535 	case TCPS_CLOSING:
16536 		return (MIB2_TCP_closing);
16537 	case TCPS_LAST_ACK:
16538 		return (MIB2_TCP_lastAck);
16539 	case TCPS_FIN_WAIT_2:
16540 		return (MIB2_TCP_finWait2);
16541 	case TCPS_TIME_WAIT:
16542 		return (MIB2_TCP_timeWait);
16543 	default:
16544 		return (0);
16545 	}
16546 }
16547 
16548 static char tcp_report_header[] =
16549 	"TCP     " MI_COL_HDRPAD_STR
16550 	"zone dest            snxt     suna     "
16551 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16552 	"recent   [lport,fport] state";
16553 
16554 /*
16555  * TCP status report triggered via the Named Dispatch mechanism.
16556  */
16557 /* ARGSUSED */
16558 static void
16559 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16560     cred_t *cr)
16561 {
16562 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16563 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16564 	char cflag;
16565 	in6_addr_t	v6dst;
16566 	char buf[80];
16567 	uint_t print_len, buf_len;
16568 
16569 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16570 	if (buf_len <= 0)
16571 		return;
16572 
16573 	if (hashval >= 0)
16574 		(void) sprintf(hash, "%03d ", hashval);
16575 	else
16576 		hash[0] = '\0';
16577 
16578 	/*
16579 	 * Note that we use the remote address in the tcp_b  structure.
16580 	 * This means that it will print out the real destination address,
16581 	 * not the next hop's address if source routing is used.  This
16582 	 * avoid the confusion on the output because user may not
16583 	 * know that source routing is used for a connection.
16584 	 */
16585 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16586 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16587 	} else {
16588 		v6dst = tcp->tcp_remote_v6;
16589 	}
16590 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16591 	/*
16592 	 * the ispriv checks are so that normal users cannot determine
16593 	 * sequence number information using NDD.
16594 	 */
16595 
16596 	if (TCP_IS_DETACHED(tcp))
16597 		cflag = '*';
16598 	else
16599 		cflag = ' ';
16600 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16601 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16602 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16603 	    hash,
16604 	    (void *)tcp,
16605 	    tcp->tcp_connp->conn_zoneid,
16606 	    addrbuf,
16607 	    (ispriv) ? tcp->tcp_snxt : 0,
16608 	    (ispriv) ? tcp->tcp_suna : 0,
16609 	    tcp->tcp_swnd,
16610 	    (ispriv) ? tcp->tcp_rnxt : 0,
16611 	    (ispriv) ? tcp->tcp_rack : 0,
16612 	    tcp->tcp_rwnd,
16613 	    tcp->tcp_rto,
16614 	    tcp->tcp_mss,
16615 	    tcp->tcp_snd_ws_ok,
16616 	    tcp->tcp_snd_ws,
16617 	    tcp->tcp_rcv_ws,
16618 	    tcp->tcp_snd_ts_ok,
16619 	    tcp->tcp_ts_recent,
16620 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16621 	if (print_len < buf_len) {
16622 		((mblk_t *)mp)->b_wptr += print_len;
16623 	} else {
16624 		((mblk_t *)mp)->b_wptr += buf_len;
16625 	}
16626 }
16627 
16628 /*
16629  * TCP status report (for listeners only) triggered via the Named Dispatch
16630  * mechanism.
16631  */
16632 /* ARGSUSED */
16633 static void
16634 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16635 {
16636 	char addrbuf[INET6_ADDRSTRLEN];
16637 	in6_addr_t	v6dst;
16638 	uint_t print_len, buf_len;
16639 
16640 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16641 	if (buf_len <= 0)
16642 		return;
16643 
16644 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16645 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16646 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16647 	} else {
16648 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16649 		    addrbuf, sizeof (addrbuf));
16650 	}
16651 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16652 	    "%03d "
16653 	    MI_COL_PTRFMT_STR
16654 	    "%d %s %05u %08u %d/%d/%d%c\n",
16655 	    hashval, (void *)tcp,
16656 	    tcp->tcp_connp->conn_zoneid,
16657 	    addrbuf,
16658 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16659 	    tcp->tcp_conn_req_seqnum,
16660 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16661 	    tcp->tcp_conn_req_max,
16662 	    tcp->tcp_syn_defense ? '*' : ' ');
16663 	if (print_len < buf_len) {
16664 		((mblk_t *)mp)->b_wptr += print_len;
16665 	} else {
16666 		((mblk_t *)mp)->b_wptr += buf_len;
16667 	}
16668 }
16669 
16670 /* TCP status report triggered via the Named Dispatch mechanism. */
16671 /* ARGSUSED */
16672 static int
16673 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16674 {
16675 	tcp_t	*tcp;
16676 	int	i;
16677 	conn_t	*connp;
16678 	connf_t	*connfp;
16679 	zoneid_t zoneid;
16680 	tcp_stack_t *tcps;
16681 	ip_stack_t *ipst;
16682 
16683 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16684 	tcps = Q_TO_TCP(q)->tcp_tcps;
16685 
16686 	/*
16687 	 * Because of the ndd constraint, at most we can have 64K buffer
16688 	 * to put in all TCP info.  So to be more efficient, just
16689 	 * allocate a 64K buffer here, assuming we need that large buffer.
16690 	 * This may be a problem as any user can read tcp_status.  Therefore
16691 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16692 	 * This should be OK as normal users should not do this too often.
16693 	 */
16694 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16695 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16696 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16697 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16698 			return (0);
16699 		}
16700 	}
16701 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16702 		/* The following may work even if we cannot get a large buf. */
16703 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16704 		return (0);
16705 	}
16706 
16707 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16708 
16709 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16710 
16711 		ipst = tcps->tcps_netstack->netstack_ip;
16712 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16713 
16714 		connp = NULL;
16715 
16716 		while ((connp =
16717 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16718 			tcp = connp->conn_tcp;
16719 			if (zoneid != GLOBAL_ZONEID &&
16720 			    zoneid != connp->conn_zoneid)
16721 				continue;
16722 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16723 			    cr);
16724 		}
16725 
16726 	}
16727 
16728 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16729 	return (0);
16730 }
16731 
16732 /* TCP status report triggered via the Named Dispatch mechanism. */
16733 /* ARGSUSED */
16734 static int
16735 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16736 {
16737 	tf_t	*tbf;
16738 	tcp_t	*tcp;
16739 	int	i;
16740 	zoneid_t zoneid;
16741 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16742 
16743 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16744 
16745 	/* Refer to comments in tcp_status_report(). */
16746 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16747 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16748 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16749 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16750 			return (0);
16751 		}
16752 	}
16753 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16754 		/* The following may work even if we cannot get a large buf. */
16755 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16756 		return (0);
16757 	}
16758 
16759 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16760 
16761 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16762 		tbf = &tcps->tcps_bind_fanout[i];
16763 		mutex_enter(&tbf->tf_lock);
16764 		for (tcp = tbf->tf_tcp; tcp != NULL;
16765 		    tcp = tcp->tcp_bind_hash) {
16766 			if (zoneid != GLOBAL_ZONEID &&
16767 			    zoneid != tcp->tcp_connp->conn_zoneid)
16768 				continue;
16769 			CONN_INC_REF(tcp->tcp_connp);
16770 			tcp_report_item(mp->b_cont, tcp, i,
16771 			    Q_TO_TCP(q), cr);
16772 			CONN_DEC_REF(tcp->tcp_connp);
16773 		}
16774 		mutex_exit(&tbf->tf_lock);
16775 	}
16776 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16777 	return (0);
16778 }
16779 
16780 /* TCP status report triggered via the Named Dispatch mechanism. */
16781 /* ARGSUSED */
16782 static int
16783 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16784 {
16785 	connf_t	*connfp;
16786 	conn_t	*connp;
16787 	tcp_t	*tcp;
16788 	int	i;
16789 	zoneid_t zoneid;
16790 	tcp_stack_t *tcps;
16791 	ip_stack_t	*ipst;
16792 
16793 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16794 	tcps = Q_TO_TCP(q)->tcp_tcps;
16795 
16796 	/* Refer to comments in tcp_status_report(). */
16797 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16798 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16799 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16800 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16801 			return (0);
16802 		}
16803 	}
16804 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16805 		/* The following may work even if we cannot get a large buf. */
16806 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16807 		return (0);
16808 	}
16809 
16810 	(void) mi_mpprintf(mp,
16811 	    "    TCP    " MI_COL_HDRPAD_STR
16812 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16813 
16814 	ipst = tcps->tcps_netstack->netstack_ip;
16815 
16816 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16817 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16818 		connp = NULL;
16819 		while ((connp =
16820 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16821 			tcp = connp->conn_tcp;
16822 			if (zoneid != GLOBAL_ZONEID &&
16823 			    zoneid != connp->conn_zoneid)
16824 				continue;
16825 			tcp_report_listener(mp->b_cont, tcp, i);
16826 		}
16827 	}
16828 
16829 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16830 	return (0);
16831 }
16832 
16833 /* TCP status report triggered via the Named Dispatch mechanism. */
16834 /* ARGSUSED */
16835 static int
16836 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16837 {
16838 	connf_t	*connfp;
16839 	conn_t	*connp;
16840 	tcp_t	*tcp;
16841 	int	i;
16842 	zoneid_t zoneid;
16843 	tcp_stack_t *tcps;
16844 	ip_stack_t *ipst;
16845 
16846 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16847 	tcps = Q_TO_TCP(q)->tcp_tcps;
16848 	ipst = tcps->tcps_netstack->netstack_ip;
16849 
16850 	/* Refer to comments in tcp_status_report(). */
16851 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16852 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16853 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16854 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16855 			return (0);
16856 		}
16857 	}
16858 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16859 		/* The following may work even if we cannot get a large buf. */
16860 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16861 		return (0);
16862 	}
16863 
16864 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16865 	    ipst->ips_ipcl_conn_fanout_size);
16866 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16867 
16868 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16869 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16870 		connp = NULL;
16871 		while ((connp =
16872 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16873 			tcp = connp->conn_tcp;
16874 			if (zoneid != GLOBAL_ZONEID &&
16875 			    zoneid != connp->conn_zoneid)
16876 				continue;
16877 			tcp_report_item(mp->b_cont, tcp, i,
16878 			    Q_TO_TCP(q), cr);
16879 		}
16880 	}
16881 
16882 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16883 	return (0);
16884 }
16885 
16886 /* TCP status report triggered via the Named Dispatch mechanism. */
16887 /* ARGSUSED */
16888 static int
16889 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16890 {
16891 	tf_t	*tf;
16892 	tcp_t	*tcp;
16893 	int	i;
16894 	zoneid_t zoneid;
16895 	tcp_stack_t	*tcps;
16896 
16897 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16898 	tcps = Q_TO_TCP(q)->tcp_tcps;
16899 
16900 	/* Refer to comments in tcp_status_report(). */
16901 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16902 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16903 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16904 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16905 			return (0);
16906 		}
16907 	}
16908 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16909 		/* The following may work even if we cannot get a large buf. */
16910 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16911 		return (0);
16912 	}
16913 
16914 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16915 
16916 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16917 		tf = &tcps->tcps_acceptor_fanout[i];
16918 		mutex_enter(&tf->tf_lock);
16919 		for (tcp = tf->tf_tcp; tcp != NULL;
16920 		    tcp = tcp->tcp_acceptor_hash) {
16921 			if (zoneid != GLOBAL_ZONEID &&
16922 			    zoneid != tcp->tcp_connp->conn_zoneid)
16923 				continue;
16924 			tcp_report_item(mp->b_cont, tcp, i,
16925 			    Q_TO_TCP(q), cr);
16926 		}
16927 		mutex_exit(&tf->tf_lock);
16928 	}
16929 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16930 	return (0);
16931 }
16932 
16933 /*
16934  * tcp_timer is the timer service routine.  It handles the retransmission,
16935  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16936  * from the state of the tcp instance what kind of action needs to be done
16937  * at the time it is called.
16938  */
16939 static void
16940 tcp_timer(void *arg)
16941 {
16942 	mblk_t		*mp;
16943 	clock_t		first_threshold;
16944 	clock_t		second_threshold;
16945 	clock_t		ms;
16946 	uint32_t	mss;
16947 	conn_t		*connp = (conn_t *)arg;
16948 	tcp_t		*tcp = connp->conn_tcp;
16949 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16950 
16951 	tcp->tcp_timer_tid = 0;
16952 
16953 	if (tcp->tcp_fused)
16954 		return;
16955 
16956 	first_threshold =  tcp->tcp_first_timer_threshold;
16957 	second_threshold = tcp->tcp_second_timer_threshold;
16958 	switch (tcp->tcp_state) {
16959 	case TCPS_IDLE:
16960 	case TCPS_BOUND:
16961 	case TCPS_LISTEN:
16962 		return;
16963 	case TCPS_SYN_RCVD: {
16964 		tcp_t	*listener = tcp->tcp_listener;
16965 
16966 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16967 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16968 			/* it's our first timeout */
16969 			tcp->tcp_syn_rcvd_timeout = 1;
16970 			mutex_enter(&listener->tcp_eager_lock);
16971 			listener->tcp_syn_rcvd_timeout++;
16972 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16973 				/*
16974 				 * Make this eager available for drop if we
16975 				 * need to drop one to accomodate a new
16976 				 * incoming SYN request.
16977 				 */
16978 				MAKE_DROPPABLE(listener, tcp);
16979 			}
16980 			if (!listener->tcp_syn_defense &&
16981 			    (listener->tcp_syn_rcvd_timeout >
16982 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
16983 			    (tcps->tcps_conn_req_max_q0 > 200)) {
16984 				/* We may be under attack. Put on a defense. */
16985 				listener->tcp_syn_defense = B_TRUE;
16986 				cmn_err(CE_WARN, "High TCP connect timeout "
16987 				    "rate! System (port %d) may be under a "
16988 				    "SYN flood attack!",
16989 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16990 
16991 				listener->tcp_ip_addr_cache = kmem_zalloc(
16992 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16993 				    KM_NOSLEEP);
16994 			}
16995 			mutex_exit(&listener->tcp_eager_lock);
16996 		} else if (listener != NULL) {
16997 			mutex_enter(&listener->tcp_eager_lock);
16998 			tcp->tcp_syn_rcvd_timeout++;
16999 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17000 			    !tcp->tcp_closemp_used) {
17001 				/*
17002 				 * This is our second timeout. Put the tcp in
17003 				 * the list of droppable eagers to allow it to
17004 				 * be dropped, if needed. We don't check
17005 				 * whether tcp_dontdrop is set or not to
17006 				 * protect ourselve from a SYN attack where a
17007 				 * remote host can spoof itself as one of the
17008 				 * good IP source and continue to hold
17009 				 * resources too long.
17010 				 */
17011 				MAKE_DROPPABLE(listener, tcp);
17012 			}
17013 			mutex_exit(&listener->tcp_eager_lock);
17014 		}
17015 	}
17016 		/* FALLTHRU */
17017 	case TCPS_SYN_SENT:
17018 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17019 		second_threshold = tcp->tcp_second_ctimer_threshold;
17020 		break;
17021 	case TCPS_ESTABLISHED:
17022 	case TCPS_FIN_WAIT_1:
17023 	case TCPS_CLOSING:
17024 	case TCPS_CLOSE_WAIT:
17025 	case TCPS_LAST_ACK:
17026 		/* If we have data to rexmit */
17027 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17028 			clock_t	time_to_wait;
17029 
17030 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17031 			if (!tcp->tcp_xmit_head)
17032 				break;
17033 			time_to_wait = lbolt -
17034 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17035 			time_to_wait = tcp->tcp_rto -
17036 			    TICK_TO_MSEC(time_to_wait);
17037 			/*
17038 			 * If the timer fires too early, 1 clock tick earlier,
17039 			 * restart the timer.
17040 			 */
17041 			if (time_to_wait > msec_per_tick) {
17042 				TCP_STAT(tcps, tcp_timer_fire_early);
17043 				TCP_TIMER_RESTART(tcp, time_to_wait);
17044 				return;
17045 			}
17046 			/*
17047 			 * When we probe zero windows, we force the swnd open.
17048 			 * If our peer acks with a closed window swnd will be
17049 			 * set to zero by tcp_rput(). As long as we are
17050 			 * receiving acks tcp_rput will
17051 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17052 			 * first and second interval actions.  NOTE: the timer
17053 			 * interval is allowed to continue its exponential
17054 			 * backoff.
17055 			 */
17056 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17057 				if (tcp->tcp_debug) {
17058 					(void) strlog(TCP_MOD_ID, 0, 1,
17059 					    SL_TRACE, "tcp_timer: zero win");
17060 				}
17061 			} else {
17062 				/*
17063 				 * After retransmission, we need to do
17064 				 * slow start.  Set the ssthresh to one
17065 				 * half of current effective window and
17066 				 * cwnd to one MSS.  Also reset
17067 				 * tcp_cwnd_cnt.
17068 				 *
17069 				 * Note that if tcp_ssthresh is reduced because
17070 				 * of ECN, do not reduce it again unless it is
17071 				 * already one window of data away (tcp_cwr
17072 				 * should then be cleared) or this is a
17073 				 * timeout for a retransmitted segment.
17074 				 */
17075 				uint32_t npkt;
17076 
17077 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17078 					npkt = ((tcp->tcp_timer_backoff ?
17079 					    tcp->tcp_cwnd_ssthresh :
17080 					    tcp->tcp_snxt -
17081 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17082 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17083 					    tcp->tcp_mss;
17084 				}
17085 				tcp->tcp_cwnd = tcp->tcp_mss;
17086 				tcp->tcp_cwnd_cnt = 0;
17087 				if (tcp->tcp_ecn_ok) {
17088 					tcp->tcp_cwr = B_TRUE;
17089 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17090 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17091 				}
17092 			}
17093 			break;
17094 		}
17095 		/*
17096 		 * We have something to send yet we cannot send.  The
17097 		 * reason can be:
17098 		 *
17099 		 * 1. Zero send window: we need to do zero window probe.
17100 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17101 		 * segments.
17102 		 * 3. SWS avoidance: receiver may have shrunk window,
17103 		 * reset our knowledge.
17104 		 *
17105 		 * Note that condition 2 can happen with either 1 or
17106 		 * 3.  But 1 and 3 are exclusive.
17107 		 */
17108 		if (tcp->tcp_unsent != 0) {
17109 			if (tcp->tcp_cwnd == 0) {
17110 				/*
17111 				 * Set tcp_cwnd to 1 MSS so that a
17112 				 * new segment can be sent out.  We
17113 				 * are "clocking out" new data when
17114 				 * the network is really congested.
17115 				 */
17116 				ASSERT(tcp->tcp_ecn_ok);
17117 				tcp->tcp_cwnd = tcp->tcp_mss;
17118 			}
17119 			if (tcp->tcp_swnd == 0) {
17120 				/* Extend window for zero window probe */
17121 				tcp->tcp_swnd++;
17122 				tcp->tcp_zero_win_probe = B_TRUE;
17123 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17124 			} else {
17125 				/*
17126 				 * Handle timeout from sender SWS avoidance.
17127 				 * Reset our knowledge of the max send window
17128 				 * since the receiver might have reduced its
17129 				 * receive buffer.  Avoid setting tcp_max_swnd
17130 				 * to one since that will essentially disable
17131 				 * the SWS checks.
17132 				 *
17133 				 * Note that since we don't have a SWS
17134 				 * state variable, if the timeout is set
17135 				 * for ECN but not for SWS, this
17136 				 * code will also be executed.  This is
17137 				 * fine as tcp_max_swnd is updated
17138 				 * constantly and it will not affect
17139 				 * anything.
17140 				 */
17141 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17142 			}
17143 			tcp_wput_data(tcp, NULL, B_FALSE);
17144 			return;
17145 		}
17146 		/* Is there a FIN that needs to be to re retransmitted? */
17147 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17148 		    !tcp->tcp_fin_acked)
17149 			break;
17150 		/* Nothing to do, return without restarting timer. */
17151 		TCP_STAT(tcps, tcp_timer_fire_miss);
17152 		return;
17153 	case TCPS_FIN_WAIT_2:
17154 		/*
17155 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17156 		 * We waited some time for for peer's FIN, but it hasn't
17157 		 * arrived.  We flush the connection now to avoid
17158 		 * case where the peer has rebooted.
17159 		 */
17160 		if (TCP_IS_DETACHED(tcp)) {
17161 			(void) tcp_clean_death(tcp, 0, 23);
17162 		} else {
17163 			TCP_TIMER_RESTART(tcp,
17164 			    tcps->tcps_fin_wait_2_flush_interval);
17165 		}
17166 		return;
17167 	case TCPS_TIME_WAIT:
17168 		(void) tcp_clean_death(tcp, 0, 24);
17169 		return;
17170 	default:
17171 		if (tcp->tcp_debug) {
17172 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17173 			    "tcp_timer: strange state (%d) %s",
17174 			    tcp->tcp_state, tcp_display(tcp, NULL,
17175 			    DISP_PORT_ONLY));
17176 		}
17177 		return;
17178 	}
17179 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17180 		/*
17181 		 * For zero window probe, we need to send indefinitely,
17182 		 * unless we have not heard from the other side for some
17183 		 * time...
17184 		 */
17185 		if ((tcp->tcp_zero_win_probe == 0) ||
17186 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17187 		    second_threshold)) {
17188 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17189 			/*
17190 			 * If TCP is in SYN_RCVD state, send back a
17191 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17192 			 * should be zero in TCPS_SYN_RCVD state.
17193 			 */
17194 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17195 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17196 				    "in SYN_RCVD",
17197 				    tcp, tcp->tcp_snxt,
17198 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17199 			}
17200 			(void) tcp_clean_death(tcp,
17201 			    tcp->tcp_client_errno ?
17202 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17203 			return;
17204 		} else {
17205 			/*
17206 			 * Set tcp_ms_we_have_waited to second_threshold
17207 			 * so that in next timeout, we will do the above
17208 			 * check (lbolt - tcp_last_recv_time).  This is
17209 			 * also to avoid overflow.
17210 			 *
17211 			 * We don't need to decrement tcp_timer_backoff
17212 			 * to avoid overflow because it will be decremented
17213 			 * later if new timeout value is greater than
17214 			 * tcp_rexmit_interval_max.  In the case when
17215 			 * tcp_rexmit_interval_max is greater than
17216 			 * second_threshold, it means that we will wait
17217 			 * longer than second_threshold to send the next
17218 			 * window probe.
17219 			 */
17220 			tcp->tcp_ms_we_have_waited = second_threshold;
17221 		}
17222 	} else if (ms > first_threshold) {
17223 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17224 		    tcp->tcp_xmit_head != NULL) {
17225 			tcp->tcp_xmit_head =
17226 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17227 		}
17228 		/*
17229 		 * We have been retransmitting for too long...  The RTT
17230 		 * we calculated is probably incorrect.  Reinitialize it.
17231 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17232 		 * tcp_rtt_update so that we won't accidentally cache a
17233 		 * bad value.  But only do this if this is not a zero
17234 		 * window probe.
17235 		 */
17236 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17237 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17238 			    (tcp->tcp_rtt_sa >> 5);
17239 			tcp->tcp_rtt_sa = 0;
17240 			tcp_ip_notify(tcp);
17241 			tcp->tcp_rtt_update = 0;
17242 		}
17243 	}
17244 	tcp->tcp_timer_backoff++;
17245 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17246 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17247 	    tcps->tcps_rexmit_interval_min) {
17248 		/*
17249 		 * This means the original RTO is tcp_rexmit_interval_min.
17250 		 * So we will use tcp_rexmit_interval_min as the RTO value
17251 		 * and do the backoff.
17252 		 */
17253 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17254 	} else {
17255 		ms <<= tcp->tcp_timer_backoff;
17256 	}
17257 	if (ms > tcps->tcps_rexmit_interval_max) {
17258 		ms = tcps->tcps_rexmit_interval_max;
17259 		/*
17260 		 * ms is at max, decrement tcp_timer_backoff to avoid
17261 		 * overflow.
17262 		 */
17263 		tcp->tcp_timer_backoff--;
17264 	}
17265 	tcp->tcp_ms_we_have_waited += ms;
17266 	if (tcp->tcp_zero_win_probe == 0) {
17267 		tcp->tcp_rto = ms;
17268 	}
17269 	TCP_TIMER_RESTART(tcp, ms);
17270 	/*
17271 	 * This is after a timeout and tcp_rto is backed off.  Set
17272 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17273 	 * restart the timer with a correct value.
17274 	 */
17275 	tcp->tcp_set_timer = 1;
17276 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17277 	if (mss > tcp->tcp_mss)
17278 		mss = tcp->tcp_mss;
17279 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17280 		mss = tcp->tcp_swnd;
17281 
17282 	if ((mp = tcp->tcp_xmit_head) != NULL)
17283 		mp->b_prev = (mblk_t *)lbolt;
17284 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17285 	    B_TRUE);
17286 
17287 	/*
17288 	 * When slow start after retransmission begins, start with
17289 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17290 	 * start phase.  tcp_snd_burst controls how many segments
17291 	 * can be sent because of an ack.
17292 	 */
17293 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17294 	tcp->tcp_snd_burst = TCP_CWND_SS;
17295 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17296 	    (tcp->tcp_unsent == 0)) {
17297 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17298 	} else {
17299 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17300 	}
17301 	tcp->tcp_rexmit = B_TRUE;
17302 	tcp->tcp_dupack_cnt = 0;
17303 
17304 	/*
17305 	 * Remove all rexmit SACK blk to start from fresh.
17306 	 */
17307 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17308 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17309 		tcp->tcp_num_notsack_blk = 0;
17310 		tcp->tcp_cnt_notsack_list = 0;
17311 	}
17312 	if (mp == NULL) {
17313 		return;
17314 	}
17315 	/* Attach credentials to retransmitted initial SYNs. */
17316 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17317 		mblk_setcred(mp, tcp->tcp_cred);
17318 		DB_CPID(mp) = tcp->tcp_cpid;
17319 	}
17320 
17321 	tcp->tcp_csuna = tcp->tcp_snxt;
17322 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17323 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17324 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17325 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17326 
17327 }
17328 
17329 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17330 static void
17331 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17332 {
17333 	conn_t	*connp;
17334 
17335 	switch (tcp->tcp_state) {
17336 	case TCPS_BOUND:
17337 	case TCPS_LISTEN:
17338 		break;
17339 	default:
17340 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17341 		return;
17342 	}
17343 
17344 	/*
17345 	 * Need to clean up all the eagers since after the unbind, segments
17346 	 * will no longer be delivered to this listener stream.
17347 	 */
17348 	mutex_enter(&tcp->tcp_eager_lock);
17349 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17350 		tcp_eager_cleanup(tcp, 0);
17351 	}
17352 	mutex_exit(&tcp->tcp_eager_lock);
17353 
17354 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17355 		tcp->tcp_ipha->ipha_src = 0;
17356 	} else {
17357 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17358 	}
17359 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17360 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17361 	tcp_bind_hash_remove(tcp);
17362 	tcp->tcp_state = TCPS_IDLE;
17363 	tcp->tcp_mdt = B_FALSE;
17364 	/* Send M_FLUSH according to TPI */
17365 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17366 	connp = tcp->tcp_connp;
17367 	connp->conn_mdt_ok = B_FALSE;
17368 	ipcl_hash_remove(connp);
17369 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17370 	mp = mi_tpi_ok_ack_alloc(mp);
17371 	putnext(tcp->tcp_rq, mp);
17372 }
17373 
17374 /*
17375  * Don't let port fall into the privileged range.
17376  * Since the extra privileged ports can be arbitrary we also
17377  * ensure that we exclude those from consideration.
17378  * tcp_g_epriv_ports is not sorted thus we loop over it until
17379  * there are no changes.
17380  *
17381  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17382  * but instead the code relies on:
17383  * - the fact that the address of the array and its size never changes
17384  * - the atomic assignment of the elements of the array
17385  *
17386  * Returns 0 if there are no more ports available.
17387  *
17388  * TS note: skip multilevel ports.
17389  */
17390 static in_port_t
17391 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17392 {
17393 	int i;
17394 	boolean_t restart = B_FALSE;
17395 	tcp_stack_t *tcps = tcp->tcp_tcps;
17396 
17397 	if (random && tcp_random_anon_port != 0) {
17398 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17399 		    sizeof (in_port_t));
17400 		/*
17401 		 * Unless changed by a sys admin, the smallest anon port
17402 		 * is 32768 and the largest anon port is 65535.  It is
17403 		 * very likely (50%) for the random port to be smaller
17404 		 * than the smallest anon port.  When that happens,
17405 		 * add port % (anon port range) to the smallest anon
17406 		 * port to get the random port.  It should fall into the
17407 		 * valid anon port range.
17408 		 */
17409 		if (port < tcps->tcps_smallest_anon_port) {
17410 			port = tcps->tcps_smallest_anon_port +
17411 			    port % (tcps->tcps_largest_anon_port -
17412 			    tcps->tcps_smallest_anon_port);
17413 		}
17414 	}
17415 
17416 retry:
17417 	if (port < tcps->tcps_smallest_anon_port)
17418 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17419 
17420 	if (port > tcps->tcps_largest_anon_port) {
17421 		if (restart)
17422 			return (0);
17423 		restart = B_TRUE;
17424 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17425 	}
17426 
17427 	if (port < tcps->tcps_smallest_nonpriv_port)
17428 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17429 
17430 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17431 		if (port == tcps->tcps_g_epriv_ports[i]) {
17432 			port++;
17433 			/*
17434 			 * Make sure whether the port is in the
17435 			 * valid range.
17436 			 */
17437 			goto retry;
17438 		}
17439 	}
17440 	if (is_system_labeled() &&
17441 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17442 	    IPPROTO_TCP, B_TRUE)) != 0) {
17443 		port = i;
17444 		goto retry;
17445 	}
17446 	return (port);
17447 }
17448 
17449 /*
17450  * Return the next anonymous port in the privileged port range for
17451  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17452  * downwards.  This is the same behavior as documented in the userland
17453  * library call rresvport(3N).
17454  *
17455  * TS note: skip multilevel ports.
17456  */
17457 static in_port_t
17458 tcp_get_next_priv_port(const tcp_t *tcp)
17459 {
17460 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17461 	in_port_t nextport;
17462 	boolean_t restart = B_FALSE;
17463 	tcp_stack_t *tcps = tcp->tcp_tcps;
17464 retry:
17465 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17466 	    next_priv_port >= IPPORT_RESERVED) {
17467 		next_priv_port = IPPORT_RESERVED - 1;
17468 		if (restart)
17469 			return (0);
17470 		restart = B_TRUE;
17471 	}
17472 	if (is_system_labeled() &&
17473 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17474 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17475 		next_priv_port = nextport;
17476 		goto retry;
17477 	}
17478 	return (next_priv_port--);
17479 }
17480 
17481 /* The write side r/w procedure. */
17482 
17483 #if CCS_STATS
17484 struct {
17485 	struct {
17486 		int64_t count, bytes;
17487 	} tot, hit;
17488 } wrw_stats;
17489 #endif
17490 
17491 /*
17492  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17493  * messages.
17494  */
17495 /* ARGSUSED */
17496 static void
17497 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17498 {
17499 	conn_t	*connp = (conn_t *)arg;
17500 	tcp_t	*tcp = connp->conn_tcp;
17501 	queue_t	*q = tcp->tcp_wq;
17502 
17503 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17504 	/*
17505 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17506 	 * Once the close starts, streamhead and sockfs will not let any data
17507 	 * packets come down (close ensures that there are no threads using the
17508 	 * queue and no new threads will come down) but since qprocsoff()
17509 	 * hasn't happened yet, a M_FLUSH or some non data message might
17510 	 * get reflected back (in response to our own FLUSHRW) and get
17511 	 * processed after tcp_close() is done. The conn would still be valid
17512 	 * because a ref would have added but we need to check the state
17513 	 * before actually processing the packet.
17514 	 */
17515 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17516 		freemsg(mp);
17517 		return;
17518 	}
17519 
17520 	switch (DB_TYPE(mp)) {
17521 	case M_IOCDATA:
17522 		tcp_wput_iocdata(tcp, mp);
17523 		break;
17524 	case M_FLUSH:
17525 		tcp_wput_flush(tcp, mp);
17526 		break;
17527 	default:
17528 		CALL_IP_WPUT(connp, q, mp);
17529 		break;
17530 	}
17531 }
17532 
17533 /*
17534  * The TCP fast path write put procedure.
17535  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17536  */
17537 /* ARGSUSED */
17538 void
17539 tcp_output(void *arg, mblk_t *mp, void *arg2)
17540 {
17541 	int		len;
17542 	int		hdrlen;
17543 	int		plen;
17544 	mblk_t		*mp1;
17545 	uchar_t		*rptr;
17546 	uint32_t	snxt;
17547 	tcph_t		*tcph;
17548 	struct datab	*db;
17549 	uint32_t	suna;
17550 	uint32_t	mss;
17551 	ipaddr_t	*dst;
17552 	ipaddr_t	*src;
17553 	uint32_t	sum;
17554 	int		usable;
17555 	conn_t		*connp = (conn_t *)arg;
17556 	tcp_t		*tcp = connp->conn_tcp;
17557 	uint32_t	msize;
17558 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17559 
17560 	/*
17561 	 * Try and ASSERT the minimum possible references on the
17562 	 * conn early enough. Since we are executing on write side,
17563 	 * the connection is obviously not detached and that means
17564 	 * there is a ref each for TCP and IP. Since we are behind
17565 	 * the squeue, the minimum references needed are 3. If the
17566 	 * conn is in classifier hash list, there should be an
17567 	 * extra ref for that (we check both the possibilities).
17568 	 */
17569 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17570 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17571 
17572 	ASSERT(DB_TYPE(mp) == M_DATA);
17573 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17574 
17575 	mutex_enter(&tcp->tcp_non_sq_lock);
17576 	tcp->tcp_squeue_bytes -= msize;
17577 	mutex_exit(&tcp->tcp_non_sq_lock);
17578 
17579 	/* Bypass tcp protocol for fused tcp loopback */
17580 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17581 		return;
17582 
17583 	mss = tcp->tcp_mss;
17584 	if (tcp->tcp_xmit_zc_clean)
17585 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17586 
17587 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17588 	len = (int)(mp->b_wptr - mp->b_rptr);
17589 
17590 	/*
17591 	 * Criteria for fast path:
17592 	 *
17593 	 *   1. no unsent data
17594 	 *   2. single mblk in request
17595 	 *   3. connection established
17596 	 *   4. data in mblk
17597 	 *   5. len <= mss
17598 	 *   6. no tcp_valid bits
17599 	 */
17600 	if ((tcp->tcp_unsent != 0) ||
17601 	    (tcp->tcp_cork) ||
17602 	    (mp->b_cont != NULL) ||
17603 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17604 	    (len == 0) ||
17605 	    (len > mss) ||
17606 	    (tcp->tcp_valid_bits != 0)) {
17607 		tcp_wput_data(tcp, mp, B_FALSE);
17608 		return;
17609 	}
17610 
17611 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17612 	ASSERT(tcp->tcp_fin_sent == 0);
17613 
17614 	/* queue new packet onto retransmission queue */
17615 	if (tcp->tcp_xmit_head == NULL) {
17616 		tcp->tcp_xmit_head = mp;
17617 	} else {
17618 		tcp->tcp_xmit_last->b_cont = mp;
17619 	}
17620 	tcp->tcp_xmit_last = mp;
17621 	tcp->tcp_xmit_tail = mp;
17622 
17623 	/* find out how much we can send */
17624 	/* BEGIN CSTYLED */
17625 	/*
17626 	 *    un-acked           usable
17627 	 *  |--------------|-----------------|
17628 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17629 	 */
17630 	/* END CSTYLED */
17631 
17632 	/* start sending from tcp_snxt */
17633 	snxt = tcp->tcp_snxt;
17634 
17635 	/*
17636 	 * Check to see if this connection has been idled for some
17637 	 * time and no ACK is expected.  If it is, we need to slow
17638 	 * start again to get back the connection's "self-clock" as
17639 	 * described in VJ's paper.
17640 	 *
17641 	 * Refer to the comment in tcp_mss_set() for the calculation
17642 	 * of tcp_cwnd after idle.
17643 	 */
17644 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17645 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17646 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17647 	}
17648 
17649 	usable = tcp->tcp_swnd;		/* tcp window size */
17650 	if (usable > tcp->tcp_cwnd)
17651 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17652 	usable -= snxt;		/* subtract stuff already sent */
17653 	suna = tcp->tcp_suna;
17654 	usable += suna;
17655 	/* usable can be < 0 if the congestion window is smaller */
17656 	if (len > usable) {
17657 		/* Can't send complete M_DATA in one shot */
17658 		goto slow;
17659 	}
17660 
17661 	mutex_enter(&tcp->tcp_non_sq_lock);
17662 	if (tcp->tcp_flow_stopped &&
17663 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17664 		tcp_clrqfull(tcp);
17665 	}
17666 	mutex_exit(&tcp->tcp_non_sq_lock);
17667 
17668 	/*
17669 	 * determine if anything to send (Nagle).
17670 	 *
17671 	 *   1. len < tcp_mss (i.e. small)
17672 	 *   2. unacknowledged data present
17673 	 *   3. len < nagle limit
17674 	 *   4. last packet sent < nagle limit (previous packet sent)
17675 	 */
17676 	if ((len < mss) && (snxt != suna) &&
17677 	    (len < (int)tcp->tcp_naglim) &&
17678 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17679 		/*
17680 		 * This was the first unsent packet and normally
17681 		 * mss < xmit_hiwater so there is no need to worry
17682 		 * about flow control. The next packet will go
17683 		 * through the flow control check in tcp_wput_data().
17684 		 */
17685 		/* leftover work from above */
17686 		tcp->tcp_unsent = len;
17687 		tcp->tcp_xmit_tail_unsent = len;
17688 
17689 		return;
17690 	}
17691 
17692 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17693 
17694 	if (snxt == suna) {
17695 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17696 	}
17697 
17698 	/* we have always sent something */
17699 	tcp->tcp_rack_cnt = 0;
17700 
17701 	tcp->tcp_snxt = snxt + len;
17702 	tcp->tcp_rack = tcp->tcp_rnxt;
17703 
17704 	if ((mp1 = dupb(mp)) == 0)
17705 		goto no_memory;
17706 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17707 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17708 
17709 	/* adjust tcp header information */
17710 	tcph = tcp->tcp_tcph;
17711 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17712 
17713 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17714 	sum = (sum >> 16) + (sum & 0xFFFF);
17715 	U16_TO_ABE16(sum, tcph->th_sum);
17716 
17717 	U32_TO_ABE32(snxt, tcph->th_seq);
17718 
17719 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17720 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17721 	BUMP_LOCAL(tcp->tcp_obsegs);
17722 
17723 	/* Update the latest receive window size in TCP header. */
17724 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17725 	    tcph->th_win);
17726 
17727 	tcp->tcp_last_sent_len = (ushort_t)len;
17728 
17729 	plen = len + tcp->tcp_hdr_len;
17730 
17731 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17732 		tcp->tcp_ipha->ipha_length = htons(plen);
17733 	} else {
17734 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17735 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17736 	}
17737 
17738 	/* see if we need to allocate a mblk for the headers */
17739 	hdrlen = tcp->tcp_hdr_len;
17740 	rptr = mp1->b_rptr - hdrlen;
17741 	db = mp1->b_datap;
17742 	if ((db->db_ref != 2) || rptr < db->db_base ||
17743 	    (!OK_32PTR(rptr))) {
17744 		/* NOTE: we assume allocb returns an OK_32PTR */
17745 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17746 		    tcps->tcps_wroff_xtra, BPRI_MED);
17747 		if (!mp) {
17748 			freemsg(mp1);
17749 			goto no_memory;
17750 		}
17751 		mp->b_cont = mp1;
17752 		mp1 = mp;
17753 		/* Leave room for Link Level header */
17754 		/* hdrlen = tcp->tcp_hdr_len; */
17755 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17756 		mp1->b_wptr = &rptr[hdrlen];
17757 	}
17758 	mp1->b_rptr = rptr;
17759 
17760 	/* Fill in the timestamp option. */
17761 	if (tcp->tcp_snd_ts_ok) {
17762 		U32_TO_BE32((uint32_t)lbolt,
17763 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17764 		U32_TO_BE32(tcp->tcp_ts_recent,
17765 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17766 	} else {
17767 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17768 	}
17769 
17770 	/* copy header into outgoing packet */
17771 	dst = (ipaddr_t *)rptr;
17772 	src = (ipaddr_t *)tcp->tcp_iphc;
17773 	dst[0] = src[0];
17774 	dst[1] = src[1];
17775 	dst[2] = src[2];
17776 	dst[3] = src[3];
17777 	dst[4] = src[4];
17778 	dst[5] = src[5];
17779 	dst[6] = src[6];
17780 	dst[7] = src[7];
17781 	dst[8] = src[8];
17782 	dst[9] = src[9];
17783 	if (hdrlen -= 40) {
17784 		hdrlen >>= 2;
17785 		dst += 10;
17786 		src += 10;
17787 		do {
17788 			*dst++ = *src++;
17789 		} while (--hdrlen);
17790 	}
17791 
17792 	/*
17793 	 * Set the ECN info in the TCP header.  Note that this
17794 	 * is not the template header.
17795 	 */
17796 	if (tcp->tcp_ecn_ok) {
17797 		SET_ECT(tcp, rptr);
17798 
17799 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17800 		if (tcp->tcp_ecn_echo_on)
17801 			tcph->th_flags[0] |= TH_ECE;
17802 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17803 			tcph->th_flags[0] |= TH_CWR;
17804 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17805 		}
17806 	}
17807 
17808 	if (tcp->tcp_ip_forward_progress) {
17809 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17810 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17811 		tcp->tcp_ip_forward_progress = B_FALSE;
17812 	}
17813 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17814 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17815 	return;
17816 
17817 	/*
17818 	 * If we ran out of memory, we pretend to have sent the packet
17819 	 * and that it was lost on the wire.
17820 	 */
17821 no_memory:
17822 	return;
17823 
17824 slow:
17825 	/* leftover work from above */
17826 	tcp->tcp_unsent = len;
17827 	tcp->tcp_xmit_tail_unsent = len;
17828 	tcp_wput_data(tcp, NULL, B_FALSE);
17829 }
17830 
17831 /*
17832  * The function called through squeue to get behind eager's perimeter to
17833  * finish the accept processing.
17834  */
17835 /* ARGSUSED */
17836 void
17837 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17838 {
17839 	conn_t			*connp = (conn_t *)arg;
17840 	tcp_t			*tcp = connp->conn_tcp;
17841 	queue_t			*q = tcp->tcp_rq;
17842 	mblk_t			*mp1;
17843 	mblk_t			*stropt_mp = mp;
17844 	struct  stroptions	*stropt;
17845 	uint_t			thwin;
17846 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17847 
17848 	/*
17849 	 * Drop the eager's ref on the listener, that was placed when
17850 	 * this eager began life in tcp_conn_request.
17851 	 */
17852 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17853 
17854 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17855 		/*
17856 		 * Someone blewoff the eager before we could finish
17857 		 * the accept.
17858 		 *
17859 		 * The only reason eager exists it because we put in
17860 		 * a ref on it when conn ind went up. We need to send
17861 		 * a disconnect indication up while the last reference
17862 		 * on the eager will be dropped by the squeue when we
17863 		 * return.
17864 		 */
17865 		ASSERT(tcp->tcp_listener == NULL);
17866 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17867 			struct	T_discon_ind	*tdi;
17868 
17869 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17870 			/*
17871 			 * Let us reuse the incoming mblk to avoid memory
17872 			 * allocation failure problems. We know that the
17873 			 * size of the incoming mblk i.e. stroptions is greater
17874 			 * than sizeof T_discon_ind. So the reallocb below
17875 			 * can't fail.
17876 			 */
17877 			freemsg(mp->b_cont);
17878 			mp->b_cont = NULL;
17879 			ASSERT(DB_REF(mp) == 1);
17880 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17881 			    B_FALSE);
17882 			ASSERT(mp != NULL);
17883 			DB_TYPE(mp) = M_PROTO;
17884 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17885 			tdi = (struct T_discon_ind *)mp->b_rptr;
17886 			if (tcp->tcp_issocket) {
17887 				tdi->DISCON_reason = ECONNREFUSED;
17888 				tdi->SEQ_number = 0;
17889 			} else {
17890 				tdi->DISCON_reason = ENOPROTOOPT;
17891 				tdi->SEQ_number =
17892 				    tcp->tcp_conn_req_seqnum;
17893 			}
17894 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17895 			putnext(q, mp);
17896 		} else {
17897 			freemsg(mp);
17898 		}
17899 		if (tcp->tcp_hard_binding) {
17900 			tcp->tcp_hard_binding = B_FALSE;
17901 			tcp->tcp_hard_bound = B_TRUE;
17902 		}
17903 		tcp->tcp_detached = B_FALSE;
17904 		return;
17905 	}
17906 
17907 	mp1 = stropt_mp->b_cont;
17908 	stropt_mp->b_cont = NULL;
17909 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17910 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17911 
17912 	while (mp1 != NULL) {
17913 		mp = mp1;
17914 		mp1 = mp1->b_cont;
17915 		mp->b_cont = NULL;
17916 		tcp->tcp_drop_opt_ack_cnt++;
17917 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17918 	}
17919 	mp = NULL;
17920 
17921 	/*
17922 	 * For a loopback connection with tcp_direct_sockfs on, note that
17923 	 * we don't have to protect tcp_rcv_list yet because synchronous
17924 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17925 	 * possibly race with us.
17926 	 */
17927 
17928 	/*
17929 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17930 	 * properly.  This is the first time we know of the acceptor'
17931 	 * queue.  So we do it here.
17932 	 */
17933 	if (tcp->tcp_rcv_list == NULL) {
17934 		/*
17935 		 * Recv queue is empty, tcp_rwnd should not have changed.
17936 		 * That means it should be equal to the listener's tcp_rwnd.
17937 		 */
17938 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17939 	} else {
17940 #ifdef DEBUG
17941 		uint_t cnt = 0;
17942 
17943 		mp1 = tcp->tcp_rcv_list;
17944 		while ((mp = mp1) != NULL) {
17945 			mp1 = mp->b_next;
17946 			cnt += msgdsize(mp);
17947 		}
17948 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17949 #endif
17950 		/* There is some data, add them back to get the max. */
17951 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17952 	}
17953 
17954 	stropt->so_flags = SO_HIWAT;
17955 	stropt->so_hiwat = MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
17956 
17957 	stropt->so_flags |= SO_MAXBLK;
17958 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17959 
17960 	/*
17961 	 * This is the first time we run on the correct
17962 	 * queue after tcp_accept. So fix all the q parameters
17963 	 * here.
17964 	 */
17965 	/* Allocate room for SACK options if needed. */
17966 	stropt->so_flags |= SO_WROFF;
17967 	if (tcp->tcp_fused) {
17968 		ASSERT(tcp->tcp_loopback);
17969 		ASSERT(tcp->tcp_loopback_peer != NULL);
17970 		/*
17971 		 * For fused tcp loopback, set the stream head's write
17972 		 * offset value to zero since we won't be needing any room
17973 		 * for TCP/IP headers.  This would also improve performance
17974 		 * since it would reduce the amount of work done by kmem.
17975 		 * Non-fused tcp loopback case is handled separately below.
17976 		 */
17977 		stropt->so_wroff = 0;
17978 		/*
17979 		 * Record the stream head's high water mark for this endpoint;
17980 		 * this is used for flow-control purposes in tcp_fuse_output().
17981 		 */
17982 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17983 		/*
17984 		 * Update the peer's transmit parameters according to
17985 		 * our recently calculated high water mark value.
17986 		 */
17987 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17988 	} else if (tcp->tcp_snd_sack_ok) {
17989 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17990 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
17991 	} else {
17992 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17993 		    tcps->tcps_wroff_xtra);
17994 	}
17995 
17996 	/*
17997 	 * If this is endpoint is handling SSL, then reserve extra
17998 	 * offset and space at the end.
17999 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18000 	 * overriding the previous setting. The extra cost of signing and
18001 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18002 	 * instead of a single contiguous one by the stream head
18003 	 * largely outweighs the statistical reduction of ACKs, when
18004 	 * applicable. The peer will also save on decyption and verification
18005 	 * costs.
18006 	 */
18007 	if (tcp->tcp_kssl_ctx != NULL) {
18008 		stropt->so_wroff += SSL3_WROFFSET;
18009 
18010 		stropt->so_flags |= SO_TAIL;
18011 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18012 
18013 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18014 	}
18015 
18016 	/* Send the options up */
18017 	putnext(q, stropt_mp);
18018 
18019 	/*
18020 	 * Pass up any data and/or a fin that has been received.
18021 	 *
18022 	 * Adjust receive window in case it had decreased
18023 	 * (because there is data <=> tcp_rcv_list != NULL)
18024 	 * while the connection was detached. Note that
18025 	 * in case the eager was flow-controlled, w/o this
18026 	 * code, the rwnd may never open up again!
18027 	 */
18028 	if (tcp->tcp_rcv_list != NULL) {
18029 		/* We drain directly in case of fused tcp loopback */
18030 		if (!tcp->tcp_fused && canputnext(q)) {
18031 			tcp->tcp_rwnd = q->q_hiwat;
18032 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18033 			    << tcp->tcp_rcv_ws;
18034 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18035 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18036 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18037 				tcp_xmit_ctl(NULL,
18038 				    tcp, (tcp->tcp_swnd == 0) ?
18039 				    tcp->tcp_suna : tcp->tcp_snxt,
18040 				    tcp->tcp_rnxt, TH_ACK);
18041 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18042 			}
18043 
18044 		}
18045 		(void) tcp_rcv_drain(q, tcp);
18046 
18047 		/*
18048 		 * For fused tcp loopback, back-enable peer endpoint
18049 		 * if it's currently flow-controlled.
18050 		 */
18051 		if (tcp->tcp_fused) {
18052 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18053 
18054 			ASSERT(peer_tcp != NULL);
18055 			ASSERT(peer_tcp->tcp_fused);
18056 			/*
18057 			 * In order to change the peer's tcp_flow_stopped,
18058 			 * we need to take locks for both end points. The
18059 			 * highest address is taken first.
18060 			 */
18061 			if (peer_tcp > tcp) {
18062 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18063 				mutex_enter(&tcp->tcp_non_sq_lock);
18064 			} else {
18065 				mutex_enter(&tcp->tcp_non_sq_lock);
18066 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18067 			}
18068 			if (peer_tcp->tcp_flow_stopped) {
18069 				tcp_clrqfull(peer_tcp);
18070 				TCP_STAT(tcps, tcp_fusion_backenabled);
18071 			}
18072 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18073 			mutex_exit(&tcp->tcp_non_sq_lock);
18074 		}
18075 	}
18076 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18077 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18078 		mp = mi_tpi_ordrel_ind();
18079 		if (mp) {
18080 			tcp->tcp_ordrel_done = B_TRUE;
18081 			putnext(q, mp);
18082 			if (tcp->tcp_deferred_clean_death) {
18083 				/*
18084 				 * tcp_clean_death was deferred
18085 				 * for T_ORDREL_IND - do it now
18086 				 */
18087 				(void) tcp_clean_death(tcp,
18088 				    tcp->tcp_client_errno, 21);
18089 				tcp->tcp_deferred_clean_death = B_FALSE;
18090 			}
18091 		} else {
18092 			/*
18093 			 * Run the orderly release in the
18094 			 * service routine.
18095 			 */
18096 			qenable(q);
18097 		}
18098 	}
18099 	if (tcp->tcp_hard_binding) {
18100 		tcp->tcp_hard_binding = B_FALSE;
18101 		tcp->tcp_hard_bound = B_TRUE;
18102 	}
18103 
18104 	tcp->tcp_detached = B_FALSE;
18105 
18106 	/* We can enable synchronous streams now */
18107 	if (tcp->tcp_fused) {
18108 		tcp_fuse_syncstr_enable_pair(tcp);
18109 	}
18110 
18111 	if (tcp->tcp_ka_enabled) {
18112 		tcp->tcp_ka_last_intrvl = 0;
18113 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18114 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18115 	}
18116 
18117 	/*
18118 	 * At this point, eager is fully established and will
18119 	 * have the following references -
18120 	 *
18121 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18122 	 * 1 reference for the squeue which will be dropped by the squeue as
18123 	 *	soon as this function returns.
18124 	 * There will be 1 additonal reference for being in classifier
18125 	 *	hash list provided something bad hasn't happened.
18126 	 */
18127 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18128 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18129 }
18130 
18131 /*
18132  * The function called through squeue to get behind listener's perimeter to
18133  * send a deffered conn_ind.
18134  */
18135 /* ARGSUSED */
18136 void
18137 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18138 {
18139 	conn_t	*connp = (conn_t *)arg;
18140 	tcp_t *listener = connp->conn_tcp;
18141 
18142 	if (listener->tcp_state == TCPS_CLOSED ||
18143 	    TCP_IS_DETACHED(listener)) {
18144 		/*
18145 		 * If listener has closed, it would have caused a
18146 		 * a cleanup/blowoff to happen for the eager.
18147 		 */
18148 		tcp_t *tcp;
18149 		struct T_conn_ind	*conn_ind;
18150 
18151 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18152 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18153 		    conn_ind->OPT_length);
18154 		/*
18155 		 * We need to drop the ref on eager that was put
18156 		 * tcp_rput_data() before trying to send the conn_ind
18157 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18158 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18159 		 * listener is closed so we drop the ref.
18160 		 */
18161 		CONN_DEC_REF(tcp->tcp_connp);
18162 		freemsg(mp);
18163 		return;
18164 	}
18165 	putnext(listener->tcp_rq, mp);
18166 }
18167 
18168 
18169 /*
18170  * This is the STREAMS entry point for T_CONN_RES coming down on
18171  * Acceptor STREAM when  sockfs listener does accept processing.
18172  * Read the block comment on top of tcp_conn_request().
18173  */
18174 void
18175 tcp_wput_accept(queue_t *q, mblk_t *mp)
18176 {
18177 	queue_t *rq = RD(q);
18178 	struct T_conn_res *conn_res;
18179 	tcp_t *eager;
18180 	tcp_t *listener;
18181 	struct T_ok_ack *ok;
18182 	t_scalar_t PRIM_type;
18183 	mblk_t *opt_mp;
18184 	conn_t *econnp;
18185 
18186 	ASSERT(DB_TYPE(mp) == M_PROTO);
18187 
18188 	conn_res = (struct T_conn_res *)mp->b_rptr;
18189 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18190 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18191 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18192 		if (mp != NULL)
18193 			putnext(rq, mp);
18194 		return;
18195 	}
18196 	switch (conn_res->PRIM_type) {
18197 	case O_T_CONN_RES:
18198 	case T_CONN_RES:
18199 		/*
18200 		 * We pass up an err ack if allocb fails. This will
18201 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18202 		 * tcp_eager_blowoff to be called. sockfs will then call
18203 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18204 		 * we need to do the allocb up here because we have to
18205 		 * make sure rq->q_qinfo->qi_qclose still points to the
18206 		 * correct function (tcpclose_accept) in case allocb
18207 		 * fails.
18208 		 */
18209 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18210 		if (opt_mp == NULL) {
18211 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18212 			if (mp != NULL)
18213 				putnext(rq, mp);
18214 			return;
18215 		}
18216 
18217 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18218 		    &eager, conn_res->OPT_length);
18219 		PRIM_type = conn_res->PRIM_type;
18220 		mp->b_datap->db_type = M_PCPROTO;
18221 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18222 		ok = (struct T_ok_ack *)mp->b_rptr;
18223 		ok->PRIM_type = T_OK_ACK;
18224 		ok->CORRECT_prim = PRIM_type;
18225 		econnp = eager->tcp_connp;
18226 		econnp->conn_dev = (dev_t)q->q_ptr;
18227 		eager->tcp_rq = rq;
18228 		eager->tcp_wq = q;
18229 		rq->q_ptr = econnp;
18230 		rq->q_qinfo = &tcp_rinit;
18231 		q->q_ptr = econnp;
18232 		q->q_qinfo = &tcp_winit;
18233 		listener = eager->tcp_listener;
18234 		eager->tcp_issocket = B_TRUE;
18235 
18236 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18237 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18238 		ASSERT(econnp->conn_netstack ==
18239 		    listener->tcp_connp->conn_netstack);
18240 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18241 
18242 		/* Put the ref for IP */
18243 		CONN_INC_REF(econnp);
18244 
18245 		/*
18246 		 * We should have minimum of 3 references on the conn
18247 		 * at this point. One each for TCP and IP and one for
18248 		 * the T_conn_ind that was sent up when the 3-way handshake
18249 		 * completed. In the normal case we would also have another
18250 		 * reference (making a total of 4) for the conn being in the
18251 		 * classifier hash list. However the eager could have received
18252 		 * an RST subsequently and tcp_closei_local could have removed
18253 		 * the eager from the classifier hash list, hence we can't
18254 		 * assert that reference.
18255 		 */
18256 		ASSERT(econnp->conn_ref >= 3);
18257 
18258 		/*
18259 		 * Send the new local address also up to sockfs. There
18260 		 * should already be enough space in the mp that came
18261 		 * down from soaccept().
18262 		 */
18263 		if (eager->tcp_family == AF_INET) {
18264 			sin_t *sin;
18265 
18266 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18267 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18268 			sin = (sin_t *)mp->b_wptr;
18269 			mp->b_wptr += sizeof (sin_t);
18270 			sin->sin_family = AF_INET;
18271 			sin->sin_port = eager->tcp_lport;
18272 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18273 		} else {
18274 			sin6_t *sin6;
18275 
18276 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18277 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18278 			sin6 = (sin6_t *)mp->b_wptr;
18279 			mp->b_wptr += sizeof (sin6_t);
18280 			sin6->sin6_family = AF_INET6;
18281 			sin6->sin6_port = eager->tcp_lport;
18282 			if (eager->tcp_ipversion == IPV4_VERSION) {
18283 				sin6->sin6_flowinfo = 0;
18284 				IN6_IPADDR_TO_V4MAPPED(
18285 					eager->tcp_ipha->ipha_src,
18286 					    &sin6->sin6_addr);
18287 			} else {
18288 				ASSERT(eager->tcp_ip6h != NULL);
18289 				sin6->sin6_flowinfo =
18290 				    eager->tcp_ip6h->ip6_vcf &
18291 				    ~IPV6_VERS_AND_FLOW_MASK;
18292 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18293 			}
18294 			sin6->sin6_scope_id = 0;
18295 			sin6->__sin6_src_id = 0;
18296 		}
18297 
18298 		putnext(rq, mp);
18299 
18300 		opt_mp->b_datap->db_type = M_SETOPTS;
18301 		opt_mp->b_wptr += sizeof (struct stroptions);
18302 
18303 		/*
18304 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18305 		 * from listener to acceptor. The message is chained on the
18306 		 * bind_mp which tcp_rput_other will send down to IP.
18307 		 */
18308 		if (listener->tcp_bound_if != 0) {
18309 			/* allocate optmgmt req */
18310 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18311 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18312 			    sizeof (int));
18313 			if (mp != NULL)
18314 				linkb(opt_mp, mp);
18315 		}
18316 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18317 			uint_t on = 1;
18318 
18319 			/* allocate optmgmt req */
18320 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18321 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18322 			if (mp != NULL)
18323 				linkb(opt_mp, mp);
18324 		}
18325 
18326 
18327 		mutex_enter(&listener->tcp_eager_lock);
18328 
18329 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18330 
18331 			tcp_t *tail;
18332 			tcp_t *tcp;
18333 			mblk_t *mp1;
18334 
18335 			tcp = listener->tcp_eager_prev_q0;
18336 			/*
18337 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18338 			 * deferred T_conn_ind queue. We need to get to the head
18339 			 * of the queue in order to send up T_conn_ind the same
18340 			 * order as how the 3WHS is completed.
18341 			 */
18342 			while (tcp != listener) {
18343 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18344 				    !tcp->tcp_kssl_pending)
18345 					break;
18346 				else
18347 					tcp = tcp->tcp_eager_prev_q0;
18348 			}
18349 			/* None of the pending eagers can be sent up now */
18350 			if (tcp == listener)
18351 				goto no_more_eagers;
18352 
18353 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18354 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18355 			/* Move from q0 to q */
18356 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18357 			listener->tcp_conn_req_cnt_q0--;
18358 			listener->tcp_conn_req_cnt_q++;
18359 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18360 			    tcp->tcp_eager_prev_q0;
18361 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18362 			    tcp->tcp_eager_next_q0;
18363 			tcp->tcp_eager_prev_q0 = NULL;
18364 			tcp->tcp_eager_next_q0 = NULL;
18365 			tcp->tcp_conn_def_q0 = B_FALSE;
18366 
18367 			/* Make sure the tcp isn't in the list of droppables */
18368 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18369 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18370 
18371 			/*
18372 			 * Insert at end of the queue because sockfs sends
18373 			 * down T_CONN_RES in chronological order. Leaving
18374 			 * the older conn indications at front of the queue
18375 			 * helps reducing search time.
18376 			 */
18377 			tail = listener->tcp_eager_last_q;
18378 			if (tail != NULL) {
18379 				tail->tcp_eager_next_q = tcp;
18380 			} else {
18381 				listener->tcp_eager_next_q = tcp;
18382 			}
18383 			listener->tcp_eager_last_q = tcp;
18384 			tcp->tcp_eager_next_q = NULL;
18385 
18386 			/* Need to get inside the listener perimeter */
18387 			CONN_INC_REF(listener->tcp_connp);
18388 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18389 			    tcp_send_pending, listener->tcp_connp,
18390 			    SQTAG_TCP_SEND_PENDING);
18391 		}
18392 no_more_eagers:
18393 		tcp_eager_unlink(eager);
18394 		mutex_exit(&listener->tcp_eager_lock);
18395 
18396 		/*
18397 		 * At this point, the eager is detached from the listener
18398 		 * but we still have an extra refs on eager (apart from the
18399 		 * usual tcp references). The ref was placed in tcp_rput_data
18400 		 * before sending the conn_ind in tcp_send_conn_ind.
18401 		 * The ref will be dropped in tcp_accept_finish().
18402 		 */
18403 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18404 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18405 		return;
18406 	default:
18407 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18408 		if (mp != NULL)
18409 			putnext(rq, mp);
18410 		return;
18411 	}
18412 }
18413 
18414 void
18415 tcp_wput(queue_t *q, mblk_t *mp)
18416 {
18417 	conn_t	*connp = Q_TO_CONN(q);
18418 	tcp_t	*tcp;
18419 	void (*output_proc)();
18420 	t_scalar_t type;
18421 	uchar_t *rptr;
18422 	struct iocblk	*iocp;
18423 	uint32_t	msize;
18424 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18425 
18426 	ASSERT(connp->conn_ref >= 2);
18427 
18428 	switch (DB_TYPE(mp)) {
18429 	case M_DATA:
18430 		tcp = connp->conn_tcp;
18431 		ASSERT(tcp != NULL);
18432 
18433 		msize = msgdsize(mp);
18434 
18435 		mutex_enter(&tcp->tcp_non_sq_lock);
18436 		tcp->tcp_squeue_bytes += msize;
18437 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18438 			tcp_setqfull(tcp);
18439 		}
18440 		mutex_exit(&tcp->tcp_non_sq_lock);
18441 
18442 		CONN_INC_REF(connp);
18443 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18444 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18445 		return;
18446 	case M_PROTO:
18447 	case M_PCPROTO:
18448 		/*
18449 		 * if it is a snmp message, don't get behind the squeue
18450 		 */
18451 		tcp = connp->conn_tcp;
18452 		rptr = mp->b_rptr;
18453 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18454 			type = ((union T_primitives *)rptr)->type;
18455 		} else {
18456 			if (tcp->tcp_debug) {
18457 				(void) strlog(TCP_MOD_ID, 0, 1,
18458 				    SL_ERROR|SL_TRACE,
18459 				    "tcp_wput_proto, dropping one...");
18460 			}
18461 			freemsg(mp);
18462 			return;
18463 		}
18464 		if (type == T_SVR4_OPTMGMT_REQ) {
18465 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18466 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18467 			    cr)) {
18468 				/*
18469 				 * This was a SNMP request
18470 				 */
18471 				return;
18472 			} else {
18473 				output_proc = tcp_wput_proto;
18474 			}
18475 		} else {
18476 			output_proc = tcp_wput_proto;
18477 		}
18478 		break;
18479 	case M_IOCTL:
18480 		/*
18481 		 * Most ioctls can be processed right away without going via
18482 		 * squeues - process them right here. Those that do require
18483 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18484 		 * are processed by tcp_wput_ioctl().
18485 		 */
18486 		iocp = (struct iocblk *)mp->b_rptr;
18487 		tcp = connp->conn_tcp;
18488 
18489 		switch (iocp->ioc_cmd) {
18490 		case TCP_IOC_ABORT_CONN:
18491 			tcp_ioctl_abort_conn(q, mp);
18492 			return;
18493 		case TI_GETPEERNAME:
18494 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18495 				iocp->ioc_error = ENOTCONN;
18496 				iocp->ioc_count = 0;
18497 				mp->b_datap->db_type = M_IOCACK;
18498 				qreply(q, mp);
18499 				return;
18500 			}
18501 			/* FALLTHRU */
18502 		case TI_GETMYNAME:
18503 			mi_copyin(q, mp, NULL,
18504 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18505 			return;
18506 		case ND_SET:
18507 			/* nd_getset does the necessary checks */
18508 		case ND_GET:
18509 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18510 				CALL_IP_WPUT(connp, q, mp);
18511 				return;
18512 			}
18513 			qreply(q, mp);
18514 			return;
18515 		case TCP_IOC_DEFAULT_Q:
18516 			/*
18517 			 * Wants to be the default wq. Check the credentials
18518 			 * first, the rest is executed via squeue.
18519 			 */
18520 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18521 				iocp->ioc_error = EPERM;
18522 				iocp->ioc_count = 0;
18523 				mp->b_datap->db_type = M_IOCACK;
18524 				qreply(q, mp);
18525 				return;
18526 			}
18527 			output_proc = tcp_wput_ioctl;
18528 			break;
18529 		default:
18530 			output_proc = tcp_wput_ioctl;
18531 			break;
18532 		}
18533 		break;
18534 	default:
18535 		output_proc = tcp_wput_nondata;
18536 		break;
18537 	}
18538 
18539 	CONN_INC_REF(connp);
18540 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18541 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18542 }
18543 
18544 /*
18545  * Initial STREAMS write side put() procedure for sockets. It tries to
18546  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18547  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18548  * are handled by tcp_wput() as usual.
18549  *
18550  * All further messages will also be handled by tcp_wput() because we cannot
18551  * be sure that the above short cut is safe later.
18552  */
18553 static void
18554 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18555 {
18556 	conn_t			*connp = Q_TO_CONN(wq);
18557 	tcp_t			*tcp = connp->conn_tcp;
18558 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18559 
18560 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18561 	wq->q_qinfo = &tcp_winit;
18562 
18563 	ASSERT(IPCL_IS_TCP(connp));
18564 	ASSERT(TCP_IS_SOCKET(tcp));
18565 
18566 	if (DB_TYPE(mp) == M_PCPROTO &&
18567 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18568 	    car->PRIM_type == T_CAPABILITY_REQ) {
18569 		tcp_capability_req(tcp, mp);
18570 		return;
18571 	}
18572 
18573 	tcp_wput(wq, mp);
18574 }
18575 
18576 static boolean_t
18577 tcp_zcopy_check(tcp_t *tcp)
18578 {
18579 	conn_t	*connp = tcp->tcp_connp;
18580 	ire_t	*ire;
18581 	boolean_t	zc_enabled = B_FALSE;
18582 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18583 
18584 	if (do_tcpzcopy == 2)
18585 		zc_enabled = B_TRUE;
18586 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18587 	    IPCL_IS_CONNECTED(connp) &&
18588 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18589 	    connp->conn_dontroute == 0 &&
18590 	    !connp->conn_nexthop_set &&
18591 	    connp->conn_xmit_if_ill == NULL &&
18592 	    connp->conn_nofailover_ill == NULL &&
18593 	    do_tcpzcopy == 1) {
18594 		/*
18595 		 * the checks above  closely resemble the fast path checks
18596 		 * in tcp_send_data().
18597 		 */
18598 		mutex_enter(&connp->conn_lock);
18599 		ire = connp->conn_ire_cache;
18600 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18601 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18602 			IRE_REFHOLD(ire);
18603 			if (ire->ire_stq != NULL) {
18604 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18605 
18606 				zc_enabled = ill && (ill->ill_capabilities &
18607 				    ILL_CAPAB_ZEROCOPY) &&
18608 				    (ill->ill_zerocopy_capab->
18609 				    ill_zerocopy_flags != 0);
18610 			}
18611 			IRE_REFRELE(ire);
18612 		}
18613 		mutex_exit(&connp->conn_lock);
18614 	}
18615 	tcp->tcp_snd_zcopy_on = zc_enabled;
18616 	if (!TCP_IS_DETACHED(tcp)) {
18617 		if (zc_enabled) {
18618 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18619 			TCP_STAT(tcps, tcp_zcopy_on);
18620 		} else {
18621 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18622 			TCP_STAT(tcps, tcp_zcopy_off);
18623 		}
18624 	}
18625 	return (zc_enabled);
18626 }
18627 
18628 static mblk_t *
18629 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18630 {
18631 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18632 
18633 	if (do_tcpzcopy == 2)
18634 		return (bp);
18635 	else if (tcp->tcp_snd_zcopy_on) {
18636 		tcp->tcp_snd_zcopy_on = B_FALSE;
18637 		if (!TCP_IS_DETACHED(tcp)) {
18638 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18639 			TCP_STAT(tcps, tcp_zcopy_disable);
18640 		}
18641 	}
18642 	return (tcp_zcopy_backoff(tcp, bp, 0));
18643 }
18644 
18645 /*
18646  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18647  * the original desballoca'ed segmapped mblk.
18648  */
18649 static mblk_t *
18650 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18651 {
18652 	mblk_t *head, *tail, *nbp;
18653 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18654 
18655 	if (IS_VMLOANED_MBLK(bp)) {
18656 		TCP_STAT(tcps, tcp_zcopy_backoff);
18657 		if ((head = copyb(bp)) == NULL) {
18658 			/* fail to backoff; leave it for the next backoff */
18659 			tcp->tcp_xmit_zc_clean = B_FALSE;
18660 			return (bp);
18661 		}
18662 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18663 			if (fix_xmitlist)
18664 				tcp_zcopy_notify(tcp);
18665 			else
18666 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18667 		}
18668 		nbp = bp->b_cont;
18669 		if (fix_xmitlist) {
18670 			head->b_prev = bp->b_prev;
18671 			head->b_next = bp->b_next;
18672 			if (tcp->tcp_xmit_tail == bp)
18673 				tcp->tcp_xmit_tail = head;
18674 		}
18675 		bp->b_next = NULL;
18676 		bp->b_prev = NULL;
18677 		freeb(bp);
18678 	} else {
18679 		head = bp;
18680 		nbp = bp->b_cont;
18681 	}
18682 	tail = head;
18683 	while (nbp) {
18684 		if (IS_VMLOANED_MBLK(nbp)) {
18685 			TCP_STAT(tcps, tcp_zcopy_backoff);
18686 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18687 				tcp->tcp_xmit_zc_clean = B_FALSE;
18688 				tail->b_cont = nbp;
18689 				return (head);
18690 			}
18691 			tail = tail->b_cont;
18692 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18693 				if (fix_xmitlist)
18694 					tcp_zcopy_notify(tcp);
18695 				else
18696 					tail->b_datap->db_struioflag |=
18697 					    STRUIO_ZCNOTIFY;
18698 			}
18699 			bp = nbp;
18700 			nbp = nbp->b_cont;
18701 			if (fix_xmitlist) {
18702 				tail->b_prev = bp->b_prev;
18703 				tail->b_next = bp->b_next;
18704 				if (tcp->tcp_xmit_tail == bp)
18705 					tcp->tcp_xmit_tail = tail;
18706 			}
18707 			bp->b_next = NULL;
18708 			bp->b_prev = NULL;
18709 			freeb(bp);
18710 		} else {
18711 			tail->b_cont = nbp;
18712 			tail = nbp;
18713 			nbp = nbp->b_cont;
18714 		}
18715 	}
18716 	if (fix_xmitlist) {
18717 		tcp->tcp_xmit_last = tail;
18718 		tcp->tcp_xmit_zc_clean = B_TRUE;
18719 	}
18720 	return (head);
18721 }
18722 
18723 static void
18724 tcp_zcopy_notify(tcp_t *tcp)
18725 {
18726 	struct stdata	*stp;
18727 
18728 	if (tcp->tcp_detached)
18729 		return;
18730 	stp = STREAM(tcp->tcp_rq);
18731 	mutex_enter(&stp->sd_lock);
18732 	stp->sd_flag |= STZCNOTIFY;
18733 	cv_broadcast(&stp->sd_zcopy_wait);
18734 	mutex_exit(&stp->sd_lock);
18735 }
18736 
18737 static boolean_t
18738 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
18739 {
18740 	ire_t	*ire;
18741 	conn_t	*connp = tcp->tcp_connp;
18742 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18743 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18744 
18745 	mutex_enter(&connp->conn_lock);
18746 	ire = connp->conn_ire_cache;
18747 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18748 
18749 	if ((ire != NULL) &&
18750 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
18751 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
18752 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18753 		IRE_REFHOLD(ire);
18754 		mutex_exit(&connp->conn_lock);
18755 	} else {
18756 		boolean_t cached = B_FALSE;
18757 		ts_label_t *tsl;
18758 
18759 		/* force a recheck later on */
18760 		tcp->tcp_ire_ill_check_done = B_FALSE;
18761 
18762 		TCP_DBGSTAT(tcps, tcp_ire_null1);
18763 		connp->conn_ire_cache = NULL;
18764 		mutex_exit(&connp->conn_lock);
18765 
18766 		if (ire != NULL)
18767 			IRE_REFRELE_NOTR(ire);
18768 
18769 		tsl = crgetlabel(CONN_CRED(connp));
18770 		ire = (dst ?
18771 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
18772 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18773 		    connp->conn_zoneid, tsl, ipst));
18774 
18775 		if (ire == NULL) {
18776 			TCP_STAT(tcps, tcp_ire_null);
18777 			return (B_FALSE);
18778 		}
18779 
18780 		IRE_REFHOLD_NOTR(ire);
18781 		/*
18782 		 * Since we are inside the squeue, there cannot be another
18783 		 * thread in TCP trying to set the conn_ire_cache now.  The
18784 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18785 		 * unplumb thread has not yet started cleaning up the conns.
18786 		 * Hence we don't need to grab the conn lock.
18787 		 */
18788 		if (CONN_CACHE_IRE(connp)) {
18789 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18790 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18791 				TCP_CHECK_IREINFO(tcp, ire);
18792 				connp->conn_ire_cache = ire;
18793 				cached = B_TRUE;
18794 			}
18795 			rw_exit(&ire->ire_bucket->irb_lock);
18796 		}
18797 
18798 		/*
18799 		 * We can continue to use the ire but since it was
18800 		 * not cached, we should drop the extra reference.
18801 		 */
18802 		if (!cached)
18803 			IRE_REFRELE_NOTR(ire);
18804 
18805 		/*
18806 		 * Rampart note: no need to select a new label here, since
18807 		 * labels are not allowed to change during the life of a TCP
18808 		 * connection.
18809 		 */
18810 	}
18811 
18812 	*irep = ire;
18813 
18814 	return (B_TRUE);
18815 }
18816 
18817 /*
18818  * Called from tcp_send() or tcp_send_data() to find workable IRE.
18819  *
18820  * 0 = success;
18821  * 1 = failed to find ire and ill.
18822  */
18823 static boolean_t
18824 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
18825 {
18826 	ipha_t		*ipha;
18827 	ipaddr_t	dst;
18828 	ire_t		*ire;
18829 	ill_t		*ill;
18830 	conn_t		*connp = tcp->tcp_connp;
18831 	mblk_t		*ire_fp_mp;
18832 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18833 
18834 	if (mp != NULL)
18835 		ipha = (ipha_t *)mp->b_rptr;
18836 	else
18837 		ipha = tcp->tcp_ipha;
18838 	dst = ipha->ipha_dst;
18839 
18840 	if (!tcp_send_find_ire(tcp, &dst, &ire))
18841 		return (B_FALSE);
18842 
18843 	if ((ire->ire_flags & RTF_MULTIRT) ||
18844 	    (ire->ire_stq == NULL) ||
18845 	    (ire->ire_nce == NULL) ||
18846 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
18847 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18848 		MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
18849 		TCP_STAT(tcps, tcp_ip_ire_send);
18850 		IRE_REFRELE(ire);
18851 		return (B_FALSE);
18852 	}
18853 
18854 	ill = ire_to_ill(ire);
18855 	if (connp->conn_outgoing_ill != NULL) {
18856 		ill_t *conn_outgoing_ill = NULL;
18857 		/*
18858 		 * Choose a good ill in the group to send the packets on.
18859 		 */
18860 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18861 		ill = ire_to_ill(ire);
18862 	}
18863 	ASSERT(ill != NULL);
18864 
18865 	if (!tcp->tcp_ire_ill_check_done) {
18866 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18867 		tcp->tcp_ire_ill_check_done = B_TRUE;
18868 	}
18869 
18870 	*irep = ire;
18871 	*illp = ill;
18872 
18873 	return (B_TRUE);
18874 }
18875 
18876 static void
18877 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18878 {
18879 	ipha_t		*ipha;
18880 	ipaddr_t	src;
18881 	ipaddr_t	dst;
18882 	uint32_t	cksum;
18883 	ire_t		*ire;
18884 	uint16_t	*up;
18885 	ill_t		*ill;
18886 	conn_t		*connp = tcp->tcp_connp;
18887 	uint32_t	hcksum_txflags = 0;
18888 	mblk_t		*ire_fp_mp;
18889 	uint_t		ire_fp_mp_len;
18890 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18891 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18892 
18893 	ASSERT(DB_TYPE(mp) == M_DATA);
18894 
18895 	if (DB_CRED(mp) == NULL)
18896 		mblk_setcred(mp, CONN_CRED(connp));
18897 
18898 	ipha = (ipha_t *)mp->b_rptr;
18899 	src = ipha->ipha_src;
18900 	dst = ipha->ipha_dst;
18901 
18902 	/*
18903 	 * Drop off fast path for IPv6 and also if options are present or
18904 	 * we need to resolve a TS label.
18905 	 */
18906 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18907 	    !IPCL_IS_CONNECTED(connp) ||
18908 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
18909 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18910 	    !connp->conn_ulp_labeled ||
18911 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18912 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18913 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
18914 		if (tcp->tcp_snd_zcopy_aware)
18915 			mp = tcp_zcopy_disable(tcp, mp);
18916 		TCP_STAT(tcps, tcp_ip_send);
18917 		CALL_IP_WPUT(connp, q, mp);
18918 		return;
18919 	}
18920 
18921 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
18922 		if (tcp->tcp_snd_zcopy_aware)
18923 			mp = tcp_zcopy_backoff(tcp, mp, 0);
18924 		CALL_IP_WPUT(connp, q, mp);
18925 		return;
18926 	}
18927 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
18928 	ire_fp_mp_len = MBLKL(ire_fp_mp);
18929 
18930 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18931 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18932 #ifndef _BIG_ENDIAN
18933 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18934 #endif
18935 
18936 	/*
18937 	 * Check to see if we need to re-enable LSO/MDT for this connection
18938 	 * because it was previously disabled due to changes in the ill;
18939 	 * note that by doing it here, this re-enabling only applies when
18940 	 * the packet is not dispatched through CALL_IP_WPUT().
18941 	 *
18942 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
18943 	 * case, since that's how we ended up here.  For IPv6, we do the
18944 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18945 	 */
18946 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
18947 		/*
18948 		 * Restore LSO for this connection, so that next time around
18949 		 * it is eligible to go through tcp_lsosend() path again.
18950 		 */
18951 		TCP_STAT(tcps, tcp_lso_enabled);
18952 		tcp->tcp_lso = B_TRUE;
18953 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
18954 		    "interface %s\n", (void *)connp, ill->ill_name));
18955 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18956 		/*
18957 		 * Restore MDT for this connection, so that next time around
18958 		 * it is eligible to go through tcp_multisend() path again.
18959 		 */
18960 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
18961 		tcp->tcp_mdt = B_TRUE;
18962 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18963 		    "interface %s\n", (void *)connp, ill->ill_name));
18964 	}
18965 
18966 	if (tcp->tcp_snd_zcopy_aware) {
18967 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18968 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18969 			mp = tcp_zcopy_disable(tcp, mp);
18970 		/*
18971 		 * we shouldn't need to reset ipha as the mp containing
18972 		 * ipha should never be a zero-copy mp.
18973 		 */
18974 	}
18975 
18976 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18977 		ASSERT(ill->ill_hcksum_capab != NULL);
18978 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18979 	}
18980 
18981 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18982 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18983 
18984 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18985 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18986 
18987 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18988 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18989 
18990 	/* Software checksum? */
18991 	if (DB_CKSUMFLAGS(mp) == 0) {
18992 		TCP_STAT(tcps, tcp_out_sw_cksum);
18993 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
18994 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18995 	}
18996 
18997 	ipha->ipha_fragment_offset_and_flags |=
18998 	    (uint32_t)htons(ire->ire_frag_flag);
18999 
19000 	/* Calculate IP header checksum if hardware isn't capable */
19001 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19002 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19003 		    ((uint16_t *)ipha)[4]);
19004 	}
19005 
19006 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19007 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19008 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19009 
19010 	UPDATE_OB_PKT_COUNT(ire);
19011 	ire->ire_last_used_time = lbolt;
19012 
19013 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19014 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19015 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19016 	    ntohs(ipha->ipha_length));
19017 
19018 	if (ILL_DLS_CAPABLE(ill)) {
19019 		/*
19020 		 * Send the packet directly to DLD, where it may be queued
19021 		 * depending on the availability of transmit resources at
19022 		 * the media layer.
19023 		 */
19024 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19025 	} else {
19026 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19027 		DTRACE_PROBE4(ip4__physical__out__start,
19028 		    ill_t *, NULL, ill_t *, out_ill,
19029 		    ipha_t *, ipha, mblk_t *, mp);
19030 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19031 		    ipst->ips_ipv4firewall_physical_out,
19032 		    NULL, out_ill, ipha, mp, mp, ipst);
19033 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19034 		if (mp != NULL)
19035 			putnext(ire->ire_stq, mp);
19036 	}
19037 	IRE_REFRELE(ire);
19038 }
19039 
19040 /*
19041  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19042  * if the receiver shrinks the window, i.e. moves the right window to the
19043  * left, the we should not send new data, but should retransmit normally the
19044  * old unacked data between suna and suna + swnd. We might has sent data
19045  * that is now outside the new window, pretend that we didn't send  it.
19046  */
19047 static void
19048 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19049 {
19050 	uint32_t	snxt = tcp->tcp_snxt;
19051 	mblk_t		*xmit_tail;
19052 	int32_t		offset;
19053 
19054 	ASSERT(shrunk_count > 0);
19055 
19056 	/* Pretend we didn't send the data outside the window */
19057 	snxt -= shrunk_count;
19058 
19059 	/* Get the mblk and the offset in it per the shrunk window */
19060 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19061 
19062 	ASSERT(xmit_tail != NULL);
19063 
19064 	/* Reset all the values per the now shrunk window */
19065 	tcp->tcp_snxt = snxt;
19066 	tcp->tcp_xmit_tail = xmit_tail;
19067 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19068 	    offset;
19069 	tcp->tcp_unsent += shrunk_count;
19070 
19071 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19072 		/*
19073 		 * Make sure the timer is running so that we will probe a zero
19074 		 * window.
19075 		 */
19076 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19077 }
19078 
19079 
19080 /*
19081  * The TCP normal data output path.
19082  * NOTE: the logic of the fast path is duplicated from this function.
19083  */
19084 static void
19085 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19086 {
19087 	int		len;
19088 	mblk_t		*local_time;
19089 	mblk_t		*mp1;
19090 	uint32_t	snxt;
19091 	int		tail_unsent;
19092 	int		tcpstate;
19093 	int		usable = 0;
19094 	mblk_t		*xmit_tail;
19095 	queue_t		*q = tcp->tcp_wq;
19096 	int32_t		mss;
19097 	int32_t		num_sack_blk = 0;
19098 	int32_t		tcp_hdr_len;
19099 	int32_t		tcp_tcp_hdr_len;
19100 	int		mdt_thres;
19101 	int		rc;
19102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19103 	ip_stack_t	*ipst;
19104 
19105 	tcpstate = tcp->tcp_state;
19106 	if (mp == NULL) {
19107 		/*
19108 		 * tcp_wput_data() with NULL mp should only be called when
19109 		 * there is unsent data.
19110 		 */
19111 		ASSERT(tcp->tcp_unsent > 0);
19112 		/* Really tacky... but we need this for detached closes. */
19113 		len = tcp->tcp_unsent;
19114 		goto data_null;
19115 	}
19116 
19117 #if CCS_STATS
19118 	wrw_stats.tot.count++;
19119 	wrw_stats.tot.bytes += msgdsize(mp);
19120 #endif
19121 	ASSERT(mp->b_datap->db_type == M_DATA);
19122 	/*
19123 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19124 	 * or before a connection attempt has begun.
19125 	 */
19126 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19127 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19128 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19129 #ifdef DEBUG
19130 			cmn_err(CE_WARN,
19131 			    "tcp_wput_data: data after ordrel, %s",
19132 			    tcp_display(tcp, NULL,
19133 			    DISP_ADDR_AND_PORT));
19134 #else
19135 			if (tcp->tcp_debug) {
19136 				(void) strlog(TCP_MOD_ID, 0, 1,
19137 				    SL_TRACE|SL_ERROR,
19138 				    "tcp_wput_data: data after ordrel, %s\n",
19139 				    tcp_display(tcp, NULL,
19140 				    DISP_ADDR_AND_PORT));
19141 			}
19142 #endif /* DEBUG */
19143 		}
19144 		if (tcp->tcp_snd_zcopy_aware &&
19145 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19146 			tcp_zcopy_notify(tcp);
19147 		freemsg(mp);
19148 		mutex_enter(&tcp->tcp_non_sq_lock);
19149 		if (tcp->tcp_flow_stopped &&
19150 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19151 			tcp_clrqfull(tcp);
19152 		}
19153 		mutex_exit(&tcp->tcp_non_sq_lock);
19154 		return;
19155 	}
19156 
19157 	/* Strip empties */
19158 	for (;;) {
19159 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19160 		    (uintptr_t)INT_MAX);
19161 		len = (int)(mp->b_wptr - mp->b_rptr);
19162 		if (len > 0)
19163 			break;
19164 		mp1 = mp;
19165 		mp = mp->b_cont;
19166 		freeb(mp1);
19167 		if (!mp) {
19168 			return;
19169 		}
19170 	}
19171 
19172 	/* If we are the first on the list ... */
19173 	if (tcp->tcp_xmit_head == NULL) {
19174 		tcp->tcp_xmit_head = mp;
19175 		tcp->tcp_xmit_tail = mp;
19176 		tcp->tcp_xmit_tail_unsent = len;
19177 	} else {
19178 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19179 		struct datab *dp;
19180 
19181 		mp1 = tcp->tcp_xmit_last;
19182 		if (len < tcp_tx_pull_len &&
19183 		    (dp = mp1->b_datap)->db_ref == 1 &&
19184 		    dp->db_lim - mp1->b_wptr >= len) {
19185 			ASSERT(len > 0);
19186 			ASSERT(!mp1->b_cont);
19187 			if (len == 1) {
19188 				*mp1->b_wptr++ = *mp->b_rptr;
19189 			} else {
19190 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19191 				mp1->b_wptr += len;
19192 			}
19193 			if (mp1 == tcp->tcp_xmit_tail)
19194 				tcp->tcp_xmit_tail_unsent += len;
19195 			mp1->b_cont = mp->b_cont;
19196 			if (tcp->tcp_snd_zcopy_aware &&
19197 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19198 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19199 			freeb(mp);
19200 			mp = mp1;
19201 		} else {
19202 			tcp->tcp_xmit_last->b_cont = mp;
19203 		}
19204 		len += tcp->tcp_unsent;
19205 	}
19206 
19207 	/* Tack on however many more positive length mblks we have */
19208 	if ((mp1 = mp->b_cont) != NULL) {
19209 		do {
19210 			int tlen;
19211 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19212 			    (uintptr_t)INT_MAX);
19213 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19214 			if (tlen <= 0) {
19215 				mp->b_cont = mp1->b_cont;
19216 				freeb(mp1);
19217 			} else {
19218 				len += tlen;
19219 				mp = mp1;
19220 			}
19221 		} while ((mp1 = mp->b_cont) != NULL);
19222 	}
19223 	tcp->tcp_xmit_last = mp;
19224 	tcp->tcp_unsent = len;
19225 
19226 	if (urgent)
19227 		usable = 1;
19228 
19229 data_null:
19230 	snxt = tcp->tcp_snxt;
19231 	xmit_tail = tcp->tcp_xmit_tail;
19232 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19233 
19234 	/*
19235 	 * Note that tcp_mss has been adjusted to take into account the
19236 	 * timestamp option if applicable.  Because SACK options do not
19237 	 * appear in every TCP segments and they are of variable lengths,
19238 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19239 	 * the actual segment length when we need to send a segment which
19240 	 * includes SACK options.
19241 	 */
19242 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19243 		int32_t	opt_len;
19244 
19245 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19246 		    tcp->tcp_num_sack_blk);
19247 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19248 		    2 + TCPOPT_HEADER_LEN;
19249 		mss = tcp->tcp_mss - opt_len;
19250 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19251 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19252 	} else {
19253 		mss = tcp->tcp_mss;
19254 		tcp_hdr_len = tcp->tcp_hdr_len;
19255 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19256 	}
19257 
19258 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19259 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19260 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19261 	}
19262 	if (tcpstate == TCPS_SYN_RCVD) {
19263 		/*
19264 		 * The three-way connection establishment handshake is not
19265 		 * complete yet. We want to queue the data for transmission
19266 		 * after entering ESTABLISHED state (RFC793). A jump to
19267 		 * "done" label effectively leaves data on the queue.
19268 		 */
19269 		goto done;
19270 	} else {
19271 		int usable_r;
19272 
19273 		/*
19274 		 * In the special case when cwnd is zero, which can only
19275 		 * happen if the connection is ECN capable, return now.
19276 		 * New segments is sent using tcp_timer().  The timer
19277 		 * is set in tcp_rput_data().
19278 		 */
19279 		if (tcp->tcp_cwnd == 0) {
19280 			/*
19281 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19282 			 * finished.
19283 			 */
19284 			ASSERT(tcp->tcp_ecn_ok ||
19285 			    tcp->tcp_state < TCPS_ESTABLISHED);
19286 			return;
19287 		}
19288 
19289 		/* NOTE: trouble if xmitting while SYN not acked? */
19290 		usable_r = snxt - tcp->tcp_suna;
19291 		usable_r = tcp->tcp_swnd - usable_r;
19292 
19293 		/*
19294 		 * Check if the receiver has shrunk the window.  If
19295 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19296 		 * cannot be set as there is unsent data, so FIN cannot
19297 		 * be sent out.  Otherwise, we need to take into account
19298 		 * of FIN as it consumes an "invisible" sequence number.
19299 		 */
19300 		ASSERT(tcp->tcp_fin_sent == 0);
19301 		if (usable_r < 0) {
19302 			/*
19303 			 * The receiver has shrunk the window and we have sent
19304 			 * -usable_r date beyond the window, re-adjust.
19305 			 *
19306 			 * If TCP window scaling is enabled, there can be
19307 			 * round down error as the advertised receive window
19308 			 * is actually right shifted n bits.  This means that
19309 			 * the lower n bits info is wiped out.  It will look
19310 			 * like the window is shrunk.  Do a check here to
19311 			 * see if the shrunk amount is actually within the
19312 			 * error in window calculation.  If it is, just
19313 			 * return.  Note that this check is inside the
19314 			 * shrunk window check.  This makes sure that even
19315 			 * though tcp_process_shrunk_swnd() is not called,
19316 			 * we will stop further processing.
19317 			 */
19318 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19319 				tcp_process_shrunk_swnd(tcp, -usable_r);
19320 			}
19321 			return;
19322 		}
19323 
19324 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19325 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19326 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19327 
19328 		/* usable = MIN(usable, unsent) */
19329 		if (usable_r > len)
19330 			usable_r = len;
19331 
19332 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19333 		if (usable_r > 0) {
19334 			usable = usable_r;
19335 		} else {
19336 			/* Bypass all other unnecessary processing. */
19337 			goto done;
19338 		}
19339 	}
19340 
19341 	local_time = (mblk_t *)lbolt;
19342 
19343 	/*
19344 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19345 	 * BSD.  This is more in line with the true intent of Nagle.
19346 	 *
19347 	 * The conditions are:
19348 	 * 1. The amount of unsent data (or amount of data which can be
19349 	 *    sent, whichever is smaller) is less than Nagle limit.
19350 	 * 2. The last sent size is also less than Nagle limit.
19351 	 * 3. There is unack'ed data.
19352 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19353 	 *    Nagle algorithm.  This reduces the probability that urgent
19354 	 *    bytes get "merged" together.
19355 	 * 5. The app has not closed the connection.  This eliminates the
19356 	 *    wait time of the receiving side waiting for the last piece of
19357 	 *    (small) data.
19358 	 *
19359 	 * If all are satisified, exit without sending anything.  Note
19360 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19361 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19362 	 * 4095).
19363 	 */
19364 	if (usable < (int)tcp->tcp_naglim &&
19365 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19366 	    snxt != tcp->tcp_suna &&
19367 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19368 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19369 		goto done;
19370 	}
19371 
19372 	if (tcp->tcp_cork) {
19373 		/*
19374 		 * if the tcp->tcp_cork option is set, then we have to force
19375 		 * TCP not to send partial segment (smaller than MSS bytes).
19376 		 * We are calculating the usable now based on full mss and
19377 		 * will save the rest of remaining data for later.
19378 		 */
19379 		if (usable < mss)
19380 			goto done;
19381 		usable = (usable / mss) * mss;
19382 	}
19383 
19384 	/* Update the latest receive window size in TCP header. */
19385 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19386 	    tcp->tcp_tcph->th_win);
19387 
19388 	/*
19389 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19390 	 *
19391 	 * 1. Simple TCP/IP{v4,v6} (no options).
19392 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19393 	 * 3. If the TCP connection is in ESTABLISHED state.
19394 	 * 4. The TCP is not detached.
19395 	 *
19396 	 * If any of the above conditions have changed during the
19397 	 * connection, stop using LSO/MDT and restore the stream head
19398 	 * parameters accordingly.
19399 	 */
19400 	ipst = tcps->tcps_netstack->netstack_ip;
19401 
19402 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19403 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19404 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19405 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19406 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19407 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19408 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19409 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19410 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19411 		if (tcp->tcp_lso) {
19412 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19413 			tcp->tcp_lso = B_FALSE;
19414 		} else {
19415 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19416 			tcp->tcp_mdt = B_FALSE;
19417 		}
19418 
19419 		/* Anything other than detached is considered pathological */
19420 		if (!TCP_IS_DETACHED(tcp)) {
19421 			if (tcp->tcp_lso)
19422 				TCP_STAT(tcps, tcp_lso_disabled);
19423 			else
19424 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19425 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19426 		}
19427 	}
19428 
19429 	/* Use MDT if sendable amount is greater than the threshold */
19430 	if (tcp->tcp_mdt &&
19431 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19432 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19433 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19434 	    (tcp->tcp_valid_bits == 0 ||
19435 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19436 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19437 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19438 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19439 		    local_time, mdt_thres);
19440 	} else {
19441 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19442 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19443 		    local_time, INT_MAX);
19444 	}
19445 
19446 	/* Pretend that all we were trying to send really got sent */
19447 	if (rc < 0 && tail_unsent < 0) {
19448 		do {
19449 			xmit_tail = xmit_tail->b_cont;
19450 			xmit_tail->b_prev = local_time;
19451 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19452 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19453 			tail_unsent += (int)(xmit_tail->b_wptr -
19454 			    xmit_tail->b_rptr);
19455 		} while (tail_unsent < 0);
19456 	}
19457 done:;
19458 	tcp->tcp_xmit_tail = xmit_tail;
19459 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19460 	len = tcp->tcp_snxt - snxt;
19461 	if (len) {
19462 		/*
19463 		 * If new data was sent, need to update the notsack
19464 		 * list, which is, afterall, data blocks that have
19465 		 * not been sack'ed by the receiver.  New data is
19466 		 * not sack'ed.
19467 		 */
19468 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19469 			/* len is a negative value. */
19470 			tcp->tcp_pipe -= len;
19471 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19472 			    tcp->tcp_snxt, snxt,
19473 			    &(tcp->tcp_num_notsack_blk),
19474 			    &(tcp->tcp_cnt_notsack_list));
19475 		}
19476 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19477 		tcp->tcp_rack = tcp->tcp_rnxt;
19478 		tcp->tcp_rack_cnt = 0;
19479 		if ((snxt + len) == tcp->tcp_suna) {
19480 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19481 		}
19482 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19483 		/*
19484 		 * Didn't send anything. Make sure the timer is running
19485 		 * so that we will probe a zero window.
19486 		 */
19487 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19488 	}
19489 	/* Note that len is the amount we just sent but with a negative sign */
19490 	tcp->tcp_unsent += len;
19491 	mutex_enter(&tcp->tcp_non_sq_lock);
19492 	if (tcp->tcp_flow_stopped) {
19493 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19494 			tcp_clrqfull(tcp);
19495 		}
19496 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19497 		tcp_setqfull(tcp);
19498 	}
19499 	mutex_exit(&tcp->tcp_non_sq_lock);
19500 }
19501 
19502 /*
19503  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19504  * outgoing TCP header with the template header, as well as other
19505  * options such as time-stamp, ECN and/or SACK.
19506  */
19507 static void
19508 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19509 {
19510 	tcph_t *tcp_tmpl, *tcp_h;
19511 	uint32_t *dst, *src;
19512 	int hdrlen;
19513 
19514 	ASSERT(OK_32PTR(rptr));
19515 
19516 	/* Template header */
19517 	tcp_tmpl = tcp->tcp_tcph;
19518 
19519 	/* Header of outgoing packet */
19520 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19521 
19522 	/* dst and src are opaque 32-bit fields, used for copying */
19523 	dst = (uint32_t *)rptr;
19524 	src = (uint32_t *)tcp->tcp_iphc;
19525 	hdrlen = tcp->tcp_hdr_len;
19526 
19527 	/* Fill time-stamp option if needed */
19528 	if (tcp->tcp_snd_ts_ok) {
19529 		U32_TO_BE32((uint32_t)now,
19530 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19531 		U32_TO_BE32(tcp->tcp_ts_recent,
19532 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19533 	} else {
19534 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19535 	}
19536 
19537 	/*
19538 	 * Copy the template header; is this really more efficient than
19539 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19540 	 * but perhaps not for other scenarios.
19541 	 */
19542 	dst[0] = src[0];
19543 	dst[1] = src[1];
19544 	dst[2] = src[2];
19545 	dst[3] = src[3];
19546 	dst[4] = src[4];
19547 	dst[5] = src[5];
19548 	dst[6] = src[6];
19549 	dst[7] = src[7];
19550 	dst[8] = src[8];
19551 	dst[9] = src[9];
19552 	if (hdrlen -= 40) {
19553 		hdrlen >>= 2;
19554 		dst += 10;
19555 		src += 10;
19556 		do {
19557 			*dst++ = *src++;
19558 		} while (--hdrlen);
19559 	}
19560 
19561 	/*
19562 	 * Set the ECN info in the TCP header if it is not a zero
19563 	 * window probe.  Zero window probe is only sent in
19564 	 * tcp_wput_data() and tcp_timer().
19565 	 */
19566 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19567 		SET_ECT(tcp, rptr);
19568 
19569 		if (tcp->tcp_ecn_echo_on)
19570 			tcp_h->th_flags[0] |= TH_ECE;
19571 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19572 			tcp_h->th_flags[0] |= TH_CWR;
19573 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19574 		}
19575 	}
19576 
19577 	/* Fill in SACK options */
19578 	if (num_sack_blk > 0) {
19579 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19580 		sack_blk_t *tmp;
19581 		int32_t	i;
19582 
19583 		wptr[0] = TCPOPT_NOP;
19584 		wptr[1] = TCPOPT_NOP;
19585 		wptr[2] = TCPOPT_SACK;
19586 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19587 		    sizeof (sack_blk_t);
19588 		wptr += TCPOPT_REAL_SACK_LEN;
19589 
19590 		tmp = tcp->tcp_sack_list;
19591 		for (i = 0; i < num_sack_blk; i++) {
19592 			U32_TO_BE32(tmp[i].begin, wptr);
19593 			wptr += sizeof (tcp_seq);
19594 			U32_TO_BE32(tmp[i].end, wptr);
19595 			wptr += sizeof (tcp_seq);
19596 		}
19597 		tcp_h->th_offset_and_rsrvd[0] +=
19598 		    ((num_sack_blk * 2 + 1) << 4);
19599 	}
19600 }
19601 
19602 /*
19603  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19604  * the destination address and SAP attribute, and if necessary, the
19605  * hardware checksum offload attribute to a Multidata message.
19606  */
19607 static int
19608 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19609     const uint32_t start, const uint32_t stuff, const uint32_t end,
19610     const uint32_t flags, tcp_stack_t *tcps)
19611 {
19612 	/* Add global destination address & SAP attribute */
19613 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19614 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19615 		    "destination address+SAP\n"));
19616 
19617 		if (dlmp != NULL)
19618 			TCP_STAT(tcps, tcp_mdt_allocfail);
19619 		return (-1);
19620 	}
19621 
19622 	/* Add global hwcksum attribute */
19623 	if (hwcksum &&
19624 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19625 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19626 		    "checksum attribute\n"));
19627 
19628 		TCP_STAT(tcps, tcp_mdt_allocfail);
19629 		return (-1);
19630 	}
19631 
19632 	return (0);
19633 }
19634 
19635 /*
19636  * Smaller and private version of pdescinfo_t used specifically for TCP,
19637  * which allows for only two payload spans per packet.
19638  */
19639 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
19640 
19641 /*
19642  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19643  * scheme, and returns one the following:
19644  *
19645  * -1 = failed allocation.
19646  *  0 = success; burst count reached, or usable send window is too small,
19647  *      and that we'd rather wait until later before sending again.
19648  */
19649 static int
19650 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19651     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19652     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19653     const int mdt_thres)
19654 {
19655 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19656 	multidata_t	*mmd;
19657 	uint_t		obsegs, obbytes, hdr_frag_sz;
19658 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19659 	int		num_burst_seg, max_pld;
19660 	pdesc_t		*pkt;
19661 	tcp_pdescinfo_t	tcp_pkt_info;
19662 	pdescinfo_t	*pkt_info;
19663 	int		pbuf_idx, pbuf_idx_nxt;
19664 	int		seg_len, len, spill, af;
19665 	boolean_t	add_buffer, zcopy, clusterwide;
19666 	boolean_t	buf_trunked = B_FALSE;
19667 	boolean_t	rconfirm = B_FALSE;
19668 	boolean_t	done = B_FALSE;
19669 	uint32_t	cksum;
19670 	uint32_t	hwcksum_flags;
19671 	ire_t		*ire = NULL;
19672 	ill_t		*ill;
19673 	ipha_t		*ipha;
19674 	ip6_t		*ip6h;
19675 	ipaddr_t	src, dst;
19676 	ill_zerocopy_capab_t *zc_cap = NULL;
19677 	uint16_t	*up;
19678 	int		err;
19679 	conn_t		*connp;
19680 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
19681 	uchar_t		*pld_start;
19682 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19683 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
19684 
19685 #ifdef	_BIG_ENDIAN
19686 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19687 #else
19688 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19689 #endif
19690 
19691 #define	PREP_NEW_MULTIDATA() {			\
19692 	mmd = NULL;				\
19693 	md_mp = md_hbuf = NULL;			\
19694 	cur_hdr_off = 0;			\
19695 	max_pld = tcp->tcp_mdt_max_pld;		\
19696 	pbuf_idx = pbuf_idx_nxt = -1;		\
19697 	add_buffer = B_TRUE;			\
19698 	zcopy = B_FALSE;			\
19699 }
19700 
19701 #define	PREP_NEW_PBUF() {			\
19702 	md_pbuf = md_pbuf_nxt = NULL;		\
19703 	pbuf_idx = pbuf_idx_nxt = -1;		\
19704 	cur_pld_off = 0;			\
19705 	first_snxt = *snxt;			\
19706 	ASSERT(*tail_unsent > 0);		\
19707 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19708 }
19709 
19710 	ASSERT(mdt_thres >= mss);
19711 	ASSERT(*usable > 0 && *usable > mdt_thres);
19712 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19713 	ASSERT(!TCP_IS_DETACHED(tcp));
19714 	ASSERT(tcp->tcp_valid_bits == 0 ||
19715 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19716 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19717 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19718 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19719 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19720 
19721 	connp = tcp->tcp_connp;
19722 	ASSERT(connp != NULL);
19723 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
19724 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19725 
19726 	/*
19727 	 * Note that tcp will only declare at most 2 payload spans per
19728 	 * packet, which is much lower than the maximum allowable number
19729 	 * of packet spans per Multidata.  For this reason, we use the
19730 	 * privately declared and smaller descriptor info structure, in
19731 	 * order to save some stack space.
19732 	 */
19733 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19734 
19735 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19736 	if (af == AF_INET) {
19737 		dst = tcp->tcp_ipha->ipha_dst;
19738 		src = tcp->tcp_ipha->ipha_src;
19739 		ASSERT(!CLASSD(dst));
19740 	}
19741 	ASSERT(af == AF_INET ||
19742 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19743 
19744 	obsegs = obbytes = 0;
19745 	num_burst_seg = tcp->tcp_snd_burst;
19746 	md_mp_head = NULL;
19747 	PREP_NEW_MULTIDATA();
19748 
19749 	/*
19750 	 * Before we go on further, make sure there is an IRE that we can
19751 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19752 	 * in proceeding any further, and we should just hand everything
19753 	 * off to the legacy path.
19754 	 */
19755 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
19756 		goto legacy_send_no_md;
19757 
19758 	ASSERT(ire != NULL);
19759 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19760 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19761 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19762 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19763 	/*
19764 	 * If we do support loopback for MDT (which requires modifications
19765 	 * to the receiving paths), the following assertions should go away,
19766 	 * and we would be sending the Multidata to loopback conn later on.
19767 	 */
19768 	ASSERT(!IRE_IS_LOCAL(ire));
19769 	ASSERT(ire->ire_stq != NULL);
19770 
19771 	ill = ire_to_ill(ire);
19772 	ASSERT(ill != NULL);
19773 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19774 
19775 	if (!tcp->tcp_ire_ill_check_done) {
19776 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19777 		tcp->tcp_ire_ill_check_done = B_TRUE;
19778 	}
19779 
19780 	/*
19781 	 * If the underlying interface conditions have changed, or if the
19782 	 * new interface does not support MDT, go back to legacy path.
19783 	 */
19784 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19785 		/* don't go through this path anymore for this connection */
19786 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
19787 		tcp->tcp_mdt = B_FALSE;
19788 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19789 		    "interface %s\n", (void *)connp, ill->ill_name));
19790 		/* IRE will be released prior to returning */
19791 		goto legacy_send_no_md;
19792 	}
19793 
19794 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19795 		zc_cap = ill->ill_zerocopy_capab;
19796 
19797 	/*
19798 	 * Check if we can take tcp fast-path. Note that "incomplete"
19799 	 * ire's (where the link-layer for next hop is not resolved
19800 	 * or where the fast-path header in nce_fp_mp is not available
19801 	 * yet) are sent down the legacy (slow) path.
19802 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
19803 	 */
19804 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
19805 		/* IRE will be released prior to returning */
19806 		goto legacy_send_no_md;
19807 	}
19808 
19809 	/* go to legacy path if interface doesn't support zerocopy */
19810 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19811 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19812 		/* IRE will be released prior to returning */
19813 		goto legacy_send_no_md;
19814 	}
19815 
19816 	/* does the interface support hardware checksum offload? */
19817 	hwcksum_flags = 0;
19818 	if (ILL_HCKSUM_CAPABLE(ill) &&
19819 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19820 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19821 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19822 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19823 		    HCKSUM_IPHDRCKSUM)
19824 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19825 
19826 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19827 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19828 			hwcksum_flags |= HCK_FULLCKSUM;
19829 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19830 		    HCKSUM_INET_PARTIAL)
19831 			hwcksum_flags |= HCK_PARTIALCKSUM;
19832 	}
19833 
19834 	/*
19835 	 * Each header fragment consists of the leading extra space,
19836 	 * followed by the TCP/IP header, and the trailing extra space.
19837 	 * We make sure that each header fragment begins on a 32-bit
19838 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19839 	 * aligned in tcp_mdt_update).
19840 	 */
19841 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19842 	    tcp->tcp_mdt_hdr_tail), 4);
19843 
19844 	/* are we starting from the beginning of data block? */
19845 	if (*tail_unsent == 0) {
19846 		*xmit_tail = (*xmit_tail)->b_cont;
19847 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19848 		*tail_unsent = (int)MBLKL(*xmit_tail);
19849 	}
19850 
19851 	/*
19852 	 * Here we create one or more Multidata messages, each made up of
19853 	 * one header buffer and up to N payload buffers.  This entire
19854 	 * operation is done within two loops:
19855 	 *
19856 	 * The outer loop mostly deals with creating the Multidata message,
19857 	 * as well as the header buffer that gets added to it.  It also
19858 	 * links the Multidata messages together such that all of them can
19859 	 * be sent down to the lower layer in a single putnext call; this
19860 	 * linking behavior depends on the tcp_mdt_chain tunable.
19861 	 *
19862 	 * The inner loop takes an existing Multidata message, and adds
19863 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19864 	 * packetizes those buffers by filling up the corresponding header
19865 	 * buffer fragments with the proper IP and TCP headers, and by
19866 	 * describing the layout of each packet in the packet descriptors
19867 	 * that get added to the Multidata.
19868 	 */
19869 	do {
19870 		/*
19871 		 * If usable send window is too small, or data blocks in
19872 		 * transmit list are smaller than our threshold (i.e. app
19873 		 * performs large writes followed by small ones), we hand
19874 		 * off the control over to the legacy path.  Note that we'll
19875 		 * get back the control once it encounters a large block.
19876 		 */
19877 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19878 		    (*xmit_tail)->b_cont != NULL &&
19879 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19880 			/* send down what we've got so far */
19881 			if (md_mp_head != NULL) {
19882 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19883 				    obsegs, obbytes, &rconfirm);
19884 			}
19885 			/*
19886 			 * Pass control over to tcp_send(), but tell it to
19887 			 * return to us once a large-size transmission is
19888 			 * possible.
19889 			 */
19890 			TCP_STAT(tcps, tcp_mdt_legacy_small);
19891 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19892 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19893 			    tail_unsent, xmit_tail, local_time,
19894 			    mdt_thres)) <= 0) {
19895 				/* burst count reached, or alloc failed */
19896 				IRE_REFRELE(ire);
19897 				return (err);
19898 			}
19899 
19900 			/* tcp_send() may have sent everything, so check */
19901 			if (*usable <= 0) {
19902 				IRE_REFRELE(ire);
19903 				return (0);
19904 			}
19905 
19906 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
19907 			/*
19908 			 * We may have delivered the Multidata, so make sure
19909 			 * to re-initialize before the next round.
19910 			 */
19911 			md_mp_head = NULL;
19912 			obsegs = obbytes = 0;
19913 			num_burst_seg = tcp->tcp_snd_burst;
19914 			PREP_NEW_MULTIDATA();
19915 
19916 			/* are we starting from the beginning of data block? */
19917 			if (*tail_unsent == 0) {
19918 				*xmit_tail = (*xmit_tail)->b_cont;
19919 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19920 				    (uintptr_t)INT_MAX);
19921 				*tail_unsent = (int)MBLKL(*xmit_tail);
19922 			}
19923 		}
19924 
19925 		/*
19926 		 * max_pld limits the number of mblks in tcp's transmit
19927 		 * queue that can be added to a Multidata message.  Once
19928 		 * this counter reaches zero, no more additional mblks
19929 		 * can be added to it.  What happens afterwards depends
19930 		 * on whether or not we are set to chain the Multidata
19931 		 * messages.  If we are to link them together, reset
19932 		 * max_pld to its original value (tcp_mdt_max_pld) and
19933 		 * prepare to create a new Multidata message which will
19934 		 * get linked to md_mp_head.  Else, leave it alone and
19935 		 * let the inner loop break on its own.
19936 		 */
19937 		if (tcp_mdt_chain && max_pld == 0)
19938 			PREP_NEW_MULTIDATA();
19939 
19940 		/* adding a payload buffer; re-initialize values */
19941 		if (add_buffer)
19942 			PREP_NEW_PBUF();
19943 
19944 		/*
19945 		 * If we don't have a Multidata, either because we just
19946 		 * (re)entered this outer loop, or after we branched off
19947 		 * to tcp_send above, setup the Multidata and header
19948 		 * buffer to be used.
19949 		 */
19950 		if (md_mp == NULL) {
19951 			int md_hbuflen;
19952 			uint32_t start, stuff;
19953 
19954 			/*
19955 			 * Calculate Multidata header buffer size large enough
19956 			 * to hold all of the headers that can possibly be
19957 			 * sent at this moment.  We'd rather over-estimate
19958 			 * the size than running out of space; this is okay
19959 			 * since this buffer is small anyway.
19960 			 */
19961 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19962 
19963 			/*
19964 			 * Start and stuff offset for partial hardware
19965 			 * checksum offload; these are currently for IPv4.
19966 			 * For full checksum offload, they are set to zero.
19967 			 */
19968 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19969 				if (af == AF_INET) {
19970 					start = IP_SIMPLE_HDR_LENGTH;
19971 					stuff = IP_SIMPLE_HDR_LENGTH +
19972 					    TCP_CHECKSUM_OFFSET;
19973 				} else {
19974 					start = IPV6_HDR_LEN;
19975 					stuff = IPV6_HDR_LEN +
19976 					    TCP_CHECKSUM_OFFSET;
19977 				}
19978 			} else {
19979 				start = stuff = 0;
19980 			}
19981 
19982 			/*
19983 			 * Create the header buffer, Multidata, as well as
19984 			 * any necessary attributes (destination address,
19985 			 * SAP and hardware checksum offload) that should
19986 			 * be associated with the Multidata message.
19987 			 */
19988 			ASSERT(cur_hdr_off == 0);
19989 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19990 			    ((md_hbuf->b_wptr += md_hbuflen),
19991 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19992 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19993 			    /* fastpath mblk */
19994 			    ire->ire_nce->nce_res_mp,
19995 			    /* hardware checksum enabled */
19996 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19997 			    /* hardware checksum offsets */
19998 			    start, stuff, 0,
19999 			    /* hardware checksum flag */
20000 			    hwcksum_flags, tcps) != 0)) {
20001 legacy_send:
20002 				if (md_mp != NULL) {
20003 					/* Unlink message from the chain */
20004 					if (md_mp_head != NULL) {
20005 						err = (intptr_t)rmvb(md_mp_head,
20006 						    md_mp);
20007 						/*
20008 						 * We can't assert that rmvb
20009 						 * did not return -1, since we
20010 						 * may get here before linkb
20011 						 * happens.  We do, however,
20012 						 * check if we just removed the
20013 						 * only element in the list.
20014 						 */
20015 						if (err == 0)
20016 							md_mp_head = NULL;
20017 					}
20018 					/* md_hbuf gets freed automatically */
20019 					TCP_STAT(tcps, tcp_mdt_discarded);
20020 					freeb(md_mp);
20021 				} else {
20022 					/* Either allocb or mmd_alloc failed */
20023 					TCP_STAT(tcps, tcp_mdt_allocfail);
20024 					if (md_hbuf != NULL)
20025 						freeb(md_hbuf);
20026 				}
20027 
20028 				/* send down what we've got so far */
20029 				if (md_mp_head != NULL) {
20030 					tcp_multisend_data(tcp, ire, ill,
20031 					    md_mp_head, obsegs, obbytes,
20032 					    &rconfirm);
20033 				}
20034 legacy_send_no_md:
20035 				if (ire != NULL)
20036 					IRE_REFRELE(ire);
20037 				/*
20038 				 * Too bad; let the legacy path handle this.
20039 				 * We specify INT_MAX for the threshold, since
20040 				 * we gave up with the Multidata processings
20041 				 * and let the old path have it all.
20042 				 */
20043 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20044 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20045 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20046 				    snxt, tail_unsent, xmit_tail, local_time,
20047 				    INT_MAX));
20048 			}
20049 
20050 			/* link to any existing ones, if applicable */
20051 			TCP_STAT(tcps, tcp_mdt_allocd);
20052 			if (md_mp_head == NULL) {
20053 				md_mp_head = md_mp;
20054 			} else if (tcp_mdt_chain) {
20055 				TCP_STAT(tcps, tcp_mdt_linked);
20056 				linkb(md_mp_head, md_mp);
20057 			}
20058 		}
20059 
20060 		ASSERT(md_mp_head != NULL);
20061 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20062 		ASSERT(md_mp != NULL && mmd != NULL);
20063 		ASSERT(md_hbuf != NULL);
20064 
20065 		/*
20066 		 * Packetize the transmittable portion of the data block;
20067 		 * each data block is essentially added to the Multidata
20068 		 * as a payload buffer.  We also deal with adding more
20069 		 * than one payload buffers, which happens when the remaining
20070 		 * packetized portion of the current payload buffer is less
20071 		 * than MSS, while the next data block in transmit queue
20072 		 * has enough data to make up for one.  This "spillover"
20073 		 * case essentially creates a split-packet, where portions
20074 		 * of the packet's payload fragments may span across two
20075 		 * virtually discontiguous address blocks.
20076 		 */
20077 		seg_len = mss;
20078 		do {
20079 			len = seg_len;
20080 
20081 			ASSERT(len > 0);
20082 			ASSERT(max_pld >= 0);
20083 			ASSERT(!add_buffer || cur_pld_off == 0);
20084 
20085 			/*
20086 			 * First time around for this payload buffer; note
20087 			 * in the case of a spillover, the following has
20088 			 * been done prior to adding the split-packet
20089 			 * descriptor to Multidata, and we don't want to
20090 			 * repeat the process.
20091 			 */
20092 			if (add_buffer) {
20093 				ASSERT(mmd != NULL);
20094 				ASSERT(md_pbuf == NULL);
20095 				ASSERT(md_pbuf_nxt == NULL);
20096 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20097 
20098 				/*
20099 				 * Have we reached the limit?  We'd get to
20100 				 * this case when we're not chaining the
20101 				 * Multidata messages together, and since
20102 				 * we're done, terminate this loop.
20103 				 */
20104 				if (max_pld == 0)
20105 					break; /* done */
20106 
20107 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20108 					TCP_STAT(tcps, tcp_mdt_allocfail);
20109 					goto legacy_send; /* out_of_mem */
20110 				}
20111 
20112 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20113 				    zc_cap != NULL) {
20114 					if (!ip_md_zcopy_attr(mmd, NULL,
20115 					    zc_cap->ill_zerocopy_flags)) {
20116 						freeb(md_pbuf);
20117 						TCP_STAT(tcps,
20118 						    tcp_mdt_allocfail);
20119 						/* out_of_mem */
20120 						goto legacy_send;
20121 					}
20122 					zcopy = B_TRUE;
20123 				}
20124 
20125 				md_pbuf->b_rptr += base_pld_off;
20126 
20127 				/*
20128 				 * Add a payload buffer to the Multidata; this
20129 				 * operation must not fail, or otherwise our
20130 				 * logic in this routine is broken.  There
20131 				 * is no memory allocation done by the
20132 				 * routine, so any returned failure simply
20133 				 * tells us that we've done something wrong.
20134 				 *
20135 				 * A failure tells us that either we're adding
20136 				 * the same payload buffer more than once, or
20137 				 * we're trying to add more buffers than
20138 				 * allowed (max_pld calculation is wrong).
20139 				 * None of the above cases should happen, and
20140 				 * we panic because either there's horrible
20141 				 * heap corruption, and/or programming mistake.
20142 				 */
20143 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20144 				if (pbuf_idx < 0) {
20145 					cmn_err(CE_PANIC, "tcp_multisend: "
20146 					    "payload buffer logic error "
20147 					    "detected for tcp %p mmd %p "
20148 					    "pbuf %p (%d)\n",
20149 					    (void *)tcp, (void *)mmd,
20150 					    (void *)md_pbuf, pbuf_idx);
20151 				}
20152 
20153 				ASSERT(max_pld > 0);
20154 				--max_pld;
20155 				add_buffer = B_FALSE;
20156 			}
20157 
20158 			ASSERT(md_mp_head != NULL);
20159 			ASSERT(md_pbuf != NULL);
20160 			ASSERT(md_pbuf_nxt == NULL);
20161 			ASSERT(pbuf_idx != -1);
20162 			ASSERT(pbuf_idx_nxt == -1);
20163 			ASSERT(*usable > 0);
20164 
20165 			/*
20166 			 * We spillover to the next payload buffer only
20167 			 * if all of the following is true:
20168 			 *
20169 			 *   1. There is not enough data on the current
20170 			 *	payload buffer to make up `len',
20171 			 *   2. We are allowed to send `len',
20172 			 *   3. The next payload buffer length is large
20173 			 *	enough to accomodate `spill'.
20174 			 */
20175 			if ((spill = len - *tail_unsent) > 0 &&
20176 			    *usable >= len &&
20177 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20178 			    max_pld > 0) {
20179 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20180 				if (md_pbuf_nxt == NULL) {
20181 					TCP_STAT(tcps, tcp_mdt_allocfail);
20182 					goto legacy_send; /* out_of_mem */
20183 				}
20184 
20185 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20186 				    zc_cap != NULL) {
20187 					if (!ip_md_zcopy_attr(mmd, NULL,
20188 					    zc_cap->ill_zerocopy_flags)) {
20189 						freeb(md_pbuf_nxt);
20190 						TCP_STAT(tcps,
20191 						    tcp_mdt_allocfail);
20192 						/* out_of_mem */
20193 						goto legacy_send;
20194 					}
20195 					zcopy = B_TRUE;
20196 				}
20197 
20198 				/*
20199 				 * See comments above on the first call to
20200 				 * mmd_addpldbuf for explanation on the panic.
20201 				 */
20202 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20203 				if (pbuf_idx_nxt < 0) {
20204 					panic("tcp_multisend: "
20205 					    "next payload buffer logic error "
20206 					    "detected for tcp %p mmd %p "
20207 					    "pbuf %p (%d)\n",
20208 					    (void *)tcp, (void *)mmd,
20209 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20210 				}
20211 
20212 				ASSERT(max_pld > 0);
20213 				--max_pld;
20214 			} else if (spill > 0) {
20215 				/*
20216 				 * If there's a spillover, but the following
20217 				 * xmit_tail couldn't give us enough octets
20218 				 * to reach "len", then stop the current
20219 				 * Multidata creation and let the legacy
20220 				 * tcp_send() path take over.  We don't want
20221 				 * to send the tiny segment as part of this
20222 				 * Multidata for performance reasons; instead,
20223 				 * we let the legacy path deal with grouping
20224 				 * it with the subsequent small mblks.
20225 				 */
20226 				if (*usable >= len &&
20227 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20228 					max_pld = 0;
20229 					break;	/* done */
20230 				}
20231 
20232 				/*
20233 				 * We can't spillover, and we are near
20234 				 * the end of the current payload buffer,
20235 				 * so send what's left.
20236 				 */
20237 				ASSERT(*tail_unsent > 0);
20238 				len = *tail_unsent;
20239 			}
20240 
20241 			/* tail_unsent is negated if there is a spillover */
20242 			*tail_unsent -= len;
20243 			*usable -= len;
20244 			ASSERT(*usable >= 0);
20245 
20246 			if (*usable < mss)
20247 				seg_len = *usable;
20248 			/*
20249 			 * Sender SWS avoidance; see comments in tcp_send();
20250 			 * everything else is the same, except that we only
20251 			 * do this here if there is no more data to be sent
20252 			 * following the current xmit_tail.  We don't check
20253 			 * for 1-byte urgent data because we shouldn't get
20254 			 * here if TCP_URG_VALID is set.
20255 			 */
20256 			if (*usable > 0 && *usable < mss &&
20257 			    ((md_pbuf_nxt == NULL &&
20258 			    (*xmit_tail)->b_cont == NULL) ||
20259 			    (md_pbuf_nxt != NULL &&
20260 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20261 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20262 			    (tcp->tcp_unsent -
20263 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20264 			    !tcp->tcp_zero_win_probe) {
20265 				if ((*snxt + len) == tcp->tcp_snxt &&
20266 				    (*snxt + len) == tcp->tcp_suna) {
20267 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20268 				}
20269 				done = B_TRUE;
20270 			}
20271 
20272 			/*
20273 			 * Prime pump for IP's checksumming on our behalf;
20274 			 * include the adjustment for a source route if any.
20275 			 * Do this only for software/partial hardware checksum
20276 			 * offload, as this field gets zeroed out later for
20277 			 * the full hardware checksum offload case.
20278 			 */
20279 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20280 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20281 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20282 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20283 			}
20284 
20285 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20286 			*snxt += len;
20287 
20288 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20289 			/*
20290 			 * We set the PUSH bit only if TCP has no more buffered
20291 			 * data to be transmitted (or if sender SWS avoidance
20292 			 * takes place), as opposed to setting it for every
20293 			 * last packet in the burst.
20294 			 */
20295 			if (done ||
20296 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20297 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20298 
20299 			/*
20300 			 * Set FIN bit if this is our last segment; snxt
20301 			 * already includes its length, and it will not
20302 			 * be adjusted after this point.
20303 			 */
20304 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20305 			    *snxt == tcp->tcp_fss) {
20306 				if (!tcp->tcp_fin_acked) {
20307 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20308 					BUMP_MIB(&tcps->tcps_mib,
20309 					    tcpOutControl);
20310 				}
20311 				if (!tcp->tcp_fin_sent) {
20312 					tcp->tcp_fin_sent = B_TRUE;
20313 					/*
20314 					 * tcp state must be ESTABLISHED
20315 					 * in order for us to get here in
20316 					 * the first place.
20317 					 */
20318 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20319 
20320 					/*
20321 					 * Upon returning from this routine,
20322 					 * tcp_wput_data() will set tcp_snxt
20323 					 * to be equal to snxt + tcp_fin_sent.
20324 					 * This is essentially the same as
20325 					 * setting it to tcp_fss + 1.
20326 					 */
20327 				}
20328 			}
20329 
20330 			tcp->tcp_last_sent_len = (ushort_t)len;
20331 
20332 			len += tcp_hdr_len;
20333 			if (tcp->tcp_ipversion == IPV4_VERSION)
20334 				tcp->tcp_ipha->ipha_length = htons(len);
20335 			else
20336 				tcp->tcp_ip6h->ip6_plen = htons(len -
20337 				    ((char *)&tcp->tcp_ip6h[1] -
20338 				    tcp->tcp_iphc));
20339 
20340 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20341 
20342 			/* setup header fragment */
20343 			PDESC_HDR_ADD(pkt_info,
20344 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20345 			    tcp->tcp_mdt_hdr_head,		/* head room */
20346 			    tcp_hdr_len,			/* len */
20347 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20348 
20349 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20350 			    hdr_frag_sz);
20351 			ASSERT(MBLKIN(md_hbuf,
20352 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20353 			    PDESC_HDRSIZE(pkt_info)));
20354 
20355 			/* setup first payload fragment */
20356 			PDESC_PLD_INIT(pkt_info);
20357 			PDESC_PLD_SPAN_ADD(pkt_info,
20358 			    pbuf_idx,				/* index */
20359 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20360 			    tcp->tcp_last_sent_len);		/* len */
20361 
20362 			/* create a split-packet in case of a spillover */
20363 			if (md_pbuf_nxt != NULL) {
20364 				ASSERT(spill > 0);
20365 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20366 				ASSERT(!add_buffer);
20367 
20368 				md_pbuf = md_pbuf_nxt;
20369 				md_pbuf_nxt = NULL;
20370 				pbuf_idx = pbuf_idx_nxt;
20371 				pbuf_idx_nxt = -1;
20372 				cur_pld_off = spill;
20373 
20374 				/* trim out first payload fragment */
20375 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20376 
20377 				/* setup second payload fragment */
20378 				PDESC_PLD_SPAN_ADD(pkt_info,
20379 				    pbuf_idx,			/* index */
20380 				    md_pbuf->b_rptr,		/* start */
20381 				    spill);			/* len */
20382 
20383 				if ((*xmit_tail)->b_next == NULL) {
20384 					/*
20385 					 * Store the lbolt used for RTT
20386 					 * estimation. We can only record one
20387 					 * timestamp per mblk so we do it when
20388 					 * we reach the end of the payload
20389 					 * buffer.  Also we only take a new
20390 					 * timestamp sample when the previous
20391 					 * timed data from the same mblk has
20392 					 * been ack'ed.
20393 					 */
20394 					(*xmit_tail)->b_prev = local_time;
20395 					(*xmit_tail)->b_next =
20396 					    (mblk_t *)(uintptr_t)first_snxt;
20397 				}
20398 
20399 				first_snxt = *snxt - spill;
20400 
20401 				/*
20402 				 * Advance xmit_tail; usable could be 0 by
20403 				 * the time we got here, but we made sure
20404 				 * above that we would only spillover to
20405 				 * the next data block if usable includes
20406 				 * the spilled-over amount prior to the
20407 				 * subtraction.  Therefore, we are sure
20408 				 * that xmit_tail->b_cont can't be NULL.
20409 				 */
20410 				ASSERT((*xmit_tail)->b_cont != NULL);
20411 				*xmit_tail = (*xmit_tail)->b_cont;
20412 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20413 				    (uintptr_t)INT_MAX);
20414 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20415 			} else {
20416 				cur_pld_off += tcp->tcp_last_sent_len;
20417 			}
20418 
20419 			/*
20420 			 * Fill in the header using the template header, and
20421 			 * add options such as time-stamp, ECN and/or SACK,
20422 			 * as needed.
20423 			 */
20424 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20425 			    (clock_t)local_time, num_sack_blk);
20426 
20427 			/* take care of some IP header businesses */
20428 			if (af == AF_INET) {
20429 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20430 
20431 				ASSERT(OK_32PTR((uchar_t *)ipha));
20432 				ASSERT(PDESC_HDRL(pkt_info) >=
20433 				    IP_SIMPLE_HDR_LENGTH);
20434 				ASSERT(ipha->ipha_version_and_hdr_length ==
20435 				    IP_SIMPLE_HDR_VERSION);
20436 
20437 				/*
20438 				 * Assign ident value for current packet; see
20439 				 * related comments in ip_wput_ire() about the
20440 				 * contract private interface with clustering
20441 				 * group.
20442 				 */
20443 				clusterwide = B_FALSE;
20444 				if (cl_inet_ipident != NULL) {
20445 					ASSERT(cl_inet_isclusterwide != NULL);
20446 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20447 					    AF_INET,
20448 					    (uint8_t *)(uintptr_t)src)) {
20449 						ipha->ipha_ident =
20450 						    (*cl_inet_ipident)
20451 						    (IPPROTO_IP, AF_INET,
20452 						    (uint8_t *)(uintptr_t)src,
20453 						    (uint8_t *)(uintptr_t)dst);
20454 						clusterwide = B_TRUE;
20455 					}
20456 				}
20457 
20458 				if (!clusterwide) {
20459 					ipha->ipha_ident = (uint16_t)
20460 					    atomic_add_32_nv(
20461 						&ire->ire_ident, 1);
20462 				}
20463 #ifndef _BIG_ENDIAN
20464 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20465 				    (ipha->ipha_ident >> 8);
20466 #endif
20467 			} else {
20468 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20469 
20470 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20471 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20472 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20473 				ASSERT(PDESC_HDRL(pkt_info) >=
20474 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20475 				    TCP_CHECKSUM_SIZE));
20476 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20477 
20478 				if (tcp->tcp_ip_forward_progress) {
20479 					rconfirm = B_TRUE;
20480 					tcp->tcp_ip_forward_progress = B_FALSE;
20481 				}
20482 			}
20483 
20484 			/* at least one payload span, and at most two */
20485 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20486 
20487 			/* add the packet descriptor to Multidata */
20488 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20489 			    KM_NOSLEEP)) == NULL) {
20490 				/*
20491 				 * Any failure other than ENOMEM indicates
20492 				 * that we have passed in invalid pkt_info
20493 				 * or parameters to mmd_addpdesc, which must
20494 				 * not happen.
20495 				 *
20496 				 * EINVAL is a result of failure on boundary
20497 				 * checks against the pkt_info contents.  It
20498 				 * should not happen, and we panic because
20499 				 * either there's horrible heap corruption,
20500 				 * and/or programming mistake.
20501 				 */
20502 				if (err != ENOMEM) {
20503 					cmn_err(CE_PANIC, "tcp_multisend: "
20504 					    "pdesc logic error detected for "
20505 					    "tcp %p mmd %p pinfo %p (%d)\n",
20506 					    (void *)tcp, (void *)mmd,
20507 					    (void *)pkt_info, err);
20508 				}
20509 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20510 				goto legacy_send; /* out_of_mem */
20511 			}
20512 			ASSERT(pkt != NULL);
20513 
20514 			/* calculate IP header and TCP checksums */
20515 			if (af == AF_INET) {
20516 				/* calculate pseudo-header checksum */
20517 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20518 				    (src >> 16) + (src & 0xFFFF);
20519 
20520 				/* offset for TCP header checksum */
20521 				up = IPH_TCPH_CHECKSUMP(ipha,
20522 				    IP_SIMPLE_HDR_LENGTH);
20523 			} else {
20524 				up = (uint16_t *)&ip6h->ip6_src;
20525 
20526 				/* calculate pseudo-header checksum */
20527 				cksum = up[0] + up[1] + up[2] + up[3] +
20528 				    up[4] + up[5] + up[6] + up[7] +
20529 				    up[8] + up[9] + up[10] + up[11] +
20530 				    up[12] + up[13] + up[14] + up[15];
20531 
20532 				/* Fold the initial sum */
20533 				cksum = (cksum & 0xffff) + (cksum >> 16);
20534 
20535 				up = (uint16_t *)(((uchar_t *)ip6h) +
20536 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20537 			}
20538 
20539 			if (hwcksum_flags & HCK_FULLCKSUM) {
20540 				/* clear checksum field for hardware */
20541 				*up = 0;
20542 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20543 				uint32_t sum;
20544 
20545 				/* pseudo-header checksumming */
20546 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20547 				sum = (sum & 0xFFFF) + (sum >> 16);
20548 				*up = (sum & 0xFFFF) + (sum >> 16);
20549 			} else {
20550 				/* software checksumming */
20551 				TCP_STAT(tcps, tcp_out_sw_cksum);
20552 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20553 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20554 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20555 				    cksum + IP_TCP_CSUM_COMP);
20556 				if (*up == 0)
20557 					*up = 0xFFFF;
20558 			}
20559 
20560 			/* IPv4 header checksum */
20561 			if (af == AF_INET) {
20562 				ipha->ipha_fragment_offset_and_flags |=
20563 				    (uint32_t)htons(ire->ire_frag_flag);
20564 
20565 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20566 					ipha->ipha_hdr_checksum = 0;
20567 				} else {
20568 					IP_HDR_CKSUM(ipha, cksum,
20569 					    ((uint32_t *)ipha)[0],
20570 					    ((uint16_t *)ipha)[4]);
20571 				}
20572 			}
20573 
20574 			if (af == AF_INET &&
20575 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
20576 			    af == AF_INET6 &&
20577 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
20578 				/* build header(IP/TCP) mblk for this segment */
20579 				if ((mp = dupb(md_hbuf)) == NULL)
20580 					goto legacy_send;
20581 
20582 				mp->b_rptr = pkt_info->hdr_rptr;
20583 				mp->b_wptr = pkt_info->hdr_wptr;
20584 
20585 				/* build payload mblk for this segment */
20586 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
20587 					freemsg(mp);
20588 					goto legacy_send;
20589 				}
20590 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
20591 				mp1->b_rptr = mp1->b_wptr -
20592 				    tcp->tcp_last_sent_len;
20593 				linkb(mp, mp1);
20594 
20595 				pld_start = mp1->b_rptr;
20596 
20597 				if (af == AF_INET) {
20598 					DTRACE_PROBE4(
20599 					    ip4__physical__out__start,
20600 					    ill_t *, NULL,
20601 					    ill_t *, ill,
20602 					    ipha_t *, ipha,
20603 					    mblk_t *, mp);
20604 					FW_HOOKS(
20605 					    ipst->ips_ip4_physical_out_event,
20606 					    ipst->ips_ipv4firewall_physical_out,
20607 					    NULL, ill, ipha, mp, mp, ipst);
20608 					DTRACE_PROBE1(
20609 					    ip4__physical__out__end,
20610 					    mblk_t *, mp);
20611 				} else {
20612 					DTRACE_PROBE4(
20613 					    ip6__physical__out_start,
20614 					    ill_t *, NULL,
20615 					    ill_t *, ill,
20616 					    ip6_t *, ip6h,
20617 					    mblk_t *, mp);
20618 					FW_HOOKS6(
20619 					    ipst->ips_ip6_physical_out_event,
20620 					    ipst->ips_ipv6firewall_physical_out,
20621 					    NULL, ill, ip6h, mp, mp, ipst);
20622 					DTRACE_PROBE1(
20623 					    ip6__physical__out__end,
20624 					    mblk_t *, mp);
20625 				}
20626 
20627 				if (buf_trunked && mp != NULL) {
20628 					/*
20629 					 * Need to pass it to normal path.
20630 					 */
20631 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20632 				} else if (mp == NULL ||
20633 				    mp->b_rptr != pkt_info->hdr_rptr ||
20634 				    mp->b_wptr != pkt_info->hdr_wptr ||
20635 				    (mp1 = mp->b_cont) == NULL ||
20636 				    mp1->b_rptr != pld_start ||
20637 				    mp1->b_wptr != pld_start +
20638 				    tcp->tcp_last_sent_len ||
20639 				    mp1->b_cont != NULL) {
20640 					/*
20641 					 * Need to pass all packets of this
20642 					 * buffer to normal path, either when
20643 					 * packet is blocked, or when boundary
20644 					 * of header buffer or payload buffer
20645 					 * has been changed by FW_HOOKS[6].
20646 					 */
20647 					buf_trunked = B_TRUE;
20648 					if (md_mp_head != NULL) {
20649 						err = (intptr_t)rmvb(md_mp_head,
20650 						    md_mp);
20651 						if (err == 0)
20652 							md_mp_head = NULL;
20653 					}
20654 
20655 					/* send down what we've got so far */
20656 					if (md_mp_head != NULL) {
20657 						tcp_multisend_data(tcp, ire,
20658 						    ill, md_mp_head, obsegs,
20659 						    obbytes, &rconfirm);
20660 					}
20661 					md_mp_head = NULL;
20662 
20663 					if (mp != NULL)
20664 						CALL_IP_WPUT(tcp->tcp_connp,
20665 						    q, mp);
20666 
20667 					mp1 = fw_mp_head;
20668 					do {
20669 						mp = mp1;
20670 						mp1 = mp1->b_next;
20671 						mp->b_next = NULL;
20672 						mp->b_prev = NULL;
20673 						CALL_IP_WPUT(tcp->tcp_connp,
20674 						    q, mp);
20675 					} while (mp1 != NULL);
20676 
20677 					fw_mp_head = NULL;
20678 				} else {
20679 					if (fw_mp_head == NULL)
20680 						fw_mp_head = mp;
20681 					else
20682 						fw_mp_head->b_prev->b_next = mp;
20683 					fw_mp_head->b_prev = mp;
20684 				}
20685 			}
20686 
20687 			/* advance header offset */
20688 			cur_hdr_off += hdr_frag_sz;
20689 
20690 			obbytes += tcp->tcp_last_sent_len;
20691 			++obsegs;
20692 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20693 		    *tail_unsent > 0);
20694 
20695 		if ((*xmit_tail)->b_next == NULL) {
20696 			/*
20697 			 * Store the lbolt used for RTT estimation. We can only
20698 			 * record one timestamp per mblk so we do it when we
20699 			 * reach the end of the payload buffer. Also we only
20700 			 * take a new timestamp sample when the previous timed
20701 			 * data from the same mblk has been ack'ed.
20702 			 */
20703 			(*xmit_tail)->b_prev = local_time;
20704 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20705 		}
20706 
20707 		ASSERT(*tail_unsent >= 0);
20708 		if (*tail_unsent > 0) {
20709 			/*
20710 			 * We got here because we broke out of the above
20711 			 * loop due to of one of the following cases:
20712 			 *
20713 			 *   1. len < adjusted MSS (i.e. small),
20714 			 *   2. Sender SWS avoidance,
20715 			 *   3. max_pld is zero.
20716 			 *
20717 			 * We are done for this Multidata, so trim our
20718 			 * last payload buffer (if any) accordingly.
20719 			 */
20720 			if (md_pbuf != NULL)
20721 				md_pbuf->b_wptr -= *tail_unsent;
20722 		} else if (*usable > 0) {
20723 			*xmit_tail = (*xmit_tail)->b_cont;
20724 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20725 			    (uintptr_t)INT_MAX);
20726 			*tail_unsent = (int)MBLKL(*xmit_tail);
20727 			add_buffer = B_TRUE;
20728 		}
20729 
20730 		while (fw_mp_head) {
20731 			mp = fw_mp_head;
20732 			fw_mp_head = fw_mp_head->b_next;
20733 			mp->b_prev = mp->b_next = NULL;
20734 			freemsg(mp);
20735 		}
20736 		if (buf_trunked) {
20737 			TCP_STAT(tcps, tcp_mdt_discarded);
20738 			freeb(md_mp);
20739 			buf_trunked = B_FALSE;
20740 		}
20741 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20742 	    (tcp_mdt_chain || max_pld > 0));
20743 
20744 	if (md_mp_head != NULL) {
20745 		/* send everything down */
20746 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20747 		    &rconfirm);
20748 	}
20749 
20750 #undef PREP_NEW_MULTIDATA
20751 #undef PREP_NEW_PBUF
20752 #undef IPVER
20753 
20754 	IRE_REFRELE(ire);
20755 	return (0);
20756 }
20757 
20758 /*
20759  * A wrapper function for sending one or more Multidata messages down to
20760  * the module below ip; this routine does not release the reference of the
20761  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20762  */
20763 static void
20764 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20765     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20766 {
20767 	uint64_t delta;
20768 	nce_t *nce;
20769 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20770 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20771 
20772 	ASSERT(ire != NULL && ill != NULL);
20773 	ASSERT(ire->ire_stq != NULL);
20774 	ASSERT(md_mp_head != NULL);
20775 	ASSERT(rconfirm != NULL);
20776 
20777 	/* adjust MIBs and IRE timestamp */
20778 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20779 	tcp->tcp_obsegs += obsegs;
20780 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
20781 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
20782 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
20783 
20784 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20785 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
20786 	} else {
20787 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
20788 	}
20789 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
20790 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
20791 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
20792 
20793 	ire->ire_ob_pkt_count += obsegs;
20794 	if (ire->ire_ipif != NULL)
20795 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20796 	ire->ire_last_used_time = lbolt;
20797 
20798 	/* send it down */
20799 	putnext(ire->ire_stq, md_mp_head);
20800 
20801 	/* we're done for TCP/IPv4 */
20802 	if (tcp->tcp_ipversion == IPV4_VERSION)
20803 		return;
20804 
20805 	nce = ire->ire_nce;
20806 
20807 	ASSERT(nce != NULL);
20808 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20809 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20810 
20811 	/* reachability confirmation? */
20812 	if (*rconfirm) {
20813 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20814 		if (nce->nce_state != ND_REACHABLE) {
20815 			mutex_enter(&nce->nce_lock);
20816 			nce->nce_state = ND_REACHABLE;
20817 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20818 			mutex_exit(&nce->nce_lock);
20819 			(void) untimeout(nce->nce_timeout_id);
20820 			if (ip_debug > 2) {
20821 				/* ip1dbg */
20822 				pr_addr_dbg("tcp_multisend_data: state "
20823 				    "for %s changed to REACHABLE\n",
20824 				    AF_INET6, &ire->ire_addr_v6);
20825 			}
20826 		}
20827 		/* reset transport reachability confirmation */
20828 		*rconfirm = B_FALSE;
20829 	}
20830 
20831 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20832 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20833 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20834 
20835 	if (delta > (uint64_t)ill->ill_reachable_time) {
20836 		mutex_enter(&nce->nce_lock);
20837 		switch (nce->nce_state) {
20838 		case ND_REACHABLE:
20839 		case ND_STALE:
20840 			/*
20841 			 * ND_REACHABLE is identical to ND_STALE in this
20842 			 * specific case. If reachable time has expired for
20843 			 * this neighbor (delta is greater than reachable
20844 			 * time), conceptually, the neighbor cache is no
20845 			 * longer in REACHABLE state, but already in STALE
20846 			 * state.  So the correct transition here is to
20847 			 * ND_DELAY.
20848 			 */
20849 			nce->nce_state = ND_DELAY;
20850 			mutex_exit(&nce->nce_lock);
20851 			NDP_RESTART_TIMER(nce,
20852 			    ipst->ips_delay_first_probe_time);
20853 			if (ip_debug > 3) {
20854 				/* ip2dbg */
20855 				pr_addr_dbg("tcp_multisend_data: state "
20856 				    "for %s changed to DELAY\n",
20857 				    AF_INET6, &ire->ire_addr_v6);
20858 			}
20859 			break;
20860 		case ND_DELAY:
20861 		case ND_PROBE:
20862 			mutex_exit(&nce->nce_lock);
20863 			/* Timers have already started */
20864 			break;
20865 		case ND_UNREACHABLE:
20866 			/*
20867 			 * ndp timer has detected that this nce is
20868 			 * unreachable and initiated deleting this nce
20869 			 * and all its associated IREs. This is a race
20870 			 * where we found the ire before it was deleted
20871 			 * and have just sent out a packet using this
20872 			 * unreachable nce.
20873 			 */
20874 			mutex_exit(&nce->nce_lock);
20875 			break;
20876 		default:
20877 			ASSERT(0);
20878 		}
20879 	}
20880 }
20881 
20882 /*
20883  * Derived from tcp_send_data().
20884  */
20885 static void
20886 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
20887     int num_lso_seg)
20888 {
20889 	ipha_t		*ipha;
20890 	mblk_t		*ire_fp_mp;
20891 	uint_t		ire_fp_mp_len;
20892 	uint32_t	hcksum_txflags = 0;
20893 	ipaddr_t	src;
20894 	ipaddr_t	dst;
20895 	uint32_t	cksum;
20896 	uint16_t	*up;
20897 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20898 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
20899 
20900 	ASSERT(DB_TYPE(mp) == M_DATA);
20901 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20902 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
20903 	ASSERT(tcp->tcp_connp != NULL);
20904 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
20905 
20906 	ipha = (ipha_t *)mp->b_rptr;
20907 	src = ipha->ipha_src;
20908 	dst = ipha->ipha_dst;
20909 
20910 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20911 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
20912 	    num_lso_seg);
20913 #ifndef _BIG_ENDIAN
20914 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20915 #endif
20916 	if (tcp->tcp_snd_zcopy_aware) {
20917 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
20918 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
20919 			mp = tcp_zcopy_disable(tcp, mp);
20920 	}
20921 
20922 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
20923 		ASSERT(ill->ill_hcksum_capab != NULL);
20924 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
20925 	}
20926 
20927 	/*
20928 	 * Since the TCP checksum should be recalculated by h/w, we can just
20929 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
20930 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
20931 	 * The partial pseudo-header excludes TCP length, that was calculated
20932 	 * in tcp_send(), so to zero *up before further processing.
20933 	 */
20934 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20935 
20936 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
20937 	*up = 0;
20938 
20939 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
20940 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
20941 
20942 	/*
20943 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
20944 	 */
20945 	DB_LSOFLAGS(mp) |= HW_LSO;
20946 	DB_LSOMSS(mp) = mss;
20947 
20948 	ipha->ipha_fragment_offset_and_flags |=
20949 	    (uint32_t)htons(ire->ire_frag_flag);
20950 
20951 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
20952 	ire_fp_mp_len = MBLKL(ire_fp_mp);
20953 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
20954 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
20955 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
20956 
20957 	UPDATE_OB_PKT_COUNT(ire);
20958 	ire->ire_last_used_time = lbolt;
20959 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
20960 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
20961 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
20962 	    ntohs(ipha->ipha_length));
20963 
20964 	if (ILL_DLS_CAPABLE(ill)) {
20965 		/*
20966 		 * Send the packet directly to DLD, where it may be queued
20967 		 * depending on the availability of transmit resources at
20968 		 * the media layer.
20969 		 */
20970 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
20971 	} else {
20972 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
20973 		DTRACE_PROBE4(ip4__physical__out__start,
20974 		    ill_t *, NULL, ill_t *, out_ill,
20975 		    ipha_t *, ipha, mblk_t *, mp);
20976 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
20977 		    ipst->ips_ipv4firewall_physical_out,
20978 		    NULL, out_ill, ipha, mp, mp, ipst);
20979 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
20980 		if (mp != NULL)
20981 			putnext(ire->ire_stq, mp);
20982 	}
20983 }
20984 
20985 /*
20986  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20987  * scheme, and returns one of the following:
20988  *
20989  * -1 = failed allocation.
20990  *  0 = success; burst count reached, or usable send window is too small,
20991  *      and that we'd rather wait until later before sending again.
20992  *  1 = success; we are called from tcp_multisend(), and both usable send
20993  *      window and tail_unsent are greater than the MDT threshold, and thus
20994  *      Multidata Transmit should be used instead.
20995  */
20996 static int
20997 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20998     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20999     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21000     const int mdt_thres)
21001 {
21002 	int num_burst_seg = tcp->tcp_snd_burst;
21003 	ire_t		*ire = NULL;
21004 	ill_t		*ill = NULL;
21005 	mblk_t		*ire_fp_mp = NULL;
21006 	uint_t		ire_fp_mp_len = 0;
21007 	int		num_lso_seg = 1;
21008 	uint_t		lso_usable;
21009 	boolean_t	do_lso_send = B_FALSE;
21010 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21011 
21012 	/*
21013 	 * Check LSO capability before any further work. And the similar check
21014 	 * need to be done in for(;;) loop.
21015 	 * LSO will be deployed when therer is more than one mss of available
21016 	 * data and a burst transmission is allowed.
21017 	 */
21018 	if (tcp->tcp_lso &&
21019 	    (tcp->tcp_valid_bits == 0 ||
21020 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21021 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21022 		/*
21023 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21024 		 */
21025 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21026 			/*
21027 			 * Enable LSO with this transmission.
21028 			 * Since IRE has been hold in
21029 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21030 			 * should be called before return.
21031 			 */
21032 			do_lso_send = B_TRUE;
21033 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21034 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21035 			/* Round up to multiple of 4 */
21036 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21037 		} else {
21038 			do_lso_send = B_FALSE;
21039 			ill = NULL;
21040 		}
21041 	}
21042 
21043 	for (;;) {
21044 		struct datab	*db;
21045 		tcph_t		*tcph;
21046 		uint32_t	sum;
21047 		mblk_t		*mp, *mp1;
21048 		uchar_t		*rptr;
21049 		int		len;
21050 
21051 		/*
21052 		 * If we're called by tcp_multisend(), and the amount of
21053 		 * sendable data as well as the size of current xmit_tail
21054 		 * is beyond the MDT threshold, return to the caller and
21055 		 * let the large data transmit be done using MDT.
21056 		 */
21057 		if (*usable > 0 && *usable > mdt_thres &&
21058 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21059 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21060 			ASSERT(tcp->tcp_mdt);
21061 			return (1);	/* success; do large send */
21062 		}
21063 
21064 		if (num_burst_seg == 0)
21065 			break;		/* success; burst count reached */
21066 
21067 		/*
21068 		 * Calculate the maximum payload length we can send in *one*
21069 		 * time.
21070 		 */
21071 		if (do_lso_send) {
21072 			/*
21073 			 * Check whether need to do LSO any more.
21074 			 */
21075 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21076 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21077 				lso_usable = MIN(lso_usable,
21078 				    num_burst_seg * mss);
21079 
21080 				num_lso_seg = lso_usable / mss;
21081 				if (lso_usable % mss) {
21082 					num_lso_seg++;
21083 					tcp->tcp_last_sent_len = (ushort_t)
21084 					    (lso_usable % mss);
21085 				} else {
21086 					tcp->tcp_last_sent_len = (ushort_t)mss;
21087 				}
21088 			} else {
21089 				do_lso_send = B_FALSE;
21090 				num_lso_seg = 1;
21091 				lso_usable = mss;
21092 			}
21093 		}
21094 
21095 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21096 
21097 		/*
21098 		 * Adjust num_burst_seg here.
21099 		 */
21100 		num_burst_seg -= num_lso_seg;
21101 
21102 		len = mss;
21103 		if (len > *usable) {
21104 			ASSERT(do_lso_send == B_FALSE);
21105 
21106 			len = *usable;
21107 			if (len <= 0) {
21108 				/* Terminate the loop */
21109 				break;	/* success; too small */
21110 			}
21111 			/*
21112 			 * Sender silly-window avoidance.
21113 			 * Ignore this if we are going to send a
21114 			 * zero window probe out.
21115 			 *
21116 			 * TODO: force data into microscopic window?
21117 			 *	==> (!pushed || (unsent > usable))
21118 			 */
21119 			if (len < (tcp->tcp_max_swnd >> 1) &&
21120 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21121 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21122 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21123 				/*
21124 				 * If the retransmit timer is not running
21125 				 * we start it so that we will retransmit
21126 				 * in the case when the the receiver has
21127 				 * decremented the window.
21128 				 */
21129 				if (*snxt == tcp->tcp_snxt &&
21130 				    *snxt == tcp->tcp_suna) {
21131 					/*
21132 					 * We are not supposed to send
21133 					 * anything.  So let's wait a little
21134 					 * bit longer before breaking SWS
21135 					 * avoidance.
21136 					 *
21137 					 * What should the value be?
21138 					 * Suggestion: MAX(init rexmit time,
21139 					 * tcp->tcp_rto)
21140 					 */
21141 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21142 				}
21143 				break;	/* success; too small */
21144 			}
21145 		}
21146 
21147 		tcph = tcp->tcp_tcph;
21148 
21149 		/*
21150 		 * The reason to adjust len here is that we need to set flags
21151 		 * and calculate checksum.
21152 		 */
21153 		if (do_lso_send)
21154 			len = lso_usable;
21155 
21156 		*usable -= len; /* Approximate - can be adjusted later */
21157 		if (*usable > 0)
21158 			tcph->th_flags[0] = TH_ACK;
21159 		else
21160 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21161 
21162 		/*
21163 		 * Prime pump for IP's checksumming on our behalf
21164 		 * Include the adjustment for a source route if any.
21165 		 */
21166 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21167 		sum = (sum >> 16) + (sum & 0xFFFF);
21168 		U16_TO_ABE16(sum, tcph->th_sum);
21169 
21170 		U32_TO_ABE32(*snxt, tcph->th_seq);
21171 
21172 		/*
21173 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21174 		 * set.  For the case when TCP_FSS_VALID is the only valid
21175 		 * bit (normal active close), branch off only when we think
21176 		 * that the FIN flag needs to be set.  Note for this case,
21177 		 * that (snxt + len) may not reflect the actual seg_len,
21178 		 * as len may be further reduced in tcp_xmit_mp().  If len
21179 		 * gets modified, we will end up here again.
21180 		 */
21181 		if (tcp->tcp_valid_bits != 0 &&
21182 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21183 		    ((*snxt + len) == tcp->tcp_fss))) {
21184 			uchar_t		*prev_rptr;
21185 			uint32_t	prev_snxt = tcp->tcp_snxt;
21186 
21187 			if (*tail_unsent == 0) {
21188 				ASSERT((*xmit_tail)->b_cont != NULL);
21189 				*xmit_tail = (*xmit_tail)->b_cont;
21190 				prev_rptr = (*xmit_tail)->b_rptr;
21191 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21192 				    (*xmit_tail)->b_rptr);
21193 			} else {
21194 				prev_rptr = (*xmit_tail)->b_rptr;
21195 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21196 				    *tail_unsent;
21197 			}
21198 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21199 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21200 			/* Restore tcp_snxt so we get amount sent right. */
21201 			tcp->tcp_snxt = prev_snxt;
21202 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21203 				/*
21204 				 * If the previous timestamp is still in use,
21205 				 * don't stomp on it.
21206 				 */
21207 				if ((*xmit_tail)->b_next == NULL) {
21208 					(*xmit_tail)->b_prev = local_time;
21209 					(*xmit_tail)->b_next =
21210 					    (mblk_t *)(uintptr_t)(*snxt);
21211 				}
21212 			} else
21213 				(*xmit_tail)->b_rptr = prev_rptr;
21214 
21215 			if (mp == NULL) {
21216 				if (ire != NULL)
21217 					IRE_REFRELE(ire);
21218 				return (-1);
21219 			}
21220 			mp1 = mp->b_cont;
21221 
21222 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21223 				tcp->tcp_last_sent_len = (ushort_t)len;
21224 			while (mp1->b_cont) {
21225 				*xmit_tail = (*xmit_tail)->b_cont;
21226 				(*xmit_tail)->b_prev = local_time;
21227 				(*xmit_tail)->b_next =
21228 				    (mblk_t *)(uintptr_t)(*snxt);
21229 				mp1 = mp1->b_cont;
21230 			}
21231 			*snxt += len;
21232 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21233 			BUMP_LOCAL(tcp->tcp_obsegs);
21234 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21235 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21236 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21237 			tcp_send_data(tcp, q, mp);
21238 			continue;
21239 		}
21240 
21241 		*snxt += len;	/* Adjust later if we don't send all of len */
21242 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21243 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21244 
21245 		if (*tail_unsent) {
21246 			/* Are the bytes above us in flight? */
21247 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21248 			if (rptr != (*xmit_tail)->b_rptr) {
21249 				*tail_unsent -= len;
21250 				if (len <= mss) /* LSO is unusable */
21251 					tcp->tcp_last_sent_len = (ushort_t)len;
21252 				len += tcp_hdr_len;
21253 				if (tcp->tcp_ipversion == IPV4_VERSION)
21254 					tcp->tcp_ipha->ipha_length = htons(len);
21255 				else
21256 					tcp->tcp_ip6h->ip6_plen =
21257 					    htons(len -
21258 					    ((char *)&tcp->tcp_ip6h[1] -
21259 					    tcp->tcp_iphc));
21260 				mp = dupb(*xmit_tail);
21261 				if (mp == NULL) {
21262 					if (ire != NULL)
21263 						IRE_REFRELE(ire);
21264 					return (-1);	/* out_of_mem */
21265 				}
21266 				mp->b_rptr = rptr;
21267 				/*
21268 				 * If the old timestamp is no longer in use,
21269 				 * sample a new timestamp now.
21270 				 */
21271 				if ((*xmit_tail)->b_next == NULL) {
21272 					(*xmit_tail)->b_prev = local_time;
21273 					(*xmit_tail)->b_next =
21274 					    (mblk_t *)(uintptr_t)(*snxt-len);
21275 				}
21276 				goto must_alloc;
21277 			}
21278 		} else {
21279 			*xmit_tail = (*xmit_tail)->b_cont;
21280 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21281 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21282 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21283 			    (*xmit_tail)->b_rptr);
21284 		}
21285 
21286 		(*xmit_tail)->b_prev = local_time;
21287 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21288 
21289 		*tail_unsent -= len;
21290 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21291 			tcp->tcp_last_sent_len = (ushort_t)len;
21292 
21293 		len += tcp_hdr_len;
21294 		if (tcp->tcp_ipversion == IPV4_VERSION)
21295 			tcp->tcp_ipha->ipha_length = htons(len);
21296 		else
21297 			tcp->tcp_ip6h->ip6_plen = htons(len -
21298 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21299 
21300 		mp = dupb(*xmit_tail);
21301 		if (mp == NULL) {
21302 			if (ire != NULL)
21303 				IRE_REFRELE(ire);
21304 			return (-1);	/* out_of_mem */
21305 		}
21306 
21307 		len = tcp_hdr_len;
21308 		/*
21309 		 * There are four reasons to allocate a new hdr mblk:
21310 		 *  1) The bytes above us are in use by another packet
21311 		 *  2) We don't have good alignment
21312 		 *  3) The mblk is being shared
21313 		 *  4) We don't have enough room for a header
21314 		 */
21315 		rptr = mp->b_rptr - len;
21316 		if (!OK_32PTR(rptr) ||
21317 		    ((db = mp->b_datap), db->db_ref != 2) ||
21318 		    rptr < db->db_base + ire_fp_mp_len) {
21319 			/* NOTE: we assume allocb returns an OK_32PTR */
21320 
21321 		must_alloc:;
21322 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21323 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21324 			if (mp1 == NULL) {
21325 				freemsg(mp);
21326 				if (ire != NULL)
21327 					IRE_REFRELE(ire);
21328 				return (-1);	/* out_of_mem */
21329 			}
21330 			mp1->b_cont = mp;
21331 			mp = mp1;
21332 			/* Leave room for Link Level header */
21333 			len = tcp_hdr_len;
21334 			rptr =
21335 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21336 			mp->b_wptr = &rptr[len];
21337 		}
21338 
21339 		/*
21340 		 * Fill in the header using the template header, and add
21341 		 * options such as time-stamp, ECN and/or SACK, as needed.
21342 		 */
21343 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21344 
21345 		mp->b_rptr = rptr;
21346 
21347 		if (*tail_unsent) {
21348 			int spill = *tail_unsent;
21349 
21350 			mp1 = mp->b_cont;
21351 			if (mp1 == NULL)
21352 				mp1 = mp;
21353 
21354 			/*
21355 			 * If we're a little short, tack on more mblks until
21356 			 * there is no more spillover.
21357 			 */
21358 			while (spill < 0) {
21359 				mblk_t *nmp;
21360 				int nmpsz;
21361 
21362 				nmp = (*xmit_tail)->b_cont;
21363 				nmpsz = MBLKL(nmp);
21364 
21365 				/*
21366 				 * Excess data in mblk; can we split it?
21367 				 * If MDT is enabled for the connection,
21368 				 * keep on splitting as this is a transient
21369 				 * send path.
21370 				 */
21371 				if (!do_lso_send && !tcp->tcp_mdt &&
21372 				    (spill + nmpsz > 0)) {
21373 					/*
21374 					 * Don't split if stream head was
21375 					 * told to break up larger writes
21376 					 * into smaller ones.
21377 					 */
21378 					if (tcp->tcp_maxpsz > 0)
21379 						break;
21380 
21381 					/*
21382 					 * Next mblk is less than SMSS/2
21383 					 * rounded up to nearest 64-byte;
21384 					 * let it get sent as part of the
21385 					 * next segment.
21386 					 */
21387 					if (tcp->tcp_localnet &&
21388 					    !tcp->tcp_cork &&
21389 					    (nmpsz < roundup((mss >> 1), 64)))
21390 						break;
21391 				}
21392 
21393 				*xmit_tail = nmp;
21394 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21395 				/* Stash for rtt use later */
21396 				(*xmit_tail)->b_prev = local_time;
21397 				(*xmit_tail)->b_next =
21398 				    (mblk_t *)(uintptr_t)(*snxt - len);
21399 				mp1->b_cont = dupb(*xmit_tail);
21400 				mp1 = mp1->b_cont;
21401 
21402 				spill += nmpsz;
21403 				if (mp1 == NULL) {
21404 					*tail_unsent = spill;
21405 					freemsg(mp);
21406 					if (ire != NULL)
21407 						IRE_REFRELE(ire);
21408 					return (-1);	/* out_of_mem */
21409 				}
21410 			}
21411 
21412 			/* Trim back any surplus on the last mblk */
21413 			if (spill >= 0) {
21414 				mp1->b_wptr -= spill;
21415 				*tail_unsent = spill;
21416 			} else {
21417 				/*
21418 				 * We did not send everything we could in
21419 				 * order to remain within the b_cont limit.
21420 				 */
21421 				*usable -= spill;
21422 				*snxt += spill;
21423 				tcp->tcp_last_sent_len += spill;
21424 				UPDATE_MIB(&tcps->tcps_mib,
21425 				    tcpOutDataBytes, spill);
21426 				/*
21427 				 * Adjust the checksum
21428 				 */
21429 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21430 				sum += spill;
21431 				sum = (sum >> 16) + (sum & 0xFFFF);
21432 				U16_TO_ABE16(sum, tcph->th_sum);
21433 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21434 					sum = ntohs(
21435 					    ((ipha_t *)rptr)->ipha_length) +
21436 					    spill;
21437 					((ipha_t *)rptr)->ipha_length =
21438 					    htons(sum);
21439 				} else {
21440 					sum = ntohs(
21441 					    ((ip6_t *)rptr)->ip6_plen) +
21442 					    spill;
21443 					((ip6_t *)rptr)->ip6_plen =
21444 					    htons(sum);
21445 				}
21446 				*tail_unsent = 0;
21447 			}
21448 		}
21449 		if (tcp->tcp_ip_forward_progress) {
21450 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21451 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21452 			tcp->tcp_ip_forward_progress = B_FALSE;
21453 		}
21454 
21455 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21456 		if (do_lso_send) {
21457 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21458 			    num_lso_seg);
21459 			tcp->tcp_obsegs += num_lso_seg;
21460 
21461 			TCP_STAT(tcps, tcp_lso_times);
21462 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21463 		} else {
21464 			tcp_send_data(tcp, q, mp);
21465 			BUMP_LOCAL(tcp->tcp_obsegs);
21466 		}
21467 	}
21468 
21469 	if (ire != NULL)
21470 		IRE_REFRELE(ire);
21471 	return (0);
21472 }
21473 
21474 /* Unlink and return any mblk that looks like it contains a MDT info */
21475 static mblk_t *
21476 tcp_mdt_info_mp(mblk_t *mp)
21477 {
21478 	mblk_t	*prev_mp;
21479 
21480 	for (;;) {
21481 		prev_mp = mp;
21482 		/* no more to process? */
21483 		if ((mp = mp->b_cont) == NULL)
21484 			break;
21485 
21486 		switch (DB_TYPE(mp)) {
21487 		case M_CTL:
21488 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21489 				continue;
21490 			ASSERT(prev_mp != NULL);
21491 			prev_mp->b_cont = mp->b_cont;
21492 			mp->b_cont = NULL;
21493 			return (mp);
21494 		default:
21495 			break;
21496 		}
21497 	}
21498 	return (mp);
21499 }
21500 
21501 /* MDT info update routine, called when IP notifies us about MDT */
21502 static void
21503 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21504 {
21505 	boolean_t prev_state;
21506 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21507 
21508 	/*
21509 	 * IP is telling us to abort MDT on this connection?  We know
21510 	 * this because the capability is only turned off when IP
21511 	 * encounters some pathological cases, e.g. link-layer change
21512 	 * where the new driver doesn't support MDT, or in situation
21513 	 * where MDT usage on the link-layer has been switched off.
21514 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21515 	 * if the link-layer doesn't support MDT, and if it does, it
21516 	 * will indicate that the feature is to be turned on.
21517 	 */
21518 	prev_state = tcp->tcp_mdt;
21519 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21520 	if (!tcp->tcp_mdt && !first) {
21521 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21522 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21523 		    (void *)tcp->tcp_connp));
21524 	}
21525 
21526 	/*
21527 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21528 	 * so disable MDT otherwise.  The checks are done here
21529 	 * and in tcp_wput_data().
21530 	 */
21531 	if (tcp->tcp_mdt &&
21532 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21533 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21534 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21535 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21536 		tcp->tcp_mdt = B_FALSE;
21537 
21538 	if (tcp->tcp_mdt) {
21539 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21540 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21541 			    "version (%d), expected version is %d",
21542 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21543 			tcp->tcp_mdt = B_FALSE;
21544 			return;
21545 		}
21546 
21547 		/*
21548 		 * We need the driver to be able to handle at least three
21549 		 * spans per packet in order for tcp MDT to be utilized.
21550 		 * The first is for the header portion, while the rest are
21551 		 * needed to handle a packet that straddles across two
21552 		 * virtually non-contiguous buffers; a typical tcp packet
21553 		 * therefore consists of only two spans.  Note that we take
21554 		 * a zero as "don't care".
21555 		 */
21556 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21557 		    mdt_capab->ill_mdt_span_limit < 3) {
21558 			tcp->tcp_mdt = B_FALSE;
21559 			return;
21560 		}
21561 
21562 		/* a zero means driver wants default value */
21563 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21564 		    tcps->tcps_mdt_max_pbufs);
21565 		if (tcp->tcp_mdt_max_pld == 0)
21566 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21567 
21568 		/* ensure 32-bit alignment */
21569 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21570 		    mdt_capab->ill_mdt_hdr_head), 4);
21571 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21572 		    mdt_capab->ill_mdt_hdr_tail), 4);
21573 
21574 		if (!first && !prev_state) {
21575 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
21576 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21577 			    (void *)tcp->tcp_connp));
21578 		}
21579 	}
21580 }
21581 
21582 /* Unlink and return any mblk that looks like it contains a LSO info */
21583 static mblk_t *
21584 tcp_lso_info_mp(mblk_t *mp)
21585 {
21586 	mblk_t	*prev_mp;
21587 
21588 	for (;;) {
21589 		prev_mp = mp;
21590 		/* no more to process? */
21591 		if ((mp = mp->b_cont) == NULL)
21592 			break;
21593 
21594 		switch (DB_TYPE(mp)) {
21595 		case M_CTL:
21596 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
21597 				continue;
21598 			ASSERT(prev_mp != NULL);
21599 			prev_mp->b_cont = mp->b_cont;
21600 			mp->b_cont = NULL;
21601 			return (mp);
21602 		default:
21603 			break;
21604 		}
21605 	}
21606 
21607 	return (mp);
21608 }
21609 
21610 /* LSO info update routine, called when IP notifies us about LSO */
21611 static void
21612 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
21613 {
21614 	tcp_stack_t *tcps = tcp->tcp_tcps;
21615 
21616 	/*
21617 	 * IP is telling us to abort LSO on this connection?  We know
21618 	 * this because the capability is only turned off when IP
21619 	 * encounters some pathological cases, e.g. link-layer change
21620 	 * where the new NIC/driver doesn't support LSO, or in situation
21621 	 * where LSO usage on the link-layer has been switched off.
21622 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
21623 	 * if the link-layer doesn't support LSO, and if it does, it
21624 	 * will indicate that the feature is to be turned on.
21625 	 */
21626 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
21627 	TCP_STAT(tcps, tcp_lso_enabled);
21628 
21629 	/*
21630 	 * We currently only support LSO on simple TCP/IPv4,
21631 	 * so disable LSO otherwise.  The checks are done here
21632 	 * and in tcp_wput_data().
21633 	 */
21634 	if (tcp->tcp_lso &&
21635 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21636 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21637 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
21638 		tcp->tcp_lso = B_FALSE;
21639 		TCP_STAT(tcps, tcp_lso_disabled);
21640 	} else {
21641 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
21642 		    lso_capab->ill_lso_max);
21643 	}
21644 }
21645 
21646 static void
21647 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
21648 {
21649 	conn_t *connp = tcp->tcp_connp;
21650 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21651 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21652 
21653 	ASSERT(ire != NULL);
21654 
21655 	/*
21656 	 * We may be in the fastpath here, and although we essentially do
21657 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
21658 	 * we try to keep things as brief as possible.  After all, these
21659 	 * are only best-effort checks, and we do more thorough ones prior
21660 	 * to calling tcp_send()/tcp_multisend().
21661 	 */
21662 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
21663 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21664 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21665 	    !(ire->ire_flags & RTF_MULTIRT) &&
21666 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
21667 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
21668 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
21669 			/* Cache the result */
21670 			connp->conn_lso_ok = B_TRUE;
21671 
21672 			ASSERT(ill->ill_lso_capab != NULL);
21673 			if (!ill->ill_lso_capab->ill_lso_on) {
21674 				ill->ill_lso_capab->ill_lso_on = 1;
21675 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21676 				    "LSO for interface %s\n", (void *)connp,
21677 				    ill->ill_name));
21678 			}
21679 			tcp_lso_update(tcp, ill->ill_lso_capab);
21680 		} else if (ipst->ips_ip_multidata_outbound &&
21681 		    ILL_MDT_CAPABLE(ill)) {
21682 			/* Cache the result */
21683 			connp->conn_mdt_ok = B_TRUE;
21684 
21685 			ASSERT(ill->ill_mdt_capab != NULL);
21686 			if (!ill->ill_mdt_capab->ill_mdt_on) {
21687 				ill->ill_mdt_capab->ill_mdt_on = 1;
21688 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
21689 				    "MDT for interface %s\n", (void *)connp,
21690 				    ill->ill_name));
21691 			}
21692 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21693 		}
21694 	}
21695 
21696 	/*
21697 	 * The goal is to reduce the number of generated tcp segments by
21698 	 * setting the maxpsz multiplier to 0; this will have an affect on
21699 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21700 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21701 	 * of outbound segments and incoming ACKs, thus allowing for better
21702 	 * network and system performance.  In contrast the legacy behavior
21703 	 * may result in sending less than SMSS size, because the last mblk
21704 	 * for some packets may have more data than needed to make up SMSS,
21705 	 * and the legacy code refused to "split" it.
21706 	 *
21707 	 * We apply the new behavior on following situations:
21708 	 *
21709 	 *   1) Loopback connections,
21710 	 *   2) Connections in which the remote peer is not on local subnet,
21711 	 *   3) Local subnet connections over the bge interface (see below).
21712 	 *
21713 	 * Ideally, we would like this behavior to apply for interfaces other
21714 	 * than bge.  However, doing so would negatively impact drivers which
21715 	 * perform dynamic mapping and unmapping of DMA resources, which are
21716 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21717 	 * packet will be generated by tcp).  The bge driver does not suffer
21718 	 * from this, as it copies the mblks into pre-mapped buffers, and
21719 	 * therefore does not require more I/O resources than before.
21720 	 *
21721 	 * Otherwise, this behavior is present on all network interfaces when
21722 	 * the destination endpoint is non-local, since reducing the number
21723 	 * of packets in general is good for the network.
21724 	 *
21725 	 * TODO We need to remove this hard-coded conditional for bge once
21726 	 *	a better "self-tuning" mechanism, or a way to comprehend
21727 	 *	the driver transmit strategy is devised.  Until the solution
21728 	 *	is found and well understood, we live with this hack.
21729 	 */
21730 	if (!tcp_static_maxpsz &&
21731 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21732 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21733 		/* override the default value */
21734 		tcp->tcp_maxpsz = 0;
21735 
21736 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21737 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21738 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21739 	}
21740 
21741 	/* set the stream head parameters accordingly */
21742 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21743 }
21744 
21745 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21746 static void
21747 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21748 {
21749 	uchar_t	fval = *mp->b_rptr;
21750 	mblk_t	*tail;
21751 	queue_t	*q = tcp->tcp_wq;
21752 
21753 	/* TODO: How should flush interact with urgent data? */
21754 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21755 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21756 		/*
21757 		 * Flush only data that has not yet been put on the wire.  If
21758 		 * we flush data that we have already transmitted, life, as we
21759 		 * know it, may come to an end.
21760 		 */
21761 		tail = tcp->tcp_xmit_tail;
21762 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21763 		tcp->tcp_xmit_tail_unsent = 0;
21764 		tcp->tcp_unsent = 0;
21765 		if (tail->b_wptr != tail->b_rptr)
21766 			tail = tail->b_cont;
21767 		if (tail) {
21768 			mblk_t **excess = &tcp->tcp_xmit_head;
21769 			for (;;) {
21770 				mblk_t *mp1 = *excess;
21771 				if (mp1 == tail)
21772 					break;
21773 				tcp->tcp_xmit_tail = mp1;
21774 				tcp->tcp_xmit_last = mp1;
21775 				excess = &mp1->b_cont;
21776 			}
21777 			*excess = NULL;
21778 			tcp_close_mpp(&tail);
21779 			if (tcp->tcp_snd_zcopy_aware)
21780 				tcp_zcopy_notify(tcp);
21781 		}
21782 		/*
21783 		 * We have no unsent data, so unsent must be less than
21784 		 * tcp_xmit_lowater, so re-enable flow.
21785 		 */
21786 		mutex_enter(&tcp->tcp_non_sq_lock);
21787 		if (tcp->tcp_flow_stopped) {
21788 			tcp_clrqfull(tcp);
21789 		}
21790 		mutex_exit(&tcp->tcp_non_sq_lock);
21791 	}
21792 	/*
21793 	 * TODO: you can't just flush these, you have to increase rwnd for one
21794 	 * thing.  For another, how should urgent data interact?
21795 	 */
21796 	if (fval & FLUSHR) {
21797 		*mp->b_rptr = fval & ~FLUSHW;
21798 		/* XXX */
21799 		qreply(q, mp);
21800 		return;
21801 	}
21802 	freemsg(mp);
21803 }
21804 
21805 /*
21806  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21807  * messages.
21808  */
21809 static void
21810 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21811 {
21812 	mblk_t	*mp1;
21813 	STRUCT_HANDLE(strbuf, sb);
21814 	uint16_t port;
21815 	queue_t 	*q = tcp->tcp_wq;
21816 	in6_addr_t	v6addr;
21817 	ipaddr_t	v4addr;
21818 	uint32_t	flowinfo = 0;
21819 	int		addrlen;
21820 
21821 	/* Make sure it is one of ours. */
21822 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21823 	case TI_GETMYNAME:
21824 	case TI_GETPEERNAME:
21825 		break;
21826 	default:
21827 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21828 		return;
21829 	}
21830 	switch (mi_copy_state(q, mp, &mp1)) {
21831 	case -1:
21832 		return;
21833 	case MI_COPY_CASE(MI_COPY_IN, 1):
21834 		break;
21835 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21836 		/* Copy out the strbuf. */
21837 		mi_copyout(q, mp);
21838 		return;
21839 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21840 		/* All done. */
21841 		mi_copy_done(q, mp, 0);
21842 		return;
21843 	default:
21844 		mi_copy_done(q, mp, EPROTO);
21845 		return;
21846 	}
21847 	/* Check alignment of the strbuf */
21848 	if (!OK_32PTR(mp1->b_rptr)) {
21849 		mi_copy_done(q, mp, EINVAL);
21850 		return;
21851 	}
21852 
21853 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21854 	    (void *)mp1->b_rptr);
21855 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21856 
21857 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21858 		mi_copy_done(q, mp, EINVAL);
21859 		return;
21860 	}
21861 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21862 	case TI_GETMYNAME:
21863 		if (tcp->tcp_family == AF_INET) {
21864 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21865 				v4addr = tcp->tcp_ipha->ipha_src;
21866 			} else {
21867 				/* can't return an address in this case */
21868 				v4addr = 0;
21869 			}
21870 		} else {
21871 			/* tcp->tcp_family == AF_INET6 */
21872 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21873 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21874 				    &v6addr);
21875 			} else {
21876 				v6addr = tcp->tcp_ip6h->ip6_src;
21877 			}
21878 		}
21879 		port = tcp->tcp_lport;
21880 		break;
21881 	case TI_GETPEERNAME:
21882 		if (tcp->tcp_family == AF_INET) {
21883 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21884 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21885 				    v4addr);
21886 			} else {
21887 				/* can't return an address in this case */
21888 				v4addr = 0;
21889 			}
21890 		} else {
21891 			/* tcp->tcp_family == AF_INET6) */
21892 			v6addr = tcp->tcp_remote_v6;
21893 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21894 				/*
21895 				 * No flowinfo if tcp->tcp_ipversion is v4.
21896 				 *
21897 				 * flowinfo was already initialized to zero
21898 				 * where it was declared above, so only
21899 				 * set it if ipversion is v6.
21900 				 */
21901 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21902 				    ~IPV6_VERS_AND_FLOW_MASK;
21903 			}
21904 		}
21905 		port = tcp->tcp_fport;
21906 		break;
21907 	default:
21908 		mi_copy_done(q, mp, EPROTO);
21909 		return;
21910 	}
21911 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21912 	if (!mp1)
21913 		return;
21914 
21915 	if (tcp->tcp_family == AF_INET) {
21916 		sin_t *sin;
21917 
21918 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21919 		sin = (sin_t *)mp1->b_rptr;
21920 		mp1->b_wptr = (uchar_t *)&sin[1];
21921 		*sin = sin_null;
21922 		sin->sin_family = AF_INET;
21923 		sin->sin_addr.s_addr = v4addr;
21924 		sin->sin_port = port;
21925 	} else {
21926 		/* tcp->tcp_family == AF_INET6 */
21927 		sin6_t *sin6;
21928 
21929 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21930 		sin6 = (sin6_t *)mp1->b_rptr;
21931 		mp1->b_wptr = (uchar_t *)&sin6[1];
21932 		*sin6 = sin6_null;
21933 		sin6->sin6_family = AF_INET6;
21934 		sin6->sin6_flowinfo = flowinfo;
21935 		sin6->sin6_addr = v6addr;
21936 		sin6->sin6_port = port;
21937 	}
21938 	/* Copy out the address */
21939 	mi_copyout(q, mp);
21940 }
21941 
21942 /*
21943  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21944  * messages.
21945  */
21946 /* ARGSUSED */
21947 static void
21948 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21949 {
21950 	conn_t 	*connp = (conn_t *)arg;
21951 	tcp_t	*tcp = connp->conn_tcp;
21952 	queue_t	*q = tcp->tcp_wq;
21953 	struct iocblk	*iocp;
21954 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21955 
21956 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21957 	/*
21958 	 * Try and ASSERT the minimum possible references on the
21959 	 * conn early enough. Since we are executing on write side,
21960 	 * the connection is obviously not detached and that means
21961 	 * there is a ref each for TCP and IP. Since we are behind
21962 	 * the squeue, the minimum references needed are 3. If the
21963 	 * conn is in classifier hash list, there should be an
21964 	 * extra ref for that (we check both the possibilities).
21965 	 */
21966 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21967 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21968 
21969 	iocp = (struct iocblk *)mp->b_rptr;
21970 	switch (iocp->ioc_cmd) {
21971 	case TCP_IOC_DEFAULT_Q:
21972 		/* Wants to be the default wq. */
21973 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
21974 			iocp->ioc_error = EPERM;
21975 			iocp->ioc_count = 0;
21976 			mp->b_datap->db_type = M_IOCACK;
21977 			qreply(q, mp);
21978 			return;
21979 		}
21980 		tcp_def_q_set(tcp, mp);
21981 		return;
21982 	case _SIOCSOCKFALLBACK:
21983 		/*
21984 		 * Either sockmod is about to be popped and the socket
21985 		 * would now be treated as a plain stream, or a module
21986 		 * is about to be pushed so we could no longer use read-
21987 		 * side synchronous streams for fused loopback tcp.
21988 		 * Drain any queued data and disable direct sockfs
21989 		 * interface from now on.
21990 		 */
21991 		if (!tcp->tcp_issocket) {
21992 			DB_TYPE(mp) = M_IOCNAK;
21993 			iocp->ioc_error = EINVAL;
21994 		} else {
21995 #ifdef	_ILP32
21996 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21997 #else
21998 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21999 #endif
22000 			/*
22001 			 * Insert this socket into the acceptor hash.
22002 			 * We might need it for T_CONN_RES message
22003 			 */
22004 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22005 
22006 			if (tcp->tcp_fused) {
22007 				/*
22008 				 * This is a fused loopback tcp; disable
22009 				 * read-side synchronous streams interface
22010 				 * and drain any queued data.  It is okay
22011 				 * to do this for non-synchronous streams
22012 				 * fused tcp as well.
22013 				 */
22014 				tcp_fuse_disable_pair(tcp, B_FALSE);
22015 			}
22016 			tcp->tcp_issocket = B_FALSE;
22017 			TCP_STAT(tcps, tcp_sock_fallback);
22018 
22019 			DB_TYPE(mp) = M_IOCACK;
22020 			iocp->ioc_error = 0;
22021 		}
22022 		iocp->ioc_count = 0;
22023 		iocp->ioc_rval = 0;
22024 		qreply(q, mp);
22025 		return;
22026 	}
22027 	CALL_IP_WPUT(connp, q, mp);
22028 }
22029 
22030 /*
22031  * This routine is called by tcp_wput() to handle all TPI requests.
22032  */
22033 /* ARGSUSED */
22034 static void
22035 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22036 {
22037 	conn_t 	*connp = (conn_t *)arg;
22038 	tcp_t	*tcp = connp->conn_tcp;
22039 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22040 	uchar_t *rptr;
22041 	t_scalar_t type;
22042 	int len;
22043 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22044 
22045 	/*
22046 	 * Try and ASSERT the minimum possible references on the
22047 	 * conn early enough. Since we are executing on write side,
22048 	 * the connection is obviously not detached and that means
22049 	 * there is a ref each for TCP and IP. Since we are behind
22050 	 * the squeue, the minimum references needed are 3. If the
22051 	 * conn is in classifier hash list, there should be an
22052 	 * extra ref for that (we check both the possibilities).
22053 	 */
22054 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22055 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22056 
22057 	rptr = mp->b_rptr;
22058 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22059 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22060 		type = ((union T_primitives *)rptr)->type;
22061 		if (type == T_EXDATA_REQ) {
22062 			uint32_t msize = msgdsize(mp->b_cont);
22063 
22064 			len = msize - 1;
22065 			if (len < 0) {
22066 				freemsg(mp);
22067 				return;
22068 			}
22069 			/*
22070 			 * Try to force urgent data out on the wire.
22071 			 * Even if we have unsent data this will
22072 			 * at least send the urgent flag.
22073 			 * XXX does not handle more flag correctly.
22074 			 */
22075 			len += tcp->tcp_unsent;
22076 			len += tcp->tcp_snxt;
22077 			tcp->tcp_urg = len;
22078 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22079 
22080 			/* Bypass tcp protocol for fused tcp loopback */
22081 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22082 				return;
22083 		} else if (type != T_DATA_REQ) {
22084 			goto non_urgent_data;
22085 		}
22086 		/* TODO: options, flags, ... from user */
22087 		/* Set length to zero for reclamation below */
22088 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22089 		freeb(mp);
22090 		return;
22091 	} else {
22092 		if (tcp->tcp_debug) {
22093 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22094 			    "tcp_wput_proto, dropping one...");
22095 		}
22096 		freemsg(mp);
22097 		return;
22098 	}
22099 
22100 non_urgent_data:
22101 
22102 	switch ((int)tprim->type) {
22103 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22104 		/*
22105 		 * save the kssl_ent_t from the next block, and convert this
22106 		 * back to a normal bind_req.
22107 		 */
22108 		if (mp->b_cont != NULL) {
22109 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22110 
22111 			if (tcp->tcp_kssl_ent != NULL) {
22112 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22113 				    KSSL_NO_PROXY);
22114 				tcp->tcp_kssl_ent = NULL;
22115 			}
22116 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22117 			    sizeof (kssl_ent_t));
22118 			kssl_hold_ent(tcp->tcp_kssl_ent);
22119 			freemsg(mp->b_cont);
22120 			mp->b_cont = NULL;
22121 		}
22122 		tprim->type = T_BIND_REQ;
22123 
22124 	/* FALLTHROUGH */
22125 	case O_T_BIND_REQ:	/* bind request */
22126 	case T_BIND_REQ:	/* new semantics bind request */
22127 		tcp_bind(tcp, mp);
22128 		break;
22129 	case T_UNBIND_REQ:	/* unbind request */
22130 		tcp_unbind(tcp, mp);
22131 		break;
22132 	case O_T_CONN_RES:	/* old connection response XXX */
22133 	case T_CONN_RES:	/* connection response */
22134 		tcp_accept(tcp, mp);
22135 		break;
22136 	case T_CONN_REQ:	/* connection request */
22137 		tcp_connect(tcp, mp);
22138 		break;
22139 	case T_DISCON_REQ:	/* disconnect request */
22140 		tcp_disconnect(tcp, mp);
22141 		break;
22142 	case T_CAPABILITY_REQ:
22143 		tcp_capability_req(tcp, mp);	/* capability request */
22144 		break;
22145 	case T_INFO_REQ:	/* information request */
22146 		tcp_info_req(tcp, mp);
22147 		break;
22148 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22149 		/* Only IP is allowed to return meaningful value */
22150 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22151 		break;
22152 	case T_OPTMGMT_REQ:
22153 		/*
22154 		 * Note:  no support for snmpcom_req() through new
22155 		 * T_OPTMGMT_REQ. See comments in ip.c
22156 		 */
22157 		/* Only IP is allowed to return meaningful value */
22158 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
22159 		break;
22160 
22161 	case T_UNITDATA_REQ:	/* unitdata request */
22162 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22163 		break;
22164 	case T_ORDREL_REQ:	/* orderly release req */
22165 		freemsg(mp);
22166 
22167 		if (tcp->tcp_fused)
22168 			tcp_unfuse(tcp);
22169 
22170 		if (tcp_xmit_end(tcp) != 0) {
22171 			/*
22172 			 * We were crossing FINs and got a reset from
22173 			 * the other side. Just ignore it.
22174 			 */
22175 			if (tcp->tcp_debug) {
22176 				(void) strlog(TCP_MOD_ID, 0, 1,
22177 				    SL_ERROR|SL_TRACE,
22178 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22179 				    "state %s",
22180 				    tcp_display(tcp, NULL,
22181 				    DISP_ADDR_AND_PORT));
22182 			}
22183 		}
22184 		break;
22185 	case T_ADDR_REQ:
22186 		tcp_addr_req(tcp, mp);
22187 		break;
22188 	default:
22189 		if (tcp->tcp_debug) {
22190 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22191 			    "tcp_wput_proto, bogus TPI msg, type %d",
22192 			    tprim->type);
22193 		}
22194 		/*
22195 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22196 		 * to recover.
22197 		 */
22198 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22199 		break;
22200 	}
22201 }
22202 
22203 /*
22204  * The TCP write service routine should never be called...
22205  */
22206 /* ARGSUSED */
22207 static void
22208 tcp_wsrv(queue_t *q)
22209 {
22210 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22211 
22212 	TCP_STAT(tcps, tcp_wsrv_called);
22213 }
22214 
22215 /* Non overlapping byte exchanger */
22216 static void
22217 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22218 {
22219 	uchar_t	uch;
22220 
22221 	while (len-- > 0) {
22222 		uch = a[len];
22223 		a[len] = b[len];
22224 		b[len] = uch;
22225 	}
22226 }
22227 
22228 /*
22229  * Send out a control packet on the tcp connection specified.  This routine
22230  * is typically called where we need a simple ACK or RST generated.
22231  */
22232 static void
22233 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22234 {
22235 	uchar_t		*rptr;
22236 	tcph_t		*tcph;
22237 	ipha_t		*ipha = NULL;
22238 	ip6_t		*ip6h = NULL;
22239 	uint32_t	sum;
22240 	int		tcp_hdr_len;
22241 	int		tcp_ip_hdr_len;
22242 	mblk_t		*mp;
22243 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22244 
22245 	/*
22246 	 * Save sum for use in source route later.
22247 	 */
22248 	ASSERT(tcp != NULL);
22249 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22250 	tcp_hdr_len = tcp->tcp_hdr_len;
22251 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22252 
22253 	/* If a text string is passed in with the request, pass it to strlog. */
22254 	if (str != NULL && tcp->tcp_debug) {
22255 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22256 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22257 		    str, seq, ack, ctl);
22258 	}
22259 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22260 	    BPRI_MED);
22261 	if (mp == NULL) {
22262 		return;
22263 	}
22264 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22265 	mp->b_rptr = rptr;
22266 	mp->b_wptr = &rptr[tcp_hdr_len];
22267 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22268 
22269 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22270 		ipha = (ipha_t *)rptr;
22271 		ipha->ipha_length = htons(tcp_hdr_len);
22272 	} else {
22273 		ip6h = (ip6_t *)rptr;
22274 		ASSERT(tcp != NULL);
22275 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22276 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22277 	}
22278 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22279 	tcph->th_flags[0] = (uint8_t)ctl;
22280 	if (ctl & TH_RST) {
22281 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22282 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22283 		/*
22284 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22285 		 */
22286 		if (tcp->tcp_snd_ts_ok &&
22287 		    tcp->tcp_state > TCPS_SYN_SENT) {
22288 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22289 			*(mp->b_wptr) = TCPOPT_EOL;
22290 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22291 				ipha->ipha_length = htons(tcp_hdr_len -
22292 				    TCPOPT_REAL_TS_LEN);
22293 			} else {
22294 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22295 				    TCPOPT_REAL_TS_LEN);
22296 			}
22297 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22298 			sum -= TCPOPT_REAL_TS_LEN;
22299 		}
22300 	}
22301 	if (ctl & TH_ACK) {
22302 		if (tcp->tcp_snd_ts_ok) {
22303 			U32_TO_BE32(lbolt,
22304 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22305 			U32_TO_BE32(tcp->tcp_ts_recent,
22306 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22307 		}
22308 
22309 		/* Update the latest receive window size in TCP header. */
22310 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22311 		    tcph->th_win);
22312 		tcp->tcp_rack = ack;
22313 		tcp->tcp_rack_cnt = 0;
22314 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22315 	}
22316 	BUMP_LOCAL(tcp->tcp_obsegs);
22317 	U32_TO_BE32(seq, tcph->th_seq);
22318 	U32_TO_BE32(ack, tcph->th_ack);
22319 	/*
22320 	 * Include the adjustment for a source route if any.
22321 	 */
22322 	sum = (sum >> 16) + (sum & 0xFFFF);
22323 	U16_TO_BE16(sum, tcph->th_sum);
22324 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22325 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22326 }
22327 
22328 /*
22329  * If this routine returns B_TRUE, TCP can generate a RST in response
22330  * to a segment.  If it returns B_FALSE, TCP should not respond.
22331  */
22332 static boolean_t
22333 tcp_send_rst_chk(tcp_stack_t *tcps)
22334 {
22335 	clock_t	now;
22336 
22337 	/*
22338 	 * TCP needs to protect itself from generating too many RSTs.
22339 	 * This can be a DoS attack by sending us random segments
22340 	 * soliciting RSTs.
22341 	 *
22342 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22343 	 * in each 1 second interval.  In this way, TCP still generate
22344 	 * RSTs in normal cases but when under attack, the impact is
22345 	 * limited.
22346 	 */
22347 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22348 		now = lbolt;
22349 		/* lbolt can wrap around. */
22350 		if ((tcps->tcps_last_rst_intrvl > now) ||
22351 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22352 		    1*SECONDS)) {
22353 			tcps->tcps_last_rst_intrvl = now;
22354 			tcps->tcps_rst_cnt = 1;
22355 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22356 			return (B_FALSE);
22357 		}
22358 	}
22359 	return (B_TRUE);
22360 }
22361 
22362 /*
22363  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22364  */
22365 static void
22366 tcp_ip_ire_mark_advice(tcp_t *tcp)
22367 {
22368 	mblk_t *mp;
22369 	ipic_t *ipic;
22370 
22371 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22372 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22373 		    &ipic);
22374 	} else {
22375 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22376 		    &ipic);
22377 	}
22378 	if (mp == NULL)
22379 		return;
22380 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22381 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22382 }
22383 
22384 /*
22385  * Return an IP advice ioctl mblk and set ipic to be the pointer
22386  * to the advice structure.
22387  */
22388 static mblk_t *
22389 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22390 {
22391 	struct iocblk *ioc;
22392 	mblk_t *mp, *mp1;
22393 
22394 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22395 	if (mp == NULL)
22396 		return (NULL);
22397 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22398 	*ipic = (ipic_t *)mp->b_rptr;
22399 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22400 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22401 
22402 	bcopy(addr, *ipic + 1, addr_len);
22403 
22404 	(*ipic)->ipic_addr_length = addr_len;
22405 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22406 
22407 	mp1 = mkiocb(IP_IOCTL);
22408 	if (mp1 == NULL) {
22409 		freemsg(mp);
22410 		return (NULL);
22411 	}
22412 	mp1->b_cont = mp;
22413 	ioc = (struct iocblk *)mp1->b_rptr;
22414 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22415 
22416 	return (mp1);
22417 }
22418 
22419 /*
22420  * Generate a reset based on an inbound packet for which there is no active
22421  * tcp state that we can find.
22422  *
22423  * IPSEC NOTE : Try to send the reply with the same protection as it came
22424  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22425  * the packet will go out at the same level of protection as it came in by
22426  * converting the IPSEC_IN to IPSEC_OUT.
22427  */
22428 static void
22429 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22430     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22431     tcp_stack_t *tcps)
22432 {
22433 	ipha_t		*ipha = NULL;
22434 	ip6_t		*ip6h = NULL;
22435 	ushort_t	len;
22436 	tcph_t		*tcph;
22437 	int		i;
22438 	mblk_t		*ipsec_mp;
22439 	boolean_t	mctl_present;
22440 	ipic_t		*ipic;
22441 	ipaddr_t	v4addr;
22442 	in6_addr_t	v6addr;
22443 	int		addr_len;
22444 	void		*addr;
22445 	queue_t		*q = tcps->tcps_g_q;
22446 	tcp_t		*tcp;
22447 	cred_t		*cr;
22448 	mblk_t		*nmp;
22449 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22450 
22451 	if (tcps->tcps_g_q == NULL) {
22452 		/*
22453 		 * For non-zero stackids the default queue isn't created
22454 		 * until the first open, thus there can be a need to send
22455 		 * a reset before then. But we can't do that, hence we just
22456 		 * drop the packet. Later during boot, when the default queue
22457 		 * has been setup, a retransmitted packet from the peer
22458 		 * will result in a reset.
22459 		 */
22460 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22461 		    GLOBAL_NETSTACKID);
22462 		freemsg(mp);
22463 		return;
22464 	}
22465 
22466 	tcp = Q_TO_TCP(q);
22467 
22468 	if (!tcp_send_rst_chk(tcps)) {
22469 		tcps->tcps_rst_unsent++;
22470 		freemsg(mp);
22471 		return;
22472 	}
22473 
22474 	if (mp->b_datap->db_type == M_CTL) {
22475 		ipsec_mp = mp;
22476 		mp = mp->b_cont;
22477 		mctl_present = B_TRUE;
22478 	} else {
22479 		ipsec_mp = mp;
22480 		mctl_present = B_FALSE;
22481 	}
22482 
22483 	if (str && q && tcps->tcps_dbg) {
22484 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22485 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22486 		    "flags 0x%x",
22487 		    str, seq, ack, ctl);
22488 	}
22489 	if (mp->b_datap->db_ref != 1) {
22490 		mblk_t *mp1 = copyb(mp);
22491 		freemsg(mp);
22492 		mp = mp1;
22493 		if (!mp) {
22494 			if (mctl_present)
22495 				freeb(ipsec_mp);
22496 			return;
22497 		} else {
22498 			if (mctl_present) {
22499 				ipsec_mp->b_cont = mp;
22500 			} else {
22501 				ipsec_mp = mp;
22502 			}
22503 		}
22504 	} else if (mp->b_cont) {
22505 		freemsg(mp->b_cont);
22506 		mp->b_cont = NULL;
22507 	}
22508 	/*
22509 	 * We skip reversing source route here.
22510 	 * (for now we replace all IP options with EOL)
22511 	 */
22512 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22513 		ipha = (ipha_t *)mp->b_rptr;
22514 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22515 			mp->b_rptr[i] = IPOPT_EOL;
22516 		/*
22517 		 * Make sure that src address isn't flagrantly invalid.
22518 		 * Not all broadcast address checking for the src address
22519 		 * is possible, since we don't know the netmask of the src
22520 		 * addr.  No check for destination address is done, since
22521 		 * IP will not pass up a packet with a broadcast dest
22522 		 * address to TCP.  Similar checks are done below for IPv6.
22523 		 */
22524 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22525 		    CLASSD(ipha->ipha_src)) {
22526 			freemsg(ipsec_mp);
22527 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22528 			return;
22529 		}
22530 	} else {
22531 		ip6h = (ip6_t *)mp->b_rptr;
22532 
22533 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22534 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22535 			freemsg(ipsec_mp);
22536 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22537 			return;
22538 		}
22539 
22540 		/* Remove any extension headers assuming partial overlay */
22541 		if (ip_hdr_len > IPV6_HDR_LEN) {
22542 			uint8_t *to;
22543 
22544 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22545 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22546 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22547 			ip_hdr_len = IPV6_HDR_LEN;
22548 			ip6h = (ip6_t *)mp->b_rptr;
22549 			ip6h->ip6_nxt = IPPROTO_TCP;
22550 		}
22551 	}
22552 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22553 	if (tcph->th_flags[0] & TH_RST) {
22554 		freemsg(ipsec_mp);
22555 		return;
22556 	}
22557 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22558 	len = ip_hdr_len + sizeof (tcph_t);
22559 	mp->b_wptr = &mp->b_rptr[len];
22560 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22561 		ipha->ipha_length = htons(len);
22562 		/* Swap addresses */
22563 		v4addr = ipha->ipha_src;
22564 		ipha->ipha_src = ipha->ipha_dst;
22565 		ipha->ipha_dst = v4addr;
22566 		ipha->ipha_ident = 0;
22567 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22568 		addr_len = IP_ADDR_LEN;
22569 		addr = &v4addr;
22570 	} else {
22571 		/* No ip6i_t in this case */
22572 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22573 		/* Swap addresses */
22574 		v6addr = ip6h->ip6_src;
22575 		ip6h->ip6_src = ip6h->ip6_dst;
22576 		ip6h->ip6_dst = v6addr;
22577 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22578 		addr_len = IPV6_ADDR_LEN;
22579 		addr = &v6addr;
22580 	}
22581 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22582 	U32_TO_BE32(ack, tcph->th_ack);
22583 	U32_TO_BE32(seq, tcph->th_seq);
22584 	U16_TO_BE16(0, tcph->th_win);
22585 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22586 	tcph->th_flags[0] = (uint8_t)ctl;
22587 	if (ctl & TH_RST) {
22588 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22589 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22590 	}
22591 
22592 	/* IP trusts us to set up labels when required. */
22593 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22594 	    crgetlabel(cr) != NULL) {
22595 		int err, adjust;
22596 
22597 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22598 			err = tsol_check_label(cr, &mp, &adjust,
22599 			    tcp->tcp_connp->conn_mac_exempt,
22600 			    tcps->tcps_netstack->netstack_ip);
22601 		else
22602 			err = tsol_check_label_v6(cr, &mp, &adjust,
22603 			    tcp->tcp_connp->conn_mac_exempt,
22604 			    tcps->tcps_netstack->netstack_ip);
22605 		if (mctl_present)
22606 			ipsec_mp->b_cont = mp;
22607 		else
22608 			ipsec_mp = mp;
22609 		if (err != 0) {
22610 			freemsg(ipsec_mp);
22611 			return;
22612 		}
22613 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22614 			ipha = (ipha_t *)mp->b_rptr;
22615 			adjust += ntohs(ipha->ipha_length);
22616 			ipha->ipha_length = htons(adjust);
22617 		} else {
22618 			ip6h = (ip6_t *)mp->b_rptr;
22619 		}
22620 	}
22621 
22622 	if (mctl_present) {
22623 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22624 
22625 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22626 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22627 			return;
22628 		}
22629 	}
22630 	if (zoneid == ALL_ZONES)
22631 		zoneid = GLOBAL_ZONEID;
22632 
22633 	/* Add the zoneid so ip_output routes it properly */
22634 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22635 		freemsg(ipsec_mp);
22636 		return;
22637 	}
22638 	ipsec_mp = nmp;
22639 
22640 	/*
22641 	 * NOTE:  one might consider tracing a TCP packet here, but
22642 	 * this function has no active TCP state and no tcp structure
22643 	 * that has a trace buffer.  If we traced here, we would have
22644 	 * to keep a local trace buffer in tcp_record_trace().
22645 	 *
22646 	 * TSol note: The mblk that contains the incoming packet was
22647 	 * reused by tcp_xmit_listener_reset, so it already contains
22648 	 * the right credentials and we don't need to call mblk_setcred.
22649 	 * Also the conn's cred is not right since it is associated
22650 	 * with tcps_g_q.
22651 	 */
22652 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
22653 
22654 	/*
22655 	 * Tell IP to mark the IRE used for this destination temporary.
22656 	 * This way, we can limit our exposure to DoS attack because IP
22657 	 * creates an IRE for each destination.  If there are too many,
22658 	 * the time to do any routing lookup will be extremely long.  And
22659 	 * the lookup can be in interrupt context.
22660 	 *
22661 	 * Note that in normal circumstances, this marking should not
22662 	 * affect anything.  It would be nice if only 1 message is
22663 	 * needed to inform IP that the IRE created for this RST should
22664 	 * not be added to the cache table.  But there is currently
22665 	 * not such communication mechanism between TCP and IP.  So
22666 	 * the best we can do now is to send the advice ioctl to IP
22667 	 * to mark the IRE temporary.
22668 	 */
22669 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
22670 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22671 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22672 	}
22673 }
22674 
22675 /*
22676  * Initiate closedown sequence on an active connection.  (May be called as
22677  * writer.)  Return value zero for OK return, non-zero for error return.
22678  */
22679 static int
22680 tcp_xmit_end(tcp_t *tcp)
22681 {
22682 	ipic_t	*ipic;
22683 	mblk_t	*mp;
22684 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22685 
22686 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
22687 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
22688 		/*
22689 		 * Invalid state, only states TCPS_SYN_RCVD,
22690 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
22691 		 */
22692 		return (-1);
22693 	}
22694 
22695 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
22696 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
22697 	/*
22698 	 * If there is nothing more unsent, send the FIN now.
22699 	 * Otherwise, it will go out with the last segment.
22700 	 */
22701 	if (tcp->tcp_unsent == 0) {
22702 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
22703 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
22704 
22705 		if (mp) {
22706 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22707 			tcp_send_data(tcp, tcp->tcp_wq, mp);
22708 		} else {
22709 			/*
22710 			 * Couldn't allocate msg.  Pretend we got it out.
22711 			 * Wait for rexmit timeout.
22712 			 */
22713 			tcp->tcp_snxt = tcp->tcp_fss + 1;
22714 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22715 		}
22716 
22717 		/*
22718 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
22719 		 * changed.
22720 		 */
22721 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
22722 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
22723 		}
22724 	} else {
22725 		/*
22726 		 * If tcp->tcp_cork is set, then the data will not get sent,
22727 		 * so we have to check that and unset it first.
22728 		 */
22729 		if (tcp->tcp_cork)
22730 			tcp->tcp_cork = B_FALSE;
22731 		tcp_wput_data(tcp, NULL, B_FALSE);
22732 	}
22733 
22734 	/*
22735 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22736 	 * is 0, don't update the cache.
22737 	 */
22738 	if (tcps->tcps_rtt_updates == 0 ||
22739 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
22740 		return (0);
22741 
22742 	/*
22743 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22744 	 * different from the destination.
22745 	 */
22746 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22747 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22748 			return (0);
22749 		}
22750 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22751 		    &ipic);
22752 	} else {
22753 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22754 		    &tcp->tcp_ip6h->ip6_dst))) {
22755 			return (0);
22756 		}
22757 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22758 		    &ipic);
22759 	}
22760 
22761 	/* Record route attributes in the IRE for use by future connections. */
22762 	if (mp == NULL)
22763 		return (0);
22764 
22765 	/*
22766 	 * We do not have a good algorithm to update ssthresh at this time.
22767 	 * So don't do any update.
22768 	 */
22769 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22770 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22771 
22772 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22773 	return (0);
22774 }
22775 
22776 /*
22777  * Generate a "no listener here" RST in response to an "unknown" segment.
22778  * Note that we are reusing the incoming mp to construct the outgoing
22779  * RST.
22780  */
22781 void
22782 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
22783     tcp_stack_t *tcps)
22784 {
22785 	uchar_t		*rptr;
22786 	uint32_t	seg_len;
22787 	tcph_t		*tcph;
22788 	uint32_t	seg_seq;
22789 	uint32_t	seg_ack;
22790 	uint_t		flags;
22791 	mblk_t		*ipsec_mp;
22792 	ipha_t 		*ipha;
22793 	ip6_t 		*ip6h;
22794 	boolean_t	mctl_present = B_FALSE;
22795 	boolean_t	check = B_TRUE;
22796 	boolean_t	policy_present;
22797 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
22798 
22799 	TCP_STAT(tcps, tcp_no_listener);
22800 
22801 	ipsec_mp = mp;
22802 
22803 	if (mp->b_datap->db_type == M_CTL) {
22804 		ipsec_in_t *ii;
22805 
22806 		mctl_present = B_TRUE;
22807 		mp = mp->b_cont;
22808 
22809 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22810 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22811 		if (ii->ipsec_in_dont_check) {
22812 			check = B_FALSE;
22813 			if (!ii->ipsec_in_secure) {
22814 				freeb(ipsec_mp);
22815 				mctl_present = B_FALSE;
22816 				ipsec_mp = mp;
22817 			}
22818 		}
22819 	}
22820 
22821 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22822 		policy_present = ipss->ipsec_inbound_v4_policy_present;
22823 		ipha = (ipha_t *)mp->b_rptr;
22824 		ip6h = NULL;
22825 	} else {
22826 		policy_present = ipss->ipsec_inbound_v6_policy_present;
22827 		ipha = NULL;
22828 		ip6h = (ip6_t *)mp->b_rptr;
22829 	}
22830 
22831 	if (check && policy_present) {
22832 		/*
22833 		 * The conn_t parameter is NULL because we already know
22834 		 * nobody's home.
22835 		 */
22836 		ipsec_mp = ipsec_check_global_policy(
22837 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
22838 		    tcps->tcps_netstack);
22839 		if (ipsec_mp == NULL)
22840 			return;
22841 	}
22842 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
22843 		DTRACE_PROBE2(
22844 		    tx__ip__log__error__nolistener__tcp,
22845 		    char *, "Could not reply with RST to mp(1)",
22846 		    mblk_t *, mp);
22847 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
22848 		freemsg(ipsec_mp);
22849 		return;
22850 	}
22851 
22852 	rptr = mp->b_rptr;
22853 
22854 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22855 	seg_seq = BE32_TO_U32(tcph->th_seq);
22856 	seg_ack = BE32_TO_U32(tcph->th_ack);
22857 	flags = tcph->th_flags[0];
22858 
22859 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22860 	if (flags & TH_RST) {
22861 		freemsg(ipsec_mp);
22862 	} else if (flags & TH_ACK) {
22863 		tcp_xmit_early_reset("no tcp, reset",
22864 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps);
22865 	} else {
22866 		if (flags & TH_SYN) {
22867 			seg_len++;
22868 		} else {
22869 			/*
22870 			 * Here we violate the RFC.  Note that a normal
22871 			 * TCP will never send a segment without the ACK
22872 			 * flag, except for RST or SYN segment.  This
22873 			 * segment is neither.  Just drop it on the
22874 			 * floor.
22875 			 */
22876 			freemsg(ipsec_mp);
22877 			tcps->tcps_rst_unsent++;
22878 			return;
22879 		}
22880 
22881 		tcp_xmit_early_reset("no tcp, reset/ack",
22882 		    ipsec_mp, 0, seg_seq + seg_len,
22883 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps);
22884 	}
22885 }
22886 
22887 /*
22888  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22889  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22890  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22891  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22892  * otherwise it will dup partial mblks.)
22893  * Otherwise, an appropriate ACK packet will be generated.  This
22894  * routine is not usually called to send new data for the first time.  It
22895  * is mostly called out of the timer for retransmits, and to generate ACKs.
22896  *
22897  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22898  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22899  * of the original mblk chain will be returned in *offset and *end_mp.
22900  */
22901 mblk_t *
22902 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22903     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22904     boolean_t rexmit)
22905 {
22906 	int	data_length;
22907 	int32_t	off = 0;
22908 	uint_t	flags;
22909 	mblk_t	*mp1;
22910 	mblk_t	*mp2;
22911 	uchar_t	*rptr;
22912 	tcph_t	*tcph;
22913 	int32_t	num_sack_blk = 0;
22914 	int32_t	sack_opt_len = 0;
22915 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22916 
22917 	/* Allocate for our maximum TCP header + link-level */
22918 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
22919 	    tcps->tcps_wroff_xtra, BPRI_MED);
22920 	if (!mp1)
22921 		return (NULL);
22922 	data_length = 0;
22923 
22924 	/*
22925 	 * Note that tcp_mss has been adjusted to take into account the
22926 	 * timestamp option if applicable.  Because SACK options do not
22927 	 * appear in every TCP segments and they are of variable lengths,
22928 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22929 	 * the actual segment length when we need to send a segment which
22930 	 * includes SACK options.
22931 	 */
22932 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22933 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22934 		    tcp->tcp_num_sack_blk);
22935 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22936 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22937 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22938 			max_to_send -= sack_opt_len;
22939 	}
22940 
22941 	if (offset != NULL) {
22942 		off = *offset;
22943 		/* We use offset as an indicator that end_mp is not NULL. */
22944 		*end_mp = NULL;
22945 	}
22946 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22947 		/* This could be faster with cooperation from downstream */
22948 		if (mp2 != mp1 && !sendall &&
22949 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22950 		    max_to_send)
22951 			/*
22952 			 * Don't send the next mblk since the whole mblk
22953 			 * does not fit.
22954 			 */
22955 			break;
22956 		mp2->b_cont = dupb(mp);
22957 		mp2 = mp2->b_cont;
22958 		if (!mp2) {
22959 			freemsg(mp1);
22960 			return (NULL);
22961 		}
22962 		mp2->b_rptr += off;
22963 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22964 		    (uintptr_t)INT_MAX);
22965 
22966 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22967 		if (data_length > max_to_send) {
22968 			mp2->b_wptr -= data_length - max_to_send;
22969 			data_length = max_to_send;
22970 			off = mp2->b_wptr - mp->b_rptr;
22971 			break;
22972 		} else {
22973 			off = 0;
22974 		}
22975 	}
22976 	if (offset != NULL) {
22977 		*offset = off;
22978 		*end_mp = mp;
22979 	}
22980 	if (seg_len != NULL) {
22981 		*seg_len = data_length;
22982 	}
22983 
22984 	/* Update the latest receive window size in TCP header. */
22985 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22986 	    tcp->tcp_tcph->th_win);
22987 
22988 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
22989 	mp1->b_rptr = rptr;
22990 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22991 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22992 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22993 	U32_TO_ABE32(seq, tcph->th_seq);
22994 
22995 	/*
22996 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22997 	 * that this function was called from tcp_wput_data. Thus, when called
22998 	 * to retransmit data the setting of the PUSH bit may appear some
22999 	 * what random in that it might get set when it should not. This
23000 	 * should not pose any performance issues.
23001 	 */
23002 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23003 	    tcp->tcp_unsent == data_length)) {
23004 		flags = TH_ACK | TH_PUSH;
23005 	} else {
23006 		flags = TH_ACK;
23007 	}
23008 
23009 	if (tcp->tcp_ecn_ok) {
23010 		if (tcp->tcp_ecn_echo_on)
23011 			flags |= TH_ECE;
23012 
23013 		/*
23014 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23015 		 * There is no TCP flow control for non-data segments, and
23016 		 * only data segment is transmitted reliably.
23017 		 */
23018 		if (data_length > 0 && !rexmit) {
23019 			SET_ECT(tcp, rptr);
23020 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23021 				flags |= TH_CWR;
23022 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23023 			}
23024 		}
23025 	}
23026 
23027 	if (tcp->tcp_valid_bits) {
23028 		uint32_t u1;
23029 
23030 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23031 		    seq == tcp->tcp_iss) {
23032 			uchar_t	*wptr;
23033 
23034 			/*
23035 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23036 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23037 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23038 			 * our SYN is not ack'ed but the app closes this
23039 			 * TCP connection.
23040 			 */
23041 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23042 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23043 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23044 
23045 			/*
23046 			 * Tack on the MSS option.  It is always needed
23047 			 * for both active and passive open.
23048 			 *
23049 			 * MSS option value should be interface MTU - MIN
23050 			 * TCP/IP header according to RFC 793 as it means
23051 			 * the maximum segment size TCP can receive.  But
23052 			 * to get around some broken middle boxes/end hosts
23053 			 * out there, we allow the option value to be the
23054 			 * same as the MSS option size on the peer side.
23055 			 * In this way, the other side will not send
23056 			 * anything larger than they can receive.
23057 			 *
23058 			 * Note that for SYN_SENT state, the ndd param
23059 			 * tcp_use_smss_as_mss_opt has no effect as we
23060 			 * don't know the peer's MSS option value. So
23061 			 * the only case we need to take care of is in
23062 			 * SYN_RCVD state, which is done later.
23063 			 */
23064 			wptr = mp1->b_wptr;
23065 			wptr[0] = TCPOPT_MAXSEG;
23066 			wptr[1] = TCPOPT_MAXSEG_LEN;
23067 			wptr += 2;
23068 			u1 = tcp->tcp_if_mtu -
23069 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23070 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23071 			    TCP_MIN_HEADER_LENGTH;
23072 			U16_TO_BE16(u1, wptr);
23073 			mp1->b_wptr = wptr + 2;
23074 			/* Update the offset to cover the additional word */
23075 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23076 
23077 			/*
23078 			 * Note that the following way of filling in
23079 			 * TCP options are not optimal.  Some NOPs can
23080 			 * be saved.  But there is no need at this time
23081 			 * to optimize it.  When it is needed, we will
23082 			 * do it.
23083 			 */
23084 			switch (tcp->tcp_state) {
23085 			case TCPS_SYN_SENT:
23086 				flags = TH_SYN;
23087 
23088 				if (tcp->tcp_snd_ts_ok) {
23089 					uint32_t llbolt = (uint32_t)lbolt;
23090 
23091 					wptr = mp1->b_wptr;
23092 					wptr[0] = TCPOPT_NOP;
23093 					wptr[1] = TCPOPT_NOP;
23094 					wptr[2] = TCPOPT_TSTAMP;
23095 					wptr[3] = TCPOPT_TSTAMP_LEN;
23096 					wptr += 4;
23097 					U32_TO_BE32(llbolt, wptr);
23098 					wptr += 4;
23099 					ASSERT(tcp->tcp_ts_recent == 0);
23100 					U32_TO_BE32(0L, wptr);
23101 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23102 					tcph->th_offset_and_rsrvd[0] +=
23103 					    (3 << 4);
23104 				}
23105 
23106 				/*
23107 				 * Set up all the bits to tell other side
23108 				 * we are ECN capable.
23109 				 */
23110 				if (tcp->tcp_ecn_ok) {
23111 					flags |= (TH_ECE | TH_CWR);
23112 				}
23113 				break;
23114 			case TCPS_SYN_RCVD:
23115 				flags |= TH_SYN;
23116 
23117 				/*
23118 				 * Reset the MSS option value to be SMSS
23119 				 * We should probably add back the bytes
23120 				 * for timestamp option and IPsec.  We
23121 				 * don't do that as this is a workaround
23122 				 * for broken middle boxes/end hosts, it
23123 				 * is better for us to be more cautious.
23124 				 * They may not take these things into
23125 				 * account in their SMSS calculation.  Thus
23126 				 * the peer's calculated SMSS may be smaller
23127 				 * than what it can be.  This should be OK.
23128 				 */
23129 				if (tcps->tcps_use_smss_as_mss_opt) {
23130 					u1 = tcp->tcp_mss;
23131 					U16_TO_BE16(u1, wptr);
23132 				}
23133 
23134 				/*
23135 				 * If the other side is ECN capable, reply
23136 				 * that we are also ECN capable.
23137 				 */
23138 				if (tcp->tcp_ecn_ok)
23139 					flags |= TH_ECE;
23140 				break;
23141 			default:
23142 				/*
23143 				 * The above ASSERT() makes sure that this
23144 				 * must be FIN-WAIT-1 state.  Our SYN has
23145 				 * not been ack'ed so retransmit it.
23146 				 */
23147 				flags |= TH_SYN;
23148 				break;
23149 			}
23150 
23151 			if (tcp->tcp_snd_ws_ok) {
23152 				wptr = mp1->b_wptr;
23153 				wptr[0] =  TCPOPT_NOP;
23154 				wptr[1] =  TCPOPT_WSCALE;
23155 				wptr[2] =  TCPOPT_WS_LEN;
23156 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23157 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23158 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23159 			}
23160 
23161 			if (tcp->tcp_snd_sack_ok) {
23162 				wptr = mp1->b_wptr;
23163 				wptr[0] = TCPOPT_NOP;
23164 				wptr[1] = TCPOPT_NOP;
23165 				wptr[2] = TCPOPT_SACK_PERMITTED;
23166 				wptr[3] = TCPOPT_SACK_OK_LEN;
23167 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23168 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23169 			}
23170 
23171 			/* allocb() of adequate mblk assures space */
23172 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23173 			    (uintptr_t)INT_MAX);
23174 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23175 			/*
23176 			 * Get IP set to checksum on our behalf
23177 			 * Include the adjustment for a source route if any.
23178 			 */
23179 			u1 += tcp->tcp_sum;
23180 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23181 			U16_TO_BE16(u1, tcph->th_sum);
23182 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23183 		}
23184 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23185 		    (seq + data_length) == tcp->tcp_fss) {
23186 			if (!tcp->tcp_fin_acked) {
23187 				flags |= TH_FIN;
23188 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23189 			}
23190 			if (!tcp->tcp_fin_sent) {
23191 				tcp->tcp_fin_sent = B_TRUE;
23192 				switch (tcp->tcp_state) {
23193 				case TCPS_SYN_RCVD:
23194 				case TCPS_ESTABLISHED:
23195 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23196 					break;
23197 				case TCPS_CLOSE_WAIT:
23198 					tcp->tcp_state = TCPS_LAST_ACK;
23199 					break;
23200 				}
23201 				if (tcp->tcp_suna == tcp->tcp_snxt)
23202 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23203 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23204 			}
23205 		}
23206 		/*
23207 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23208 		 * is smaller than seq, u1 will become a very huge value.
23209 		 * So the comparison will fail.  Also note that tcp_urp
23210 		 * should be positive, see RFC 793 page 17.
23211 		 */
23212 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23213 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23214 		    u1 < (uint32_t)(64 * 1024)) {
23215 			flags |= TH_URG;
23216 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23217 			U32_TO_ABE16(u1, tcph->th_urp);
23218 		}
23219 	}
23220 	tcph->th_flags[0] = (uchar_t)flags;
23221 	tcp->tcp_rack = tcp->tcp_rnxt;
23222 	tcp->tcp_rack_cnt = 0;
23223 
23224 	if (tcp->tcp_snd_ts_ok) {
23225 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23226 			uint32_t llbolt = (uint32_t)lbolt;
23227 
23228 			U32_TO_BE32(llbolt,
23229 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23230 			U32_TO_BE32(tcp->tcp_ts_recent,
23231 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23232 		}
23233 	}
23234 
23235 	if (num_sack_blk > 0) {
23236 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23237 		sack_blk_t *tmp;
23238 		int32_t	i;
23239 
23240 		wptr[0] = TCPOPT_NOP;
23241 		wptr[1] = TCPOPT_NOP;
23242 		wptr[2] = TCPOPT_SACK;
23243 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23244 		    sizeof (sack_blk_t);
23245 		wptr += TCPOPT_REAL_SACK_LEN;
23246 
23247 		tmp = tcp->tcp_sack_list;
23248 		for (i = 0; i < num_sack_blk; i++) {
23249 			U32_TO_BE32(tmp[i].begin, wptr);
23250 			wptr += sizeof (tcp_seq);
23251 			U32_TO_BE32(tmp[i].end, wptr);
23252 			wptr += sizeof (tcp_seq);
23253 		}
23254 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23255 	}
23256 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23257 	data_length += (int)(mp1->b_wptr - rptr);
23258 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23259 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23260 	} else {
23261 		ip6_t *ip6 = (ip6_t *)(rptr +
23262 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23263 		    sizeof (ip6i_t) : 0));
23264 
23265 		ip6->ip6_plen = htons(data_length -
23266 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23267 	}
23268 
23269 	/*
23270 	 * Prime pump for IP
23271 	 * Include the adjustment for a source route if any.
23272 	 */
23273 	data_length -= tcp->tcp_ip_hdr_len;
23274 	data_length += tcp->tcp_sum;
23275 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23276 	U16_TO_ABE16(data_length, tcph->th_sum);
23277 	if (tcp->tcp_ip_forward_progress) {
23278 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23279 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23280 		tcp->tcp_ip_forward_progress = B_FALSE;
23281 	}
23282 	return (mp1);
23283 }
23284 
23285 /* This function handles the push timeout. */
23286 void
23287 tcp_push_timer(void *arg)
23288 {
23289 	conn_t	*connp = (conn_t *)arg;
23290 	tcp_t *tcp = connp->conn_tcp;
23291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23292 
23293 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23294 
23295 	ASSERT(tcp->tcp_listener == NULL);
23296 
23297 	/*
23298 	 * We need to plug synchronous streams during our drain to prevent
23299 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23300 	 */
23301 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23302 	tcp->tcp_push_tid = 0;
23303 	if ((tcp->tcp_rcv_list != NULL) &&
23304 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
23305 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23306 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23307 }
23308 
23309 /*
23310  * This function handles delayed ACK timeout.
23311  */
23312 static void
23313 tcp_ack_timer(void *arg)
23314 {
23315 	conn_t	*connp = (conn_t *)arg;
23316 	tcp_t *tcp = connp->conn_tcp;
23317 	mblk_t *mp;
23318 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23319 
23320 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23321 
23322 	tcp->tcp_ack_tid = 0;
23323 
23324 	if (tcp->tcp_fused)
23325 		return;
23326 
23327 	/*
23328 	 * Do not send ACK if there is no outstanding unack'ed data.
23329 	 */
23330 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23331 		return;
23332 	}
23333 
23334 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23335 		/*
23336 		 * Make sure we don't allow deferred ACKs to result in
23337 		 * timer-based ACKing.  If we have held off an ACK
23338 		 * when there was more than an mss here, and the timer
23339 		 * goes off, we have to worry about the possibility
23340 		 * that the sender isn't doing slow-start, or is out
23341 		 * of step with us for some other reason.  We fall
23342 		 * permanently back in the direction of
23343 		 * ACK-every-other-packet as suggested in RFC 1122.
23344 		 */
23345 		if (tcp->tcp_rack_abs_max > 2)
23346 			tcp->tcp_rack_abs_max--;
23347 		tcp->tcp_rack_cur_max = 2;
23348 	}
23349 	mp = tcp_ack_mp(tcp);
23350 
23351 	if (mp != NULL) {
23352 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
23353 		BUMP_LOCAL(tcp->tcp_obsegs);
23354 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23355 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23356 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23357 	}
23358 }
23359 
23360 
23361 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23362 static mblk_t *
23363 tcp_ack_mp(tcp_t *tcp)
23364 {
23365 	uint32_t	seq_no;
23366 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23367 
23368 	/*
23369 	 * There are a few cases to be considered while setting the sequence no.
23370 	 * Essentially, we can come here while processing an unacceptable pkt
23371 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23372 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23373 	 * If we are here for a zero window probe, stick with suna. In all
23374 	 * other cases, we check if suna + swnd encompasses snxt and set
23375 	 * the sequence number to snxt, if so. If snxt falls outside the
23376 	 * window (the receiver probably shrunk its window), we will go with
23377 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23378 	 * receiver.
23379 	 */
23380 	if (tcp->tcp_zero_win_probe) {
23381 		seq_no = tcp->tcp_suna;
23382 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23383 		ASSERT(tcp->tcp_swnd == 0);
23384 		seq_no = tcp->tcp_snxt;
23385 	} else {
23386 		seq_no = SEQ_GT(tcp->tcp_snxt,
23387 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23388 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23389 	}
23390 
23391 	if (tcp->tcp_valid_bits) {
23392 		/*
23393 		 * For the complex case where we have to send some
23394 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23395 		 */
23396 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23397 		    NULL, B_FALSE));
23398 	} else {
23399 		/* Generate a simple ACK */
23400 		int	data_length;
23401 		uchar_t	*rptr;
23402 		tcph_t	*tcph;
23403 		mblk_t	*mp1;
23404 		int32_t	tcp_hdr_len;
23405 		int32_t	tcp_tcp_hdr_len;
23406 		int32_t	num_sack_blk = 0;
23407 		int32_t sack_opt_len;
23408 
23409 		/*
23410 		 * Allocate space for TCP + IP headers
23411 		 * and link-level header
23412 		 */
23413 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23414 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23415 			    tcp->tcp_num_sack_blk);
23416 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23417 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23418 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23419 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23420 		} else {
23421 			tcp_hdr_len = tcp->tcp_hdr_len;
23422 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23423 		}
23424 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23425 		if (!mp1)
23426 			return (NULL);
23427 
23428 		/* Update the latest receive window size in TCP header. */
23429 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23430 		    tcp->tcp_tcph->th_win);
23431 		/* copy in prototype TCP + IP header */
23432 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23433 		mp1->b_rptr = rptr;
23434 		mp1->b_wptr = rptr + tcp_hdr_len;
23435 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23436 
23437 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23438 
23439 		/* Set the TCP sequence number. */
23440 		U32_TO_ABE32(seq_no, tcph->th_seq);
23441 
23442 		/* Set up the TCP flag field. */
23443 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23444 		if (tcp->tcp_ecn_echo_on)
23445 			tcph->th_flags[0] |= TH_ECE;
23446 
23447 		tcp->tcp_rack = tcp->tcp_rnxt;
23448 		tcp->tcp_rack_cnt = 0;
23449 
23450 		/* fill in timestamp option if in use */
23451 		if (tcp->tcp_snd_ts_ok) {
23452 			uint32_t llbolt = (uint32_t)lbolt;
23453 
23454 			U32_TO_BE32(llbolt,
23455 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23456 			U32_TO_BE32(tcp->tcp_ts_recent,
23457 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23458 		}
23459 
23460 		/* Fill in SACK options */
23461 		if (num_sack_blk > 0) {
23462 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23463 			sack_blk_t *tmp;
23464 			int32_t	i;
23465 
23466 			wptr[0] = TCPOPT_NOP;
23467 			wptr[1] = TCPOPT_NOP;
23468 			wptr[2] = TCPOPT_SACK;
23469 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23470 			    sizeof (sack_blk_t);
23471 			wptr += TCPOPT_REAL_SACK_LEN;
23472 
23473 			tmp = tcp->tcp_sack_list;
23474 			for (i = 0; i < num_sack_blk; i++) {
23475 				U32_TO_BE32(tmp[i].begin, wptr);
23476 				wptr += sizeof (tcp_seq);
23477 				U32_TO_BE32(tmp[i].end, wptr);
23478 				wptr += sizeof (tcp_seq);
23479 			}
23480 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23481 			    << 4);
23482 		}
23483 
23484 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23485 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23486 		} else {
23487 			/* Check for ip6i_t header in sticky hdrs */
23488 			ip6_t *ip6 = (ip6_t *)(rptr +
23489 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23490 			    sizeof (ip6i_t) : 0));
23491 
23492 			ip6->ip6_plen = htons(tcp_hdr_len -
23493 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23494 		}
23495 
23496 		/*
23497 		 * Prime pump for checksum calculation in IP.  Include the
23498 		 * adjustment for a source route if any.
23499 		 */
23500 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23501 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23502 		U16_TO_ABE16(data_length, tcph->th_sum);
23503 
23504 		if (tcp->tcp_ip_forward_progress) {
23505 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23506 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23507 			tcp->tcp_ip_forward_progress = B_FALSE;
23508 		}
23509 		return (mp1);
23510 	}
23511 }
23512 
23513 /*
23514  * To create a temporary tcp structure for inserting into bind hash list.
23515  * The parameter is assumed to be in network byte order, ready for use.
23516  */
23517 /* ARGSUSED */
23518 static tcp_t *
23519 tcp_alloc_temp_tcp(in_port_t port, tcp_stack_t *tcps)
23520 {
23521 	conn_t	*connp;
23522 	tcp_t	*tcp;
23523 
23524 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP, tcps->tcps_netstack);
23525 	if (connp == NULL)
23526 		return (NULL);
23527 
23528 	tcp = connp->conn_tcp;
23529 	tcp->tcp_tcps = tcps;
23530 	TCPS_REFHOLD(tcps);
23531 
23532 	/*
23533 	 * Only initialize the necessary info in those structures.  Note
23534 	 * that since INADDR_ANY is all 0, we do not need to set
23535 	 * tcp_bound_source to INADDR_ANY here.
23536 	 */
23537 	tcp->tcp_state = TCPS_BOUND;
23538 	tcp->tcp_lport = port;
23539 	tcp->tcp_exclbind = 1;
23540 	tcp->tcp_reserved_port = 1;
23541 
23542 	/* Just for place holding... */
23543 	tcp->tcp_ipversion = IPV4_VERSION;
23544 
23545 	return (tcp);
23546 }
23547 
23548 /*
23549  * To remove a port range specified by lo_port and hi_port from the
23550  * reserved port ranges.  This is one of the three public functions of
23551  * the reserved port interface.  Note that a port range has to be removed
23552  * as a whole.  Ports in a range cannot be removed individually.
23553  *
23554  * Params:
23555  *	in_port_t lo_port: the beginning port of the reserved port range to
23556  *		be deleted.
23557  *	in_port_t hi_port: the ending port of the reserved port range to
23558  *		be deleted.
23559  *
23560  * Return:
23561  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
23562  *
23563  * Assumes that nca is only for zoneid=0
23564  */
23565 boolean_t
23566 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
23567 {
23568 	int	i, j;
23569 	int	size;
23570 	tcp_t	**temp_tcp_array;
23571 	tcp_t	*tcp;
23572 	tcp_stack_t	*tcps;
23573 
23574 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23575 	ASSERT(tcps != NULL);
23576 
23577 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23578 
23579 	/* First make sure that the port ranage is indeed reserved. */
23580 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23581 		if (tcps->tcps_reserved_port[i].lo_port == lo_port) {
23582 			hi_port = tcps->tcps_reserved_port[i].hi_port;
23583 			temp_tcp_array =
23584 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23585 			break;
23586 		}
23587 	}
23588 	if (i == tcps->tcps_reserved_port_array_size) {
23589 		rw_exit(&tcps->tcps_reserved_port_lock);
23590 		netstack_rele(tcps->tcps_netstack);
23591 		return (B_FALSE);
23592 	}
23593 
23594 	/*
23595 	 * Remove the range from the array.  This simple loop is possible
23596 	 * because port ranges are inserted in ascending order.
23597 	 */
23598 	for (j = i; j < tcps->tcps_reserved_port_array_size - 1; j++) {
23599 		tcps->tcps_reserved_port[j].lo_port =
23600 		    tcps->tcps_reserved_port[j+1].lo_port;
23601 		tcps->tcps_reserved_port[j].hi_port =
23602 		    tcps->tcps_reserved_port[j+1].hi_port;
23603 		tcps->tcps_reserved_port[j].temp_tcp_array =
23604 		    tcps->tcps_reserved_port[j+1].temp_tcp_array;
23605 	}
23606 
23607 	/* Remove all the temporary tcp structures. */
23608 	size = hi_port - lo_port + 1;
23609 	while (size > 0) {
23610 		tcp = temp_tcp_array[size - 1];
23611 		ASSERT(tcp != NULL);
23612 		tcp_bind_hash_remove(tcp);
23613 		CONN_DEC_REF(tcp->tcp_connp);
23614 		size--;
23615 	}
23616 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
23617 	tcps->tcps_reserved_port_array_size--;
23618 	rw_exit(&tcps->tcps_reserved_port_lock);
23619 	netstack_rele(tcps->tcps_netstack);
23620 	return (B_TRUE);
23621 }
23622 
23623 /*
23624  * Macro to remove temporary tcp structure from the bind hash list.  The
23625  * first parameter is the list of tcp to be removed.  The second parameter
23626  * is the number of tcps in the array.
23627  */
23628 #define	TCP_TMP_TCP_REMOVE(tcp_array, num, tcps) \
23629 { \
23630 	while ((num) > 0) { \
23631 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
23632 		tf_t *tbf; \
23633 		tcp_t *tcpnext; \
23634 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
23635 		mutex_enter(&tbf->tf_lock); \
23636 		tcpnext = tcp->tcp_bind_hash; \
23637 		if (tcpnext) { \
23638 			tcpnext->tcp_ptpbhn = \
23639 				tcp->tcp_ptpbhn; \
23640 		} \
23641 		*tcp->tcp_ptpbhn = tcpnext; \
23642 		mutex_exit(&tbf->tf_lock); \
23643 		kmem_free(tcp, sizeof (tcp_t)); \
23644 		(tcp_array)[(num) - 1] = NULL; \
23645 		(num)--; \
23646 	} \
23647 }
23648 
23649 /*
23650  * The public interface for other modules to call to reserve a port range
23651  * in TCP.  The caller passes in how large a port range it wants.  TCP
23652  * will try to find a range and return it via lo_port and hi_port.  This is
23653  * used by NCA's nca_conn_init.
23654  * NCA can only be used in the global zone so this only affects the global
23655  * zone's ports.
23656  *
23657  * Params:
23658  *	int size: the size of the port range to be reserved.
23659  *	in_port_t *lo_port (referenced): returns the beginning port of the
23660  *		reserved port range added.
23661  *	in_port_t *hi_port (referenced): returns the ending port of the
23662  *		reserved port range added.
23663  *
23664  * Return:
23665  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
23666  *
23667  * Assumes that nca is only for zoneid=0
23668  */
23669 boolean_t
23670 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
23671 {
23672 	tcp_t		*tcp;
23673 	tcp_t		*tmp_tcp;
23674 	tcp_t		**temp_tcp_array;
23675 	tf_t		*tbf;
23676 	in_port_t	net_port;
23677 	in_port_t	port;
23678 	int32_t		cur_size;
23679 	int		i, j;
23680 	boolean_t	used;
23681 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
23682 	zoneid_t	zoneid = GLOBAL_ZONEID;
23683 	tcp_stack_t	*tcps;
23684 
23685 	/* Sanity check. */
23686 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
23687 		return (B_FALSE);
23688 	}
23689 
23690 	tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_tcp;
23691 	ASSERT(tcps != NULL);
23692 
23693 	rw_enter(&tcps->tcps_reserved_port_lock, RW_WRITER);
23694 	if (tcps->tcps_reserved_port_array_size ==
23695 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
23696 		rw_exit(&tcps->tcps_reserved_port_lock);
23697 		netstack_rele(tcps->tcps_netstack);
23698 		return (B_FALSE);
23699 	}
23700 
23701 	/*
23702 	 * Find the starting port to try.  Since the port ranges are ordered
23703 	 * in the reserved port array, we can do a simple search here.
23704 	 */
23705 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
23706 	*hi_port = TCP_LARGEST_RESERVED_PORT;
23707 	for (i = 0; i < tcps->tcps_reserved_port_array_size;
23708 	    *lo_port = tcps->tcps_reserved_port[i].hi_port + 1, i++) {
23709 		if (tcps->tcps_reserved_port[i].lo_port - *lo_port >= size) {
23710 			*hi_port = tcps->tcps_reserved_port[i].lo_port - 1;
23711 			break;
23712 		}
23713 	}
23714 	/* No available port range. */
23715 	if (i == tcps->tcps_reserved_port_array_size &&
23716 	    *hi_port - *lo_port < size) {
23717 		rw_exit(&tcps->tcps_reserved_port_lock);
23718 		netstack_rele(tcps->tcps_netstack);
23719 		return (B_FALSE);
23720 	}
23721 
23722 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
23723 	if (temp_tcp_array == NULL) {
23724 		rw_exit(&tcps->tcps_reserved_port_lock);
23725 		netstack_rele(tcps->tcps_netstack);
23726 		return (B_FALSE);
23727 	}
23728 
23729 	/* Go thru the port range to see if some ports are already bound. */
23730 	for (port = *lo_port, cur_size = 0;
23731 	    cur_size < size && port <= *hi_port;
23732 	    cur_size++, port++) {
23733 		used = B_FALSE;
23734 		net_port = htons(port);
23735 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(net_port)];
23736 		mutex_enter(&tbf->tf_lock);
23737 		for (tcp = tbf->tf_tcp; tcp != NULL;
23738 		    tcp = tcp->tcp_bind_hash) {
23739 			if (IPCL_ZONE_MATCH(tcp->tcp_connp, zoneid) &&
23740 			    net_port == tcp->tcp_lport) {
23741 				/*
23742 				 * A port is already bound.  Search again
23743 				 * starting from port + 1.  Release all
23744 				 * temporary tcps.
23745 				 */
23746 				mutex_exit(&tbf->tf_lock);
23747 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23748 				    tcps);
23749 				*lo_port = port + 1;
23750 				cur_size = -1;
23751 				used = B_TRUE;
23752 				break;
23753 			}
23754 		}
23755 		if (!used) {
23756 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port, tcps)) ==
23757 			    NULL) {
23758 				/*
23759 				 * Allocation failure.  Just fail the request.
23760 				 * Need to remove all those temporary tcp
23761 				 * structures.
23762 				 */
23763 				mutex_exit(&tbf->tf_lock);
23764 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size,
23765 				    tcps);
23766 				rw_exit(&tcps->tcps_reserved_port_lock);
23767 				kmem_free(temp_tcp_array,
23768 				    (hi_port - lo_port + 1) *
23769 				    sizeof (tcp_t *));
23770 				netstack_rele(tcps->tcps_netstack);
23771 				return (B_FALSE);
23772 			}
23773 			temp_tcp_array[cur_size] = tmp_tcp;
23774 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
23775 			mutex_exit(&tbf->tf_lock);
23776 		}
23777 	}
23778 
23779 	/*
23780 	 * The current range is not large enough.  We can actually do another
23781 	 * search if this search is done between 2 reserved port ranges.  But
23782 	 * for first release, we just stop here and return saying that no port
23783 	 * range is available.
23784 	 */
23785 	if (cur_size < size) {
23786 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size, tcps);
23787 		rw_exit(&tcps->tcps_reserved_port_lock);
23788 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23789 		netstack_rele(tcps->tcps_netstack);
23790 		return (B_FALSE);
23791 	}
23792 	*hi_port = port - 1;
23793 
23794 	/*
23795 	 * Insert range into array in ascending order.  Since this function
23796 	 * must not be called often, we choose to use the simplest method.
23797 	 * The above array should not consume excessive stack space as
23798 	 * the size must be very small.  If in future releases, we find
23799 	 * that we should provide more reserved port ranges, this function
23800 	 * has to be modified to be more efficient.
23801 	 */
23802 	if (tcps->tcps_reserved_port_array_size == 0) {
23803 		tcps->tcps_reserved_port[0].lo_port = *lo_port;
23804 		tcps->tcps_reserved_port[0].hi_port = *hi_port;
23805 		tcps->tcps_reserved_port[0].temp_tcp_array = temp_tcp_array;
23806 	} else {
23807 		for (i = 0, j = 0; i < tcps->tcps_reserved_port_array_size;
23808 		    i++, j++) {
23809 			if (*lo_port < tcps->tcps_reserved_port[i].lo_port &&
23810 			    i == j) {
23811 				tmp_ports[j].lo_port = *lo_port;
23812 				tmp_ports[j].hi_port = *hi_port;
23813 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23814 				j++;
23815 			}
23816 			tmp_ports[j].lo_port =
23817 			    tcps->tcps_reserved_port[i].lo_port;
23818 			tmp_ports[j].hi_port =
23819 			    tcps->tcps_reserved_port[i].hi_port;
23820 			tmp_ports[j].temp_tcp_array =
23821 			    tcps->tcps_reserved_port[i].temp_tcp_array;
23822 		}
23823 		if (j == i) {
23824 			tmp_ports[j].lo_port = *lo_port;
23825 			tmp_ports[j].hi_port = *hi_port;
23826 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23827 		}
23828 		bcopy(tmp_ports, tcps->tcps_reserved_port, sizeof (tmp_ports));
23829 	}
23830 	tcps->tcps_reserved_port_array_size++;
23831 	rw_exit(&tcps->tcps_reserved_port_lock);
23832 	netstack_rele(tcps->tcps_netstack);
23833 	return (B_TRUE);
23834 }
23835 
23836 /*
23837  * Check to see if a port is in any reserved port range.
23838  *
23839  * Params:
23840  *	in_port_t port: the port to be verified.
23841  *
23842  * Return:
23843  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23844  */
23845 boolean_t
23846 tcp_reserved_port_check(in_port_t port, tcp_stack_t *tcps)
23847 {
23848 	int i;
23849 
23850 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23851 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23852 		if (port >= tcps->tcps_reserved_port[i].lo_port ||
23853 		    port <= tcps->tcps_reserved_port[i].hi_port) {
23854 			rw_exit(&tcps->tcps_reserved_port_lock);
23855 			return (B_TRUE);
23856 		}
23857 	}
23858 	rw_exit(&tcps->tcps_reserved_port_lock);
23859 	return (B_FALSE);
23860 }
23861 
23862 /*
23863  * To list all reserved port ranges.  This is the function to handle
23864  * ndd tcp_reserved_port_list.
23865  */
23866 /* ARGSUSED */
23867 static int
23868 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23869 {
23870 	int i;
23871 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
23872 
23873 	rw_enter(&tcps->tcps_reserved_port_lock, RW_READER);
23874 	if (tcps->tcps_reserved_port_array_size > 0)
23875 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23876 	else
23877 		(void) mi_mpprintf(mp, "No port is reserved.");
23878 	for (i = 0; i < tcps->tcps_reserved_port_array_size; i++) {
23879 		(void) mi_mpprintf(mp, "%d-%d",
23880 		    tcps->tcps_reserved_port[i].lo_port,
23881 		    tcps->tcps_reserved_port[i].hi_port);
23882 	}
23883 	rw_exit(&tcps->tcps_reserved_port_lock);
23884 	return (0);
23885 }
23886 
23887 /*
23888  * Hash list insertion routine for tcp_t structures.
23889  * Inserts entries with the ones bound to a specific IP address first
23890  * followed by those bound to INADDR_ANY.
23891  */
23892 static void
23893 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23894 {
23895 	tcp_t	**tcpp;
23896 	tcp_t	*tcpnext;
23897 
23898 	if (tcp->tcp_ptpbhn != NULL) {
23899 		ASSERT(!caller_holds_lock);
23900 		tcp_bind_hash_remove(tcp);
23901 	}
23902 	tcpp = &tbf->tf_tcp;
23903 	if (!caller_holds_lock) {
23904 		mutex_enter(&tbf->tf_lock);
23905 	} else {
23906 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23907 	}
23908 	tcpnext = tcpp[0];
23909 	if (tcpnext) {
23910 		/*
23911 		 * If the new tcp bound to the INADDR_ANY address
23912 		 * and the first one in the list is not bound to
23913 		 * INADDR_ANY we skip all entries until we find the
23914 		 * first one bound to INADDR_ANY.
23915 		 * This makes sure that applications binding to a
23916 		 * specific address get preference over those binding to
23917 		 * INADDR_ANY.
23918 		 */
23919 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23920 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23921 			while ((tcpnext = tcpp[0]) != NULL &&
23922 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23923 				tcpp = &(tcpnext->tcp_bind_hash);
23924 			if (tcpnext)
23925 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23926 		} else
23927 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23928 	}
23929 	tcp->tcp_bind_hash = tcpnext;
23930 	tcp->tcp_ptpbhn = tcpp;
23931 	tcpp[0] = tcp;
23932 	if (!caller_holds_lock)
23933 		mutex_exit(&tbf->tf_lock);
23934 }
23935 
23936 /*
23937  * Hash list removal routine for tcp_t structures.
23938  */
23939 static void
23940 tcp_bind_hash_remove(tcp_t *tcp)
23941 {
23942 	tcp_t	*tcpnext;
23943 	kmutex_t *lockp;
23944 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23945 
23946 	if (tcp->tcp_ptpbhn == NULL)
23947 		return;
23948 
23949 	/*
23950 	 * Extract the lock pointer in case there are concurrent
23951 	 * hash_remove's for this instance.
23952 	 */
23953 	ASSERT(tcp->tcp_lport != 0);
23954 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23955 
23956 	ASSERT(lockp != NULL);
23957 	mutex_enter(lockp);
23958 	if (tcp->tcp_ptpbhn) {
23959 		tcpnext = tcp->tcp_bind_hash;
23960 		if (tcpnext) {
23961 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23962 			tcp->tcp_bind_hash = NULL;
23963 		}
23964 		*tcp->tcp_ptpbhn = tcpnext;
23965 		tcp->tcp_ptpbhn = NULL;
23966 	}
23967 	mutex_exit(lockp);
23968 }
23969 
23970 
23971 /*
23972  * Hash list lookup routine for tcp_t structures.
23973  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23974  */
23975 static tcp_t *
23976 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
23977 {
23978 	tf_t	*tf;
23979 	tcp_t	*tcp;
23980 
23981 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23982 	mutex_enter(&tf->tf_lock);
23983 	for (tcp = tf->tf_tcp; tcp != NULL;
23984 	    tcp = tcp->tcp_acceptor_hash) {
23985 		if (tcp->tcp_acceptor_id == id) {
23986 			CONN_INC_REF(tcp->tcp_connp);
23987 			mutex_exit(&tf->tf_lock);
23988 			return (tcp);
23989 		}
23990 	}
23991 	mutex_exit(&tf->tf_lock);
23992 	return (NULL);
23993 }
23994 
23995 
23996 /*
23997  * Hash list insertion routine for tcp_t structures.
23998  */
23999 void
24000 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24001 {
24002 	tf_t	*tf;
24003 	tcp_t	**tcpp;
24004 	tcp_t	*tcpnext;
24005 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24006 
24007 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24008 
24009 	if (tcp->tcp_ptpahn != NULL)
24010 		tcp_acceptor_hash_remove(tcp);
24011 	tcpp = &tf->tf_tcp;
24012 	mutex_enter(&tf->tf_lock);
24013 	tcpnext = tcpp[0];
24014 	if (tcpnext)
24015 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24016 	tcp->tcp_acceptor_hash = tcpnext;
24017 	tcp->tcp_ptpahn = tcpp;
24018 	tcpp[0] = tcp;
24019 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24020 	mutex_exit(&tf->tf_lock);
24021 }
24022 
24023 /*
24024  * Hash list removal routine for tcp_t structures.
24025  */
24026 static void
24027 tcp_acceptor_hash_remove(tcp_t *tcp)
24028 {
24029 	tcp_t	*tcpnext;
24030 	kmutex_t *lockp;
24031 
24032 	/*
24033 	 * Extract the lock pointer in case there are concurrent
24034 	 * hash_remove's for this instance.
24035 	 */
24036 	lockp = tcp->tcp_acceptor_lockp;
24037 
24038 	if (tcp->tcp_ptpahn == NULL)
24039 		return;
24040 
24041 	ASSERT(lockp != NULL);
24042 	mutex_enter(lockp);
24043 	if (tcp->tcp_ptpahn) {
24044 		tcpnext = tcp->tcp_acceptor_hash;
24045 		if (tcpnext) {
24046 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24047 			tcp->tcp_acceptor_hash = NULL;
24048 		}
24049 		*tcp->tcp_ptpahn = tcpnext;
24050 		tcp->tcp_ptpahn = NULL;
24051 	}
24052 	mutex_exit(lockp);
24053 	tcp->tcp_acceptor_lockp = NULL;
24054 }
24055 
24056 /* ARGSUSED */
24057 static int
24058 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
24059 {
24060 	int error = 0;
24061 	int retval;
24062 	char *end;
24063 	tcp_hsp_t *hsp;
24064 	tcp_hsp_t *hspprev;
24065 	ipaddr_t addr = 0;		/* Address we're looking for */
24066 	in6_addr_t v6addr;		/* Address we're looking for */
24067 	uint32_t hash;			/* Hash of that address */
24068 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24069 
24070 	/*
24071 	 * If the following variables are still zero after parsing the input
24072 	 * string, the user didn't specify them and we don't change them in
24073 	 * the HSP.
24074 	 */
24075 
24076 	ipaddr_t mask = 0;		/* Subnet mask */
24077 	in6_addr_t v6mask;
24078 	long sendspace = 0;		/* Send buffer size */
24079 	long recvspace = 0;		/* Receive buffer size */
24080 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
24081 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
24082 
24083 	rw_enter(&tcps->tcps_hsp_lock, RW_WRITER);
24084 
24085 	/* Parse and validate address */
24086 	if (af == AF_INET) {
24087 		retval = inet_pton(af, value, &addr);
24088 		if (retval == 1)
24089 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
24090 	} else if (af == AF_INET6) {
24091 		retval = inet_pton(af, value, &v6addr);
24092 	} else {
24093 		error = EINVAL;
24094 		goto done;
24095 	}
24096 	if (retval == 0) {
24097 		error = EINVAL;
24098 		goto done;
24099 	}
24100 
24101 	while ((*value) && *value != ' ')
24102 		value++;
24103 
24104 	/* Parse individual keywords, set variables if found */
24105 	while (*value) {
24106 		/* Skip leading blanks */
24107 
24108 		while (*value == ' ' || *value == '\t')
24109 			value++;
24110 
24111 		/* If at end of string, we're done */
24112 
24113 		if (!*value)
24114 			break;
24115 
24116 		/* We have a word, figure out what it is */
24117 
24118 		if (strncmp("mask", value, 4) == 0) {
24119 			value += 4;
24120 			while (*value == ' ' || *value == '\t')
24121 				value++;
24122 			/* Parse subnet mask */
24123 			if (af == AF_INET) {
24124 				retval = inet_pton(af, value, &mask);
24125 				if (retval == 1) {
24126 					V4MASK_TO_V6(mask, v6mask);
24127 				}
24128 			} else if (af == AF_INET6) {
24129 				retval = inet_pton(af, value, &v6mask);
24130 			}
24131 			if (retval != 1) {
24132 				error = EINVAL;
24133 				goto done;
24134 			}
24135 			while ((*value) && *value != ' ')
24136 				value++;
24137 		} else if (strncmp("sendspace", value, 9) == 0) {
24138 			value += 9;
24139 
24140 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
24141 			    sendspace < TCP_XMIT_HIWATER ||
24142 			    sendspace >= (1L<<30)) {
24143 				error = EINVAL;
24144 				goto done;
24145 			}
24146 			value = end;
24147 		} else if (strncmp("recvspace", value, 9) == 0) {
24148 			value += 9;
24149 
24150 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
24151 			    recvspace < TCP_RECV_HIWATER ||
24152 			    recvspace >= (1L<<30)) {
24153 				error = EINVAL;
24154 				goto done;
24155 			}
24156 			value = end;
24157 		} else if (strncmp("timestamp", value, 9) == 0) {
24158 			value += 9;
24159 
24160 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
24161 			    timestamp < 0 || timestamp > 1) {
24162 				error = EINVAL;
24163 				goto done;
24164 			}
24165 
24166 			/*
24167 			 * We increment timestamp so we know it's been set;
24168 			 * this is undone when we put it in the HSP
24169 			 */
24170 			timestamp++;
24171 			value = end;
24172 		} else if (strncmp("delete", value, 6) == 0) {
24173 			value += 6;
24174 			delete = B_TRUE;
24175 		} else {
24176 			error = EINVAL;
24177 			goto done;
24178 		}
24179 	}
24180 
24181 	/* Hash address for lookup */
24182 
24183 	hash = TCP_HSP_HASH(addr);
24184 
24185 	if (delete) {
24186 		/*
24187 		 * Note that deletes don't return an error if the thing
24188 		 * we're trying to delete isn't there.
24189 		 */
24190 		if (tcps->tcps_hsp_hash == NULL)
24191 			goto done;
24192 		hsp = tcps->tcps_hsp_hash[hash];
24193 
24194 		if (hsp) {
24195 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24196 			    &v6addr)) {
24197 				tcps->tcps_hsp_hash[hash] = hsp->tcp_hsp_next;
24198 				mi_free((char *)hsp);
24199 			} else {
24200 				hspprev = hsp;
24201 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
24202 					if (IN6_ARE_ADDR_EQUAL(
24203 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
24204 						hspprev->tcp_hsp_next =
24205 						    hsp->tcp_hsp_next;
24206 						mi_free((char *)hsp);
24207 						break;
24208 					}
24209 					hspprev = hsp;
24210 				}
24211 			}
24212 		}
24213 	} else {
24214 		/*
24215 		 * We're adding/modifying an HSP.  If we haven't already done
24216 		 * so, allocate the hash table.
24217 		 */
24218 
24219 		if (!tcps->tcps_hsp_hash) {
24220 			tcps->tcps_hsp_hash = (tcp_hsp_t **)
24221 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
24222 			if (!tcps->tcps_hsp_hash) {
24223 				error = EINVAL;
24224 				goto done;
24225 			}
24226 		}
24227 
24228 		/* Get head of hash chain */
24229 
24230 		hsp = tcps->tcps_hsp_hash[hash];
24231 
24232 		/* Try to find pre-existing hsp on hash chain */
24233 		/* Doesn't handle CIDR prefixes. */
24234 		while (hsp) {
24235 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
24236 				break;
24237 			hsp = hsp->tcp_hsp_next;
24238 		}
24239 
24240 		/*
24241 		 * If we didn't, create one with default values and put it
24242 		 * at head of hash chain
24243 		 */
24244 
24245 		if (!hsp) {
24246 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
24247 			if (!hsp) {
24248 				error = EINVAL;
24249 				goto done;
24250 			}
24251 			hsp->tcp_hsp_next = tcps->tcps_hsp_hash[hash];
24252 			tcps->tcps_hsp_hash[hash] = hsp;
24253 		}
24254 
24255 		/* Set values that the user asked us to change */
24256 
24257 		hsp->tcp_hsp_addr_v6 = v6addr;
24258 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
24259 			hsp->tcp_hsp_vers = IPV4_VERSION;
24260 		else
24261 			hsp->tcp_hsp_vers = IPV6_VERSION;
24262 		hsp->tcp_hsp_subnet_v6 = v6mask;
24263 		if (sendspace > 0)
24264 			hsp->tcp_hsp_sendspace = sendspace;
24265 		if (recvspace > 0)
24266 			hsp->tcp_hsp_recvspace = recvspace;
24267 		if (timestamp > 0)
24268 			hsp->tcp_hsp_tstamp = timestamp - 1;
24269 	}
24270 
24271 done:
24272 	rw_exit(&tcps->tcps_hsp_lock);
24273 	return (error);
24274 }
24275 
24276 /* Set callback routine passed to nd_load by tcp_param_register. */
24277 /* ARGSUSED */
24278 static int
24279 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
24280 {
24281 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
24282 }
24283 /* ARGSUSED */
24284 static int
24285 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24286     cred_t *cr)
24287 {
24288 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
24289 }
24290 
24291 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
24292 /* ARGSUSED */
24293 static int
24294 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
24295 {
24296 	tcp_hsp_t *hsp;
24297 	int i;
24298 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
24299 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24300 
24301 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24302 	(void) mi_mpprintf(mp,
24303 	    "Hash HSP     " MI_COL_HDRPAD_STR
24304 	    "Address         Subnet Mask     Send       Receive    TStamp");
24305 	if (tcps->tcps_hsp_hash) {
24306 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
24307 			hsp = tcps->tcps_hsp_hash[i];
24308 			while (hsp) {
24309 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
24310 					(void) inet_ntop(AF_INET,
24311 					    &hsp->tcp_hsp_addr,
24312 					    addrbuf, sizeof (addrbuf));
24313 					(void) inet_ntop(AF_INET,
24314 					    &hsp->tcp_hsp_subnet,
24315 					    subnetbuf, sizeof (subnetbuf));
24316 				} else {
24317 					(void) inet_ntop(AF_INET6,
24318 					    &hsp->tcp_hsp_addr_v6,
24319 					    addrbuf, sizeof (addrbuf));
24320 					(void) inet_ntop(AF_INET6,
24321 					    &hsp->tcp_hsp_subnet_v6,
24322 					    subnetbuf, sizeof (subnetbuf));
24323 				}
24324 				(void) mi_mpprintf(mp,
24325 				    " %03d " MI_COL_PTRFMT_STR
24326 				    "%s %s %010d %010d      %d",
24327 				    i,
24328 				    (void *)hsp,
24329 				    addrbuf,
24330 				    subnetbuf,
24331 				    hsp->tcp_hsp_sendspace,
24332 				    hsp->tcp_hsp_recvspace,
24333 				    hsp->tcp_hsp_tstamp);
24334 
24335 				hsp = hsp->tcp_hsp_next;
24336 			}
24337 		}
24338 	}
24339 	rw_exit(&tcps->tcps_hsp_lock);
24340 	return (0);
24341 }
24342 
24343 
24344 /* Data for fast netmask macro used by tcp_hsp_lookup */
24345 
24346 static ipaddr_t netmasks[] = {
24347 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24348 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24349 };
24350 
24351 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24352 
24353 /*
24354  * XXX This routine should go away and instead we should use the metrics
24355  * associated with the routes to determine the default sndspace and rcvspace.
24356  */
24357 static tcp_hsp_t *
24358 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24359 {
24360 	tcp_hsp_t *hsp = NULL;
24361 
24362 	/* Quick check without acquiring the lock. */
24363 	if (tcps->tcps_hsp_hash == NULL)
24364 		return (NULL);
24365 
24366 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24367 
24368 	/* This routine finds the best-matching HSP for address addr. */
24369 
24370 	if (tcps->tcps_hsp_hash) {
24371 		int i;
24372 		ipaddr_t srchaddr;
24373 		tcp_hsp_t *hsp_net;
24374 
24375 		/* We do three passes: host, network, and subnet. */
24376 
24377 		srchaddr = addr;
24378 
24379 		for (i = 1; i <= 3; i++) {
24380 			/* Look for exact match on srchaddr */
24381 
24382 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24383 			while (hsp) {
24384 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24385 				    hsp->tcp_hsp_addr == srchaddr)
24386 					break;
24387 				hsp = hsp->tcp_hsp_next;
24388 			}
24389 			ASSERT(hsp == NULL ||
24390 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24391 
24392 			/*
24393 			 * If this is the first pass:
24394 			 *   If we found a match, great, return it.
24395 			 *   If not, search for the network on the second pass.
24396 			 */
24397 
24398 			if (i == 1)
24399 				if (hsp)
24400 					break;
24401 				else
24402 				{
24403 					srchaddr = addr & netmask(addr);
24404 					continue;
24405 				}
24406 
24407 			/*
24408 			 * If this is the second pass:
24409 			 *   If we found a match, but there's a subnet mask,
24410 			 *    save the match but try again using the subnet
24411 			 *    mask on the third pass.
24412 			 *   Otherwise, return whatever we found.
24413 			 */
24414 
24415 			if (i == 2) {
24416 				if (hsp && hsp->tcp_hsp_subnet) {
24417 					hsp_net = hsp;
24418 					srchaddr = addr & hsp->tcp_hsp_subnet;
24419 					continue;
24420 				} else {
24421 					break;
24422 				}
24423 			}
24424 
24425 			/*
24426 			 * This must be the third pass.  If we didn't find
24427 			 * anything, return the saved network HSP instead.
24428 			 */
24429 
24430 			if (!hsp)
24431 				hsp = hsp_net;
24432 		}
24433 	}
24434 
24435 	rw_exit(&tcps->tcps_hsp_lock);
24436 	return (hsp);
24437 }
24438 
24439 /*
24440  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24441  * match lookup.
24442  */
24443 static tcp_hsp_t *
24444 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24445 {
24446 	tcp_hsp_t *hsp = NULL;
24447 
24448 	/* Quick check without acquiring the lock. */
24449 	if (tcps->tcps_hsp_hash == NULL)
24450 		return (NULL);
24451 
24452 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24453 
24454 	/* This routine finds the best-matching HSP for address addr. */
24455 
24456 	if (tcps->tcps_hsp_hash) {
24457 		int i;
24458 		in6_addr_t v6srchaddr;
24459 		tcp_hsp_t *hsp_net;
24460 
24461 		/* We do three passes: host, network, and subnet. */
24462 
24463 		v6srchaddr = *v6addr;
24464 
24465 		for (i = 1; i <= 3; i++) {
24466 			/* Look for exact match on srchaddr */
24467 
24468 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24469 			    V4_PART_OF_V6(v6srchaddr))];
24470 			while (hsp) {
24471 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24472 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24473 				    &v6srchaddr))
24474 					break;
24475 				hsp = hsp->tcp_hsp_next;
24476 			}
24477 
24478 			/*
24479 			 * If this is the first pass:
24480 			 *   If we found a match, great, return it.
24481 			 *   If not, search for the network on the second pass.
24482 			 */
24483 
24484 			if (i == 1)
24485 				if (hsp)
24486 					break;
24487 				else {
24488 					/* Assume a 64 bit mask */
24489 					v6srchaddr.s6_addr32[0] =
24490 					    v6addr->s6_addr32[0];
24491 					v6srchaddr.s6_addr32[1] =
24492 					    v6addr->s6_addr32[1];
24493 					v6srchaddr.s6_addr32[2] = 0;
24494 					v6srchaddr.s6_addr32[3] = 0;
24495 					continue;
24496 				}
24497 
24498 			/*
24499 			 * If this is the second pass:
24500 			 *   If we found a match, but there's a subnet mask,
24501 			 *    save the match but try again using the subnet
24502 			 *    mask on the third pass.
24503 			 *   Otherwise, return whatever we found.
24504 			 */
24505 
24506 			if (i == 2) {
24507 				ASSERT(hsp == NULL ||
24508 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24509 				if (hsp &&
24510 				    !IN6_IS_ADDR_UNSPECIFIED(
24511 				    &hsp->tcp_hsp_subnet_v6)) {
24512 					hsp_net = hsp;
24513 					V6_MASK_COPY(*v6addr,
24514 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24515 					continue;
24516 				} else {
24517 					break;
24518 				}
24519 			}
24520 
24521 			/*
24522 			 * This must be the third pass.  If we didn't find
24523 			 * anything, return the saved network HSP instead.
24524 			 */
24525 
24526 			if (!hsp)
24527 				hsp = hsp_net;
24528 		}
24529 	}
24530 
24531 	rw_exit(&tcps->tcps_hsp_lock);
24532 	return (hsp);
24533 }
24534 
24535 /*
24536  * Type three generator adapted from the random() function in 4.4 BSD:
24537  */
24538 
24539 /*
24540  * Copyright (c) 1983, 1993
24541  *	The Regents of the University of California.  All rights reserved.
24542  *
24543  * Redistribution and use in source and binary forms, with or without
24544  * modification, are permitted provided that the following conditions
24545  * are met:
24546  * 1. Redistributions of source code must retain the above copyright
24547  *    notice, this list of conditions and the following disclaimer.
24548  * 2. Redistributions in binary form must reproduce the above copyright
24549  *    notice, this list of conditions and the following disclaimer in the
24550  *    documentation and/or other materials provided with the distribution.
24551  * 3. All advertising materials mentioning features or use of this software
24552  *    must display the following acknowledgement:
24553  *	This product includes software developed by the University of
24554  *	California, Berkeley and its contributors.
24555  * 4. Neither the name of the University nor the names of its contributors
24556  *    may be used to endorse or promote products derived from this software
24557  *    without specific prior written permission.
24558  *
24559  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24560  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24561  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24562  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24563  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24564  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24565  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24566  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24567  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24568  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24569  * SUCH DAMAGE.
24570  */
24571 
24572 /* Type 3 -- x**31 + x**3 + 1 */
24573 #define	DEG_3		31
24574 #define	SEP_3		3
24575 
24576 
24577 /* Protected by tcp_random_lock */
24578 static int tcp_randtbl[DEG_3 + 1];
24579 
24580 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24581 static int *tcp_random_rptr = &tcp_randtbl[1];
24582 
24583 static int *tcp_random_state = &tcp_randtbl[1];
24584 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24585 
24586 kmutex_t tcp_random_lock;
24587 
24588 void
24589 tcp_random_init(void)
24590 {
24591 	int i;
24592 	hrtime_t hrt;
24593 	time_t wallclock;
24594 	uint64_t result;
24595 
24596 	/*
24597 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24598 	 * a longlong, which may contain resolution down to nanoseconds.
24599 	 * The current time will either be a 32-bit or a 64-bit quantity.
24600 	 * XOR the two together in a 64-bit result variable.
24601 	 * Convert the result to a 32-bit value by multiplying the high-order
24602 	 * 32-bits by the low-order 32-bits.
24603 	 */
24604 
24605 	hrt = gethrtime();
24606 	(void) drv_getparm(TIME, &wallclock);
24607 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24608 	mutex_enter(&tcp_random_lock);
24609 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24610 	    (result & 0xffffffff);
24611 
24612 	for (i = 1; i < DEG_3; i++)
24613 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24614 			+ 12345;
24615 	tcp_random_fptr = &tcp_random_state[SEP_3];
24616 	tcp_random_rptr = &tcp_random_state[0];
24617 	mutex_exit(&tcp_random_lock);
24618 	for (i = 0; i < 10 * DEG_3; i++)
24619 		(void) tcp_random();
24620 }
24621 
24622 /*
24623  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24624  * This range is selected to be approximately centered on TCP_ISS / 2,
24625  * and easy to compute. We get this value by generating a 32-bit random
24626  * number, selecting out the high-order 17 bits, and then adding one so
24627  * that we never return zero.
24628  */
24629 int
24630 tcp_random(void)
24631 {
24632 	int i;
24633 
24634 	mutex_enter(&tcp_random_lock);
24635 	*tcp_random_fptr += *tcp_random_rptr;
24636 
24637 	/*
24638 	 * The high-order bits are more random than the low-order bits,
24639 	 * so we select out the high-order 17 bits and add one so that
24640 	 * we never return zero.
24641 	 */
24642 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24643 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24644 		tcp_random_fptr = tcp_random_state;
24645 		++tcp_random_rptr;
24646 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24647 		tcp_random_rptr = tcp_random_state;
24648 
24649 	mutex_exit(&tcp_random_lock);
24650 	return (i);
24651 }
24652 
24653 /*
24654  * XXX This will go away when TPI is extended to send
24655  * info reqs to sockfs/timod .....
24656  * Given a queue, set the max packet size for the write
24657  * side of the queue below stream head.  This value is
24658  * cached on the stream head.
24659  * Returns 1 on success, 0 otherwise.
24660  */
24661 static int
24662 setmaxps(queue_t *q, int maxpsz)
24663 {
24664 	struct stdata	*stp;
24665 	queue_t		*wq;
24666 	stp = STREAM(q);
24667 
24668 	/*
24669 	 * At this point change of a queue parameter is not allowed
24670 	 * when a multiplexor is sitting on top.
24671 	 */
24672 	if (stp->sd_flag & STPLEX)
24673 		return (0);
24674 
24675 	claimstr(stp->sd_wrq);
24676 	wq = stp->sd_wrq->q_next;
24677 	ASSERT(wq != NULL);
24678 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24679 	releasestr(stp->sd_wrq);
24680 	return (1);
24681 }
24682 
24683 static int
24684 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24685     int *t_errorp, int *sys_errorp)
24686 {
24687 	int error;
24688 	int is_absreq_failure;
24689 	t_scalar_t *opt_lenp;
24690 	t_scalar_t opt_offset;
24691 	int prim_type;
24692 	struct T_conn_req *tcreqp;
24693 	struct T_conn_res *tcresp;
24694 	cred_t *cr;
24695 
24696 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24697 
24698 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24699 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24700 	    prim_type == T_CONN_RES);
24701 
24702 	switch (prim_type) {
24703 	case T_CONN_REQ:
24704 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24705 		opt_offset = tcreqp->OPT_offset;
24706 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24707 		break;
24708 	case O_T_CONN_RES:
24709 	case T_CONN_RES:
24710 		tcresp = (struct T_conn_res *)mp->b_rptr;
24711 		opt_offset = tcresp->OPT_offset;
24712 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24713 		break;
24714 	}
24715 
24716 	*t_errorp = 0;
24717 	*sys_errorp = 0;
24718 	*do_disconnectp = 0;
24719 
24720 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24721 	    opt_offset, cr, &tcp_opt_obj,
24722 	    NULL, &is_absreq_failure);
24723 
24724 	switch (error) {
24725 	case  0:		/* no error */
24726 		ASSERT(is_absreq_failure == 0);
24727 		return (0);
24728 	case ENOPROTOOPT:
24729 		*t_errorp = TBADOPT;
24730 		break;
24731 	case EACCES:
24732 		*t_errorp = TACCES;
24733 		break;
24734 	default:
24735 		*t_errorp = TSYSERR; *sys_errorp = error;
24736 		break;
24737 	}
24738 	if (is_absreq_failure != 0) {
24739 		/*
24740 		 * The connection request should get the local ack
24741 		 * T_OK_ACK and then a T_DISCON_IND.
24742 		 */
24743 		*do_disconnectp = 1;
24744 	}
24745 	return (-1);
24746 }
24747 
24748 /*
24749  * Split this function out so that if the secret changes, I'm okay.
24750  *
24751  * Initialize the tcp_iss_cookie and tcp_iss_key.
24752  */
24753 
24754 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24755 
24756 static void
24757 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24758 {
24759 	struct {
24760 		int32_t current_time;
24761 		uint32_t randnum;
24762 		uint16_t pad;
24763 		uint8_t ether[6];
24764 		uint8_t passwd[PASSWD_SIZE];
24765 	} tcp_iss_cookie;
24766 	time_t t;
24767 
24768 	/*
24769 	 * Start with the current absolute time.
24770 	 */
24771 	(void) drv_getparm(TIME, &t);
24772 	tcp_iss_cookie.current_time = t;
24773 
24774 	/*
24775 	 * XXX - Need a more random number per RFC 1750, not this crap.
24776 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24777 	 */
24778 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24779 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24780 
24781 	/*
24782 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24783 	 * as a good template.
24784 	 */
24785 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24786 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24787 
24788 	/*
24789 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24790 	 */
24791 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24792 
24793 	/*
24794 	 * See 4010593 if this section becomes a problem again,
24795 	 * but the local ethernet address is useful here.
24796 	 */
24797 	(void) localetheraddr(NULL,
24798 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24799 
24800 	/*
24801 	 * Hash 'em all together.  The MD5Final is called per-connection.
24802 	 */
24803 	mutex_enter(&tcps->tcps_iss_key_lock);
24804 	MD5Init(&tcps->tcps_iss_key);
24805 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24806 	    sizeof (tcp_iss_cookie));
24807 	mutex_exit(&tcps->tcps_iss_key_lock);
24808 }
24809 
24810 /*
24811  * Set the RFC 1948 pass phrase
24812  */
24813 /* ARGSUSED */
24814 static int
24815 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24816     cred_t *cr)
24817 {
24818 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24819 
24820 	/*
24821 	 * Basically, value contains a new pass phrase.  Pass it along!
24822 	 */
24823 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24824 	return (0);
24825 }
24826 
24827 /* ARGSUSED */
24828 static int
24829 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24830 {
24831 	bzero(buf, sizeof (tcp_sack_info_t));
24832 	return (0);
24833 }
24834 
24835 /* ARGSUSED */
24836 static int
24837 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24838 {
24839 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24840 	return (0);
24841 }
24842 
24843 /*
24844  * Make sure we wait until the default queue is setup, yet allow
24845  * tcp_g_q_create() to open a TCP stream.
24846  * We need to allow tcp_g_q_create() do do an open
24847  * of tcp, hence we compare curhread.
24848  * All others have to wait until the tcps_g_q has been
24849  * setup.
24850  */
24851 void
24852 tcp_g_q_setup(tcp_stack_t *tcps)
24853 {
24854 	mutex_enter(&tcps->tcps_g_q_lock);
24855 	if (tcps->tcps_g_q != NULL) {
24856 		mutex_exit(&tcps->tcps_g_q_lock);
24857 		return;
24858 	}
24859 	if (tcps->tcps_g_q_creator == NULL) {
24860 		/* This thread will set it up */
24861 		tcps->tcps_g_q_creator = curthread;
24862 		mutex_exit(&tcps->tcps_g_q_lock);
24863 		tcp_g_q_create(tcps);
24864 		mutex_enter(&tcps->tcps_g_q_lock);
24865 		ASSERT(tcps->tcps_g_q_creator == curthread);
24866 		tcps->tcps_g_q_creator = NULL;
24867 		cv_signal(&tcps->tcps_g_q_cv);
24868 		ASSERT(tcps->tcps_g_q != NULL);
24869 		mutex_exit(&tcps->tcps_g_q_lock);
24870 		return;
24871 	}
24872 	/* Everybody but the creator has to wait */
24873 	if (tcps->tcps_g_q_creator != curthread) {
24874 		while (tcps->tcps_g_q == NULL)
24875 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24876 	}
24877 	mutex_exit(&tcps->tcps_g_q_lock);
24878 }
24879 
24880 major_t IP_MAJ;
24881 #define	IP	"ip"
24882 
24883 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24884 
24885 /*
24886  * Create a default tcp queue here instead of in strplumb
24887  */
24888 void
24889 tcp_g_q_create(tcp_stack_t *tcps)
24890 {
24891 	int error;
24892 	ldi_handle_t	lh = NULL;
24893 	ldi_ident_t	li = NULL;
24894 	int		rval;
24895 	cred_t		*cr;
24896 
24897 #ifdef NS_DEBUG
24898 	(void) printf("tcp_g_q_create()\n");
24899 #endif
24900 
24901 	ASSERT(tcps->tcps_g_q_creator == curthread);
24902 
24903 	error = ldi_ident_from_major(IP_MAJ, &li);
24904 	if (error) {
24905 #ifdef DEBUG
24906 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24907 		    error);
24908 #endif
24909 		return;
24910 	}
24911 
24912 	cr = zone_get_kcred(netstackid_to_zoneid(
24913 				tcps->tcps_netstack->netstack_stackid));
24914 	ASSERT(cr != NULL);
24915 	/*
24916 	 * We set the tcp default queue to IPv6 because IPv4 falls
24917 	 * back to IPv6 when it can't find a client, but
24918 	 * IPv6 does not fall back to IPv4.
24919 	 */
24920 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24921 	if (error) {
24922 #ifdef DEBUG
24923 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24924 		    error);
24925 #endif
24926 		goto out;
24927 	}
24928 
24929 	/*
24930 	 * This ioctl causes the tcp framework to cache a pointer to
24931 	 * this stream, so we don't want to close the stream after
24932 	 * this operation.
24933 	 * Use the kernel credentials that are for the zone we're in.
24934 	 */
24935 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24936 	    (intptr_t)0, FKIOCTL, cr, &rval);
24937 	if (error) {
24938 #ifdef DEBUG
24939 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24940 		    "error %d\n", error);
24941 #endif
24942 		goto out;
24943 	}
24944 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24945 	lh = NULL;
24946 out:
24947 	/* Close layered handles */
24948 	if (li)
24949 		ldi_ident_release(li);
24950 	/* Keep cred around until _inactive needs it */
24951 	tcps->tcps_g_q_cr = cr;
24952 }
24953 
24954 /*
24955  * We keep tcp_g_q set until all other tcp_t's in the zone
24956  * has gone away, and then when tcp_g_q_inactive() is called
24957  * we clear it.
24958  */
24959 void
24960 tcp_g_q_destroy(tcp_stack_t *tcps)
24961 {
24962 #ifdef NS_DEBUG
24963 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24964 	    tcps->tcps_netstack->netstack_stackid);
24965 #endif
24966 
24967 	if (tcps->tcps_g_q == NULL) {
24968 		return;	/* Nothing to cleanup */
24969 	}
24970 	/*
24971 	 * Drop reference corresponding to the default queue.
24972 	 * This reference was added from tcp_open when the default queue
24973 	 * was created, hence we compensate for this extra drop in
24974 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24975 	 * the default queue was the last one to be open, in which
24976 	 * case, then tcp_g_q_inactive will be
24977 	 * called as a result of the refrele.
24978 	 */
24979 	TCPS_REFRELE(tcps);
24980 }
24981 
24982 /*
24983  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24984  * Run by tcp_q_q_inactive using a taskq.
24985  */
24986 static void
24987 tcp_g_q_close(void *arg)
24988 {
24989 	tcp_stack_t *tcps = arg;
24990 	int error;
24991 	ldi_handle_t	lh = NULL;
24992 	ldi_ident_t	li = NULL;
24993 	cred_t		*cr;
24994 
24995 #ifdef NS_DEBUG
24996 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24997 	    tcps->tcps_netstack->netstack_stackid,
24998 	    tcps->tcps_netstack->netstack_refcnt);
24999 #endif
25000 	lh = tcps->tcps_g_q_lh;
25001 	if (lh == NULL)
25002 		return;	/* Nothing to cleanup */
25003 
25004 	ASSERT(tcps->tcps_refcnt == 1);
25005 	ASSERT(tcps->tcps_g_q != NULL);
25006 
25007 	error = ldi_ident_from_major(IP_MAJ, &li);
25008 	if (error) {
25009 #ifdef DEBUG
25010 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
25011 		    error);
25012 #endif
25013 		return;
25014 	}
25015 
25016 	cr = tcps->tcps_g_q_cr;
25017 	tcps->tcps_g_q_cr = NULL;
25018 	ASSERT(cr != NULL);
25019 
25020 	/*
25021 	 * Make sure we can break the recursion when tcp_close decrements
25022 	 * the reference count causing g_q_inactive to be called again.
25023 	 */
25024 	tcps->tcps_g_q_lh = NULL;
25025 
25026 	/* close the default queue */
25027 	(void) ldi_close(lh, FREAD|FWRITE, cr);
25028 	/*
25029 	 * At this point in time tcps and the rest of netstack_t might
25030 	 * have been deleted.
25031 	 */
25032 	tcps = NULL;
25033 
25034 	/* Close layered handles */
25035 	ldi_ident_release(li);
25036 	crfree(cr);
25037 }
25038 
25039 /*
25040  * Called when last tcp_t drops reference count using TCPS_REFRELE.
25041  *
25042  * Have to ensure that the ldi routines are not used by an
25043  * interrupt thread by using a taskq.
25044  */
25045 void
25046 tcp_g_q_inactive(tcp_stack_t *tcps)
25047 {
25048 	if (tcps->tcps_g_q_lh == NULL)
25049 		return;	/* Nothing to cleanup */
25050 
25051 	ASSERT(tcps->tcps_refcnt == 0);
25052 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
25053 
25054 	if (servicing_interrupt()) {
25055 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
25056 			    (void *) tcps, TQ_SLEEP);
25057 	} else {
25058 		tcp_g_q_close(tcps);
25059 	}
25060 }
25061 
25062 /*
25063  * Called by IP when IP is loaded into the kernel
25064  */
25065 void
25066 tcp_ddi_g_init(void)
25067 {
25068 	IP_MAJ = ddi_name_to_major(IP);
25069 
25070 	tcp_timercache = kmem_cache_create("tcp_timercache",
25071 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
25072 	    NULL, NULL, NULL, NULL, NULL, 0);
25073 
25074 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
25075 	    sizeof (tcp_sack_info_t), 0,
25076 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
25077 
25078 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
25079 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
25080 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
25081 
25082 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
25083 
25084 	/* Initialize the random number generator */
25085 	tcp_random_init();
25086 
25087 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
25088 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
25089 
25090 	/* A single callback independently of how many netstacks we have */
25091 	ip_squeue_init(tcp_squeue_add);
25092 
25093 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
25094 
25095 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
25096 	    TASKQ_PREPOPULATE);
25097 
25098 	/*
25099 	 * We want to be informed each time a stack is created or
25100 	 * destroyed in the kernel, so we can maintain the
25101 	 * set of tcp_stack_t's.
25102 	 */
25103 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
25104 	    tcp_stack_fini);
25105 }
25106 
25107 
25108 /*
25109  * Initialize the TCP stack instance.
25110  */
25111 static void *
25112 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
25113 {
25114 	tcp_stack_t	*tcps;
25115 	tcpparam_t	*pa;
25116 	int		i;
25117 
25118 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
25119 	tcps->tcps_netstack = ns;
25120 
25121 	/* Initialize locks */
25122 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
25123 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
25124 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
25125 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
25126 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
25127 	rw_init(&tcps->tcps_reserved_port_lock, NULL, RW_DEFAULT, NULL);
25128 
25129 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
25130 	tcps->tcps_g_epriv_ports[0] = 2049;
25131 	tcps->tcps_g_epriv_ports[1] = 4045;
25132 	tcps->tcps_min_anonpriv_port = 512;
25133 
25134 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
25135 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
25136 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
25137 	    TCP_FANOUT_SIZE, KM_SLEEP);
25138 	tcps->tcps_reserved_port = kmem_zalloc(sizeof (tcp_rport_t) *
25139 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE, KM_SLEEP);
25140 
25141 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25142 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
25143 		    MUTEX_DEFAULT, NULL);
25144 	}
25145 
25146 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25147 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25148 		    MUTEX_DEFAULT, NULL);
25149 	}
25150 
25151 	/* TCP's IPsec code calls the packet dropper. */
25152 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25153 
25154 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25155 	tcps->tcps_params = pa;
25156 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25157 
25158 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25159 	    A_CNT(lcl_tcp_param_arr), tcps);
25160 
25161 	/*
25162 	 * Note: To really walk the device tree you need the devinfo
25163 	 * pointer to your device which is only available after probe/attach.
25164 	 * The following is safe only because it uses ddi_root_node()
25165 	 */
25166 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25167 	    tcp_opt_obj.odb_opt_arr_cnt);
25168 
25169 	/*
25170 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25171 	 * by the boot scripts.
25172 	 *
25173 	 * Use NULL name, as the name is caught by the new lockstats.
25174 	 *
25175 	 * Initialize with some random, non-guessable string, like the global
25176 	 * T_INFO_ACK.
25177 	 */
25178 
25179 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25180 	    sizeof (tcp_g_t_info_ack), tcps);
25181 
25182 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25183 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25184 
25185 	return (tcps);
25186 }
25187 
25188 /*
25189  * Called when the IP module is about to be unloaded.
25190  */
25191 void
25192 tcp_ddi_g_destroy(void)
25193 {
25194 	tcp_g_kstat_fini(tcp_g_kstat);
25195 	tcp_g_kstat = NULL;
25196 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25197 
25198 	mutex_destroy(&tcp_random_lock);
25199 
25200 	kmem_cache_destroy(tcp_timercache);
25201 	kmem_cache_destroy(tcp_sack_info_cache);
25202 	kmem_cache_destroy(tcp_iphc_cache);
25203 
25204 	netstack_unregister(NS_TCP);
25205 	taskq_destroy(tcp_taskq);
25206 }
25207 
25208 /*
25209  * Shut down the TCP stack instance.
25210  */
25211 /* ARGSUSED */
25212 static void
25213 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25214 {
25215 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25216 
25217 	tcp_g_q_destroy(tcps);
25218 }
25219 
25220 /*
25221  * Free the TCP stack instance.
25222  */
25223 static void
25224 tcp_stack_fini(netstackid_t stackid, void *arg)
25225 {
25226 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25227 	int i;
25228 
25229 	nd_free(&tcps->tcps_g_nd);
25230 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25231 	tcps->tcps_params = NULL;
25232 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25233 	tcps->tcps_wroff_xtra_param = NULL;
25234 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25235 	tcps->tcps_mdt_head_param = NULL;
25236 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25237 	tcps->tcps_mdt_tail_param = NULL;
25238 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25239 	tcps->tcps_mdt_max_pbufs_param = NULL;
25240 
25241 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25242 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25243 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25244 	}
25245 
25246 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25247 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25248 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25249 	}
25250 
25251 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25252 	tcps->tcps_bind_fanout = NULL;
25253 
25254 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25255 	tcps->tcps_acceptor_fanout = NULL;
25256 
25257 	kmem_free(tcps->tcps_reserved_port, sizeof (tcp_rport_t) *
25258 	    TCP_RESERVED_PORTS_ARRAY_MAX_SIZE);
25259 	tcps->tcps_reserved_port = NULL;
25260 
25261 	mutex_destroy(&tcps->tcps_iss_key_lock);
25262 	rw_destroy(&tcps->tcps_hsp_lock);
25263 	mutex_destroy(&tcps->tcps_g_q_lock);
25264 	cv_destroy(&tcps->tcps_g_q_cv);
25265 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25266 	rw_destroy(&tcps->tcps_reserved_port_lock);
25267 
25268 	ip_drop_unregister(&tcps->tcps_dropper);
25269 
25270 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25271 	tcps->tcps_kstat = NULL;
25272 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25273 
25274 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25275 	tcps->tcps_mibkp = NULL;
25276 
25277 	kmem_free(tcps, sizeof (*tcps));
25278 }
25279 
25280 /*
25281  * Generate ISS, taking into account NDD changes may happen halfway through.
25282  * (If the iss is not zero, set it.)
25283  */
25284 
25285 static void
25286 tcp_iss_init(tcp_t *tcp)
25287 {
25288 	MD5_CTX context;
25289 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25290 	uint32_t answer[4];
25291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25292 
25293 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25294 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25295 	switch (tcps->tcps_strong_iss) {
25296 	case 2:
25297 		mutex_enter(&tcps->tcps_iss_key_lock);
25298 		context = tcps->tcps_iss_key;
25299 		mutex_exit(&tcps->tcps_iss_key_lock);
25300 		arg.ports = tcp->tcp_ports;
25301 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25302 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25303 			    &arg.src);
25304 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25305 			    &arg.dst);
25306 		} else {
25307 			arg.src = tcp->tcp_ip6h->ip6_src;
25308 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25309 		}
25310 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25311 		MD5Final((uchar_t *)answer, &context);
25312 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25313 		/*
25314 		 * Now that we've hashed into a unique per-connection sequence
25315 		 * space, add a random increment per strong_iss == 1.  So I
25316 		 * guess we'll have to...
25317 		 */
25318 		/* FALLTHRU */
25319 	case 1:
25320 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25321 		break;
25322 	default:
25323 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25324 		break;
25325 	}
25326 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25327 	tcp->tcp_fss = tcp->tcp_iss - 1;
25328 	tcp->tcp_suna = tcp->tcp_iss;
25329 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25330 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25331 	tcp->tcp_csuna = tcp->tcp_snxt;
25332 }
25333 
25334 /*
25335  * Exported routine for extracting active tcp connection status.
25336  *
25337  * This is used by the Solaris Cluster Networking software to
25338  * gather a list of connections that need to be forwarded to
25339  * specific nodes in the cluster when configuration changes occur.
25340  *
25341  * The callback is invoked for each tcp_t structure. Returning
25342  * non-zero from the callback routine terminates the search.
25343  */
25344 int
25345 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25346     void *arg)
25347 {
25348 	netstack_handle_t nh;
25349 	netstack_t *ns;
25350 	int ret = 0;
25351 
25352 	netstack_next_init(&nh);
25353 	while ((ns = netstack_next(&nh)) != NULL) {
25354 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25355 		    ns->netstack_tcp);
25356 		netstack_rele(ns);
25357 	}
25358 	netstack_next_fini(&nh);
25359 	return (ret);
25360 }
25361 
25362 static int
25363 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25364     tcp_stack_t *tcps)
25365 {
25366 	tcp_t *tcp;
25367 	cl_tcp_info_t	cl_tcpi;
25368 	connf_t	*connfp;
25369 	conn_t	*connp;
25370 	int	i;
25371 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25372 
25373 	ASSERT(callback != NULL);
25374 
25375 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25376 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25377 		connp = NULL;
25378 
25379 		while ((connp =
25380 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25381 
25382 			tcp = connp->conn_tcp;
25383 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25384 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25385 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25386 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25387 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25388 			/*
25389 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25390 			 * addresses. They are copied implicitly below as
25391 			 * mapped addresses.
25392 			 */
25393 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25394 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25395 				cl_tcpi.cl_tcpi_faddr =
25396 				    tcp->tcp_ipha->ipha_dst;
25397 			} else {
25398 				cl_tcpi.cl_tcpi_faddr_v6 =
25399 				    tcp->tcp_ip6h->ip6_dst;
25400 			}
25401 
25402 			/*
25403 			 * If the callback returns non-zero
25404 			 * we terminate the traversal.
25405 			 */
25406 			if ((*callback)(&cl_tcpi, arg) != 0) {
25407 				CONN_DEC_REF(tcp->tcp_connp);
25408 				return (1);
25409 			}
25410 		}
25411 	}
25412 
25413 	return (0);
25414 }
25415 
25416 /*
25417  * Macros used for accessing the different types of sockaddr
25418  * structures inside a tcp_ioc_abort_conn_t.
25419  */
25420 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25421 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25422 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25423 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25424 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25425 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25426 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25427 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25428 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25429 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25430 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25431 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25432 
25433 /*
25434  * Return the correct error code to mimic the behavior
25435  * of a connection reset.
25436  */
25437 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25438 		switch ((state)) {		\
25439 		case TCPS_SYN_SENT:		\
25440 		case TCPS_SYN_RCVD:		\
25441 			(err) = ECONNREFUSED;	\
25442 			break;			\
25443 		case TCPS_ESTABLISHED:		\
25444 		case TCPS_FIN_WAIT_1:		\
25445 		case TCPS_FIN_WAIT_2:		\
25446 		case TCPS_CLOSE_WAIT:		\
25447 			(err) = ECONNRESET;	\
25448 			break;			\
25449 		case TCPS_CLOSING:		\
25450 		case TCPS_LAST_ACK:		\
25451 		case TCPS_TIME_WAIT:		\
25452 			(err) = 0;		\
25453 			break;			\
25454 		default:			\
25455 			(err) = ENXIO;		\
25456 		}				\
25457 	}
25458 
25459 /*
25460  * Check if a tcp structure matches the info in acp.
25461  */
25462 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25463 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25464 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25465 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25466 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25467 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25468 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25469 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25470 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25471 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25472 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25473 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25474 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25475 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25476 	&(tcp)->tcp_ip_src_v6)) &&				\
25477 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25478 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25479 	&(tcp)->tcp_remote_v6)) &&				\
25480 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25481 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25482 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25483 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25484 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25485 	(acp)->ac_end >= (tcp)->tcp_state))
25486 
25487 #define	TCP_AC_MATCH(acp, tcp)					\
25488 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25489 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25490 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25491 
25492 /*
25493  * Build a message containing a tcp_ioc_abort_conn_t structure
25494  * which is filled in with information from acp and tp.
25495  */
25496 static mblk_t *
25497 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25498 {
25499 	mblk_t *mp;
25500 	tcp_ioc_abort_conn_t *tacp;
25501 
25502 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25503 	if (mp == NULL)
25504 		return (NULL);
25505 
25506 	mp->b_datap->db_type = M_CTL;
25507 
25508 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25509 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25510 		sizeof (uint32_t));
25511 
25512 	tacp->ac_start = acp->ac_start;
25513 	tacp->ac_end = acp->ac_end;
25514 	tacp->ac_zoneid = acp->ac_zoneid;
25515 
25516 	if (acp->ac_local.ss_family == AF_INET) {
25517 		tacp->ac_local.ss_family = AF_INET;
25518 		tacp->ac_remote.ss_family = AF_INET;
25519 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25520 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25521 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25522 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25523 	} else {
25524 		tacp->ac_local.ss_family = AF_INET6;
25525 		tacp->ac_remote.ss_family = AF_INET6;
25526 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25527 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25528 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25529 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25530 	}
25531 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25532 	return (mp);
25533 }
25534 
25535 /*
25536  * Print a tcp_ioc_abort_conn_t structure.
25537  */
25538 static void
25539 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25540 {
25541 	char lbuf[128];
25542 	char rbuf[128];
25543 	sa_family_t af;
25544 	in_port_t lport, rport;
25545 	ushort_t logflags;
25546 
25547 	af = acp->ac_local.ss_family;
25548 
25549 	if (af == AF_INET) {
25550 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25551 				lbuf, 128);
25552 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25553 				rbuf, 128);
25554 		lport = ntohs(TCP_AC_V4LPORT(acp));
25555 		rport = ntohs(TCP_AC_V4RPORT(acp));
25556 	} else {
25557 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25558 				lbuf, 128);
25559 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25560 				rbuf, 128);
25561 		lport = ntohs(TCP_AC_V6LPORT(acp));
25562 		rport = ntohs(TCP_AC_V6RPORT(acp));
25563 	}
25564 
25565 	logflags = SL_TRACE | SL_NOTE;
25566 	/*
25567 	 * Don't print this message to the console if the operation was done
25568 	 * to a non-global zone.
25569 	 */
25570 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25571 		logflags |= SL_CONSOLE;
25572 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25573 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25574 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25575 		acp->ac_start, acp->ac_end);
25576 }
25577 
25578 /*
25579  * Called inside tcp_rput when a message built using
25580  * tcp_ioctl_abort_build_msg is put into a queue.
25581  * Note that when we get here there is no wildcard in acp any more.
25582  */
25583 static void
25584 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25585 {
25586 	tcp_ioc_abort_conn_t *acp;
25587 
25588 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25589 	if (tcp->tcp_state <= acp->ac_end) {
25590 		/*
25591 		 * If we get here, we are already on the correct
25592 		 * squeue. This ioctl follows the following path
25593 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25594 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25595 		 * different squeue)
25596 		 */
25597 		int errcode;
25598 
25599 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25600 		(void) tcp_clean_death(tcp, errcode, 26);
25601 	}
25602 	freemsg(mp);
25603 }
25604 
25605 /*
25606  * Abort all matching connections on a hash chain.
25607  */
25608 static int
25609 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25610     boolean_t exact, tcp_stack_t *tcps)
25611 {
25612 	int nmatch, err = 0;
25613 	tcp_t *tcp;
25614 	MBLKP mp, last, listhead = NULL;
25615 	conn_t	*tconnp;
25616 	connf_t	*connfp;
25617 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25618 
25619 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25620 
25621 startover:
25622 	nmatch = 0;
25623 
25624 	mutex_enter(&connfp->connf_lock);
25625 	for (tconnp = connfp->connf_head; tconnp != NULL;
25626 	    tconnp = tconnp->conn_next) {
25627 		tcp = tconnp->conn_tcp;
25628 		if (TCP_AC_MATCH(acp, tcp)) {
25629 			CONN_INC_REF(tcp->tcp_connp);
25630 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25631 			if (mp == NULL) {
25632 				err = ENOMEM;
25633 				CONN_DEC_REF(tcp->tcp_connp);
25634 				break;
25635 			}
25636 			mp->b_prev = (mblk_t *)tcp;
25637 
25638 			if (listhead == NULL) {
25639 				listhead = mp;
25640 				last = mp;
25641 			} else {
25642 				last->b_next = mp;
25643 				last = mp;
25644 			}
25645 			nmatch++;
25646 			if (exact)
25647 				break;
25648 		}
25649 
25650 		/* Avoid holding lock for too long. */
25651 		if (nmatch >= 500)
25652 			break;
25653 	}
25654 	mutex_exit(&connfp->connf_lock);
25655 
25656 	/* Pass mp into the correct tcp */
25657 	while ((mp = listhead) != NULL) {
25658 		listhead = listhead->b_next;
25659 		tcp = (tcp_t *)mp->b_prev;
25660 		mp->b_next = mp->b_prev = NULL;
25661 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25662 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25663 	}
25664 
25665 	*count += nmatch;
25666 	if (nmatch >= 500 && err == 0)
25667 		goto startover;
25668 	return (err);
25669 }
25670 
25671 /*
25672  * Abort all connections that matches the attributes specified in acp.
25673  */
25674 static int
25675 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25676 {
25677 	sa_family_t af;
25678 	uint32_t  ports;
25679 	uint16_t *pports;
25680 	int err = 0, count = 0;
25681 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25682 	int index = -1;
25683 	ushort_t logflags;
25684 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25685 
25686 	af = acp->ac_local.ss_family;
25687 
25688 	if (af == AF_INET) {
25689 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25690 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25691 			pports = (uint16_t *)&ports;
25692 			pports[1] = TCP_AC_V4LPORT(acp);
25693 			pports[0] = TCP_AC_V4RPORT(acp);
25694 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25695 		}
25696 	} else {
25697 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25698 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25699 			pports = (uint16_t *)&ports;
25700 			pports[1] = TCP_AC_V6LPORT(acp);
25701 			pports[0] = TCP_AC_V6RPORT(acp);
25702 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25703 		}
25704 	}
25705 
25706 	/*
25707 	 * For cases where remote addr, local port, and remote port are non-
25708 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25709 	 */
25710 	if (index != -1) {
25711 		err = tcp_ioctl_abort_bucket(acp, index,
25712 			    &count, exact, tcps);
25713 	} else {
25714 		/*
25715 		 * loop through all entries for wildcard case
25716 		 */
25717 		for (index = 0;
25718 		    index < ipst->ips_ipcl_conn_fanout_size;
25719 		    index++) {
25720 			err = tcp_ioctl_abort_bucket(acp, index,
25721 			    &count, exact, tcps);
25722 			if (err != 0)
25723 				break;
25724 		}
25725 	}
25726 
25727 	logflags = SL_TRACE | SL_NOTE;
25728 	/*
25729 	 * Don't print this message to the console if the operation was done
25730 	 * to a non-global zone.
25731 	 */
25732 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25733 		logflags |= SL_CONSOLE;
25734 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25735 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25736 	if (err == 0 && count == 0)
25737 		err = ENOENT;
25738 	return (err);
25739 }
25740 
25741 /*
25742  * Process the TCP_IOC_ABORT_CONN ioctl request.
25743  */
25744 static void
25745 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25746 {
25747 	int	err;
25748 	IOCP    iocp;
25749 	MBLKP   mp1;
25750 	sa_family_t laf, raf;
25751 	tcp_ioc_abort_conn_t *acp;
25752 	zone_t		*zptr;
25753 	conn_t		*connp = Q_TO_CONN(q);
25754 	zoneid_t	zoneid = connp->conn_zoneid;
25755 	tcp_t		*tcp = connp->conn_tcp;
25756 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25757 
25758 	iocp = (IOCP)mp->b_rptr;
25759 
25760 	if ((mp1 = mp->b_cont) == NULL ||
25761 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25762 		err = EINVAL;
25763 		goto out;
25764 	}
25765 
25766 	/* check permissions */
25767 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25768 		err = EPERM;
25769 		goto out;
25770 	}
25771 
25772 	if (mp1->b_cont != NULL) {
25773 		freemsg(mp1->b_cont);
25774 		mp1->b_cont = NULL;
25775 	}
25776 
25777 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25778 	laf = acp->ac_local.ss_family;
25779 	raf = acp->ac_remote.ss_family;
25780 
25781 	/* check that a zone with the supplied zoneid exists */
25782 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25783 		zptr = zone_find_by_id(zoneid);
25784 		if (zptr != NULL) {
25785 			zone_rele(zptr);
25786 		} else {
25787 			err = EINVAL;
25788 			goto out;
25789 		}
25790 	}
25791 
25792 	/*
25793 	 * For exclusive stacks we set the zoneid to zero
25794 	 * to make TCP operate as if in the global zone.
25795 	 */
25796 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25797 		acp->ac_zoneid = GLOBAL_ZONEID;
25798 
25799 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25800 	    acp->ac_start > acp->ac_end || laf != raf ||
25801 	    (laf != AF_INET && laf != AF_INET6)) {
25802 		err = EINVAL;
25803 		goto out;
25804 	}
25805 
25806 	tcp_ioctl_abort_dump(acp);
25807 	err = tcp_ioctl_abort(acp, tcps);
25808 
25809 out:
25810 	if (mp1 != NULL) {
25811 		freemsg(mp1);
25812 		mp->b_cont = NULL;
25813 	}
25814 
25815 	if (err != 0)
25816 		miocnak(q, mp, 0, err);
25817 	else
25818 		miocack(q, mp, 0, 0);
25819 }
25820 
25821 /*
25822  * tcp_time_wait_processing() handles processing of incoming packets when
25823  * the tcp is in the TIME_WAIT state.
25824  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25825  * on the time wait list.
25826  */
25827 void
25828 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25829     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25830 {
25831 	int32_t		bytes_acked;
25832 	int32_t		gap;
25833 	int32_t		rgap;
25834 	tcp_opt_t	tcpopt;
25835 	uint_t		flags;
25836 	uint32_t	new_swnd = 0;
25837 	conn_t		*connp;
25838 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25839 
25840 	BUMP_LOCAL(tcp->tcp_ibsegs);
25841 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
25842 
25843 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25844 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25845 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25846 	if (tcp->tcp_snd_ts_ok) {
25847 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25848 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25849 			    tcp->tcp_rnxt, TH_ACK);
25850 			goto done;
25851 		}
25852 	}
25853 	gap = seg_seq - tcp->tcp_rnxt;
25854 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25855 	if (gap < 0) {
25856 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25857 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25858 		    (seg_len > -gap ? -gap : seg_len));
25859 		seg_len += gap;
25860 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25861 			if (flags & TH_RST) {
25862 				goto done;
25863 			}
25864 			if ((flags & TH_FIN) && seg_len == -1) {
25865 				/*
25866 				 * When TCP receives a duplicate FIN in
25867 				 * TIME_WAIT state, restart the 2 MSL timer.
25868 				 * See page 73 in RFC 793. Make sure this TCP
25869 				 * is already on the TIME_WAIT list. If not,
25870 				 * just restart the timer.
25871 				 */
25872 				if (TCP_IS_DETACHED(tcp)) {
25873 					if (tcp_time_wait_remove(tcp, NULL) ==
25874 					    B_TRUE) {
25875 						tcp_time_wait_append(tcp);
25876 						TCP_DBGSTAT(tcps,
25877 						    tcp_rput_time_wait);
25878 					}
25879 				} else {
25880 					ASSERT(tcp != NULL);
25881 					TCP_TIMER_RESTART(tcp,
25882 					    tcps->tcps_time_wait_interval);
25883 				}
25884 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25885 				    tcp->tcp_rnxt, TH_ACK);
25886 				goto done;
25887 			}
25888 			flags |=  TH_ACK_NEEDED;
25889 			seg_len = 0;
25890 			goto process_ack;
25891 		}
25892 
25893 		/* Fix seg_seq, and chew the gap off the front. */
25894 		seg_seq = tcp->tcp_rnxt;
25895 	}
25896 
25897 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25898 		/*
25899 		 * Make sure that when we accept the connection, pick
25900 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25901 		 * old connection.
25902 		 *
25903 		 * The next ISS generated is equal to tcp_iss_incr_extra
25904 		 * + ISS_INCR/2 + other components depending on the
25905 		 * value of tcp_strong_iss.  We pre-calculate the new
25906 		 * ISS here and compare with tcp_snxt to determine if
25907 		 * we need to make adjustment to tcp_iss_incr_extra.
25908 		 *
25909 		 * The above calculation is ugly and is a
25910 		 * waste of CPU cycles...
25911 		 */
25912 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25913 		int32_t adj;
25914 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25915 
25916 		switch (tcps->tcps_strong_iss) {
25917 		case 2: {
25918 			/* Add time and MD5 components. */
25919 			uint32_t answer[4];
25920 			struct {
25921 				uint32_t ports;
25922 				in6_addr_t src;
25923 				in6_addr_t dst;
25924 			} arg;
25925 			MD5_CTX context;
25926 
25927 			mutex_enter(&tcps->tcps_iss_key_lock);
25928 			context = tcps->tcps_iss_key;
25929 			mutex_exit(&tcps->tcps_iss_key_lock);
25930 			arg.ports = tcp->tcp_ports;
25931 			/* We use MAPPED addresses in tcp_iss_init */
25932 			arg.src = tcp->tcp_ip_src_v6;
25933 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25934 				IN6_IPADDR_TO_V4MAPPED(
25935 					tcp->tcp_ipha->ipha_dst,
25936 					    &arg.dst);
25937 			} else {
25938 				arg.dst =
25939 				    tcp->tcp_ip6h->ip6_dst;
25940 			}
25941 			MD5Update(&context, (uchar_t *)&arg,
25942 			    sizeof (arg));
25943 			MD5Final((uchar_t *)answer, &context);
25944 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25945 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25946 			break;
25947 		}
25948 		case 1:
25949 			/* Add time component and min random (i.e. 1). */
25950 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25951 			break;
25952 		default:
25953 			/* Add only time component. */
25954 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25955 			break;
25956 		}
25957 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25958 			/*
25959 			 * New ISS not guaranteed to be ISS_INCR/2
25960 			 * ahead of the current tcp_snxt, so add the
25961 			 * difference to tcp_iss_incr_extra.
25962 			 */
25963 			tcps->tcps_iss_incr_extra += adj;
25964 		}
25965 		/*
25966 		 * If tcp_clean_death() can not perform the task now,
25967 		 * drop the SYN packet and let the other side re-xmit.
25968 		 * Otherwise pass the SYN packet back in, since the
25969 		 * old tcp state has been cleaned up or freed.
25970 		 */
25971 		if (tcp_clean_death(tcp, 0, 27) == -1)
25972 			goto done;
25973 		/*
25974 		 * We will come back to tcp_rput_data
25975 		 * on the global queue. Packets destined
25976 		 * for the global queue will be checked
25977 		 * with global policy. But the policy for
25978 		 * this packet has already been checked as
25979 		 * this was destined for the detached
25980 		 * connection. We need to bypass policy
25981 		 * check this time by attaching a dummy
25982 		 * ipsec_in with ipsec_in_dont_check set.
25983 		 */
25984 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25985 		if (connp != NULL) {
25986 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25987 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25988 			return;
25989 		}
25990 		goto done;
25991 	}
25992 
25993 	/*
25994 	 * rgap is the amount of stuff received out of window.  A negative
25995 	 * value is the amount out of window.
25996 	 */
25997 	if (rgap < 0) {
25998 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25999 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
26000 		/* Fix seg_len and make sure there is something left. */
26001 		seg_len += rgap;
26002 		if (seg_len <= 0) {
26003 			if (flags & TH_RST) {
26004 				goto done;
26005 			}
26006 			flags |=  TH_ACK_NEEDED;
26007 			seg_len = 0;
26008 			goto process_ack;
26009 		}
26010 	}
26011 	/*
26012 	 * Check whether we can update tcp_ts_recent.  This test is
26013 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
26014 	 * Extensions for High Performance: An Update", Internet Draft.
26015 	 */
26016 	if (tcp->tcp_snd_ts_ok &&
26017 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
26018 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
26019 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
26020 		tcp->tcp_last_rcv_lbolt = lbolt64;
26021 	}
26022 
26023 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
26024 		/* Always ack out of order packets */
26025 		flags |= TH_ACK_NEEDED;
26026 		seg_len = 0;
26027 	} else if (seg_len > 0) {
26028 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
26029 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
26030 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
26031 	}
26032 	if (flags & TH_RST) {
26033 		(void) tcp_clean_death(tcp, 0, 28);
26034 		goto done;
26035 	}
26036 	if (flags & TH_SYN) {
26037 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
26038 		    TH_RST|TH_ACK);
26039 		/*
26040 		 * Do not delete the TCP structure if it is in
26041 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
26042 		 */
26043 		goto done;
26044 	}
26045 process_ack:
26046 	if (flags & TH_ACK) {
26047 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
26048 		if (bytes_acked <= 0) {
26049 			if (bytes_acked == 0 && seg_len == 0 &&
26050 			    new_swnd == tcp->tcp_swnd)
26051 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
26052 		} else {
26053 			/* Acks something not sent */
26054 			flags |= TH_ACK_NEEDED;
26055 		}
26056 	}
26057 	if (flags & TH_ACK_NEEDED) {
26058 		/*
26059 		 * Time to send an ack for some reason.
26060 		 */
26061 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
26062 		    tcp->tcp_rnxt, TH_ACK);
26063 	}
26064 done:
26065 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26066 		DB_CKSUMSTART(mp) = 0;
26067 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
26068 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
26069 	}
26070 	freemsg(mp);
26071 }
26072 
26073 /*
26074  * Allocate a T_SVR4_OPTMGMT_REQ.
26075  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
26076  * that tcp_rput_other can drop the acks.
26077  */
26078 static mblk_t *
26079 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
26080 {
26081 	mblk_t *mp;
26082 	struct T_optmgmt_req *tor;
26083 	struct opthdr *oh;
26084 	uint_t size;
26085 	char *optptr;
26086 
26087 	size = sizeof (*tor) + sizeof (*oh) + optlen;
26088 	mp = allocb(size, BPRI_MED);
26089 	if (mp == NULL)
26090 		return (NULL);
26091 
26092 	mp->b_wptr += size;
26093 	mp->b_datap->db_type = M_PROTO;
26094 	tor = (struct T_optmgmt_req *)mp->b_rptr;
26095 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
26096 	tor->MGMT_flags = T_NEGOTIATE;
26097 	tor->OPT_length = sizeof (*oh) + optlen;
26098 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
26099 
26100 	oh = (struct opthdr *)&tor[1];
26101 	oh->level = level;
26102 	oh->name = cmd;
26103 	oh->len = optlen;
26104 	if (optlen != 0) {
26105 		optptr = (char *)&oh[1];
26106 		bcopy(opt, optptr, optlen);
26107 	}
26108 	return (mp);
26109 }
26110 
26111 /*
26112  * TCP Timers Implementation.
26113  */
26114 timeout_id_t
26115 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
26116 {
26117 	mblk_t *mp;
26118 	tcp_timer_t *tcpt;
26119 	tcp_t *tcp = connp->conn_tcp;
26120 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26121 
26122 	ASSERT(connp->conn_sqp != NULL);
26123 
26124 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
26125 
26126 	if (tcp->tcp_timercache == NULL) {
26127 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
26128 	} else {
26129 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
26130 		mp = tcp->tcp_timercache;
26131 		tcp->tcp_timercache = mp->b_next;
26132 		mp->b_next = NULL;
26133 		ASSERT(mp->b_wptr == NULL);
26134 	}
26135 
26136 	CONN_INC_REF(connp);
26137 	tcpt = (tcp_timer_t *)mp->b_rptr;
26138 	tcpt->connp = connp;
26139 	tcpt->tcpt_proc = f;
26140 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
26141 	return ((timeout_id_t)mp);
26142 }
26143 
26144 static void
26145 tcp_timer_callback(void *arg)
26146 {
26147 	mblk_t *mp = (mblk_t *)arg;
26148 	tcp_timer_t *tcpt;
26149 	conn_t	*connp;
26150 
26151 	tcpt = (tcp_timer_t *)mp->b_rptr;
26152 	connp = tcpt->connp;
26153 	squeue_fill(connp->conn_sqp, mp,
26154 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26155 }
26156 
26157 static void
26158 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26159 {
26160 	tcp_timer_t *tcpt;
26161 	conn_t *connp = (conn_t *)arg;
26162 	tcp_t *tcp = connp->conn_tcp;
26163 
26164 	tcpt = (tcp_timer_t *)mp->b_rptr;
26165 	ASSERT(connp == tcpt->connp);
26166 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26167 
26168 	/*
26169 	 * If the TCP has reached the closed state, don't proceed any
26170 	 * further. This TCP logically does not exist on the system.
26171 	 * tcpt_proc could for example access queues, that have already
26172 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26173 	 */
26174 	if (tcp->tcp_state != TCPS_CLOSED) {
26175 		(*tcpt->tcpt_proc)(connp);
26176 	} else {
26177 		tcp->tcp_timer_tid = 0;
26178 	}
26179 	tcp_timer_free(connp->conn_tcp, mp);
26180 }
26181 
26182 /*
26183  * There is potential race with untimeout and the handler firing at the same
26184  * time. The mblock may be freed by the handler while we are trying to use
26185  * it. But since both should execute on the same squeue, this race should not
26186  * occur.
26187  */
26188 clock_t
26189 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26190 {
26191 	mblk_t	*mp = (mblk_t *)id;
26192 	tcp_timer_t *tcpt;
26193 	clock_t delta;
26194 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26195 
26196 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26197 
26198 	if (mp == NULL)
26199 		return (-1);
26200 
26201 	tcpt = (tcp_timer_t *)mp->b_rptr;
26202 	ASSERT(tcpt->connp == connp);
26203 
26204 	delta = untimeout(tcpt->tcpt_tid);
26205 
26206 	if (delta >= 0) {
26207 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26208 		tcp_timer_free(connp->conn_tcp, mp);
26209 		CONN_DEC_REF(connp);
26210 	}
26211 
26212 	return (delta);
26213 }
26214 
26215 /*
26216  * Allocate space for the timer event. The allocation looks like mblk, but it is
26217  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26218  *
26219  * Dealing with failures: If we can't allocate from the timer cache we try
26220  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26221  * points to b_rptr.
26222  * If we can't allocate anything using allocb_tryhard(), we perform a last
26223  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26224  * save the actual allocation size in b_datap.
26225  */
26226 mblk_t *
26227 tcp_timermp_alloc(int kmflags)
26228 {
26229 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26230 	    kmflags & ~KM_PANIC);
26231 
26232 	if (mp != NULL) {
26233 		mp->b_next = mp->b_prev = NULL;
26234 		mp->b_rptr = (uchar_t *)(&mp[1]);
26235 		mp->b_wptr = NULL;
26236 		mp->b_datap = NULL;
26237 		mp->b_queue = NULL;
26238 		mp->b_cont = NULL;
26239 	} else if (kmflags & KM_PANIC) {
26240 		/*
26241 		 * Failed to allocate memory for the timer. Try allocating from
26242 		 * dblock caches.
26243 		 */
26244 		/* ipclassifier calls this from a constructor - hence no tcps */
26245 		TCP_G_STAT(tcp_timermp_allocfail);
26246 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26247 		if (mp == NULL) {
26248 			size_t size = 0;
26249 			/*
26250 			 * Memory is really low. Try tryhard allocation.
26251 			 *
26252 			 * ipclassifier calls this from a constructor -
26253 			 * hence no tcps
26254 			 */
26255 			TCP_G_STAT(tcp_timermp_allocdblfail);
26256 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26257 			    sizeof (tcp_timer_t), &size, kmflags);
26258 			mp->b_rptr = (uchar_t *)(&mp[1]);
26259 			mp->b_next = mp->b_prev = NULL;
26260 			mp->b_wptr = (uchar_t *)-1;
26261 			mp->b_datap = (dblk_t *)size;
26262 			mp->b_queue = NULL;
26263 			mp->b_cont = NULL;
26264 		}
26265 		ASSERT(mp->b_wptr != NULL);
26266 	}
26267 	/* ipclassifier calls this from a constructor - hence no tcps */
26268 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26269 
26270 	return (mp);
26271 }
26272 
26273 /*
26274  * Free per-tcp timer cache.
26275  * It can only contain entries from tcp_timercache.
26276  */
26277 void
26278 tcp_timermp_free(tcp_t *tcp)
26279 {
26280 	mblk_t *mp;
26281 
26282 	while ((mp = tcp->tcp_timercache) != NULL) {
26283 		ASSERT(mp->b_wptr == NULL);
26284 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26285 		kmem_cache_free(tcp_timercache, mp);
26286 	}
26287 }
26288 
26289 /*
26290  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26291  * events there already (currently at most two events are cached).
26292  * If the event is not allocated from the timer cache, free it right away.
26293  */
26294 static void
26295 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26296 {
26297 	mblk_t *mp1 = tcp->tcp_timercache;
26298 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26299 
26300 	if (mp->b_wptr != NULL) {
26301 		/*
26302 		 * This allocation is not from a timer cache, free it right
26303 		 * away.
26304 		 */
26305 		if (mp->b_wptr != (uchar_t *)-1)
26306 			freeb(mp);
26307 		else
26308 			kmem_free(mp, (size_t)mp->b_datap);
26309 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26310 		/* Cache this timer block for future allocations */
26311 		mp->b_rptr = (uchar_t *)(&mp[1]);
26312 		mp->b_next = mp1;
26313 		tcp->tcp_timercache = mp;
26314 	} else {
26315 		kmem_cache_free(tcp_timercache, mp);
26316 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26317 	}
26318 }
26319 
26320 /*
26321  * End of TCP Timers implementation.
26322  */
26323 
26324 /*
26325  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26326  * on the specified backing STREAMS q. Note, the caller may make the
26327  * decision to call based on the tcp_t.tcp_flow_stopped value which
26328  * when check outside the q's lock is only an advisory check ...
26329  */
26330 
26331 void
26332 tcp_setqfull(tcp_t *tcp)
26333 {
26334 	queue_t *q = tcp->tcp_wq;
26335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26336 
26337 	if (!(q->q_flag & QFULL)) {
26338 		mutex_enter(QLOCK(q));
26339 		if (!(q->q_flag & QFULL)) {
26340 			/* still need to set QFULL */
26341 			q->q_flag |= QFULL;
26342 			tcp->tcp_flow_stopped = B_TRUE;
26343 			mutex_exit(QLOCK(q));
26344 			TCP_STAT(tcps, tcp_flwctl_on);
26345 		} else {
26346 			mutex_exit(QLOCK(q));
26347 		}
26348 	}
26349 }
26350 
26351 void
26352 tcp_clrqfull(tcp_t *tcp)
26353 {
26354 	queue_t *q = tcp->tcp_wq;
26355 
26356 	if (q->q_flag & QFULL) {
26357 		mutex_enter(QLOCK(q));
26358 		if (q->q_flag & QFULL) {
26359 			q->q_flag &= ~QFULL;
26360 			tcp->tcp_flow_stopped = B_FALSE;
26361 			mutex_exit(QLOCK(q));
26362 			if (q->q_flag & QWANTW)
26363 				qbackenable(q, 0);
26364 		} else {
26365 			mutex_exit(QLOCK(q));
26366 		}
26367 	}
26368 }
26369 
26370 
26371 /*
26372  * kstats related to squeues i.e. not per IP instance
26373  */
26374 static void *
26375 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26376 {
26377 	kstat_t *ksp;
26378 
26379 	tcp_g_stat_t template = {
26380 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26381 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26382 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26383 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26384 	};
26385 
26386 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26387 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26388 	    KSTAT_FLAG_VIRTUAL);
26389 
26390 	if (ksp == NULL)
26391 		return (NULL);
26392 
26393 	bcopy(&template, tcp_g_statp, sizeof (template));
26394 	ksp->ks_data = (void *)tcp_g_statp;
26395 
26396 	kstat_install(ksp);
26397 	return (ksp);
26398 }
26399 
26400 static void
26401 tcp_g_kstat_fini(kstat_t *ksp)
26402 {
26403 	if (ksp != NULL) {
26404 		kstat_delete(ksp);
26405 	}
26406 }
26407 
26408 
26409 static void *
26410 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26411 {
26412 	kstat_t *ksp;
26413 
26414 	tcp_stat_t template = {
26415 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26416 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26417 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26418 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26419 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26420 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26421 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26422 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26423 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26424 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26425 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26426 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26427 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26428 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26429 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26430 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26431 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26432 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26433 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26434 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26435 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26436 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26437 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26438 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26439 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26440 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26441 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26442 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26443 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26444 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26445 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26446 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26447 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26448 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26449 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26450 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26451 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26452 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26453 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26454 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26455 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26456 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26457 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26458 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26459 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26460 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26461 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26462 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26463 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26464 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26465 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26466 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26467 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26468 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26469 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26470 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26471 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26472 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26473 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26474 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26475 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26476 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26477 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26478 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26479 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26480 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26481 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26482 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26483 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26484 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26485 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26486 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26487 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26488 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26489 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26490 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26491 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26492 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26493 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26494 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26495 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26496 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26497 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26498 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26499 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26500 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26501 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26502 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26503 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26504 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26505 	};
26506 
26507 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26508 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26509 	    KSTAT_FLAG_VIRTUAL, stackid);
26510 
26511 	if (ksp == NULL)
26512 		return (NULL);
26513 
26514 	bcopy(&template, tcps_statisticsp, sizeof (template));
26515 	ksp->ks_data = (void *)tcps_statisticsp;
26516 	ksp->ks_private = (void *)(uintptr_t)stackid;
26517 
26518 	kstat_install(ksp);
26519 	return (ksp);
26520 }
26521 
26522 static void
26523 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26524 {
26525 	if (ksp != NULL) {
26526 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26527 		kstat_delete_netstack(ksp, stackid);
26528 	}
26529 }
26530 
26531 /*
26532  * TCP Kstats implementation
26533  */
26534 static void *
26535 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26536 {
26537 	kstat_t	*ksp;
26538 
26539 	tcp_named_kstat_t template = {
26540 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26541 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26542 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26543 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26544 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26545 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26546 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26547 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26548 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26549 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26550 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26551 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26552 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26553 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26554 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26555 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26556 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26557 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26558 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26559 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26560 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26561 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26562 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26563 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26564 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26565 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26566 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26567 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26568 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26569 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26570 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26571 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26572 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26573 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26574 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26575 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26576 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26577 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26578 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26579 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26580 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26581 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26582 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26583 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26584 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26585 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26586 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26587 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26588 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26589 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26590 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26591 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26592 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26593 	};
26594 
26595 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26596 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26597 
26598 	if (ksp == NULL)
26599 		return (NULL);
26600 
26601 	template.rtoAlgorithm.value.ui32 = 4;
26602 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26603 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26604 	template.maxConn.value.i32 = -1;
26605 
26606 	bcopy(&template, ksp->ks_data, sizeof (template));
26607 	ksp->ks_update = tcp_kstat_update;
26608 	ksp->ks_private = (void *)(uintptr_t)stackid;
26609 
26610 	kstat_install(ksp);
26611 	return (ksp);
26612 }
26613 
26614 static void
26615 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26616 {
26617 	if (ksp != NULL) {
26618 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26619 		kstat_delete_netstack(ksp, stackid);
26620 	}
26621 }
26622 
26623 static int
26624 tcp_kstat_update(kstat_t *kp, int rw)
26625 {
26626 	tcp_named_kstat_t *tcpkp;
26627 	tcp_t		*tcp;
26628 	connf_t		*connfp;
26629 	conn_t		*connp;
26630 	int 		i;
26631 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26632 	netstack_t	*ns;
26633 	tcp_stack_t	*tcps;
26634 	ip_stack_t	*ipst;
26635 
26636 	if ((kp == NULL) || (kp->ks_data == NULL))
26637 		return (EIO);
26638 
26639 	if (rw == KSTAT_WRITE)
26640 		return (EACCES);
26641 
26642 	ns = netstack_find_by_stackid(stackid);
26643 	if (ns == NULL)
26644 		return (-1);
26645 	tcps = ns->netstack_tcp;
26646 	if (tcps == NULL) {
26647 		netstack_rele(ns);
26648 		return (-1);
26649 	}
26650 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26651 
26652 	tcpkp->currEstab.value.ui32 = 0;
26653 
26654 	ipst = ns->netstack_ip;
26655 
26656 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26657 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26658 		connp = NULL;
26659 		while ((connp =
26660 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26661 			tcp = connp->conn_tcp;
26662 			switch (tcp_snmp_state(tcp)) {
26663 			case MIB2_TCP_established:
26664 			case MIB2_TCP_closeWait:
26665 				tcpkp->currEstab.value.ui32++;
26666 				break;
26667 			}
26668 		}
26669 	}
26670 
26671 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26672 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26673 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26674 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26675 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26676 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26677 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26678 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26679 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26680 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26681 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26682 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26683 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26684 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26685 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26686 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26687 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26688 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26689 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26690 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26691 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26692 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26693 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26694 	tcpkp->inDataInorderSegs.value.ui32 =
26695 	    tcps->tcps_mib.tcpInDataInorderSegs;
26696 	tcpkp->inDataInorderBytes.value.ui32 =
26697 	    tcps->tcps_mib.tcpInDataInorderBytes;
26698 	tcpkp->inDataUnorderSegs.value.ui32 =
26699 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26700 	tcpkp->inDataUnorderBytes.value.ui32 =
26701 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26702 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26703 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26704 	tcpkp->inDataPartDupSegs.value.ui32 =
26705 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26706 	tcpkp->inDataPartDupBytes.value.ui32 =
26707 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26708 	tcpkp->inDataPastWinSegs.value.ui32 =
26709 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26710 	tcpkp->inDataPastWinBytes.value.ui32 =
26711 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26712 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26713 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26714 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26715 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26716 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26717 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26718 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26719 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26720 	tcpkp->timKeepaliveProbe.value.ui32 =
26721 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26722 	tcpkp->timKeepaliveDrop.value.ui32 =
26723 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26724 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26725 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26726 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26727 	tcpkp->outSackRetransSegs.value.ui32 =
26728 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26729 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26730 
26731 	netstack_rele(ns);
26732 	return (0);
26733 }
26734 
26735 void
26736 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26737 {
26738 	uint16_t	hdr_len;
26739 	ipha_t		*ipha;
26740 	uint8_t		*nexthdrp;
26741 	tcph_t		*tcph;
26742 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26743 
26744 	/* Already has an eager */
26745 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26746 		TCP_STAT(tcps, tcp_reinput_syn);
26747 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26748 		    connp, SQTAG_TCP_REINPUT_EAGER);
26749 		return;
26750 	}
26751 
26752 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26753 	case IPV4_VERSION:
26754 		ipha = (ipha_t *)mp->b_rptr;
26755 		hdr_len = IPH_HDR_LENGTH(ipha);
26756 		break;
26757 	case IPV6_VERSION:
26758 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26759 		    &hdr_len, &nexthdrp)) {
26760 			CONN_DEC_REF(connp);
26761 			freemsg(mp);
26762 			return;
26763 		}
26764 		break;
26765 	}
26766 
26767 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26768 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26769 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26770 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26771 	}
26772 
26773 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26774 	    SQTAG_TCP_REINPUT);
26775 }
26776 
26777 static squeue_func_t
26778 tcp_squeue_switch(int val)
26779 {
26780 	squeue_func_t rval = squeue_fill;
26781 
26782 	switch (val) {
26783 	case 1:
26784 		rval = squeue_enter_nodrain;
26785 		break;
26786 	case 2:
26787 		rval = squeue_enter;
26788 		break;
26789 	default:
26790 		break;
26791 	}
26792 	return (rval);
26793 }
26794 
26795 /*
26796  * This is called once for each squeue - globally for all stack
26797  * instances.
26798  */
26799 static void
26800 tcp_squeue_add(squeue_t *sqp)
26801 {
26802 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26803 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
26804 
26805 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26806 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
26807 	    sqp, TCP_TIME_WAIT_DELAY);
26808 	if (tcp_free_list_max_cnt == 0) {
26809 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26810 			max_ncpus : boot_max_ncpus);
26811 
26812 		/*
26813 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26814 		 */
26815 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26816 			(tcp_ncpus * sizeof (tcp_t) * 100);
26817 	}
26818 	tcp_time_wait->tcp_free_list_cnt = 0;
26819 }
26820