xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision 11a8fa6cb17403e630122ac19b39a323c6e64142)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 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 
30 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
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/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/ethernet.h>
51 #include <sys/cpuvar.h>
52 #include <sys/dlpi.h>
53 #include <sys/multidata.h>
54 #include <sys/multidata_impl.h>
55 #include <sys/pattr.h>
56 #include <sys/policy.h>
57 #include <sys/zone.h>
58 
59 #include <sys/errno.h>
60 #include <sys/signal.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <netinet/in.h>
67 #include <netinet/tcp.h>
68 #include <netinet/ip6.h>
69 #include <netinet/icmp6.h>
70 #include <net/if.h>
71 #include <net/route.h>
72 #include <inet/ipsec_impl.h>
73 
74 #include <inet/common.h>
75 #include <inet/ip.h>
76 #include <inet/ip6.h>
77 #include <inet/ip_ndp.h>
78 #include <inet/mi.h>
79 #include <inet/mib2.h>
80 #include <inet/nd.h>
81 #include <inet/optcom.h>
82 #include <inet/snmpcom.h>
83 #include <inet/kstatcom.h>
84 #include <inet/tcp.h>
85 #include <net/pfkeyv2.h>
86 #include <inet/ipsec_info.h>
87 #include <inet/ipdrop.h>
88 #include <inet/tcp_trace.h>
89 
90 #include <inet/ipclassifier.h>
91 #include <inet/ip_ire.h>
92 #include <inet/ip_if.h>
93 #include <inet/ipp_common.h>
94 #include <sys/squeue.h>
95 
96 /*
97  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
98  *
99  * (Read the detailed design doc in PSARC case directory)
100  *
101  * The entire tcp state is contained in tcp_t and conn_t structure
102  * which are allocated in tandem using ipcl_conn_create() and passing
103  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
104  * the references on the tcp_t. The tcp_t structure is never compressed
105  * and packets always land on the correct TCP perimeter from the time
106  * eager is created till the time tcp_t dies (as such the old mentat
107  * TCP global queue is not used for detached state and no IPSEC checking
108  * is required). The global queue is still allocated to send out resets
109  * for connection which have no listeners and IP directly calls
110  * tcp_xmit_listeners_reset() which does any policy check.
111  *
112  * Protection and Synchronisation mechanism:
113  *
114  * The tcp data structure does not use any kind of lock for protecting
115  * its state but instead uses 'squeues' for mutual exclusion from various
116  * read and write side threads. To access a tcp member, the thread should
117  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
118  * squeue_fill). Since the squeues allow a direct function call, caller
119  * can pass any tcp function having prototype of edesc_t as argument
120  * (different from traditional STREAMs model where packets come in only
121  * designated entry points). The list of functions that can be directly
122  * called via squeue are listed before the usual function prototype.
123  *
124  * Referencing:
125  *
126  * TCP is MT-Hot and we use a reference based scheme to make sure that the
127  * tcp structure doesn't disappear when its needed. When the application
128  * creates an outgoing connection or accepts an incoming connection, we
129  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
130  * The IP reference is just a symbolic reference since ip_tcpclose()
131  * looks at tcp structure after tcp_close_output() returns which could
132  * have dropped the last TCP reference. So as long as the connection is
133  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
134  * conn_t. The classifier puts its own reference when the connection is
135  * inserted in listen or connected hash. Anytime a thread needs to enter
136  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
137  * on write side or by doing a classify on read side and then puts a
138  * reference on the conn before doing squeue_enter/tryenter/fill. For
139  * read side, the classifier itself puts the reference under fanout lock
140  * to make sure that tcp can't disappear before it gets processed. The
141  * squeue will drop this reference automatically so the called function
142  * doesn't have to do a DEC_REF.
143  *
144  * Opening a new connection:
145  *
146  * The outgoing connection open is pretty simple. ip_tcpopen() does the
147  * work in creating the conn/tcp structure and initializing it. The
148  * squeue assignment is done based on the CPU the application
149  * is running on. So for outbound connections, processing is always done
150  * on application CPU which might be different from the incoming CPU
151  * being interrupted by the NIC. An optimal way would be to figure out
152  * the NIC <-> CPU binding at listen time, and assign the outgoing
153  * connection to the squeue attached to the CPU that will be interrupted
154  * for incoming packets (we know the NIC based on the bind IP address).
155  * This might seem like a problem if more data is going out but the
156  * fact is that in most cases the transmit is ACK driven transmit where
157  * the outgoing data normally sits on TCP's xmit queue waiting to be
158  * transmitted.
159  *
160  * Accepting a connection:
161  *
162  * This is a more interesting case because of various races involved in
163  * establishing a eager in its own perimeter. Read the meta comment on
164  * top of tcp_conn_request(). But briefly, the squeue is picked by
165  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
166  *
167  * Closing a connection:
168  *
169  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
170  * via squeue to do the close and mark the tcp as detached if the connection
171  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
172  * reference but tcp_close() drop IP's reference always. So if tcp was
173  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
174  * and 1 because it is in classifier's connected hash. This is the condition
175  * we use to determine that its OK to clean up the tcp outside of squeue
176  * when time wait expires (check the ref under fanout and conn_lock and
177  * if it is 2, remove it from fanout hash and kill it).
178  *
179  * Although close just drops the necessary references and marks the
180  * tcp_detached state, tcp_close needs to know the tcp_detached has been
181  * set (under squeue) before letting the STREAM go away (because a
182  * inbound packet might attempt to go up the STREAM while the close
183  * has happened and tcp_detached is not set). So a special lock and
184  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
185  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
186  * tcp_detached.
187  *
188  * Special provisions and fast paths:
189  *
190  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
191  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
192  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
193  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
194  * check to send packets directly to tcp_rput_data via squeue. Everyone
195  * else comes through tcp_input() on the read side.
196  *
197  * We also make special provisions for sockfs by marking tcp_issocket
198  * whenever we have only sockfs on top of TCP. This allows us to skip
199  * putting the tcp in acceptor hash since a sockfs listener can never
200  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
201  * since eager has already been allocated and the accept now happens
202  * on acceptor STREAM. There is a big blob of comment on top of
203  * tcp_conn_request explaining the new accept. When socket is POP'd,
204  * sockfs sends us an ioctl to mark the fact and we go back to old
205  * behaviour. Once tcp_issocket is unset, its never set for the
206  * life of that connection.
207  *
208  * IPsec notes :
209  *
210  * Since a packet is always executed on the correct TCP perimeter
211  * all IPsec processing is defered to IP including checking new
212  * connections and setting IPSEC policies for new connection. The
213  * only exception is tcp_xmit_listeners_reset() which is called
214  * directly from IP and needs to policy check to see if TH_RST
215  * can be sent out.
216  */
217 
218 
219 extern major_t TCP6_MAJ;
220 
221 /*
222  * Values for squeue switch:
223  * 1: squeue_enter_nodrain
224  * 2: squeue_enter
225  * 3: squeue_fill
226  */
227 int tcp_squeue_close = 2;
228 int tcp_squeue_wput = 2;
229 
230 squeue_func_t tcp_squeue_close_proc;
231 squeue_func_t tcp_squeue_wput_proc;
232 
233 extern vmem_t *ip_minor_arena;
234 
235 /*
236  * This controls how tiny a write must be before we try to copy it
237  * into the the mblk on the tail of the transmit queue.  Not much
238  * speedup is observed for values larger than sixteen.  Zero will
239  * disable the optimisation.
240  */
241 int tcp_tx_pull_len = 16;
242 
243 /*
244  * TCP Statistics.
245  *
246  * How TCP statistics work.
247  *
248  * There are two types of statistics invoked by two macros.
249  *
250  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
251  * supposed to be used in non MT-hot paths of the code.
252  *
253  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
254  * supposed to be used for DEBUG purposes and may be used on a hot path.
255  *
256  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
257  * (use "kstat tcp" to get them).
258  *
259  * There is also additional debugging facility that marks tcp_clean_death()
260  * instances and saves them in tcp_t structure. It is triggered by
261  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
262  * tcp_clean_death() calls that counts the number of times each tag was hit. It
263  * is triggered by TCP_CLD_COUNTERS define.
264  *
265  * How to add new counters.
266  *
267  * 1) Add a field in the tcp_stat structure describing your counter.
268  * 2) Add a line in tcp_statistics with the name of the counter.
269  *
270  *    IMPORTANT!! - make sure that both are in sync !!
271  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
272  *
273  * Please avoid using private counters which are not kstat-exported.
274  *
275  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
276  * in tcp_t structure.
277  *
278  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
279  */
280 
281 #define	TCP_COUNTERS 1
282 #define	TCP_CLD_COUNTERS 0
283 
284 #ifndef TCP_DEBUG_COUNTER
285 #ifdef DEBUG
286 #define	TCP_DEBUG_COUNTER 1
287 #else
288 #define	TCP_DEBUG_COUNTER 0
289 #endif
290 #endif
291 
292 
293 #define	TCP_TAG_CLEAN_DEATH 1
294 #define	TCP_MAX_CLEAN_DEATH_TAG 32
295 
296 #ifdef lint
297 static int _lint_dummy_;
298 #endif
299 
300 #if TCP_COUNTERS
301 #define	TCP_STAT(x)		(tcp_statistics.x.value.ui64++)
302 #define	TCP_STAT_UPDATE(x, n)	(tcp_statistics.x.value.ui64 += (n))
303 #define	TCP_STAT_SET(x, n)	(tcp_statistics.x.value.ui64 = (n))
304 #elif defined(lint)
305 #define	TCP_STAT(x)		ASSERT(_lint_dummy_ == 0);
306 #define	TCP_STAT_UPDATE(x, n)	ASSERT(_lint_dummy_ == 0);
307 #define	TCP_STAT_SET(x, n)	ASSERT(_lint_dummy_ == 0);
308 #else
309 #define	TCP_STAT(x)
310 #define	TCP_STAT_UPDATE(x, n)
311 #define	TCP_STAT_SET(x, n)
312 #endif
313 
314 #if TCP_CLD_COUNTERS
315 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
316 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
317 #elif defined(lint)
318 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
319 #else
320 #define	TCP_CLD_STAT(x)
321 #endif
322 
323 #if TCP_DEBUG_COUNTER
324 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
325 #elif defined(lint)
326 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
327 #else
328 #define	TCP_DBGSTAT(x)
329 #endif
330 
331 typedef struct tcp_stat {
332 	kstat_named_t	tcp_time_wait;
333 	kstat_named_t	tcp_time_wait_syn;
334 	kstat_named_t	tcp_time_wait_syn_success;
335 	kstat_named_t	tcp_time_wait_syn_fail;
336 	kstat_named_t	tcp_reinput_syn;
337 	kstat_named_t	tcp_ip_output;
338 	kstat_named_t	tcp_detach_non_time_wait;
339 	kstat_named_t	tcp_detach_time_wait;
340 	kstat_named_t	tcp_time_wait_reap;
341 	kstat_named_t	tcp_clean_death_nondetached;
342 	kstat_named_t	tcp_reinit_calls;
343 	kstat_named_t	tcp_eager_err1;
344 	kstat_named_t	tcp_eager_err2;
345 	kstat_named_t	tcp_eager_blowoff_calls;
346 	kstat_named_t	tcp_eager_blowoff_q;
347 	kstat_named_t	tcp_eager_blowoff_q0;
348 	kstat_named_t	tcp_not_hard_bound;
349 	kstat_named_t	tcp_no_listener;
350 	kstat_named_t	tcp_found_eager;
351 	kstat_named_t	tcp_wrong_queue;
352 	kstat_named_t	tcp_found_eager_binding1;
353 	kstat_named_t	tcp_found_eager_bound1;
354 	kstat_named_t	tcp_eager_has_listener1;
355 	kstat_named_t	tcp_open_alloc;
356 	kstat_named_t	tcp_open_detached_alloc;
357 	kstat_named_t	tcp_rput_time_wait;
358 	kstat_named_t	tcp_listendrop;
359 	kstat_named_t	tcp_listendropq0;
360 	kstat_named_t	tcp_wrong_rq;
361 	kstat_named_t	tcp_rsrv_calls;
362 	kstat_named_t	tcp_eagerfree2;
363 	kstat_named_t	tcp_eagerfree3;
364 	kstat_named_t	tcp_eagerfree4;
365 	kstat_named_t	tcp_eagerfree5;
366 	kstat_named_t	tcp_timewait_syn_fail;
367 	kstat_named_t	tcp_listen_badflags;
368 	kstat_named_t	tcp_timeout_calls;
369 	kstat_named_t	tcp_timeout_cached_alloc;
370 	kstat_named_t	tcp_timeout_cancel_reqs;
371 	kstat_named_t	tcp_timeout_canceled;
372 	kstat_named_t	tcp_timermp_alloced;
373 	kstat_named_t	tcp_timermp_freed;
374 	kstat_named_t	tcp_timermp_allocfail;
375 	kstat_named_t	tcp_timermp_allocdblfail;
376 	kstat_named_t	tcp_push_timer_cnt;
377 	kstat_named_t	tcp_ack_timer_cnt;
378 	kstat_named_t	tcp_ire_null1;
379 	kstat_named_t	tcp_ire_null;
380 	kstat_named_t	tcp_ip_send;
381 	kstat_named_t	tcp_ip_ire_send;
382 	kstat_named_t   tcp_wsrv_called;
383 	kstat_named_t   tcp_flwctl_on;
384 	kstat_named_t	tcp_timer_fire_early;
385 	kstat_named_t	tcp_timer_fire_miss;
386 	kstat_named_t	tcp_freelist_cleanup;
387 	kstat_named_t	tcp_rput_v6_error;
388 	kstat_named_t	tcp_out_sw_cksum;
389 	kstat_named_t	tcp_zcopy_on;
390 	kstat_named_t	tcp_zcopy_off;
391 	kstat_named_t	tcp_zcopy_backoff;
392 	kstat_named_t	tcp_zcopy_disable;
393 	kstat_named_t	tcp_mdt_pkt_out;
394 	kstat_named_t	tcp_mdt_pkt_out_v4;
395 	kstat_named_t	tcp_mdt_pkt_out_v6;
396 	kstat_named_t	tcp_mdt_discarded;
397 	kstat_named_t	tcp_mdt_conn_halted1;
398 	kstat_named_t	tcp_mdt_conn_halted2;
399 	kstat_named_t	tcp_mdt_conn_halted3;
400 	kstat_named_t	tcp_mdt_conn_resumed1;
401 	kstat_named_t	tcp_mdt_conn_resumed2;
402 	kstat_named_t	tcp_mdt_legacy_small;
403 	kstat_named_t	tcp_mdt_legacy_all;
404 	kstat_named_t	tcp_mdt_legacy_ret;
405 	kstat_named_t	tcp_mdt_allocfail;
406 	kstat_named_t	tcp_mdt_addpdescfail;
407 	kstat_named_t	tcp_mdt_allocd;
408 	kstat_named_t	tcp_mdt_linked;
409 	kstat_named_t	tcp_fusion_flowctl;
410 	kstat_named_t	tcp_fusion_backenabled;
411 	kstat_named_t	tcp_fusion_urg;
412 	kstat_named_t	tcp_fusion_putnext;
413 	kstat_named_t	tcp_fusion_unfusable;
414 	kstat_named_t	tcp_fusion_aborted;
415 	kstat_named_t	tcp_fusion_unqualified;
416 	kstat_named_t	tcp_in_ack_unsent_drop;
417 } tcp_stat_t;
418 
419 #if (TCP_COUNTERS || TCP_DEBUG_COUNTER)
420 static tcp_stat_t tcp_statistics = {
421 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
422 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
423 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
424 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
425 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
426 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
427 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
428 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
429 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
430 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
431 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
432 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
433 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
434 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
435 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
436 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
437 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
438 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
439 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
440 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
441 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
442 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
443 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
444 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
445 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
446 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
447 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
448 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
449 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
450 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
451 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
452 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
453 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
454 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
455 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
456 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
457 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
458 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
459 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
460 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
461 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
462 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
463 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
464 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
465 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
466 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
467 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
468 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
469 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
470 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
471 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
472 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
473 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
474 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
475 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
476 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
477 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
478 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
479 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
480 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
481 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
482 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
483 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
484 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
485 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
486 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
487 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
488 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
489 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
490 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
491 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
492 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
493 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
494 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
495 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
496 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
497 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
498 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
499 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
500 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
501 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
502 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
503 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
504 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
505 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
506 };
507 
508 static kstat_t *tcp_kstat;
509 
510 #endif
511 
512 /*
513  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
514  * tcp write side.
515  */
516 #define	CALL_IP_WPUT(connp, q, mp) {					\
517 	ASSERT(((q)->q_flag & QREADR) == 0);				\
518 	TCP_DBGSTAT(tcp_ip_output);					\
519 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
520 }
521 
522 /*
523  * Was this tcp created via socket() interface?
524  */
525 #define	TCP_IS_SOCKET(tcp) ((tcp)->tcp_issocket)
526 
527 
528 /* Macros for timestamp comparisons */
529 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
530 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
531 
532 /*
533  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
534  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
535  * by adding three components: a time component which grows by 1 every 4096
536  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
537  * a per-connection component which grows by 125000 for every new connection;
538  * and an "extra" component that grows by a random amount centered
539  * approximately on 64000.  This causes the the ISS generator to cycle every
540  * 4.89 hours if no TCP connections are made, and faster if connections are
541  * made.
542  *
543  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
544  * components: a time component which grows by 250000 every second; and
545  * a per-connection component which grows by 125000 for every new connections.
546  *
547  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
548  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
549  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
550  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
551  * password.
552  */
553 #define	ISS_INCR	250000
554 #define	ISS_NSEC_SHT	12
555 
556 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
557 static kmutex_t tcp_iss_key_lock;
558 static MD5_CTX tcp_iss_key;
559 static sin_t	sin_null;	/* Zero address for quick clears */
560 static sin6_t	sin6_null;	/* Zero address for quick clears */
561 
562 /* Packet dropper for TCP IPsec policy drops. */
563 static ipdropper_t tcp_dropper;
564 
565 /*
566  * This implementation follows the 4.3BSD interpretation of the urgent
567  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
568  * incompatible changes in protocols like telnet and rlogin.
569  */
570 #define	TCP_OLD_URP_INTERPRETATION	1
571 
572 #define	TCP_IS_DETACHED(tcp)		((tcp)->tcp_detached)
573 
574 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
575 	(TCP_IS_DETACHED(tcp) && \
576 	    (!(tcp)->tcp_hard_binding))
577 
578 /*
579  * TCP reassembly macros.  We hide starting and ending sequence numbers in
580  * b_next and b_prev of messages on the reassembly queue.  The messages are
581  * chained using b_cont.  These macros are used in tcp_reass() so we don't
582  * have to see the ugly casts and assignments.
583  */
584 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
585 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
586 					(mblk_t *)(uintptr_t)(u))
587 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
588 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
589 					(mblk_t *)(uintptr_t)(u))
590 
591 /*
592  * Implementation of TCP Timers.
593  * =============================
594  *
595  * INTERFACE:
596  *
597  * There are two basic functions dealing with tcp timers:
598  *
599  *	timeout_id_t	tcp_timeout(connp, func, time)
600  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
601  *	TCP_TIMER_RESTART(tcp, intvl)
602  *
603  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
604  * after 'time' ticks passed. The function called by timeout() must adhere to
605  * the same restrictions as a driver soft interrupt handler - it must not sleep
606  * or call other functions that might sleep. The value returned is the opaque
607  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
608  * cancel the request. The call to tcp_timeout() may fail in which case it
609  * returns zero. This is different from the timeout(9F) function which never
610  * fails.
611  *
612  * The call-back function 'func' always receives 'connp' as its single
613  * argument. It is always executed in the squeue corresponding to the tcp
614  * structure. The tcp structure is guaranteed to be present at the time the
615  * call-back is called.
616  *
617  * NOTE: The call-back function 'func' is never called if tcp is in
618  * 	the TCPS_CLOSED state.
619  *
620  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
621  * request. locks acquired by the call-back routine should not be held across
622  * the call to tcp_timeout_cancel() or a deadlock may result.
623  *
624  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
625  * Otherwise, it returns an integer value greater than or equal to 0. In
626  * particular, if the call-back function is already placed on the squeue, it can
627  * not be canceled.
628  *
629  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
630  * 	within squeue context corresponding to the tcp instance. Since the
631  *	call-back is also called via the same squeue, there are no race
632  *	conditions described in untimeout(9F) manual page since all calls are
633  *	strictly serialized.
634  *
635  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
636  *	stored in tcp_timer_tid and starts a new one using
637  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
638  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
639  *	field.
640  *
641  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
642  *	call-back may still be called, so it is possible tcp_timer() will be
643  *	called several times. This should not be a problem since tcp_timer()
644  *	should always check the tcp instance state.
645  *
646  *
647  * IMPLEMENTATION:
648  *
649  * TCP timers are implemented using three-stage process. The call to
650  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
651  * when the timer expires. The tcp_timer_callback() arranges the call of the
652  * tcp_timer_handler() function via squeue corresponding to the tcp
653  * instance. The tcp_timer_handler() calls actual requested timeout call-back
654  * and passes tcp instance as an argument to it. Information is passed between
655  * stages using the tcp_timer_t structure which contains the connp pointer, the
656  * tcp call-back to call and the timeout id returned by the timeout(9F).
657  *
658  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
659  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
660  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
661  * returns the pointer to this mblk.
662  *
663  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
664  * looks like a normal mblk without actual dblk attached to it.
665  *
666  * To optimize performance each tcp instance holds a small cache of timer
667  * mblocks. In the current implementation it caches up to two timer mblocks per
668  * tcp instance. The cache is preserved over tcp frees and is only freed when
669  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
670  * timer processing happens on a corresponding squeue, the cache manipulation
671  * does not require any locks. Experiments show that majority of timer mblocks
672  * allocations are satisfied from the tcp cache and do not involve kmem calls.
673  *
674  * The tcp_timeout() places a refhold on the connp instance which guarantees
675  * that it will be present at the time the call-back function fires. The
676  * tcp_timer_handler() drops the reference after calling the call-back, so the
677  * call-back function does not need to manipulate the references explicitly.
678  */
679 
680 typedef struct tcp_timer_s {
681 	conn_t	*connp;
682 	void 	(*tcpt_proc)(void *);
683 	timeout_id_t   tcpt_tid;
684 } tcp_timer_t;
685 
686 static kmem_cache_t *tcp_timercache;
687 kmem_cache_t	*tcp_sack_info_cache;
688 kmem_cache_t	*tcp_iphc_cache;
689 
690 #define	TCP_TIMER(tcp, f, tim) tcp_timeout(tcp->tcp_connp, f, tim)
691 #define	TCP_TIMER_CANCEL(tcp, id) tcp_timeout_cancel(tcp->tcp_connp, id)
692 
693 /*
694  * To restart the TCP retransmission timer.
695  */
696 #define	TCP_TIMER_RESTART(tcp, intvl) \
697 { \
698 	if ((tcp)->tcp_timer_tid != 0) { \
699 		(void) TCP_TIMER_CANCEL((tcp),	\
700 					(tcp)->tcp_timer_tid); \
701 	} \
702 	(tcp)->tcp_timer_tid = TCP_TIMER((tcp), tcp_timer, \
703 	    MSEC_TO_TICK(intvl)); \
704 }
705 
706 /*
707  * For scalability, we must not run a timer for every TCP connection
708  * in TIME_WAIT state.  To see why, consider (for time wait interval of
709  * 4 minutes):
710  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
711  *
712  * This list is ordered by time, so you need only delete from the head
713  * until you get to entries which aren't old enough to delete yet.
714  * The list consists of only the detached TIME_WAIT connections.
715  *
716  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
717  * becomes detached TIME_WAIT (either by changing the state and already
718  * being detached or the other way around). This means that the TIME_WAIT
719  * state can be extended (up to doubled) if the connection doesn't become
720  * detached for a long time.
721  *
722  * The list manipulations (including tcp_time_wait_next/prev)
723  * are protected by the tcp_time_wait_lock. The content of the
724  * detached TIME_WAIT connections is protected by the normal perimeters.
725  */
726 
727 typedef struct tcp_squeue_priv_s {
728 	kmutex_t	tcp_time_wait_lock;
729 				/* Protects the next 3 globals */
730 	timeout_id_t	tcp_time_wait_tid;
731 	tcp_t		*tcp_time_wait_head;
732 	tcp_t		*tcp_time_wait_tail;
733 	tcp_t		*tcp_free_list;
734 } tcp_squeue_priv_t;
735 
736 /*
737  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
738  * Running it every 5 seconds seems to give the best results.
739  */
740 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
741 
742 
743 #define	TCP_XMIT_LOWATER	4096
744 #define	TCP_XMIT_HIWATER	49152
745 #define	TCP_RECV_LOWATER	2048
746 #define	TCP_RECV_HIWATER	49152
747 
748 /*
749  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
750  */
751 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
752 
753 #define	TIDUSZ	4096	/* transport interface data unit size */
754 
755 /*
756  * Bind hash list size and has function.  It has to be a power of 2 for
757  * hashing.
758  */
759 #define	TCP_BIND_FANOUT_SIZE	512
760 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
761 /*
762  * Size of listen and acceptor hash list.  It has to be a power of 2 for
763  * hashing.
764  */
765 #define	TCP_FANOUT_SIZE		256
766 
767 #ifdef	_ILP32
768 #define	TCP_ACCEPTOR_HASH(accid)					\
769 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
770 #else
771 #define	TCP_ACCEPTOR_HASH(accid)					\
772 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
773 #endif	/* _ILP32 */
774 
775 #define	IP_ADDR_CACHE_SIZE	2048
776 #define	IP_ADDR_CACHE_HASH(faddr)					\
777 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
778 
779 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
780 #define	TCP_HSP_HASH_SIZE 256
781 
782 #define	TCP_HSP_HASH(addr)					\
783 	(((addr>>24) ^ (addr >>16) ^			\
784 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
785 
786 /*
787  * TCP options struct returned from tcp_parse_options.
788  */
789 typedef struct tcp_opt_s {
790 	uint32_t	tcp_opt_mss;
791 	uint32_t	tcp_opt_wscale;
792 	uint32_t	tcp_opt_ts_val;
793 	uint32_t	tcp_opt_ts_ecr;
794 	tcp_t		*tcp;
795 } tcp_opt_t;
796 
797 /*
798  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
799  */
800 
801 #ifdef _BIG_ENDIAN
802 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
803 	(TCPOPT_TSTAMP << 8) | 10)
804 #else
805 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
806 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
807 #endif
808 
809 /*
810  * Flags returned from tcp_parse_options.
811  */
812 #define	TCP_OPT_MSS_PRESENT	1
813 #define	TCP_OPT_WSCALE_PRESENT	2
814 #define	TCP_OPT_TSTAMP_PRESENT	4
815 #define	TCP_OPT_SACK_OK_PRESENT	8
816 #define	TCP_OPT_SACK_PRESENT	16
817 
818 /* TCP option length */
819 #define	TCPOPT_NOP_LEN		1
820 #define	TCPOPT_MAXSEG_LEN	4
821 #define	TCPOPT_WS_LEN		3
822 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
823 #define	TCPOPT_TSTAMP_LEN	10
824 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
825 #define	TCPOPT_SACK_OK_LEN	2
826 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
827 #define	TCPOPT_REAL_SACK_LEN	4
828 #define	TCPOPT_MAX_SACK_LEN	36
829 #define	TCPOPT_HEADER_LEN	2
830 
831 /* TCP cwnd burst factor. */
832 #define	TCP_CWND_INFINITE	65535
833 #define	TCP_CWND_SS		3
834 #define	TCP_CWND_NORMAL		5
835 
836 /* Maximum TCP initial cwin (start/restart). */
837 #define	TCP_MAX_INIT_CWND	8
838 
839 /*
840  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
841  * either tcp_slow_start_initial or tcp_slow_start_after idle
842  * depending on the caller.  If the upper layer has not used the
843  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
844  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
845  * If the upper layer has changed set the tcp_init_cwnd, just use
846  * it to calculate the tcp_cwnd.
847  */
848 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
849 {									\
850 	if ((tcp)->tcp_init_cwnd == 0) {				\
851 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
852 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
853 	} else {							\
854 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
855 	}								\
856 	tcp->tcp_cwnd_cnt = 0;						\
857 }
858 
859 /* TCP Timer control structure */
860 typedef struct tcpt_s {
861 	pfv_t	tcpt_pfv;	/* The routine we are to call */
862 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
863 } tcpt_t;
864 
865 /* Host Specific Parameter structure */
866 typedef struct tcp_hsp {
867 	struct tcp_hsp	*tcp_hsp_next;
868 	in6_addr_t	tcp_hsp_addr_v6;
869 	in6_addr_t	tcp_hsp_subnet_v6;
870 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
871 	int32_t		tcp_hsp_sendspace;
872 	int32_t		tcp_hsp_recvspace;
873 	int32_t		tcp_hsp_tstamp;
874 } tcp_hsp_t;
875 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
876 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
877 
878 /*
879  * Functions called directly via squeue having a prototype of edesc_t.
880  */
881 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
882 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
883 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
884 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
885 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
886 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
887 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
888 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
889 static void	tcp_output(void *arg, mblk_t *mp, void *arg2);
890 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
891 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
892 
893 
894 /* Prototype for TCP functions */
895 static void	tcp_random_init(void);
896 int		tcp_random(void);
897 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
898 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
899 		    tcp_t *eager);
900 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
901 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
902     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
903     boolean_t user_specified);
904 static void	tcp_closei_local(tcp_t *tcp);
905 static void	tcp_close_detached(tcp_t *tcp);
906 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
907 			mblk_t *idmp, mblk_t **defermp);
908 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
909 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
910 		    in_port_t dstport, uint_t srcid);
911 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
912 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
913 		    uint32_t scope_id);
914 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
915 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
916 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
917 static char	*tcp_display(tcp_t *tcp, char *, char);
918 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
919 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
920 static void	tcp_eager_unlink(tcp_t *tcp);
921 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
922 		    int unixerr);
923 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
924 		    int tlierr, int unixerr);
925 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
926 		    cred_t *cr);
927 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
928 		    char *value, caddr_t cp, cred_t *cr);
929 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
930 		    char *value, caddr_t cp, cred_t *cr);
931 static int	tcp_tpistate(tcp_t *tcp);
932 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
933     int caller_holds_lock);
934 static void	tcp_bind_hash_remove(tcp_t *tcp);
935 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
936 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
937 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
938 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
939 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
940 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
941 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
942 static int	tcp_header_init_ipv4(tcp_t *tcp);
943 static int	tcp_header_init_ipv6(tcp_t *tcp);
944 int		tcp_init(tcp_t *tcp, queue_t *q);
945 static int	tcp_init_values(tcp_t *tcp);
946 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
947 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
948 		    t_scalar_t addr_length);
949 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
950 static void	tcp_ip_notify(tcp_t *tcp);
951 static mblk_t	*tcp_ire_mp(mblk_t *mp);
952 static void	tcp_iss_init(tcp_t *tcp);
953 static void	tcp_keepalive_killer(void *arg);
954 static int	tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk);
955 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
956 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
957 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
958 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
959 static boolean_t tcp_allow_connopt_set(int level, int name);
960 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
961 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
962 static int	tcp_opt_get_user(ipha_t *ipha, uchar_t *ptr);
963 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
964 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
965 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
966 		    mblk_t *mblk);
967 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
968 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
969 		    uchar_t *ptr, uint_t len);
970 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
971 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
972 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
973 		    caddr_t cp, cred_t *cr);
974 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
975 		    caddr_t cp, cred_t *cr);
976 static void	tcp_iss_key_init(uint8_t *phrase, int len);
977 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
978 		    caddr_t cp, cred_t *cr);
979 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
980 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
981 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
982 static void	tcp_reinit(tcp_t *tcp);
983 static void	tcp_reinit_values(tcp_t *tcp);
984 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
985 		    tcp_t *thisstream, cred_t *cr);
986 
987 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
988 static void	tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len);
989 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
990 static boolean_t tcp_send_rst_chk(void);
991 static void	tcp_ss_rexmit(tcp_t *tcp);
992 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
993 static void	tcp_process_options(tcp_t *, tcph_t *);
994 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
995 static void	tcp_rsrv(queue_t *q);
996 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
997 static int	tcp_snmp_get(queue_t *q, mblk_t *mpctl);
998 static int	tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr,
999 		    int len);
1000 static int	tcp_snmp_state(tcp_t *tcp);
1001 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
1002 		    cred_t *cr);
1003 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
1004 		    cred_t *cr);
1005 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
1006 		    cred_t *cr);
1007 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
1008 		    cred_t *cr);
1009 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
1010 		    cred_t *cr);
1011 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
1012 		    caddr_t cp, cred_t *cr);
1013 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
1014 		    caddr_t cp, cred_t *cr);
1015 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
1016 		    cred_t *cr);
1017 static void	tcp_timer(void *arg);
1018 static void	tcp_timer_callback(void *);
1019 static in_port_t tcp_update_next_port(in_port_t port, boolean_t random);
1020 static in_port_t tcp_get_next_priv_port(void);
1021 static void	tcp_wput(queue_t *q, mblk_t *mp);
1022 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
1023 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
1024 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
1025 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
1026 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
1027 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
1028 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
1029 		    const int num_sack_blk, int *usable, uint_t *snxt,
1030 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
1031 		    const int mdt_thres);
1032 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
1033 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
1034 		    const int num_sack_blk, int *usable, uint_t *snxt,
1035 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
1036 		    const int mdt_thres);
1037 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
1038 		    int num_sack_blk);
1039 static void	tcp_wsrv(queue_t *q);
1040 static int	tcp_xmit_end(tcp_t *tcp);
1041 void		tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len);
1042 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
1043 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
1044 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
1045 static void	tcp_ack_timer(void *arg);
1046 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
1047 static void	tcp_push_timer(void *arg);
1048 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
1049 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
1050 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
1051 		    uint32_t ack, int ctl);
1052 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
1053 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
1054 static int	setmaxps(queue_t *q, int maxpsz);
1055 static void	tcp_set_rto(tcp_t *, time_t);
1056 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
1057 		    boolean_t, boolean_t);
1058 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
1059 		    boolean_t ipsec_mctl);
1060 static boolean_t tcp_cmpbuf(void *a, uint_t alen,
1061 		    boolean_t b_valid, void *b, uint_t blen);
1062 static boolean_t tcp_allocbuf(void **dstp, uint_t *dstlenp,
1063 		    boolean_t src_valid, void *src, uint_t srclen);
1064 static void	tcp_savebuf(void **dstp, uint_t *dstlenp,
1065 		    boolean_t src_valid, void *src, uint_t srclen);
1066 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
1067 		    char *opt, int optlen);
1068 static int	tcp_pkt_set(uchar_t *, uint_t, uchar_t **, uint_t *);
1069 static int	tcp_build_hdrs(queue_t *, tcp_t *);
1070 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
1071 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
1072 		    tcph_t *tcph);
1073 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
1074 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
1075 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
1076 boolean_t	tcp_reserved_port_check(in_port_t);
1077 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
1078 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
1079 static void	tcp_timers_stop(tcp_t *);
1080 static timeout_id_t tcp_timeout(conn_t *, void (*)(void *), clock_t);
1081 static clock_t	tcp_timeout_cancel(conn_t *, timeout_id_t);
1082 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
1083 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
1084 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
1085 		    const boolean_t, const uint32_t, const uint32_t,
1086 		    const uint32_t, const uint32_t);
1087 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
1088 		    const uint_t, const uint_t, boolean_t *);
1089 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
1090 extern mblk_t	*tcp_timermp_alloc(int);
1091 extern void	tcp_timermp_free(tcp_t *);
1092 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
1093 static void	tcp_stop_lingering(tcp_t *tcp);
1094 static void	tcp_close_linger_timeout(void *arg);
1095 void		tcp_ddi_init(void);
1096 void		tcp_ddi_destroy(void);
1097 static void	tcp_kstat_init(void);
1098 static void	tcp_kstat_fini(void);
1099 static int	tcp_kstat_update(kstat_t *kp, int rw);
1100 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
1101 conn_t		*tcp_get_next_conn(connf_t *, conn_t *);
1102 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
1103 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
1104 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
1105 			tcph_t *tcph, mblk_t *idmp);
1106 static squeue_func_t tcp_squeue_switch(int);
1107 
1108 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
1109 static int	tcp_close(queue_t *, int);
1110 static int	tcpclose_accept(queue_t *);
1111 static int	tcp_modclose(queue_t *);
1112 static void	tcp_wput_mod(queue_t *, mblk_t *);
1113 
1114 static void	tcp_squeue_add(squeue_t *);
1115 static boolean_t tcp_zcopy_check(tcp_t *);
1116 static void	tcp_zcopy_notify(tcp_t *);
1117 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
1118 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
1119 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
1120 
1121 static void	tcp_fuse(tcp_t *, uchar_t *, tcph_t *);
1122 static void	tcp_unfuse(tcp_t *);
1123 static boolean_t tcp_fuse_output(tcp_t *, mblk_t *);
1124 static void	tcp_fuse_output_urg(tcp_t *, mblk_t *);
1125 static boolean_t tcp_fuse_rcv_drain(queue_t *, tcp_t *, mblk_t **);
1126 
1127 extern mblk_t	*allocb_tryhard(size_t);
1128 
1129 /*
1130  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
1131  *
1132  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
1133  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
1134  * (defined in tcp.h) needs to be filled in and passed into the kernel
1135  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
1136  * structure contains the four-tuple of a TCP connection and a range of TCP
1137  * states (specified by ac_start and ac_end). The use of wildcard addresses
1138  * and ports is allowed. Connections with a matching four tuple and a state
1139  * within the specified range will be aborted. The valid states for the
1140  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1141  * inclusive.
1142  *
1143  * An application which has its connection aborted by this ioctl will receive
1144  * an error that is dependent on the connection state at the time of the abort.
1145  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1146  * though a RST packet has been received.  If the connection state is equal to
1147  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1148  * and all resources associated with the connection will be freed.
1149  */
1150 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1151 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1152 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1153 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1154 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1155 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1156     boolean_t);
1157 
1158 /*
1159  * Write-side flow-control is implemented via the per instance STREAMS
1160  * write-side Q by explicitly setting QFULL to stop the flow of mblk_t(s)
1161  * and clearing QFULL and calling qbackenable() to restart the flow based
1162  * on the number of TCP unsent bytes (i.e. those not on the wire waiting
1163  * for a remote ACK).
1164  *
1165  * This is different than a standard STREAMS kmod which when using the
1166  * STREAMS Q the framework would automatictly flow-control based on the
1167  * defined hiwat/lowat values as mblk_t's are enqueued/dequeued.
1168  *
1169  * As of FireEngine TCP write-side flow-control needs to take into account
1170  * both the unsent tcp_xmit list bytes but also any squeue_t enqueued bytes
1171  * (i.e. from tcp_wput() -> tcp_output()).
1172  *
1173  * This is accomplished by adding a new tcp_t fields, tcp_squeue_bytes, to
1174  * count the number of bytes enqueued by tcp_wput() and the number of bytes
1175  * dequeued and processed by tcp_output().
1176  *
1177  * So, the total number of bytes unsent is (squeue_bytes + unsent) with all
1178  * flow-control uses of unsent replaced with the macro TCP_UNSENT_BYTES.
1179  */
1180 
1181 static void	tcp_clrqfull(tcp_t *);
1182 static void	tcp_setqfull(tcp_t *);
1183 
1184 #define	TCP_UNSENT_BYTES(tcp) \
1185 	((tcp)->tcp_squeue_bytes + (tcp)->tcp_unsent)
1186 
1187 /*
1188  * STREAMS kmod stuff ...
1189  */
1190 
1191 static struct module_info tcp_rinfo =  {
1192 #define	TCP_MODULE_ID	5105
1193 	TCP_MODULE_ID, "tcp", 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1194 };
1195 
1196 static struct module_info tcp_winfo =  {
1197 	TCP_MODULE_ID, "tcp", 0, INFPSZ, 127, 16
1198 };
1199 
1200 /*
1201  * Entry points for TCP as a module. It only allows SNMP requests
1202  * to pass through.
1203  */
1204 struct qinit tcp_mod_rinit = {
1205 	(pfi_t)putnext, NULL, tcp_open, tcp_modclose, NULL, &tcp_rinfo
1206 };
1207 
1208 struct qinit tcp_mod_winit = {
1209 	(pfi_t)tcp_wput_mod, NULL, tcp_open, tcp_modclose, NULL, &tcp_rinfo
1210 };
1211 
1212 /*
1213  * Entry points for TCP as a device. The normal case which supports
1214  * the TCP functionality.
1215  */
1216 struct qinit tcp_rinit = {
1217 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1218 };
1219 
1220 struct qinit tcp_winit = {
1221 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1222 };
1223 
1224 /* Initial entry point for TCP in socket mode. */
1225 struct qinit tcp_sock_winit = {
1226 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1227 };
1228 
1229 /*
1230  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1231  * an accept. Avoid allocating data structures since eager has already
1232  * been created.
1233  */
1234 struct qinit tcp_acceptor_rinit = {
1235 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1236 };
1237 
1238 struct qinit tcp_acceptor_winit = {
1239 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1240 };
1241 
1242 struct streamtab tcpinfo = {
1243 	&tcp_rinit, &tcp_winit
1244 };
1245 
1246 
1247 extern squeue_func_t tcp_squeue_wput_proc;
1248 extern squeue_func_t tcp_squeue_timer_proc;
1249 
1250 /* Protected by tcp_g_q_lock */
1251 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1252 kmutex_t tcp_g_q_lock;
1253 
1254 /* Protected by tcp_hsp_lock */
1255 /*
1256  * XXX The host param mechanism should go away and instead we should use
1257  * the metrics associated with the routes to determine the default sndspace
1258  * and rcvspace.
1259  */
1260 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1261 krwlock_t tcp_hsp_lock;
1262 
1263 /*
1264  * Extra privileged ports. In host byte order.
1265  * Protected by tcp_epriv_port_lock.
1266  */
1267 #define	TCP_NUM_EPRIV_PORTS	64
1268 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1269 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1270 kmutex_t tcp_epriv_port_lock;
1271 
1272 /*
1273  * The smallest anonymous port in the priviledged port range which TCP
1274  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1275  */
1276 static in_port_t tcp_min_anonpriv_port = 512;
1277 
1278 /* Only modified during _init and _fini thus no locking is needed. */
1279 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1280 
1281 /* Hint not protected by any lock */
1282 static uint_t	tcp_next_port_to_try;
1283 
1284 
1285 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1286 static tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1287 
1288 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1289 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1290 
1291 /*
1292  * TCP has a private interface for other kernel modules to reserve a
1293  * port range for them to use.  Once reserved, TCP will not use any ports
1294  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1295  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1296  * has to be verified.
1297  *
1298  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1299  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1300  * range is [port a, port b] inclusive.  And each port range is between
1301  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1302  *
1303  * Note that the default anonymous port range starts from 32768.  There is
1304  * no port "collision" between that and the reserved port range.  If there
1305  * is port collision (because the default smallest anonymous port is lowered
1306  * or some apps specifically bind to ports in the reserved port range), the
1307  * system may not be able to reserve a port range even there are enough
1308  * unbound ports as a reserved port range contains consecutive ports .
1309  */
1310 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1311 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1312 #define	TCP_SMALLEST_RESERVED_PORT		10240
1313 #define	TCP_LARGEST_RESERVED_PORT		20480
1314 
1315 /* Structure to represent those reserved port ranges. */
1316 typedef struct tcp_rport_s {
1317 	in_port_t	lo_port;
1318 	in_port_t	hi_port;
1319 	tcp_t		**temp_tcp_array;
1320 } tcp_rport_t;
1321 
1322 /* The reserved port array. */
1323 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1324 
1325 /* Locks to protect the tcp_reserved_ports array. */
1326 static krwlock_t tcp_reserved_port_lock;
1327 
1328 /* The number of ranges in the array. */
1329 uint32_t tcp_reserved_port_array_size = 0;
1330 
1331 /*
1332  * MIB-2 stuff for SNMP
1333  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1334  */
1335 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1336 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1337 
1338 /*
1339  * Object to represent database of options to search passed to
1340  * {sock,tpi}optcom_req() interface routine to take care of option
1341  * management and associated methods.
1342  * XXX These and other externs should ideally move to a TCP header
1343  */
1344 extern optdb_obj_t	tcp_opt_obj;
1345 extern uint_t		tcp_max_optsize;
1346 
1347 boolean_t tcp_icmp_source_quench = B_FALSE;
1348 /*
1349  * Following assumes TPI alignment requirements stay along 32 bit
1350  * boundaries
1351  */
1352 #define	ROUNDUP32(x) \
1353 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1354 
1355 /* Template for response to info request. */
1356 static struct T_info_ack tcp_g_t_info_ack = {
1357 	T_INFO_ACK,		/* PRIM_type */
1358 	0,			/* TSDU_size */
1359 	T_INFINITE,		/* ETSDU_size */
1360 	T_INVALID,		/* CDATA_size */
1361 	T_INVALID,		/* DDATA_size */
1362 	sizeof (sin_t),		/* ADDR_size */
1363 	0,			/* OPT_size - not initialized here */
1364 	TIDUSZ,			/* TIDU_size */
1365 	T_COTS_ORD,		/* SERV_type */
1366 	TCPS_IDLE,		/* CURRENT_state */
1367 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1368 };
1369 
1370 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1371 	T_INFO_ACK,		/* PRIM_type */
1372 	0,			/* TSDU_size */
1373 	T_INFINITE,		/* ETSDU_size */
1374 	T_INVALID,		/* CDATA_size */
1375 	T_INVALID,		/* DDATA_size */
1376 	sizeof (sin6_t),	/* ADDR_size */
1377 	0,			/* OPT_size - not initialized here */
1378 	TIDUSZ,		/* TIDU_size */
1379 	T_COTS_ORD,		/* SERV_type */
1380 	TCPS_IDLE,		/* CURRENT_state */
1381 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1382 };
1383 
1384 #define	MS	1L
1385 #define	SECONDS	(1000 * MS)
1386 #define	MINUTES	(60 * SECONDS)
1387 #define	HOURS	(60 * MINUTES)
1388 #define	DAYS	(24 * HOURS)
1389 
1390 #define	PARAM_MAX (~(uint32_t)0)
1391 
1392 /* Max size IP datagram is 64k - 1 */
1393 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1394 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1395 /* Max of the above */
1396 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1397 
1398 /* Largest TCP port number */
1399 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1400 
1401 /*
1402  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1403  * layer header.  It has to be a multiple of 4.
1404  */
1405 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1406 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1407 
1408 /*
1409  * All of these are alterable, within the min/max values given, at run time.
1410  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1411  * per the TCP spec.
1412  */
1413 /* BEGIN CSTYLED */
1414 tcpparam_t	tcp_param_arr[] = {
1415  /*min		max		value		name */
1416  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1417  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1418  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1419  { 1,		1024,		1,		"tcp_conn_req_min" },
1420  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1421  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1422  { 0,		10,		0,		"tcp_debug" },
1423  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1424  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1425  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1426  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1427  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1428  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1429  { 1,		255,		64,		"tcp_ipv4_ttl"},
1430  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1431  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1432  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1433  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1434  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1435  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1436  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1437  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1438  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1439  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1440  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1441  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1442  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1443  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1444  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1445  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1446  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1447  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1448  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1449  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1450  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1451  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1452  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1453  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1454 /*
1455  * Question:  What default value should I set for tcp_strong_iss?
1456  */
1457  { 0,		2,		1,		"tcp_strong_iss"},
1458  { 0,		65536,		20,		"tcp_rtt_updates"},
1459  { 0,		1,		1,		"tcp_wscale_always"},
1460  { 0,		1,		0,		"tcp_tstamp_always"},
1461  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1462  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1463  { 0,		16,		2,		"tcp_deferred_acks_max"},
1464  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1465  { 1,		4,		4,		"tcp_slow_start_initial"},
1466  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1467  { 0,		2,		2,		"tcp_sack_permitted"},
1468  { 0,		1,		0,		"tcp_trace"},
1469  { 0,		1,		1,		"tcp_compression_enabled"},
1470  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1471  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1472  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1473  { 0,		1,		0,		"tcp_rev_src_routes"},
1474  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1475  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1476  { 0,		16,		8,		"tcp_local_dacks_max"},
1477  { 0,		2,		1,		"tcp_ecn_permitted"},
1478  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1479  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1480  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1481  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1482  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1483 };
1484 /* END CSTYLED */
1485 
1486 
1487 #define	tcp_time_wait_interval			tcp_param_arr[0].tcp_param_val
1488 #define	tcp_conn_req_max_q			tcp_param_arr[1].tcp_param_val
1489 #define	tcp_conn_req_max_q0			tcp_param_arr[2].tcp_param_val
1490 #define	tcp_conn_req_min			tcp_param_arr[3].tcp_param_val
1491 #define	tcp_conn_grace_period			tcp_param_arr[4].tcp_param_val
1492 #define	tcp_cwnd_max_				tcp_param_arr[5].tcp_param_val
1493 #define	tcp_dbg					tcp_param_arr[6].tcp_param_val
1494 #define	tcp_smallest_nonpriv_port		tcp_param_arr[7].tcp_param_val
1495 #define	tcp_ip_abort_cinterval			tcp_param_arr[8].tcp_param_val
1496 #define	tcp_ip_abort_linterval			tcp_param_arr[9].tcp_param_val
1497 #define	tcp_ip_abort_interval			tcp_param_arr[10].tcp_param_val
1498 #define	tcp_ip_notify_cinterval			tcp_param_arr[11].tcp_param_val
1499 #define	tcp_ip_notify_interval			tcp_param_arr[12].tcp_param_val
1500 #define	tcp_ipv4_ttl				tcp_param_arr[13].tcp_param_val
1501 #define	tcp_keepalive_interval_high		tcp_param_arr[14].tcp_param_max
1502 #define	tcp_keepalive_interval			tcp_param_arr[14].tcp_param_val
1503 #define	tcp_keepalive_interval_low		tcp_param_arr[14].tcp_param_min
1504 #define	tcp_maxpsz_multiplier			tcp_param_arr[15].tcp_param_val
1505 #define	tcp_mss_def_ipv4			tcp_param_arr[16].tcp_param_val
1506 #define	tcp_mss_max_ipv4			tcp_param_arr[17].tcp_param_val
1507 #define	tcp_mss_min				tcp_param_arr[18].tcp_param_val
1508 #define	tcp_naglim_def				tcp_param_arr[19].tcp_param_val
1509 #define	tcp_rexmit_interval_initial		tcp_param_arr[20].tcp_param_val
1510 #define	tcp_rexmit_interval_max			tcp_param_arr[21].tcp_param_val
1511 #define	tcp_rexmit_interval_min			tcp_param_arr[22].tcp_param_val
1512 #define	tcp_deferred_ack_interval		tcp_param_arr[23].tcp_param_val
1513 #define	tcp_snd_lowat_fraction			tcp_param_arr[24].tcp_param_val
1514 #define	tcp_sth_rcv_hiwat			tcp_param_arr[25].tcp_param_val
1515 #define	tcp_sth_rcv_lowat			tcp_param_arr[26].tcp_param_val
1516 #define	tcp_dupack_fast_retransmit		tcp_param_arr[27].tcp_param_val
1517 #define	tcp_ignore_path_mtu			tcp_param_arr[28].tcp_param_val
1518 #define	tcp_smallest_anon_port			tcp_param_arr[29].tcp_param_val
1519 #define	tcp_largest_anon_port			tcp_param_arr[30].tcp_param_val
1520 #define	tcp_xmit_hiwat				tcp_param_arr[31].tcp_param_val
1521 #define	tcp_xmit_lowat				tcp_param_arr[32].tcp_param_val
1522 #define	tcp_recv_hiwat				tcp_param_arr[33].tcp_param_val
1523 #define	tcp_recv_hiwat_minmss			tcp_param_arr[34].tcp_param_val
1524 #define	tcp_fin_wait_2_flush_interval		tcp_param_arr[35].tcp_param_val
1525 #define	tcp_co_min				tcp_param_arr[36].tcp_param_val
1526 #define	tcp_max_buf				tcp_param_arr[37].tcp_param_val
1527 #define	tcp_strong_iss				tcp_param_arr[38].tcp_param_val
1528 #define	tcp_rtt_updates				tcp_param_arr[39].tcp_param_val
1529 #define	tcp_wscale_always			tcp_param_arr[40].tcp_param_val
1530 #define	tcp_tstamp_always			tcp_param_arr[41].tcp_param_val
1531 #define	tcp_tstamp_if_wscale			tcp_param_arr[42].tcp_param_val
1532 #define	tcp_rexmit_interval_extra		tcp_param_arr[43].tcp_param_val
1533 #define	tcp_deferred_acks_max			tcp_param_arr[44].tcp_param_val
1534 #define	tcp_slow_start_after_idle		tcp_param_arr[45].tcp_param_val
1535 #define	tcp_slow_start_initial			tcp_param_arr[46].tcp_param_val
1536 #define	tcp_co_timer_interval			tcp_param_arr[47].tcp_param_val
1537 #define	tcp_sack_permitted			tcp_param_arr[48].tcp_param_val
1538 #define	tcp_trace				tcp_param_arr[49].tcp_param_val
1539 #define	tcp_compression_enabled			tcp_param_arr[50].tcp_param_val
1540 #define	tcp_ipv6_hoplimit			tcp_param_arr[51].tcp_param_val
1541 #define	tcp_mss_def_ipv6			tcp_param_arr[52].tcp_param_val
1542 #define	tcp_mss_max_ipv6			tcp_param_arr[53].tcp_param_val
1543 #define	tcp_rev_src_routes			tcp_param_arr[54].tcp_param_val
1544 #define	tcp_local_dack_interval			tcp_param_arr[55].tcp_param_val
1545 #define	tcp_ndd_get_info_interval		tcp_param_arr[56].tcp_param_val
1546 #define	tcp_local_dacks_max			tcp_param_arr[57].tcp_param_val
1547 #define	tcp_ecn_permitted			tcp_param_arr[58].tcp_param_val
1548 #define	tcp_rst_sent_rate_enabled		tcp_param_arr[59].tcp_param_val
1549 #define	tcp_rst_sent_rate			tcp_param_arr[60].tcp_param_val
1550 #define	tcp_push_timer_interval			tcp_param_arr[61].tcp_param_val
1551 #define	tcp_use_smss_as_mss_opt			tcp_param_arr[62].tcp_param_val
1552 #define	tcp_keepalive_abort_interval_high	tcp_param_arr[63].tcp_param_max
1553 #define	tcp_keepalive_abort_interval		tcp_param_arr[63].tcp_param_val
1554 #define	tcp_keepalive_abort_interval_low	tcp_param_arr[63].tcp_param_min
1555 
1556 /*
1557  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1558  * each header fragment in the header buffer.  Each parameter value has
1559  * to be a multiple of 4 (32-bit aligned).
1560  */
1561 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1562 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1563 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1564 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1565 
1566 /*
1567  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1568  * the maximum number of payload buffers associated per Multidata.
1569  */
1570 static tcpparam_t tcp_mdt_max_pbufs_param =
1571 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1572 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1573 
1574 /* Round up the value to the nearest mss. */
1575 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1576 
1577 /*
1578  * Set ECN capable transport (ECT) code point in IP header.
1579  *
1580  * Note that there are 2 ECT code points '01' and '10', which are called
1581  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1582  * point ECT(0) for TCP as described in RFC 2481.
1583  */
1584 #define	SET_ECT(tcp, iph) \
1585 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1586 		/* We need to clear the code point first. */ \
1587 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1588 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1589 	} else { \
1590 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1591 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1592 	}
1593 
1594 /*
1595  * The format argument to pass to tcp_display().
1596  * DISP_PORT_ONLY means that the returned string has only port info.
1597  * DISP_ADDR_AND_PORT means that the returned string also contains the
1598  * remote and local IP address.
1599  */
1600 #define	DISP_PORT_ONLY		1
1601 #define	DISP_ADDR_AND_PORT	2
1602 
1603 /*
1604  * This controls the rate some ndd info report functions can be used
1605  * by non-priviledged users.  It stores the last time such info is
1606  * requested.  When those report functions are called again, this
1607  * is checked with the current time and compare with the ndd param
1608  * tcp_ndd_get_info_interval.
1609  */
1610 static clock_t tcp_last_ndd_get_info_time = 0;
1611 #define	NDD_TOO_QUICK_MSG \
1612 	"ndd get info rate too high for non-priviledged users, try again " \
1613 	"later.\n"
1614 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1615 
1616 #define	IS_VMLOANED_MBLK(mp) \
1617 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1618 
1619 /*
1620  * These two variables control the rate for TCP to generate RSTs in
1621  * response to segments not belonging to any connections.  We limit
1622  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1623  * each 1 second interval.  This is to protect TCP against DoS attack.
1624  */
1625 static clock_t tcp_last_rst_intrvl;
1626 static uint32_t tcp_rst_cnt;
1627 
1628 /* The number of RST not sent because of the rate limit. */
1629 static uint32_t tcp_rst_unsent;
1630 
1631 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1632 boolean_t tcp_mdt_chain = B_TRUE;
1633 
1634 /*
1635  * MDT threshold in the form of effective send MSS multiplier; we take
1636  * the MDT path if the amount of unsent data exceeds the threshold value
1637  * (default threshold is 1*SMSS).
1638  */
1639 uint_t tcp_mdt_smss_threshold = 1;
1640 
1641 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1642 
1643 /*
1644  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1645  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1646  * determined dynamically during tcp_adapt_ire(), which is the default.
1647  */
1648 boolean_t tcp_static_maxpsz = B_FALSE;
1649 
1650 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1651 uint32_t tcp_random_anon_port = 1;
1652 
1653 /*
1654  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1655  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1656  * data, TCP will not respond with an ACK.  RFC 793 requires that
1657  * TCP responds with an ACK for such a bogus ACK.  By not following
1658  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1659  * an attacker successfully spoofs an acceptable segment to our
1660  * peer; or when our peer is "confused."
1661  */
1662 uint32_t tcp_drop_ack_unsent_cnt = 10;
1663 
1664 /*
1665  * Hook functions to enable cluster networking
1666  * On non-clustered systems these vectors must always be NULL.
1667  */
1668 
1669 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1670 			    uint8_t *laddrp, in_port_t lport) = NULL;
1671 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1672 			    uint8_t *laddrp, in_port_t lport) = NULL;
1673 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1674 			    uint8_t *laddrp, in_port_t lport,
1675 			    uint8_t *faddrp, in_port_t fport) = NULL;
1676 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1677 			    uint8_t *laddrp, in_port_t lport,
1678 			    uint8_t *faddrp, in_port_t fport) = NULL;
1679 
1680 /*
1681  * The following are defined in ip.c
1682  */
1683 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1684 				uint8_t *laddrp);
1685 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1686 				uint8_t *laddrp, uint8_t *faddrp);
1687 
1688 #define	CL_INET_CONNECT(tcp)		{			\
1689 	if (cl_inet_connect != NULL) {				\
1690 		/*						\
1691 		 * Running in cluster mode - register active connection	\
1692 		 * information						\
1693 		 */							\
1694 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1695 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1696 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1697 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1698 				    (in_port_t)(tcp)->tcp_lport,	\
1699 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1700 				    (in_port_t)(tcp)->tcp_fport);	\
1701 			}						\
1702 		} else {						\
1703 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1704 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1705 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1706 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1707 				    (in_port_t)(tcp)->tcp_lport,	\
1708 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1709 				    (in_port_t)(tcp)->tcp_fport);	\
1710 			}						\
1711 		}							\
1712 	}								\
1713 }
1714 
1715 #define	CL_INET_DISCONNECT(tcp)	{				\
1716 	if (cl_inet_disconnect != NULL) {				\
1717 		/*							\
1718 		 * Running in cluster mode - deregister active		\
1719 		 * connection information				\
1720 		 */							\
1721 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1722 			if ((tcp)->tcp_ip_src != 0) {			\
1723 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1724 				    AF_INET,				\
1725 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1726 				    (in_port_t)(tcp)->tcp_lport,	\
1727 				    (uint8_t *)				\
1728 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1729 				    (in_port_t)(tcp)->tcp_fport);	\
1730 			}						\
1731 		} else {						\
1732 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1733 			    &(tcp)->tcp_ip_src_v6)) {			\
1734 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1735 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1736 				    (in_port_t)(tcp)->tcp_lport,	\
1737 				    (uint8_t *)				\
1738 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1739 				    (in_port_t)(tcp)->tcp_fport);	\
1740 			}						\
1741 		}							\
1742 	}								\
1743 }
1744 
1745 /*
1746  * Cluster networking hook for traversing current connection list.
1747  * This routine is used to extract the current list of live connections
1748  * which must continue to to be dispatched to this node.
1749  */
1750 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1751 
1752 #define	IPH_TCPH_CHECKSUMP(ipha, hlen) \
1753 	((uint16_t *)(((uchar_t *)(ipha)) + ((hlen) + 16)))
1754 
1755 #ifdef  _BIG_ENDIAN
1756 #define	IP_TCP_CSUM_COMP	IPPROTO_TCP
1757 #else
1758 #define	IP_TCP_CSUM_COMP	(IPPROTO_TCP << 8)
1759 #endif
1760 
1761 #define	IP_HDR_CKSUM(ipha, sum, v_hlen_tos_len, ttl_protocol) {		\
1762 	(sum) += (ttl_protocol) + (ipha)->ipha_ident +			\
1763 	    ((v_hlen_tos_len) >> 16) +					\
1764 	    ((v_hlen_tos_len) & 0xFFFF) +				\
1765 	    (ipha)->ipha_fragment_offset_and_flags;			\
1766 	(sum) = (((sum) & 0xFFFF) + ((sum) >> 16));			\
1767 	(sum) = ~((sum) + ((sum) >> 16));				\
1768 	(ipha)->ipha_hdr_checksum = (uint16_t)(sum);			\
1769 }
1770 
1771 /*
1772  * Macros that determine whether or not IP processing is needed for TCP.
1773  */
1774 #define	TCP_IPOPT_POLICY_V4(tcp)					\
1775 	((tcp)->tcp_ipversion == IPV4_VERSION &&			\
1776 	((tcp)->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH ||		\
1777 	CONN_OUTBOUND_POLICY_PRESENT((tcp)->tcp_connp) ||		\
1778 	CONN_INBOUND_POLICY_PRESENT((tcp)->tcp_connp)))
1779 
1780 #define	TCP_IPOPT_POLICY_V6(tcp)					\
1781 	((tcp)->tcp_ipversion == IPV6_VERSION &&			\
1782 	((tcp)->tcp_ip_hdr_len != IPV6_HDR_LEN ||			\
1783 	CONN_OUTBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp) ||		\
1784 	CONN_INBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp)))
1785 
1786 #define	TCP_LOOPBACK_IP(tcp)						\
1787 	(TCP_IPOPT_POLICY_V4(tcp) || TCP_IPOPT_POLICY_V6(tcp) ||	\
1788 	!CONN_IS_MD_FASTPATH((tcp)->tcp_connp))
1789 
1790 boolean_t do_tcp_fusion = B_TRUE;
1791 
1792 /*
1793  * This routine gets called by the eager tcp upon changing state from
1794  * SYN_RCVD to ESTABLISHED.  It fuses a direct path between itself
1795  * and the active connect tcp such that the regular tcp processings
1796  * may be bypassed under allowable circumstances.  Because the fusion
1797  * requires both endpoints to be in the same squeue, it does not work
1798  * for simultaneous active connects because there is no easy way to
1799  * switch from one squeue to another once the connection is created.
1800  * This is different from the eager tcp case where we assign it the
1801  * same squeue as the one given to the active connect tcp during open.
1802  */
1803 static void
1804 tcp_fuse(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph)
1805 {
1806 	conn_t *peer_connp, *connp = tcp->tcp_connp;
1807 	tcp_t *peer_tcp;
1808 
1809 	ASSERT(!tcp->tcp_fused);
1810 	ASSERT(tcp->tcp_loopback);
1811 	ASSERT(tcp->tcp_loopback_peer == NULL);
1812 	/*
1813 	 * We need to check the listener tcp to make sure it's a socket
1814 	 * endpoint, but we can't really use tcp_listener since we get
1815 	 * here after sending up T_CONN_IND and tcp_wput_accept() may be
1816 	 * called independently, at which point tcp_listener is cleared;
1817 	 * this is why we use tcp_saved_listener.  The listener itself
1818 	 * is guaranteed to be around until tcp_accept_finish() is called
1819 	 * on this eager -- this won't happen until we're done since
1820 	 * we're inside the eager's perimeter now.
1821 	 */
1822 	ASSERT(tcp->tcp_saved_listener != NULL);
1823 
1824 	/*
1825 	 * Lookup peer endpoint; search for the remote endpoint having
1826 	 * the reversed address-port quadruplet in ESTABLISHED state,
1827 	 * which is guaranteed to be unique in the system.  Zone check
1828 	 * is applied accordingly for loopback address, but not for
1829 	 * local address since we want fusion to happen across Zones.
1830 	 */
1831 	if (tcp->tcp_ipversion == IPV4_VERSION) {
1832 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv4(connp,
1833 		    (ipha_t *)iphdr, tcph);
1834 	} else {
1835 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv6(connp,
1836 		    (ip6_t *)iphdr, tcph);
1837 	}
1838 
1839 	/*
1840 	 * We can only proceed if peer exists, resides in the same squeue
1841 	 * as our conn and is not raw-socket.  The squeue assignment of
1842 	 * this eager tcp was done earlier at the time of SYN processing
1843 	 * in ip_fanout_tcp{_v6}.  Note that similar squeues by itself
1844 	 * doesn't guarantee a safe condition to fuse, hence we perform
1845 	 * additional tests below.
1846 	 */
1847 	ASSERT(peer_connp == NULL || peer_connp != connp);
1848 	if (peer_connp == NULL || peer_connp->conn_sqp != connp->conn_sqp ||
1849 	    !IPCL_IS_TCP(peer_connp)) {
1850 		if (peer_connp != NULL) {
1851 			TCP_STAT(tcp_fusion_unqualified);
1852 			CONN_DEC_REF(peer_connp);
1853 		}
1854 		return;
1855 	}
1856 	peer_tcp = peer_connp->conn_tcp;	/* active connect tcp */
1857 
1858 	ASSERT(peer_tcp != NULL && peer_tcp != tcp && !peer_tcp->tcp_fused);
1859 	ASSERT(peer_tcp->tcp_loopback && peer_tcp->tcp_loopback_peer == NULL);
1860 	ASSERT(peer_connp->conn_sqp == connp->conn_sqp);
1861 
1862 	/*
1863 	 * Fuse the endpoints; we perform further checks against both
1864 	 * tcp endpoints to ensure that a fusion is allowed to happen.
1865 	 * In particular we bail out for TPI, non-simple TCP/IP or if
1866 	 * IPsec/IPQoS policy exists.  We could actually do it for the
1867 	 * XTI/TLI/TPI case but this requires more testing, so for now
1868 	 * we handle only the socket case.
1869 	 */
1870 	if (!tcp->tcp_unfusable && !peer_tcp->tcp_unfusable &&
1871 	    TCP_IS_SOCKET(tcp->tcp_saved_listener) && TCP_IS_SOCKET(peer_tcp) &&
1872 	    !TCP_LOOPBACK_IP(tcp) && !TCP_LOOPBACK_IP(peer_tcp) &&
1873 	    !IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
1874 		mblk_t *mp;
1875 		struct stroptions *stropt;
1876 		queue_t *peer_rq = peer_tcp->tcp_rq;
1877 		size_t sth_hiwat;
1878 
1879 		ASSERT(!TCP_IS_DETACHED(peer_tcp) && peer_rq != NULL);
1880 
1881 		/*
1882 		 * We need to drain data on both endpoints during unfuse.
1883 		 * If we need to send up SIGURG at the time of draining,
1884 		 * we want to be sure that an mblk is readily available.
1885 		 * This is why we pre-allocate the M_PCSIG mblks for both
1886 		 * endpoints which will only be used during/after unfuse.
1887 		 */
1888 		if ((mp = allocb(1, BPRI_HI)) == NULL) {
1889 			CONN_DEC_REF(peer_connp);
1890 			return;
1891 		}
1892 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
1893 		tcp->tcp_fused_sigurg_mp = mp;
1894 
1895 		if ((mp = allocb(1, BPRI_HI)) == NULL) {
1896 			freeb(tcp->tcp_fused_sigurg_mp);
1897 			tcp->tcp_fused_sigurg_mp = NULL;
1898 			CONN_DEC_REF(peer_connp);
1899 			return;
1900 		}
1901 		ASSERT(peer_tcp->tcp_fused_sigurg_mp == NULL);
1902 		peer_tcp->tcp_fused_sigurg_mp = mp;
1903 
1904 		/* Allocate M_SETOPTS mblk */
1905 		mp = allocb(sizeof (*stropt), BPRI_HI);
1906 		if (mp == NULL) {
1907 			freeb(tcp->tcp_fused_sigurg_mp);
1908 			tcp->tcp_fused_sigurg_mp = NULL;
1909 			freeb(peer_tcp->tcp_fused_sigurg_mp);
1910 			peer_tcp->tcp_fused_sigurg_mp = NULL;
1911 			CONN_DEC_REF(peer_connp);
1912 			return;
1913 		}
1914 
1915 		/* Fuse both endpoints */
1916 		peer_tcp->tcp_loopback_peer = tcp;
1917 		tcp->tcp_loopback_peer = peer_tcp;
1918 		peer_tcp->tcp_fused = tcp->tcp_fused = B_TRUE;
1919 
1920 		/*
1921 		 * We never use regular tcp paths in fusion and should
1922 		 * therefore clear tcp_unsent on both endpoints.  Having
1923 		 * them set to non-zero values means asking for trouble
1924 		 * especially after unfuse, where we may end up sending
1925 		 * through regular tcp paths which expect xmit_list and
1926 		 * friends to be correctly setup.
1927 		 */
1928 		peer_tcp->tcp_unsent = tcp->tcp_unsent = 0;
1929 
1930 		tcp_timers_stop(tcp);
1931 		tcp_timers_stop(peer_tcp);
1932 
1933 		/*
1934 		 * Set the stream head's write offset value to zero, since we
1935 		 * won't be needing any room for TCP/IP headers, and tell it
1936 		 * to not break up the writes.  This would reduce the amount
1937 		 * of work done by kmem.  In addition, we set the receive
1938 		 * buffer to twice that of q_hiwat in order to simulate the
1939 		 * non-fusion case.  Note that we can only do this for the
1940 		 * active connect tcp since our eager is still detached;
1941 		 * it will be dealt with later in tcp_accept_finish().
1942 		 */
1943 		DB_TYPE(mp) = M_SETOPTS;
1944 		mp->b_wptr += sizeof (*stropt);
1945 
1946 		sth_hiwat = peer_rq->q_hiwat << 1;
1947 		if (sth_hiwat > tcp_max_buf)
1948 			sth_hiwat = tcp_max_buf;
1949 
1950 		stropt = (struct stroptions *)mp->b_rptr;
1951 		stropt->so_flags = SO_MAXBLK | SO_WROFF | SO_HIWAT;
1952 		stropt->so_maxblk = tcp_maxpsz_set(peer_tcp, B_FALSE);
1953 		stropt->so_wroff = 0;
1954 		stropt->so_hiwat = MAX(sth_hiwat, tcp_sth_rcv_hiwat);
1955 
1956 		/* Send the options up */
1957 		putnext(peer_rq, mp);
1958 	} else {
1959 		TCP_STAT(tcp_fusion_unqualified);
1960 	}
1961 	CONN_DEC_REF(peer_connp);
1962 }
1963 
1964 /*
1965  * Unfuse a previously-fused pair of tcp loopback endpoints.
1966  */
1967 static void
1968 tcp_unfuse(tcp_t *tcp)
1969 {
1970 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
1971 
1972 	ASSERT(tcp->tcp_fused && peer_tcp != NULL);
1973 	ASSERT(peer_tcp->tcp_fused && peer_tcp->tcp_loopback_peer == tcp);
1974 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
1975 	ASSERT(tcp->tcp_unsent == 0 && peer_tcp->tcp_unsent == 0);
1976 	ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
1977 	ASSERT(peer_tcp->tcp_fused_sigurg_mp != NULL);
1978 
1979 	/*
1980 	 * Drain any pending data; the detached check is needed because
1981 	 * we may be called from tcp_fuse_output().  Note that in case of
1982 	 * a detached tcp, the draining will happen later after the tcp
1983 	 * is unfused.  For non-urgent data, this can be handled by the
1984 	 * regular tcp_rcv_drain().  If we have urgent data sitting in
1985 	 * the receive list, we will need to send up a SIGURG signal first
1986 	 * before draining the data.  All of these will be handled by the
1987 	 * code in tcp_fuse_rcv_drain() when called from tcp_rcv_drain().
1988 	 */
1989 	if (!TCP_IS_DETACHED(tcp)) {
1990 		(void) tcp_fuse_rcv_drain(tcp->tcp_rq, tcp,
1991 		    &tcp->tcp_fused_sigurg_mp);
1992 	}
1993 	if (!TCP_IS_DETACHED(peer_tcp)) {
1994 		(void) tcp_fuse_rcv_drain(peer_tcp->tcp_rq, peer_tcp,
1995 		    &peer_tcp->tcp_fused_sigurg_mp);
1996 	}
1997 	/* Lift up any flow-control conditions */
1998 	if (tcp->tcp_flow_stopped) {
1999 		tcp_clrqfull(tcp);
2000 		TCP_STAT(tcp_fusion_backenabled);
2001 	}
2002 	if (peer_tcp->tcp_flow_stopped) {
2003 		tcp_clrqfull(peer_tcp);
2004 		TCP_STAT(tcp_fusion_backenabled);
2005 	}
2006 
2007 	/* Free up M_PCSIG mblk(s) if not needed */
2008 	if (!tcp->tcp_fused_sigurg && tcp->tcp_fused_sigurg_mp != NULL) {
2009 		freeb(tcp->tcp_fused_sigurg_mp);
2010 		tcp->tcp_fused_sigurg_mp = NULL;
2011 	}
2012 	if (!peer_tcp->tcp_fused_sigurg &&
2013 	    peer_tcp->tcp_fused_sigurg_mp != NULL) {
2014 		freeb(peer_tcp->tcp_fused_sigurg_mp);
2015 		peer_tcp->tcp_fused_sigurg_mp = NULL;
2016 	}
2017 
2018 	/*
2019 	 * Update th_seq and th_ack in the header template
2020 	 */
2021 	U32_TO_ABE32(tcp->tcp_snxt, tcp->tcp_tcph->th_seq);
2022 	U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
2023 	U32_TO_ABE32(peer_tcp->tcp_snxt, peer_tcp->tcp_tcph->th_seq);
2024 	U32_TO_ABE32(peer_tcp->tcp_rnxt, peer_tcp->tcp_tcph->th_ack);
2025 
2026 	/* Unfuse the endpoints */
2027 	peer_tcp->tcp_fused = tcp->tcp_fused = B_FALSE;
2028 	peer_tcp->tcp_loopback_peer = tcp->tcp_loopback_peer = NULL;
2029 }
2030 
2031 /*
2032  * Fusion output routine for urgent data.  This routine is called by
2033  * tcp_fuse_output() for handling non-M_DATA mblks.
2034  */
2035 static void
2036 tcp_fuse_output_urg(tcp_t *tcp, mblk_t *mp)
2037 {
2038 	mblk_t *mp1;
2039 	struct T_exdata_ind *tei;
2040 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2041 	mblk_t *head, *prev_head = NULL;
2042 
2043 	ASSERT(tcp->tcp_fused);
2044 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
2045 	ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
2046 	ASSERT(mp->b_cont != NULL && DB_TYPE(mp->b_cont) == M_DATA);
2047 	ASSERT(MBLKL(mp) >= sizeof (*tei) && MBLKL(mp->b_cont) > 0);
2048 
2049 	/*
2050 	 * Urgent data arrives in the form of T_EXDATA_REQ from above.
2051 	 * Each occurence denotes a new urgent pointer.  For each new
2052 	 * urgent pointer we signal (SIGURG) the receiving app to indicate
2053 	 * that it needs to go into urgent mode.  This is similar to the
2054 	 * urgent data handling in the regular tcp.  We don't need to keep
2055 	 * track of where the urgent pointer is, because each T_EXDATA_REQ
2056 	 * "advances" the urgent pointer for us.
2057 	 *
2058 	 * The actual urgent data carried by T_EXDATA_REQ is then prepended
2059 	 * by a T_EXDATA_IND before being enqueued behind any existing data
2060 	 * destined for the receiving app.  There is only a single urgent
2061 	 * pointer (out-of-band mark) for a given tcp.  If the new urgent
2062 	 * data arrives before the receiving app reads some existing urgent
2063 	 * data, the previous marker is lost.  This behavior is emulated
2064 	 * accordingly below, by removing any existing T_EXDATA_IND messages
2065 	 * and essentially converting old urgent data into non-urgent.
2066 	 */
2067 	ASSERT(tcp->tcp_valid_bits & TCP_URG_VALID);
2068 	/* Let sender get out of urgent mode */
2069 	tcp->tcp_valid_bits &= ~TCP_URG_VALID;
2070 
2071 	/*
2072 	 * Send up SIGURG to the receiving peer; if the peer is detached
2073 	 * or if we can't allocate the M_PCSIG, indicate that we need to
2074 	 * signal upon draining to the peer by marking tcp_fused_sigurg.
2075 	 * This flag will only get cleared once SIGURG is delivered and
2076 	 * is not affected by the tcp_fused flag -- delivery will still
2077 	 * happen even after an endpoint is unfused, to handle the case
2078 	 * where the sending endpoint immediately closes/unfuses after
2079 	 * sending urgent data and the accept is not yet finished.
2080 	 */
2081 	if (!TCP_IS_DETACHED(peer_tcp) &&
2082 	    ((mp1 = allocb(1, BPRI_HI)) != NULL ||
2083 	    (mp1 = allocb_tryhard(1)) != NULL)) {
2084 		peer_tcp->tcp_fused_sigurg = B_FALSE;
2085 		/* Send up the signal */
2086 		DB_TYPE(mp1) = M_PCSIG;
2087 		*mp1->b_wptr++ = (uchar_t)SIGURG;
2088 		putnext(peer_tcp->tcp_rq, mp1);
2089 	} else {
2090 		peer_tcp->tcp_fused_sigurg = B_TRUE;
2091 	}
2092 
2093 	/* Reuse T_EXDATA_REQ mblk for T_EXDATA_IND */
2094 	DB_TYPE(mp) = M_PROTO;
2095 	tei = (struct T_exdata_ind *)mp->b_rptr;
2096 	tei->PRIM_type = T_EXDATA_IND;
2097 	tei->MORE_flag = 0;
2098 	mp->b_wptr = (uchar_t *)&tei[1];
2099 
2100 	TCP_STAT(tcp_fusion_urg);
2101 	BUMP_MIB(&tcp_mib, tcpOutUrg);
2102 
2103 	head = peer_tcp->tcp_rcv_list;
2104 	while (head != NULL) {
2105 		/*
2106 		 * Remove existing T_EXDATA_IND, keep the data which follows
2107 		 * it and relink our list.  Note that we don't modify the
2108 		 * tcp_rcv_last_tail since it never points to T_EXDATA_IND.
2109 		 */
2110 		if (DB_TYPE(head) != M_DATA) {
2111 			mp1 = head;
2112 
2113 			ASSERT(DB_TYPE(mp1->b_cont) == M_DATA);
2114 			head = mp1->b_cont;
2115 			mp1->b_cont = NULL;
2116 			head->b_next = mp1->b_next;
2117 			mp1->b_next = NULL;
2118 			if (prev_head != NULL)
2119 				prev_head->b_next = head;
2120 			if (peer_tcp->tcp_rcv_list == mp1)
2121 				peer_tcp->tcp_rcv_list = head;
2122 			if (peer_tcp->tcp_rcv_last_head == mp1)
2123 				peer_tcp->tcp_rcv_last_head = head;
2124 			freeb(mp1);
2125 		}
2126 		prev_head = head;
2127 		head = head->b_next;
2128 	}
2129 }
2130 
2131 /*
2132  * Fusion output routine, called by tcp_output() and tcp_wput_proto().
2133  */
2134 static boolean_t
2135 tcp_fuse_output(tcp_t *tcp, mblk_t *mp)
2136 {
2137 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2138 	queue_t *peer_rq;
2139 	mblk_t *mp_tail = mp;
2140 	uint32_t send_size = 0;
2141 
2142 	ASSERT(tcp->tcp_fused);
2143 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
2144 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
2145 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_PROTO ||
2146 	    DB_TYPE(mp) == M_PCPROTO);
2147 
2148 	peer_rq = peer_tcp->tcp_rq;
2149 
2150 	/* If this connection requires IP, unfuse and use regular path */
2151 	if (TCP_LOOPBACK_IP(tcp) || TCP_LOOPBACK_IP(peer_tcp) ||
2152 	    IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
2153 		TCP_STAT(tcp_fusion_aborted);
2154 		tcp_unfuse(tcp);
2155 		return (B_FALSE);
2156 	}
2157 
2158 	for (;;) {
2159 		if (DB_TYPE(mp_tail) == M_DATA)
2160 			send_size += MBLKL(mp_tail);
2161 		if (mp_tail->b_cont == NULL)
2162 			break;
2163 		mp_tail = mp_tail->b_cont;
2164 	}
2165 
2166 	if (send_size == 0) {
2167 		freemsg(mp);
2168 		return (B_TRUE);
2169 	}
2170 
2171 	/*
2172 	 * Handle urgent data; we either send up SIGURG to the peer now
2173 	 * or do it later when we drain, in case the peer is detached
2174 	 * or if we're short of memory for M_PCSIG mblk.
2175 	 */
2176 	if (DB_TYPE(mp) != M_DATA)
2177 		tcp_fuse_output_urg(tcp, mp);
2178 
2179 	/*
2180 	 * Enqueue data into the peer's receive list; we may or may not
2181 	 * drain the contents depending on the conditions below.
2182 	 */
2183 	tcp_rcv_enqueue(peer_tcp, mp, send_size);
2184 
2185 	/* In case it wrapped around and also to keep it constant */
2186 	peer_tcp->tcp_rwnd += send_size;
2187 
2188 	/*
2189 	 * If peer is detached, exercise flow-control when needed; we will
2190 	 * get back-enabled either in tcp_accept_finish() or tcp_unfuse().
2191 	 */
2192 	if (TCP_IS_DETACHED(peer_tcp) &&
2193 	    peer_tcp->tcp_rcv_cnt > peer_rq->q_hiwat) {
2194 		tcp_setqfull(tcp);
2195 		TCP_STAT(tcp_fusion_flowctl);
2196 	}
2197 
2198 	loopback_packets++;
2199 	tcp->tcp_last_sent_len = send_size;
2200 
2201 	/* Need to adjust the following SNMP MIB-related variables */
2202 	tcp->tcp_snxt += send_size;
2203 	tcp->tcp_suna = tcp->tcp_snxt;
2204 	peer_tcp->tcp_rnxt += send_size;
2205 	peer_tcp->tcp_rack = peer_tcp->tcp_rnxt;
2206 
2207 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
2208 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, send_size);
2209 
2210 	BUMP_MIB(&tcp_mib, tcpInSegs);
2211 	BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
2212 	UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, send_size);
2213 
2214 	BUMP_LOCAL(tcp->tcp_obsegs);
2215 	BUMP_LOCAL(peer_tcp->tcp_ibsegs);
2216 
2217 	if (!TCP_IS_DETACHED(peer_tcp)) {
2218 		/*
2219 		 * If we can't send SIGURG above due to lack of memory,
2220 		 * schedule push timer and try again.  Otherwise drain
2221 		 * the data if we're not flow-controlled.
2222 		 */
2223 		if (peer_tcp->tcp_fused_sigurg) {
2224 			if (peer_tcp->tcp_push_tid == 0) {
2225 				peer_tcp->tcp_push_tid =
2226 				    TCP_TIMER(peer_tcp, tcp_push_timer,
2227 				    MSEC_TO_TICK(tcp_push_timer_interval));
2228 			}
2229 		} else if (!tcp->tcp_flow_stopped) {
2230 			if (!canputnext(peer_rq)) {
2231 				tcp_setqfull(tcp);
2232 				TCP_STAT(tcp_fusion_flowctl);
2233 			} else {
2234 				ASSERT(peer_tcp->tcp_rcv_list != NULL);
2235 				(void) tcp_fuse_rcv_drain(peer_rq,
2236 				    peer_tcp, NULL);
2237 				TCP_STAT(tcp_fusion_putnext);
2238 			}
2239 		} else if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
2240 			tcp_clrqfull(tcp);
2241 		}
2242 	}
2243 	return (B_TRUE);
2244 }
2245 
2246 /*
2247  * This routine gets called to deliver data upstream on a fused or
2248  * previously fused tcp loopback endpoint; the latter happens only
2249  * when there is a pending SIGURG signal plus urgent data that can't
2250  * be sent upstream in the past.
2251  */
2252 static boolean_t
2253 tcp_fuse_rcv_drain(queue_t *q, tcp_t *tcp, mblk_t **sigurg_mpp)
2254 {
2255 	mblk_t *mp;
2256 #ifdef DEBUG
2257 	uint_t cnt = 0;
2258 #endif
2259 
2260 	ASSERT(tcp->tcp_loopback);
2261 	ASSERT(tcp->tcp_fused || tcp->tcp_fused_sigurg);
2262 	ASSERT(!tcp->tcp_fused || tcp->tcp_loopback_peer != NULL);
2263 	ASSERT(sigurg_mpp != NULL || tcp->tcp_fused);
2264 
2265 	/* No need for the push timer now, in case it was scheduled */
2266 	if (tcp->tcp_push_tid != 0) {
2267 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
2268 		tcp->tcp_push_tid = 0;
2269 	}
2270 	/*
2271 	 * If there's urgent data sitting in receive list and we didn't
2272 	 * get a chance to send up a SIGURG signal, make sure we send
2273 	 * it first before draining in order to ensure that SIOCATMARK
2274 	 * works properly.
2275 	 */
2276 	if (tcp->tcp_fused_sigurg) {
2277 		/*
2278 		 * sigurg_mpp is normally NULL, i.e. when we're still
2279 		 * fused and didn't get here because of tcp_unfuse().
2280 		 * In this case try hard to allocate the M_PCSIG mblk.
2281 		 */
2282 		if (sigurg_mpp == NULL &&
2283 		    (mp = allocb(1, BPRI_HI)) == NULL &&
2284 		    (mp = allocb_tryhard(1)) == NULL) {
2285 			/* Alloc failed; try again next time */
2286 			tcp->tcp_push_tid = TCP_TIMER(tcp, tcp_push_timer,
2287 			    MSEC_TO_TICK(tcp_push_timer_interval));
2288 			return (B_TRUE);
2289 		} else if (sigurg_mpp != NULL) {
2290 			/*
2291 			 * Use the supplied M_PCSIG mblk; it means we're
2292 			 * either unfused or in the process of unfusing,
2293 			 * and the drain must happen now.
2294 			 */
2295 			mp = *sigurg_mpp;
2296 			*sigurg_mpp = NULL;
2297 		}
2298 		ASSERT(mp != NULL);
2299 
2300 		tcp->tcp_fused_sigurg = B_FALSE;
2301 		/* Send up the signal */
2302 		DB_TYPE(mp) = M_PCSIG;
2303 		*mp->b_wptr++ = (uchar_t)SIGURG;
2304 		putnext(q, mp);
2305 		/*
2306 		 * Let the regular tcp_rcv_drain() path handle
2307 		 * draining the data if we're no longer fused.
2308 		 */
2309 		if (!tcp->tcp_fused)
2310 			return (B_FALSE);
2311 	}
2312 
2313 	/* Drain the data */
2314 	while ((mp = tcp->tcp_rcv_list) != NULL) {
2315 		tcp->tcp_rcv_list = mp->b_next;
2316 		mp->b_next = NULL;
2317 #ifdef DEBUG
2318 		cnt += msgdsize(mp);
2319 #endif
2320 		putnext(q, mp);
2321 	}
2322 
2323 	ASSERT(cnt == tcp->tcp_rcv_cnt);
2324 	tcp->tcp_rcv_last_head = NULL;
2325 	tcp->tcp_rcv_last_tail = NULL;
2326 	tcp->tcp_rcv_cnt = 0;
2327 	tcp->tcp_rwnd = q->q_hiwat;
2328 
2329 	return (B_TRUE);
2330 }
2331 
2332 /*
2333  * This is the walker function, which is TCP specific.
2334  * It walks through the conn_hash bucket searching for the
2335  * next valid connp/tcp in the list, selecting connp/tcp
2336  * which haven't closed or condemned. It also REFHOLDS the
2337  * reference for the tcp, ensuring that the tcp exists
2338  * when the caller uses the tcp.
2339  *
2340  * tcp_get_next_conn
2341  * 	get the next entry in the conn global list
2342  * 	and put a reference on the next_conn.
2343  * 	decrement the reference on the current conn.
2344  */
2345 conn_t *
2346 tcp_get_next_conn(connf_t *connfp, conn_t *connp)
2347 {
2348 	conn_t	*next_connp;
2349 
2350 	if (connfp == NULL)
2351 		return (NULL);
2352 
2353 	mutex_enter(&connfp->connf_lock);
2354 
2355 	next_connp = (connp == NULL) ?
2356 	    connfp->connf_head : connp->conn_g_next;
2357 
2358 	while (next_connp != NULL) {
2359 		mutex_enter(&next_connp->conn_lock);
2360 		if ((next_connp->conn_state_flags &
2361 		    (CONN_CONDEMNED | CONN_INCIPIENT)) ||
2362 			!IPCL_IS_TCP(next_connp)) {
2363 			/*
2364 			 * This conn has been condemned or
2365 			 * is closing.
2366 			 */
2367 			mutex_exit(&next_connp->conn_lock);
2368 			next_connp = next_connp->conn_g_next;
2369 			continue;
2370 		}
2371 		ASSERT(next_connp->conn_tcp != NULL);
2372 		CONN_INC_REF_LOCKED(next_connp);
2373 		mutex_exit(&next_connp->conn_lock);
2374 		break;
2375 	}
2376 
2377 	mutex_exit(&connfp->connf_lock);
2378 
2379 	if (connp != NULL) {
2380 		CONN_DEC_REF(connp);
2381 	}
2382 
2383 	return (next_connp);
2384 }
2385 
2386 /*
2387  * Figure out the value of window scale opton.  Note that the rwnd is
2388  * ASSUMED to be rounded up to the nearest MSS before the calculation.
2389  * We cannot find the scale value and then do a round up of tcp_rwnd
2390  * because the scale value may not be correct after that.
2391  *
2392  * Set the compiler flag to make this function inline.
2393  */
2394 static void
2395 tcp_set_ws_value(tcp_t *tcp)
2396 {
2397 	int i;
2398 	uint32_t rwnd = tcp->tcp_rwnd;
2399 
2400 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
2401 	    i++, rwnd >>= 1)
2402 		;
2403 	tcp->tcp_rcv_ws = i;
2404 }
2405 
2406 /*
2407  * Remove a connection from the list of detached TIME_WAIT connections.
2408  */
2409 static void
2410 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
2411 {
2412 	boolean_t	locked = B_FALSE;
2413 
2414 	if (tcp_time_wait == NULL) {
2415 		tcp_time_wait = *((tcp_squeue_priv_t **)
2416 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
2417 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2418 		locked = B_TRUE;
2419 	}
2420 
2421 	if (tcp->tcp_time_wait_expire == 0) {
2422 		ASSERT(tcp->tcp_time_wait_next == NULL);
2423 		ASSERT(tcp->tcp_time_wait_prev == NULL);
2424 		if (locked)
2425 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2426 		return;
2427 	}
2428 	ASSERT(TCP_IS_DETACHED(tcp));
2429 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
2430 
2431 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
2432 		ASSERT(tcp->tcp_time_wait_prev == NULL);
2433 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
2434 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
2435 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
2436 			    NULL;
2437 		} else {
2438 			tcp_time_wait->tcp_time_wait_tail = NULL;
2439 		}
2440 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
2441 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
2442 		ASSERT(tcp->tcp_time_wait_next == NULL);
2443 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
2444 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
2445 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
2446 	} else {
2447 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
2448 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
2449 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
2450 		    tcp->tcp_time_wait_next;
2451 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
2452 		    tcp->tcp_time_wait_prev;
2453 	}
2454 	tcp->tcp_time_wait_next = NULL;
2455 	tcp->tcp_time_wait_prev = NULL;
2456 	tcp->tcp_time_wait_expire = 0;
2457 
2458 	if (locked)
2459 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2460 }
2461 
2462 /*
2463  * Add a connection to the list of detached TIME_WAIT connections
2464  * and set its time to expire.
2465  */
2466 static void
2467 tcp_time_wait_append(tcp_t *tcp)
2468 {
2469 	tcp_squeue_priv_t *tcp_time_wait =
2470 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
2471 		SQPRIVATE_TCP));
2472 
2473 	tcp_timers_stop(tcp);
2474 
2475 	/* Freed above */
2476 	ASSERT(tcp->tcp_timer_tid == 0);
2477 	ASSERT(tcp->tcp_ack_tid == 0);
2478 
2479 	/* must have happened at the time of detaching the tcp */
2480 	ASSERT(tcp->tcp_ptpahn == NULL);
2481 	ASSERT(tcp->tcp_flow_stopped == 0);
2482 	ASSERT(tcp->tcp_time_wait_next == NULL);
2483 	ASSERT(tcp->tcp_time_wait_prev == NULL);
2484 	ASSERT(tcp->tcp_time_wait_expire == NULL);
2485 	ASSERT(tcp->tcp_listener == NULL);
2486 
2487 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
2488 	/*
2489 	 * The value computed below in tcp->tcp_time_wait_expire may
2490 	 * appear negative or wrap around. That is ok since our
2491 	 * interest is only in the difference between the current lbolt
2492 	 * value and tcp->tcp_time_wait_expire. But the value should not
2493 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
2494 	 * The corresponding comparison in tcp_time_wait_collector() uses
2495 	 * modular arithmetic.
2496 	 */
2497 	tcp->tcp_time_wait_expire +=
2498 	    drv_usectohz(tcp_time_wait_interval * 1000);
2499 	if (tcp->tcp_time_wait_expire == 0)
2500 		tcp->tcp_time_wait_expire = 1;
2501 
2502 	ASSERT(TCP_IS_DETACHED(tcp));
2503 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
2504 	ASSERT(tcp->tcp_time_wait_next == NULL);
2505 	ASSERT(tcp->tcp_time_wait_prev == NULL);
2506 	TCP_DBGSTAT(tcp_time_wait);
2507 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2508 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
2509 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
2510 		tcp_time_wait->tcp_time_wait_head = tcp;
2511 	} else {
2512 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
2513 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
2514 		    TCPS_TIME_WAIT);
2515 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
2516 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
2517 	}
2518 	tcp_time_wait->tcp_time_wait_tail = tcp;
2519 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2520 }
2521 
2522 /* ARGSUSED */
2523 void
2524 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
2525 {
2526 	conn_t	*connp = (conn_t *)arg;
2527 	tcp_t	*tcp = connp->conn_tcp;
2528 
2529 	ASSERT(tcp != NULL);
2530 	if (tcp->tcp_state == TCPS_CLOSED) {
2531 		return;
2532 	}
2533 
2534 	ASSERT((tcp->tcp_family == AF_INET &&
2535 	    tcp->tcp_ipversion == IPV4_VERSION) ||
2536 	    (tcp->tcp_family == AF_INET6 &&
2537 	    (tcp->tcp_ipversion == IPV4_VERSION ||
2538 	    tcp->tcp_ipversion == IPV6_VERSION)));
2539 	ASSERT(!tcp->tcp_listener);
2540 
2541 	TCP_STAT(tcp_time_wait_reap);
2542 	ASSERT(TCP_IS_DETACHED(tcp));
2543 
2544 	/*
2545 	 * Because they have no upstream client to rebind or tcp_close()
2546 	 * them later, we axe the connection here and now.
2547 	 */
2548 	tcp_close_detached(tcp);
2549 }
2550 
2551 void
2552 tcp_cleanup(tcp_t *tcp)
2553 {
2554 	mblk_t		*mp;
2555 	char		*tcp_iphc;
2556 	int		tcp_iphc_len;
2557 	int		tcp_hdr_grown;
2558 	tcp_sack_info_t	*tcp_sack_info;
2559 	conn_t		*connp = tcp->tcp_connp;
2560 
2561 	tcp_bind_hash_remove(tcp);
2562 	tcp_free(tcp);
2563 
2564 	conn_delete_ire(connp, NULL);
2565 	if (connp->conn_flags & IPCL_TCPCONN) {
2566 		if (connp->conn_latch != NULL)
2567 			IPLATCH_REFRELE(connp->conn_latch);
2568 		if (connp->conn_policy != NULL)
2569 			IPPH_REFRELE(connp->conn_policy);
2570 	}
2571 
2572 	/*
2573 	 * Since we will bzero the entire structure, we need to
2574 	 * remove it and reinsert it in global hash list. We
2575 	 * know the walkers can't get to this conn because we
2576 	 * had set CONDEMNED flag earlier and checked reference
2577 	 * under conn_lock so walker won't pick it and when we
2578 	 * go the ipcl_globalhash_remove() below, no walker
2579 	 * can get to it.
2580 	 */
2581 	ipcl_globalhash_remove(connp);
2582 
2583 	/* Save some state */
2584 	mp = tcp->tcp_timercache;
2585 
2586 	tcp_sack_info = tcp->tcp_sack_info;
2587 	tcp_iphc = tcp->tcp_iphc;
2588 	tcp_iphc_len = tcp->tcp_iphc_len;
2589 	tcp_hdr_grown = tcp->tcp_hdr_grown;
2590 
2591 	bzero(connp, sizeof (conn_t));
2592 	bzero(tcp, sizeof (tcp_t));
2593 
2594 	/* restore the state */
2595 	tcp->tcp_timercache = mp;
2596 
2597 	tcp->tcp_sack_info = tcp_sack_info;
2598 	tcp->tcp_iphc = tcp_iphc;
2599 	tcp->tcp_iphc_len = tcp_iphc_len;
2600 	tcp->tcp_hdr_grown = tcp_hdr_grown;
2601 
2602 
2603 	tcp->tcp_connp = connp;
2604 
2605 	connp->conn_tcp = tcp;
2606 	connp->conn_flags = IPCL_TCPCONN;
2607 	connp->conn_state_flags = CONN_INCIPIENT;
2608 	connp->conn_ulp = IPPROTO_TCP;
2609 	connp->conn_ref = 1;
2610 
2611 	ipcl_globalhash_insert(connp);
2612 }
2613 
2614 /*
2615  * Blows away all tcps whose TIME_WAIT has expired. List traversal
2616  * is done forwards from the head.
2617  */
2618 /* ARGSUSED */
2619 void
2620 tcp_time_wait_collector(void *arg)
2621 {
2622 	tcp_t *tcp;
2623 	clock_t now;
2624 	mblk_t *mp;
2625 	conn_t *connp;
2626 	kmutex_t *lock;
2627 
2628 	squeue_t *sqp = (squeue_t *)arg;
2629 	tcp_squeue_priv_t *tcp_time_wait =
2630 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
2631 
2632 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2633 	tcp_time_wait->tcp_time_wait_tid = 0;
2634 
2635 	if (tcp_time_wait->tcp_free_list != NULL &&
2636 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
2637 		TCP_STAT(tcp_freelist_cleanup);
2638 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
2639 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
2640 			CONN_DEC_REF(tcp->tcp_connp);
2641 		}
2642 	}
2643 
2644 	/*
2645 	 * In order to reap time waits reliably, we should use a
2646 	 * source of time that is not adjustable by the user -- hence
2647 	 * the call to ddi_get_lbolt().
2648 	 */
2649 	now = ddi_get_lbolt();
2650 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
2651 		/*
2652 		 * Compare times using modular arithmetic, since
2653 		 * lbolt can wrapover.
2654 		 */
2655 		if ((now - tcp->tcp_time_wait_expire) < 0) {
2656 			break;
2657 		}
2658 
2659 		tcp_time_wait_remove(tcp, tcp_time_wait);
2660 
2661 		connp = tcp->tcp_connp;
2662 		ASSERT(connp->conn_fanout != NULL);
2663 		lock = &connp->conn_fanout->connf_lock;
2664 		/*
2665 		 * This is essentially a TW reclaim fast path optimization for
2666 		 * performance where the timewait collector checks under the
2667 		 * fanout lock (so that no one else can get access to the
2668 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
2669 		 * the classifier hash list. If ref count is indeed 2, we can
2670 		 * just remove the conn under the fanout lock and avoid
2671 		 * cleaning up the conn under the squeue, provided that
2672 		 * clustering callbacks are not enabled. If clustering is
2673 		 * enabled, we need to make the clustering callback before
2674 		 * setting the CONDEMNED flag and after dropping all locks and
2675 		 * so we forego this optimization and fall back to the slow
2676 		 * path. Also please see the comments in tcp_closei_local
2677 		 * regarding the refcnt logic.
2678 		 *
2679 		 * Since we are holding the tcp_time_wait_lock, its better
2680 		 * not to block on the fanout_lock because other connections
2681 		 * can't add themselves to time_wait list. So we do a
2682 		 * tryenter instead of mutex_enter.
2683 		 */
2684 		if (mutex_tryenter(lock)) {
2685 			mutex_enter(&connp->conn_lock);
2686 			if ((connp->conn_ref == 2) &&
2687 			    (cl_inet_disconnect == NULL)) {
2688 				ipcl_hash_remove_locked(connp,
2689 				    connp->conn_fanout);
2690 				/*
2691 				 * Set the CONDEMNED flag now itself so that
2692 				 * the refcnt cannot increase due to any
2693 				 * walker. But we have still not cleaned up
2694 				 * conn_ire_cache. This is still ok since
2695 				 * we are going to clean it up in tcp_cleanup
2696 				 * immediately and any interface unplumb
2697 				 * thread will wait till the ire is blown away
2698 				 */
2699 				connp->conn_state_flags |= CONN_CONDEMNED;
2700 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2701 				mutex_exit(lock);
2702 				mutex_exit(&connp->conn_lock);
2703 				tcp_cleanup(tcp);
2704 				mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2705 				tcp->tcp_time_wait_next =
2706 				    tcp_time_wait->tcp_free_list;
2707 				tcp_time_wait->tcp_free_list = tcp;
2708 				continue;
2709 			} else {
2710 				CONN_INC_REF_LOCKED(connp);
2711 				mutex_exit(lock);
2712 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2713 				mutex_exit(&connp->conn_lock);
2714 				/*
2715 				 * We can reuse the closemp here since conn has
2716 				 * detached (otherwise we wouldn't even be in
2717 				 * time_wait list).
2718 				 */
2719 				mp = &tcp->tcp_closemp;
2720 				squeue_fill(connp->conn_sqp, mp,
2721 				    tcp_timewait_output, connp,
2722 				    SQTAG_TCP_TIMEWAIT);
2723 			}
2724 		} else {
2725 			mutex_enter(&connp->conn_lock);
2726 			CONN_INC_REF_LOCKED(connp);
2727 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2728 			mutex_exit(&connp->conn_lock);
2729 			/*
2730 			 * We can reuse the closemp here since conn has
2731 			 * detached (otherwise we wouldn't even be in
2732 			 * time_wait list).
2733 			 */
2734 			mp = &tcp->tcp_closemp;
2735 			squeue_fill(connp->conn_sqp, mp,
2736 			    tcp_timewait_output, connp, 0);
2737 		}
2738 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2739 	}
2740 
2741 	if (tcp_time_wait->tcp_free_list != NULL)
2742 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
2743 
2744 	tcp_time_wait->tcp_time_wait_tid =
2745 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
2746 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2747 }
2748 
2749 /*
2750  * Reply to a clients T_CONN_RES TPI message. This function
2751  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
2752  * on the acceptor STREAM and processed in tcp_wput_accept().
2753  * Read the block comment on top of tcp_conn_request().
2754  */
2755 static void
2756 tcp_accept(tcp_t *listener, mblk_t *mp)
2757 {
2758 	tcp_t	*acceptor;
2759 	tcp_t	*eager;
2760 	tcp_t   *tcp;
2761 	struct T_conn_res	*tcr;
2762 	t_uscalar_t	acceptor_id;
2763 	t_scalar_t	seqnum;
2764 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
2765 	mblk_t	*ok_mp;
2766 	mblk_t	*mp1;
2767 
2768 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
2769 		tcp_err_ack(listener, mp, TPROTO, 0);
2770 		return;
2771 	}
2772 	tcr = (struct T_conn_res *)mp->b_rptr;
2773 
2774 	/*
2775 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
2776 	 * read side queue of the streams device underneath us i.e. the
2777 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
2778 	 * look it up in the queue_hash.  Under LP64 it sends down the
2779 	 * minor_t of the accepting endpoint.
2780 	 *
2781 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
2782 	 * fanout hash lock is held.
2783 	 * This prevents any thread from entering the acceptor queue from
2784 	 * below (since it has not been hard bound yet i.e. any inbound
2785 	 * packets will arrive on the listener or default tcp queue and
2786 	 * go through tcp_lookup).
2787 	 * The CONN_INC_REF will prevent the acceptor from closing.
2788 	 *
2789 	 * XXX It is still possible for a tli application to send down data
2790 	 * on the accepting stream while another thread calls t_accept.
2791 	 * This should not be a problem for well-behaved applications since
2792 	 * the T_OK_ACK is sent after the queue swapping is completed.
2793 	 *
2794 	 * If the accepting fd is the same as the listening fd, avoid
2795 	 * queue hash lookup since that will return an eager listener in a
2796 	 * already established state.
2797 	 */
2798 	acceptor_id = tcr->ACCEPTOR_id;
2799 	mutex_enter(&listener->tcp_eager_lock);
2800 	if (listener->tcp_acceptor_id == acceptor_id) {
2801 		eager = listener->tcp_eager_next_q;
2802 		/* only count how many T_CONN_INDs so don't count q0 */
2803 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2804 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2805 			mutex_exit(&listener->tcp_eager_lock);
2806 			tcp_err_ack(listener, mp, TBADF, 0);
2807 			return;
2808 		}
2809 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2810 			/* Throw away all the eagers on q0. */
2811 			tcp_eager_cleanup(listener, 1);
2812 		}
2813 		if (listener->tcp_syn_defense) {
2814 			listener->tcp_syn_defense = B_FALSE;
2815 			if (listener->tcp_ip_addr_cache != NULL) {
2816 				kmem_free(listener->tcp_ip_addr_cache,
2817 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2818 				listener->tcp_ip_addr_cache = NULL;
2819 			}
2820 		}
2821 		/*
2822 		 * Transfer tcp_conn_req_max to the eager so that when
2823 		 * a disconnect occurs we can revert the endpoint to the
2824 		 * listen state.
2825 		 */
2826 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2827 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2828 		/*
2829 		 * Get a reference on the acceptor just like the
2830 		 * tcp_acceptor_hash_lookup below.
2831 		 */
2832 		acceptor = listener;
2833 		CONN_INC_REF(acceptor->tcp_connp);
2834 	} else {
2835 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
2836 		if (acceptor == NULL) {
2837 			if (listener->tcp_debug) {
2838 				(void) strlog(TCP_MODULE_ID, 0, 1,
2839 				    SL_ERROR|SL_TRACE,
2840 				    "tcp_accept: did not find acceptor 0x%x\n",
2841 				    acceptor_id);
2842 			}
2843 			mutex_exit(&listener->tcp_eager_lock);
2844 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2845 			return;
2846 		}
2847 		/*
2848 		 * Verify acceptor state. The acceptable states for an acceptor
2849 		 * include TCPS_IDLE and TCPS_BOUND.
2850 		 */
2851 		switch (acceptor->tcp_state) {
2852 		case TCPS_IDLE:
2853 			/* FALLTHRU */
2854 		case TCPS_BOUND:
2855 			break;
2856 		default:
2857 			CONN_DEC_REF(acceptor->tcp_connp);
2858 			mutex_exit(&listener->tcp_eager_lock);
2859 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2860 			return;
2861 		}
2862 	}
2863 
2864 	/* The listener must be in TCPS_LISTEN */
2865 	if (listener->tcp_state != TCPS_LISTEN) {
2866 		CONN_DEC_REF(acceptor->tcp_connp);
2867 		mutex_exit(&listener->tcp_eager_lock);
2868 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2869 		return;
2870 	}
2871 
2872 	/*
2873 	 * Rendezvous with an eager connection request packet hanging off
2874 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2875 	 * tcp structure when the connection packet arrived in
2876 	 * tcp_conn_request().
2877 	 */
2878 	seqnum = tcr->SEQ_number;
2879 	eager = listener;
2880 	do {
2881 		eager = eager->tcp_eager_next_q;
2882 		if (eager == NULL) {
2883 			CONN_DEC_REF(acceptor->tcp_connp);
2884 			mutex_exit(&listener->tcp_eager_lock);
2885 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2886 			return;
2887 		}
2888 	} while (eager->tcp_conn_req_seqnum != seqnum);
2889 	mutex_exit(&listener->tcp_eager_lock);
2890 
2891 	/*
2892 	 * At this point, both acceptor and listener have 2 ref
2893 	 * that they begin with. Acceptor has one additional ref
2894 	 * we placed in lookup while listener has 3 additional
2895 	 * ref for being behind the squeue (tcp_accept() is
2896 	 * done on listener's squeue); being in classifier hash;
2897 	 * and eager's ref on listener.
2898 	 */
2899 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2900 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2901 
2902 	/*
2903 	 * The eager at this point is set in its own squeue and
2904 	 * could easily have been killed (tcp_accept_finish will
2905 	 * deal with that) because of a TH_RST so we can only
2906 	 * ASSERT for a single ref.
2907 	 */
2908 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2909 
2910 	/* Pre allocate the stroptions mblk also */
2911 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2912 	if (opt_mp == NULL) {
2913 		CONN_DEC_REF(acceptor->tcp_connp);
2914 		CONN_DEC_REF(eager->tcp_connp);
2915 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2916 		return;
2917 	}
2918 	DB_TYPE(opt_mp) = M_SETOPTS;
2919 	opt_mp->b_wptr += sizeof (struct stroptions);
2920 
2921 	/*
2922 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2923 	 * from listener to acceptor. The message is chained on opt_mp
2924 	 * which will be sent onto eager's squeue.
2925 	 */
2926 	if (listener->tcp_bound_if != 0) {
2927 		/* allocate optmgmt req */
2928 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2929 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2930 		    sizeof (int));
2931 		if (mp1 != NULL)
2932 			linkb(opt_mp, mp1);
2933 	}
2934 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2935 		uint_t on = 1;
2936 
2937 		/* allocate optmgmt req */
2938 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2939 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2940 		if (mp1 != NULL)
2941 			linkb(opt_mp, mp1);
2942 	}
2943 
2944 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2945 	if ((mp1 = copymsg(mp)) == NULL) {
2946 		CONN_DEC_REF(acceptor->tcp_connp);
2947 		CONN_DEC_REF(eager->tcp_connp);
2948 		freemsg(opt_mp);
2949 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2950 		return;
2951 	}
2952 
2953 	tcr = (struct T_conn_res *)mp1->b_rptr;
2954 
2955 	/*
2956 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2957 	 * which allocates a larger mblk and appends the new
2958 	 * local address to the ok_ack.  The address is copied by
2959 	 * soaccept() for getsockname().
2960 	 */
2961 	{
2962 		int extra;
2963 
2964 		extra = (eager->tcp_family == AF_INET) ?
2965 		    sizeof (sin_t) : sizeof (sin6_t);
2966 
2967 		/*
2968 		 * Try to re-use mp, if possible.  Otherwise, allocate
2969 		 * an mblk and return it as ok_mp.  In any case, mp
2970 		 * is no longer usable upon return.
2971 		 */
2972 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2973 			CONN_DEC_REF(acceptor->tcp_connp);
2974 			CONN_DEC_REF(eager->tcp_connp);
2975 			freemsg(opt_mp);
2976 			/* Original mp has been freed by now, so use mp1 */
2977 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2978 			return;
2979 		}
2980 
2981 		mp = NULL;	/* We should never use mp after this point */
2982 
2983 		switch (extra) {
2984 		case sizeof (sin_t): {
2985 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2986 
2987 				ok_mp->b_wptr += extra;
2988 				sin->sin_family = AF_INET;
2989 				sin->sin_port = eager->tcp_lport;
2990 				sin->sin_addr.s_addr =
2991 				    eager->tcp_ipha->ipha_src;
2992 				break;
2993 			}
2994 		case sizeof (sin6_t): {
2995 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2996 
2997 				ok_mp->b_wptr += extra;
2998 				sin6->sin6_family = AF_INET6;
2999 				sin6->sin6_port = eager->tcp_lport;
3000 				if (eager->tcp_ipversion == IPV4_VERSION) {
3001 					sin6->sin6_flowinfo = 0;
3002 					IN6_IPADDR_TO_V4MAPPED(
3003 					    eager->tcp_ipha->ipha_src,
3004 					    &sin6->sin6_addr);
3005 				} else {
3006 					ASSERT(eager->tcp_ip6h != NULL);
3007 					sin6->sin6_flowinfo =
3008 					    eager->tcp_ip6h->ip6_vcf &
3009 					    ~IPV6_VERS_AND_FLOW_MASK;
3010 					sin6->sin6_addr =
3011 					    eager->tcp_ip6h->ip6_src;
3012 				}
3013 				break;
3014 			}
3015 		default:
3016 			break;
3017 		}
3018 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
3019 	}
3020 
3021 	/*
3022 	 * If there are no options we know that the T_CONN_RES will
3023 	 * succeed. However, we can't send the T_OK_ACK upstream until
3024 	 * the tcp_accept_swap is done since it would be dangerous to
3025 	 * let the application start using the new fd prior to the swap.
3026 	 */
3027 	tcp_accept_swap(listener, acceptor, eager);
3028 
3029 	/*
3030 	 * tcp_accept_swap unlinks eager from listener but does not drop
3031 	 * the eager's reference on the listener.
3032 	 */
3033 	ASSERT(eager->tcp_listener == NULL);
3034 	ASSERT(listener->tcp_connp->conn_ref >= 5);
3035 
3036 	/*
3037 	 * The eager is now associated with its own queue. Insert in
3038 	 * the hash so that the connection can be reused for a future
3039 	 * T_CONN_RES.
3040 	 */
3041 	tcp_acceptor_hash_insert(acceptor_id, eager);
3042 
3043 	/*
3044 	 * We now do the processing of options with T_CONN_RES.
3045 	 * We delay till now since we wanted to have queue to pass to
3046 	 * option processing routines that points back to the right
3047 	 * instance structure which does not happen until after
3048 	 * tcp_accept_swap().
3049 	 *
3050 	 * Note:
3051 	 * The sanity of the logic here assumes that whatever options
3052 	 * are appropriate to inherit from listner=>eager are done
3053 	 * before this point, and whatever were to be overridden (or not)
3054 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
3055 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
3056 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
3057 	 * This may not be true at this point in time but can be fixed
3058 	 * independently. This option processing code starts with
3059 	 * the instantiated acceptor instance and the final queue at
3060 	 * this point.
3061 	 */
3062 
3063 	if (tcr->OPT_length != 0) {
3064 		/* Options to process */
3065 		int t_error = 0;
3066 		int sys_error = 0;
3067 		int do_disconnect = 0;
3068 
3069 		if (tcp_conprim_opt_process(eager, mp1,
3070 		    &do_disconnect, &t_error, &sys_error) < 0) {
3071 			eager->tcp_accept_error = 1;
3072 			if (do_disconnect) {
3073 				/*
3074 				 * An option failed which does not allow
3075 				 * connection to be accepted.
3076 				 *
3077 				 * We allow T_CONN_RES to succeed and
3078 				 * put a T_DISCON_IND on the eager queue.
3079 				 */
3080 				ASSERT(t_error == 0 && sys_error == 0);
3081 				eager->tcp_send_discon_ind = 1;
3082 			} else {
3083 				ASSERT(t_error != 0);
3084 				freemsg(ok_mp);
3085 				/*
3086 				 * Original mp was either freed or set
3087 				 * to ok_mp above, so use mp1 instead.
3088 				 */
3089 				tcp_err_ack(listener, mp1, t_error, sys_error);
3090 				goto finish;
3091 			}
3092 		}
3093 		/*
3094 		 * Most likely success in setting options (except if
3095 		 * eager->tcp_send_discon_ind set).
3096 		 * mp1 option buffer represented by OPT_length/offset
3097 		 * potentially modified and contains results of setting
3098 		 * options at this point
3099 		 */
3100 	}
3101 
3102 	/* We no longer need mp1, since all options processing has passed */
3103 	freemsg(mp1);
3104 
3105 	putnext(listener->tcp_rq, ok_mp);
3106 
3107 	mutex_enter(&listener->tcp_eager_lock);
3108 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
3109 		tcp_t	*tail;
3110 		mblk_t	*conn_ind;
3111 
3112 		/*
3113 		 * This path should not be executed if listener and
3114 		 * acceptor streams are the same.
3115 		 */
3116 		ASSERT(listener != acceptor);
3117 
3118 		tcp = listener->tcp_eager_prev_q0;
3119 		/*
3120 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
3121 		 * deferred T_conn_ind queue. We need to get to the head of
3122 		 * the queue in order to send up T_conn_ind the same order as
3123 		 * how the 3WHS is completed.
3124 		 */
3125 		while (tcp != listener) {
3126 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
3127 				break;
3128 			else
3129 				tcp = tcp->tcp_eager_prev_q0;
3130 		}
3131 		ASSERT(tcp != listener);
3132 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
3133 		ASSERT(conn_ind != NULL);
3134 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
3135 
3136 		/* Move from q0 to q */
3137 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
3138 		listener->tcp_conn_req_cnt_q0--;
3139 		listener->tcp_conn_req_cnt_q++;
3140 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
3141 		    tcp->tcp_eager_prev_q0;
3142 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
3143 		    tcp->tcp_eager_next_q0;
3144 		tcp->tcp_eager_prev_q0 = NULL;
3145 		tcp->tcp_eager_next_q0 = NULL;
3146 		tcp->tcp_conn_def_q0 = B_FALSE;
3147 
3148 		/*
3149 		 * Insert at end of the queue because sockfs sends
3150 		 * down T_CONN_RES in chronological order. Leaving
3151 		 * the older conn indications at front of the queue
3152 		 * helps reducing search time.
3153 		 */
3154 		tail = listener->tcp_eager_last_q;
3155 		if (tail != NULL)
3156 			tail->tcp_eager_next_q = tcp;
3157 		else
3158 			listener->tcp_eager_next_q = tcp;
3159 		listener->tcp_eager_last_q = tcp;
3160 		tcp->tcp_eager_next_q = NULL;
3161 		mutex_exit(&listener->tcp_eager_lock);
3162 		putnext(tcp->tcp_rq, conn_ind);
3163 	} else {
3164 		mutex_exit(&listener->tcp_eager_lock);
3165 	}
3166 
3167 	/*
3168 	 * Done with the acceptor - free it
3169 	 *
3170 	 * Note: from this point on, no access to listener should be made
3171 	 * as listener can be equal to acceptor.
3172 	 */
3173 finish:
3174 	ASSERT(acceptor->tcp_detached);
3175 	acceptor->tcp_rq = tcp_g_q;
3176 	acceptor->tcp_wq = WR(tcp_g_q);
3177 	(void) tcp_clean_death(acceptor, 0, 2);
3178 	CONN_DEC_REF(acceptor->tcp_connp);
3179 
3180 	/*
3181 	 * In case we already received a FIN we have to make tcp_rput send
3182 	 * the ordrel_ind. This will also send up a window update if the window
3183 	 * has opened up.
3184 	 *
3185 	 * In the normal case of a successful connection acceptance
3186 	 * we give the O_T_BIND_REQ to the read side put procedure as an
3187 	 * indication that this was just accepted. This tells tcp_rput to
3188 	 * pass up any data queued in tcp_rcv_list.
3189 	 *
3190 	 * In the fringe case where options sent with T_CONN_RES failed and
3191 	 * we required, we would be indicating a T_DISCON_IND to blow
3192 	 * away this connection.
3193 	 */
3194 
3195 	/*
3196 	 * XXX: we currently have a problem if XTI application closes the
3197 	 * acceptor stream in between. This problem exists in on10-gate also
3198 	 * and is well know but nothing can be done short of major rewrite
3199 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
3200 	 * eager same squeue as listener (we can distinguish non socket
3201 	 * listeners at the time of handling a SYN in tcp_conn_request)
3202 	 * and do most of the work that tcp_accept_finish does here itself
3203 	 * and then get behind the acceptor squeue to access the acceptor
3204 	 * queue.
3205 	 */
3206 	/*
3207 	 * We already have a ref on tcp so no need to do one before squeue_fill
3208 	 */
3209 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
3210 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
3211 }
3212 
3213 /*
3214  * Swap information between the eager and acceptor for a TLI/XTI client.
3215  * The sockfs accept is done on the acceptor stream and control goes
3216  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
3217  * called. In either case, both the eager and listener are in their own
3218  * perimeter (squeue) and the code has to deal with potential race.
3219  *
3220  * See the block comment on top of tcp_accept() and tcp_wput_accept().
3221  */
3222 static void
3223 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
3224 {
3225 	conn_t	*econnp, *aconnp;
3226 
3227 	ASSERT(eager->tcp_rq == listener->tcp_rq);
3228 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
3229 	ASSERT(!eager->tcp_hard_bound);
3230 	ASSERT(!TCP_IS_SOCKET(acceptor));
3231 	ASSERT(!TCP_IS_SOCKET(eager));
3232 	ASSERT(!TCP_IS_SOCKET(listener));
3233 
3234 	acceptor->tcp_detached = B_TRUE;
3235 	/*
3236 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
3237 	 * the acceptor id.
3238 	 */
3239 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
3240 
3241 	/* remove eager from listen list... */
3242 	mutex_enter(&listener->tcp_eager_lock);
3243 	tcp_eager_unlink(eager);
3244 	ASSERT(eager->tcp_eager_next_q == NULL &&
3245 	    eager->tcp_eager_last_q == NULL);
3246 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
3247 	    eager->tcp_eager_prev_q0 == NULL);
3248 	mutex_exit(&listener->tcp_eager_lock);
3249 	eager->tcp_rq = acceptor->tcp_rq;
3250 	eager->tcp_wq = acceptor->tcp_wq;
3251 
3252 	econnp = eager->tcp_connp;
3253 	aconnp = acceptor->tcp_connp;
3254 
3255 	eager->tcp_rq->q_ptr = econnp;
3256 	eager->tcp_wq->q_ptr = econnp;
3257 	eager->tcp_detached = B_FALSE;
3258 
3259 	ASSERT(eager->tcp_ack_tid == 0);
3260 
3261 	econnp->conn_dev = aconnp->conn_dev;
3262 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
3263 	econnp->conn_zoneid = aconnp->conn_zoneid;
3264 	aconnp->conn_cred = NULL;
3265 
3266 	/* Do the IPC initialization */
3267 	CONN_INC_REF(econnp);
3268 
3269 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
3270 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
3271 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
3272 	econnp->conn_ulp = aconnp->conn_ulp;
3273 
3274 	/* Done with old IPC. Drop its ref on its connp */
3275 	CONN_DEC_REF(aconnp);
3276 }
3277 
3278 
3279 /*
3280  * Adapt to the information, such as rtt and rtt_sd, provided from the
3281  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
3282  *
3283  * Checks for multicast and broadcast destination address.
3284  * Returns zero on failure; non-zero if ok.
3285  *
3286  * Note that the MSS calculation here is based on the info given in
3287  * the IRE.  We do not do any calculation based on TCP options.  They
3288  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
3289  * knows which options to use.
3290  *
3291  * Note on how TCP gets its parameters for a connection.
3292  *
3293  * When a tcp_t structure is allocated, it gets all the default parameters.
3294  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
3295  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
3296  * default.  But if there is an associated tcp_host_param, it will override
3297  * the metrics.
3298  *
3299  * An incoming SYN with a multicast or broadcast destination address, is dropped
3300  * in 1 of 2 places.
3301  *
3302  * 1. If the packet was received over the wire it is dropped in
3303  * ip_rput_process_broadcast()
3304  *
3305  * 2. If the packet was received through internal IP loopback, i.e. the packet
3306  * was generated and received on the same machine, it is dropped in
3307  * ip_wput_local()
3308  *
3309  * An incoming SYN with a multicast or broadcast source address is always
3310  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
3311  * reject an attempt to connect to a broadcast or multicast (destination)
3312  * address.
3313  */
3314 static int
3315 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
3316 {
3317 	tcp_hsp_t	*hsp;
3318 	ire_t		*ire;
3319 	ire_t		*sire = NULL;
3320 	iulp_t		*ire_uinfo;
3321 	uint32_t	mss_max;
3322 	uint32_t	mss;
3323 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
3324 	conn_t		*connp = tcp->tcp_connp;
3325 	boolean_t	ire_cacheable = B_FALSE;
3326 	zoneid_t	zoneid = connp->conn_zoneid;
3327 	ill_t		*ill = NULL;
3328 	boolean_t	incoming = (ire_mp == NULL);
3329 
3330 	ASSERT(connp->conn_ire_cache == NULL);
3331 
3332 	if (tcp->tcp_ipversion == IPV4_VERSION) {
3333 
3334 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
3335 			BUMP_MIB(&ip_mib, ipInDiscards);
3336 			return (0);
3337 		}
3338 
3339 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
3340 		if (ire != NULL) {
3341 			ire_cacheable = B_TRUE;
3342 			ire_uinfo = (ire_mp != NULL) ?
3343 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
3344 			    &ire->ire_uinfo;
3345 
3346 		} else {
3347 			if (ire_mp == NULL) {
3348 				ire = ire_ftable_lookup(
3349 				    tcp->tcp_connp->conn_rem,
3350 				    0, 0, 0, NULL, &sire, zoneid, 0,
3351 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
3352 				if (ire == NULL)
3353 					return (0);
3354 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
3355 				    &ire->ire_uinfo;
3356 			} else {
3357 				ire = (ire_t *)ire_mp->b_rptr;
3358 				ire_uinfo =
3359 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
3360 			}
3361 		}
3362 		ASSERT(ire != NULL);
3363 		ASSERT(ire_uinfo != NULL);
3364 
3365 		if ((ire->ire_src_addr == INADDR_ANY) ||
3366 		    (ire->ire_type & IRE_BROADCAST)) {
3367 			/*
3368 			 * ire->ire_mp is non null when ire_mp passed in is used
3369 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
3370 			 */
3371 			if (ire->ire_mp == NULL)
3372 				ire_refrele(ire);
3373 			if (sire != NULL)
3374 				ire_refrele(sire);
3375 			return (0);
3376 		}
3377 
3378 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
3379 			ipaddr_t src_addr;
3380 
3381 			/*
3382 			 * ip_bind_connected() has stored the correct source
3383 			 * address in conn_src.
3384 			 */
3385 			src_addr = tcp->tcp_connp->conn_src;
3386 			tcp->tcp_ipha->ipha_src = src_addr;
3387 			/*
3388 			 * Copy of the src addr. in tcp_t is needed
3389 			 * for the lookup funcs.
3390 			 */
3391 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
3392 		}
3393 		/*
3394 		 * Set the fragment bit so that IP will tell us if the MTU
3395 		 * should change. IP tells us the latest setting of
3396 		 * ip_path_mtu_discovery through ire_frag_flag.
3397 		 */
3398 		if (ip_path_mtu_discovery) {
3399 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
3400 			    htons(IPH_DF);
3401 		}
3402 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
3403 	} else {
3404 		/*
3405 		 * For incoming connection ire_mp = NULL
3406 		 * For outgoing connection ire_mp != NULL
3407 		 * Technically we should check conn_incoming_ill
3408 		 * when ire_mp is NULL and conn_outgoing_ill when
3409 		 * ire_mp is non-NULL. But this is performance
3410 		 * critical path and for IPV*_BOUND_IF, outgoing
3411 		 * and incoming ill are always set to the same value.
3412 		 */
3413 		ill_t	*dst_ill = NULL;
3414 		ipif_t  *dst_ipif = NULL;
3415 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
3416 
3417 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
3418 
3419 		if (connp->conn_outgoing_ill != NULL) {
3420 			/* Outgoing or incoming path */
3421 			int   err;
3422 
3423 			dst_ill = conn_get_held_ill(connp,
3424 			    &connp->conn_outgoing_ill, &err);
3425 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
3426 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
3427 				return (0);
3428 			}
3429 			match_flags |= MATCH_IRE_ILL;
3430 			dst_ipif = dst_ill->ill_ipif;
3431 		}
3432 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
3433 		    0, 0, dst_ipif, zoneid, match_flags);
3434 
3435 		if (ire != NULL) {
3436 			ire_cacheable = B_TRUE;
3437 			ire_uinfo = (ire_mp != NULL) ?
3438 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
3439 			    &ire->ire_uinfo;
3440 		} else {
3441 			if (ire_mp == NULL) {
3442 				ire = ire_ftable_lookup_v6(
3443 				    &tcp->tcp_connp->conn_remv6,
3444 				    0, 0, 0, dst_ipif, &sire, zoneid,
3445 				    0, match_flags);
3446 				if (ire == NULL) {
3447 					if (dst_ill != NULL)
3448 						ill_refrele(dst_ill);
3449 					return (0);
3450 				}
3451 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
3452 				    &ire->ire_uinfo;
3453 			} else {
3454 				ire = (ire_t *)ire_mp->b_rptr;
3455 				ire_uinfo =
3456 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
3457 			}
3458 		}
3459 		if (dst_ill != NULL)
3460 			ill_refrele(dst_ill);
3461 
3462 		ASSERT(ire != NULL);
3463 		ASSERT(ire_uinfo != NULL);
3464 
3465 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
3466 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
3467 			/*
3468 			 * ire->ire_mp is non null when ire_mp passed in is used
3469 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
3470 			 */
3471 			if (ire->ire_mp == NULL)
3472 				ire_refrele(ire);
3473 			if (sire != NULL)
3474 				ire_refrele(sire);
3475 			return (0);
3476 		}
3477 
3478 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
3479 			in6_addr_t	src_addr;
3480 
3481 			/*
3482 			 * ip_bind_connected_v6() has stored the correct source
3483 			 * address per IPv6 addr. selection policy in
3484 			 * conn_src_v6.
3485 			 */
3486 			src_addr = tcp->tcp_connp->conn_srcv6;
3487 
3488 			tcp->tcp_ip6h->ip6_src = src_addr;
3489 			/*
3490 			 * Copy of the src addr. in tcp_t is needed
3491 			 * for the lookup funcs.
3492 			 */
3493 			tcp->tcp_ip_src_v6 = src_addr;
3494 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
3495 			    &connp->conn_srcv6));
3496 		}
3497 		tcp->tcp_localnet =
3498 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
3499 	}
3500 
3501 	/*
3502 	 * This allows applications to fail quickly when connections are made
3503 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
3504 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
3505 	 */
3506 	if ((ire->ire_flags & RTF_REJECT) &&
3507 	    (ire->ire_flags & RTF_PRIVATE))
3508 		goto error;
3509 
3510 	/*
3511 	 * Make use of the cached rtt and rtt_sd values to calculate the
3512 	 * initial RTO.  Note that they are already initialized in
3513 	 * tcp_init_values().
3514 	 */
3515 	if (ire_uinfo->iulp_rtt != 0) {
3516 		clock_t	rto;
3517 
3518 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
3519 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
3520 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
3521 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
3522 
3523 		if (rto > tcp_rexmit_interval_max) {
3524 			tcp->tcp_rto = tcp_rexmit_interval_max;
3525 		} else if (rto < tcp_rexmit_interval_min) {
3526 			tcp->tcp_rto = tcp_rexmit_interval_min;
3527 		} else {
3528 			tcp->tcp_rto = rto;
3529 		}
3530 	}
3531 	if (ire_uinfo->iulp_ssthresh != 0)
3532 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
3533 	else
3534 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
3535 	if (ire_uinfo->iulp_spipe > 0) {
3536 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
3537 		    tcp_max_buf);
3538 		if (tcp_snd_lowat_fraction != 0)
3539 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
3540 			    tcp_snd_lowat_fraction;
3541 		(void) tcp_maxpsz_set(tcp, B_TRUE);
3542 	}
3543 	/*
3544 	 * Note that up till now, acceptor always inherits receive
3545 	 * window from the listener.  But if there is a metrics associated
3546 	 * with a host, we should use that instead of inheriting it from
3547 	 * listener.  Thus we need to pass this info back to the caller.
3548 	 */
3549 	if (ire_uinfo->iulp_rpipe > 0) {
3550 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
3551 	} else {
3552 		/*
3553 		 * For passive open, set tcp_rwnd to 0 so that the caller
3554 		 * knows that there is no rpipe metric for this connection.
3555 		 */
3556 		if (tcp_detached)
3557 			tcp->tcp_rwnd = 0;
3558 	}
3559 	if (ire_uinfo->iulp_rtomax > 0) {
3560 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
3561 	}
3562 
3563 	/*
3564 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
3565 	 * only for active open.  What this means is that if the other side
3566 	 * uses timestamp or window scale option, TCP will also use those
3567 	 * options.  That is for passive open.  If the application sets a
3568 	 * large window, window scale is enabled regardless of the value in
3569 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
3570 	 * The only case left in passive open processing is the check for SACK.
3571 	 *
3572 	 * For ECN, it should probably be like SACK.  But the current
3573 	 * value is binary, so we treat it like the other cases.  The
3574 	 * metric only controls active open.  For passive open, the ndd
3575 	 * param, tcp_ecn_permitted, controls the behavior.
3576 	 */
3577 	if (!tcp_detached) {
3578 		/*
3579 		 * The if check means that the following can only be turned
3580 		 * on by the metrics only IRE, but not off.
3581 		 */
3582 		if (ire_uinfo->iulp_tstamp_ok)
3583 			tcp->tcp_snd_ts_ok = B_TRUE;
3584 		if (ire_uinfo->iulp_wscale_ok)
3585 			tcp->tcp_snd_ws_ok = B_TRUE;
3586 		if (ire_uinfo->iulp_sack == 2)
3587 			tcp->tcp_snd_sack_ok = B_TRUE;
3588 		if (ire_uinfo->iulp_ecn_ok)
3589 			tcp->tcp_ecn_ok = B_TRUE;
3590 	} else {
3591 		/*
3592 		 * Passive open.
3593 		 *
3594 		 * As above, the if check means that SACK can only be
3595 		 * turned on by the metric only IRE.
3596 		 */
3597 		if (ire_uinfo->iulp_sack > 0) {
3598 			tcp->tcp_snd_sack_ok = B_TRUE;
3599 		}
3600 	}
3601 
3602 	/*
3603 	 * XXX: Note that currently, ire_max_frag can be as small as 68
3604 	 * because of PMTUd.  So tcp_mss may go to negative if combined
3605 	 * length of all those options exceeds 28 bytes.  But because
3606 	 * of the tcp_mss_min check below, we may not have a problem if
3607 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
3608 	 * the negative problem still exists.  And the check defeats PMTUd.
3609 	 * In fact, if PMTUd finds that the MSS should be smaller than
3610 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
3611 	 * value.
3612 	 *
3613 	 * We do not deal with that now.  All those problems related to
3614 	 * PMTUd will be fixed later.
3615 	 */
3616 	ASSERT(ire->ire_max_frag != 0);
3617 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
3618 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
3619 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
3620 			mss = MIN(mss, IPV6_MIN_MTU);
3621 		}
3622 	}
3623 
3624 	/* Sanity check for MSS value. */
3625 	if (tcp->tcp_ipversion == IPV4_VERSION)
3626 		mss_max = tcp_mss_max_ipv4;
3627 	else
3628 		mss_max = tcp_mss_max_ipv6;
3629 
3630 	if (tcp->tcp_ipversion == IPV6_VERSION &&
3631 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
3632 		/*
3633 		 * After receiving an ICMPv6 "packet too big" message with a
3634 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3635 		 * will insert a 8-byte fragment header in every packet; we
3636 		 * reduce the MSS by that amount here.
3637 		 */
3638 		mss -= sizeof (ip6_frag_t);
3639 	}
3640 
3641 	if (tcp->tcp_ipsec_overhead == 0)
3642 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
3643 
3644 	mss -= tcp->tcp_ipsec_overhead;
3645 
3646 	if (mss < tcp_mss_min)
3647 		mss = tcp_mss_min;
3648 	if (mss > mss_max)
3649 		mss = mss_max;
3650 
3651 	/* Note that this is the maximum MSS, excluding all options. */
3652 	tcp->tcp_mss = mss;
3653 
3654 	/*
3655 	 * Initialize the ISS here now that we have the full connection ID.
3656 	 * The RFC 1948 method of initial sequence number generation requires
3657 	 * knowledge of the full connection ID before setting the ISS.
3658 	 */
3659 
3660 	tcp_iss_init(tcp);
3661 
3662 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
3663 		tcp->tcp_loopback = B_TRUE;
3664 
3665 	if (tcp->tcp_ipversion == IPV4_VERSION) {
3666 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
3667 	} else {
3668 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
3669 	}
3670 
3671 	if (hsp != NULL) {
3672 		/* Only modify if we're going to make them bigger */
3673 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
3674 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
3675 			if (tcp_snd_lowat_fraction != 0)
3676 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
3677 					tcp_snd_lowat_fraction;
3678 		}
3679 
3680 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
3681 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
3682 		}
3683 
3684 		/* Copy timestamp flag only for active open */
3685 		if (!tcp_detached)
3686 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
3687 	}
3688 
3689 	if (sire != NULL)
3690 		IRE_REFRELE(sire);
3691 
3692 	/*
3693 	 * If we got an IRE_CACHE and an ILL, go through their properties;
3694 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
3695 	 */
3696 	if (tcp->tcp_loopback ||
3697 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
3698 		/*
3699 		 * For incoming, see if this tcp may be MDT-capable.  For
3700 		 * outgoing, this process has been taken care of through
3701 		 * tcp_rput_other.
3702 		 */
3703 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3704 		tcp->tcp_ire_ill_check_done = B_TRUE;
3705 	}
3706 
3707 	mutex_enter(&connp->conn_lock);
3708 	/*
3709 	 * Make sure that conn is not marked incipient
3710 	 * for incoming connections. A blind
3711 	 * removal of incipient flag is cheaper than
3712 	 * check and removal.
3713 	 */
3714 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3715 
3716 	/* Must not cache forwarding table routes. */
3717 	if (ire_cacheable) {
3718 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3719 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3720 			connp->conn_ire_cache = ire;
3721 			IRE_UNTRACE_REF(ire);
3722 			rw_exit(&ire->ire_bucket->irb_lock);
3723 			mutex_exit(&connp->conn_lock);
3724 			return (1);
3725 		}
3726 		rw_exit(&ire->ire_bucket->irb_lock);
3727 	}
3728 	mutex_exit(&connp->conn_lock);
3729 
3730 	if (ire->ire_mp == NULL)
3731 		ire_refrele(ire);
3732 	return (1);
3733 
3734 error:
3735 	if (ire->ire_mp == NULL)
3736 		ire_refrele(ire);
3737 	if (sire != NULL)
3738 		ire_refrele(sire);
3739 	return (0);
3740 }
3741 
3742 /*
3743  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3744  * O_T_BIND_REQ/T_BIND_REQ message.
3745  */
3746 static void
3747 tcp_bind(tcp_t *tcp, mblk_t *mp)
3748 {
3749 	sin_t	*sin;
3750 	sin6_t	*sin6;
3751 	mblk_t	*mp1;
3752 	in_port_t requested_port;
3753 	in_port_t allocated_port;
3754 	struct T_bind_req *tbr;
3755 	boolean_t	bind_to_req_port_only;
3756 	boolean_t	backlog_update = B_FALSE;
3757 	boolean_t	user_specified;
3758 	in6_addr_t	v6addr;
3759 	ipaddr_t	v4addr;
3760 	uint_t	origipversion;
3761 	int	err;
3762 	queue_t *q = tcp->tcp_wq;
3763 
3764 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3765 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3766 		if (tcp->tcp_debug) {
3767 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3768 			    "tcp_bind: bad req, len %u",
3769 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3770 		}
3771 		tcp_err_ack(tcp, mp, TPROTO, 0);
3772 		return;
3773 	}
3774 	/* Make sure the largest address fits */
3775 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3776 	if (mp1 == NULL) {
3777 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3778 		return;
3779 	}
3780 	mp = mp1;
3781 	tbr = (struct T_bind_req *)mp->b_rptr;
3782 	if (tcp->tcp_state >= TCPS_BOUND) {
3783 		if ((tcp->tcp_state == TCPS_BOUND ||
3784 		    tcp->tcp_state == TCPS_LISTEN) &&
3785 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3786 		    tbr->CONIND_number > 0) {
3787 			/*
3788 			 * Handle listen() increasing CONIND_number.
3789 			 * This is more "liberal" then what the TPI spec
3790 			 * requires but is needed to avoid a t_unbind
3791 			 * when handling listen() since the port number
3792 			 * might be "stolen" between the unbind and bind.
3793 			 */
3794 			backlog_update = B_TRUE;
3795 			goto do_bind;
3796 		}
3797 		if (tcp->tcp_debug) {
3798 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3799 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3800 		}
3801 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3802 		return;
3803 	}
3804 	origipversion = tcp->tcp_ipversion;
3805 
3806 	switch (tbr->ADDR_length) {
3807 	case 0:			/* request for a generic port */
3808 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3809 		if (tcp->tcp_family == AF_INET) {
3810 			tbr->ADDR_length = sizeof (sin_t);
3811 			sin = (sin_t *)&tbr[1];
3812 			*sin = sin_null;
3813 			sin->sin_family = AF_INET;
3814 			mp->b_wptr = (uchar_t *)&sin[1];
3815 			tcp->tcp_ipversion = IPV4_VERSION;
3816 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3817 		} else {
3818 			ASSERT(tcp->tcp_family == AF_INET6);
3819 			tbr->ADDR_length = sizeof (sin6_t);
3820 			sin6 = (sin6_t *)&tbr[1];
3821 			*sin6 = sin6_null;
3822 			sin6->sin6_family = AF_INET6;
3823 			mp->b_wptr = (uchar_t *)&sin6[1];
3824 			tcp->tcp_ipversion = IPV6_VERSION;
3825 			V6_SET_ZERO(v6addr);
3826 		}
3827 		requested_port = 0;
3828 		break;
3829 
3830 	case sizeof (sin_t):	/* Complete IPv4 address */
3831 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3832 		    sizeof (sin_t));
3833 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3834 			if (tcp->tcp_debug) {
3835 				(void) strlog(TCP_MODULE_ID, 0, 1,
3836 				    SL_ERROR|SL_TRACE,
3837 				    "tcp_bind: bad address parameter, "
3838 				    "offset %d, len %d",
3839 				    tbr->ADDR_offset, tbr->ADDR_length);
3840 			}
3841 			tcp_err_ack(tcp, mp, TPROTO, 0);
3842 			return;
3843 		}
3844 		/*
3845 		 * With sockets sockfs will accept bogus sin_family in
3846 		 * bind() and replace it with the family used in the socket
3847 		 * call.
3848 		 */
3849 		if (sin->sin_family != AF_INET ||
3850 		    tcp->tcp_family != AF_INET) {
3851 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3852 			return;
3853 		}
3854 		requested_port = ntohs(sin->sin_port);
3855 		tcp->tcp_ipversion = IPV4_VERSION;
3856 		v4addr = sin->sin_addr.s_addr;
3857 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3858 		break;
3859 
3860 	case sizeof (sin6_t): /* Complete IPv6 address */
3861 		sin6 = (sin6_t *)mi_offset_param(mp,
3862 		    tbr->ADDR_offset, sizeof (sin6_t));
3863 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3864 			if (tcp->tcp_debug) {
3865 				(void) strlog(TCP_MODULE_ID, 0, 1,
3866 				    SL_ERROR|SL_TRACE,
3867 				    "tcp_bind: bad IPv6 address parameter, "
3868 				    "offset %d, len %d", tbr->ADDR_offset,
3869 				    tbr->ADDR_length);
3870 			}
3871 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3872 			return;
3873 		}
3874 		if (sin6->sin6_family != AF_INET6 ||
3875 		    tcp->tcp_family != AF_INET6) {
3876 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3877 			return;
3878 		}
3879 		requested_port = ntohs(sin6->sin6_port);
3880 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3881 		    IPV4_VERSION : IPV6_VERSION;
3882 		v6addr = sin6->sin6_addr;
3883 		break;
3884 
3885 	default:
3886 		if (tcp->tcp_debug) {
3887 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3888 			    "tcp_bind: bad address length, %d",
3889 			    tbr->ADDR_length);
3890 		}
3891 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3892 		return;
3893 	}
3894 	tcp->tcp_bound_source_v6 = v6addr;
3895 
3896 	/* Check for change in ipversion */
3897 	if (origipversion != tcp->tcp_ipversion) {
3898 		ASSERT(tcp->tcp_family == AF_INET6);
3899 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3900 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3901 		if (err) {
3902 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3903 			return;
3904 		}
3905 	}
3906 
3907 	/*
3908 	 * Initialize family specific fields. Copy of the src addr.
3909 	 * in tcp_t is needed for the lookup funcs.
3910 	 */
3911 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3912 		tcp->tcp_ip6h->ip6_src = v6addr;
3913 	} else {
3914 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3915 	}
3916 	tcp->tcp_ip_src_v6 = v6addr;
3917 
3918 	/*
3919 	 * For O_T_BIND_REQ:
3920 	 * Verify that the target port/addr is available, or choose
3921 	 * another.
3922 	 * For  T_BIND_REQ:
3923 	 * Verify that the target port/addr is available or fail.
3924 	 * In both cases when it succeeds the tcp is inserted in the
3925 	 * bind hash table. This ensures that the operation is atomic
3926 	 * under the lock on the hash bucket.
3927 	 */
3928 	bind_to_req_port_only = requested_port != 0 &&
3929 	    tbr->PRIM_type != O_T_BIND_REQ;
3930 	/*
3931 	 * Get a valid port (within the anonymous range and should not
3932 	 * be a privileged one) to use if the user has not given a port.
3933 	 * If multiple threads are here, they may all start with
3934 	 * with the same initial port. But, it should be fine as long as
3935 	 * tcp_bindi will ensure that no two threads will be assigned
3936 	 * the same port.
3937 	 *
3938 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3939 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3940 	 * unless TCP_ANONPRIVBIND option is set.
3941 	 */
3942 	if (requested_port == 0) {
3943 		requested_port = tcp->tcp_anon_priv_bind ?
3944 		    tcp_get_next_priv_port() :
3945 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3946 		user_specified = B_FALSE;
3947 	} else {
3948 		int i;
3949 		boolean_t priv = B_FALSE;
3950 		/*
3951 		 * If the requested_port is in the well-known privileged range,
3952 		 * verify that the stream was opened by a privileged user.
3953 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3954 		 * but instead the code relies on:
3955 		 * - the fact that the address of the array and its size never
3956 		 *   changes
3957 		 * - the atomic assignment of the elements of the array
3958 		 */
3959 		if (requested_port < tcp_smallest_nonpriv_port) {
3960 			priv = B_TRUE;
3961 		} else {
3962 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3963 				if (requested_port ==
3964 				    tcp_g_epriv_ports[i]) {
3965 					priv = B_TRUE;
3966 					break;
3967 				}
3968 			}
3969 		}
3970 		if (priv) {
3971 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3972 
3973 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3974 				if (tcp->tcp_debug) {
3975 					(void) strlog(TCP_MODULE_ID, 0, 1,
3976 					    SL_ERROR|SL_TRACE,
3977 					    "tcp_bind: no priv for port %d",
3978 					    requested_port);
3979 				}
3980 				tcp_err_ack(tcp, mp, TACCES, 0);
3981 				return;
3982 			}
3983 		}
3984 		user_specified = B_TRUE;
3985 	}
3986 
3987 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3988 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3989 
3990 	if (allocated_port == 0) {
3991 		if (bind_to_req_port_only) {
3992 			if (tcp->tcp_debug) {
3993 				(void) strlog(TCP_MODULE_ID, 0, 1,
3994 				    SL_ERROR|SL_TRACE,
3995 				    "tcp_bind: requested addr busy");
3996 			}
3997 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3998 		} else {
3999 			/* If we are out of ports, fail the bind. */
4000 			if (tcp->tcp_debug) {
4001 				(void) strlog(TCP_MODULE_ID, 0, 1,
4002 				    SL_ERROR|SL_TRACE,
4003 				    "tcp_bind: out of ports?");
4004 			}
4005 			tcp_err_ack(tcp, mp, TNOADDR, 0);
4006 		}
4007 		return;
4008 	}
4009 	ASSERT(tcp->tcp_state == TCPS_BOUND);
4010 do_bind:
4011 	if (!backlog_update) {
4012 		if (tcp->tcp_family == AF_INET)
4013 			sin->sin_port = htons(allocated_port);
4014 		else
4015 			sin6->sin6_port = htons(allocated_port);
4016 	}
4017 	if (tcp->tcp_family == AF_INET) {
4018 		if (tbr->CONIND_number != 0) {
4019 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
4020 			    sizeof (sin_t));
4021 		} else {
4022 			/* Just verify the local IP address */
4023 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
4024 		}
4025 	} else {
4026 		if (tbr->CONIND_number != 0) {
4027 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
4028 			    sizeof (sin6_t));
4029 		} else {
4030 			/* Just verify the local IP address */
4031 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
4032 			    IPV6_ADDR_LEN);
4033 		}
4034 	}
4035 	if (!mp1) {
4036 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
4037 		return;
4038 	}
4039 
4040 	tbr->PRIM_type = T_BIND_ACK;
4041 	mp->b_datap->db_type = M_PCPROTO;
4042 
4043 	/* Chain in the reply mp for tcp_rput() */
4044 	mp1->b_cont = mp;
4045 	mp = mp1;
4046 
4047 	tcp->tcp_conn_req_max = tbr->CONIND_number;
4048 	if (tcp->tcp_conn_req_max) {
4049 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
4050 			tcp->tcp_conn_req_max = tcp_conn_req_min;
4051 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
4052 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
4053 		/*
4054 		 * If this is a listener, do not reset the eager list
4055 		 * and other stuffs.  Note that we don't check if the
4056 		 * existing eager list meets the new tcp_conn_req_max
4057 		 * requirement.
4058 		 */
4059 		if (tcp->tcp_state != TCPS_LISTEN) {
4060 			tcp->tcp_state = TCPS_LISTEN;
4061 			/* Initialize the chain. Don't need the eager_lock */
4062 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
4063 			tcp->tcp_second_ctimer_threshold =
4064 			    tcp_ip_abort_linterval;
4065 		}
4066 	}
4067 
4068 	/*
4069 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
4070 	 * processing continues in tcp_rput_other().
4071 	 */
4072 	if (tcp->tcp_family == AF_INET6) {
4073 		ASSERT(tcp->tcp_connp->conn_af_isv6);
4074 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
4075 	} else {
4076 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
4077 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
4078 	}
4079 	/*
4080 	 * If the bind cannot complete immediately
4081 	 * IP will arrange to call tcp_rput_other
4082 	 * when the bind completes.
4083 	 */
4084 	if (mp != NULL) {
4085 		tcp_rput_other(tcp, mp);
4086 	} else {
4087 		/*
4088 		 * Bind will be resumed later. Need to ensure
4089 		 * that conn doesn't disappear when that happens.
4090 		 * This will be decremented in ip_resume_tcp_bind().
4091 		 */
4092 		CONN_INC_REF(tcp->tcp_connp);
4093 	}
4094 }
4095 
4096 
4097 /*
4098  * If the "bind_to_req_port_only" parameter is set, if the requested port
4099  * number is available, return it, If not return 0
4100  *
4101  * If "bind_to_req_port_only" parameter is not set and
4102  * If the requested port number is available, return it.  If not, return
4103  * the first anonymous port we happen across.  If no anonymous ports are
4104  * available, return 0. addr is the requested local address, if any.
4105  *
4106  * In either case, when succeeding update the tcp_t to record the port number
4107  * and insert it in the bind hash table.
4108  *
4109  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
4110  * without setting SO_REUSEADDR. This is needed so that they
4111  * can be viewed as two independent transport protocols.
4112  */
4113 static in_port_t
4114 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
4115     int reuseaddr, boolean_t quick_connect,
4116     boolean_t bind_to_req_port_only, boolean_t user_specified)
4117 {
4118 	/* number of times we have run around the loop */
4119 	int count = 0;
4120 	/* maximum number of times to run around the loop */
4121 	int loopmax;
4122 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
4123 
4124 	/*
4125 	 * Lookup for free addresses is done in a loop and "loopmax"
4126 	 * influences how long we spin in the loop
4127 	 */
4128 	if (bind_to_req_port_only) {
4129 		/*
4130 		 * If the requested port is busy, don't bother to look
4131 		 * for a new one. Setting loop maximum count to 1 has
4132 		 * that effect.
4133 		 */
4134 		loopmax = 1;
4135 	} else {
4136 		/*
4137 		 * If the requested port is busy, look for a free one
4138 		 * in the anonymous port range.
4139 		 * Set loopmax appropriately so that one does not look
4140 		 * forever in the case all of the anonymous ports are in use.
4141 		 */
4142 		if (tcp->tcp_anon_priv_bind) {
4143 			/*
4144 			 * loopmax =
4145 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
4146 			 */
4147 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
4148 		} else {
4149 			loopmax = (tcp_largest_anon_port -
4150 			    tcp_smallest_anon_port + 1);
4151 		}
4152 	}
4153 	do {
4154 		uint16_t	lport;
4155 		tf_t		*tbf;
4156 		tcp_t		*ltcp;
4157 
4158 		lport = htons(port);
4159 
4160 		/*
4161 		 * Ensure that the tcp_t is not currently in the bind hash.
4162 		 * Hold the lock on the hash bucket to ensure that
4163 		 * the duplicate check plus the insertion is an atomic
4164 		 * operation.
4165 		 *
4166 		 * This function does an inline lookup on the bind hash list
4167 		 * Make sure that we access only members of tcp_t
4168 		 * and that we don't look at tcp_tcp, since we are not
4169 		 * doing a CONN_INC_REF.
4170 		 */
4171 		tcp_bind_hash_remove(tcp);
4172 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
4173 		mutex_enter(&tbf->tf_lock);
4174 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
4175 		    ltcp = ltcp->tcp_bind_hash) {
4176 			if (lport != ltcp->tcp_lport ||
4177 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
4178 				continue;
4179 			}
4180 
4181 			/*
4182 			 * If TCP_EXCLBIND is set for either the bound or
4183 			 * binding endpoint, the semantics of bind
4184 			 * is changed according to the following.
4185 			 *
4186 			 * spec = specified address (v4 or v6)
4187 			 * unspec = unspecified address (v4 or v6)
4188 			 * A = specified addresses are different for endpoints
4189 			 *
4190 			 * bound	bind to		allowed
4191 			 * -------------------------------------
4192 			 * unspec	unspec		no
4193 			 * unspec	spec		no
4194 			 * spec		unspec		no
4195 			 * spec		spec		yes if A
4196 			 *
4197 			 * Note:
4198 			 *
4199 			 * 1. Because of TLI semantics, an endpoint can go
4200 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
4201 			 * TCPS_BOUND, depending on whether it is originally
4202 			 * a listener or not.  That is why we need to check
4203 			 * for states greater than or equal to TCPS_BOUND
4204 			 * here.
4205 			 *
4206 			 * 2. Ideally, we should only check for state equals
4207 			 * to TCPS_LISTEN. And the following check should be
4208 			 * added.
4209 			 *
4210 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
4211 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
4212 			 *		...
4213 			 * }
4214 			 *
4215 			 * The semantics will be changed to this.  If the
4216 			 * endpoint on the list is in state not equal to
4217 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
4218 			 * set, let the bind succeed.
4219 			 *
4220 			 * But because of (1), we cannot do that now.  If
4221 			 * in future, we can change this going back semantics,
4222 			 * we can add the above check.
4223 			 */
4224 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
4225 				if (V6_OR_V4_INADDR_ANY(
4226 				    ltcp->tcp_bound_source_v6) ||
4227 				    V6_OR_V4_INADDR_ANY(*laddr) ||
4228 				    IN6_ARE_ADDR_EQUAL(laddr,
4229 				    &ltcp->tcp_bound_source_v6)) {
4230 					break;
4231 				}
4232 				continue;
4233 			}
4234 
4235 			/*
4236 			 * Check ipversion to allow IPv4 and IPv6 sockets to
4237 			 * have disjoint port number spaces, if *_EXCLBIND
4238 			 * is not set and only if the application binds to a
4239 			 * specific port. We use the same autoassigned port
4240 			 * number space for IPv4 and IPv6 sockets.
4241 			 */
4242 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
4243 			    bind_to_req_port_only)
4244 				continue;
4245 
4246 			/*
4247 			 * Ideally, we should make sure that the source
4248 			 * address, remote address, and remote port in the
4249 			 * four tuple for this tcp-connection is unique.
4250 			 * However, trying to find out the local source
4251 			 * address would require too much code duplication
4252 			 * with IP, since IP needs needs to have that code
4253 			 * to support userland TCP implementations.
4254 			 */
4255 			if (quick_connect &&
4256 			    (ltcp->tcp_state > TCPS_LISTEN) &&
4257 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
4258 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
4259 				    &ltcp->tcp_remote_v6)))
4260 				continue;
4261 
4262 			if (!reuseaddr) {
4263 				/*
4264 				 * No socket option SO_REUSEADDR.
4265 				 * If existing port is bound to
4266 				 * a non-wildcard IP address
4267 				 * and the requesting stream is
4268 				 * bound to a distinct
4269 				 * different IP addresses
4270 				 * (non-wildcard, also), keep
4271 				 * going.
4272 				 */
4273 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
4274 				    !V6_OR_V4_INADDR_ANY(
4275 				    ltcp->tcp_bound_source_v6) &&
4276 				    !IN6_ARE_ADDR_EQUAL(laddr,
4277 					&ltcp->tcp_bound_source_v6))
4278 					continue;
4279 				if (ltcp->tcp_state >= TCPS_BOUND) {
4280 					/*
4281 					 * This port is being used and
4282 					 * its state is >= TCPS_BOUND,
4283 					 * so we can't bind to it.
4284 					 */
4285 					break;
4286 				}
4287 			} else {
4288 				/*
4289 				 * socket option SO_REUSEADDR is set on the
4290 				 * binding tcp_t.
4291 				 *
4292 				 * If two streams are bound to
4293 				 * same IP address or both addr
4294 				 * and bound source are wildcards
4295 				 * (INADDR_ANY), we want to stop
4296 				 * searching.
4297 				 * We have found a match of IP source
4298 				 * address and source port, which is
4299 				 * refused regardless of the
4300 				 * SO_REUSEADDR setting, so we break.
4301 				 */
4302 				if (IN6_ARE_ADDR_EQUAL(laddr,
4303 				    &ltcp->tcp_bound_source_v6) &&
4304 				    (ltcp->tcp_state == TCPS_LISTEN ||
4305 					ltcp->tcp_state == TCPS_BOUND))
4306 					break;
4307 			}
4308 		}
4309 		if (ltcp != NULL) {
4310 			/* The port number is busy */
4311 			mutex_exit(&tbf->tf_lock);
4312 		} else {
4313 			/*
4314 			 * This port is ours. Insert in fanout and mark as
4315 			 * bound to prevent others from getting the port
4316 			 * number.
4317 			 */
4318 			tcp->tcp_state = TCPS_BOUND;
4319 			tcp->tcp_lport = htons(port);
4320 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
4321 
4322 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
4323 			    tcp->tcp_lport)] == tbf);
4324 			tcp_bind_hash_insert(tbf, tcp, 1);
4325 
4326 			mutex_exit(&tbf->tf_lock);
4327 
4328 			/*
4329 			 * We don't want tcp_next_port_to_try to "inherit"
4330 			 * a port number supplied by the user in a bind.
4331 			 */
4332 			if (user_specified)
4333 				return (port);
4334 
4335 			/*
4336 			 * This is the only place where tcp_next_port_to_try
4337 			 * is updated. After the update, it may or may not
4338 			 * be in the valid range.
4339 			 */
4340 			if (!tcp->tcp_anon_priv_bind)
4341 				tcp_next_port_to_try = port + 1;
4342 			return (port);
4343 		}
4344 
4345 		if (tcp->tcp_anon_priv_bind) {
4346 			port = tcp_get_next_priv_port();
4347 		} else {
4348 			if (count == 0 && user_specified) {
4349 				/*
4350 				 * We may have to return an anonymous port. So
4351 				 * get one to start with.
4352 				 */
4353 				port =
4354 				    tcp_update_next_port(tcp_next_port_to_try,
4355 					B_TRUE);
4356 				user_specified = B_FALSE;
4357 			} else {
4358 				port = tcp_update_next_port(port + 1, B_FALSE);
4359 			}
4360 		}
4361 
4362 		/*
4363 		 * Don't let this loop run forever in the case where
4364 		 * all of the anonymous ports are in use.
4365 		 */
4366 	} while (++count < loopmax);
4367 	return (0);
4368 }
4369 
4370 /*
4371  * We are dying for some reason.  Try to do it gracefully.  (May be called
4372  * as writer.)
4373  *
4374  * Return -1 if the structure was not cleaned up (if the cleanup had to be
4375  * done by a service procedure).
4376  * TBD - Should the return value distinguish between the tcp_t being
4377  * freed and it being reinitialized?
4378  */
4379 static int
4380 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
4381 {
4382 	mblk_t	*mp;
4383 	queue_t	*q;
4384 
4385 	TCP_CLD_STAT(tag);
4386 
4387 #if TCP_TAG_CLEAN_DEATH
4388 	tcp->tcp_cleandeathtag = tag;
4389 #endif
4390 
4391 	if (tcp->tcp_linger_tid != 0 &&
4392 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4393 		tcp_stop_lingering(tcp);
4394 	}
4395 
4396 	ASSERT(tcp != NULL);
4397 	ASSERT((tcp->tcp_family == AF_INET &&
4398 	    tcp->tcp_ipversion == IPV4_VERSION) ||
4399 	    (tcp->tcp_family == AF_INET6 &&
4400 	    (tcp->tcp_ipversion == IPV4_VERSION ||
4401 	    tcp->tcp_ipversion == IPV6_VERSION)));
4402 
4403 	if (TCP_IS_DETACHED(tcp)) {
4404 		if (tcp->tcp_hard_binding) {
4405 			/*
4406 			 * Its an eager that we are dealing with. We close the
4407 			 * eager but in case a conn_ind has already gone to the
4408 			 * listener, let tcp_accept_finish() send a discon_ind
4409 			 * to the listener and drop the last reference. If the
4410 			 * listener doesn't even know about the eager i.e. the
4411 			 * conn_ind hasn't gone up, blow away the eager and drop
4412 			 * the last reference as well. If the conn_ind has gone
4413 			 * up, state should be BOUND. tcp_accept_finish
4414 			 * will figure out that the connection has received a
4415 			 * RST and will send a DISCON_IND to the application.
4416 			 */
4417 			tcp_closei_local(tcp);
4418 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4419 				CONN_DEC_REF(tcp->tcp_connp);
4420 			} else {
4421 				tcp->tcp_state = TCPS_BOUND;
4422 			}
4423 		} else {
4424 			tcp_close_detached(tcp);
4425 		}
4426 		return (0);
4427 	}
4428 
4429 	TCP_STAT(tcp_clean_death_nondetached);
4430 
4431 	/*
4432 	 * If T_ORDREL_IND has not been sent yet (done when service routine
4433 	 * is run) postpone cleaning up the endpoint until service routine
4434 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
4435 	 * client_errno since tcp_close uses the client_errno field.
4436 	 */
4437 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
4438 		if (err != 0)
4439 			tcp->tcp_client_errno = err;
4440 
4441 		tcp->tcp_deferred_clean_death = B_TRUE;
4442 		return (-1);
4443 	}
4444 
4445 	q = tcp->tcp_rq;
4446 
4447 	/* Trash all inbound data */
4448 	flushq(q, FLUSHALL);
4449 
4450 	/*
4451 	 * If we are at least part way open and there is error
4452 	 * (err==0 implies no error)
4453 	 * notify our client by a T_DISCON_IND.
4454 	 */
4455 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
4456 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
4457 		    !TCP_IS_SOCKET(tcp)) {
4458 			/*
4459 			 * Send M_FLUSH according to TPI. Because sockets will
4460 			 * (and must) ignore FLUSHR we do that only for TPI
4461 			 * endpoints and sockets in STREAMS mode.
4462 			 */
4463 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
4464 		}
4465 		if (tcp->tcp_debug) {
4466 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
4467 			    "tcp_clean_death: discon err %d", err);
4468 		}
4469 		mp = mi_tpi_discon_ind(NULL, err, 0);
4470 		if (mp != NULL) {
4471 			putnext(q, mp);
4472 		} else {
4473 			if (tcp->tcp_debug) {
4474 				(void) strlog(TCP_MODULE_ID, 0, 1,
4475 				    SL_ERROR|SL_TRACE,
4476 				    "tcp_clean_death, sending M_ERROR");
4477 			}
4478 			(void) putnextctl1(q, M_ERROR, EPROTO);
4479 		}
4480 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
4481 			/* SYN_SENT or SYN_RCVD */
4482 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4483 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
4484 			/* ESTABLISHED or CLOSE_WAIT */
4485 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4486 		}
4487 	}
4488 
4489 	tcp_reinit(tcp);
4490 	return (-1);
4491 }
4492 
4493 /*
4494  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
4495  * to expire, stop the wait and finish the close.
4496  */
4497 static void
4498 tcp_stop_lingering(tcp_t *tcp)
4499 {
4500 	clock_t	delta = 0;
4501 
4502 	tcp->tcp_linger_tid = 0;
4503 	if (tcp->tcp_state > TCPS_LISTEN) {
4504 		tcp_acceptor_hash_remove(tcp);
4505 		if (tcp->tcp_flow_stopped) {
4506 			tcp_clrqfull(tcp);
4507 		}
4508 
4509 		if (tcp->tcp_timer_tid != 0) {
4510 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4511 			tcp->tcp_timer_tid = 0;
4512 		}
4513 		/*
4514 		 * Need to cancel those timers which will not be used when
4515 		 * TCP is detached.  This has to be done before the tcp_wq
4516 		 * is set to the global queue.
4517 		 */
4518 		tcp_timers_stop(tcp);
4519 
4520 
4521 		tcp->tcp_detached = B_TRUE;
4522 		tcp->tcp_rq = tcp_g_q;
4523 		tcp->tcp_wq = WR(tcp_g_q);
4524 
4525 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4526 			tcp_time_wait_append(tcp);
4527 			TCP_DBGSTAT(tcp_detach_time_wait);
4528 			goto finish;
4529 		}
4530 
4531 		/*
4532 		 * If delta is zero the timer event wasn't executed and was
4533 		 * successfully canceled. In this case we need to restart it
4534 		 * with the minimal delta possible.
4535 		 */
4536 		if (delta >= 0) {
4537 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4538 			    delta ? delta : 1);
4539 		}
4540 	} else {
4541 		tcp_closei_local(tcp);
4542 		CONN_DEC_REF(tcp->tcp_connp);
4543 	}
4544 finish:
4545 	/* Signal closing thread that it can complete close */
4546 	mutex_enter(&tcp->tcp_closelock);
4547 	tcp->tcp_detached = B_TRUE;
4548 	tcp->tcp_rq = tcp_g_q;
4549 	tcp->tcp_wq = WR(tcp_g_q);
4550 	tcp->tcp_closed = 1;
4551 	cv_signal(&tcp->tcp_closecv);
4552 	mutex_exit(&tcp->tcp_closelock);
4553 }
4554 
4555 /*
4556  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
4557  * expires.
4558  */
4559 static void
4560 tcp_close_linger_timeout(void *arg)
4561 {
4562 	conn_t	*connp = (conn_t *)arg;
4563 	tcp_t 	*tcp = connp->conn_tcp;
4564 
4565 	tcp->tcp_client_errno = ETIMEDOUT;
4566 	tcp_stop_lingering(tcp);
4567 }
4568 
4569 static int
4570 tcp_close(queue_t *q, int flags)
4571 {
4572 	conn_t		*connp = Q_TO_CONN(q);
4573 	tcp_t		*tcp = connp->conn_tcp;
4574 	mblk_t 		*mp = &tcp->tcp_closemp;
4575 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4576 
4577 	ASSERT(WR(q)->q_next == NULL);
4578 	ASSERT(connp->conn_ref >= 2);
4579 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
4580 
4581 	/*
4582 	 * We are being closed as /dev/tcp or /dev/tcp6.
4583 	 *
4584 	 * Mark the conn as closing. ill_pending_mp_add will not
4585 	 * add any mp to the pending mp list, after this conn has
4586 	 * started closing. Same for sq_pending_mp_add
4587 	 */
4588 	mutex_enter(&connp->conn_lock);
4589 	connp->conn_state_flags |= CONN_CLOSING;
4590 	if (connp->conn_oper_pending_ill != NULL)
4591 		conn_ioctl_cleanup_reqd = B_TRUE;
4592 	CONN_INC_REF_LOCKED(connp);
4593 	mutex_exit(&connp->conn_lock);
4594 	tcp->tcp_closeflags = (uint8_t)flags;
4595 	ASSERT(connp->conn_ref >= 3);
4596 
4597 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4598 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4599 
4600 	mutex_enter(&tcp->tcp_closelock);
4601 	while (!tcp->tcp_closed)
4602 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4603 	mutex_exit(&tcp->tcp_closelock);
4604 	/*
4605 	 * In the case of listener streams that have eagers in the q or q0
4606 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4607 	 * tcp_wq of the eagers point to our queues. By waiting for the
4608 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4609 	 * up their queue pointers and also dropped their references to us.
4610 	 */
4611 	if (tcp->tcp_wait_for_eagers) {
4612 		mutex_enter(&connp->conn_lock);
4613 		while (connp->conn_ref != 1) {
4614 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4615 		}
4616 		mutex_exit(&connp->conn_lock);
4617 	}
4618 	/*
4619 	 * ioctl cleanup. The mp is queued in the
4620 	 * ill_pending_mp or in the sq_pending_mp.
4621 	 */
4622 	if (conn_ioctl_cleanup_reqd)
4623 		conn_ioctl_cleanup(connp);
4624 
4625 	qprocsoff(q);
4626 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4627 
4628 	ASSERT(connp->conn_cred != NULL);
4629 	crfree(connp->conn_cred);
4630 	tcp->tcp_cred = connp->conn_cred = NULL;
4631 	tcp->tcp_cpid = -1;
4632 
4633 	/*
4634 	 * Drop IP's reference on the conn. This is the last reference
4635 	 * on the connp if the state was less than established. If the
4636 	 * connection has gone into timewait state, then we will have
4637 	 * one ref for the TCP and one more ref (total of two) for the
4638 	 * classifier connected hash list (a timewait connections stays
4639 	 * in connected hash till closed).
4640 	 *
4641 	 * We can't assert the references because there might be other
4642 	 * transient reference places because of some walkers or queued
4643 	 * packets in squeue for the timewait state.
4644 	 */
4645 	CONN_DEC_REF(connp);
4646 	q->q_ptr = WR(q)->q_ptr = NULL;
4647 	return (0);
4648 }
4649 
4650 int
4651 tcp_modclose(queue_t *q)
4652 {
4653 	conn_t *connp = Q_TO_CONN(q);
4654 	ASSERT((connp->conn_flags & IPCL_TCPMOD) != 0);
4655 
4656 	qprocsoff(q);
4657 
4658 	if (connp->conn_cred != NULL) {
4659 		crfree(connp->conn_cred);
4660 		connp->conn_cred = NULL;
4661 	}
4662 	CONN_DEC_REF(connp);
4663 	q->q_ptr = WR(q)->q_ptr = NULL;
4664 	return (0);
4665 }
4666 
4667 static int
4668 tcpclose_accept(queue_t *q)
4669 {
4670 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4671 
4672 	/*
4673 	 * We had opened an acceptor STREAM for sockfs which is
4674 	 * now being closed due to some error.
4675 	 */
4676 	qprocsoff(q);
4677 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4678 	q->q_ptr = WR(q)->q_ptr = NULL;
4679 	return (0);
4680 }
4681 
4682 
4683 /*
4684  * Called by streams close routine via squeues when our client blows off her
4685  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4686  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4687  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4688  * acked.
4689  *
4690  * NOTE: tcp_close potentially returns error when lingering.
4691  * However, the stream head currently does not pass these errors
4692  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4693  * errors to the application (from tsleep()) and not errors
4694  * like ECONNRESET caused by receiving a reset packet.
4695  */
4696 
4697 /* ARGSUSED */
4698 static void
4699 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4700 {
4701 	char	*msg;
4702 	conn_t	*connp = (conn_t *)arg;
4703 	tcp_t	*tcp = connp->conn_tcp;
4704 	clock_t	delta = 0;
4705 
4706 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4707 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4708 
4709 	/* Cancel any pending timeout */
4710 	if (tcp->tcp_ordrelid != 0) {
4711 		if (tcp->tcp_timeout) {
4712 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4713 		}
4714 		tcp->tcp_ordrelid = 0;
4715 		tcp->tcp_timeout = B_FALSE;
4716 	}
4717 
4718 	mutex_enter(&tcp->tcp_eager_lock);
4719 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4720 		/* Cleanup for listener */
4721 		tcp_eager_cleanup(tcp, 0);
4722 		tcp->tcp_wait_for_eagers = 1;
4723 	}
4724 	mutex_exit(&tcp->tcp_eager_lock);
4725 
4726 	connp->conn_mdt_ok = B_FALSE;
4727 	tcp->tcp_mdt = B_FALSE;
4728 
4729 	msg = NULL;
4730 	switch (tcp->tcp_state) {
4731 	case TCPS_CLOSED:
4732 	case TCPS_IDLE:
4733 	case TCPS_BOUND:
4734 	case TCPS_LISTEN:
4735 		break;
4736 	case TCPS_SYN_SENT:
4737 		msg = "tcp_close, during connect";
4738 		break;
4739 	case TCPS_SYN_RCVD:
4740 		/*
4741 		 * Close during the connect 3-way handshake
4742 		 * but here there may or may not be pending data
4743 		 * already on queue. Process almost same as in
4744 		 * the ESTABLISHED state.
4745 		 */
4746 		/* FALLTHRU */
4747 	default:
4748 		if (tcp->tcp_fused)
4749 			tcp_unfuse(tcp);
4750 
4751 		/*
4752 		 * If SO_LINGER has set a zero linger time, abort the
4753 		 * connection with a reset.
4754 		 */
4755 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4756 			msg = "tcp_close, zero lingertime";
4757 			break;
4758 		}
4759 
4760 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4761 		/*
4762 		 * Abort connection if there is unread data queued.
4763 		 */
4764 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4765 			msg = "tcp_close, unread data";
4766 			break;
4767 		}
4768 		/*
4769 		 * tcp_hard_bound is now cleared thus all packets go through
4770 		 * tcp_lookup. This fact is used by tcp_detach below.
4771 		 *
4772 		 * We have done a qwait() above which could have possibly
4773 		 * drained more messages in turn causing transition to a
4774 		 * different state. Check whether we have to do the rest
4775 		 * of the processing or not.
4776 		 */
4777 		if (tcp->tcp_state <= TCPS_LISTEN)
4778 			break;
4779 
4780 		/*
4781 		 * Transmit the FIN before detaching the tcp_t.
4782 		 * After tcp_detach returns this queue/perimeter
4783 		 * no longer owns the tcp_t thus others can modify it.
4784 		 */
4785 		(void) tcp_xmit_end(tcp);
4786 
4787 		/*
4788 		 * If lingering on close then wait until the fin is acked,
4789 		 * the SO_LINGER time passes, or a reset is sent/received.
4790 		 */
4791 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4792 		    !(tcp->tcp_fin_acked) &&
4793 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4794 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4795 				tcp->tcp_client_errno = EWOULDBLOCK;
4796 			} else if (tcp->tcp_client_errno == 0) {
4797 
4798 				ASSERT(tcp->tcp_linger_tid == 0);
4799 
4800 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4801 				    tcp_close_linger_timeout,
4802 				    tcp->tcp_lingertime * hz);
4803 
4804 				/* tcp_close_linger_timeout will finish close */
4805 				if (tcp->tcp_linger_tid == 0)
4806 					tcp->tcp_client_errno = ENOSR;
4807 				else
4808 					return;
4809 			}
4810 
4811 			/*
4812 			 * Check if we need to detach or just close
4813 			 * the instance.
4814 			 */
4815 			if (tcp->tcp_state <= TCPS_LISTEN)
4816 				break;
4817 		}
4818 
4819 		/*
4820 		 * Make sure that no other thread will access the tcp_rq of
4821 		 * this instance (through lookups etc.) as tcp_rq will go
4822 		 * away shortly.
4823 		 */
4824 		tcp_acceptor_hash_remove(tcp);
4825 
4826 		if (tcp->tcp_flow_stopped) {
4827 			tcp_clrqfull(tcp);
4828 		}
4829 
4830 		if (tcp->tcp_timer_tid != 0) {
4831 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4832 			tcp->tcp_timer_tid = 0;
4833 		}
4834 		/*
4835 		 * Need to cancel those timers which will not be used when
4836 		 * TCP is detached.  This has to be done before the tcp_wq
4837 		 * is set to the global queue.
4838 		 */
4839 		tcp_timers_stop(tcp);
4840 
4841 		tcp->tcp_detached = B_TRUE;
4842 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4843 			tcp_time_wait_append(tcp);
4844 			TCP_DBGSTAT(tcp_detach_time_wait);
4845 			ASSERT(connp->conn_ref >= 3);
4846 			goto finish;
4847 		}
4848 
4849 		/*
4850 		 * If delta is zero the timer event wasn't executed and was
4851 		 * successfully canceled. In this case we need to restart it
4852 		 * with the minimal delta possible.
4853 		 */
4854 		if (delta >= 0)
4855 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4856 			    delta ? delta : 1);
4857 
4858 		ASSERT(connp->conn_ref >= 3);
4859 		goto finish;
4860 	}
4861 
4862 	/* Detach did not complete. Still need to remove q from stream. */
4863 	if (msg) {
4864 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4865 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4866 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4867 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4868 		    tcp->tcp_state == TCPS_SYN_RCVD)
4869 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4870 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4871 	}
4872 
4873 	tcp_closei_local(tcp);
4874 	CONN_DEC_REF(connp);
4875 	ASSERT(connp->conn_ref >= 2);
4876 
4877 finish:
4878 	/*
4879 	 * Although packets are always processed on the correct
4880 	 * tcp's perimeter and access is serialized via squeue's,
4881 	 * IP still needs a queue when sending packets in time_wait
4882 	 * state so use WR(tcp_g_q) till ip_output() can be
4883 	 * changed to deal with just connp. For read side, we
4884 	 * could have set tcp_rq to NULL but there are some cases
4885 	 * in tcp_rput_data() from early days of this code which
4886 	 * do a putnext without checking if tcp is closed. Those
4887 	 * need to be identified before both tcp_rq and tcp_wq
4888 	 * can be set to NULL and tcp_q_q can disappear forever.
4889 	 */
4890 	mutex_enter(&tcp->tcp_closelock);
4891 	/*
4892 	 * Don't change the queues in the case of a listener that has
4893 	 * eagers in its q or q0. It could surprise the eagers.
4894 	 * Instead wait for the eagers outside the squeue.
4895 	 */
4896 	if (!tcp->tcp_wait_for_eagers) {
4897 		tcp->tcp_detached = B_TRUE;
4898 		tcp->tcp_rq = tcp_g_q;
4899 		tcp->tcp_wq = WR(tcp_g_q);
4900 	}
4901 	/* Signal tcp_close() to finish closing. */
4902 	tcp->tcp_closed = 1;
4903 	cv_signal(&tcp->tcp_closecv);
4904 	mutex_exit(&tcp->tcp_closelock);
4905 }
4906 
4907 
4908 /*
4909  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4910  * Some stream heads get upset if they see these later on as anything but NULL.
4911  */
4912 static void
4913 tcp_close_mpp(mblk_t **mpp)
4914 {
4915 	mblk_t	*mp;
4916 
4917 	if ((mp = *mpp) != NULL) {
4918 		do {
4919 			mp->b_next = NULL;
4920 			mp->b_prev = NULL;
4921 		} while ((mp = mp->b_cont) != NULL);
4922 
4923 		mp = *mpp;
4924 		*mpp = NULL;
4925 		freemsg(mp);
4926 	}
4927 }
4928 
4929 /* Do detached close. */
4930 static void
4931 tcp_close_detached(tcp_t *tcp)
4932 {
4933 	if (tcp->tcp_fused)
4934 		tcp_unfuse(tcp);
4935 
4936 	/*
4937 	 * Clustering code serializes TCP disconnect callbacks and
4938 	 * cluster tcp list walks by blocking a TCP disconnect callback
4939 	 * if a cluster tcp list walk is in progress. This ensures
4940 	 * accurate accounting of TCPs in the cluster code even though
4941 	 * the TCP list walk itself is not atomic.
4942 	 */
4943 	tcp_closei_local(tcp);
4944 	CONN_DEC_REF(tcp->tcp_connp);
4945 }
4946 
4947 /*
4948  * Stop all TCP timers, and free the timer mblks if requested.
4949  */
4950 static void
4951 tcp_timers_stop(tcp_t *tcp)
4952 {
4953 	if (tcp->tcp_timer_tid != 0) {
4954 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4955 		tcp->tcp_timer_tid = 0;
4956 	}
4957 	if (tcp->tcp_ka_tid != 0) {
4958 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4959 		tcp->tcp_ka_tid = 0;
4960 	}
4961 	if (tcp->tcp_ack_tid != 0) {
4962 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4963 		tcp->tcp_ack_tid = 0;
4964 	}
4965 	if (tcp->tcp_push_tid != 0) {
4966 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4967 		tcp->tcp_push_tid = 0;
4968 	}
4969 }
4970 
4971 /*
4972  * The tcp_t is going away. Remove it from all lists and set it
4973  * to TCPS_CLOSED. The freeing up of memory is deferred until
4974  * tcp_inactive. This is needed since a thread in tcp_rput might have
4975  * done a CONN_INC_REF on this structure before it was removed from the
4976  * hashes.
4977  */
4978 static void
4979 tcp_closei_local(tcp_t *tcp)
4980 {
4981 	ire_t 	*ire;
4982 	conn_t	*connp = tcp->tcp_connp;
4983 
4984 	if (!TCP_IS_SOCKET(tcp))
4985 		tcp_acceptor_hash_remove(tcp);
4986 
4987 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4988 	tcp->tcp_ibsegs = 0;
4989 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4990 	tcp->tcp_obsegs = 0;
4991 	/*
4992 	 * If we are an eager connection hanging off a listener that
4993 	 * hasn't formally accepted the connection yet, get off his
4994 	 * list and blow off any data that we have accumulated.
4995 	 */
4996 	if (tcp->tcp_listener != NULL) {
4997 		tcp_t	*listener = tcp->tcp_listener;
4998 		mutex_enter(&listener->tcp_eager_lock);
4999 		/*
5000 		 * tcp_eager_conn_ind == NULL means that the
5001 		 * conn_ind has already gone to listener. At
5002 		 * this point, eager will be closed but we
5003 		 * leave it in listeners eager list so that
5004 		 * if listener decides to close without doing
5005 		 * accept, we can clean this up. In tcp_wput_accept
5006 		 * we take case of the case of accept on closed
5007 		 * eager.
5008 		 */
5009 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
5010 			tcp_eager_unlink(tcp);
5011 			mutex_exit(&listener->tcp_eager_lock);
5012 			/*
5013 			 * We don't want to have any pointers to the
5014 			 * listener queue, after we have released our
5015 			 * reference on the listener
5016 			 */
5017 			tcp->tcp_rq = tcp_g_q;
5018 			tcp->tcp_wq = WR(tcp_g_q);
5019 			CONN_DEC_REF(listener->tcp_connp);
5020 		} else {
5021 			mutex_exit(&listener->tcp_eager_lock);
5022 		}
5023 	}
5024 
5025 	/* Stop all the timers */
5026 	tcp_timers_stop(tcp);
5027 
5028 	if (tcp->tcp_state == TCPS_LISTEN) {
5029 		if (tcp->tcp_ip_addr_cache) {
5030 			kmem_free((void *)tcp->tcp_ip_addr_cache,
5031 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
5032 			tcp->tcp_ip_addr_cache = NULL;
5033 		}
5034 	}
5035 	if (tcp->tcp_flow_stopped)
5036 		tcp_clrqfull(tcp);
5037 
5038 	tcp_bind_hash_remove(tcp);
5039 	/*
5040 	 * If the tcp_time_wait_collector (which runs outside the squeue)
5041 	 * is trying to remove this tcp from the time wait list, we will
5042 	 * block in tcp_time_wait_remove while trying to acquire the
5043 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
5044 	 * requires the ipcl_hash_remove to be ordered after the
5045 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
5046 	 */
5047 	if (tcp->tcp_state == TCPS_TIME_WAIT)
5048 		tcp_time_wait_remove(tcp, NULL);
5049 	CL_INET_DISCONNECT(tcp);
5050 	ipcl_hash_remove(connp);
5051 
5052 	/*
5053 	 * Delete the cached ire in conn_ire_cache and also mark
5054 	 * the conn as CONDEMNED
5055 	 */
5056 	mutex_enter(&connp->conn_lock);
5057 	connp->conn_state_flags |= CONN_CONDEMNED;
5058 	ire = connp->conn_ire_cache;
5059 	connp->conn_ire_cache = NULL;
5060 	mutex_exit(&connp->conn_lock);
5061 	if (ire != NULL)
5062 		IRE_REFRELE_NOTR(ire);
5063 
5064 	/* Need to cleanup any pending ioctls */
5065 	ASSERT(tcp->tcp_time_wait_next == NULL);
5066 	ASSERT(tcp->tcp_time_wait_prev == NULL);
5067 	ASSERT(tcp->tcp_time_wait_expire == 0);
5068 	tcp->tcp_state = TCPS_CLOSED;
5069 }
5070 
5071 /*
5072  * tcp is dying (called from ipcl_conn_destroy and error cases).
5073  * Free the tcp_t in either case.
5074  */
5075 void
5076 tcp_free(tcp_t *tcp)
5077 {
5078 	mblk_t	*mp;
5079 	ip6_pkt_t	*ipp;
5080 
5081 	ASSERT(tcp != NULL);
5082 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
5083 
5084 	tcp->tcp_rq = NULL;
5085 	tcp->tcp_wq = NULL;
5086 
5087 	tcp_close_mpp(&tcp->tcp_xmit_head);
5088 	tcp_close_mpp(&tcp->tcp_reass_head);
5089 	if (tcp->tcp_rcv_list != NULL) {
5090 		/* Free b_next chain */
5091 		tcp_close_mpp(&tcp->tcp_rcv_list);
5092 	}
5093 	if ((mp = tcp->tcp_urp_mp) != NULL) {
5094 		freemsg(mp);
5095 	}
5096 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
5097 		freemsg(mp);
5098 	}
5099 
5100 	if (tcp->tcp_fused_sigurg_mp != NULL) {
5101 		freeb(tcp->tcp_fused_sigurg_mp);
5102 		tcp->tcp_fused_sigurg_mp = NULL;
5103 	}
5104 
5105 	if (tcp->tcp_sack_info != NULL) {
5106 		if (tcp->tcp_notsack_list != NULL) {
5107 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
5108 		}
5109 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
5110 	}
5111 
5112 	if (tcp->tcp_hopopts != NULL) {
5113 		mi_free(tcp->tcp_hopopts);
5114 		tcp->tcp_hopopts = NULL;
5115 		tcp->tcp_hopoptslen = 0;
5116 	}
5117 	ASSERT(tcp->tcp_hopoptslen == 0);
5118 	if (tcp->tcp_dstopts != NULL) {
5119 		mi_free(tcp->tcp_dstopts);
5120 		tcp->tcp_dstopts = NULL;
5121 		tcp->tcp_dstoptslen = 0;
5122 	}
5123 	ASSERT(tcp->tcp_dstoptslen == 0);
5124 	if (tcp->tcp_rtdstopts != NULL) {
5125 		mi_free(tcp->tcp_rtdstopts);
5126 		tcp->tcp_rtdstopts = NULL;
5127 		tcp->tcp_rtdstoptslen = 0;
5128 	}
5129 	ASSERT(tcp->tcp_rtdstoptslen == 0);
5130 	if (tcp->tcp_rthdr != NULL) {
5131 		mi_free(tcp->tcp_rthdr);
5132 		tcp->tcp_rthdr = NULL;
5133 		tcp->tcp_rthdrlen = 0;
5134 	}
5135 	ASSERT(tcp->tcp_rthdrlen == 0);
5136 
5137 	ipp = &tcp->tcp_sticky_ipp;
5138 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
5139 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
5140 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
5141 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
5142 			ipp->ipp_hopopts = NULL;
5143 			ipp->ipp_hopoptslen = 0;
5144 		}
5145 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
5146 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
5147 			ipp->ipp_rtdstopts = NULL;
5148 			ipp->ipp_rtdstoptslen = 0;
5149 		}
5150 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
5151 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
5152 			ipp->ipp_dstopts = NULL;
5153 			ipp->ipp_dstoptslen = 0;
5154 		}
5155 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
5156 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
5157 			ipp->ipp_rthdr = NULL;
5158 			ipp->ipp_rthdrlen = 0;
5159 		}
5160 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
5161 		    IPPF_DSTOPTS | IPPF_RTHDR);
5162 	}
5163 
5164 	/*
5165 	 * Free memory associated with the tcp/ip header template.
5166 	 */
5167 
5168 	if (tcp->tcp_iphc != NULL)
5169 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5170 
5171 	/*
5172 	 * Following is really a blowing away a union.
5173 	 * It happens to have exactly two members of identical size
5174 	 * the following code is enough.
5175 	 */
5176 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
5177 
5178 	if (tcp->tcp_tracebuf != NULL) {
5179 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
5180 		tcp->tcp_tracebuf = NULL;
5181 	}
5182 }
5183 
5184 
5185 /*
5186  * Put a connection confirmation message upstream built from the
5187  * address information within 'iph' and 'tcph'.  Report our success or failure.
5188  */
5189 static boolean_t
5190 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
5191     mblk_t **defermp)
5192 {
5193 	sin_t	sin;
5194 	sin6_t	sin6;
5195 	mblk_t	*mp;
5196 	char	*optp = NULL;
5197 	int	optlen = 0;
5198 	cred_t	*cr;
5199 
5200 	if (defermp != NULL)
5201 		*defermp = NULL;
5202 
5203 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
5204 		/*
5205 		 * Return in T_CONN_CON results of option negotiation through
5206 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
5207 		 * negotiation, then what is received from remote end needs
5208 		 * to be taken into account but there is no such thing (yet?)
5209 		 * in our TCP/IP.
5210 		 * Note: We do not use mi_offset_param() here as
5211 		 * tcp_opts_conn_req contents do not directly come from
5212 		 * an application and are either generated in kernel or
5213 		 * from user input that was already verified.
5214 		 */
5215 		mp = tcp->tcp_conn.tcp_opts_conn_req;
5216 		optp = (char *)(mp->b_rptr +
5217 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
5218 		optlen = (int)
5219 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
5220 	}
5221 
5222 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
5223 		ipha_t *ipha = (ipha_t *)iphdr;
5224 
5225 		/* packet is IPv4 */
5226 		if (tcp->tcp_family == AF_INET) {
5227 			sin = sin_null;
5228 			sin.sin_addr.s_addr = ipha->ipha_src;
5229 			sin.sin_port = *(uint16_t *)tcph->th_lport;
5230 			sin.sin_family = AF_INET;
5231 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
5232 			    (int)sizeof (sin_t), optp, optlen);
5233 		} else {
5234 			sin6 = sin6_null;
5235 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
5236 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5237 			sin6.sin6_family = AF_INET6;
5238 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
5239 			    (int)sizeof (sin6_t), optp, optlen);
5240 
5241 		}
5242 	} else {
5243 		ip6_t	*ip6h = (ip6_t *)iphdr;
5244 
5245 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
5246 		ASSERT(tcp->tcp_family == AF_INET6);
5247 		sin6 = sin6_null;
5248 		sin6.sin6_addr = ip6h->ip6_src;
5249 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5250 		sin6.sin6_family = AF_INET6;
5251 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
5252 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
5253 		    (int)sizeof (sin6_t), optp, optlen);
5254 	}
5255 
5256 	if (!mp)
5257 		return (B_FALSE);
5258 
5259 	if ((cr = DB_CRED(idmp)) != NULL) {
5260 		mblk_setcred(mp, cr);
5261 		DB_CPID(mp) = DB_CPID(idmp);
5262 	}
5263 
5264 	if (defermp == NULL)
5265 		putnext(tcp->tcp_rq, mp);
5266 	else
5267 		*defermp = mp;
5268 
5269 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5270 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5271 	return (B_TRUE);
5272 }
5273 
5274 /*
5275  * Defense for the SYN attack -
5276  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
5277  *    one that doesn't have the dontdrop bit set.
5278  * 2. Don't drop a SYN request before its first timeout. This gives every
5279  *    request at least til the first timeout to complete its 3-way handshake.
5280  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
5281  *    requests currently on the queue that has timed out. This will be used
5282  *    as an indicator of whether an attack is under way, so that appropriate
5283  *    actions can be taken. (It's incremented in tcp_timer() and decremented
5284  *    either when eager goes into ESTABLISHED, or gets freed up.)
5285  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
5286  *    # of timeout drops back to <= q0len/32 => SYN alert off
5287  */
5288 static boolean_t
5289 tcp_drop_q0(tcp_t *tcp)
5290 {
5291 	tcp_t	*eager;
5292 
5293 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
5294 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
5295 	/*
5296 	 * New one is added after next_q0 so prev_q0 points to the oldest
5297 	 * Also do not drop any established connections that are deferred on
5298 	 * q0 due to q being full
5299 	 */
5300 
5301 	eager = tcp->tcp_eager_prev_q0;
5302 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
5303 		eager = eager->tcp_eager_prev_q0;
5304 		if (eager == tcp) {
5305 			eager = tcp->tcp_eager_prev_q0;
5306 			break;
5307 		}
5308 	}
5309 	if (eager->tcp_syn_rcvd_timeout == 0)
5310 		return (B_FALSE);
5311 
5312 	if (tcp->tcp_debug) {
5313 		(void) strlog(TCP_MODULE_ID, 0, 3, SL_TRACE,
5314 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
5315 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
5316 		    tcp->tcp_conn_req_cnt_q0,
5317 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5318 	}
5319 
5320 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
5321 
5322 	/*
5323 	 * need to do refhold here because the selected eager could
5324 	 * be removed by someone else if we release the eager lock.
5325 	 */
5326 	CONN_INC_REF(eager->tcp_connp);
5327 	mutex_exit(&tcp->tcp_eager_lock);
5328 
5329 	/* Mark the IRE created for this SYN request temporary */
5330 	tcp_ip_ire_mark_advice(eager);
5331 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
5332 	CONN_DEC_REF(eager->tcp_connp);
5333 
5334 	mutex_enter(&tcp->tcp_eager_lock);
5335 	return (B_TRUE);
5336 }
5337 
5338 int
5339 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
5340     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
5341 {
5342 	tcp_t 		*ltcp = lconnp->conn_tcp;
5343 	tcp_t		*tcp = connp->conn_tcp;
5344 	mblk_t		*tpi_mp;
5345 	ipha_t		*ipha;
5346 	ip6_t		*ip6h;
5347 	sin6_t 		sin6;
5348 	in6_addr_t 	v6dst;
5349 	int		err;
5350 	int		ifindex = 0;
5351 	cred_t		*cr;
5352 
5353 	if (ipvers == IPV4_VERSION) {
5354 		ipha = (ipha_t *)mp->b_rptr;
5355 
5356 		connp->conn_send = ip_output;
5357 		connp->conn_recv = tcp_input;
5358 
5359 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5360 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5361 
5362 		sin6 = sin6_null;
5363 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
5364 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
5365 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5366 		sin6.sin6_family = AF_INET6;
5367 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
5368 		    lconnp->conn_zoneid);
5369 		if (tcp->tcp_recvdstaddr) {
5370 			sin6_t	sin6d;
5371 
5372 			sin6d = sin6_null;
5373 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
5374 			    &sin6d.sin6_addr);
5375 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
5376 			sin6d.sin6_family = AF_INET;
5377 			tpi_mp = mi_tpi_extconn_ind(NULL,
5378 			    (char *)&sin6d, sizeof (sin6_t),
5379 			    (char *)&tcp,
5380 			    (t_scalar_t)sizeof (intptr_t),
5381 			    (char *)&sin6d, sizeof (sin6_t),
5382 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5383 		} else {
5384 			tpi_mp = mi_tpi_conn_ind(NULL,
5385 			    (char *)&sin6, sizeof (sin6_t),
5386 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5387 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5388 		}
5389 	} else {
5390 		ip6h = (ip6_t *)mp->b_rptr;
5391 
5392 		connp->conn_send = ip_output_v6;
5393 		connp->conn_recv = tcp_input;
5394 
5395 		connp->conn_srcv6 = ip6h->ip6_dst;
5396 		connp->conn_remv6 = ip6h->ip6_src;
5397 
5398 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
5399 		ifindex = (int)mp->b_datap->db_cksumstuff;
5400 		mp->b_datap->db_cksumstuff = 0;
5401 
5402 		sin6 = sin6_null;
5403 		sin6.sin6_addr = ip6h->ip6_src;
5404 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5405 		sin6.sin6_family = AF_INET6;
5406 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
5407 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
5408 		    lconnp->conn_zoneid);
5409 
5410 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
5411 			/* Pass up the scope_id of remote addr */
5412 			sin6.sin6_scope_id = ifindex;
5413 		} else {
5414 			sin6.sin6_scope_id = 0;
5415 		}
5416 		if (tcp->tcp_recvdstaddr) {
5417 			sin6_t	sin6d;
5418 
5419 			sin6d = sin6_null;
5420 			sin6.sin6_addr = ip6h->ip6_dst;
5421 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
5422 			sin6d.sin6_family = AF_INET;
5423 			tpi_mp = mi_tpi_extconn_ind(NULL,
5424 			    (char *)&sin6d, sizeof (sin6_t),
5425 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5426 			    (char *)&sin6d, sizeof (sin6_t),
5427 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5428 		} else {
5429 			tpi_mp = mi_tpi_conn_ind(NULL,
5430 			    (char *)&sin6, sizeof (sin6_t),
5431 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5432 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5433 		}
5434 	}
5435 
5436 	if (tpi_mp == NULL)
5437 		return (ENOMEM);
5438 
5439 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5440 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5441 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
5442 	connp->conn_fully_bound = B_FALSE;
5443 
5444 	if (tcp_trace)
5445 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5446 
5447 	/* Inherit information from the "parent" */
5448 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5449 	tcp->tcp_family = ltcp->tcp_family;
5450 	tcp->tcp_wq = ltcp->tcp_wq;
5451 	tcp->tcp_rq = ltcp->tcp_rq;
5452 	tcp->tcp_mss = tcp_mss_def_ipv6;
5453 	tcp->tcp_detached = B_TRUE;
5454 	if ((err = tcp_init_values(tcp)) != 0) {
5455 		freemsg(tpi_mp);
5456 		return (err);
5457 	}
5458 
5459 	if (ipvers == IPV4_VERSION) {
5460 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
5461 			freemsg(tpi_mp);
5462 			return (err);
5463 		}
5464 		ASSERT(tcp->tcp_ipha != NULL);
5465 	} else {
5466 		/* ifindex must be already set */
5467 		ASSERT(ifindex != 0);
5468 
5469 		if (ltcp->tcp_bound_if != 0) {
5470 			/*
5471 			 * Set newtcp's bound_if equal to
5472 			 * listener's value. If ifindex is
5473 			 * not the same as ltcp->tcp_bound_if,
5474 			 * it must be a packet for the ipmp group
5475 			 * of interfaces
5476 			 */
5477 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
5478 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
5479 			tcp->tcp_bound_if = ifindex;
5480 		}
5481 
5482 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
5483 		tcp->tcp_recvifindex = 0;
5484 		tcp->tcp_recvhops = 0xffffffffU;
5485 		ASSERT(tcp->tcp_ip6h != NULL);
5486 	}
5487 
5488 	tcp->tcp_lport = ltcp->tcp_lport;
5489 
5490 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
5491 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
5492 			/*
5493 			 * Listener had options of some sort; eager inherits.
5494 			 * Free up the eager template and allocate one
5495 			 * of the right size.
5496 			 */
5497 			if (tcp->tcp_hdr_grown) {
5498 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
5499 			} else {
5500 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5501 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5502 			}
5503 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5504 			    KM_NOSLEEP);
5505 			if (tcp->tcp_iphc == NULL) {
5506 				tcp->tcp_iphc_len = 0;
5507 				freemsg(tpi_mp);
5508 				return (ENOMEM);
5509 			}
5510 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5511 			tcp->tcp_hdr_grown = B_TRUE;
5512 		}
5513 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5514 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5515 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5516 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5517 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5518 
5519 		/*
5520 		 * Copy the IP+TCP header template from listener to eager
5521 		 */
5522 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5523 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5524 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5525 			    IPPROTO_RAW) {
5526 				tcp->tcp_ip6h =
5527 				    (ip6_t *)(tcp->tcp_iphc +
5528 					sizeof (ip6i_t));
5529 			} else {
5530 				tcp->tcp_ip6h =
5531 				    (ip6_t *)(tcp->tcp_iphc);
5532 			}
5533 			tcp->tcp_ipha = NULL;
5534 		} else {
5535 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5536 			tcp->tcp_ip6h = NULL;
5537 		}
5538 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5539 		    tcp->tcp_ip_hdr_len);
5540 	} else {
5541 		/*
5542 		 * only valid case when ipversion of listener and
5543 		 * eager differ is when listener is IPv6 and
5544 		 * eager is IPv4.
5545 		 * Eager header template has been initialized to the
5546 		 * maximum v4 header sizes, which includes space for
5547 		 * TCP and IP options.
5548 		 */
5549 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5550 		    (tcp->tcp_ipversion == IPV4_VERSION));
5551 		ASSERT(tcp->tcp_iphc_len >=
5552 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5553 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5554 		/* copy IP header fields individually */
5555 		tcp->tcp_ipha->ipha_ttl =
5556 		    ltcp->tcp_ip6h->ip6_hops;
5557 		bcopy(ltcp->tcp_tcph->th_lport,
5558 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5559 	}
5560 
5561 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5562 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5563 	    sizeof (in_port_t));
5564 
5565 	if (ltcp->tcp_lport == 0) {
5566 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5567 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5568 		    sizeof (in_port_t));
5569 	}
5570 
5571 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5572 		ASSERT(ipha != NULL);
5573 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5574 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5575 
5576 		/* Source routing option copyover (reverse it) */
5577 		if (tcp_rev_src_routes)
5578 			tcp_opt_reverse(tcp, ipha);
5579 	} else {
5580 		ASSERT(ip6h != NULL);
5581 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5582 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5583 	}
5584 
5585 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5586 	/*
5587 	 * If the SYN contains a credential, it's a loopback packet; attach
5588 	 * the credential to the TPI message.
5589 	 */
5590 	if ((cr = DB_CRED(idmp)) != NULL) {
5591 		mblk_setcred(tpi_mp, cr);
5592 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5593 	}
5594 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5595 
5596 	return (0);
5597 }
5598 
5599 
5600 int
5601 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5602     tcph_t *tcph, mblk_t *idmp)
5603 {
5604 	tcp_t 		*ltcp = lconnp->conn_tcp;
5605 	tcp_t		*tcp = connp->conn_tcp;
5606 	sin_t		sin;
5607 	mblk_t		*tpi_mp = NULL;
5608 	int		err;
5609 	cred_t		*cr;
5610 
5611 	sin = sin_null;
5612 	sin.sin_addr.s_addr = ipha->ipha_src;
5613 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5614 	sin.sin_family = AF_INET;
5615 	if (ltcp->tcp_recvdstaddr) {
5616 		sin_t	sind;
5617 
5618 		sind = sin_null;
5619 		sind.sin_addr.s_addr = ipha->ipha_dst;
5620 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5621 		sind.sin_family = AF_INET;
5622 		tpi_mp = mi_tpi_extconn_ind(NULL,
5623 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5624 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5625 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5626 	} else {
5627 		tpi_mp = mi_tpi_conn_ind(NULL,
5628 		    (char *)&sin, sizeof (sin_t),
5629 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5630 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5631 	}
5632 
5633 	if (tpi_mp == NULL) {
5634 		return (ENOMEM);
5635 	}
5636 
5637 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5638 	connp->conn_send = ip_output;
5639 	connp->conn_recv = tcp_input;
5640 	connp->conn_fully_bound = B_FALSE;
5641 
5642 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5643 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5644 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5645 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5646 
5647 	if (tcp_trace) {
5648 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5649 	}
5650 
5651 	/* Inherit information from the "parent" */
5652 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5653 	tcp->tcp_family = ltcp->tcp_family;
5654 	tcp->tcp_wq = ltcp->tcp_wq;
5655 	tcp->tcp_rq = ltcp->tcp_rq;
5656 	tcp->tcp_mss = tcp_mss_def_ipv4;
5657 	tcp->tcp_detached = B_TRUE;
5658 	if ((err = tcp_init_values(tcp)) != 0) {
5659 		freemsg(tpi_mp);
5660 		return (err);
5661 	}
5662 
5663 	/*
5664 	 * Let's make sure that eager tcp template has enough space to
5665 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5666 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5667 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5668 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5669 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5670 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5671 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5672 	 */
5673 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5674 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5675 
5676 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5677 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5678 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5679 	tcp->tcp_ttl = ltcp->tcp_ttl;
5680 	tcp->tcp_tos = ltcp->tcp_tos;
5681 
5682 	/* Copy the IP+TCP header template from listener to eager */
5683 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5684 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5685 	tcp->tcp_ip6h = NULL;
5686 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5687 	    tcp->tcp_ip_hdr_len);
5688 
5689 	/* Initialize the IP addresses and Ports */
5690 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5691 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5692 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5693 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5694 
5695 	/* Source routing option copyover (reverse it) */
5696 	if (tcp_rev_src_routes)
5697 		tcp_opt_reverse(tcp, ipha);
5698 
5699 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5700 
5701 	/*
5702 	 * If the SYN contains a credential, it's a loopback packet; attach
5703 	 * the credential to the TPI message.
5704 	 */
5705 	if ((cr = DB_CRED(idmp)) != NULL) {
5706 		mblk_setcred(tpi_mp, cr);
5707 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5708 	}
5709 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5710 
5711 	return (0);
5712 }
5713 
5714 /*
5715  * sets up conn for ipsec.
5716  * if the first mblk is M_CTL it is consumed and mpp is updated.
5717  * in case of error mpp is freed.
5718  */
5719 conn_t *
5720 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5721 {
5722 	conn_t 		*connp = tcp->tcp_connp;
5723 	conn_t 		*econnp;
5724 	squeue_t 	*new_sqp;
5725 	mblk_t 		*first_mp = *mpp;
5726 	mblk_t		*mp = *mpp;
5727 	boolean_t	mctl_present = B_FALSE;
5728 	uint_t		ipvers;
5729 
5730 	econnp = tcp_get_conn(sqp);
5731 	if (econnp == NULL) {
5732 		freemsg(first_mp);
5733 		return (NULL);
5734 	}
5735 	if (DB_TYPE(mp) == M_CTL) {
5736 		if (mp->b_cont == NULL ||
5737 		    mp->b_cont->b_datap->db_type != M_DATA) {
5738 			freemsg(first_mp);
5739 			return (NULL);
5740 		}
5741 		mp = mp->b_cont;
5742 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5743 			freemsg(first_mp);
5744 			return (NULL);
5745 		}
5746 
5747 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5748 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5749 		mctl_present = B_TRUE;
5750 	} else {
5751 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5752 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5753 	}
5754 
5755 	new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
5756 	mp->b_datap->db_cksumstart = 0;
5757 
5758 	ASSERT(OK_32PTR(mp->b_rptr));
5759 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5760 	if (ipvers == IPV4_VERSION) {
5761 		uint16_t  	*up;
5762 		uint32_t	ports;
5763 		ipha_t		*ipha;
5764 
5765 		ipha = (ipha_t *)mp->b_rptr;
5766 		up = (uint16_t *)((uchar_t *)ipha +
5767 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5768 		ports = *(uint32_t *)up;
5769 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5770 		    ipha->ipha_dst, ipha->ipha_src, ports);
5771 	} else {
5772 		uint16_t  	*up;
5773 		uint32_t	ports;
5774 		uint16_t	ip_hdr_len;
5775 		uint8_t		*nexthdrp;
5776 		ip6_t 		*ip6h;
5777 		tcph_t		*tcph;
5778 
5779 		ip6h = (ip6_t *)mp->b_rptr;
5780 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5781 			ip_hdr_len = IPV6_HDR_LEN;
5782 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5783 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5784 			CONN_DEC_REF(econnp);
5785 			freemsg(first_mp);
5786 			return (NULL);
5787 		}
5788 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5789 		up = (uint16_t *)tcph->th_lport;
5790 		ports = *(uint32_t *)up;
5791 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5792 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5793 	}
5794 
5795 	/*
5796 	 * The caller already ensured that there is a sqp present.
5797 	 */
5798 	econnp->conn_sqp = new_sqp;
5799 
5800 	if (connp->conn_policy != NULL) {
5801 		ipsec_in_t *ii;
5802 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5803 		ASSERT(ii->ipsec_in_policy == NULL);
5804 		IPPH_REFHOLD(connp->conn_policy);
5805 		ii->ipsec_in_policy = connp->conn_policy;
5806 
5807 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5808 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5809 			CONN_DEC_REF(econnp);
5810 			freemsg(first_mp);
5811 			return (NULL);
5812 		}
5813 	}
5814 
5815 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5816 		CONN_DEC_REF(econnp);
5817 		freemsg(first_mp);
5818 		return (NULL);
5819 	}
5820 
5821 	/*
5822 	 * If we know we have some policy, pass the "IPSEC"
5823 	 * options size TCP uses this adjust the MSS.
5824 	 */
5825 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5826 	if (mctl_present) {
5827 		freeb(first_mp);
5828 		*mpp = mp;
5829 	}
5830 
5831 	return (econnp);
5832 }
5833 
5834 /*
5835  * tcp_get_conn/tcp_free_conn
5836  *
5837  * tcp_get_conn is used to get a clean tcp connection structure.
5838  * It tries to reuse the connections put on the freelist by the
5839  * time_wait_collector failing which it goes to kmem_cache. This
5840  * way has two benefits compared to just allocating from and
5841  * freeing to kmem_cache.
5842  * 1) The time_wait_collector can free (which includes the cleanup)
5843  * outside the squeue. So when the interrupt comes, we have a clean
5844  * connection sitting in the freelist. Obviously, this buys us
5845  * performance.
5846  *
5847  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5848  * has multiple disadvantages - tying up the squeue during alloc, and the
5849  * fact that IPSec policy initialization has to happen here which
5850  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5851  * But allocating the conn/tcp in IP land is also not the best since
5852  * we can't check the 'q' and 'q0' which are protected by squeue and
5853  * blindly allocate memory which might have to be freed here if we are
5854  * not allowed to accept the connection. By using the freelist and
5855  * putting the conn/tcp back in freelist, we don't pay a penalty for
5856  * allocating memory without checking 'q/q0' and freeing it if we can't
5857  * accept the connection.
5858  *
5859  * Care should be taken to put the conn back in the same squeue's freelist
5860  * from which it was allocated. Best results are obtained if conn is
5861  * allocated from listener's squeue and freed to the same. Time wait
5862  * collector will free up the freelist is the connection ends up sitting
5863  * there for too long.
5864  */
5865 void *
5866 tcp_get_conn(void *arg)
5867 {
5868 	tcp_t			*tcp = NULL;
5869 	conn_t			*connp = NULL;
5870 	squeue_t		*sqp = (squeue_t *)arg;
5871 	tcp_squeue_priv_t 	*tcp_time_wait;
5872 
5873 	tcp_time_wait =
5874 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5875 
5876 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5877 	tcp = tcp_time_wait->tcp_free_list;
5878 	if (tcp != NULL) {
5879 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5880 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5881 		tcp->tcp_time_wait_next = NULL;
5882 		connp = tcp->tcp_connp;
5883 		connp->conn_flags |= IPCL_REUSED;
5884 		return ((void *)connp);
5885 	}
5886 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5887 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5888 		return (NULL);
5889 	return ((void *)connp);
5890 }
5891 
5892 /* BEGIN CSTYLED */
5893 /*
5894  *
5895  * The sockfs ACCEPT path:
5896  * =======================
5897  *
5898  * The eager is now established in its own perimeter as soon as SYN is
5899  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5900  * completes the accept processing on the acceptor STREAM. The sending
5901  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5902  * listener but a TLI/XTI listener completes the accept processing
5903  * on the listener perimeter.
5904  *
5905  * Common control flow for 3 way handshake:
5906  * ----------------------------------------
5907  *
5908  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5909  *					-> tcp_conn_request()
5910  *
5911  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5912  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5913  *
5914  * Sockfs ACCEPT Path:
5915  * -------------------
5916  *
5917  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5918  * as STREAM entry point)
5919  *
5920  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5921  *
5922  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5923  * association (we are not behind eager's squeue but sockfs is protecting us
5924  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5925  * is changed to point at tcp_wput().
5926  *
5927  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5928  * listener (done on listener's perimeter).
5929  *
5930  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5931  * accept.
5932  *
5933  * TLI/XTI client ACCEPT path:
5934  * ---------------------------
5935  *
5936  * soaccept() sends T_CONN_RES on the listener STREAM.
5937  *
5938  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5939  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5940  *
5941  * Locks:
5942  * ======
5943  *
5944  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5945  * and listeners->tcp_eager_next_q.
5946  *
5947  * Referencing:
5948  * ============
5949  *
5950  * 1) We start out in tcp_conn_request by eager placing a ref on
5951  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5952  *
5953  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5954  * doing so we place a ref on the eager. This ref is finally dropped at the
5955  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5956  * reference is dropped by the squeue framework.
5957  *
5958  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5959  *
5960  * The reference must be released by the same entity that added the reference
5961  * In the above scheme, the eager is the entity that adds and releases the
5962  * references. Note that tcp_accept_finish executes in the squeue of the eager
5963  * (albeit after it is attached to the acceptor stream). Though 1. executes
5964  * in the listener's squeue, the eager is nascent at this point and the
5965  * reference can be considered to have been added on behalf of the eager.
5966  *
5967  * Eager getting a Reset or listener closing:
5968  * ==========================================
5969  *
5970  * Once the listener and eager are linked, the listener never does the unlink.
5971  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5972  * a message on all eager perimeter. The eager then does the unlink, clears
5973  * any pointers to the listener's queue and drops the reference to the
5974  * listener. The listener waits in tcp_close outside the squeue until its
5975  * refcount has dropped to 1. This ensures that the listener has waited for
5976  * all eagers to clear their association with the listener.
5977  *
5978  * Similarly, if eager decides to go away, it can unlink itself and close.
5979  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5980  * the reference to eager is still valid because of the extra ref we put
5981  * in tcp_send_conn_ind.
5982  *
5983  * Listener can always locate the eager under the protection
5984  * of the listener->tcp_eager_lock, and then do a refhold
5985  * on the eager during the accept processing.
5986  *
5987  * The acceptor stream accesses the eager in the accept processing
5988  * based on the ref placed on eager before sending T_conn_ind.
5989  * The only entity that can negate this refhold is a listener close
5990  * which is mutually exclusive with an active acceptor stream.
5991  *
5992  * Eager's reference on the listener
5993  * ===================================
5994  *
5995  * If the accept happens (even on a closed eager) the eager drops its
5996  * reference on the listener at the start of tcp_accept_finish. If the
5997  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5998  * the reference is dropped in tcp_closei_local. If the listener closes,
5999  * the reference is dropped in tcp_eager_kill. In all cases the reference
6000  * is dropped while executing in the eager's context (squeue).
6001  */
6002 /* END CSTYLED */
6003 
6004 /* Process the SYN packet, mp, directed at the listener 'tcp' */
6005 
6006 /*
6007  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
6008  * tcp_rput_data will not see any SYN packets.
6009  */
6010 /* ARGSUSED */
6011 void
6012 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
6013 {
6014 	tcph_t		*tcph;
6015 	uint32_t	seg_seq;
6016 	tcp_t		*eager;
6017 	uint_t		ipvers;
6018 	ipha_t		*ipha;
6019 	ip6_t		*ip6h;
6020 	int		err;
6021 	conn_t		*econnp = NULL;
6022 	squeue_t	*new_sqp;
6023 	mblk_t		*mp1;
6024 	uint_t 		ip_hdr_len;
6025 	conn_t		*connp = (conn_t *)arg;
6026 	tcp_t		*tcp = connp->conn_tcp;
6027 	ire_t		*ire;
6028 
6029 	if (tcp->tcp_state != TCPS_LISTEN)
6030 		goto error2;
6031 
6032 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
6033 
6034 	mutex_enter(&tcp->tcp_eager_lock);
6035 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
6036 		mutex_exit(&tcp->tcp_eager_lock);
6037 		TCP_STAT(tcp_listendrop);
6038 		BUMP_MIB(&tcp_mib, tcpListenDrop);
6039 		if (tcp->tcp_debug) {
6040 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
6041 			    "tcp_conn_request: listen backlog (max=%d) "
6042 			    "overflow (%d pending) on %s",
6043 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
6044 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
6045 		}
6046 		goto error2;
6047 	}
6048 
6049 	if (tcp->tcp_conn_req_cnt_q0 >=
6050 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
6051 		/*
6052 		 * Q0 is full. Drop a pending half-open req from the queue
6053 		 * to make room for the new SYN req. Also mark the time we
6054 		 * drop a SYN.
6055 		 *
6056 		 * A more aggressive defense against SYN attack will
6057 		 * be to set the "tcp_syn_defense" flag now.
6058 		 */
6059 		TCP_STAT(tcp_listendropq0);
6060 		tcp->tcp_last_rcv_lbolt = lbolt64;
6061 		if (!tcp_drop_q0(tcp)) {
6062 			mutex_exit(&tcp->tcp_eager_lock);
6063 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
6064 			if (tcp->tcp_debug) {
6065 				(void) strlog(TCP_MODULE_ID, 0, 3, SL_TRACE,
6066 				    "tcp_conn_request: listen half-open queue "
6067 				    "(max=%d) full (%d pending) on %s",
6068 				    tcp_conn_req_max_q0,
6069 				    tcp->tcp_conn_req_cnt_q0,
6070 				    tcp_display(tcp, NULL,
6071 				    DISP_PORT_ONLY));
6072 			}
6073 			goto error2;
6074 		}
6075 	}
6076 	mutex_exit(&tcp->tcp_eager_lock);
6077 
6078 	/*
6079 	 * IP adds STRUIO_EAGER and ensures that the received packet is
6080 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
6081 	 * link local address.  If IPSec is enabled, db_struioflag has
6082 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
6083 	 * otherwise an error case if neither of them is set.
6084 	 */
6085 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6086 		new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
6087 		mp->b_datap->db_cksumstart = 0;
6088 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
6089 		econnp = (conn_t *)tcp_get_conn(arg2);
6090 		if (econnp == NULL)
6091 			goto error2;
6092 		econnp->conn_sqp = new_sqp;
6093 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
6094 		/*
6095 		 * mp is updated in tcp_get_ipsec_conn().
6096 		 */
6097 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
6098 		if (econnp == NULL) {
6099 			/*
6100 			 * mp freed by tcp_get_ipsec_conn.
6101 			 */
6102 			return;
6103 		}
6104 	} else {
6105 		goto error2;
6106 	}
6107 
6108 	ASSERT(DB_TYPE(mp) == M_DATA);
6109 
6110 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
6111 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
6112 	ASSERT(OK_32PTR(mp->b_rptr));
6113 	if (ipvers == IPV4_VERSION) {
6114 		ipha = (ipha_t *)mp->b_rptr;
6115 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
6116 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6117 	} else {
6118 		ip6h = (ip6_t *)mp->b_rptr;
6119 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
6120 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6121 	}
6122 
6123 	if (tcp->tcp_family == AF_INET) {
6124 		ASSERT(ipvers == IPV4_VERSION);
6125 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
6126 	} else {
6127 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
6128 	}
6129 
6130 	if (err)
6131 		goto error3;
6132 
6133 	eager = econnp->conn_tcp;
6134 
6135 	/* Inherit various TCP parameters from the listener */
6136 	eager->tcp_naglim = tcp->tcp_naglim;
6137 	eager->tcp_first_timer_threshold =
6138 	    tcp->tcp_first_timer_threshold;
6139 	eager->tcp_second_timer_threshold =
6140 	    tcp->tcp_second_timer_threshold;
6141 
6142 	eager->tcp_first_ctimer_threshold =
6143 	    tcp->tcp_first_ctimer_threshold;
6144 	eager->tcp_second_ctimer_threshold =
6145 	    tcp->tcp_second_ctimer_threshold;
6146 
6147 	/*
6148 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
6149 	 * zone id before the accept is completed in tcp_wput_accept().
6150 	 */
6151 	econnp->conn_zoneid = connp->conn_zoneid;
6152 
6153 	eager->tcp_hard_binding = B_TRUE;
6154 
6155 	tcp_bind_hash_insert(&tcp_bind_fanout[
6156 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
6157 
6158 	CL_INET_CONNECT(eager);
6159 
6160 	/*
6161 	 * No need to check for multicast destination since ip will only pass
6162 	 * up multicasts to those that have expressed interest
6163 	 * TODO: what about rejecting broadcasts?
6164 	 * Also check that source is not a multicast or broadcast address.
6165 	 */
6166 	eager->tcp_state = TCPS_SYN_RCVD;
6167 
6168 
6169 	/*
6170 	 * There should be no ire in the mp as we are being called after
6171 	 * receiving the SYN.
6172 	 */
6173 	ASSERT(tcp_ire_mp(mp) == NULL);
6174 
6175 	/*
6176 	 * Adapt our mss, ttl, ... according to information provided in IRE.
6177 	 */
6178 
6179 	if (tcp_adapt_ire(eager, NULL) == 0) {
6180 		/* Undo the bind_hash_insert */
6181 		tcp_bind_hash_remove(eager);
6182 		goto error3;
6183 	}
6184 
6185 	/* Process all TCP options. */
6186 	tcp_process_options(eager, tcph);
6187 
6188 	/* Is the other end ECN capable? */
6189 	if (tcp_ecn_permitted >= 1 &&
6190 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
6191 		eager->tcp_ecn_ok = B_TRUE;
6192 	}
6193 
6194 	/*
6195 	 * listener->tcp_rq->q_hiwat should be the default window size or a
6196 	 * window size changed via SO_RCVBUF option.  First round up the
6197 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
6198 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
6199 	 * setting.
6200 	 *
6201 	 * Note if there is a rpipe metric associated with the remote host,
6202 	 * we should not inherit receive window size from listener.
6203 	 */
6204 	eager->tcp_rwnd = MSS_ROUNDUP(
6205 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
6206 	    eager->tcp_rwnd), eager->tcp_mss);
6207 	if (eager->tcp_snd_ws_ok)
6208 		tcp_set_ws_value(eager);
6209 	/*
6210 	 * Note that this is the only place tcp_rwnd_set() is called for
6211 	 * accepting a connection.  We need to call it here instead of
6212 	 * after the 3-way handshake because we need to tell the other
6213 	 * side our rwnd in the SYN-ACK segment.
6214 	 */
6215 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
6216 
6217 	/*
6218 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
6219 	 * via soaccept()->soinheritoptions() which essentially applies
6220 	 * all the listener options to the new STREAM. The options that we
6221 	 * need to take care of are:
6222 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
6223 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
6224 	 * SO_SNDBUF, SO_RCVBUF.
6225 	 *
6226 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
6227 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
6228 	 *		tcp_maxpsz_set() gets called later from
6229 	 *		tcp_accept_finish(), the option takes effect.
6230 	 *
6231 	 */
6232 	/* Set the TCP options */
6233 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
6234 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
6235 	eager->tcp_oobinline = tcp->tcp_oobinline;
6236 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
6237 	eager->tcp_broadcast = tcp->tcp_broadcast;
6238 	eager->tcp_useloopback = tcp->tcp_useloopback;
6239 	eager->tcp_dontroute = tcp->tcp_dontroute;
6240 	eager->tcp_linger = tcp->tcp_linger;
6241 	eager->tcp_lingertime = tcp->tcp_lingertime;
6242 	if (tcp->tcp_ka_enabled)
6243 		eager->tcp_ka_enabled = 1;
6244 
6245 	/* Set the IP options */
6246 	econnp->conn_broadcast = connp->conn_broadcast;
6247 	econnp->conn_loopback = connp->conn_loopback;
6248 	econnp->conn_dontroute = connp->conn_dontroute;
6249 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
6250 
6251 	/* Put a ref on the listener for the eager. */
6252 	CONN_INC_REF(connp);
6253 	mutex_enter(&tcp->tcp_eager_lock);
6254 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
6255 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
6256 	tcp->tcp_eager_next_q0 = eager;
6257 	eager->tcp_eager_prev_q0 = tcp;
6258 
6259 	/* Set tcp_listener before adding it to tcp_conn_fanout */
6260 	eager->tcp_listener = tcp;
6261 	eager->tcp_saved_listener = tcp;
6262 
6263 	/*
6264 	 * Tag this detached tcp vector for later retrieval
6265 	 * by our listener client in tcp_accept().
6266 	 */
6267 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
6268 	tcp->tcp_conn_req_cnt_q0++;
6269 	if (++tcp->tcp_conn_req_seqnum == -1) {
6270 		/*
6271 		 * -1 is "special" and defined in TPI as something
6272 		 * that should never be used in T_CONN_IND
6273 		 */
6274 		++tcp->tcp_conn_req_seqnum;
6275 	}
6276 	mutex_exit(&tcp->tcp_eager_lock);
6277 
6278 	if (tcp->tcp_syn_defense) {
6279 		/* Don't drop the SYN that comes from a good IP source */
6280 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
6281 		if (addr_cache != NULL && eager->tcp_remote ==
6282 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
6283 			eager->tcp_dontdrop = B_TRUE;
6284 		}
6285 	}
6286 
6287 	/*
6288 	 * We need to insert the eager in its own perimeter but as soon
6289 	 * as we do that, we expose the eager to the classifier and
6290 	 * should not touch any field outside the eager's perimeter.
6291 	 * So do all the work necessary before inserting the eager
6292 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
6293 	 * will succeed but undo everything if it fails.
6294 	 */
6295 	seg_seq = ABE32_TO_U32(tcph->th_seq);
6296 	eager->tcp_irs = seg_seq;
6297 	eager->tcp_rack = seg_seq;
6298 	eager->tcp_rnxt = seg_seq + 1;
6299 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
6300 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
6301 	eager->tcp_state = TCPS_SYN_RCVD;
6302 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
6303 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
6304 	if (mp1 == NULL)
6305 		goto error1;
6306 	mblk_setcred(mp1, tcp->tcp_cred);
6307 	DB_CPID(mp1) = tcp->tcp_cpid;
6308 
6309 	/*
6310 	 * We need to start the rto timer. In normal case, we start
6311 	 * the timer after sending the packet on the wire (or at
6312 	 * least believing that packet was sent by waiting for
6313 	 * CALL_IP_WPUT() to return). Since this is the first packet
6314 	 * being sent on the wire for the eager, our initial tcp_rto
6315 	 * is at least tcp_rexmit_interval_min which is a fairly
6316 	 * large value to allow the algorithm to adjust slowly to large
6317 	 * fluctuations of RTT during first few transmissions.
6318 	 *
6319 	 * Starting the timer first and then sending the packet in this
6320 	 * case shouldn't make much difference since tcp_rexmit_interval_min
6321 	 * is of the order of several 100ms and starting the timer
6322 	 * first and then sending the packet will result in difference
6323 	 * of few micro seconds.
6324 	 *
6325 	 * Without this optimization, we are forced to hold the fanout
6326 	 * lock across the ipcl_bind_insert() and sending the packet
6327 	 * so that we don't race against an incoming packet (maybe RST)
6328 	 * for this eager.
6329 	 */
6330 
6331 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
6332 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6333 
6334 
6335 	/*
6336 	 * Insert the eager in its own perimeter now. We are ready to deal
6337 	 * with any packets on eager.
6338 	 */
6339 	if (eager->tcp_ipversion == IPV4_VERSION) {
6340 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6341 			goto error;
6342 		}
6343 	} else {
6344 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6345 			goto error;
6346 		}
6347 	}
6348 
6349 	/* mark conn as fully-bound */
6350 	econnp->conn_fully_bound = B_TRUE;
6351 
6352 	/* Send the SYN-ACK */
6353 	tcp_send_data(eager, eager->tcp_wq, mp1);
6354 	freemsg(mp);
6355 
6356 	return;
6357 error:
6358 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
6359 	freemsg(mp1);
6360 error1:
6361 	/* Undo what we did above */
6362 	mutex_enter(&tcp->tcp_eager_lock);
6363 	tcp_eager_unlink(eager);
6364 	mutex_exit(&tcp->tcp_eager_lock);
6365 	/* Drop eager's reference on the listener */
6366 	CONN_DEC_REF(connp);
6367 
6368 	/*
6369 	 * Delete the cached ire in conn_ire_cache and also mark
6370 	 * the conn as CONDEMNED
6371 	 */
6372 	mutex_enter(&econnp->conn_lock);
6373 	econnp->conn_state_flags |= CONN_CONDEMNED;
6374 	ire = econnp->conn_ire_cache;
6375 	econnp->conn_ire_cache = NULL;
6376 	mutex_exit(&econnp->conn_lock);
6377 	if (ire != NULL)
6378 		IRE_REFRELE_NOTR(ire);
6379 
6380 	/*
6381 	 * tcp_accept_comm inserts the eager to the bind_hash
6382 	 * we need to remove it from the hash if ipcl_conn_insert
6383 	 * fails.
6384 	 */
6385 	tcp_bind_hash_remove(eager);
6386 	/* Drop the eager ref placed in tcp_open_detached */
6387 	CONN_DEC_REF(econnp);
6388 
6389 	/*
6390 	 * If a connection already exists, send the mp to that connections so
6391 	 * that it can be appropriately dealt with.
6392 	 */
6393 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
6394 		if (!IPCL_IS_CONNECTED(econnp)) {
6395 			/*
6396 			 * Something bad happened. ipcl_conn_insert()
6397 			 * failed because a connection already existed
6398 			 * in connected hash but we can't find it
6399 			 * anymore (someone blew it away). Just
6400 			 * free this message and hopefully remote
6401 			 * will retransmit at which time the SYN can be
6402 			 * treated as a new connection or dealth with
6403 			 * a TH_RST if a connection already exists.
6404 			 */
6405 			freemsg(mp);
6406 		} else {
6407 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6408 			    econnp, SQTAG_TCP_CONN_REQ);
6409 		}
6410 	} else {
6411 		/* Nobody wants this packet */
6412 		freemsg(mp);
6413 	}
6414 	return;
6415 error2:
6416 	freemsg(mp);
6417 	return;
6418 error3:
6419 	CONN_DEC_REF(econnp);
6420 	freemsg(mp);
6421 }
6422 
6423 /*
6424  * In an ideal case of vertical partition in NUMA architecture, its
6425  * beneficial to have the listener and all the incoming connections
6426  * tied to the same squeue. The other constraint is that incoming
6427  * connections should be tied to the squeue attached to interrupted
6428  * CPU for obvious locality reason so this leaves the listener to
6429  * be tied to the same squeue. Our only problem is that when listener
6430  * is binding, the CPU that will get interrupted by the NIC whose
6431  * IP address the listener is binding to is not even known. So
6432  * the code below allows us to change that binding at the time the
6433  * CPU is interrupted by virtue of incoming connection's squeue.
6434  *
6435  * This is usefull only in case of a listener bound to a specific IP
6436  * address. For other kind of listeners, they get bound the
6437  * very first time and there is no attempt to rebind them.
6438  */
6439 void
6440 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6441 {
6442 	conn_t		*connp = (conn_t *)arg;
6443 	squeue_t	*sqp = (squeue_t *)arg2;
6444 	squeue_t	*new_sqp;
6445 	uint32_t	conn_flags;
6446 
6447 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6448 		new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
6449 	} else {
6450 		goto done;
6451 	}
6452 
6453 	if (connp->conn_fanout == NULL)
6454 		goto done;
6455 
6456 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6457 		mutex_enter(&connp->conn_fanout->connf_lock);
6458 		mutex_enter(&connp->conn_lock);
6459 		/*
6460 		 * No one from read or write side can access us now
6461 		 * except for already queued packets on this squeue.
6462 		 * But since we haven't changed the squeue yet, they
6463 		 * can't execute. If they are processed after we have
6464 		 * changed the squeue, they are sent back to the
6465 		 * correct squeue down below.
6466 		 */
6467 		if (connp->conn_sqp != new_sqp) {
6468 			while (connp->conn_sqp != new_sqp)
6469 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6470 		}
6471 
6472 		do {
6473 			conn_flags = connp->conn_flags;
6474 			conn_flags |= IPCL_FULLY_BOUND;
6475 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6476 			    conn_flags);
6477 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6478 
6479 		mutex_exit(&connp->conn_fanout->connf_lock);
6480 		mutex_exit(&connp->conn_lock);
6481 	}
6482 
6483 done:
6484 	if (connp->conn_sqp != sqp) {
6485 		CONN_INC_REF(connp);
6486 		squeue_fill(connp->conn_sqp, mp,
6487 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6488 	} else {
6489 		tcp_conn_request(connp, mp, sqp);
6490 	}
6491 }
6492 
6493 /*
6494  * Successful connect request processing begins when our client passes
6495  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6496  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6497  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6498  *   upstream <- tcp_rput()                <- IP
6499  * After various error checks are completed, tcp_connect() lays
6500  * the target address and port into the composite header template,
6501  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6502  * request followed by an IRE request, and passes the three mblk message
6503  * down to IP looking like this:
6504  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6505  * Processing continues in tcp_rput() when we receive the following message:
6506  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6507  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6508  * to fire off the connection request, and then passes the T_OK_ACK mblk
6509  * upstream that we filled in below.  There are, of course, numerous
6510  * error conditions along the way which truncate the processing described
6511  * above.
6512  */
6513 static void
6514 tcp_connect(tcp_t *tcp, mblk_t *mp)
6515 {
6516 	sin_t		*sin;
6517 	sin6_t		*sin6;
6518 	queue_t		*q = tcp->tcp_wq;
6519 	struct T_conn_req	*tcr;
6520 	ipaddr_t	*dstaddrp;
6521 	in_port_t	dstport;
6522 	uint_t		srcid;
6523 
6524 	tcr = (struct T_conn_req *)mp->b_rptr;
6525 
6526 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6527 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6528 		tcp_err_ack(tcp, mp, TPROTO, 0);
6529 		return;
6530 	}
6531 
6532 	/*
6533 	 * Determine packet type based on type of address passed in
6534 	 * the request should contain an IPv4 or IPv6 address.
6535 	 * Make sure that address family matches the type of
6536 	 * family of the the address passed down
6537 	 */
6538 	switch (tcr->DEST_length) {
6539 	default:
6540 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6541 		return;
6542 
6543 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6544 		/*
6545 		 * XXX: The check for valid DEST_length was not there
6546 		 * in earlier releases and some buggy
6547 		 * TLI apps (e.g Sybase) got away with not feeding
6548 		 * in sin_zero part of address.
6549 		 * We allow that bug to keep those buggy apps humming.
6550 		 * Test suites require the check on DEST_length.
6551 		 * We construct a new mblk with valid DEST_length
6552 		 * free the original so the rest of the code does
6553 		 * not have to keep track of this special shorter
6554 		 * length address case.
6555 		 */
6556 		mblk_t *nmp;
6557 		struct T_conn_req *ntcr;
6558 		sin_t *nsin;
6559 
6560 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6561 		    tcr->OPT_length, BPRI_HI);
6562 		if (nmp == NULL) {
6563 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6564 			return;
6565 		}
6566 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6567 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6568 		ntcr->PRIM_type = T_CONN_REQ;
6569 		ntcr->DEST_length = sizeof (sin_t);
6570 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6571 
6572 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6573 		*nsin = sin_null;
6574 		/* Get pointer to shorter address to copy from original mp */
6575 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6576 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6577 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6578 			freemsg(nmp);
6579 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6580 			return;
6581 		}
6582 		nsin->sin_family = sin->sin_family;
6583 		nsin->sin_port = sin->sin_port;
6584 		nsin->sin_addr = sin->sin_addr;
6585 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6586 		nmp->b_wptr = (uchar_t *)&nsin[1];
6587 		if (tcr->OPT_length != 0) {
6588 			ntcr->OPT_length = tcr->OPT_length;
6589 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6590 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6591 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6592 			    tcr->OPT_length);
6593 			nmp->b_wptr += tcr->OPT_length;
6594 		}
6595 		freemsg(mp);	/* original mp freed */
6596 		mp = nmp;	/* re-initialize original variables */
6597 		tcr = ntcr;
6598 	}
6599 	/* FALLTHRU */
6600 
6601 	case sizeof (sin_t):
6602 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6603 		    sizeof (sin_t));
6604 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6605 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6606 			return;
6607 		}
6608 		if (tcp->tcp_family != AF_INET ||
6609 		    sin->sin_family != AF_INET) {
6610 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6611 			return;
6612 		}
6613 		if (sin->sin_port == 0) {
6614 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6615 			return;
6616 		}
6617 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6618 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6619 			return;
6620 		}
6621 
6622 		break;
6623 
6624 	case sizeof (sin6_t):
6625 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6626 		    sizeof (sin6_t));
6627 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6628 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6629 			return;
6630 		}
6631 		if (tcp->tcp_family != AF_INET6 ||
6632 		    sin6->sin6_family != AF_INET6) {
6633 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6634 			return;
6635 		}
6636 		if (sin6->sin6_port == 0) {
6637 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6638 			return;
6639 		}
6640 		break;
6641 	}
6642 	/*
6643 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6644 	 * should key on their sequence number and cut them loose.
6645 	 */
6646 
6647 	/*
6648 	 * If options passed in, feed it for verification and handling
6649 	 */
6650 	if (tcr->OPT_length != 0) {
6651 		mblk_t	*ok_mp;
6652 		mblk_t	*discon_mp;
6653 		mblk_t  *conn_opts_mp;
6654 		int t_error, sys_error, do_disconnect;
6655 
6656 		conn_opts_mp = NULL;
6657 
6658 		if (tcp_conprim_opt_process(tcp, mp,
6659 			&do_disconnect, &t_error, &sys_error) < 0) {
6660 			if (do_disconnect) {
6661 				ASSERT(t_error == 0 && sys_error == 0);
6662 				discon_mp = mi_tpi_discon_ind(NULL,
6663 				    ECONNREFUSED, 0);
6664 				if (!discon_mp) {
6665 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6666 					    TSYSERR, ENOMEM);
6667 					return;
6668 				}
6669 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6670 				if (!ok_mp) {
6671 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6672 					    TSYSERR, ENOMEM);
6673 					return;
6674 				}
6675 				qreply(q, ok_mp);
6676 				qreply(q, discon_mp); /* no flush! */
6677 			} else {
6678 				ASSERT(t_error != 0);
6679 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6680 				    sys_error);
6681 			}
6682 			return;
6683 		}
6684 		/*
6685 		 * Success in setting options, the mp option buffer represented
6686 		 * by OPT_length/offset has been potentially modified and
6687 		 * contains results of option processing. We copy it in
6688 		 * another mp to save it for potentially influencing returning
6689 		 * it in T_CONN_CONN.
6690 		 */
6691 		if (tcr->OPT_length != 0) { /* there are resulting options */
6692 			conn_opts_mp = copyb(mp);
6693 			if (!conn_opts_mp) {
6694 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6695 				    TSYSERR, ENOMEM);
6696 				return;
6697 			}
6698 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6699 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6700 			/*
6701 			 * Note:
6702 			 * These resulting option negotiation can include any
6703 			 * end-to-end negotiation options but there no such
6704 			 * thing (yet?) in our TCP/IP.
6705 			 */
6706 		}
6707 	}
6708 
6709 	/*
6710 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6711 	 * make sure that the template IP header in the tcp structure is an
6712 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6713 	 * need to this before we call tcp_bindi() so that the port lookup
6714 	 * code will look for ports in the correct port space (IPv4 and
6715 	 * IPv6 have separate port spaces).
6716 	 */
6717 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6718 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6719 		int err = 0;
6720 
6721 		err = tcp_header_init_ipv4(tcp);
6722 		if (err != 0) {
6723 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6724 			goto connect_failed;
6725 		}
6726 		if (tcp->tcp_lport != 0)
6727 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6728 	}
6729 
6730 	switch (tcp->tcp_state) {
6731 	case TCPS_IDLE:
6732 		/*
6733 		 * We support quick connect, refer to comments in
6734 		 * tcp_connect_*()
6735 		 */
6736 		/* FALLTHRU */
6737 	case TCPS_BOUND:
6738 	case TCPS_LISTEN:
6739 		if (tcp->tcp_family == AF_INET6) {
6740 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6741 				tcp_connect_ipv6(tcp, mp,
6742 				    &sin6->sin6_addr,
6743 				    sin6->sin6_port, sin6->sin6_flowinfo,
6744 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6745 				return;
6746 			}
6747 			/*
6748 			 * Destination adress is mapped IPv6 address.
6749 			 * Source bound address should be unspecified or
6750 			 * IPv6 mapped address as well.
6751 			 */
6752 			if (!IN6_IS_ADDR_UNSPECIFIED(
6753 			    &tcp->tcp_bound_source_v6) &&
6754 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6755 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6756 				    EADDRNOTAVAIL);
6757 				break;
6758 			}
6759 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6760 			dstport = sin6->sin6_port;
6761 			srcid = sin6->__sin6_src_id;
6762 		} else {
6763 			dstaddrp = &sin->sin_addr.s_addr;
6764 			dstport = sin->sin_port;
6765 			srcid = 0;
6766 		}
6767 
6768 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6769 		return;
6770 	default:
6771 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6772 		break;
6773 	}
6774 	/*
6775 	 * Note: Code below is the "failure" case
6776 	 */
6777 	/* return error ack and blow away saved option results if any */
6778 connect_failed:
6779 	if (mp != NULL)
6780 		putnext(tcp->tcp_rq, mp);
6781 	else {
6782 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6783 		    TSYSERR, ENOMEM);
6784 	}
6785 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6786 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6787 }
6788 
6789 /*
6790  * Handle connect to IPv4 destinations, including connections for AF_INET6
6791  * sockets connecting to IPv4 mapped IPv6 destinations.
6792  */
6793 static void
6794 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6795     uint_t srcid)
6796 {
6797 	tcph_t	*tcph;
6798 	mblk_t	*mp1;
6799 	ipaddr_t dstaddr = *dstaddrp;
6800 	int32_t	oldstate;
6801 	uint16_t lport;
6802 
6803 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6804 
6805 	/* Check for attempt to connect to INADDR_ANY */
6806 	if (dstaddr == INADDR_ANY)  {
6807 		/*
6808 		 * SunOS 4.x and 4.3 BSD allow an application
6809 		 * to connect a TCP socket to INADDR_ANY.
6810 		 * When they do this, the kernel picks the
6811 		 * address of one interface and uses it
6812 		 * instead.  The kernel usually ends up
6813 		 * picking the address of the loopback
6814 		 * interface.  This is an undocumented feature.
6815 		 * However, we provide the same thing here
6816 		 * in order to have source and binary
6817 		 * compatibility with SunOS 4.x.
6818 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6819 		 * generate the T_CONN_CON.
6820 		 */
6821 		dstaddr = htonl(INADDR_LOOPBACK);
6822 		*dstaddrp = dstaddr;
6823 	}
6824 
6825 	/* Handle __sin6_src_id if socket not bound to an IP address */
6826 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6827 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6828 		    tcp->tcp_connp->conn_zoneid);
6829 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6830 		    tcp->tcp_ipha->ipha_src);
6831 	}
6832 
6833 	/*
6834 	 * Don't let an endpoint connect to itself.  Note that
6835 	 * the test here does not catch the case where the
6836 	 * source IP addr was left unspecified by the user. In
6837 	 * this case, the source addr is set in tcp_adapt_ire()
6838 	 * using the reply to the T_BIND message that we send
6839 	 * down to IP here and the check is repeated in tcp_rput_other.
6840 	 */
6841 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6842 	    dstport == tcp->tcp_lport) {
6843 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6844 		goto failed;
6845 	}
6846 
6847 	tcp->tcp_ipha->ipha_dst = dstaddr;
6848 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6849 
6850 	/*
6851 	 * Massage a source route if any putting the first hop
6852 	 * in iph_dst. Compute a starting value for the checksum which
6853 	 * takes into account that the original iph_dst should be
6854 	 * included in the checksum but that ip will include the
6855 	 * first hop in the source route in the tcp checksum.
6856 	 */
6857 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6858 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6859 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6860 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6861 	if ((int)tcp->tcp_sum < 0)
6862 		tcp->tcp_sum--;
6863 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6864 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6865 	    (tcp->tcp_sum >> 16));
6866 	tcph = tcp->tcp_tcph;
6867 	*(uint16_t *)tcph->th_fport = dstport;
6868 	tcp->tcp_fport = dstport;
6869 
6870 	oldstate = tcp->tcp_state;
6871 	/*
6872 	 * At this point the remote destination address and remote port fields
6873 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6874 	 * have to see which state tcp was in so we can take apropriate action.
6875 	 */
6876 	if (oldstate == TCPS_IDLE) {
6877 		/*
6878 		 * We support a quick connect capability here, allowing
6879 		 * clients to transition directly from IDLE to SYN_SENT
6880 		 * tcp_bindi will pick an unused port, insert the connection
6881 		 * in the bind hash and transition to BOUND state.
6882 		 */
6883 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6884 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6885 		    B_FALSE, B_FALSE);
6886 		if (lport == 0) {
6887 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6888 			goto failed;
6889 		}
6890 	}
6891 	tcp->tcp_state = TCPS_SYN_SENT;
6892 
6893 	/*
6894 	 * TODO: allow data with connect requests
6895 	 * by unlinking M_DATA trailers here and
6896 	 * linking them in behind the T_OK_ACK mblk.
6897 	 * The tcp_rput() bind ack handler would then
6898 	 * feed them to tcp_wput_data() rather than call
6899 	 * tcp_timer().
6900 	 */
6901 	mp = mi_tpi_ok_ack_alloc(mp);
6902 	if (!mp) {
6903 		tcp->tcp_state = oldstate;
6904 		goto failed;
6905 	}
6906 	if (tcp->tcp_family == AF_INET) {
6907 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6908 		    sizeof (ipa_conn_t));
6909 	} else {
6910 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6911 		    sizeof (ipa6_conn_t));
6912 	}
6913 	if (mp1) {
6914 		/* Hang onto the T_OK_ACK for later. */
6915 		linkb(mp1, mp);
6916 		if (tcp->tcp_family == AF_INET)
6917 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6918 		else {
6919 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6920 			    &tcp->tcp_sticky_ipp);
6921 		}
6922 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6923 		tcp->tcp_active_open = 1;
6924 		/*
6925 		 * If the bind cannot complete immediately
6926 		 * IP will arrange to call tcp_rput_other
6927 		 * when the bind completes.
6928 		 */
6929 		if (mp1 != NULL)
6930 			tcp_rput_other(tcp, mp1);
6931 		return;
6932 	}
6933 	/* Error case */
6934 	tcp->tcp_state = oldstate;
6935 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6936 
6937 failed:
6938 	/* return error ack and blow away saved option results if any */
6939 	if (mp != NULL)
6940 		putnext(tcp->tcp_rq, mp);
6941 	else {
6942 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6943 		    TSYSERR, ENOMEM);
6944 	}
6945 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6946 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6947 
6948 }
6949 
6950 /*
6951  * Handle connect to IPv6 destinations.
6952  */
6953 static void
6954 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6955     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6956 {
6957 	tcph_t	*tcph;
6958 	mblk_t	*mp1;
6959 	ip6_rthdr_t *rth;
6960 	int32_t  oldstate;
6961 	uint16_t lport;
6962 
6963 	ASSERT(tcp->tcp_family == AF_INET6);
6964 
6965 	/*
6966 	 * If we're here, it means that the destination address is a native
6967 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6968 	 * reason why it might not be IPv6 is if the socket was bound to an
6969 	 * IPv4-mapped IPv6 address.
6970 	 */
6971 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6972 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6973 		goto failed;
6974 	}
6975 
6976 	/*
6977 	 * Interpret a zero destination to mean loopback.
6978 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6979 	 * generate the T_CONN_CON.
6980 	 */
6981 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6982 		*dstaddrp = ipv6_loopback;
6983 	}
6984 
6985 	/* Handle __sin6_src_id if socket not bound to an IP address */
6986 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6987 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6988 		    tcp->tcp_connp->conn_zoneid);
6989 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6990 	}
6991 
6992 	/*
6993 	 * Take care of the scope_id now and add ip6i_t
6994 	 * if ip6i_t is not already allocated through TCP
6995 	 * sticky options. At this point tcp_ip6h does not
6996 	 * have dst info, thus use dstaddrp.
6997 	 */
6998 	if (scope_id != 0 &&
6999 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
7000 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
7001 		ip6i_t  *ip6i;
7002 
7003 		ipp->ipp_ifindex = scope_id;
7004 		ip6i = (ip6i_t *)tcp->tcp_iphc;
7005 
7006 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
7007 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
7008 			/* Already allocated */
7009 			ip6i->ip6i_flags |= IP6I_IFINDEX;
7010 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
7011 			ipp->ipp_fields |= IPPF_SCOPE_ID;
7012 		} else {
7013 			int reterr;
7014 
7015 			ipp->ipp_fields |= IPPF_SCOPE_ID;
7016 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
7017 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
7018 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
7019 			if (reterr != 0)
7020 				goto failed;
7021 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
7022 		}
7023 	}
7024 
7025 	/*
7026 	 * Don't let an endpoint connect to itself.  Note that
7027 	 * the test here does not catch the case where the
7028 	 * source IP addr was left unspecified by the user. In
7029 	 * this case, the source addr is set in tcp_adapt_ire()
7030 	 * using the reply to the T_BIND message that we send
7031 	 * down to IP here and the check is repeated in tcp_rput_other.
7032 	 */
7033 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
7034 	    (dstport == tcp->tcp_lport)) {
7035 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
7036 		goto failed;
7037 	}
7038 
7039 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
7040 	tcp->tcp_remote_v6 = *dstaddrp;
7041 	tcp->tcp_ip6h->ip6_vcf =
7042 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
7043 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
7044 
7045 
7046 	/*
7047 	 * Massage a routing header (if present) putting the first hop
7048 	 * in ip6_dst. Compute a starting value for the checksum which
7049 	 * takes into account that the original ip6_dst should be
7050 	 * included in the checksum but that ip will include the
7051 	 * first hop in the source route in the tcp checksum.
7052 	 */
7053 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
7054 	if (rth != NULL) {
7055 
7056 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
7057 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
7058 		    (tcp->tcp_sum >> 16));
7059 	} else {
7060 		tcp->tcp_sum = 0;
7061 	}
7062 
7063 	tcph = tcp->tcp_tcph;
7064 	*(uint16_t *)tcph->th_fport = dstport;
7065 	tcp->tcp_fport = dstport;
7066 
7067 	oldstate = tcp->tcp_state;
7068 	/*
7069 	 * At this point the remote destination address and remote port fields
7070 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
7071 	 * have to see which state tcp was in so we can take apropriate action.
7072 	 */
7073 	if (oldstate == TCPS_IDLE) {
7074 		/*
7075 		 * We support a quick connect capability here, allowing
7076 		 * clients to transition directly from IDLE to SYN_SENT
7077 		 * tcp_bindi will pick an unused port, insert the connection
7078 		 * in the bind hash and transition to BOUND state.
7079 		 */
7080 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
7081 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
7082 		    B_FALSE, B_FALSE);
7083 		if (lport == 0) {
7084 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
7085 			goto failed;
7086 		}
7087 	}
7088 	tcp->tcp_state = TCPS_SYN_SENT;
7089 	/*
7090 	 * TODO: allow data with connect requests
7091 	 * by unlinking M_DATA trailers here and
7092 	 * linking them in behind the T_OK_ACK mblk.
7093 	 * The tcp_rput() bind ack handler would then
7094 	 * feed them to tcp_wput_data() rather than call
7095 	 * tcp_timer().
7096 	 */
7097 	mp = mi_tpi_ok_ack_alloc(mp);
7098 	if (!mp) {
7099 		tcp->tcp_state = oldstate;
7100 		goto failed;
7101 	}
7102 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
7103 	if (mp1) {
7104 		/* Hang onto the T_OK_ACK for later. */
7105 		linkb(mp1, mp);
7106 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
7107 		    &tcp->tcp_sticky_ipp);
7108 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
7109 		tcp->tcp_active_open = 1;
7110 		/* ip_bind_v6() may return ACK or ERROR */
7111 		if (mp1 != NULL)
7112 			tcp_rput_other(tcp, mp1);
7113 		return;
7114 	}
7115 	/* Error case */
7116 	tcp->tcp_state = oldstate;
7117 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
7118 
7119 failed:
7120 	/* return error ack and blow away saved option results if any */
7121 	if (mp != NULL)
7122 		putnext(tcp->tcp_rq, mp);
7123 	else {
7124 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
7125 		    TSYSERR, ENOMEM);
7126 	}
7127 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
7128 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
7129 }
7130 
7131 /*
7132  * We need a stream q for detached closing tcp connections
7133  * to use.  Our client hereby indicates that this q is the
7134  * one to use.
7135  */
7136 static void
7137 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
7138 {
7139 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
7140 	queue_t	*q = tcp->tcp_wq;
7141 
7142 	mp->b_datap->db_type = M_IOCACK;
7143 	iocp->ioc_count = 0;
7144 	mutex_enter(&tcp_g_q_lock);
7145 	if (tcp_g_q != NULL) {
7146 		mutex_exit(&tcp_g_q_lock);
7147 		iocp->ioc_error = EALREADY;
7148 	} else {
7149 		mblk_t *mp1;
7150 
7151 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
7152 		if (mp1 == NULL) {
7153 			mutex_exit(&tcp_g_q_lock);
7154 			iocp->ioc_error = ENOMEM;
7155 		} else {
7156 			tcp_g_q = tcp->tcp_rq;
7157 			mutex_exit(&tcp_g_q_lock);
7158 			iocp->ioc_error = 0;
7159 			iocp->ioc_rval = 0;
7160 			/*
7161 			 * We are passing tcp_sticky_ipp as NULL
7162 			 * as it is not useful for tcp_default queue
7163 			 */
7164 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
7165 			if (mp1 != NULL)
7166 				tcp_rput_other(tcp, mp1);
7167 		}
7168 	}
7169 	qreply(q, mp);
7170 }
7171 
7172 /*
7173  * Our client hereby directs us to reject the connection request
7174  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
7175  * of sending the appropriate RST, not an ICMP error.
7176  */
7177 static void
7178 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
7179 {
7180 	tcp_t	*ltcp = NULL;
7181 	t_scalar_t seqnum;
7182 	conn_t	*connp;
7183 
7184 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
7185 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
7186 		tcp_err_ack(tcp, mp, TPROTO, 0);
7187 		return;
7188 	}
7189 
7190 	/*
7191 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
7192 	 * when the stream is in BOUND state. Do not send a reset,
7193 	 * since the destination IP address is not valid, and it can
7194 	 * be the initialized value of all zeros (broadcast address).
7195 	 *
7196 	 * If TCP has sent down a bind request to IP and has not
7197 	 * received the reply, reject the request.  Otherwise, TCP
7198 	 * will be confused.
7199 	 */
7200 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
7201 		if (tcp->tcp_debug) {
7202 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
7203 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
7204 		}
7205 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
7206 		return;
7207 	}
7208 
7209 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
7210 
7211 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
7212 
7213 		/*
7214 		 * According to TPI, for non-listeners, ignore seqnum
7215 		 * and disconnect.
7216 		 * Following interpretation of -1 seqnum is historical
7217 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
7218 		 * a valid seqnum should not be -1).
7219 		 *
7220 		 *	-1 means disconnect everything
7221 		 *	regardless even on a listener.
7222 		 */
7223 
7224 		int old_state = tcp->tcp_state;
7225 
7226 		/*
7227 		 * The connection can't be on the tcp_time_wait_head list
7228 		 * since it is not detached.
7229 		 */
7230 		ASSERT(tcp->tcp_time_wait_next == NULL);
7231 		ASSERT(tcp->tcp_time_wait_prev == NULL);
7232 		ASSERT(tcp->tcp_time_wait_expire == 0);
7233 		ltcp = NULL;
7234 		/*
7235 		 * If it used to be a listener, check to make sure no one else
7236 		 * has taken the port before switching back to LISTEN state.
7237 		 */
7238 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7239 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
7240 			    tcp->tcp_ipha->ipha_src,
7241 			    tcp->tcp_connp->conn_zoneid);
7242 			if (connp != NULL)
7243 				ltcp = connp->conn_tcp;
7244 		} else {
7245 			/* Allow tcp_bound_if listeners? */
7246 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
7247 			    &tcp->tcp_ip6h->ip6_src, 0,
7248 			    tcp->tcp_connp->conn_zoneid);
7249 			if (connp != NULL)
7250 				ltcp = connp->conn_tcp;
7251 		}
7252 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
7253 			tcp->tcp_state = TCPS_LISTEN;
7254 		} else if (old_state > TCPS_BOUND) {
7255 			tcp->tcp_conn_req_max = 0;
7256 			tcp->tcp_state = TCPS_BOUND;
7257 		}
7258 		if (ltcp != NULL)
7259 			CONN_DEC_REF(ltcp->tcp_connp);
7260 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
7261 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
7262 		} else if (old_state == TCPS_ESTABLISHED ||
7263 		    old_state == TCPS_CLOSE_WAIT) {
7264 			BUMP_MIB(&tcp_mib, tcpEstabResets);
7265 		}
7266 
7267 		if (tcp->tcp_fused)
7268 			tcp_unfuse(tcp);
7269 
7270 		mutex_enter(&tcp->tcp_eager_lock);
7271 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
7272 		    (tcp->tcp_conn_req_cnt_q != 0)) {
7273 			tcp_eager_cleanup(tcp, 0);
7274 		}
7275 		mutex_exit(&tcp->tcp_eager_lock);
7276 
7277 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
7278 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
7279 
7280 		tcp_reinit(tcp);
7281 
7282 		if (old_state >= TCPS_ESTABLISHED) {
7283 			/* Send M_FLUSH according to TPI */
7284 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7285 		}
7286 		mp = mi_tpi_ok_ack_alloc(mp);
7287 		if (mp)
7288 			putnext(tcp->tcp_rq, mp);
7289 		return;
7290 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7291 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7292 		return;
7293 	}
7294 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7295 		/* Send M_FLUSH according to TPI */
7296 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7297 	}
7298 	mp = mi_tpi_ok_ack_alloc(mp);
7299 	if (mp)
7300 		putnext(tcp->tcp_rq, mp);
7301 }
7302 
7303 /*
7304  * Diagnostic routine used to return a string associated with the tcp state.
7305  * Note that if the caller does not supply a buffer, it will use an internal
7306  * static string.  This means that if multiple threads call this function at
7307  * the same time, output can be corrupted...  Note also that this function
7308  * does not check the size of the supplied buffer.  The caller has to make
7309  * sure that it is big enough.
7310  */
7311 static char *
7312 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7313 {
7314 	char		buf1[30];
7315 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7316 	char		*buf;
7317 	char		*cp;
7318 	in6_addr_t	local, remote;
7319 	char		local_addrbuf[INET6_ADDRSTRLEN];
7320 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7321 
7322 	if (sup_buf != NULL)
7323 		buf = sup_buf;
7324 	else
7325 		buf = priv_buf;
7326 
7327 	if (tcp == NULL)
7328 		return ("NULL_TCP");
7329 	switch (tcp->tcp_state) {
7330 	case TCPS_CLOSED:
7331 		cp = "TCP_CLOSED";
7332 		break;
7333 	case TCPS_IDLE:
7334 		cp = "TCP_IDLE";
7335 		break;
7336 	case TCPS_BOUND:
7337 		cp = "TCP_BOUND";
7338 		break;
7339 	case TCPS_LISTEN:
7340 		cp = "TCP_LISTEN";
7341 		break;
7342 	case TCPS_SYN_SENT:
7343 		cp = "TCP_SYN_SENT";
7344 		break;
7345 	case TCPS_SYN_RCVD:
7346 		cp = "TCP_SYN_RCVD";
7347 		break;
7348 	case TCPS_ESTABLISHED:
7349 		cp = "TCP_ESTABLISHED";
7350 		break;
7351 	case TCPS_CLOSE_WAIT:
7352 		cp = "TCP_CLOSE_WAIT";
7353 		break;
7354 	case TCPS_FIN_WAIT_1:
7355 		cp = "TCP_FIN_WAIT_1";
7356 		break;
7357 	case TCPS_CLOSING:
7358 		cp = "TCP_CLOSING";
7359 		break;
7360 	case TCPS_LAST_ACK:
7361 		cp = "TCP_LAST_ACK";
7362 		break;
7363 	case TCPS_FIN_WAIT_2:
7364 		cp = "TCP_FIN_WAIT_2";
7365 		break;
7366 	case TCPS_TIME_WAIT:
7367 		cp = "TCP_TIME_WAIT";
7368 		break;
7369 	default:
7370 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7371 		cp = buf1;
7372 		break;
7373 	}
7374 	switch (format) {
7375 	case DISP_ADDR_AND_PORT:
7376 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7377 			/*
7378 			 * Note that we use the remote address in the tcp_b
7379 			 * structure.  This means that it will print out
7380 			 * the real destination address, not the next hop's
7381 			 * address if source routing is used.
7382 			 */
7383 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7384 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7385 
7386 		} else {
7387 			local = tcp->tcp_ip_src_v6;
7388 			remote = tcp->tcp_remote_v6;
7389 		}
7390 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7391 		    sizeof (local_addrbuf));
7392 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7393 		    sizeof (remote_addrbuf));
7394 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7395 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7396 		    ntohs(tcp->tcp_fport), cp);
7397 		break;
7398 	case DISP_PORT_ONLY:
7399 	default:
7400 		(void) mi_sprintf(buf, "[%u, %u] %s",
7401 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7402 		break;
7403 	}
7404 
7405 	return (buf);
7406 }
7407 
7408 /*
7409  * Called via squeue to get on to eager's perimeter to send a
7410  * TH_RST. The listener wants the eager to disappear either
7411  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
7412  * being called.
7413  */
7414 /* ARGSUSED */
7415 void
7416 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7417 {
7418 	conn_t	*econnp = (conn_t *)arg;
7419 	tcp_t	*eager = econnp->conn_tcp;
7420 	tcp_t	*listener = eager->tcp_listener;
7421 
7422 	/*
7423 	 * We could be called because listener is closing. Since
7424 	 * the eager is using listener's queue's, its not safe.
7425 	 * Better use the default queue just to send the TH_RST
7426 	 * out.
7427 	 */
7428 	eager->tcp_rq = tcp_g_q;
7429 	eager->tcp_wq = WR(tcp_g_q);
7430 
7431 	if (eager->tcp_state > TCPS_LISTEN) {
7432 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7433 		    eager, eager->tcp_snxt, 0, TH_RST);
7434 	}
7435 
7436 	/* We are here because listener wants this eager gone */
7437 	if (listener != NULL) {
7438 		mutex_enter(&listener->tcp_eager_lock);
7439 		tcp_eager_unlink(eager);
7440 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
7441 			/*
7442 			 * The eager has sent a conn_ind up to the
7443 			 * listener but listener decides to close
7444 			 * instead. We need to drop the extra ref
7445 			 * placed on eager in tcp_rput_data() before
7446 			 * sending the conn_ind to listener.
7447 			 */
7448 			CONN_DEC_REF(econnp);
7449 		}
7450 		mutex_exit(&listener->tcp_eager_lock);
7451 		CONN_DEC_REF(listener->tcp_connp);
7452 	}
7453 
7454 	if (eager->tcp_state > TCPS_BOUND)
7455 		tcp_close_detached(eager);
7456 }
7457 
7458 /*
7459  * Reset any eager connection hanging off this listener marked
7460  * with 'seqnum' and then reclaim it's resources.
7461  */
7462 static boolean_t
7463 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7464 {
7465 	tcp_t	*eager;
7466 	mblk_t 	*mp;
7467 
7468 	TCP_STAT(tcp_eager_blowoff_calls);
7469 	eager = listener;
7470 	mutex_enter(&listener->tcp_eager_lock);
7471 	do {
7472 		eager = eager->tcp_eager_next_q;
7473 		if (eager == NULL) {
7474 			mutex_exit(&listener->tcp_eager_lock);
7475 			return (B_FALSE);
7476 		}
7477 	} while (eager->tcp_conn_req_seqnum != seqnum);
7478 	CONN_INC_REF(eager->tcp_connp);
7479 	mutex_exit(&listener->tcp_eager_lock);
7480 	mp = &eager->tcp_closemp;
7481 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7482 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7483 	return (B_TRUE);
7484 }
7485 
7486 /*
7487  * Reset any eager connection hanging off this listener
7488  * and then reclaim it's resources.
7489  */
7490 static void
7491 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7492 {
7493 	tcp_t	*eager;
7494 	mblk_t	*mp;
7495 
7496 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7497 
7498 	if (!q0_only) {
7499 		/* First cleanup q */
7500 		TCP_STAT(tcp_eager_blowoff_q);
7501 		eager = listener->tcp_eager_next_q;
7502 		while (eager != NULL) {
7503 			CONN_INC_REF(eager->tcp_connp);
7504 			mp = &eager->tcp_closemp;
7505 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7506 			    tcp_eager_kill, eager->tcp_connp,
7507 			    SQTAG_TCP_EAGER_CLEANUP);
7508 			eager = eager->tcp_eager_next_q;
7509 		}
7510 	}
7511 	/* Then cleanup q0 */
7512 	TCP_STAT(tcp_eager_blowoff_q0);
7513 	eager = listener->tcp_eager_next_q0;
7514 	while (eager != listener) {
7515 		CONN_INC_REF(eager->tcp_connp);
7516 		mp = &eager->tcp_closemp;
7517 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
7518 		    tcp_eager_kill, eager->tcp_connp,
7519 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
7520 		eager = eager->tcp_eager_next_q0;
7521 	}
7522 }
7523 
7524 /*
7525  * If we are an eager connection hanging off a listener that hasn't
7526  * formally accepted the connection yet, get off his list and blow off
7527  * any data that we have accumulated.
7528  */
7529 static void
7530 tcp_eager_unlink(tcp_t *tcp)
7531 {
7532 	tcp_t	*listener = tcp->tcp_listener;
7533 
7534 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7535 	ASSERT(listener != NULL);
7536 	if (tcp->tcp_eager_next_q0 != NULL) {
7537 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7538 
7539 		/* Remove the eager tcp from q0 */
7540 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7541 		    tcp->tcp_eager_prev_q0;
7542 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7543 		    tcp->tcp_eager_next_q0;
7544 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7545 		listener->tcp_conn_req_cnt_q0--;
7546 
7547 		tcp->tcp_eager_next_q0 = NULL;
7548 		tcp->tcp_eager_prev_q0 = NULL;
7549 
7550 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7551 			/* we have timed out before */
7552 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7553 			listener->tcp_syn_rcvd_timeout--;
7554 		}
7555 	} else {
7556 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7557 		tcp_t	*prev = NULL;
7558 
7559 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7560 			if (tcpp[0] == tcp) {
7561 				if (listener->tcp_eager_last_q == tcp) {
7562 					/*
7563 					 * If we are unlinking the last
7564 					 * element on the list, adjust
7565 					 * tail pointer. Set tail pointer
7566 					 * to nil when list is empty.
7567 					 */
7568 					ASSERT(tcp->tcp_eager_next_q == NULL);
7569 					if (listener->tcp_eager_last_q ==
7570 					    listener->tcp_eager_next_q) {
7571 						listener->tcp_eager_last_q =
7572 						NULL;
7573 					} else {
7574 						/*
7575 						 * We won't get here if there
7576 						 * is only one eager in the
7577 						 * list.
7578 						 */
7579 						ASSERT(prev != NULL);
7580 						listener->tcp_eager_last_q =
7581 						    prev;
7582 					}
7583 				}
7584 				tcpp[0] = tcp->tcp_eager_next_q;
7585 				tcp->tcp_eager_next_q = NULL;
7586 				tcp->tcp_eager_last_q = NULL;
7587 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7588 				listener->tcp_conn_req_cnt_q--;
7589 				break;
7590 			}
7591 			prev = tcpp[0];
7592 		}
7593 	}
7594 	tcp->tcp_listener = NULL;
7595 }
7596 
7597 /* Shorthand to generate and send TPI error acks to our client */
7598 static void
7599 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7600 {
7601 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7602 		putnext(tcp->tcp_rq, mp);
7603 }
7604 
7605 /* Shorthand to generate and send TPI error acks to our client */
7606 static void
7607 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7608     int t_error, int sys_error)
7609 {
7610 	struct T_error_ack	*teackp;
7611 
7612 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7613 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7614 		teackp = (struct T_error_ack *)mp->b_rptr;
7615 		teackp->ERROR_prim = primitive;
7616 		teackp->TLI_error = t_error;
7617 		teackp->UNIX_error = sys_error;
7618 		putnext(tcp->tcp_rq, mp);
7619 	}
7620 }
7621 
7622 /*
7623  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7624  * but instead the code relies on:
7625  * - the fact that the address of the array and its size never changes
7626  * - the atomic assignment of the elements of the array
7627  */
7628 /* ARGSUSED */
7629 static int
7630 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7631 {
7632 	int i;
7633 
7634 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7635 		if (tcp_g_epriv_ports[i] != 0)
7636 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7637 	}
7638 	return (0);
7639 }
7640 
7641 /*
7642  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7643  * threads from changing it at the same time.
7644  */
7645 /* ARGSUSED */
7646 static int
7647 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7648     cred_t *cr)
7649 {
7650 	long	new_value;
7651 	int	i;
7652 
7653 	/*
7654 	 * Fail the request if the new value does not lie within the
7655 	 * port number limits.
7656 	 */
7657 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7658 	    new_value <= 0 || new_value >= 65536) {
7659 		return (EINVAL);
7660 	}
7661 
7662 	mutex_enter(&tcp_epriv_port_lock);
7663 	/* Check if the value is already in the list */
7664 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7665 		if (new_value == tcp_g_epriv_ports[i]) {
7666 			mutex_exit(&tcp_epriv_port_lock);
7667 			return (EEXIST);
7668 		}
7669 	}
7670 	/* Find an empty slot */
7671 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7672 		if (tcp_g_epriv_ports[i] == 0)
7673 			break;
7674 	}
7675 	if (i == tcp_g_num_epriv_ports) {
7676 		mutex_exit(&tcp_epriv_port_lock);
7677 		return (EOVERFLOW);
7678 	}
7679 	/* Set the new value */
7680 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7681 	mutex_exit(&tcp_epriv_port_lock);
7682 	return (0);
7683 }
7684 
7685 /*
7686  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7687  * threads from changing it at the same time.
7688  */
7689 /* ARGSUSED */
7690 static int
7691 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7692     cred_t *cr)
7693 {
7694 	long	new_value;
7695 	int	i;
7696 
7697 	/*
7698 	 * Fail the request if the new value does not lie within the
7699 	 * port number limits.
7700 	 */
7701 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7702 	    new_value >= 65536) {
7703 		return (EINVAL);
7704 	}
7705 
7706 	mutex_enter(&tcp_epriv_port_lock);
7707 	/* Check that the value is already in the list */
7708 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7709 		if (tcp_g_epriv_ports[i] == new_value)
7710 			break;
7711 	}
7712 	if (i == tcp_g_num_epriv_ports) {
7713 		mutex_exit(&tcp_epriv_port_lock);
7714 		return (ESRCH);
7715 	}
7716 	/* Clear the value */
7717 	tcp_g_epriv_ports[i] = 0;
7718 	mutex_exit(&tcp_epriv_port_lock);
7719 	return (0);
7720 }
7721 
7722 /* Return the TPI/TLI equivalent of our current tcp_state */
7723 static int
7724 tcp_tpistate(tcp_t *tcp)
7725 {
7726 	switch (tcp->tcp_state) {
7727 	case TCPS_IDLE:
7728 		return (TS_UNBND);
7729 	case TCPS_LISTEN:
7730 		/*
7731 		 * Return whether there are outstanding T_CONN_IND waiting
7732 		 * for the matching T_CONN_RES. Therefore don't count q0.
7733 		 */
7734 		if (tcp->tcp_conn_req_cnt_q > 0)
7735 			return (TS_WRES_CIND);
7736 		else
7737 			return (TS_IDLE);
7738 	case TCPS_BOUND:
7739 		return (TS_IDLE);
7740 	case TCPS_SYN_SENT:
7741 		return (TS_WCON_CREQ);
7742 	case TCPS_SYN_RCVD:
7743 		/*
7744 		 * Note: assumption: this has to the active open SYN_RCVD.
7745 		 * The passive instance is detached in SYN_RCVD stage of
7746 		 * incoming connection processing so we cannot get request
7747 		 * for T_info_ack on it.
7748 		 */
7749 		return (TS_WACK_CRES);
7750 	case TCPS_ESTABLISHED:
7751 		return (TS_DATA_XFER);
7752 	case TCPS_CLOSE_WAIT:
7753 		return (TS_WREQ_ORDREL);
7754 	case TCPS_FIN_WAIT_1:
7755 		return (TS_WIND_ORDREL);
7756 	case TCPS_FIN_WAIT_2:
7757 		return (TS_WIND_ORDREL);
7758 
7759 	case TCPS_CLOSING:
7760 	case TCPS_LAST_ACK:
7761 	case TCPS_TIME_WAIT:
7762 	case TCPS_CLOSED:
7763 		/*
7764 		 * Following TS_WACK_DREQ7 is a rendition of "not
7765 		 * yet TS_IDLE" TPI state. There is no best match to any
7766 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7767 		 * choose a value chosen that will map to TLI/XTI level
7768 		 * state of TSTATECHNG (state is process of changing) which
7769 		 * captures what this dummy state represents.
7770 		 */
7771 		return (TS_WACK_DREQ7);
7772 	default:
7773 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7774 		    tcp->tcp_state, tcp_display(tcp, NULL,
7775 		    DISP_PORT_ONLY));
7776 		return (TS_UNBND);
7777 	}
7778 }
7779 
7780 static void
7781 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7782 {
7783 	if (tcp->tcp_family == AF_INET6)
7784 		*tia = tcp_g_t_info_ack_v6;
7785 	else
7786 		*tia = tcp_g_t_info_ack;
7787 	tia->CURRENT_state = tcp_tpistate(tcp);
7788 	tia->OPT_size = tcp_max_optsize;
7789 	if (tcp->tcp_mss == 0) {
7790 		/* Not yet set - tcp_open does not set mss */
7791 		if (tcp->tcp_ipversion == IPV4_VERSION)
7792 			tia->TIDU_size = tcp_mss_def_ipv4;
7793 		else
7794 			tia->TIDU_size = tcp_mss_def_ipv6;
7795 	} else {
7796 		tia->TIDU_size = tcp->tcp_mss;
7797 	}
7798 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7799 }
7800 
7801 /*
7802  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7803  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7804  * tcp_g_t_info_ack.  The current state of the stream is copied from
7805  * tcp_state.
7806  */
7807 static void
7808 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7809 {
7810 	t_uscalar_t		cap_bits1;
7811 	struct T_capability_ack	*tcap;
7812 
7813 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7814 		freemsg(mp);
7815 		return;
7816 	}
7817 
7818 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7819 
7820 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7821 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7822 	if (mp == NULL)
7823 		return;
7824 
7825 	tcap = (struct T_capability_ack *)mp->b_rptr;
7826 	tcap->CAP_bits1 = 0;
7827 
7828 	if (cap_bits1 & TC1_INFO) {
7829 		tcp_copy_info(&tcap->INFO_ack, tcp);
7830 		tcap->CAP_bits1 |= TC1_INFO;
7831 	}
7832 
7833 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7834 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7835 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7836 	}
7837 
7838 	putnext(tcp->tcp_rq, mp);
7839 }
7840 
7841 /*
7842  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7843  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7844  * The current state of the stream is copied from tcp_state.
7845  */
7846 static void
7847 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7848 {
7849 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7850 	    T_INFO_ACK);
7851 	if (!mp) {
7852 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7853 		return;
7854 	}
7855 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7856 	putnext(tcp->tcp_rq, mp);
7857 }
7858 
7859 /* Respond to the TPI addr request */
7860 static void
7861 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7862 {
7863 	sin_t	*sin;
7864 	mblk_t	*ackmp;
7865 	struct T_addr_ack *taa;
7866 
7867 	/* Make it large enough for worst case */
7868 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7869 	    2 * sizeof (sin6_t), 1);
7870 	if (ackmp == NULL) {
7871 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7872 		return;
7873 	}
7874 
7875 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7876 		tcp_addr_req_ipv6(tcp, ackmp);
7877 		return;
7878 	}
7879 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7880 
7881 	bzero(taa, sizeof (struct T_addr_ack));
7882 	ackmp->b_wptr = (uchar_t *)&taa[1];
7883 
7884 	taa->PRIM_type = T_ADDR_ACK;
7885 	ackmp->b_datap->db_type = M_PCPROTO;
7886 
7887 	/*
7888 	 * Note: Following code assumes 32 bit alignment of basic
7889 	 * data structures like sin_t and struct T_addr_ack.
7890 	 */
7891 	if (tcp->tcp_state >= TCPS_BOUND) {
7892 		/*
7893 		 * Fill in local address
7894 		 */
7895 		taa->LOCADDR_length = sizeof (sin_t);
7896 		taa->LOCADDR_offset = sizeof (*taa);
7897 
7898 		sin = (sin_t *)&taa[1];
7899 
7900 		/* Fill zeroes and then intialize non-zero fields */
7901 		*sin = sin_null;
7902 
7903 		sin->sin_family = AF_INET;
7904 
7905 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7906 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7907 
7908 		ackmp->b_wptr = (uchar_t *)&sin[1];
7909 
7910 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7911 			/*
7912 			 * Fill in Remote address
7913 			 */
7914 			taa->REMADDR_length = sizeof (sin_t);
7915 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7916 						taa->LOCADDR_length);
7917 
7918 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7919 			*sin = sin_null;
7920 			sin->sin_family = AF_INET;
7921 			sin->sin_addr.s_addr = tcp->tcp_remote;
7922 			sin->sin_port = tcp->tcp_fport;
7923 
7924 			ackmp->b_wptr = (uchar_t *)&sin[1];
7925 		}
7926 	}
7927 	putnext(tcp->tcp_rq, ackmp);
7928 }
7929 
7930 /* Assumes that tcp_addr_req gets enough space and alignment */
7931 static void
7932 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7933 {
7934 	sin6_t	*sin6;
7935 	struct T_addr_ack *taa;
7936 
7937 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7938 	ASSERT(OK_32PTR(ackmp->b_rptr));
7939 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7940 	    2 * sizeof (sin6_t));
7941 
7942 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7943 
7944 	bzero(taa, sizeof (struct T_addr_ack));
7945 	ackmp->b_wptr = (uchar_t *)&taa[1];
7946 
7947 	taa->PRIM_type = T_ADDR_ACK;
7948 	ackmp->b_datap->db_type = M_PCPROTO;
7949 
7950 	/*
7951 	 * Note: Following code assumes 32 bit alignment of basic
7952 	 * data structures like sin6_t and struct T_addr_ack.
7953 	 */
7954 	if (tcp->tcp_state >= TCPS_BOUND) {
7955 		/*
7956 		 * Fill in local address
7957 		 */
7958 		taa->LOCADDR_length = sizeof (sin6_t);
7959 		taa->LOCADDR_offset = sizeof (*taa);
7960 
7961 		sin6 = (sin6_t *)&taa[1];
7962 		*sin6 = sin6_null;
7963 
7964 		sin6->sin6_family = AF_INET6;
7965 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7966 		sin6->sin6_port = tcp->tcp_lport;
7967 
7968 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7969 
7970 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7971 			/*
7972 			 * Fill in Remote address
7973 			 */
7974 			taa->REMADDR_length = sizeof (sin6_t);
7975 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7976 						taa->LOCADDR_length);
7977 
7978 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7979 			*sin6 = sin6_null;
7980 			sin6->sin6_family = AF_INET6;
7981 			sin6->sin6_flowinfo =
7982 			    tcp->tcp_ip6h->ip6_vcf &
7983 			    ~IPV6_VERS_AND_FLOW_MASK;
7984 			sin6->sin6_addr = tcp->tcp_remote_v6;
7985 			sin6->sin6_port = tcp->tcp_fport;
7986 
7987 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7988 		}
7989 	}
7990 	putnext(tcp->tcp_rq, ackmp);
7991 }
7992 
7993 /*
7994  * Handle reinitialization of a tcp structure.
7995  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7996  */
7997 static void
7998 tcp_reinit(tcp_t *tcp)
7999 {
8000 	mblk_t	*mp;
8001 	int 	err;
8002 
8003 	TCP_STAT(tcp_reinit_calls);
8004 
8005 	/* tcp_reinit should never be called for detached tcp_t's */
8006 	ASSERT(tcp->tcp_listener == NULL);
8007 	ASSERT((tcp->tcp_family == AF_INET &&
8008 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8009 	    (tcp->tcp_family == AF_INET6 &&
8010 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8011 	    tcp->tcp_ipversion == IPV6_VERSION)));
8012 
8013 	/* Cancel outstanding timers */
8014 	tcp_timers_stop(tcp);
8015 
8016 	if (tcp->tcp_flow_stopped) {
8017 		tcp_clrqfull(tcp);
8018 	}
8019 	/*
8020 	 * Reset everything in the state vector, after updating global
8021 	 * MIB data from instance counters.
8022 	 */
8023 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
8024 	tcp->tcp_ibsegs = 0;
8025 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
8026 	tcp->tcp_obsegs = 0;
8027 
8028 	tcp_close_mpp(&tcp->tcp_xmit_head);
8029 	if (tcp->tcp_snd_zcopy_aware)
8030 		tcp_zcopy_notify(tcp);
8031 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
8032 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
8033 	tcp_close_mpp(&tcp->tcp_reass_head);
8034 	tcp->tcp_reass_tail = NULL;
8035 	if (tcp->tcp_rcv_list != NULL) {
8036 		/* Free b_next chain */
8037 		tcp_close_mpp(&tcp->tcp_rcv_list);
8038 		tcp->tcp_rcv_last_head = NULL;
8039 		tcp->tcp_rcv_last_tail = NULL;
8040 		tcp->tcp_rcv_cnt = 0;
8041 	}
8042 	tcp->tcp_rcv_last_tail = NULL;
8043 
8044 	if ((mp = tcp->tcp_urp_mp) != NULL) {
8045 		freemsg(mp);
8046 		tcp->tcp_urp_mp = NULL;
8047 	}
8048 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
8049 		freemsg(mp);
8050 		tcp->tcp_urp_mark_mp = NULL;
8051 	}
8052 	if (tcp->tcp_fused_sigurg_mp != NULL) {
8053 		freeb(tcp->tcp_fused_sigurg_mp);
8054 		tcp->tcp_fused_sigurg_mp = NULL;
8055 	}
8056 
8057 	/*
8058 	 * Following is a union with two members which are
8059 	 * identical types and size so the following cleanup
8060 	 * is enough.
8061 	 */
8062 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
8063 
8064 	CL_INET_DISCONNECT(tcp);
8065 
8066 	/*
8067 	 * The connection can't be on the tcp_time_wait_head list
8068 	 * since it is not detached.
8069 	 */
8070 	ASSERT(tcp->tcp_time_wait_next == NULL);
8071 	ASSERT(tcp->tcp_time_wait_prev == NULL);
8072 	ASSERT(tcp->tcp_time_wait_expire == 0);
8073 
8074 	/*
8075 	 * Reset/preserve other values
8076 	 */
8077 	tcp_reinit_values(tcp);
8078 	ipcl_hash_remove(tcp->tcp_connp);
8079 	conn_delete_ire(tcp->tcp_connp, NULL);
8080 
8081 	if (tcp->tcp_conn_req_max != 0) {
8082 		/*
8083 		 * This is the case when a TLI program uses the same
8084 		 * transport end point to accept a connection.  This
8085 		 * makes the TCP both a listener and acceptor.  When
8086 		 * this connection is closed, we need to set the state
8087 		 * back to TCPS_LISTEN.  Make sure that the eager list
8088 		 * is reinitialized.
8089 		 *
8090 		 * Note that this stream is still bound to the four
8091 		 * tuples of the previous connection in IP.  If a new
8092 		 * SYN with different foreign address comes in, IP will
8093 		 * not find it and will send it to the global queue.  In
8094 		 * the global queue, TCP will do a tcp_lookup_listener()
8095 		 * to find this stream.  This works because this stream
8096 		 * is only removed from connected hash.
8097 		 *
8098 		 */
8099 		tcp->tcp_state = TCPS_LISTEN;
8100 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
8101 		tcp->tcp_connp->conn_recv = tcp_conn_request;
8102 		if (tcp->tcp_family == AF_INET6) {
8103 			ASSERT(tcp->tcp_connp->conn_af_isv6);
8104 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
8105 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
8106 		} else {
8107 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
8108 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
8109 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
8110 		}
8111 	} else {
8112 		tcp->tcp_state = TCPS_BOUND;
8113 	}
8114 
8115 	/*
8116 	 * Initialize to default values
8117 	 * Can't fail since enough header template space already allocated
8118 	 * at open().
8119 	 */
8120 	err = tcp_init_values(tcp);
8121 	ASSERT(err == 0);
8122 	/* Restore state in tcp_tcph */
8123 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
8124 	if (tcp->tcp_ipversion == IPV4_VERSION)
8125 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
8126 	else
8127 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
8128 	/*
8129 	 * Copy of the src addr. in tcp_t is needed in tcp_t
8130 	 * since the lookup funcs can only lookup on tcp_t
8131 	 */
8132 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
8133 
8134 	ASSERT(tcp->tcp_ptpbhn != NULL);
8135 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
8136 	tcp->tcp_rwnd = tcp_recv_hiwat;
8137 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
8138 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
8139 }
8140 
8141 /*
8142  * Force values to zero that need be zero.
8143  * Do not touch values asociated with the BOUND or LISTEN state
8144  * since the connection will end up in that state after the reinit.
8145  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
8146  * structure!
8147  */
8148 static void
8149 tcp_reinit_values(tcp)
8150 	tcp_t *tcp;
8151 {
8152 #ifndef	lint
8153 #define	DONTCARE(x)
8154 #define	PRESERVE(x)
8155 #else
8156 #define	DONTCARE(x)	((x) = (x))
8157 #define	PRESERVE(x)	((x) = (x))
8158 #endif	/* lint */
8159 
8160 	PRESERVE(tcp->tcp_bind_hash);
8161 	PRESERVE(tcp->tcp_ptpbhn);
8162 	PRESERVE(tcp->tcp_acceptor_hash);
8163 	PRESERVE(tcp->tcp_ptpahn);
8164 
8165 	/* Should be ASSERT NULL on these with new code! */
8166 	ASSERT(tcp->tcp_time_wait_next == NULL);
8167 	ASSERT(tcp->tcp_time_wait_prev == NULL);
8168 	ASSERT(tcp->tcp_time_wait_expire == 0);
8169 	PRESERVE(tcp->tcp_state);
8170 	PRESERVE(tcp->tcp_rq);
8171 	PRESERVE(tcp->tcp_wq);
8172 
8173 	ASSERT(tcp->tcp_xmit_head == NULL);
8174 	ASSERT(tcp->tcp_xmit_last == NULL);
8175 	ASSERT(tcp->tcp_unsent == 0);
8176 	ASSERT(tcp->tcp_xmit_tail == NULL);
8177 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
8178 
8179 	tcp->tcp_snxt = 0;			/* Displayed in mib */
8180 	tcp->tcp_suna = 0;			/* Displayed in mib */
8181 	tcp->tcp_swnd = 0;
8182 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
8183 
8184 	ASSERT(tcp->tcp_ibsegs == 0);
8185 	ASSERT(tcp->tcp_obsegs == 0);
8186 
8187 	if (tcp->tcp_iphc != NULL) {
8188 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8189 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
8190 	}
8191 
8192 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
8193 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
8194 	DONTCARE(tcp->tcp_ipha);
8195 	DONTCARE(tcp->tcp_ip6h);
8196 	DONTCARE(tcp->tcp_ip_hdr_len);
8197 	DONTCARE(tcp->tcp_tcph);
8198 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
8199 	tcp->tcp_valid_bits = 0;
8200 
8201 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
8202 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
8203 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
8204 	tcp->tcp_last_rcv_lbolt = 0;
8205 
8206 	tcp->tcp_init_cwnd = 0;
8207 
8208 	tcp->tcp_urp_last_valid = 0;
8209 	tcp->tcp_hard_binding = 0;
8210 	tcp->tcp_hard_bound = 0;
8211 	PRESERVE(tcp->tcp_cred);
8212 	PRESERVE(tcp->tcp_cpid);
8213 	PRESERVE(tcp->tcp_exclbind);
8214 
8215 	tcp->tcp_fin_acked = 0;
8216 	tcp->tcp_fin_rcvd = 0;
8217 	tcp->tcp_fin_sent = 0;
8218 	tcp->tcp_ordrel_done = 0;
8219 
8220 	ASSERT(tcp->tcp_flow_stopped == 0);
8221 	tcp->tcp_debug = 0;
8222 	tcp->tcp_dontroute = 0;
8223 	tcp->tcp_broadcast = 0;
8224 
8225 	tcp->tcp_useloopback = 0;
8226 	tcp->tcp_reuseaddr = 0;
8227 	tcp->tcp_oobinline = 0;
8228 	tcp->tcp_dgram_errind = 0;
8229 
8230 	tcp->tcp_detached = 0;
8231 	tcp->tcp_bind_pending = 0;
8232 	tcp->tcp_unbind_pending = 0;
8233 	tcp->tcp_deferred_clean_death = 0;
8234 
8235 	tcp->tcp_snd_ws_ok = B_FALSE;
8236 	tcp->tcp_snd_ts_ok = B_FALSE;
8237 	tcp->tcp_linger = 0;
8238 	tcp->tcp_ka_enabled = 0;
8239 	tcp->tcp_zero_win_probe = 0;
8240 
8241 	tcp->tcp_loopback = 0;
8242 	tcp->tcp_localnet = 0;
8243 	tcp->tcp_syn_defense = 0;
8244 	tcp->tcp_set_timer = 0;
8245 
8246 	tcp->tcp_active_open = 0;
8247 	ASSERT(tcp->tcp_timeout == B_FALSE);
8248 	tcp->tcp_rexmit = B_FALSE;
8249 	tcp->tcp_xmit_zc_clean = B_FALSE;
8250 
8251 	tcp->tcp_snd_sack_ok = B_FALSE;
8252 	PRESERVE(tcp->tcp_recvdstaddr);
8253 	tcp->tcp_hwcksum = B_FALSE;
8254 
8255 	tcp->tcp_ire_ill_check_done = B_FALSE;
8256 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8257 
8258 	tcp->tcp_mdt = B_FALSE;
8259 	tcp->tcp_mdt_hdr_head = 0;
8260 	tcp->tcp_mdt_hdr_tail = 0;
8261 
8262 	tcp->tcp_conn_def_q0 = 0;
8263 	tcp->tcp_ip_forward_progress = B_FALSE;
8264 	tcp->tcp_anon_priv_bind = 0;
8265 	tcp->tcp_ecn_ok = B_FALSE;
8266 
8267 	tcp->tcp_cwr = B_FALSE;
8268 	tcp->tcp_ecn_echo_on = B_FALSE;
8269 
8270 	if (tcp->tcp_sack_info != NULL) {
8271 		if (tcp->tcp_notsack_list != NULL) {
8272 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8273 		}
8274 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8275 		tcp->tcp_sack_info = NULL;
8276 	}
8277 
8278 	tcp->tcp_rcv_ws = 0;
8279 	tcp->tcp_snd_ws = 0;
8280 	tcp->tcp_ts_recent = 0;
8281 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8282 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8283 	tcp->tcp_if_mtu = 0;
8284 
8285 	ASSERT(tcp->tcp_reass_head == NULL);
8286 	ASSERT(tcp->tcp_reass_tail == NULL);
8287 
8288 	tcp->tcp_cwnd_cnt = 0;
8289 
8290 	ASSERT(tcp->tcp_rcv_list == NULL);
8291 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8292 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8293 	ASSERT(tcp->tcp_rcv_cnt == 0);
8294 
8295 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8296 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8297 	tcp->tcp_csuna = 0;
8298 
8299 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8300 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8301 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8302 	tcp->tcp_rtt_update = 0;
8303 
8304 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8305 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8306 
8307 	tcp->tcp_rack = 0;			/* Displayed in mib */
8308 	tcp->tcp_rack_cnt = 0;
8309 	tcp->tcp_rack_cur_max = 0;
8310 	tcp->tcp_rack_abs_max = 0;
8311 
8312 	tcp->tcp_max_swnd = 0;
8313 
8314 	ASSERT(tcp->tcp_listener == NULL);
8315 
8316 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8317 
8318 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8319 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8320 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8321 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8322 
8323 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8324 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8325 	PRESERVE(tcp->tcp_conn_req_max);
8326 	PRESERVE(tcp->tcp_conn_req_seqnum);
8327 
8328 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8329 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8330 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8331 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8332 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8333 
8334 	tcp->tcp_lingertime = 0;
8335 
8336 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8337 	ASSERT(tcp->tcp_urp_mp == NULL);
8338 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8339 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8340 
8341 	ASSERT(tcp->tcp_eager_next_q == NULL);
8342 	ASSERT(tcp->tcp_eager_last_q == NULL);
8343 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8344 	    tcp->tcp_eager_prev_q0 == NULL) ||
8345 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8346 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8347 
8348 	tcp->tcp_client_errno = 0;
8349 
8350 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8351 
8352 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8353 
8354 	PRESERVE(tcp->tcp_bound_source_v6);
8355 	tcp->tcp_last_sent_len = 0;
8356 	tcp->tcp_dupack_cnt = 0;
8357 
8358 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8359 	PRESERVE(tcp->tcp_lport);
8360 
8361 	PRESERVE(tcp->tcp_acceptor_lockp);
8362 
8363 	ASSERT(tcp->tcp_ordrelid == 0);
8364 	PRESERVE(tcp->tcp_acceptor_id);
8365 	DONTCARE(tcp->tcp_ipsec_overhead);
8366 
8367 	/*
8368 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8369 	 * in tcp structure and now tracing), Re-initialize all
8370 	 * members of tcp_traceinfo.
8371 	 */
8372 	if (tcp->tcp_tracebuf != NULL) {
8373 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8374 	}
8375 
8376 	PRESERVE(tcp->tcp_family);
8377 	if (tcp->tcp_family == AF_INET6) {
8378 		tcp->tcp_ipversion = IPV6_VERSION;
8379 		tcp->tcp_mss = tcp_mss_def_ipv6;
8380 	} else {
8381 		tcp->tcp_ipversion = IPV4_VERSION;
8382 		tcp->tcp_mss = tcp_mss_def_ipv4;
8383 	}
8384 
8385 	tcp->tcp_bound_if = 0;
8386 	tcp->tcp_ipv6_recvancillary = 0;
8387 	tcp->tcp_recvifindex = 0;
8388 	tcp->tcp_recvhops = 0;
8389 	tcp->tcp_closed = 0;
8390 	tcp->tcp_cleandeathtag = 0;
8391 	if (tcp->tcp_hopopts != NULL) {
8392 		mi_free(tcp->tcp_hopopts);
8393 		tcp->tcp_hopopts = NULL;
8394 		tcp->tcp_hopoptslen = 0;
8395 	}
8396 	ASSERT(tcp->tcp_hopoptslen == 0);
8397 	if (tcp->tcp_dstopts != NULL) {
8398 		mi_free(tcp->tcp_dstopts);
8399 		tcp->tcp_dstopts = NULL;
8400 		tcp->tcp_dstoptslen = 0;
8401 	}
8402 	ASSERT(tcp->tcp_dstoptslen == 0);
8403 	if (tcp->tcp_rtdstopts != NULL) {
8404 		mi_free(tcp->tcp_rtdstopts);
8405 		tcp->tcp_rtdstopts = NULL;
8406 		tcp->tcp_rtdstoptslen = 0;
8407 	}
8408 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8409 	if (tcp->tcp_rthdr != NULL) {
8410 		mi_free(tcp->tcp_rthdr);
8411 		tcp->tcp_rthdr = NULL;
8412 		tcp->tcp_rthdrlen = 0;
8413 	}
8414 	ASSERT(tcp->tcp_rthdrlen == 0);
8415 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8416 
8417 	tcp->tcp_fused = B_FALSE;
8418 	tcp->tcp_unfusable = B_FALSE;
8419 	tcp->tcp_fused_sigurg = B_FALSE;
8420 	tcp->tcp_loopback_peer = NULL;
8421 
8422 	tcp->tcp_in_ack_unsent = 0;
8423 	tcp->tcp_cork = B_FALSE;
8424 
8425 	tcp->tcp_squeue_bytes = 0;
8426 
8427 #undef	DONTCARE
8428 #undef	PRESERVE
8429 }
8430 
8431 /*
8432  * Allocate necessary resources and initialize state vector.
8433  * Guaranteed not to fail so that when an error is returned,
8434  * the caller doesn't need to do any additional cleanup.
8435  */
8436 int
8437 tcp_init(tcp_t *tcp, queue_t *q)
8438 {
8439 	int	err;
8440 
8441 	tcp->tcp_rq = q;
8442 	tcp->tcp_wq = WR(q);
8443 	tcp->tcp_state = TCPS_IDLE;
8444 	if ((err = tcp_init_values(tcp)) != 0)
8445 		tcp_timers_stop(tcp);
8446 	return (err);
8447 }
8448 
8449 static int
8450 tcp_init_values(tcp_t *tcp)
8451 {
8452 	int	err;
8453 
8454 	ASSERT((tcp->tcp_family == AF_INET &&
8455 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8456 	    (tcp->tcp_family == AF_INET6 &&
8457 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8458 	    tcp->tcp_ipversion == IPV6_VERSION)));
8459 
8460 	/*
8461 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8462 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8463 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8464 	 * during first few transmissions of a connection as seen in slow
8465 	 * links.
8466 	 */
8467 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
8468 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
8469 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8470 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8471 	    tcp_conn_grace_period;
8472 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
8473 		tcp->tcp_rto = tcp_rexmit_interval_min;
8474 	tcp->tcp_timer_backoff = 0;
8475 	tcp->tcp_ms_we_have_waited = 0;
8476 	tcp->tcp_last_recv_time = lbolt;
8477 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
8478 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8479 
8480 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
8481 
8482 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
8483 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
8484 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
8485 	/*
8486 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8487 	 * passive open.
8488 	 */
8489 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
8490 
8491 	tcp->tcp_naglim = tcp_naglim_def;
8492 
8493 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8494 
8495 	tcp->tcp_mdt_hdr_head = 0;
8496 	tcp->tcp_mdt_hdr_tail = 0;
8497 
8498 	tcp->tcp_fused = B_FALSE;
8499 	tcp->tcp_unfusable = B_FALSE;
8500 	tcp->tcp_fused_sigurg = B_FALSE;
8501 	tcp->tcp_loopback_peer = NULL;
8502 
8503 	/* Initialize the header template */
8504 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8505 		err = tcp_header_init_ipv4(tcp);
8506 	} else {
8507 		err = tcp_header_init_ipv6(tcp);
8508 	}
8509 	if (err)
8510 		return (err);
8511 
8512 	/*
8513 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8514 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8515 	 */
8516 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8517 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
8518 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
8519 
8520 	tcp->tcp_cork = B_FALSE;
8521 	/*
8522 	 * Init the tcp_debug option.  This value determines whether TCP
8523 	 * calls strlog() to print out debug messages.  Doing this
8524 	 * initialization here means that this value is not inherited thru
8525 	 * tcp_reinit().
8526 	 */
8527 	tcp->tcp_debug = tcp_dbg;
8528 
8529 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8530 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8531 
8532 	return (0);
8533 }
8534 
8535 /*
8536  * Initialize the IPv4 header. Loses any record of any IP options.
8537  */
8538 static int
8539 tcp_header_init_ipv4(tcp_t *tcp)
8540 {
8541 	tcph_t		*tcph;
8542 	uint32_t	sum;
8543 
8544 	/*
8545 	 * This is a simple initialization. If there's
8546 	 * already a template, it should never be too small,
8547 	 * so reuse it.  Otherwise, allocate space for the new one.
8548 	 */
8549 	if (tcp->tcp_iphc == NULL) {
8550 		ASSERT(tcp->tcp_iphc_len == 0);
8551 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8552 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8553 		if (tcp->tcp_iphc == NULL) {
8554 			tcp->tcp_iphc_len = 0;
8555 			return (ENOMEM);
8556 		}
8557 	}
8558 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8559 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8560 	tcp->tcp_ip6h = NULL;
8561 	tcp->tcp_ipversion = IPV4_VERSION;
8562 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8563 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8564 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8565 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8566 	tcp->tcp_ipha->ipha_version_and_hdr_length
8567 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8568 	tcp->tcp_ipha->ipha_ident = 0;
8569 
8570 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8571 	tcp->tcp_tos = 0;
8572 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8573 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8574 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8575 
8576 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8577 	tcp->tcp_tcph = tcph;
8578 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8579 	/*
8580 	 * IP wants our header length in the checksum field to
8581 	 * allow it to perform a single pseudo-header+checksum
8582 	 * calculation on behalf of TCP.
8583 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8584 	 */
8585 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8586 	sum = (sum >> 16) + (sum & 0xFFFF);
8587 	U16_TO_ABE16(sum, tcph->th_sum);
8588 	return (0);
8589 }
8590 
8591 /*
8592  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8593  */
8594 static int
8595 tcp_header_init_ipv6(tcp_t *tcp)
8596 {
8597 	tcph_t	*tcph;
8598 	uint32_t	sum;
8599 
8600 	/*
8601 	 * This is a simple initialization. If there's
8602 	 * already a template, it should never be too small,
8603 	 * so reuse it. Otherwise, allocate space for the new one.
8604 	 * Ensure that there is enough space to "downgrade" the tcp_t
8605 	 * to an IPv4 tcp_t. This requires having space for a full load
8606 	 * of IPv4 options, as well as a full load of TCP options
8607 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8608 	 * than a v6 header and a TCP header with a full load of TCP options
8609 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8610 	 * We want to avoid reallocation in the "downgraded" case when
8611 	 * processing outbound IPv4 options.
8612 	 */
8613 	if (tcp->tcp_iphc == NULL) {
8614 		ASSERT(tcp->tcp_iphc_len == 0);
8615 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8616 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8617 		if (tcp->tcp_iphc == NULL) {
8618 			tcp->tcp_iphc_len = 0;
8619 			return (ENOMEM);
8620 		}
8621 	}
8622 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8623 	tcp->tcp_ipversion = IPV6_VERSION;
8624 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8625 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8626 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8627 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8628 	tcp->tcp_ipha = NULL;
8629 
8630 	/* Initialize the header template */
8631 
8632 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8633 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8634 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8635 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8636 
8637 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8638 	tcp->tcp_tcph = tcph;
8639 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8640 	/*
8641 	 * IP wants our header length in the checksum field to
8642 	 * allow it to perform a single psuedo-header+checksum
8643 	 * calculation on behalf of TCP.
8644 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8645 	 */
8646 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8647 	sum = (sum >> 16) + (sum & 0xFFFF);
8648 	U16_TO_ABE16(sum, tcph->th_sum);
8649 	return (0);
8650 }
8651 
8652 /* At minimum we need 4 bytes in the TCP header for the lookup */
8653 #define	ICMP_MIN_TCP_HDR	4
8654 
8655 /*
8656  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8657  * passed up by IP. The message is always received on the correct tcp_t.
8658  * Assumes that IP has pulled up everything up to and including the ICMP header.
8659  */
8660 void
8661 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8662 {
8663 	icmph_t *icmph;
8664 	ipha_t	*ipha;
8665 	int	iph_hdr_length;
8666 	tcph_t	*tcph;
8667 	boolean_t ipsec_mctl = B_FALSE;
8668 	boolean_t secure;
8669 	mblk_t *first_mp = mp;
8670 	uint32_t new_mss;
8671 	uint32_t ratio;
8672 	size_t mp_size = MBLKL(mp);
8673 	uint32_t seg_ack;
8674 	uint32_t seg_seq;
8675 
8676 	/* Assume IP provides aligned packets - otherwise toss */
8677 	if (!OK_32PTR(mp->b_rptr)) {
8678 		freemsg(mp);
8679 		return;
8680 	}
8681 
8682 	/*
8683 	 * Since ICMP errors are normal data marked with M_CTL when sent
8684 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8685 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8686 	 */
8687 	if ((mp_size == sizeof (ipsec_info_t)) &&
8688 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8689 		ASSERT(mp->b_cont != NULL);
8690 		mp = mp->b_cont;
8691 		/* IP should have done this */
8692 		ASSERT(OK_32PTR(mp->b_rptr));
8693 		mp_size = MBLKL(mp);
8694 		ipsec_mctl = B_TRUE;
8695 	}
8696 
8697 	/*
8698 	 * Verify that we have a complete outer IP header. If not, drop it.
8699 	 */
8700 	if (mp_size < sizeof (ipha_t)) {
8701 noticmpv4:
8702 		freemsg(first_mp);
8703 		return;
8704 	}
8705 
8706 	ipha = (ipha_t *)mp->b_rptr;
8707 	/*
8708 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8709 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8710 	 */
8711 	switch (IPH_HDR_VERSION(ipha)) {
8712 	case IPV6_VERSION:
8713 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8714 		return;
8715 	case IPV4_VERSION:
8716 		break;
8717 	default:
8718 		goto noticmpv4;
8719 	}
8720 
8721 	/* Skip past the outer IP and ICMP headers */
8722 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8723 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8724 	/*
8725 	 * If we don't have the correct outer IP header length or if the ULP
8726 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8727 	 * send it upstream.
8728 	 */
8729 	if (iph_hdr_length < sizeof (ipha_t) ||
8730 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8731 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8732 		goto noticmpv4;
8733 	}
8734 	ipha = (ipha_t *)&icmph[1];
8735 
8736 	/* Skip past the inner IP and find the ULP header */
8737 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8738 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8739 	/*
8740 	 * If we don't have the correct inner IP header length or if the ULP
8741 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8742 	 * bytes of TCP header, drop it.
8743 	 */
8744 	if (iph_hdr_length < sizeof (ipha_t) ||
8745 	    ipha->ipha_protocol != IPPROTO_TCP ||
8746 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8747 		goto noticmpv4;
8748 	}
8749 
8750 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8751 		if (ipsec_mctl) {
8752 			secure = ipsec_in_is_secure(first_mp);
8753 		} else {
8754 			secure = B_FALSE;
8755 		}
8756 		if (secure) {
8757 			/*
8758 			 * If we are willing to accept this in clear
8759 			 * we don't have to verify policy.
8760 			 */
8761 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8762 				if (!tcp_check_policy(tcp, first_mp,
8763 				    ipha, NULL, secure, ipsec_mctl)) {
8764 					/*
8765 					 * tcp_check_policy called
8766 					 * ip_drop_packet() on failure.
8767 					 */
8768 					return;
8769 				}
8770 			}
8771 		}
8772 	} else if (ipsec_mctl) {
8773 		/*
8774 		 * This is a hard_bound connection. IP has already
8775 		 * verified policy. We don't have to do it again.
8776 		 */
8777 		freeb(first_mp);
8778 		first_mp = mp;
8779 		ipsec_mctl = B_FALSE;
8780 	}
8781 
8782 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8783 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8784 	/*
8785 	 * TCP SHOULD check that the TCP sequence number contained in
8786 	 * payload of the ICMP error message is within the range
8787 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8788 	 */
8789 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8790 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8791 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8792 		/*
8793 		 * If the ICMP message is bogus, should we kill the
8794 		 * connection, or should we just drop the bogus ICMP
8795 		 * message? It would probably make more sense to just
8796 		 * drop the message so that if this one managed to get
8797 		 * in, the real connection should not suffer.
8798 		 */
8799 		goto noticmpv4;
8800 	}
8801 
8802 	switch (icmph->icmph_type) {
8803 	case ICMP_DEST_UNREACHABLE:
8804 		switch (icmph->icmph_code) {
8805 		case ICMP_FRAGMENTATION_NEEDED:
8806 			/*
8807 			 * Reduce the MSS based on the new MTU.  This will
8808 			 * eliminate any fragmentation locally.
8809 			 * N.B.  There may well be some funny side-effects on
8810 			 * the local send policy and the remote receive policy.
8811 			 * Pending further research, we provide
8812 			 * tcp_ignore_path_mtu just in case this proves
8813 			 * disastrous somewhere.
8814 			 *
8815 			 * After updating the MSS, retransmit part of the
8816 			 * dropped segment using the new mss by calling
8817 			 * tcp_wput_data().  Need to adjust all those
8818 			 * params to make sure tcp_wput_data() work properly.
8819 			 */
8820 			if (tcp_ignore_path_mtu)
8821 				break;
8822 
8823 			/*
8824 			 * Decrease the MSS by time stamp options
8825 			 * IP options and IPSEC options. tcp_hdr_len
8826 			 * includes time stamp option and IP option
8827 			 * length.
8828 			 */
8829 
8830 			new_mss = ntohs(icmph->icmph_du_mtu) -
8831 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8832 
8833 			/*
8834 			 * Only update the MSS if the new one is
8835 			 * smaller than the previous one.  This is
8836 			 * to avoid problems when getting multiple
8837 			 * ICMP errors for the same MTU.
8838 			 */
8839 			if (new_mss >= tcp->tcp_mss)
8840 				break;
8841 
8842 			/*
8843 			 * Stop doing PMTU if new_mss is less than 68
8844 			 * or less than tcp_mss_min.
8845 			 * The value 68 comes from rfc 1191.
8846 			 */
8847 			if (new_mss < MAX(68, tcp_mss_min))
8848 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8849 				    0;
8850 
8851 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8852 			ASSERT(ratio >= 1);
8853 			tcp_mss_set(tcp, new_mss);
8854 
8855 			/*
8856 			 * Make sure we have something to
8857 			 * send.
8858 			 */
8859 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8860 			    (tcp->tcp_xmit_head != NULL)) {
8861 				/*
8862 				 * Shrink tcp_cwnd in
8863 				 * proportion to the old MSS/new MSS.
8864 				 */
8865 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8866 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8867 				    (tcp->tcp_unsent == 0)) {
8868 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8869 				} else {
8870 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8871 				}
8872 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8873 				tcp->tcp_rexmit = B_TRUE;
8874 				tcp->tcp_dupack_cnt = 0;
8875 				tcp->tcp_snd_burst = TCP_CWND_SS;
8876 				tcp_ss_rexmit(tcp);
8877 			}
8878 			break;
8879 		case ICMP_PORT_UNREACHABLE:
8880 		case ICMP_PROTOCOL_UNREACHABLE:
8881 			switch (tcp->tcp_state) {
8882 			case TCPS_SYN_SENT:
8883 			case TCPS_SYN_RCVD:
8884 				/*
8885 				 * ICMP can snipe away incipient
8886 				 * TCP connections as long as
8887 				 * seq number is same as initial
8888 				 * send seq number.
8889 				 */
8890 				if (seg_seq == tcp->tcp_iss) {
8891 					(void) tcp_clean_death(tcp,
8892 					    ECONNREFUSED, 6);
8893 				}
8894 				break;
8895 			}
8896 			break;
8897 		case ICMP_HOST_UNREACHABLE:
8898 		case ICMP_NET_UNREACHABLE:
8899 			/* Record the error in case we finally time out. */
8900 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8901 				tcp->tcp_client_errno = EHOSTUNREACH;
8902 			else
8903 				tcp->tcp_client_errno = ENETUNREACH;
8904 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8905 				if (tcp->tcp_listener != NULL &&
8906 				    tcp->tcp_listener->tcp_syn_defense) {
8907 					/*
8908 					 * Ditch the half-open connection if we
8909 					 * suspect a SYN attack is under way.
8910 					 */
8911 					tcp_ip_ire_mark_advice(tcp);
8912 					(void) tcp_clean_death(tcp,
8913 					    tcp->tcp_client_errno, 7);
8914 				}
8915 			}
8916 			break;
8917 		default:
8918 			break;
8919 		}
8920 		break;
8921 	case ICMP_SOURCE_QUENCH: {
8922 		/*
8923 		 * use a global boolean to control
8924 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8925 		 * The default is false.
8926 		 */
8927 		if (tcp_icmp_source_quench) {
8928 			/*
8929 			 * Reduce the sending rate as if we got a
8930 			 * retransmit timeout
8931 			 */
8932 			uint32_t npkt;
8933 
8934 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8935 			    tcp->tcp_mss;
8936 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8937 			tcp->tcp_cwnd = tcp->tcp_mss;
8938 			tcp->tcp_cwnd_cnt = 0;
8939 		}
8940 		break;
8941 	}
8942 	}
8943 	freemsg(first_mp);
8944 }
8945 
8946 /*
8947  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8948  * error messages passed up by IP.
8949  * Assumes that IP has pulled up all the extension headers as well
8950  * as the ICMPv6 header.
8951  */
8952 static void
8953 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8954 {
8955 	icmp6_t *icmp6;
8956 	ip6_t	*ip6h;
8957 	uint16_t	iph_hdr_length;
8958 	tcpha_t	*tcpha;
8959 	uint8_t	*nexthdrp;
8960 	uint32_t new_mss;
8961 	uint32_t ratio;
8962 	boolean_t secure;
8963 	mblk_t *first_mp = mp;
8964 	size_t mp_size;
8965 	uint32_t seg_ack;
8966 	uint32_t seg_seq;
8967 
8968 	/*
8969 	 * The caller has determined if this is an IPSEC_IN packet and
8970 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8971 	 */
8972 	if (ipsec_mctl)
8973 		mp = mp->b_cont;
8974 
8975 	mp_size = MBLKL(mp);
8976 
8977 	/*
8978 	 * Verify that we have a complete IP header. If not, send it upstream.
8979 	 */
8980 	if (mp_size < sizeof (ip6_t)) {
8981 noticmpv6:
8982 		freemsg(first_mp);
8983 		return;
8984 	}
8985 
8986 	/*
8987 	 * Verify this is an ICMPV6 packet, else send it upstream.
8988 	 */
8989 	ip6h = (ip6_t *)mp->b_rptr;
8990 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8991 		iph_hdr_length = IPV6_HDR_LEN;
8992 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8993 	    &nexthdrp) ||
8994 	    *nexthdrp != IPPROTO_ICMPV6) {
8995 		goto noticmpv6;
8996 	}
8997 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8998 	ip6h = (ip6_t *)&icmp6[1];
8999 	/*
9000 	 * Verify if we have a complete ICMP and inner IP header.
9001 	 */
9002 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
9003 		goto noticmpv6;
9004 
9005 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
9006 		goto noticmpv6;
9007 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
9008 	/*
9009 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
9010 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
9011 	 * packet.
9012 	 */
9013 	if ((*nexthdrp != IPPROTO_TCP) ||
9014 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
9015 		goto noticmpv6;
9016 	}
9017 
9018 	/*
9019 	 * ICMP errors come on the right queue or come on
9020 	 * listener/global queue for detached connections and
9021 	 * get switched to the right queue. If it comes on the
9022 	 * right queue, policy check has already been done by IP
9023 	 * and thus free the first_mp without verifying the policy.
9024 	 * If it has come for a non-hard bound connection, we need
9025 	 * to verify policy as IP may not have done it.
9026 	 */
9027 	if (!tcp->tcp_hard_bound) {
9028 		if (ipsec_mctl) {
9029 			secure = ipsec_in_is_secure(first_mp);
9030 		} else {
9031 			secure = B_FALSE;
9032 		}
9033 		if (secure) {
9034 			/*
9035 			 * If we are willing to accept this in clear
9036 			 * we don't have to verify policy.
9037 			 */
9038 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
9039 				if (!tcp_check_policy(tcp, first_mp,
9040 				    NULL, ip6h, secure, ipsec_mctl)) {
9041 					/*
9042 					 * tcp_check_policy called
9043 					 * ip_drop_packet() on failure.
9044 					 */
9045 					return;
9046 				}
9047 			}
9048 		}
9049 	} else if (ipsec_mctl) {
9050 		/*
9051 		 * This is a hard_bound connection. IP has already
9052 		 * verified policy. We don't have to do it again.
9053 		 */
9054 		freeb(first_mp);
9055 		first_mp = mp;
9056 		ipsec_mctl = B_FALSE;
9057 	}
9058 
9059 	seg_ack = ntohl(tcpha->tha_ack);
9060 	seg_seq = ntohl(tcpha->tha_seq);
9061 	/*
9062 	 * TCP SHOULD check that the TCP sequence number contained in
9063 	 * payload of the ICMP error message is within the range
9064 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
9065 	 */
9066 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
9067 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
9068 		/*
9069 		 * If the ICMP message is bogus, should we kill the
9070 		 * connection, or should we just drop the bogus ICMP
9071 		 * message? It would probably make more sense to just
9072 		 * drop the message so that if this one managed to get
9073 		 * in, the real connection should not suffer.
9074 		 */
9075 		goto noticmpv6;
9076 	}
9077 
9078 	switch (icmp6->icmp6_type) {
9079 	case ICMP6_PACKET_TOO_BIG:
9080 		/*
9081 		 * Reduce the MSS based on the new MTU.  This will
9082 		 * eliminate any fragmentation locally.
9083 		 * N.B.  There may well be some funny side-effects on
9084 		 * the local send policy and the remote receive policy.
9085 		 * Pending further research, we provide
9086 		 * tcp_ignore_path_mtu just in case this proves
9087 		 * disastrous somewhere.
9088 		 *
9089 		 * After updating the MSS, retransmit part of the
9090 		 * dropped segment using the new mss by calling
9091 		 * tcp_wput_data().  Need to adjust all those
9092 		 * params to make sure tcp_wput_data() work properly.
9093 		 */
9094 		if (tcp_ignore_path_mtu)
9095 			break;
9096 
9097 		/*
9098 		 * Decrease the MSS by time stamp options
9099 		 * IP options and IPSEC options. tcp_hdr_len
9100 		 * includes time stamp option and IP option
9101 		 * length.
9102 		 */
9103 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
9104 			    tcp->tcp_ipsec_overhead;
9105 
9106 		/*
9107 		 * Only update the MSS if the new one is
9108 		 * smaller than the previous one.  This is
9109 		 * to avoid problems when getting multiple
9110 		 * ICMP errors for the same MTU.
9111 		 */
9112 		if (new_mss >= tcp->tcp_mss)
9113 			break;
9114 
9115 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
9116 		ASSERT(ratio >= 1);
9117 		tcp_mss_set(tcp, new_mss);
9118 
9119 		/*
9120 		 * Make sure we have something to
9121 		 * send.
9122 		 */
9123 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
9124 		    (tcp->tcp_xmit_head != NULL)) {
9125 			/*
9126 			 * Shrink tcp_cwnd in
9127 			 * proportion to the old MSS/new MSS.
9128 			 */
9129 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
9130 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
9131 			    (tcp->tcp_unsent == 0)) {
9132 				tcp->tcp_rexmit_max = tcp->tcp_fss;
9133 			} else {
9134 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
9135 			}
9136 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
9137 			tcp->tcp_rexmit = B_TRUE;
9138 			tcp->tcp_dupack_cnt = 0;
9139 			tcp->tcp_snd_burst = TCP_CWND_SS;
9140 			tcp_ss_rexmit(tcp);
9141 		}
9142 		break;
9143 
9144 	case ICMP6_DST_UNREACH:
9145 		switch (icmp6->icmp6_code) {
9146 		case ICMP6_DST_UNREACH_NOPORT:
9147 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9148 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9149 			    (tcpha->tha_seq == tcp->tcp_iss)) {
9150 				(void) tcp_clean_death(tcp,
9151 				    ECONNREFUSED, 8);
9152 			}
9153 			break;
9154 
9155 		case ICMP6_DST_UNREACH_ADMIN:
9156 		case ICMP6_DST_UNREACH_NOROUTE:
9157 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
9158 		case ICMP6_DST_UNREACH_ADDR:
9159 			/* Record the error in case we finally time out. */
9160 			tcp->tcp_client_errno = EHOSTUNREACH;
9161 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9162 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9163 			    (tcpha->tha_seq == tcp->tcp_iss)) {
9164 				if (tcp->tcp_listener != NULL &&
9165 				    tcp->tcp_listener->tcp_syn_defense) {
9166 					/*
9167 					 * Ditch the half-open connection if we
9168 					 * suspect a SYN attack is under way.
9169 					 */
9170 					tcp_ip_ire_mark_advice(tcp);
9171 					(void) tcp_clean_death(tcp,
9172 					    tcp->tcp_client_errno, 9);
9173 				}
9174 			}
9175 
9176 
9177 			break;
9178 		default:
9179 			break;
9180 		}
9181 		break;
9182 
9183 	case ICMP6_PARAM_PROB:
9184 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9185 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9186 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9187 		    (uchar_t *)nexthdrp) {
9188 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9189 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9190 				(void) tcp_clean_death(tcp,
9191 				    ECONNREFUSED, 10);
9192 			}
9193 			break;
9194 		}
9195 		break;
9196 
9197 	case ICMP6_TIME_EXCEEDED:
9198 	default:
9199 		break;
9200 	}
9201 	freemsg(first_mp);
9202 }
9203 
9204 /*
9205  * IP recognizes seven kinds of bind requests:
9206  *
9207  * - A zero-length address binds only to the protocol number.
9208  *
9209  * - A 4-byte address is treated as a request to
9210  * validate that the address is a valid local IPv4
9211  * address, appropriate for an application to bind to.
9212  * IP does the verification, but does not make any note
9213  * of the address at this time.
9214  *
9215  * - A 16-byte address contains is treated as a request
9216  * to validate a local IPv6 address, as the 4-byte
9217  * address case above.
9218  *
9219  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9220  * use it for the inbound fanout of packets.
9221  *
9222  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9223  * use it for the inbound fanout of packets.
9224  *
9225  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9226  * information consisting of local and remote addresses
9227  * and ports.  In this case, the addresses are both
9228  * validated as appropriate for this operation, and, if
9229  * so, the information is retained for use in the
9230  * inbound fanout.
9231  *
9232  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9233  * fanout information, like the 12-byte case above.
9234  *
9235  * IP will also fill in the IRE request mblk with information
9236  * regarding our peer.  In all cases, we notify IP of our protocol
9237  * type by appending a single protocol byte to the bind request.
9238  */
9239 static mblk_t *
9240 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9241 {
9242 	char	*cp;
9243 	mblk_t	*mp;
9244 	struct T_bind_req *tbr;
9245 	ipa_conn_t	*ac;
9246 	ipa6_conn_t	*ac6;
9247 	sin_t		*sin;
9248 	sin6_t		*sin6;
9249 
9250 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9251 	ASSERT((tcp->tcp_family == AF_INET &&
9252 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9253 	    (tcp->tcp_family == AF_INET6 &&
9254 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9255 	    tcp->tcp_ipversion == IPV6_VERSION)));
9256 
9257 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9258 	if (!mp)
9259 		return (mp);
9260 	mp->b_datap->db_type = M_PROTO;
9261 	tbr = (struct T_bind_req *)mp->b_rptr;
9262 	tbr->PRIM_type = bind_prim;
9263 	tbr->ADDR_offset = sizeof (*tbr);
9264 	tbr->CONIND_number = 0;
9265 	tbr->ADDR_length = addr_length;
9266 	cp = (char *)&tbr[1];
9267 	switch (addr_length) {
9268 	case sizeof (ipa_conn_t):
9269 		ASSERT(tcp->tcp_family == AF_INET);
9270 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9271 
9272 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9273 		if (mp->b_cont == NULL) {
9274 			freemsg(mp);
9275 			return (NULL);
9276 		}
9277 		mp->b_cont->b_wptr += sizeof (ire_t);
9278 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9279 
9280 		/* cp known to be 32 bit aligned */
9281 		ac = (ipa_conn_t *)cp;
9282 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9283 		ac->ac_faddr = tcp->tcp_remote;
9284 		ac->ac_fport = tcp->tcp_fport;
9285 		ac->ac_lport = tcp->tcp_lport;
9286 		tcp->tcp_hard_binding = 1;
9287 		break;
9288 
9289 	case sizeof (ipa6_conn_t):
9290 		ASSERT(tcp->tcp_family == AF_INET6);
9291 
9292 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9293 		if (mp->b_cont == NULL) {
9294 			freemsg(mp);
9295 			return (NULL);
9296 		}
9297 		mp->b_cont->b_wptr += sizeof (ire_t);
9298 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9299 
9300 		/* cp known to be 32 bit aligned */
9301 		ac6 = (ipa6_conn_t *)cp;
9302 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9303 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9304 			    &ac6->ac6_laddr);
9305 		} else {
9306 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9307 		}
9308 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9309 		ac6->ac6_fport = tcp->tcp_fport;
9310 		ac6->ac6_lport = tcp->tcp_lport;
9311 		tcp->tcp_hard_binding = 1;
9312 		break;
9313 
9314 	case sizeof (sin_t):
9315 		/*
9316 		 * NOTE: IPV6_ADDR_LEN also has same size.
9317 		 * Use family to discriminate.
9318 		 */
9319 		if (tcp->tcp_family == AF_INET) {
9320 			sin = (sin_t *)cp;
9321 
9322 			*sin = sin_null;
9323 			sin->sin_family = AF_INET;
9324 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9325 			sin->sin_port = tcp->tcp_lport;
9326 			break;
9327 		} else {
9328 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9329 		}
9330 		break;
9331 
9332 	case sizeof (sin6_t):
9333 		ASSERT(tcp->tcp_family == AF_INET6);
9334 		sin6 = (sin6_t *)cp;
9335 
9336 		*sin6 = sin6_null;
9337 		sin6->sin6_family = AF_INET6;
9338 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9339 		sin6->sin6_port = tcp->tcp_lport;
9340 		break;
9341 
9342 	case IP_ADDR_LEN:
9343 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9344 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9345 		break;
9346 
9347 	}
9348 	/* Add protocol number to end */
9349 	cp[addr_length] = (char)IPPROTO_TCP;
9350 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9351 	return (mp);
9352 }
9353 
9354 /*
9355  * Notify IP that we are having trouble with this connection.  IP should
9356  * blow the IRE away and start over.
9357  */
9358 static void
9359 tcp_ip_notify(tcp_t *tcp)
9360 {
9361 	struct iocblk	*iocp;
9362 	ipid_t	*ipid;
9363 	mblk_t	*mp;
9364 
9365 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9366 	if (tcp->tcp_ipversion == IPV6_VERSION)
9367 		return;
9368 
9369 	mp = mkiocb(IP_IOCTL);
9370 	if (mp == NULL)
9371 		return;
9372 
9373 	iocp = (struct iocblk *)mp->b_rptr;
9374 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9375 
9376 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9377 	if (!mp->b_cont) {
9378 		freeb(mp);
9379 		return;
9380 	}
9381 
9382 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9383 	mp->b_cont->b_wptr += iocp->ioc_count;
9384 	bzero(ipid, sizeof (*ipid));
9385 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9386 	ipid->ipid_ire_type = IRE_CACHE;
9387 	ipid->ipid_addr_offset = sizeof (ipid_t);
9388 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9389 	/*
9390 	 * Note: in the case of source routing we want to blow away the
9391 	 * route to the first source route hop.
9392 	 */
9393 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9394 	    sizeof (tcp->tcp_ipha->ipha_dst));
9395 
9396 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9397 }
9398 
9399 /* Unlink and return any mblk that looks like it contains an ire */
9400 static mblk_t *
9401 tcp_ire_mp(mblk_t *mp)
9402 {
9403 	mblk_t	*prev_mp;
9404 
9405 	for (;;) {
9406 		prev_mp = mp;
9407 		mp = mp->b_cont;
9408 		if (mp == NULL)
9409 			break;
9410 		switch (DB_TYPE(mp)) {
9411 		case IRE_DB_TYPE:
9412 		case IRE_DB_REQ_TYPE:
9413 			if (prev_mp != NULL)
9414 				prev_mp->b_cont = mp->b_cont;
9415 			mp->b_cont = NULL;
9416 			return (mp);
9417 		default:
9418 			break;
9419 		}
9420 	}
9421 	return (mp);
9422 }
9423 
9424 /*
9425  * Timer callback routine for keepalive probe.  We do a fake resend of
9426  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9427  * check to see if we have heard anything from the other end for the last
9428  * RTO period.  If we have, set the timer to expire for another
9429  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9430  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9431  * the timeout if we have not heard from the other side.  If for more than
9432  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9433  * kill the connection unless the keepalive abort threshold is 0.  In
9434  * that case, we will probe "forever."
9435  */
9436 static void
9437 tcp_keepalive_killer(void *arg)
9438 {
9439 	mblk_t	*mp;
9440 	conn_t	*connp = (conn_t *)arg;
9441 	tcp_t  	*tcp = connp->conn_tcp;
9442 	int32_t	firetime;
9443 	int32_t	idletime;
9444 	int32_t	ka_intrvl;
9445 
9446 	tcp->tcp_ka_tid = 0;
9447 
9448 	if (tcp->tcp_fused)
9449 		return;
9450 
9451 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
9452 	ka_intrvl = tcp->tcp_ka_interval;
9453 
9454 	/*
9455 	 * Keepalive probe should only be sent if the application has not
9456 	 * done a close on the connection.
9457 	 */
9458 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9459 		return;
9460 	}
9461 	/* Timer fired too early, restart it. */
9462 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9463 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9464 		    MSEC_TO_TICK(ka_intrvl));
9465 		return;
9466 	}
9467 
9468 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9469 	/*
9470 	 * If we have not heard from the other side for a long
9471 	 * time, kill the connection unless the keepalive abort
9472 	 * threshold is 0.  In that case, we will probe "forever."
9473 	 */
9474 	if (tcp->tcp_ka_abort_thres != 0 &&
9475 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9476 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
9477 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9478 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9479 		return;
9480 	}
9481 
9482 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9483 	    idletime >= ka_intrvl) {
9484 		/* Fake resend of last ACKed byte. */
9485 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9486 
9487 		if (mp1 != NULL) {
9488 			*mp1->b_wptr++ = '\0';
9489 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9490 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9491 			freeb(mp1);
9492 			/*
9493 			 * if allocation failed, fall through to start the
9494 			 * timer back.
9495 			 */
9496 			if (mp != NULL) {
9497 				TCP_RECORD_TRACE(tcp, mp,
9498 				    TCP_TRACE_SEND_PKT);
9499 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9500 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
9501 				if (tcp->tcp_ka_last_intrvl != 0) {
9502 					/*
9503 					 * We should probe again at least
9504 					 * in ka_intrvl, but not more than
9505 					 * tcp_rexmit_interval_max.
9506 					 */
9507 					firetime = MIN(ka_intrvl - 1,
9508 					    tcp->tcp_ka_last_intrvl << 1);
9509 					if (firetime > tcp_rexmit_interval_max)
9510 						firetime =
9511 						    tcp_rexmit_interval_max;
9512 				} else {
9513 					firetime = tcp->tcp_rto;
9514 				}
9515 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9516 				    tcp_keepalive_killer,
9517 				    MSEC_TO_TICK(firetime));
9518 				tcp->tcp_ka_last_intrvl = firetime;
9519 				return;
9520 			}
9521 		}
9522 	} else {
9523 		tcp->tcp_ka_last_intrvl = 0;
9524 	}
9525 
9526 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9527 	if ((firetime = ka_intrvl - idletime) < 0) {
9528 		firetime = ka_intrvl;
9529 	}
9530 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9531 	    MSEC_TO_TICK(firetime));
9532 }
9533 
9534 static int
9535 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9536 {
9537 	queue_t	*q = tcp->tcp_rq;
9538 	int32_t	mss = tcp->tcp_mss;
9539 	int	maxpsz;
9540 
9541 	if (TCP_IS_DETACHED(tcp))
9542 		return (mss);
9543 
9544 	if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
9545 		/*
9546 		 * Set the sd_qn_maxpsz according to the socket send buffer
9547 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9548 		 * instruct the stream head to copyin user data into contiguous
9549 		 * kernel-allocated buffers without breaking it up into smaller
9550 		 * chunks.  We round up the buffer size to the nearest SMSS.
9551 		 */
9552 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9553 		mss = INFPSZ;
9554 	} else {
9555 		/*
9556 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9557 		 * (and a multiple of the mss).  This instructs the stream
9558 		 * head to break down larger than SMSS writes into SMSS-
9559 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9560 		 */
9561 		maxpsz = tcp->tcp_maxpsz * mss;
9562 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9563 			maxpsz = tcp->tcp_xmit_hiwater/2;
9564 			/* Round up to nearest mss */
9565 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9566 		}
9567 	}
9568 	(void) setmaxps(q, maxpsz);
9569 	tcp->tcp_wq->q_maxpsz = maxpsz;
9570 
9571 	if (set_maxblk)
9572 		(void) mi_set_sth_maxblk(q, mss);
9573 
9574 	if (tcp->tcp_loopback)
9575 		(void) mi_set_sth_copyopt(tcp->tcp_rq, COPYCACHED);
9576 
9577 	return (mss);
9578 }
9579 
9580 /*
9581  * Extract option values from a tcp header.  We put any found values into the
9582  * tcpopt struct and return a bitmask saying which options were found.
9583  */
9584 static int
9585 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9586 {
9587 	uchar_t		*endp;
9588 	int		len;
9589 	uint32_t	mss;
9590 	uchar_t		*up = (uchar_t *)tcph;
9591 	int		found = 0;
9592 	int32_t		sack_len;
9593 	tcp_seq		sack_begin, sack_end;
9594 	tcp_t		*tcp;
9595 
9596 	endp = up + TCP_HDR_LENGTH(tcph);
9597 	up += TCP_MIN_HEADER_LENGTH;
9598 	while (up < endp) {
9599 		len = endp - up;
9600 		switch (*up) {
9601 		case TCPOPT_EOL:
9602 			break;
9603 
9604 		case TCPOPT_NOP:
9605 			up++;
9606 			continue;
9607 
9608 		case TCPOPT_MAXSEG:
9609 			if (len < TCPOPT_MAXSEG_LEN ||
9610 			    up[1] != TCPOPT_MAXSEG_LEN)
9611 				break;
9612 
9613 			mss = BE16_TO_U16(up+2);
9614 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9615 			tcpopt->tcp_opt_mss = mss;
9616 			found |= TCP_OPT_MSS_PRESENT;
9617 
9618 			up += TCPOPT_MAXSEG_LEN;
9619 			continue;
9620 
9621 		case TCPOPT_WSCALE:
9622 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9623 				break;
9624 
9625 			if (up[2] > TCP_MAX_WINSHIFT)
9626 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9627 			else
9628 				tcpopt->tcp_opt_wscale = up[2];
9629 			found |= TCP_OPT_WSCALE_PRESENT;
9630 
9631 			up += TCPOPT_WS_LEN;
9632 			continue;
9633 
9634 		case TCPOPT_SACK_PERMITTED:
9635 			if (len < TCPOPT_SACK_OK_LEN ||
9636 			    up[1] != TCPOPT_SACK_OK_LEN)
9637 				break;
9638 			found |= TCP_OPT_SACK_OK_PRESENT;
9639 			up += TCPOPT_SACK_OK_LEN;
9640 			continue;
9641 
9642 		case TCPOPT_SACK:
9643 			if (len <= 2 || up[1] <= 2 || len < up[1])
9644 				break;
9645 
9646 			/* If TCP is not interested in SACK blks... */
9647 			if ((tcp = tcpopt->tcp) == NULL) {
9648 				up += up[1];
9649 				continue;
9650 			}
9651 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9652 			up += TCPOPT_HEADER_LEN;
9653 
9654 			/*
9655 			 * If the list is empty, allocate one and assume
9656 			 * nothing is sack'ed.
9657 			 */
9658 			ASSERT(tcp->tcp_sack_info != NULL);
9659 			if (tcp->tcp_notsack_list == NULL) {
9660 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9661 				    tcp->tcp_suna, tcp->tcp_snxt,
9662 				    &(tcp->tcp_num_notsack_blk),
9663 				    &(tcp->tcp_cnt_notsack_list));
9664 
9665 				/*
9666 				 * Make sure tcp_notsack_list is not NULL.
9667 				 * This happens when kmem_alloc(KM_NOSLEEP)
9668 				 * returns NULL.
9669 				 */
9670 				if (tcp->tcp_notsack_list == NULL) {
9671 					up += sack_len;
9672 					continue;
9673 				}
9674 				tcp->tcp_fack = tcp->tcp_suna;
9675 			}
9676 
9677 			while (sack_len > 0) {
9678 				if (up + 8 > endp) {
9679 					up = endp;
9680 					break;
9681 				}
9682 				sack_begin = BE32_TO_U32(up);
9683 				up += 4;
9684 				sack_end = BE32_TO_U32(up);
9685 				up += 4;
9686 				sack_len -= 8;
9687 				/*
9688 				 * Bounds checking.  Make sure the SACK
9689 				 * info is within tcp_suna and tcp_snxt.
9690 				 * If this SACK blk is out of bound, ignore
9691 				 * it but continue to parse the following
9692 				 * blks.
9693 				 */
9694 				if (SEQ_LEQ(sack_end, sack_begin) ||
9695 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9696 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9697 					continue;
9698 				}
9699 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9700 				    sack_begin, sack_end,
9701 				    &(tcp->tcp_num_notsack_blk),
9702 				    &(tcp->tcp_cnt_notsack_list));
9703 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9704 					tcp->tcp_fack = sack_end;
9705 				}
9706 			}
9707 			found |= TCP_OPT_SACK_PRESENT;
9708 			continue;
9709 
9710 		case TCPOPT_TSTAMP:
9711 			if (len < TCPOPT_TSTAMP_LEN ||
9712 			    up[1] != TCPOPT_TSTAMP_LEN)
9713 				break;
9714 
9715 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9716 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9717 
9718 			found |= TCP_OPT_TSTAMP_PRESENT;
9719 
9720 			up += TCPOPT_TSTAMP_LEN;
9721 			continue;
9722 
9723 		default:
9724 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9725 				break;
9726 			up += up[1];
9727 			continue;
9728 		}
9729 		break;
9730 	}
9731 	return (found);
9732 }
9733 
9734 /*
9735  * Set the mss associated with a particular tcp based on its current value,
9736  * and a new one passed in. Observe minimums and maximums, and reset
9737  * other state variables that we want to view as multiples of mss.
9738  *
9739  * This function is called in various places mainly because
9740  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9741  *    other side's SYN/SYN-ACK packet arrives.
9742  * 2) PMTUd may get us a new MSS.
9743  * 3) If the other side stops sending us timestamp option, we need to
9744  *    increase the MSS size to use the extra bytes available.
9745  */
9746 static void
9747 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9748 {
9749 	uint32_t	mss_max;
9750 
9751 	if (tcp->tcp_ipversion == IPV4_VERSION)
9752 		mss_max = tcp_mss_max_ipv4;
9753 	else
9754 		mss_max = tcp_mss_max_ipv6;
9755 
9756 	if (mss < tcp_mss_min)
9757 		mss = tcp_mss_min;
9758 	if (mss > mss_max)
9759 		mss = mss_max;
9760 	/*
9761 	 * Unless naglim has been set by our client to
9762 	 * a non-mss value, force naglim to track mss.
9763 	 * This can help to aggregate small writes.
9764 	 */
9765 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9766 		tcp->tcp_naglim = mss;
9767 	/*
9768 	 * TCP should be able to buffer at least 4 MSS data for obvious
9769 	 * performance reason.
9770 	 */
9771 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9772 		tcp->tcp_xmit_hiwater = mss << 2;
9773 
9774 	/*
9775 	 * Check if we need to apply the tcp_init_cwnd here.  If
9776 	 * it is set and the MSS gets bigger (should not happen
9777 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9778 	 * The new tcp_cwnd should not get bigger.
9779 	 */
9780 	if (tcp->tcp_init_cwnd == 0) {
9781 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9782 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9783 	} else {
9784 		if (tcp->tcp_mss < mss) {
9785 			tcp->tcp_cwnd = MAX(1,
9786 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9787 		} else {
9788 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9789 		}
9790 	}
9791 	tcp->tcp_mss = mss;
9792 	tcp->tcp_cwnd_cnt = 0;
9793 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9794 }
9795 
9796 static int
9797 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9798 {
9799 	tcp_t		*tcp = NULL;
9800 	conn_t		*connp;
9801 	int		err;
9802 	dev_t		conn_dev;
9803 	zoneid_t	zoneid = getzoneid();
9804 
9805 	if (q->q_ptr != NULL)
9806 		return (0);
9807 
9808 	if (sflag == MODOPEN) {
9809 		/*
9810 		 * This is a special case. The purpose of a modopen
9811 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9812 		 * through for MIB browsers. Everything else is failed.
9813 		 */
9814 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9815 
9816 		if (connp == NULL)
9817 			return (ENOMEM);
9818 
9819 		connp->conn_flags |= IPCL_TCPMOD;
9820 		connp->conn_cred = credp;
9821 		connp->conn_zoneid = zoneid;
9822 		q->q_ptr = WR(q)->q_ptr = connp;
9823 		crhold(credp);
9824 		q->q_qinfo = &tcp_mod_rinit;
9825 		WR(q)->q_qinfo = &tcp_mod_winit;
9826 		qprocson(q);
9827 		return (0);
9828 	}
9829 
9830 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9831 		return (EBUSY);
9832 
9833 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9834 
9835 	if (flag & SO_ACCEPTOR) {
9836 		q->q_qinfo = &tcp_acceptor_rinit;
9837 		q->q_ptr = (void *)conn_dev;
9838 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9839 		WR(q)->q_ptr = (void *)conn_dev;
9840 		qprocson(q);
9841 		return (0);
9842 	}
9843 
9844 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9845 	if (connp == NULL) {
9846 		inet_minor_free(ip_minor_arena, conn_dev);
9847 		q->q_ptr = NULL;
9848 		return (ENOSR);
9849 	}
9850 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9851 	tcp = connp->conn_tcp;
9852 
9853 	q->q_ptr = WR(q)->q_ptr = connp;
9854 	if (getmajor(*devp) == TCP6_MAJ) {
9855 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9856 		connp->conn_send = ip_output_v6;
9857 		connp->conn_af_isv6 = B_TRUE;
9858 		connp->conn_pkt_isv6 = B_TRUE;
9859 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9860 		tcp->tcp_ipversion = IPV6_VERSION;
9861 		tcp->tcp_family = AF_INET6;
9862 		tcp->tcp_mss = tcp_mss_def_ipv6;
9863 	} else {
9864 		connp->conn_flags |= IPCL_TCP4;
9865 		connp->conn_send = ip_output;
9866 		connp->conn_af_isv6 = B_FALSE;
9867 		connp->conn_pkt_isv6 = B_FALSE;
9868 		tcp->tcp_ipversion = IPV4_VERSION;
9869 		tcp->tcp_family = AF_INET;
9870 		tcp->tcp_mss = tcp_mss_def_ipv4;
9871 	}
9872 
9873 	/*
9874 	 * TCP keeps a copy of cred for cache locality reasons but
9875 	 * we put a reference only once. If connp->conn_cred
9876 	 * becomes invalid, tcp_cred should also be set to NULL.
9877 	 */
9878 	tcp->tcp_cred = connp->conn_cred = credp;
9879 	crhold(connp->conn_cred);
9880 	tcp->tcp_cpid = curproc->p_pid;
9881 	connp->conn_zoneid = zoneid;
9882 
9883 	connp->conn_dev = conn_dev;
9884 
9885 	ASSERT(q->q_qinfo == &tcp_rinit);
9886 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9887 
9888 	if (flag & SO_SOCKSTR) {
9889 		/*
9890 		 * No need to insert a socket in tcp acceptor hash.
9891 		 * If it was a socket acceptor stream, we dealt with
9892 		 * it above. A socket listener can never accept a
9893 		 * connection and doesn't need acceptor_id.
9894 		 */
9895 		connp->conn_flags |= IPCL_SOCKET;
9896 		tcp->tcp_issocket = 1;
9897 
9898 		WR(q)->q_qinfo = &tcp_sock_winit;
9899 	} else {
9900 #ifdef	_ILP32
9901 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9902 #else
9903 		tcp->tcp_acceptor_id = conn_dev;
9904 #endif	/* _ILP32 */
9905 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9906 	}
9907 
9908 	if (tcp_trace)
9909 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9910 
9911 	err = tcp_init(tcp, q);
9912 	if (err != 0) {
9913 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9914 		tcp_acceptor_hash_remove(tcp);
9915 		CONN_DEC_REF(connp);
9916 		q->q_ptr = WR(q)->q_ptr = NULL;
9917 		return (err);
9918 	}
9919 
9920 	RD(q)->q_hiwat = tcp_recv_hiwat;
9921 	tcp->tcp_rwnd = tcp_recv_hiwat;
9922 
9923 	/* Non-zero default values */
9924 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9925 	/*
9926 	 * Put the ref for TCP. Ref for IP was already put
9927 	 * by ipcl_conn_create. Also Make the conn_t globally
9928 	 * visible to walkers
9929 	 */
9930 	mutex_enter(&connp->conn_lock);
9931 	CONN_INC_REF_LOCKED(connp);
9932 	ASSERT(connp->conn_ref == 2);
9933 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9934 	mutex_exit(&connp->conn_lock);
9935 
9936 	qprocson(q);
9937 	return (0);
9938 }
9939 
9940 /*
9941  * Some TCP options can be "set" by requesting them in the option
9942  * buffer. This is needed for XTI feature test though we do not
9943  * allow it in general. We interpret that this mechanism is more
9944  * applicable to OSI protocols and need not be allowed in general.
9945  * This routine filters out options for which it is not allowed (most)
9946  * and lets through those (few) for which it is. [ The XTI interface
9947  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9948  * ever implemented will have to be allowed here ].
9949  */
9950 static boolean_t
9951 tcp_allow_connopt_set(int level, int name)
9952 {
9953 
9954 	switch (level) {
9955 	case IPPROTO_TCP:
9956 		switch (name) {
9957 		case TCP_NODELAY:
9958 			return (B_TRUE);
9959 		default:
9960 			return (B_FALSE);
9961 		}
9962 		/*NOTREACHED*/
9963 	default:
9964 		return (B_FALSE);
9965 	}
9966 	/*NOTREACHED*/
9967 }
9968 
9969 /*
9970  * This routine gets default values of certain options whose default
9971  * values are maintained by protocol specific code
9972  */
9973 /* ARGSUSED */
9974 int
9975 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9976 {
9977 	int32_t	*i1 = (int32_t *)ptr;
9978 
9979 	switch (level) {
9980 	case IPPROTO_TCP:
9981 		switch (name) {
9982 		case TCP_NOTIFY_THRESHOLD:
9983 			*i1 = tcp_ip_notify_interval;
9984 			break;
9985 		case TCP_ABORT_THRESHOLD:
9986 			*i1 = tcp_ip_abort_interval;
9987 			break;
9988 		case TCP_CONN_NOTIFY_THRESHOLD:
9989 			*i1 = tcp_ip_notify_cinterval;
9990 			break;
9991 		case TCP_CONN_ABORT_THRESHOLD:
9992 			*i1 = tcp_ip_abort_cinterval;
9993 			break;
9994 		default:
9995 			return (-1);
9996 		}
9997 		break;
9998 	case IPPROTO_IP:
9999 		switch (name) {
10000 		case IP_TTL:
10001 			*i1 = tcp_ipv4_ttl;
10002 			break;
10003 		default:
10004 			return (-1);
10005 		}
10006 		break;
10007 	case IPPROTO_IPV6:
10008 		switch (name) {
10009 		case IPV6_UNICAST_HOPS:
10010 			*i1 = tcp_ipv6_hoplimit;
10011 			break;
10012 		default:
10013 			return (-1);
10014 		}
10015 		break;
10016 	default:
10017 		return (-1);
10018 	}
10019 	return (sizeof (int));
10020 }
10021 
10022 
10023 /*
10024  * TCP routine to get the values of options.
10025  */
10026 int
10027 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
10028 {
10029 	int		*i1 = (int *)ptr;
10030 	conn_t		*connp = Q_TO_CONN(q);
10031 	tcp_t		*tcp = connp->conn_tcp;
10032 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
10033 
10034 	switch (level) {
10035 	case SOL_SOCKET:
10036 		switch (name) {
10037 		case SO_LINGER:	{
10038 			struct linger *lgr = (struct linger *)ptr;
10039 
10040 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
10041 			lgr->l_linger = tcp->tcp_lingertime;
10042 			}
10043 			return (sizeof (struct linger));
10044 		case SO_DEBUG:
10045 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
10046 			break;
10047 		case SO_KEEPALIVE:
10048 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
10049 			break;
10050 		case SO_DONTROUTE:
10051 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
10052 			break;
10053 		case SO_USELOOPBACK:
10054 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
10055 			break;
10056 		case SO_BROADCAST:
10057 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
10058 			break;
10059 		case SO_REUSEADDR:
10060 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
10061 			break;
10062 		case SO_OOBINLINE:
10063 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
10064 			break;
10065 		case SO_DGRAM_ERRIND:
10066 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
10067 			break;
10068 		case SO_TYPE:
10069 			*i1 = SOCK_STREAM;
10070 			break;
10071 		case SO_SNDBUF:
10072 			*i1 = tcp->tcp_xmit_hiwater;
10073 			break;
10074 		case SO_RCVBUF:
10075 			*i1 = RD(q)->q_hiwat;
10076 			break;
10077 		case SO_SND_COPYAVOID:
10078 			*i1 = tcp->tcp_snd_zcopy_on ?
10079 			    SO_SND_COPYAVOID : 0;
10080 			break;
10081 		default:
10082 			return (-1);
10083 		}
10084 		break;
10085 	case IPPROTO_TCP:
10086 		switch (name) {
10087 		case TCP_NODELAY:
10088 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10089 			break;
10090 		case TCP_MAXSEG:
10091 			*i1 = tcp->tcp_mss;
10092 			break;
10093 		case TCP_NOTIFY_THRESHOLD:
10094 			*i1 = (int)tcp->tcp_first_timer_threshold;
10095 			break;
10096 		case TCP_ABORT_THRESHOLD:
10097 			*i1 = tcp->tcp_second_timer_threshold;
10098 			break;
10099 		case TCP_CONN_NOTIFY_THRESHOLD:
10100 			*i1 = tcp->tcp_first_ctimer_threshold;
10101 			break;
10102 		case TCP_CONN_ABORT_THRESHOLD:
10103 			*i1 = tcp->tcp_second_ctimer_threshold;
10104 			break;
10105 		case TCP_RECVDSTADDR:
10106 			*i1 = tcp->tcp_recvdstaddr;
10107 			break;
10108 		case TCP_ANONPRIVBIND:
10109 			*i1 = tcp->tcp_anon_priv_bind;
10110 			break;
10111 		case TCP_EXCLBIND:
10112 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10113 			break;
10114 		case TCP_INIT_CWND:
10115 			*i1 = tcp->tcp_init_cwnd;
10116 			break;
10117 		case TCP_KEEPALIVE_THRESHOLD:
10118 			*i1 = tcp->tcp_ka_interval;
10119 			break;
10120 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10121 			*i1 = tcp->tcp_ka_abort_thres;
10122 			break;
10123 		case TCP_CORK:
10124 			*i1 = tcp->tcp_cork;
10125 			break;
10126 		default:
10127 			return (-1);
10128 		}
10129 		break;
10130 	case IPPROTO_IP:
10131 		if (tcp->tcp_family != AF_INET)
10132 			return (-1);
10133 		switch (name) {
10134 		case IP_OPTIONS:
10135 		case T_IP_OPTIONS: {
10136 			/*
10137 			 * This is compatible with BSD in that in only return
10138 			 * the reverse source route with the final destination
10139 			 * as the last entry. The first 4 bytes of the option
10140 			 * will contain the final destination.
10141 			 */
10142 			char	*opt_ptr;
10143 			int	opt_len;
10144 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10145 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
10146 			/* Caller ensures enough space */
10147 			if (opt_len > 0) {
10148 				/*
10149 				 * TODO: Do we have to handle getsockopt on an
10150 				 * initiator as well?
10151 				 */
10152 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
10153 			}
10154 			return (0);
10155 			}
10156 		case IP_TOS:
10157 		case T_IP_TOS:
10158 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10159 			break;
10160 		case IP_TTL:
10161 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10162 			break;
10163 		default:
10164 			return (-1);
10165 		}
10166 		break;
10167 	case IPPROTO_IPV6:
10168 		/*
10169 		 * IPPROTO_IPV6 options are only supported for sockets
10170 		 * that are using IPv6 on the wire.
10171 		 */
10172 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10173 			return (-1);
10174 		}
10175 		switch (name) {
10176 		case IPV6_UNICAST_HOPS:
10177 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10178 			break;	/* goto sizeof (int) option return */
10179 		case IPV6_BOUND_IF:
10180 			/* Zero if not set */
10181 			*i1 = tcp->tcp_bound_if;
10182 			break;	/* goto sizeof (int) option return */
10183 		case IPV6_RECVPKTINFO:
10184 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10185 				*i1 = 1;
10186 			else
10187 				*i1 = 0;
10188 			break;	/* goto sizeof (int) option return */
10189 		case IPV6_RECVTCLASS:
10190 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10191 				*i1 = 1;
10192 			else
10193 				*i1 = 0;
10194 			break;	/* goto sizeof (int) option return */
10195 		case IPV6_RECVHOPLIMIT:
10196 			if (tcp->tcp_ipv6_recvancillary &
10197 			    TCP_IPV6_RECVHOPLIMIT)
10198 				*i1 = 1;
10199 			else
10200 				*i1 = 0;
10201 			break;	/* goto sizeof (int) option return */
10202 		case IPV6_RECVHOPOPTS:
10203 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10204 				*i1 = 1;
10205 			else
10206 				*i1 = 0;
10207 			break;	/* goto sizeof (int) option return */
10208 		case IPV6_RECVDSTOPTS:
10209 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10210 				*i1 = 1;
10211 			else
10212 				*i1 = 0;
10213 			break;	/* goto sizeof (int) option return */
10214 		case _OLD_IPV6_RECVDSTOPTS:
10215 			if (tcp->tcp_ipv6_recvancillary &
10216 			    TCP_OLD_IPV6_RECVDSTOPTS)
10217 				*i1 = 1;
10218 			else
10219 				*i1 = 0;
10220 			break;	/* goto sizeof (int) option return */
10221 		case IPV6_RECVRTHDR:
10222 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10223 				*i1 = 1;
10224 			else
10225 				*i1 = 0;
10226 			break;	/* goto sizeof (int) option return */
10227 		case IPV6_RECVRTHDRDSTOPTS:
10228 			if (tcp->tcp_ipv6_recvancillary &
10229 			    TCP_IPV6_RECVRTDSTOPTS)
10230 				*i1 = 1;
10231 			else
10232 				*i1 = 0;
10233 			break;	/* goto sizeof (int) option return */
10234 		case IPV6_PKTINFO: {
10235 			/* XXX assumes that caller has room for max size! */
10236 			struct in6_pktinfo *pkti;
10237 
10238 			pkti = (struct in6_pktinfo *)ptr;
10239 			if (ipp->ipp_fields & IPPF_IFINDEX)
10240 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10241 			else
10242 				pkti->ipi6_ifindex = 0;
10243 			if (ipp->ipp_fields & IPPF_ADDR)
10244 				pkti->ipi6_addr = ipp->ipp_addr;
10245 			else
10246 				pkti->ipi6_addr = ipv6_all_zeros;
10247 			return (sizeof (struct in6_pktinfo));
10248 		}
10249 		case IPV6_TCLASS:
10250 			if (ipp->ipp_fields & IPPF_TCLASS)
10251 				*i1 = ipp->ipp_tclass;
10252 			else
10253 				*i1 = IPV6_FLOW_TCLASS(
10254 				    IPV6_DEFAULT_VERS_AND_FLOW);
10255 			break;	/* goto sizeof (int) option return */
10256 		case IPV6_NEXTHOP: {
10257 			sin6_t *sin6 = (sin6_t *)ptr;
10258 
10259 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10260 				return (0);
10261 			*sin6 = sin6_null;
10262 			sin6->sin6_family = AF_INET6;
10263 			sin6->sin6_addr = ipp->ipp_nexthop;
10264 			return (sizeof (sin6_t));
10265 		}
10266 		case IPV6_HOPOPTS:
10267 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10268 				return (0);
10269 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
10270 			return (ipp->ipp_hopoptslen);
10271 		case IPV6_RTHDRDSTOPTS:
10272 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10273 				return (0);
10274 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10275 			return (ipp->ipp_rtdstoptslen);
10276 		case IPV6_RTHDR:
10277 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10278 				return (0);
10279 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10280 			return (ipp->ipp_rthdrlen);
10281 		case IPV6_DSTOPTS:
10282 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10283 				return (0);
10284 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10285 			return (ipp->ipp_dstoptslen);
10286 		case IPV6_SRC_PREFERENCES:
10287 			return (ip6_get_src_preferences(connp,
10288 			    (uint32_t *)ptr));
10289 		case IPV6_PATHMTU: {
10290 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10291 
10292 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10293 				return (-1);
10294 
10295 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10296 				connp->conn_fport, mtuinfo));
10297 		}
10298 		default:
10299 			return (-1);
10300 		}
10301 		break;
10302 	default:
10303 		return (-1);
10304 	}
10305 	return (sizeof (int));
10306 }
10307 
10308 /*
10309  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10310  * Parameters are assumed to be verified by the caller.
10311  */
10312 /* ARGSUSED */
10313 int
10314 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10315     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10316     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10317 {
10318 	tcp_t	*tcp = Q_TO_TCP(q);
10319 	int	*i1 = (int *)invalp;
10320 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10321 	boolean_t checkonly;
10322 	int	reterr;
10323 
10324 	switch (optset_context) {
10325 	case SETFN_OPTCOM_CHECKONLY:
10326 		checkonly = B_TRUE;
10327 		/*
10328 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10329 		 * inlen != 0 implies value supplied and
10330 		 * 	we have to "pretend" to set it.
10331 		 * inlen == 0 implies that there is no
10332 		 * 	value part in T_CHECK request and just validation
10333 		 * done elsewhere should be enough, we just return here.
10334 		 */
10335 		if (inlen == 0) {
10336 			*outlenp = 0;
10337 			return (0);
10338 		}
10339 		break;
10340 	case SETFN_OPTCOM_NEGOTIATE:
10341 		checkonly = B_FALSE;
10342 		break;
10343 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10344 	case SETFN_CONN_NEGOTIATE:
10345 		checkonly = B_FALSE;
10346 		/*
10347 		 * Negotiating local and "association-related" options
10348 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10349 		 * primitives is allowed by XTI, but we choose
10350 		 * to not implement this style negotiation for Internet
10351 		 * protocols (We interpret it is a must for OSI world but
10352 		 * optional for Internet protocols) for all options.
10353 		 * [ Will do only for the few options that enable test
10354 		 * suites that our XTI implementation of this feature
10355 		 * works for transports that do allow it ]
10356 		 */
10357 		if (!tcp_allow_connopt_set(level, name)) {
10358 			*outlenp = 0;
10359 			return (EINVAL);
10360 		}
10361 		break;
10362 	default:
10363 		/*
10364 		 * We should never get here
10365 		 */
10366 		*outlenp = 0;
10367 		return (EINVAL);
10368 	}
10369 
10370 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10371 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10372 
10373 	/*
10374 	 * For TCP, we should have no ancillary data sent down
10375 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10376 	 * has to be zero.
10377 	 */
10378 	ASSERT(thisdg_attrs == NULL);
10379 
10380 	/*
10381 	 * For fixed length options, no sanity check
10382 	 * of passed in length is done. It is assumed *_optcom_req()
10383 	 * routines do the right thing.
10384 	 */
10385 
10386 	switch (level) {
10387 	case SOL_SOCKET:
10388 		switch (name) {
10389 		case SO_LINGER: {
10390 			struct linger *lgr = (struct linger *)invalp;
10391 
10392 			if (!checkonly) {
10393 				if (lgr->l_onoff) {
10394 					tcp->tcp_linger = 1;
10395 					tcp->tcp_lingertime = lgr->l_linger;
10396 				} else {
10397 					tcp->tcp_linger = 0;
10398 					tcp->tcp_lingertime = 0;
10399 				}
10400 				/* struct copy */
10401 				*(struct linger *)outvalp = *lgr;
10402 			} else {
10403 				if (!lgr->l_onoff) {
10404 				    ((struct linger *)outvalp)->l_onoff = 0;
10405 				    ((struct linger *)outvalp)->l_linger = 0;
10406 				} else {
10407 				    /* struct copy */
10408 				    *(struct linger *)outvalp = *lgr;
10409 				}
10410 			}
10411 			*outlenp = sizeof (struct linger);
10412 			return (0);
10413 		}
10414 		case SO_DEBUG:
10415 			if (!checkonly)
10416 				tcp->tcp_debug = onoff;
10417 			break;
10418 		case SO_KEEPALIVE:
10419 			if (checkonly) {
10420 				/* T_CHECK case */
10421 				break;
10422 			}
10423 
10424 			if (!onoff) {
10425 				if (tcp->tcp_ka_enabled) {
10426 					if (tcp->tcp_ka_tid != 0) {
10427 						(void) TCP_TIMER_CANCEL(tcp,
10428 						    tcp->tcp_ka_tid);
10429 						tcp->tcp_ka_tid = 0;
10430 					}
10431 					tcp->tcp_ka_enabled = 0;
10432 				}
10433 				break;
10434 			}
10435 			if (!tcp->tcp_ka_enabled) {
10436 				/* Crank up the keepalive timer */
10437 				tcp->tcp_ka_last_intrvl = 0;
10438 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10439 				    tcp_keepalive_killer,
10440 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10441 				tcp->tcp_ka_enabled = 1;
10442 			}
10443 			break;
10444 		case SO_DONTROUTE:
10445 			/*
10446 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
10447 			 * only of interest to IP.  We track them here only so
10448 			 * that we can report their current value.
10449 			 */
10450 			if (!checkonly) {
10451 				tcp->tcp_dontroute = onoff;
10452 				tcp->tcp_connp->conn_dontroute = onoff;
10453 			}
10454 			break;
10455 		case SO_USELOOPBACK:
10456 			if (!checkonly) {
10457 				tcp->tcp_useloopback = onoff;
10458 				tcp->tcp_connp->conn_loopback = onoff;
10459 			}
10460 			break;
10461 		case SO_BROADCAST:
10462 			if (!checkonly) {
10463 				tcp->tcp_broadcast = onoff;
10464 				tcp->tcp_connp->conn_broadcast = onoff;
10465 			}
10466 			break;
10467 		case SO_REUSEADDR:
10468 			if (!checkonly) {
10469 				tcp->tcp_reuseaddr = onoff;
10470 				tcp->tcp_connp->conn_reuseaddr = onoff;
10471 			}
10472 			break;
10473 		case SO_OOBINLINE:
10474 			if (!checkonly)
10475 				tcp->tcp_oobinline = onoff;
10476 			break;
10477 		case SO_DGRAM_ERRIND:
10478 			if (!checkonly)
10479 				tcp->tcp_dgram_errind = onoff;
10480 			break;
10481 		case SO_SNDBUF:
10482 			if (*i1 > tcp_max_buf) {
10483 				*outlenp = 0;
10484 				return (ENOBUFS);
10485 			}
10486 			if (!checkonly) {
10487 				tcp->tcp_xmit_hiwater = *i1;
10488 				if (tcp_snd_lowat_fraction != 0)
10489 					tcp->tcp_xmit_lowater =
10490 					    tcp->tcp_xmit_hiwater /
10491 					    tcp_snd_lowat_fraction;
10492 				(void) tcp_maxpsz_set(tcp, B_TRUE);
10493 				/*
10494 				 * If we are flow-controlled, recheck the
10495 				 * condition. There are apps that increase
10496 				 * SO_SNDBUF size when flow-controlled
10497 				 * (EWOULDBLOCK), and expect the flow control
10498 				 * condition to be lifted right away.
10499 				 */
10500 				if (tcp->tcp_flow_stopped &&
10501 				    TCP_UNSENT_BYTES(tcp)
10502 				    < tcp->tcp_xmit_hiwater) {
10503 					tcp_clrqfull(tcp);
10504 				}
10505 			}
10506 			break;
10507 		case SO_RCVBUF:
10508 			if (*i1 > tcp_max_buf) {
10509 				*outlenp = 0;
10510 				return (ENOBUFS);
10511 			}
10512 			/* Silently ignore zero */
10513 			if (!checkonly && *i1 != 0) {
10514 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10515 				(void) tcp_rwnd_set(tcp, *i1);
10516 			}
10517 			/*
10518 			 * XXX should we return the rwnd here
10519 			 * and tcp_opt_get ?
10520 			 */
10521 			break;
10522 		case SO_SND_COPYAVOID:
10523 			if (!checkonly) {
10524 				/* we only allow enable at most once for now */
10525 				if (tcp->tcp_loopback ||
10526 				    (!tcp->tcp_snd_zcopy_aware &&
10527 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10528 					*outlenp = 0;
10529 					return (EOPNOTSUPP);
10530 				}
10531 				tcp->tcp_snd_zcopy_aware = 1;
10532 			}
10533 			break;
10534 		default:
10535 			*outlenp = 0;
10536 			return (EINVAL);
10537 		}
10538 		break;
10539 	case IPPROTO_TCP:
10540 		switch (name) {
10541 		case TCP_NODELAY:
10542 			if (!checkonly)
10543 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10544 			break;
10545 		case TCP_NOTIFY_THRESHOLD:
10546 			if (!checkonly)
10547 				tcp->tcp_first_timer_threshold = *i1;
10548 			break;
10549 		case TCP_ABORT_THRESHOLD:
10550 			if (!checkonly)
10551 				tcp->tcp_second_timer_threshold = *i1;
10552 			break;
10553 		case TCP_CONN_NOTIFY_THRESHOLD:
10554 			if (!checkonly)
10555 				tcp->tcp_first_ctimer_threshold = *i1;
10556 			break;
10557 		case TCP_CONN_ABORT_THRESHOLD:
10558 			if (!checkonly)
10559 				tcp->tcp_second_ctimer_threshold = *i1;
10560 			break;
10561 		case TCP_RECVDSTADDR:
10562 			if (tcp->tcp_state > TCPS_LISTEN)
10563 				return (EOPNOTSUPP);
10564 			if (!checkonly)
10565 				tcp->tcp_recvdstaddr = onoff;
10566 			break;
10567 		case TCP_ANONPRIVBIND:
10568 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10569 				*outlenp = 0;
10570 				return (reterr);
10571 			}
10572 			if (!checkonly) {
10573 				tcp->tcp_anon_priv_bind = onoff;
10574 			}
10575 			break;
10576 		case TCP_EXCLBIND:
10577 			if (!checkonly)
10578 				tcp->tcp_exclbind = onoff;
10579 			break;	/* goto sizeof (int) option return */
10580 		case TCP_INIT_CWND: {
10581 			uint32_t init_cwnd = *((uint32_t *)invalp);
10582 
10583 			if (checkonly)
10584 				break;
10585 
10586 			/*
10587 			 * Only allow socket with network configuration
10588 			 * privilege to set the initial cwnd to be larger
10589 			 * than allowed by RFC 3390.
10590 			 */
10591 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10592 				tcp->tcp_init_cwnd = init_cwnd;
10593 				break;
10594 			}
10595 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10596 				*outlenp = 0;
10597 				return (reterr);
10598 			}
10599 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10600 				*outlenp = 0;
10601 				return (EINVAL);
10602 			}
10603 			tcp->tcp_init_cwnd = init_cwnd;
10604 			break;
10605 		}
10606 		case TCP_KEEPALIVE_THRESHOLD:
10607 			if (checkonly)
10608 				break;
10609 
10610 			if (*i1 < tcp_keepalive_interval_low ||
10611 			    *i1 > tcp_keepalive_interval_high) {
10612 				*outlenp = 0;
10613 				return (EINVAL);
10614 			}
10615 			if (*i1 != tcp->tcp_ka_interval) {
10616 				tcp->tcp_ka_interval = *i1;
10617 				/*
10618 				 * Check if we need to restart the
10619 				 * keepalive timer.
10620 				 */
10621 				if (tcp->tcp_ka_tid != 0) {
10622 					ASSERT(tcp->tcp_ka_enabled);
10623 					(void) TCP_TIMER_CANCEL(tcp,
10624 					    tcp->tcp_ka_tid);
10625 					tcp->tcp_ka_last_intrvl = 0;
10626 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10627 					    tcp_keepalive_killer,
10628 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10629 				}
10630 			}
10631 			break;
10632 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10633 			if (!checkonly) {
10634 				if (*i1 < tcp_keepalive_abort_interval_low ||
10635 				    *i1 > tcp_keepalive_abort_interval_high) {
10636 					*outlenp = 0;
10637 					return (EINVAL);
10638 				}
10639 				tcp->tcp_ka_abort_thres = *i1;
10640 			}
10641 			break;
10642 		case TCP_CORK:
10643 			if (!checkonly) {
10644 				/*
10645 				 * if tcp->tcp_cork was set and is now
10646 				 * being unset, we have to make sure that
10647 				 * the remaining data gets sent out. Also
10648 				 * unset tcp->tcp_cork so that tcp_wput_data()
10649 				 * can send data even if it is less than mss
10650 				 */
10651 				if (tcp->tcp_cork && onoff == 0 &&
10652 				    tcp->tcp_unsent > 0) {
10653 					tcp->tcp_cork = B_FALSE;
10654 					tcp_wput_data(tcp, NULL, B_FALSE);
10655 				}
10656 				tcp->tcp_cork = onoff;
10657 			}
10658 			break;
10659 		default:
10660 			*outlenp = 0;
10661 			return (EINVAL);
10662 		}
10663 		break;
10664 	case IPPROTO_IP:
10665 		if (tcp->tcp_family != AF_INET) {
10666 			*outlenp = 0;
10667 			return (ENOPROTOOPT);
10668 		}
10669 		switch (name) {
10670 		case IP_OPTIONS:
10671 		case T_IP_OPTIONS:
10672 			reterr = tcp_opt_set_header(tcp, checkonly,
10673 			    invalp, inlen);
10674 			if (reterr) {
10675 				*outlenp = 0;
10676 				return (reterr);
10677 			}
10678 			/* OK return - copy input buffer into output buffer */
10679 			if (invalp != outvalp) {
10680 				/* don't trust bcopy for identical src/dst */
10681 				bcopy(invalp, outvalp, inlen);
10682 			}
10683 			*outlenp = inlen;
10684 			return (0);
10685 		case IP_TOS:
10686 		case T_IP_TOS:
10687 			if (!checkonly) {
10688 				tcp->tcp_ipha->ipha_type_of_service =
10689 				    (uchar_t)*i1;
10690 				tcp->tcp_tos = (uchar_t)*i1;
10691 			}
10692 			break;
10693 		case IP_TTL:
10694 			if (!checkonly) {
10695 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10696 				tcp->tcp_ttl = (uchar_t)*i1;
10697 			}
10698 			break;
10699 		case IP_BOUND_IF:
10700 			/* Handled at the IP level */
10701 			return (-EINVAL);
10702 		case IP_SEC_OPT:
10703 			/*
10704 			 * We should not allow policy setting after
10705 			 * we start listening for connections.
10706 			 */
10707 			if (tcp->tcp_state == TCPS_LISTEN) {
10708 				return (EINVAL);
10709 			} else {
10710 				/* Handled at the IP level */
10711 				return (-EINVAL);
10712 			}
10713 		default:
10714 			*outlenp = 0;
10715 			return (EINVAL);
10716 		}
10717 		break;
10718 	case IPPROTO_IPV6: {
10719 		ip6_pkt_t		*ipp;
10720 
10721 		/*
10722 		 * IPPROTO_IPV6 options are only supported for sockets
10723 		 * that are using IPv6 on the wire.
10724 		 */
10725 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10726 			*outlenp = 0;
10727 			return (ENOPROTOOPT);
10728 		}
10729 		/*
10730 		 * Only sticky options; no ancillary data
10731 		 */
10732 		ASSERT(thisdg_attrs == NULL);
10733 		ipp = &tcp->tcp_sticky_ipp;
10734 
10735 		switch (name) {
10736 		case IPV6_UNICAST_HOPS:
10737 			/* -1 means use default */
10738 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10739 				*outlenp = 0;
10740 				return (EINVAL);
10741 			}
10742 			if (!checkonly) {
10743 				if (*i1 == -1) {
10744 					tcp->tcp_ip6h->ip6_hops =
10745 					    ipp->ipp_unicast_hops =
10746 					    (uint8_t)tcp_ipv6_hoplimit;
10747 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10748 					/* Pass modified value to IP. */
10749 					*i1 = tcp->tcp_ip6h->ip6_hops;
10750 				} else {
10751 					tcp->tcp_ip6h->ip6_hops =
10752 					    ipp->ipp_unicast_hops =
10753 					    (uint8_t)*i1;
10754 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10755 				}
10756 				reterr = tcp_build_hdrs(q, tcp);
10757 				if (reterr != 0)
10758 					return (reterr);
10759 			}
10760 			break;
10761 		case IPV6_BOUND_IF:
10762 			if (!checkonly) {
10763 				int error = 0;
10764 
10765 				tcp->tcp_bound_if = *i1;
10766 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10767 				    B_TRUE, checkonly, level, name, mblk);
10768 				if (error != 0) {
10769 					*outlenp = 0;
10770 					return (error);
10771 				}
10772 			}
10773 			break;
10774 		/*
10775 		 * Set boolean switches for ancillary data delivery
10776 		 */
10777 		case IPV6_RECVPKTINFO:
10778 			if (!checkonly) {
10779 				if (onoff)
10780 					tcp->tcp_ipv6_recvancillary |=
10781 					    TCP_IPV6_RECVPKTINFO;
10782 				else
10783 					tcp->tcp_ipv6_recvancillary &=
10784 					    ~TCP_IPV6_RECVPKTINFO;
10785 				/* Force it to be sent up with the next msg */
10786 				tcp->tcp_recvifindex = 0;
10787 			}
10788 			break;
10789 		case IPV6_RECVTCLASS:
10790 			if (!checkonly) {
10791 				if (onoff)
10792 					tcp->tcp_ipv6_recvancillary |=
10793 					    TCP_IPV6_RECVTCLASS;
10794 				else
10795 					tcp->tcp_ipv6_recvancillary &=
10796 					    ~TCP_IPV6_RECVTCLASS;
10797 			}
10798 			break;
10799 		case IPV6_RECVHOPLIMIT:
10800 			if (!checkonly) {
10801 				if (onoff)
10802 					tcp->tcp_ipv6_recvancillary |=
10803 					    TCP_IPV6_RECVHOPLIMIT;
10804 				else
10805 					tcp->tcp_ipv6_recvancillary &=
10806 					    ~TCP_IPV6_RECVHOPLIMIT;
10807 				/* Force it to be sent up with the next msg */
10808 				tcp->tcp_recvhops = 0xffffffffU;
10809 			}
10810 			break;
10811 		case IPV6_RECVHOPOPTS:
10812 			if (!checkonly) {
10813 				if (onoff)
10814 					tcp->tcp_ipv6_recvancillary |=
10815 					    TCP_IPV6_RECVHOPOPTS;
10816 				else
10817 					tcp->tcp_ipv6_recvancillary &=
10818 					    ~TCP_IPV6_RECVHOPOPTS;
10819 			}
10820 			break;
10821 		case IPV6_RECVDSTOPTS:
10822 			if (!checkonly) {
10823 				if (onoff)
10824 					tcp->tcp_ipv6_recvancillary |=
10825 					    TCP_IPV6_RECVDSTOPTS;
10826 				else
10827 					tcp->tcp_ipv6_recvancillary &=
10828 					    ~TCP_IPV6_RECVDSTOPTS;
10829 			}
10830 			break;
10831 		case _OLD_IPV6_RECVDSTOPTS:
10832 			if (!checkonly) {
10833 				if (onoff)
10834 					tcp->tcp_ipv6_recvancillary |=
10835 					    TCP_OLD_IPV6_RECVDSTOPTS;
10836 				else
10837 					tcp->tcp_ipv6_recvancillary &=
10838 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10839 			}
10840 			break;
10841 		case IPV6_RECVRTHDR:
10842 			if (!checkonly) {
10843 				if (onoff)
10844 					tcp->tcp_ipv6_recvancillary |=
10845 					    TCP_IPV6_RECVRTHDR;
10846 				else
10847 					tcp->tcp_ipv6_recvancillary &=
10848 					    ~TCP_IPV6_RECVRTHDR;
10849 			}
10850 			break;
10851 		case IPV6_RECVRTHDRDSTOPTS:
10852 			if (!checkonly) {
10853 				if (onoff)
10854 					tcp->tcp_ipv6_recvancillary |=
10855 					    TCP_IPV6_RECVRTDSTOPTS;
10856 				else
10857 					tcp->tcp_ipv6_recvancillary &=
10858 					    ~TCP_IPV6_RECVRTDSTOPTS;
10859 			}
10860 			break;
10861 		case IPV6_PKTINFO:
10862 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10863 				return (EINVAL);
10864 			if (checkonly)
10865 				break;
10866 
10867 			if (inlen == 0) {
10868 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10869 			} else {
10870 				struct in6_pktinfo *pkti;
10871 
10872 				pkti = (struct in6_pktinfo *)invalp;
10873 				/*
10874 				 * RFC 3542 states that ipi6_addr must be
10875 				 * the unspecified address when setting the
10876 				 * IPV6_PKTINFO sticky socket option on a
10877 				 * TCP socket.
10878 				 */
10879 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10880 					return (EINVAL);
10881 				/*
10882 				 * ip6_set_pktinfo() validates the source
10883 				 * address and interface index.
10884 				 */
10885 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10886 				    pkti, mblk);
10887 				if (reterr != 0)
10888 					return (reterr);
10889 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10890 				ipp->ipp_addr = pkti->ipi6_addr;
10891 				if (ipp->ipp_ifindex != 0)
10892 					ipp->ipp_fields |= IPPF_IFINDEX;
10893 				else
10894 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10895 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10896 					ipp->ipp_fields |= IPPF_ADDR;
10897 				else
10898 					ipp->ipp_fields &= ~IPPF_ADDR;
10899 			}
10900 			reterr = tcp_build_hdrs(q, tcp);
10901 			if (reterr != 0)
10902 				return (reterr);
10903 			break;
10904 		case IPV6_TCLASS:
10905 			if (inlen != 0 && inlen != sizeof (int))
10906 				return (EINVAL);
10907 			if (checkonly)
10908 				break;
10909 
10910 			if (inlen == 0) {
10911 				ipp->ipp_fields &= ~IPPF_TCLASS;
10912 			} else {
10913 				if (*i1 > 255 || *i1 < -1)
10914 					return (EINVAL);
10915 				if (*i1 == -1) {
10916 					ipp->ipp_tclass = 0;
10917 					*i1 = 0;
10918 				} else {
10919 					ipp->ipp_tclass = *i1;
10920 				}
10921 				ipp->ipp_fields |= IPPF_TCLASS;
10922 			}
10923 			reterr = tcp_build_hdrs(q, tcp);
10924 			if (reterr != 0)
10925 				return (reterr);
10926 			break;
10927 		case IPV6_NEXTHOP:
10928 			/*
10929 			 * IP will verify that the nexthop is reachable
10930 			 * and fail for sticky options.
10931 			 */
10932 			if (inlen != 0 && inlen != sizeof (sin6_t))
10933 				return (EINVAL);
10934 			if (checkonly)
10935 				break;
10936 
10937 			if (inlen == 0) {
10938 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10939 			} else {
10940 				sin6_t *sin6 = (sin6_t *)invalp;
10941 
10942 				if (sin6->sin6_family != AF_INET6)
10943 					return (EAFNOSUPPORT);
10944 				if (IN6_IS_ADDR_V4MAPPED(
10945 				    &sin6->sin6_addr))
10946 					return (EADDRNOTAVAIL);
10947 				ipp->ipp_nexthop = sin6->sin6_addr;
10948 				if (!IN6_IS_ADDR_UNSPECIFIED(
10949 				    &ipp->ipp_nexthop))
10950 					ipp->ipp_fields |= IPPF_NEXTHOP;
10951 				else
10952 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10953 			}
10954 			reterr = tcp_build_hdrs(q, tcp);
10955 			if (reterr != 0)
10956 				return (reterr);
10957 			break;
10958 		case IPV6_HOPOPTS: {
10959 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10960 			/*
10961 			 * Sanity checks - minimum size, size a multiple of
10962 			 * eight bytes, and matching size passed in.
10963 			 */
10964 			if (inlen != 0 &&
10965 			    inlen != (8 * (hopts->ip6h_len + 1)))
10966 				return (EINVAL);
10967 
10968 			if (checkonly)
10969 				break;
10970 
10971 			if (inlen == 0) {
10972 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10973 					kmem_free(ipp->ipp_hopopts,
10974 					    ipp->ipp_hopoptslen);
10975 					ipp->ipp_hopopts = NULL;
10976 					ipp->ipp_hopoptslen = 0;
10977 				}
10978 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10979 			} else {
10980 				reterr = tcp_pkt_set(invalp, inlen,
10981 				    (uchar_t **)&ipp->ipp_hopopts,
10982 				    &ipp->ipp_hopoptslen);
10983 				if (reterr != 0)
10984 					return (reterr);
10985 				ipp->ipp_fields |= IPPF_HOPOPTS;
10986 			}
10987 			reterr = tcp_build_hdrs(q, tcp);
10988 			if (reterr != 0)
10989 				return (reterr);
10990 			break;
10991 		}
10992 		case IPV6_RTHDRDSTOPTS: {
10993 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10994 
10995 			/*
10996 			 * Sanity checks - minimum size, size a multiple of
10997 			 * eight bytes, and matching size passed in.
10998 			 */
10999 			if (inlen != 0 &&
11000 			    inlen != (8 * (dopts->ip6d_len + 1)))
11001 				return (EINVAL);
11002 
11003 			if (checkonly)
11004 				break;
11005 
11006 			if (inlen == 0) {
11007 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
11008 					kmem_free(ipp->ipp_rtdstopts,
11009 					    ipp->ipp_rtdstoptslen);
11010 					ipp->ipp_rtdstopts = NULL;
11011 					ipp->ipp_rtdstoptslen = 0;
11012 				}
11013 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
11014 			} else {
11015 				reterr = tcp_pkt_set(invalp, inlen,
11016 				    (uchar_t **)&ipp->ipp_rtdstopts,
11017 				    &ipp->ipp_rtdstoptslen);
11018 				if (reterr != 0)
11019 					return (reterr);
11020 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
11021 			}
11022 			reterr = tcp_build_hdrs(q, tcp);
11023 			if (reterr != 0)
11024 				return (reterr);
11025 			break;
11026 		}
11027 		case IPV6_DSTOPTS: {
11028 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11029 
11030 			/*
11031 			 * Sanity checks - minimum size, size a multiple of
11032 			 * eight bytes, and matching size passed in.
11033 			 */
11034 			if (inlen != 0 &&
11035 			    inlen != (8 * (dopts->ip6d_len + 1)))
11036 				return (EINVAL);
11037 
11038 			if (checkonly)
11039 				break;
11040 
11041 			if (inlen == 0) {
11042 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
11043 					kmem_free(ipp->ipp_dstopts,
11044 					    ipp->ipp_dstoptslen);
11045 					ipp->ipp_dstopts = NULL;
11046 					ipp->ipp_dstoptslen = 0;
11047 				}
11048 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11049 			} else {
11050 				reterr = tcp_pkt_set(invalp, inlen,
11051 				    (uchar_t **)&ipp->ipp_dstopts,
11052 				    &ipp->ipp_dstoptslen);
11053 				if (reterr != 0)
11054 					return (reterr);
11055 				ipp->ipp_fields |= IPPF_DSTOPTS;
11056 			}
11057 			reterr = tcp_build_hdrs(q, tcp);
11058 			if (reterr != 0)
11059 				return (reterr);
11060 			break;
11061 		}
11062 		case IPV6_RTHDR: {
11063 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11064 
11065 			/*
11066 			 * Sanity checks - minimum size, size a multiple of
11067 			 * eight bytes, and matching size passed in.
11068 			 */
11069 			if (inlen != 0 &&
11070 			    inlen != (8 * (rt->ip6r_len + 1)))
11071 				return (EINVAL);
11072 
11073 			if (checkonly)
11074 				break;
11075 
11076 			if (inlen == 0) {
11077 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
11078 					kmem_free(ipp->ipp_rthdr,
11079 					    ipp->ipp_rthdrlen);
11080 					ipp->ipp_rthdr = NULL;
11081 					ipp->ipp_rthdrlen = 0;
11082 				}
11083 				ipp->ipp_fields &= ~IPPF_RTHDR;
11084 			} else {
11085 				reterr = tcp_pkt_set(invalp, inlen,
11086 				    (uchar_t **)&ipp->ipp_rthdr,
11087 				    &ipp->ipp_rthdrlen);
11088 				if (reterr != 0)
11089 					return (reterr);
11090 				ipp->ipp_fields |= IPPF_RTHDR;
11091 			}
11092 			reterr = tcp_build_hdrs(q, tcp);
11093 			if (reterr != 0)
11094 				return (reterr);
11095 			break;
11096 		}
11097 		case IPV6_V6ONLY:
11098 			if (!checkonly)
11099 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11100 			break;
11101 		case IPV6_USE_MIN_MTU:
11102 			if (inlen != sizeof (int))
11103 				return (EINVAL);
11104 
11105 			if (*i1 < -1 || *i1 > 1)
11106 				return (EINVAL);
11107 
11108 			if (checkonly)
11109 				break;
11110 
11111 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11112 			ipp->ipp_use_min_mtu = *i1;
11113 			break;
11114 		case IPV6_BOUND_PIF:
11115 			/* Handled at the IP level */
11116 			return (-EINVAL);
11117 		case IPV6_SEC_OPT:
11118 			/*
11119 			 * We should not allow policy setting after
11120 			 * we start listening for connections.
11121 			 */
11122 			if (tcp->tcp_state == TCPS_LISTEN) {
11123 				return (EINVAL);
11124 			} else {
11125 				/* Handled at the IP level */
11126 				return (-EINVAL);
11127 			}
11128 		case IPV6_SRC_PREFERENCES:
11129 			if (inlen != sizeof (uint32_t))
11130 				return (EINVAL);
11131 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11132 			    *(uint32_t *)invalp);
11133 			if (reterr != 0) {
11134 				*outlenp = 0;
11135 				return (reterr);
11136 			}
11137 			break;
11138 		default:
11139 			*outlenp = 0;
11140 			return (EINVAL);
11141 		}
11142 		break;
11143 	}		/* end IPPROTO_IPV6 */
11144 	default:
11145 		*outlenp = 0;
11146 		return (EINVAL);
11147 	}
11148 	/*
11149 	 * Common case of OK return with outval same as inval
11150 	 */
11151 	if (invalp != outvalp) {
11152 		/* don't trust bcopy for identical src/dst */
11153 		(void) bcopy(invalp, outvalp, inlen);
11154 	}
11155 	*outlenp = inlen;
11156 	return (0);
11157 }
11158 
11159 /*
11160  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11161  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11162  * headers, and the maximum size tcp header (to avoid reallocation
11163  * on the fly for additional tcp options).
11164  * Returns failure if can't allocate memory.
11165  */
11166 static int
11167 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11168 {
11169 	char	*hdrs;
11170 	uint_t	hdrs_len;
11171 	ip6i_t	*ip6i;
11172 	char	buf[TCP_MAX_HDR_LENGTH];
11173 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11174 	in6_addr_t src, dst;
11175 
11176 	/*
11177 	 * save the existing tcp header and source/dest IP addresses
11178 	 */
11179 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11180 	src = tcp->tcp_ip6h->ip6_src;
11181 	dst = tcp->tcp_ip6h->ip6_dst;
11182 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11183 	ASSERT(hdrs_len != 0);
11184 	if (hdrs_len > tcp->tcp_iphc_len) {
11185 		/* Need to reallocate */
11186 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11187 		if (hdrs == NULL)
11188 			return (ENOMEM);
11189 		if (tcp->tcp_iphc != NULL) {
11190 			if (tcp->tcp_hdr_grown) {
11191 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11192 			} else {
11193 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11194 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11195 			}
11196 			tcp->tcp_iphc_len = 0;
11197 		}
11198 		ASSERT(tcp->tcp_iphc_len == 0);
11199 		tcp->tcp_iphc = hdrs;
11200 		tcp->tcp_iphc_len = hdrs_len;
11201 		tcp->tcp_hdr_grown = B_TRUE;
11202 	}
11203 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11204 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11205 
11206 	/* Set header fields not in ipp */
11207 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11208 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11209 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11210 	} else {
11211 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11212 	}
11213 	/*
11214 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11215 	 *
11216 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11217 	 */
11218 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11219 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11220 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11221 
11222 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11223 
11224 	tcp->tcp_ip6h->ip6_src = src;
11225 	tcp->tcp_ip6h->ip6_dst = dst;
11226 
11227 	/*
11228 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11229 	 * the default value for TCP.
11230 	 */
11231 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11232 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
11233 
11234 	/*
11235 	 * If we're setting extension headers after a connection
11236 	 * has been established, and if we have a routing header
11237 	 * among the extension headers, call ip_massage_options_v6 to
11238 	 * manipulate the routing header/ip6_dst set the checksum
11239 	 * difference in the tcp header template.
11240 	 * (This happens in tcp_connect_ipv6 if the routing header
11241 	 * is set prior to the connect.)
11242 	 * Set the tcp_sum to zero first in case we've cleared a
11243 	 * routing header or don't have one at all.
11244 	 */
11245 	tcp->tcp_sum = 0;
11246 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11247 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11248 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11249 		    (uint8_t *)tcp->tcp_tcph);
11250 		if (rth != NULL) {
11251 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11252 			    rth);
11253 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11254 			    (tcp->tcp_sum >> 16));
11255 		}
11256 	}
11257 
11258 	/* Try to get everything in a single mblk */
11259 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
11260 	return (0);
11261 }
11262 
11263 /*
11264  * Set optbuf and optlen for the option.
11265  * Allocate memory (if not already present).
11266  * Otherwise just point optbuf and optlen at invalp and inlen.
11267  * Returns failure if memory can not be allocated.
11268  */
11269 static int
11270 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
11271 {
11272 	uchar_t *optbuf;
11273 
11274 	if (inlen == *optlenp) {
11275 		/* Unchanged length - no need to realocate */
11276 		bcopy(invalp, *optbufp, inlen);
11277 		return (0);
11278 	}
11279 	if (inlen != 0) {
11280 		/* Allocate new buffer before free */
11281 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
11282 		if (optbuf == NULL)
11283 			return (ENOMEM);
11284 	} else {
11285 		optbuf = NULL;
11286 	}
11287 	/* Free old buffer */
11288 	if (*optlenp != 0)
11289 		kmem_free(*optbufp, *optlenp);
11290 
11291 	bcopy(invalp, optbuf, inlen);
11292 	*optbufp = optbuf;
11293 	*optlenp = inlen;
11294 	return (0);
11295 }
11296 
11297 
11298 /*
11299  * Use the outgoing IP header to create an IP_OPTIONS option the way
11300  * it was passed down from the application.
11301  */
11302 static int
11303 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
11304 {
11305 	ipoptp_t	opts;
11306 	uchar_t		*opt;
11307 	uint8_t		optval;
11308 	uint8_t		optlen;
11309 	uint32_t	len = 0;
11310 	uchar_t	*buf1 = buf;
11311 
11312 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
11313 	len += IP_ADDR_LEN;
11314 	bzero(buf1, IP_ADDR_LEN);
11315 
11316 	for (optval = ipoptp_first(&opts, ipha);
11317 	    optval != IPOPT_EOL;
11318 	    optval = ipoptp_next(&opts)) {
11319 		opt = opts.ipoptp_cur;
11320 		optlen = opts.ipoptp_len;
11321 		switch (optval) {
11322 			int	off;
11323 		case IPOPT_SSRR:
11324 		case IPOPT_LSRR:
11325 
11326 			/*
11327 			 * Insert ipha_dst as the first entry in the source
11328 			 * route and move down the entries on step.
11329 			 * The last entry gets placed at buf1.
11330 			 */
11331 			buf[IPOPT_OPTVAL] = optval;
11332 			buf[IPOPT_OLEN] = optlen;
11333 			buf[IPOPT_OFFSET] = optlen;
11334 
11335 			off = optlen - IP_ADDR_LEN;
11336 			if (off < 0) {
11337 				/* No entries in source route */
11338 				break;
11339 			}
11340 			/* Last entry in source route */
11341 			bcopy(opt + off, buf1, IP_ADDR_LEN);
11342 			off -= IP_ADDR_LEN;
11343 
11344 			while (off > 0) {
11345 				bcopy(opt + off,
11346 				    buf + off + IP_ADDR_LEN,
11347 				    IP_ADDR_LEN);
11348 				off -= IP_ADDR_LEN;
11349 			}
11350 			/* ipha_dst into first slot */
11351 			bcopy(&ipha->ipha_dst,
11352 			    buf + off + IP_ADDR_LEN,
11353 			    IP_ADDR_LEN);
11354 			buf += optlen;
11355 			len += optlen;
11356 			break;
11357 		default:
11358 			bcopy(opt, buf, optlen);
11359 			buf += optlen;
11360 			len += optlen;
11361 			break;
11362 		}
11363 	}
11364 done:
11365 	/* Pad the resulting options */
11366 	while (len & 0x3) {
11367 		*buf++ = IPOPT_EOL;
11368 		len++;
11369 	}
11370 	return (len);
11371 }
11372 
11373 /*
11374  * Transfer any source route option from ipha to buf/dst in reversed form.
11375  */
11376 static int
11377 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11378 {
11379 	ipoptp_t	opts;
11380 	uchar_t		*opt;
11381 	uint8_t		optval;
11382 	uint8_t		optlen;
11383 	uint32_t	len = 0;
11384 
11385 	for (optval = ipoptp_first(&opts, ipha);
11386 	    optval != IPOPT_EOL;
11387 	    optval = ipoptp_next(&opts)) {
11388 		opt = opts.ipoptp_cur;
11389 		optlen = opts.ipoptp_len;
11390 		switch (optval) {
11391 			int	off1, off2;
11392 		case IPOPT_SSRR:
11393 		case IPOPT_LSRR:
11394 
11395 			/* Reverse source route */
11396 			/*
11397 			 * First entry should be the next to last one in the
11398 			 * current source route (the last entry is our
11399 			 * address.)
11400 			 * The last entry should be the final destination.
11401 			 */
11402 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11403 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11404 			off1 = IPOPT_MINOFF_SR - 1;
11405 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11406 			if (off2 < 0) {
11407 				/* No entries in source route */
11408 				break;
11409 			}
11410 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11411 			/*
11412 			 * Note: use src since ipha has not had its src
11413 			 * and dst reversed (it is in the state it was
11414 			 * received.
11415 			 */
11416 			bcopy(&ipha->ipha_src, buf + off2,
11417 			    IP_ADDR_LEN);
11418 			off2 -= IP_ADDR_LEN;
11419 
11420 			while (off2 > 0) {
11421 				bcopy(opt + off2, buf + off1,
11422 				    IP_ADDR_LEN);
11423 				off1 += IP_ADDR_LEN;
11424 				off2 -= IP_ADDR_LEN;
11425 			}
11426 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11427 			buf += optlen;
11428 			len += optlen;
11429 			break;
11430 		}
11431 	}
11432 done:
11433 	/* Pad the resulting options */
11434 	while (len & 0x3) {
11435 		*buf++ = IPOPT_EOL;
11436 		len++;
11437 	}
11438 	return (len);
11439 }
11440 
11441 
11442 /*
11443  * Extract and revert a source route from ipha (if any)
11444  * and then update the relevant fields in both tcp_t and the standard header.
11445  */
11446 static void
11447 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11448 {
11449 	char	buf[TCP_MAX_HDR_LENGTH];
11450 	uint_t	tcph_len;
11451 	int	len;
11452 
11453 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11454 	len = IPH_HDR_LENGTH(ipha);
11455 	if (len == IP_SIMPLE_HDR_LENGTH)
11456 		/* Nothing to do */
11457 		return;
11458 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11459 	    (len & 0x3))
11460 		return;
11461 
11462 	tcph_len = tcp->tcp_tcp_hdr_len;
11463 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11464 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11465 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11466 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11467 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11468 	len += IP_SIMPLE_HDR_LENGTH;
11469 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11470 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11471 	if ((int)tcp->tcp_sum < 0)
11472 		tcp->tcp_sum--;
11473 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11474 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11475 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11476 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11477 	tcp->tcp_ip_hdr_len = len;
11478 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11479 	    (IP_VERSION << 4) | (len >> 2);
11480 	len += tcph_len;
11481 	tcp->tcp_hdr_len = len;
11482 }
11483 
11484 /*
11485  * Copy the standard header into its new location,
11486  * lay in the new options and then update the relevant
11487  * fields in both tcp_t and the standard header.
11488  */
11489 static int
11490 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11491 {
11492 	uint_t	tcph_len;
11493 	char	*ip_optp;
11494 	tcph_t	*new_tcph;
11495 
11496 	if (checkonly) {
11497 		/*
11498 		 * do not really set, just pretend to - T_CHECK
11499 		 */
11500 		if (len != 0) {
11501 			/*
11502 			 * there is value supplied, validate it as if
11503 			 * for a real set operation.
11504 			 */
11505 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11506 				return (EINVAL);
11507 		}
11508 		return (0);
11509 	}
11510 
11511 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11512 		return (EINVAL);
11513 
11514 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11515 	tcph_len = tcp->tcp_tcp_hdr_len;
11516 	new_tcph = (tcph_t *)(ip_optp + len);
11517 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
11518 	tcp->tcp_tcph = new_tcph;
11519 	bcopy(ptr, ip_optp, len);
11520 
11521 	len += IP_SIMPLE_HDR_LENGTH;
11522 
11523 	tcp->tcp_ip_hdr_len = len;
11524 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11525 		(IP_VERSION << 4) | (len >> 2);
11526 	len += tcph_len;
11527 	tcp->tcp_hdr_len = len;
11528 	if (!TCP_IS_DETACHED(tcp)) {
11529 		/* Always allocate room for all options. */
11530 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11531 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
11532 	}
11533 	return (0);
11534 }
11535 
11536 /* Get callback routine passed to nd_load by tcp_param_register */
11537 /* ARGSUSED */
11538 static int
11539 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11540 {
11541 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11542 
11543 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11544 	return (0);
11545 }
11546 
11547 /*
11548  * Walk through the param array specified registering each element with the
11549  * named dispatch handler.
11550  */
11551 static boolean_t
11552 tcp_param_register(tcpparam_t *tcppa, int cnt)
11553 {
11554 	for (; cnt-- > 0; tcppa++) {
11555 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11556 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11557 			    tcp_param_get, tcp_param_set,
11558 			    (caddr_t)tcppa)) {
11559 				nd_free(&tcp_g_nd);
11560 				return (B_FALSE);
11561 			}
11562 		}
11563 	}
11564 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11565 	    tcp_param_get, tcp_param_set_aligned,
11566 	    (caddr_t)&tcp_wroff_xtra_param)) {
11567 		nd_free(&tcp_g_nd);
11568 		return (B_FALSE);
11569 	}
11570 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11571 	    tcp_param_get, tcp_param_set_aligned,
11572 	    (caddr_t)&tcp_mdt_head_param)) {
11573 		nd_free(&tcp_g_nd);
11574 		return (B_FALSE);
11575 	}
11576 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11577 	    tcp_param_get, tcp_param_set_aligned,
11578 	    (caddr_t)&tcp_mdt_tail_param)) {
11579 		nd_free(&tcp_g_nd);
11580 		return (B_FALSE);
11581 	}
11582 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11583 	    tcp_param_get, tcp_param_set,
11584 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11585 		nd_free(&tcp_g_nd);
11586 		return (B_FALSE);
11587 	}
11588 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11589 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11590 		nd_free(&tcp_g_nd);
11591 		return (B_FALSE);
11592 	}
11593 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11594 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11595 		nd_free(&tcp_g_nd);
11596 		return (B_FALSE);
11597 	}
11598 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11599 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11600 		nd_free(&tcp_g_nd);
11601 		return (B_FALSE);
11602 	}
11603 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11604 	    NULL)) {
11605 		nd_free(&tcp_g_nd);
11606 		return (B_FALSE);
11607 	}
11608 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11609 	    NULL, NULL)) {
11610 		nd_free(&tcp_g_nd);
11611 		return (B_FALSE);
11612 	}
11613 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11614 	    NULL, NULL)) {
11615 		nd_free(&tcp_g_nd);
11616 		return (B_FALSE);
11617 	}
11618 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11619 	    NULL, NULL)) {
11620 		nd_free(&tcp_g_nd);
11621 		return (B_FALSE);
11622 	}
11623 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11624 	    NULL, NULL)) {
11625 		nd_free(&tcp_g_nd);
11626 		return (B_FALSE);
11627 	}
11628 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11629 	    tcp_host_param_set, NULL)) {
11630 		nd_free(&tcp_g_nd);
11631 		return (B_FALSE);
11632 	}
11633 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11634 	    tcp_host_param_set_ipv6, NULL)) {
11635 		nd_free(&tcp_g_nd);
11636 		return (B_FALSE);
11637 	}
11638 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11639 	    NULL)) {
11640 		nd_free(&tcp_g_nd);
11641 		return (B_FALSE);
11642 	}
11643 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11644 	    tcp_reserved_port_list, NULL, NULL)) {
11645 		nd_free(&tcp_g_nd);
11646 		return (B_FALSE);
11647 	}
11648 	/*
11649 	 * Dummy ndd variables - only to convey obsolescence information
11650 	 * through printing of their name (no get or set routines)
11651 	 * XXX Remove in future releases ?
11652 	 */
11653 	if (!nd_load(&tcp_g_nd,
11654 	    "tcp_close_wait_interval(obsoleted - "
11655 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11656 		nd_free(&tcp_g_nd);
11657 		return (B_FALSE);
11658 	}
11659 	return (B_TRUE);
11660 }
11661 
11662 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11663 /* ARGSUSED */
11664 static int
11665 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11666     cred_t *cr)
11667 {
11668 	long new_value;
11669 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11670 
11671 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11672 	    new_value < tcppa->tcp_param_min ||
11673 	    new_value > tcppa->tcp_param_max) {
11674 		return (EINVAL);
11675 	}
11676 	/*
11677 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11678 	 * round it up.  For future 64 bit requirement, we actually make it
11679 	 * a multiple of 8.
11680 	 */
11681 	if (new_value & 0x7) {
11682 		new_value = (new_value & ~0x7) + 0x8;
11683 	}
11684 	tcppa->tcp_param_val = new_value;
11685 	return (0);
11686 }
11687 
11688 /* Set callback routine passed to nd_load by tcp_param_register */
11689 /* ARGSUSED */
11690 static int
11691 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11692 {
11693 	long	new_value;
11694 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11695 
11696 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11697 	    new_value < tcppa->tcp_param_min ||
11698 	    new_value > tcppa->tcp_param_max) {
11699 		return (EINVAL);
11700 	}
11701 	tcppa->tcp_param_val = new_value;
11702 	return (0);
11703 }
11704 
11705 /*
11706  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11707  * is filled, return as much as we can.  The message passed in may be
11708  * multi-part, chained using b_cont.  "start" is the starting sequence
11709  * number for this piece.
11710  */
11711 static mblk_t *
11712 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11713 {
11714 	uint32_t	end;
11715 	mblk_t		*mp1;
11716 	mblk_t		*mp2;
11717 	mblk_t		*next_mp;
11718 	uint32_t	u1;
11719 
11720 	/* Walk through all the new pieces. */
11721 	do {
11722 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11723 		    (uintptr_t)INT_MAX);
11724 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11725 		next_mp = mp->b_cont;
11726 		if (start == end) {
11727 			/* Empty.  Blast it. */
11728 			freeb(mp);
11729 			continue;
11730 		}
11731 		mp->b_cont = NULL;
11732 		TCP_REASS_SET_SEQ(mp, start);
11733 		TCP_REASS_SET_END(mp, end);
11734 		mp1 = tcp->tcp_reass_tail;
11735 		if (!mp1) {
11736 			tcp->tcp_reass_tail = mp;
11737 			tcp->tcp_reass_head = mp;
11738 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11739 			UPDATE_MIB(&tcp_mib,
11740 			    tcpInDataUnorderBytes, end - start);
11741 			continue;
11742 		}
11743 		/* New stuff completely beyond tail? */
11744 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11745 			/* Link it on end. */
11746 			mp1->b_cont = mp;
11747 			tcp->tcp_reass_tail = mp;
11748 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11749 			UPDATE_MIB(&tcp_mib,
11750 			    tcpInDataUnorderBytes, end - start);
11751 			continue;
11752 		}
11753 		mp1 = tcp->tcp_reass_head;
11754 		u1 = TCP_REASS_SEQ(mp1);
11755 		/* New stuff at the front? */
11756 		if (SEQ_LT(start, u1)) {
11757 			/* Yes... Check for overlap. */
11758 			mp->b_cont = mp1;
11759 			tcp->tcp_reass_head = mp;
11760 			tcp_reass_elim_overlap(tcp, mp);
11761 			continue;
11762 		}
11763 		/*
11764 		 * The new piece fits somewhere between the head and tail.
11765 		 * We find our slot, where mp1 precedes us and mp2 trails.
11766 		 */
11767 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11768 			u1 = TCP_REASS_SEQ(mp2);
11769 			if (SEQ_LEQ(start, u1))
11770 				break;
11771 		}
11772 		/* Link ourselves in */
11773 		mp->b_cont = mp2;
11774 		mp1->b_cont = mp;
11775 
11776 		/* Trim overlap with following mblk(s) first */
11777 		tcp_reass_elim_overlap(tcp, mp);
11778 
11779 		/* Trim overlap with preceding mblk */
11780 		tcp_reass_elim_overlap(tcp, mp1);
11781 
11782 	} while (start = end, mp = next_mp);
11783 	mp1 = tcp->tcp_reass_head;
11784 	/* Anything ready to go? */
11785 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11786 		return (NULL);
11787 	/* Eat what we can off the queue */
11788 	for (;;) {
11789 		mp = mp1->b_cont;
11790 		end = TCP_REASS_END(mp1);
11791 		TCP_REASS_SET_SEQ(mp1, 0);
11792 		TCP_REASS_SET_END(mp1, 0);
11793 		if (!mp) {
11794 			tcp->tcp_reass_tail = NULL;
11795 			break;
11796 		}
11797 		if (end != TCP_REASS_SEQ(mp)) {
11798 			mp1->b_cont = NULL;
11799 			break;
11800 		}
11801 		mp1 = mp;
11802 	}
11803 	mp1 = tcp->tcp_reass_head;
11804 	tcp->tcp_reass_head = mp;
11805 	return (mp1);
11806 }
11807 
11808 /* Eliminate any overlap that mp may have over later mblks */
11809 static void
11810 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11811 {
11812 	uint32_t	end;
11813 	mblk_t		*mp1;
11814 	uint32_t	u1;
11815 
11816 	end = TCP_REASS_END(mp);
11817 	while ((mp1 = mp->b_cont) != NULL) {
11818 		u1 = TCP_REASS_SEQ(mp1);
11819 		if (!SEQ_GT(end, u1))
11820 			break;
11821 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11822 			mp->b_wptr -= end - u1;
11823 			TCP_REASS_SET_END(mp, u1);
11824 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11825 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11826 			break;
11827 		}
11828 		mp->b_cont = mp1->b_cont;
11829 		TCP_REASS_SET_SEQ(mp1, 0);
11830 		TCP_REASS_SET_END(mp1, 0);
11831 		freeb(mp1);
11832 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11833 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11834 	}
11835 	if (!mp1)
11836 		tcp->tcp_reass_tail = mp;
11837 }
11838 
11839 /*
11840  * Send up all messages queued on tcp_rcv_list.
11841  */
11842 static uint_t
11843 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11844 {
11845 	mblk_t *mp;
11846 	uint_t ret = 0;
11847 	uint_t thwin;
11848 #ifdef DEBUG
11849 	uint_t cnt = 0;
11850 #endif
11851 	/* Can't drain on an eager connection */
11852 	if (tcp->tcp_listener != NULL)
11853 		return (ret);
11854 
11855 	/*
11856 	 * Handle two cases here: we are currently fused or we were
11857 	 * previously fused and have some urgent data to be delivered
11858 	 * upstream.  The latter happens because we either ran out of
11859 	 * memory or were detached and therefore sending the SIGURG was
11860 	 * deferred until this point.  In either case we pass control
11861 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11862 	 * some work.
11863 	 */
11864 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11865 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11866 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11867 		    &tcp->tcp_fused_sigurg_mp))
11868 			return (ret);
11869 	}
11870 
11871 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11872 		tcp->tcp_rcv_list = mp->b_next;
11873 		mp->b_next = NULL;
11874 #ifdef DEBUG
11875 		cnt += msgdsize(mp);
11876 #endif
11877 		putnext(q, mp);
11878 	}
11879 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11880 	tcp->tcp_rcv_last_head = NULL;
11881 	tcp->tcp_rcv_last_tail = NULL;
11882 	tcp->tcp_rcv_cnt = 0;
11883 
11884 	/* Learn the latest rwnd information that we sent to the other side. */
11885 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11886 	    << tcp->tcp_rcv_ws;
11887 	/* This is peer's calculated send window (our receive window). */
11888 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11889 	/*
11890 	 * Increase the receive window to max.  But we need to do receiver
11891 	 * SWS avoidance.  This means that we need to check the increase of
11892 	 * of receive window is at least 1 MSS.
11893 	 */
11894 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11895 		/*
11896 		 * If the window that the other side knows is less than max
11897 		 * deferred acks segments, send an update immediately.
11898 		 */
11899 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11900 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11901 			ret = TH_ACK_NEEDED;
11902 		}
11903 		tcp->tcp_rwnd = q->q_hiwat;
11904 	}
11905 	/* No need for the push timer now. */
11906 	if (tcp->tcp_push_tid != 0) {
11907 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11908 		tcp->tcp_push_tid = 0;
11909 	}
11910 	return (ret);
11911 }
11912 
11913 /*
11914  * Queue data on tcp_rcv_list which is a b_next chain.
11915  * tcp_rcv_last_head/tail is the last element of this chain.
11916  * Each element of the chain is a b_cont chain.
11917  *
11918  * M_DATA messages are added to the current element.
11919  * Other messages are added as new (b_next) elements.
11920  */
11921 static void
11922 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11923 {
11924 	ASSERT(seg_len == msgdsize(mp));
11925 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11926 
11927 	if (tcp->tcp_rcv_list == NULL) {
11928 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11929 		tcp->tcp_rcv_list = mp;
11930 		tcp->tcp_rcv_last_head = mp;
11931 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11932 		tcp->tcp_rcv_last_tail->b_cont = mp;
11933 	} else {
11934 		tcp->tcp_rcv_last_head->b_next = mp;
11935 		tcp->tcp_rcv_last_head = mp;
11936 	}
11937 
11938 	while (mp->b_cont)
11939 		mp = mp->b_cont;
11940 
11941 	tcp->tcp_rcv_last_tail = mp;
11942 	tcp->tcp_rcv_cnt += seg_len;
11943 	tcp->tcp_rwnd -= seg_len;
11944 }
11945 
11946 /*
11947  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11948  *
11949  * This is the default entry function into TCP on the read side. TCP is
11950  * always entered via squeue i.e. using squeue's for mutual exclusion.
11951  * When classifier does a lookup to find the tcp, it also puts a reference
11952  * on the conn structure associated so the tcp is guaranteed to exist
11953  * when we come here. We still need to check the state because it might
11954  * as well has been closed. The squeue processing function i.e. squeue_enter,
11955  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11956  * CONN_DEC_REF.
11957  *
11958  * Apart from the default entry point, IP also sends packets directly to
11959  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11960  * connections.
11961  */
11962 void
11963 tcp_input(void *arg, mblk_t *mp, void *arg2)
11964 {
11965 	conn_t	*connp = (conn_t *)arg;
11966 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11967 
11968 	/* arg2 is the sqp */
11969 	ASSERT(arg2 != NULL);
11970 	ASSERT(mp != NULL);
11971 
11972 	/*
11973 	 * Don't accept any input on a closed tcp as this TCP logically does
11974 	 * not exist on the system. Don't proceed further with this TCP.
11975 	 * For eg. this packet could trigger another close of this tcp
11976 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11977 	 * tcp_clean_death / tcp_closei_local must be called at most once
11978 	 * on a TCP. In this case we need to refeed the packet into the
11979 	 * classifier and figure out where the packet should go. Need to
11980 	 * preserve the recv_ill somehow. Until we figure that out, for
11981 	 * now just drop the packet if we can't classify the packet.
11982 	 */
11983 	if (tcp->tcp_state == TCPS_CLOSED ||
11984 	    tcp->tcp_state == TCPS_BOUND) {
11985 		conn_t	*new_connp;
11986 
11987 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11988 		if (new_connp != NULL) {
11989 			tcp_reinput(new_connp, mp, arg2);
11990 			return;
11991 		}
11992 		/* We failed to classify. For now just drop the packet */
11993 		freemsg(mp);
11994 		return;
11995 	}
11996 
11997 	if (DB_TYPE(mp) == M_DATA)
11998 		tcp_rput_data(connp, mp, arg2);
11999 	else
12000 		tcp_rput_common(tcp, mp);
12001 }
12002 
12003 /*
12004  * The read side put procedure.
12005  * The packets passed up by ip are assume to be aligned according to
12006  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12007  */
12008 static void
12009 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12010 {
12011 	/*
12012 	 * tcp_rput_data() does not expect M_CTL except for the case
12013 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12014 	 * type. Need to make sure that any other M_CTLs don't make
12015 	 * it to tcp_rput_data since it is not expecting any and doesn't
12016 	 * check for it.
12017 	 */
12018 	if (DB_TYPE(mp) == M_CTL) {
12019 		switch (*(uint32_t *)(mp->b_rptr)) {
12020 		case TCP_IOC_ABORT_CONN:
12021 			/*
12022 			 * Handle connection abort request.
12023 			 */
12024 			tcp_ioctl_abort_handler(tcp, mp);
12025 			return;
12026 		case IPSEC_IN:
12027 			/*
12028 			 * Only secure icmp arrive in TCP and they
12029 			 * don't go through data path.
12030 			 */
12031 			tcp_icmp_error(tcp, mp);
12032 			return;
12033 		case IN_PKTINFO:
12034 			/*
12035 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12036 			 * sockets that are receiving IPv4 traffic. tcp
12037 			 */
12038 			ASSERT(tcp->tcp_family == AF_INET6);
12039 			ASSERT(tcp->tcp_ipv6_recvancillary &
12040 			    TCP_IPV6_RECVPKTINFO);
12041 			tcp_rput_data(tcp->tcp_connp, mp,
12042 			    tcp->tcp_connp->conn_sqp);
12043 			return;
12044 		case MDT_IOC_INFO_UPDATE:
12045 			/*
12046 			 * Handle Multidata information update; the
12047 			 * following routine will free the message.
12048 			 */
12049 			if (tcp->tcp_connp->conn_mdt_ok) {
12050 				tcp_mdt_update(tcp,
12051 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12052 				    B_FALSE);
12053 			}
12054 			freemsg(mp);
12055 			return;
12056 		default:
12057 			break;
12058 		}
12059 	}
12060 
12061 	/* No point processing the message if tcp is already closed */
12062 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12063 		freemsg(mp);
12064 		return;
12065 	}
12066 
12067 	tcp_rput_other(tcp, mp);
12068 }
12069 
12070 
12071 /* The minimum of smoothed mean deviation in RTO calculation. */
12072 #define	TCP_SD_MIN	400
12073 
12074 /*
12075  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12076  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12077  * are the same as those in Appendix A.2 of that paper.
12078  *
12079  * m = new measurement
12080  * sa = smoothed RTT average (8 * average estimates).
12081  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12082  */
12083 static void
12084 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12085 {
12086 	long m = TICK_TO_MSEC(rtt);
12087 	clock_t sa = tcp->tcp_rtt_sa;
12088 	clock_t sv = tcp->tcp_rtt_sd;
12089 	clock_t rto;
12090 
12091 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
12092 	tcp->tcp_rtt_update++;
12093 
12094 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12095 	if (sa != 0) {
12096 		/*
12097 		 * Update average estimator:
12098 		 *	new rtt = 7/8 old rtt + 1/8 Error
12099 		 */
12100 
12101 		/* m is now Error in estimate. */
12102 		m -= sa >> 3;
12103 		if ((sa += m) <= 0) {
12104 			/*
12105 			 * Don't allow the smoothed average to be negative.
12106 			 * We use 0 to denote reinitialization of the
12107 			 * variables.
12108 			 */
12109 			sa = 1;
12110 		}
12111 
12112 		/*
12113 		 * Update deviation estimator:
12114 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12115 		 */
12116 		if (m < 0)
12117 			m = -m;
12118 		m -= sv >> 2;
12119 		sv += m;
12120 	} else {
12121 		/*
12122 		 * This follows BSD's implementation.  So the reinitialized
12123 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12124 		 * link is bandwidth dominated, doubling the window size
12125 		 * during slow start means doubling the RTT.  We want to be
12126 		 * more conservative when we reinitialize our estimates.  3
12127 		 * is just a convenient number.
12128 		 */
12129 		sa = m << 3;
12130 		sv = m << 1;
12131 	}
12132 	if (sv < TCP_SD_MIN) {
12133 		/*
12134 		 * We do not know that if sa captures the delay ACK
12135 		 * effect as in a long train of segments, a receiver
12136 		 * does not delay its ACKs.  So set the minimum of sv
12137 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12138 		 * of BSD DATO.  That means the minimum of mean
12139 		 * deviation is 100 ms.
12140 		 *
12141 		 */
12142 		sv = TCP_SD_MIN;
12143 	}
12144 	tcp->tcp_rtt_sa = sa;
12145 	tcp->tcp_rtt_sd = sv;
12146 	/*
12147 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12148 	 *
12149 	 * Add tcp_rexmit_interval extra in case of extreme environment
12150 	 * where the algorithm fails to work.  The default value of
12151 	 * tcp_rexmit_interval_extra should be 0.
12152 	 *
12153 	 * As we use a finer grained clock than BSD and update
12154 	 * RTO for every ACKs, add in another .25 of RTT to the
12155 	 * deviation of RTO to accomodate burstiness of 1/4 of
12156 	 * window size.
12157 	 */
12158 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
12159 
12160 	if (rto > tcp_rexmit_interval_max) {
12161 		tcp->tcp_rto = tcp_rexmit_interval_max;
12162 	} else if (rto < tcp_rexmit_interval_min) {
12163 		tcp->tcp_rto = tcp_rexmit_interval_min;
12164 	} else {
12165 		tcp->tcp_rto = rto;
12166 	}
12167 
12168 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12169 	tcp->tcp_timer_backoff = 0;
12170 }
12171 
12172 /*
12173  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12174  * send queue which starts at the given seq. no.
12175  *
12176  * Parameters:
12177  *	tcp_t *tcp: the tcp instance pointer.
12178  *	uint32_t seq: the starting seq. no of the requested segment.
12179  *	int32_t *off: after the execution, *off will be the offset to
12180  *		the returned mblk which points to the requested seq no.
12181  *		It is the caller's responsibility to send in a non-null off.
12182  *
12183  * Return:
12184  *	A mblk_t pointer pointing to the requested segment in send queue.
12185  */
12186 static mblk_t *
12187 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12188 {
12189 	int32_t	cnt;
12190 	mblk_t	*mp;
12191 
12192 	/* Defensive coding.  Make sure we don't send incorrect data. */
12193 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12194 		return (NULL);
12195 
12196 	cnt = seq - tcp->tcp_suna;
12197 	mp = tcp->tcp_xmit_head;
12198 	while (cnt > 0 && mp != NULL) {
12199 		cnt -= mp->b_wptr - mp->b_rptr;
12200 		if (cnt < 0) {
12201 			cnt += mp->b_wptr - mp->b_rptr;
12202 			break;
12203 		}
12204 		mp = mp->b_cont;
12205 	}
12206 	ASSERT(mp != NULL);
12207 	*off = cnt;
12208 	return (mp);
12209 }
12210 
12211 /*
12212  * This function handles all retransmissions if SACK is enabled for this
12213  * connection.  First it calculates how many segments can be retransmitted
12214  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12215  * segments.  A segment is eligible if sack_cnt for that segment is greater
12216  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12217  * all eligible segments, it checks to see if TCP can send some new segments
12218  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12219  *
12220  * Parameters:
12221  *	tcp_t *tcp: the tcp structure of the connection.
12222  *	uint_t *flags: in return, appropriate value will be set for
12223  *	tcp_rput_data().
12224  */
12225 static void
12226 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12227 {
12228 	notsack_blk_t	*notsack_blk;
12229 	int32_t		usable_swnd;
12230 	int32_t		mss;
12231 	uint32_t	seg_len;
12232 	mblk_t		*xmit_mp;
12233 
12234 	ASSERT(tcp->tcp_sack_info != NULL);
12235 	ASSERT(tcp->tcp_notsack_list != NULL);
12236 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12237 
12238 	/* Defensive coding in case there is a bug... */
12239 	if (tcp->tcp_notsack_list == NULL) {
12240 		return;
12241 	}
12242 	notsack_blk = tcp->tcp_notsack_list;
12243 	mss = tcp->tcp_mss;
12244 
12245 	/*
12246 	 * Limit the num of outstanding data in the network to be
12247 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12248 	 */
12249 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12250 
12251 	/* At least retransmit 1 MSS of data. */
12252 	if (usable_swnd <= 0) {
12253 		usable_swnd = mss;
12254 	}
12255 
12256 	/* Make sure no new RTT samples will be taken. */
12257 	tcp->tcp_csuna = tcp->tcp_snxt;
12258 
12259 	notsack_blk = tcp->tcp_notsack_list;
12260 	while (usable_swnd > 0) {
12261 		mblk_t		*snxt_mp, *tmp_mp;
12262 		tcp_seq		begin = tcp->tcp_sack_snxt;
12263 		tcp_seq		end;
12264 		int32_t		off;
12265 
12266 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12267 			if (SEQ_GT(notsack_blk->end, begin) &&
12268 			    (notsack_blk->sack_cnt >=
12269 			    tcp_dupack_fast_retransmit)) {
12270 				end = notsack_blk->end;
12271 				if (SEQ_LT(begin, notsack_blk->begin)) {
12272 					begin = notsack_blk->begin;
12273 				}
12274 				break;
12275 			}
12276 		}
12277 		/*
12278 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12279 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12280 		 * set to tcp_cwnd_ssthresh.
12281 		 */
12282 		if (notsack_blk == NULL) {
12283 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12284 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12285 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12286 				ASSERT(tcp->tcp_cwnd > 0);
12287 				return;
12288 			} else {
12289 				usable_swnd = usable_swnd / mss;
12290 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12291 				    MAX(usable_swnd * mss, mss);
12292 				*flags |= TH_XMIT_NEEDED;
12293 				return;
12294 			}
12295 		}
12296 
12297 		/*
12298 		 * Note that we may send more than usable_swnd allows here
12299 		 * because of round off, but no more than 1 MSS of data.
12300 		 */
12301 		seg_len = end - begin;
12302 		if (seg_len > mss)
12303 			seg_len = mss;
12304 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12305 		ASSERT(snxt_mp != NULL);
12306 		/* This should not happen.  Defensive coding again... */
12307 		if (snxt_mp == NULL) {
12308 			return;
12309 		}
12310 
12311 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12312 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12313 		if (xmit_mp == NULL)
12314 			return;
12315 
12316 		usable_swnd -= seg_len;
12317 		tcp->tcp_pipe += seg_len;
12318 		tcp->tcp_sack_snxt = begin + seg_len;
12319 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12320 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12321 
12322 		/*
12323 		 * Update the send timestamp to avoid false retransmission.
12324 		 */
12325 		snxt_mp->b_prev = (mblk_t *)lbolt;
12326 
12327 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
12328 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
12329 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
12330 		/*
12331 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12332 		 * This happens when new data sent during fast recovery is
12333 		 * also lost.  If TCP retransmits those new data, it needs
12334 		 * to extend SACK recover phase to avoid starting another
12335 		 * fast retransmit/recovery unnecessarily.
12336 		 */
12337 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12338 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12339 		}
12340 	}
12341 }
12342 
12343 /*
12344  * This function handles policy checking at TCP level for non-hard_bound/
12345  * detached connections.
12346  */
12347 static boolean_t
12348 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12349     boolean_t secure, boolean_t mctl_present)
12350 {
12351 	ipsec_latch_t *ipl = NULL;
12352 	ipsec_action_t *act = NULL;
12353 	mblk_t *data_mp;
12354 	ipsec_in_t *ii;
12355 	const char *reason;
12356 	kstat_named_t *counter;
12357 
12358 	ASSERT(mctl_present || !secure);
12359 
12360 	ASSERT((ipha == NULL && ip6h != NULL) ||
12361 	    (ip6h == NULL && ipha != NULL));
12362 
12363 	/*
12364 	 * We don't necessarily have an ipsec_in_act action to verify
12365 	 * policy because of assymetrical policy where we have only
12366 	 * outbound policy and no inbound policy (possible with global
12367 	 * policy).
12368 	 */
12369 	if (!secure) {
12370 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12371 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12372 			return (B_TRUE);
12373 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
12374 		    "tcp_check_policy", ipha, ip6h, secure);
12375 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12376 		    &ipdrops_tcp_clear, &tcp_dropper);
12377 		return (B_FALSE);
12378 	}
12379 
12380 	/*
12381 	 * We have a secure packet.
12382 	 */
12383 	if (act == NULL) {
12384 		ipsec_log_policy_failure(tcp->tcp_wq,
12385 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
12386 		    secure);
12387 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12388 		    &ipdrops_tcp_secure, &tcp_dropper);
12389 		return (B_FALSE);
12390 	}
12391 
12392 	/*
12393 	 * XXX This whole routine is currently incorrect.  ipl should
12394 	 * be set to the latch pointer, but is currently not set, so
12395 	 * we initialize it to NULL to avoid picking up random garbage.
12396 	 */
12397 	if (ipl == NULL)
12398 		return (B_TRUE);
12399 
12400 	data_mp = first_mp->b_cont;
12401 
12402 	ii = (ipsec_in_t *)first_mp->b_rptr;
12403 
12404 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12405 	    &counter)) {
12406 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
12407 		return (B_TRUE);
12408 	}
12409 	(void) strlog(TCP_MODULE_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12410 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12411 	    reason);
12412 	BUMP_MIB(&ip_mib, ipsecInFailed);
12413 
12414 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
12415 	return (B_FALSE);
12416 }
12417 
12418 /*
12419  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12420  * retransmission after a timeout.
12421  *
12422  * To limit the number of duplicate segments, we limit the number of segment
12423  * to be sent in one time to tcp_snd_burst, the burst variable.
12424  */
12425 static void
12426 tcp_ss_rexmit(tcp_t *tcp)
12427 {
12428 	uint32_t	snxt;
12429 	uint32_t	smax;
12430 	int32_t		win;
12431 	int32_t		mss;
12432 	int32_t		off;
12433 	int32_t		burst = tcp->tcp_snd_burst;
12434 	mblk_t		*snxt_mp;
12435 
12436 	/*
12437 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12438 	 * all unack'ed segments.
12439 	 */
12440 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12441 		smax = tcp->tcp_rexmit_max;
12442 		snxt = tcp->tcp_rexmit_nxt;
12443 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12444 			snxt = tcp->tcp_suna;
12445 		}
12446 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12447 		win -= snxt - tcp->tcp_suna;
12448 		mss = tcp->tcp_mss;
12449 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12450 
12451 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12452 		    (burst > 0) && (snxt_mp != NULL)) {
12453 			mblk_t	*xmit_mp;
12454 			mblk_t	*old_snxt_mp = snxt_mp;
12455 			uint32_t cnt = mss;
12456 
12457 			if (win < cnt) {
12458 				cnt = win;
12459 			}
12460 			if (SEQ_GT(snxt + cnt, smax)) {
12461 				cnt = smax - snxt;
12462 			}
12463 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12464 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12465 			if (xmit_mp == NULL)
12466 				return;
12467 
12468 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12469 
12470 			snxt += cnt;
12471 			win -= cnt;
12472 			/*
12473 			 * Update the send timestamp to avoid false
12474 			 * retransmission.
12475 			 */
12476 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12477 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
12478 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
12479 
12480 			tcp->tcp_rexmit_nxt = snxt;
12481 			burst--;
12482 		}
12483 		/*
12484 		 * If we have transmitted all we have at the time
12485 		 * we started the retranmission, we can leave
12486 		 * the rest of the job to tcp_wput_data().  But we
12487 		 * need to check the send window first.  If the
12488 		 * win is not 0, go on with tcp_wput_data().
12489 		 */
12490 		if (SEQ_LT(snxt, smax) || win == 0) {
12491 			return;
12492 		}
12493 	}
12494 	/* Only call tcp_wput_data() if there is data to be sent. */
12495 	if (tcp->tcp_unsent) {
12496 		tcp_wput_data(tcp, NULL, B_FALSE);
12497 	}
12498 }
12499 
12500 /*
12501  * Process all TCP option in SYN segment.  Note that this function should
12502  * be called after tcp_adapt_ire() is called so that the necessary info
12503  * from IRE is already set in the tcp structure.
12504  *
12505  * This function sets up the correct tcp_mss value according to the
12506  * MSS option value and our header size.  It also sets up the window scale
12507  * and timestamp values, and initialize SACK info blocks.  But it does not
12508  * change receive window size after setting the tcp_mss value.  The caller
12509  * should do the appropriate change.
12510  */
12511 void
12512 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12513 {
12514 	int options;
12515 	tcp_opt_t tcpopt;
12516 	uint32_t mss_max;
12517 	char *tmp_tcph;
12518 
12519 	tcpopt.tcp = NULL;
12520 	options = tcp_parse_options(tcph, &tcpopt);
12521 
12522 	/*
12523 	 * Process MSS option.  Note that MSS option value does not account
12524 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12525 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12526 	 * IPv6.
12527 	 */
12528 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12529 		if (tcp->tcp_ipversion == IPV4_VERSION)
12530 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
12531 		else
12532 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
12533 	} else {
12534 		if (tcp->tcp_ipversion == IPV4_VERSION)
12535 			mss_max = tcp_mss_max_ipv4;
12536 		else
12537 			mss_max = tcp_mss_max_ipv6;
12538 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
12539 			tcpopt.tcp_opt_mss = tcp_mss_min;
12540 		else if (tcpopt.tcp_opt_mss > mss_max)
12541 			tcpopt.tcp_opt_mss = mss_max;
12542 	}
12543 
12544 	/* Process Window Scale option. */
12545 	if (options & TCP_OPT_WSCALE_PRESENT) {
12546 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12547 		tcp->tcp_snd_ws_ok = B_TRUE;
12548 	} else {
12549 		tcp->tcp_snd_ws = B_FALSE;
12550 		tcp->tcp_snd_ws_ok = B_FALSE;
12551 		tcp->tcp_rcv_ws = B_FALSE;
12552 	}
12553 
12554 	/* Process Timestamp option. */
12555 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12556 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12557 		tmp_tcph = (char *)tcp->tcp_tcph;
12558 
12559 		tcp->tcp_snd_ts_ok = B_TRUE;
12560 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12561 		tcp->tcp_last_rcv_lbolt = lbolt64;
12562 		ASSERT(OK_32PTR(tmp_tcph));
12563 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12564 
12565 		/* Fill in our template header with basic timestamp option. */
12566 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12567 		tmp_tcph[0] = TCPOPT_NOP;
12568 		tmp_tcph[1] = TCPOPT_NOP;
12569 		tmp_tcph[2] = TCPOPT_TSTAMP;
12570 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12571 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12572 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12573 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12574 	} else {
12575 		tcp->tcp_snd_ts_ok = B_FALSE;
12576 	}
12577 
12578 	/*
12579 	 * Process SACK options.  If SACK is enabled for this connection,
12580 	 * then allocate the SACK info structure.  Note the following ways
12581 	 * when tcp_snd_sack_ok is set to true.
12582 	 *
12583 	 * For active connection: in tcp_adapt_ire() called in
12584 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12585 	 * is checked.
12586 	 *
12587 	 * For passive connection: in tcp_adapt_ire() called in
12588 	 * tcp_accept_comm().
12589 	 *
12590 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12591 	 * That check makes sure that if we did not send a SACK OK option,
12592 	 * we will not enable SACK for this connection even though the other
12593 	 * side sends us SACK OK option.  For active connection, the SACK
12594 	 * info structure has already been allocated.  So we need to free
12595 	 * it if SACK is disabled.
12596 	 */
12597 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12598 	    (tcp->tcp_snd_sack_ok ||
12599 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12600 		/* This should be true only in the passive case. */
12601 		if (tcp->tcp_sack_info == NULL) {
12602 			ASSERT(TCP_IS_DETACHED(tcp));
12603 			tcp->tcp_sack_info =
12604 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12605 		}
12606 		if (tcp->tcp_sack_info == NULL) {
12607 			tcp->tcp_snd_sack_ok = B_FALSE;
12608 		} else {
12609 			tcp->tcp_snd_sack_ok = B_TRUE;
12610 			if (tcp->tcp_snd_ts_ok) {
12611 				tcp->tcp_max_sack_blk = 3;
12612 			} else {
12613 				tcp->tcp_max_sack_blk = 4;
12614 			}
12615 		}
12616 	} else {
12617 		/*
12618 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12619 		 * no SACK info will be used for this
12620 		 * connection.  This assumes that SACK usage
12621 		 * permission is negotiated.  This may need
12622 		 * to be changed once this is clarified.
12623 		 */
12624 		if (tcp->tcp_sack_info != NULL) {
12625 			ASSERT(tcp->tcp_notsack_list == NULL);
12626 			kmem_cache_free(tcp_sack_info_cache,
12627 			    tcp->tcp_sack_info);
12628 			tcp->tcp_sack_info = NULL;
12629 		}
12630 		tcp->tcp_snd_sack_ok = B_FALSE;
12631 	}
12632 
12633 	/*
12634 	 * Now we know the exact TCP/IP header length, subtract
12635 	 * that from tcp_mss to get our side's MSS.
12636 	 */
12637 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12638 	/*
12639 	 * Here we assume that the other side's header size will be equal to
12640 	 * our header size.  We calculate the real MSS accordingly.  Need to
12641 	 * take into additional stuffs IPsec puts in.
12642 	 *
12643 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12644 	 */
12645 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12646 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12647 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12648 
12649 	/*
12650 	 * Set MSS to the smaller one of both ends of the connection.
12651 	 * We should not have called tcp_mss_set() before, but our
12652 	 * side of the MSS should have been set to a proper value
12653 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12654 	 * STREAM head parameters properly.
12655 	 *
12656 	 * If we have a larger-than-16-bit window but the other side
12657 	 * didn't want to do window scale, tcp_rwnd_set() will take
12658 	 * care of that.
12659 	 */
12660 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12661 }
12662 
12663 /*
12664  * Sends the T_CONN_IND to the listener. The caller calls this
12665  * functions via squeue to get inside the listener's perimeter
12666  * once the 3 way hand shake is done a T_CONN_IND needs to be
12667  * sent. As an optimization, the caller can call this directly
12668  * if listener's perimeter is same as eager's.
12669  */
12670 /* ARGSUSED */
12671 void
12672 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12673 {
12674 	conn_t			*lconnp = (conn_t *)arg;
12675 	tcp_t			*listener = lconnp->conn_tcp;
12676 	tcp_t			*tcp;
12677 	struct T_conn_ind	*conn_ind;
12678 	ipaddr_t 		*addr_cache;
12679 	boolean_t		need_send_conn_ind = B_FALSE;
12680 
12681 	/* retrieve the eager */
12682 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12683 	ASSERT(conn_ind->OPT_offset != 0 &&
12684 	    conn_ind->OPT_length == sizeof (intptr_t));
12685 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12686 		conn_ind->OPT_length);
12687 
12688 	/*
12689 	 * TLI/XTI applications will get confused by
12690 	 * sending eager as an option since it violates
12691 	 * the option semantics. So remove the eager as
12692 	 * option since TLI/XTI app doesn't need it anyway.
12693 	 */
12694 	if (!TCP_IS_SOCKET(listener)) {
12695 		conn_ind->OPT_length = 0;
12696 		conn_ind->OPT_offset = 0;
12697 	}
12698 	if (listener->tcp_state == TCPS_CLOSED ||
12699 	    TCP_IS_DETACHED(listener)) {
12700 		/*
12701 		 * If listener has closed, it would have caused a
12702 		 * a cleanup/blowoff to happen for the eager. We
12703 		 * just need to return.
12704 		 */
12705 		freemsg(mp);
12706 		return;
12707 	}
12708 
12709 
12710 	/*
12711 	 * if the conn_req_q is full defer passing up the
12712 	 * T_CONN_IND until space is availabe after t_accept()
12713 	 * processing
12714 	 */
12715 	mutex_enter(&listener->tcp_eager_lock);
12716 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12717 		tcp_t *tail;
12718 
12719 		/*
12720 		 * The eager already has an extra ref put in tcp_rput_data
12721 		 * so that it stays till accept comes back even though it
12722 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12723 		 */
12724 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12725 		listener->tcp_conn_req_cnt_q0--;
12726 		listener->tcp_conn_req_cnt_q++;
12727 
12728 		/* Move from SYN_RCVD to ESTABLISHED list  */
12729 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12730 		    tcp->tcp_eager_prev_q0;
12731 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12732 		    tcp->tcp_eager_next_q0;
12733 		tcp->tcp_eager_prev_q0 = NULL;
12734 		tcp->tcp_eager_next_q0 = NULL;
12735 
12736 		/*
12737 		 * Insert at end of the queue because sockfs
12738 		 * sends down T_CONN_RES in chronological
12739 		 * order. Leaving the older conn indications
12740 		 * at front of the queue helps reducing search
12741 		 * time.
12742 		 */
12743 		tail = listener->tcp_eager_last_q;
12744 		if (tail != NULL)
12745 			tail->tcp_eager_next_q = tcp;
12746 		else
12747 			listener->tcp_eager_next_q = tcp;
12748 		listener->tcp_eager_last_q = tcp;
12749 		tcp->tcp_eager_next_q = NULL;
12750 		/*
12751 		 * Delay sending up the T_conn_ind until we are
12752 		 * done with the eager. Once we have have sent up
12753 		 * the T_conn_ind, the accept can potentially complete
12754 		 * any time and release the refhold we have on the eager.
12755 		 */
12756 		need_send_conn_ind = B_TRUE;
12757 	} else {
12758 		/*
12759 		 * Defer connection on q0 and set deferred
12760 		 * connection bit true
12761 		 */
12762 		tcp->tcp_conn_def_q0 = B_TRUE;
12763 
12764 		/* take tcp out of q0 ... */
12765 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12766 		    tcp->tcp_eager_next_q0;
12767 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12768 		    tcp->tcp_eager_prev_q0;
12769 
12770 		/* ... and place it at the end of q0 */
12771 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12772 		tcp->tcp_eager_next_q0 = listener;
12773 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12774 		listener->tcp_eager_prev_q0 = tcp;
12775 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12776 	}
12777 
12778 	/* we have timed out before */
12779 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12780 		tcp->tcp_syn_rcvd_timeout = 0;
12781 		listener->tcp_syn_rcvd_timeout--;
12782 		if (listener->tcp_syn_defense &&
12783 		    listener->tcp_syn_rcvd_timeout <=
12784 		    (tcp_conn_req_max_q0 >> 5) &&
12785 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12786 			listener->tcp_last_rcv_lbolt)) {
12787 			/*
12788 			 * Turn off the defense mode if we
12789 			 * believe the SYN attack is over.
12790 			 */
12791 			listener->tcp_syn_defense = B_FALSE;
12792 			if (listener->tcp_ip_addr_cache) {
12793 				kmem_free((void *)listener->tcp_ip_addr_cache,
12794 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12795 				listener->tcp_ip_addr_cache = NULL;
12796 			}
12797 		}
12798 	}
12799 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12800 	if (addr_cache != NULL) {
12801 		/*
12802 		 * We have finished a 3-way handshake with this
12803 		 * remote host. This proves the IP addr is good.
12804 		 * Cache it!
12805 		 */
12806 		addr_cache[IP_ADDR_CACHE_HASH(
12807 			tcp->tcp_remote)] = tcp->tcp_remote;
12808 	}
12809 	mutex_exit(&listener->tcp_eager_lock);
12810 	if (need_send_conn_ind)
12811 		putnext(listener->tcp_rq, mp);
12812 }
12813 
12814 mblk_t *
12815 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12816     uint_t *ifindexp, ip6_pkt_t *ippp)
12817 {
12818 	in_pktinfo_t	*pinfo;
12819 	ip6_t		*ip6h;
12820 	uchar_t		*rptr;
12821 	mblk_t		*first_mp = mp;
12822 	boolean_t	mctl_present = B_FALSE;
12823 	uint_t 		ifindex = 0;
12824 	ip6_pkt_t	ipp;
12825 	uint_t		ipvers;
12826 	uint_t		ip_hdr_len;
12827 
12828 	rptr = mp->b_rptr;
12829 	ASSERT(OK_32PTR(rptr));
12830 	ASSERT(tcp != NULL);
12831 	ipp.ipp_fields = 0;
12832 
12833 	switch DB_TYPE(mp) {
12834 	case M_CTL:
12835 		mp = mp->b_cont;
12836 		if (mp == NULL) {
12837 			freemsg(first_mp);
12838 			return (NULL);
12839 		}
12840 		if (DB_TYPE(mp) != M_DATA) {
12841 			freemsg(first_mp);
12842 			return (NULL);
12843 		}
12844 		mctl_present = B_TRUE;
12845 		break;
12846 	case M_DATA:
12847 		break;
12848 	default:
12849 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12850 		freemsg(mp);
12851 		return (NULL);
12852 	}
12853 	ipvers = IPH_HDR_VERSION(rptr);
12854 	if (ipvers == IPV4_VERSION) {
12855 		if (tcp == NULL) {
12856 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12857 			goto done;
12858 		}
12859 
12860 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12861 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12862 
12863 		/*
12864 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12865 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12866 		 */
12867 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12868 		    mctl_present) {
12869 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12870 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12871 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12872 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12873 				ipp.ipp_fields |= IPPF_IFINDEX;
12874 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12875 				ifindex = pinfo->in_pkt_ifindex;
12876 			}
12877 			freeb(first_mp);
12878 			mctl_present = B_FALSE;
12879 		}
12880 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12881 	} else {
12882 		ip6h = (ip6_t *)rptr;
12883 
12884 		ASSERT(ipvers == IPV6_VERSION);
12885 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12886 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12887 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12888 
12889 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12890 			uint8_t	nexthdrp;
12891 
12892 			/* Look for ifindex information */
12893 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12894 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12895 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12896 					BUMP_MIB(&ip_mib, tcpInErrs);
12897 					freemsg(first_mp);
12898 					return (NULL);
12899 				}
12900 
12901 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12902 					ASSERT(ip6i->ip6i_ifindex != 0);
12903 					ipp.ipp_fields |= IPPF_IFINDEX;
12904 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12905 					ifindex = ip6i->ip6i_ifindex;
12906 				}
12907 				rptr = (uchar_t *)&ip6i[1];
12908 				mp->b_rptr = rptr;
12909 				if (rptr == mp->b_wptr) {
12910 					mblk_t *mp1;
12911 					mp1 = mp->b_cont;
12912 					freeb(mp);
12913 					mp = mp1;
12914 					rptr = mp->b_rptr;
12915 				}
12916 				if (MBLKL(mp) < IPV6_HDR_LEN +
12917 				    sizeof (tcph_t)) {
12918 					BUMP_MIB(&ip_mib, tcpInErrs);
12919 					freemsg(first_mp);
12920 					return (NULL);
12921 				}
12922 				ip6h = (ip6_t *)rptr;
12923 			}
12924 
12925 			/*
12926 			 * Find any potentially interesting extension headers
12927 			 * as well as the length of the IPv6 + extension
12928 			 * headers.
12929 			 */
12930 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12931 			/* Verify if this is a TCP packet */
12932 			if (nexthdrp != IPPROTO_TCP) {
12933 				BUMP_MIB(&ip_mib, tcpInErrs);
12934 				freemsg(first_mp);
12935 				return (NULL);
12936 			}
12937 		} else {
12938 			ip_hdr_len = IPV6_HDR_LEN;
12939 		}
12940 	}
12941 
12942 done:
12943 	if (ipversp != NULL)
12944 		*ipversp = ipvers;
12945 	if (ip_hdr_lenp != NULL)
12946 		*ip_hdr_lenp = ip_hdr_len;
12947 	if (ippp != NULL)
12948 		*ippp = ipp;
12949 	if (ifindexp != NULL)
12950 		*ifindexp = ifindex;
12951 	if (mctl_present) {
12952 		freeb(first_mp);
12953 	}
12954 	return (mp);
12955 }
12956 
12957 /*
12958  * Handle M_DATA messages from IP. Its called directly from IP via
12959  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12960  * in this path.
12961  *
12962  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12963  * v4 and v6), we are called through tcp_input() and a M_CTL can
12964  * be present for options but tcp_find_pktinfo() deals with it. We
12965  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12966  *
12967  * The first argument is always the connp/tcp to which the mp belongs.
12968  * There are no exceptions to this rule. The caller has already put
12969  * a reference on this connp/tcp and once tcp_rput_data() returns,
12970  * the squeue will do the refrele.
12971  *
12972  * The TH_SYN for the listener directly go to tcp_conn_request via
12973  * squeue.
12974  *
12975  * sqp: NULL = recursive, sqp != NULL means called from squeue
12976  */
12977 void
12978 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12979 {
12980 	int32_t		bytes_acked;
12981 	int32_t		gap;
12982 	mblk_t		*mp1;
12983 	uint_t		flags;
12984 	uint32_t	new_swnd = 0;
12985 	uchar_t		*iphdr;
12986 	uchar_t		*rptr;
12987 	int32_t		rgap;
12988 	uint32_t	seg_ack;
12989 	int		seg_len;
12990 	uint_t		ip_hdr_len;
12991 	uint32_t	seg_seq;
12992 	tcph_t		*tcph;
12993 	int		urp;
12994 	tcp_opt_t	tcpopt;
12995 	uint_t		ipvers;
12996 	ip6_pkt_t	ipp;
12997 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12998 	uint32_t	cwnd;
12999 	uint32_t	add;
13000 	int		npkt;
13001 	int		mss;
13002 	conn_t		*connp = (conn_t *)arg;
13003 	squeue_t	*sqp = (squeue_t *)arg2;
13004 	tcp_t		*tcp = connp->conn_tcp;
13005 
13006 	/*
13007 	 * RST from fused tcp loopback peer should trigger an unfuse.
13008 	 */
13009 	if (tcp->tcp_fused) {
13010 		TCP_STAT(tcp_fusion_aborted);
13011 		tcp_unfuse(tcp);
13012 	}
13013 
13014 	iphdr = mp->b_rptr;
13015 	rptr = mp->b_rptr;
13016 	ASSERT(OK_32PTR(rptr));
13017 
13018 	/*
13019 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13020 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13021 	 * necessary information.
13022 	 */
13023 	if (IPCL_IS_TCP4(connp)) {
13024 		ipvers = IPV4_VERSION;
13025 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13026 	} else {
13027 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13028 		    NULL, &ipp);
13029 		if (mp == NULL) {
13030 			TCP_STAT(tcp_rput_v6_error);
13031 			return;
13032 		}
13033 		iphdr = mp->b_rptr;
13034 		rptr = mp->b_rptr;
13035 	}
13036 	ASSERT(DB_TYPE(mp) == M_DATA);
13037 
13038 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13039 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13040 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13041 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13042 	seg_len = (int)(mp->b_wptr - rptr) -
13043 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13044 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13045 		do {
13046 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13047 			    (uintptr_t)INT_MAX);
13048 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13049 		} while ((mp1 = mp1->b_cont) != NULL &&
13050 		    mp1->b_datap->db_type == M_DATA);
13051 	}
13052 
13053 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13054 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13055 		    seg_len, tcph);
13056 		return;
13057 	}
13058 
13059 	if (sqp != NULL) {
13060 		/*
13061 		 * This is the correct place to update tcp_last_recv_time. Note
13062 		 * that it is also updated for tcp structure that belongs to
13063 		 * global and listener queues which do not really need updating.
13064 		 * But that should not cause any harm.  And it is updated for
13065 		 * all kinds of incoming segments, not only for data segments.
13066 		 */
13067 		tcp->tcp_last_recv_time = lbolt;
13068 	}
13069 
13070 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13071 
13072 	BUMP_LOCAL(tcp->tcp_ibsegs);
13073 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
13074 
13075 	if ((flags & TH_URG) && sqp != NULL) {
13076 		/*
13077 		 * TCP can't handle urgent pointers that arrive before
13078 		 * the connection has been accept()ed since it can't
13079 		 * buffer OOB data.  Discard segment if this happens.
13080 		 *
13081 		 * Nor can it reassemble urgent pointers, so discard
13082 		 * if it's not the next segment expected.
13083 		 *
13084 		 * Otherwise, collapse chain into one mblk (discard if
13085 		 * that fails).  This makes sure the headers, retransmitted
13086 		 * data, and new data all are in the same mblk.
13087 		 */
13088 		ASSERT(mp != NULL);
13089 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
13090 			freemsg(mp);
13091 			return;
13092 		}
13093 		/* Update pointers into message */
13094 		iphdr = rptr = mp->b_rptr;
13095 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13096 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13097 			/*
13098 			 * Since we can't handle any data with this urgent
13099 			 * pointer that is out of sequence, we expunge
13100 			 * the data.  This allows us to still register
13101 			 * the urgent mark and generate the M_PCSIG,
13102 			 * which we can do.
13103 			 */
13104 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13105 			seg_len = 0;
13106 		}
13107 	}
13108 
13109 	switch (tcp->tcp_state) {
13110 	case TCPS_SYN_SENT:
13111 		if (flags & TH_ACK) {
13112 			/*
13113 			 * Note that our stack cannot send data before a
13114 			 * connection is established, therefore the
13115 			 * following check is valid.  Otherwise, it has
13116 			 * to be changed.
13117 			 */
13118 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13119 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13120 				freemsg(mp);
13121 				if (flags & TH_RST)
13122 					return;
13123 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13124 				    tcp, seg_ack, 0, TH_RST);
13125 				return;
13126 			}
13127 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13128 		}
13129 		if (flags & TH_RST) {
13130 			freemsg(mp);
13131 			if (flags & TH_ACK)
13132 				(void) tcp_clean_death(tcp,
13133 				    ECONNREFUSED, 13);
13134 			return;
13135 		}
13136 		if (!(flags & TH_SYN)) {
13137 			freemsg(mp);
13138 			return;
13139 		}
13140 
13141 		/* Process all TCP options. */
13142 		tcp_process_options(tcp, tcph);
13143 		/*
13144 		 * The following changes our rwnd to be a multiple of the
13145 		 * MIN(peer MSS, our MSS) for performance reason.
13146 		 */
13147 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13148 		    tcp->tcp_mss));
13149 
13150 		/* Is the other end ECN capable? */
13151 		if (tcp->tcp_ecn_ok) {
13152 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13153 				tcp->tcp_ecn_ok = B_FALSE;
13154 			}
13155 		}
13156 		/*
13157 		 * Clear ECN flags because it may interfere with later
13158 		 * processing.
13159 		 */
13160 		flags &= ~(TH_ECE|TH_CWR);
13161 
13162 		tcp->tcp_irs = seg_seq;
13163 		tcp->tcp_rack = seg_seq;
13164 		tcp->tcp_rnxt = seg_seq + 1;
13165 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13166 		if (!TCP_IS_DETACHED(tcp)) {
13167 			/* Allocate room for SACK options if needed. */
13168 			if (tcp->tcp_snd_sack_ok) {
13169 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13170 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13171 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13172 			} else {
13173 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13174 				    tcp->tcp_hdr_len +
13175 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13176 			}
13177 		}
13178 		if (flags & TH_ACK) {
13179 			/*
13180 			 * If we can't get the confirmation upstream, pretend
13181 			 * we didn't even see this one.
13182 			 *
13183 			 * XXX: how can we pretend we didn't see it if we
13184 			 * have updated rnxt et. al.
13185 			 *
13186 			 * For loopback we defer sending up the T_CONN_CON
13187 			 * until after some checks below.
13188 			 */
13189 			mp1 = NULL;
13190 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13191 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13192 				freemsg(mp);
13193 				return;
13194 			}
13195 			/* SYN was acked - making progress */
13196 			if (tcp->tcp_ipversion == IPV6_VERSION)
13197 				tcp->tcp_ip_forward_progress = B_TRUE;
13198 
13199 			/* One for the SYN */
13200 			tcp->tcp_suna = tcp->tcp_iss + 1;
13201 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13202 			tcp->tcp_state = TCPS_ESTABLISHED;
13203 
13204 			/*
13205 			 * If SYN was retransmitted, need to reset all
13206 			 * retransmission info.  This is because this
13207 			 * segment will be treated as a dup ACK.
13208 			 */
13209 			if (tcp->tcp_rexmit) {
13210 				tcp->tcp_rexmit = B_FALSE;
13211 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13212 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13213 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13214 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13215 				tcp->tcp_ms_we_have_waited = 0;
13216 
13217 				/*
13218 				 * Set tcp_cwnd back to 1 MSS, per
13219 				 * recommendation from
13220 				 * draft-floyd-incr-init-win-01.txt,
13221 				 * Increasing TCP's Initial Window.
13222 				 */
13223 				tcp->tcp_cwnd = tcp->tcp_mss;
13224 			}
13225 
13226 			tcp->tcp_swl1 = seg_seq;
13227 			tcp->tcp_swl2 = seg_ack;
13228 
13229 			new_swnd = BE16_TO_U16(tcph->th_win);
13230 			tcp->tcp_swnd = new_swnd;
13231 			if (new_swnd > tcp->tcp_max_swnd)
13232 				tcp->tcp_max_swnd = new_swnd;
13233 
13234 			/*
13235 			 * Always send the three-way handshake ack immediately
13236 			 * in order to make the connection complete as soon as
13237 			 * possible on the accepting host.
13238 			 */
13239 			flags |= TH_ACK_NEEDED;
13240 
13241 			/*
13242 			 * Special case for loopback.  At this point we have
13243 			 * received SYN-ACK from the remote endpoint.  In
13244 			 * order to ensure that both endpoints reach the
13245 			 * fused state prior to any data exchange, the final
13246 			 * ACK needs to be sent before we indicate T_CONN_CON
13247 			 * to the module upstream.
13248 			 */
13249 			if (tcp->tcp_loopback) {
13250 				mblk_t *ack_mp;
13251 
13252 				ASSERT(!tcp->tcp_unfusable);
13253 				ASSERT(mp1 != NULL);
13254 				/*
13255 				 * For loopback, we always get a pure SYN-ACK
13256 				 * and only need to send back the final ACK
13257 				 * with no data (this is because the other
13258 				 * tcp is ours and we don't do T/TCP).  This
13259 				 * final ACK triggers the passive side to
13260 				 * perform fusion in ESTABLISHED state.
13261 				 */
13262 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13263 					if (tcp->tcp_ack_tid != 0) {
13264 						(void) TCP_TIMER_CANCEL(tcp,
13265 						    tcp->tcp_ack_tid);
13266 						tcp->tcp_ack_tid = 0;
13267 					}
13268 					TCP_RECORD_TRACE(tcp, ack_mp,
13269 					    TCP_TRACE_SEND_PKT);
13270 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13271 					BUMP_LOCAL(tcp->tcp_obsegs);
13272 					BUMP_MIB(&tcp_mib, tcpOutAck);
13273 
13274 					/* Send up T_CONN_CON */
13275 					putnext(tcp->tcp_rq, mp1);
13276 
13277 					freemsg(mp);
13278 					return;
13279 				}
13280 				/*
13281 				 * Forget fusion; we need to handle more
13282 				 * complex cases below.  Send the deferred
13283 				 * T_CONN_CON message upstream and proceed
13284 				 * as usual.  Mark this tcp as not capable
13285 				 * of fusion.
13286 				 */
13287 				TCP_STAT(tcp_fusion_unfusable);
13288 				tcp->tcp_unfusable = B_TRUE;
13289 				putnext(tcp->tcp_rq, mp1);
13290 			}
13291 
13292 			/*
13293 			 * Check to see if there is data to be sent.  If
13294 			 * yes, set the transmit flag.  Then check to see
13295 			 * if received data processing needs to be done.
13296 			 * If not, go straight to xmit_check.  This short
13297 			 * cut is OK as we don't support T/TCP.
13298 			 */
13299 			if (tcp->tcp_unsent)
13300 				flags |= TH_XMIT_NEEDED;
13301 
13302 			if (seg_len == 0 && !(flags & TH_URG)) {
13303 				freemsg(mp);
13304 				goto xmit_check;
13305 			}
13306 
13307 			flags &= ~TH_SYN;
13308 			seg_seq++;
13309 			break;
13310 		}
13311 		tcp->tcp_state = TCPS_SYN_RCVD;
13312 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13313 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13314 		if (mp1) {
13315 			mblk_setcred(mp1, tcp->tcp_cred);
13316 			DB_CPID(mp1) = tcp->tcp_cpid;
13317 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13318 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13319 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13320 		}
13321 		freemsg(mp);
13322 		return;
13323 	case TCPS_SYN_RCVD:
13324 		if (flags & TH_ACK) {
13325 			/*
13326 			 * In this state, a SYN|ACK packet is either bogus
13327 			 * because the other side must be ACKing our SYN which
13328 			 * indicates it has seen the ACK for their SYN and
13329 			 * shouldn't retransmit it or we're crossing SYNs
13330 			 * on active open.
13331 			 */
13332 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13333 				freemsg(mp);
13334 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13335 				    tcp, seg_ack, 0, TH_RST);
13336 				return;
13337 			}
13338 			/*
13339 			 * NOTE: RFC 793 pg. 72 says this should be
13340 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13341 			 * but that would mean we have an ack that ignored
13342 			 * our SYN.
13343 			 */
13344 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13345 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13346 				freemsg(mp);
13347 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13348 				    tcp, seg_ack, 0, TH_RST);
13349 				return;
13350 			}
13351 		}
13352 		break;
13353 	case TCPS_LISTEN:
13354 		/*
13355 		 * Only a TLI listener can come through this path when a
13356 		 * acceptor is going back to be a listener and a packet
13357 		 * for the acceptor hits the classifier. For a socket
13358 		 * listener, this can never happen because a listener
13359 		 * can never accept connection on itself and hence a
13360 		 * socket acceptor can not go back to being a listener.
13361 		 */
13362 		ASSERT(!TCP_IS_SOCKET(tcp));
13363 		/*FALLTHRU*/
13364 	case TCPS_CLOSED:
13365 	case TCPS_BOUND: {
13366 		conn_t	*new_connp;
13367 
13368 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
13369 		if (new_connp != NULL) {
13370 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13371 			return;
13372 		}
13373 		/* We failed to classify. For now just drop the packet */
13374 		freemsg(mp);
13375 		return;
13376 	}
13377 	case TCPS_IDLE:
13378 		/*
13379 		 * Handle the case where the tcp_clean_death() has happened
13380 		 * on a connection (application hasn't closed yet) but a packet
13381 		 * was already queued on squeue before tcp_clean_death()
13382 		 * was processed. Calling tcp_clean_death() twice on same
13383 		 * connection can result in weird behaviour.
13384 		 */
13385 		freemsg(mp);
13386 		return;
13387 	default:
13388 		break;
13389 	}
13390 
13391 	/*
13392 	 * Already on the correct queue/perimeter.
13393 	 * If this is a detached connection and not an eager
13394 	 * connection hanging off a listener then new data
13395 	 * (past the FIN) will cause a reset.
13396 	 * We do a special check here where it
13397 	 * is out of the main line, rather than check
13398 	 * if we are detached every time we see new
13399 	 * data down below.
13400 	 */
13401 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13402 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13403 		BUMP_MIB(&tcp_mib, tcpInClosed);
13404 		TCP_RECORD_TRACE(tcp,
13405 		    mp, TCP_TRACE_RECV_PKT);
13406 		freemsg(mp);
13407 		tcp_xmit_ctl("new data when detached", tcp,
13408 		    tcp->tcp_snxt, 0, TH_RST);
13409 		(void) tcp_clean_death(tcp, EPROTO, 12);
13410 		return;
13411 	}
13412 
13413 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13414 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13415 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13416 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13417 	mss = tcp->tcp_mss;
13418 
13419 	if (tcp->tcp_snd_ts_ok) {
13420 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13421 			/*
13422 			 * This segment is not acceptable.
13423 			 * Drop it and send back an ACK.
13424 			 */
13425 			freemsg(mp);
13426 			flags |= TH_ACK_NEEDED;
13427 			goto ack_check;
13428 		}
13429 	} else if (tcp->tcp_snd_sack_ok) {
13430 		ASSERT(tcp->tcp_sack_info != NULL);
13431 		tcpopt.tcp = tcp;
13432 		/*
13433 		 * SACK info in already updated in tcp_parse_options.  Ignore
13434 		 * all other TCP options...
13435 		 */
13436 		(void) tcp_parse_options(tcph, &tcpopt);
13437 	}
13438 try_again:;
13439 	gap = seg_seq - tcp->tcp_rnxt;
13440 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13441 	/*
13442 	 * gap is the amount of sequence space between what we expect to see
13443 	 * and what we got for seg_seq.  A positive value for gap means
13444 	 * something got lost.  A negative value means we got some old stuff.
13445 	 */
13446 	if (gap < 0) {
13447 		/* Old stuff present.  Is the SYN in there? */
13448 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13449 		    (seg_len != 0)) {
13450 			flags &= ~TH_SYN;
13451 			seg_seq++;
13452 			urp--;
13453 			/* Recompute the gaps after noting the SYN. */
13454 			goto try_again;
13455 		}
13456 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
13457 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
13458 		    (seg_len > -gap ? -gap : seg_len));
13459 		/* Remove the old stuff from seg_len. */
13460 		seg_len += gap;
13461 		/*
13462 		 * Anything left?
13463 		 * Make sure to check for unack'd FIN when rest of data
13464 		 * has been previously ack'd.
13465 		 */
13466 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13467 			/*
13468 			 * Resets are only valid if they lie within our offered
13469 			 * window.  If the RST bit is set, we just ignore this
13470 			 * segment.
13471 			 */
13472 			if (flags & TH_RST) {
13473 				freemsg(mp);
13474 				return;
13475 			}
13476 
13477 			/*
13478 			 * The arriving of dup data packets indicate that we
13479 			 * may have postponed an ack for too long, or the other
13480 			 * side's RTT estimate is out of shape. Start acking
13481 			 * more often.
13482 			 */
13483 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13484 			    tcp->tcp_rack_cnt >= 1 &&
13485 			    tcp->tcp_rack_abs_max > 2) {
13486 				tcp->tcp_rack_abs_max--;
13487 			}
13488 			tcp->tcp_rack_cur_max = 1;
13489 
13490 			/*
13491 			 * This segment is "unacceptable".  None of its
13492 			 * sequence space lies within our advertized window.
13493 			 *
13494 			 * Adjust seg_len to the original value for tracing.
13495 			 */
13496 			seg_len -= gap;
13497 			if (tcp->tcp_debug) {
13498 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13499 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13500 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13501 				    "seg_len %d, rnxt %u, snxt %u, %s",
13502 				    gap, rgap, flags, seg_seq, seg_ack,
13503 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13504 				    tcp_display(tcp, NULL,
13505 				    DISP_ADDR_AND_PORT));
13506 			}
13507 
13508 			/*
13509 			 * Arrange to send an ACK in response to the
13510 			 * unacceptable segment per RFC 793 page 69. There
13511 			 * is only one small difference between ours and the
13512 			 * acceptability test in the RFC - we accept ACK-only
13513 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13514 			 * will be generated.
13515 			 *
13516 			 * Note that we have to ACK an ACK-only packet at least
13517 			 * for stacks that send 0-length keep-alives with
13518 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13519 			 * section 4.2.3.6. As long as we don't ever generate
13520 			 * an unacceptable packet in response to an incoming
13521 			 * packet that is unacceptable, it should not cause
13522 			 * "ACK wars".
13523 			 */
13524 			flags |=  TH_ACK_NEEDED;
13525 
13526 			/*
13527 			 * Continue processing this segment in order to use the
13528 			 * ACK information it contains, but skip all other
13529 			 * sequence-number processing.	Processing the ACK
13530 			 * information is necessary in order to
13531 			 * re-synchronize connections that may have lost
13532 			 * synchronization.
13533 			 *
13534 			 * We clear seg_len and flag fields related to
13535 			 * sequence number processing as they are not
13536 			 * to be trusted for an unacceptable segment.
13537 			 */
13538 			seg_len = 0;
13539 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13540 			goto process_ack;
13541 		}
13542 
13543 		/* Fix seg_seq, and chew the gap off the front. */
13544 		seg_seq = tcp->tcp_rnxt;
13545 		urp += gap;
13546 		do {
13547 			mblk_t	*mp2;
13548 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13549 			    (uintptr_t)UINT_MAX);
13550 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13551 			if (gap > 0) {
13552 				mp->b_rptr = mp->b_wptr - gap;
13553 				break;
13554 			}
13555 			mp2 = mp;
13556 			mp = mp->b_cont;
13557 			freeb(mp2);
13558 		} while (gap < 0);
13559 		/*
13560 		 * If the urgent data has already been acknowledged, we
13561 		 * should ignore TH_URG below
13562 		 */
13563 		if (urp < 0)
13564 			flags &= ~TH_URG;
13565 	}
13566 	/*
13567 	 * rgap is the amount of stuff received out of window.  A negative
13568 	 * value is the amount out of window.
13569 	 */
13570 	if (rgap < 0) {
13571 		mblk_t	*mp2;
13572 
13573 		if (tcp->tcp_rwnd == 0) {
13574 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13575 		} else {
13576 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13577 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13578 		}
13579 
13580 		/*
13581 		 * seg_len does not include the FIN, so if more than
13582 		 * just the FIN is out of window, we act like we don't
13583 		 * see it.  (If just the FIN is out of window, rgap
13584 		 * will be zero and we will go ahead and acknowledge
13585 		 * the FIN.)
13586 		 */
13587 		flags &= ~TH_FIN;
13588 
13589 		/* Fix seg_len and make sure there is something left. */
13590 		seg_len += rgap;
13591 		if (seg_len <= 0) {
13592 			/*
13593 			 * Resets are only valid if they lie within our offered
13594 			 * window.  If the RST bit is set, we just ignore this
13595 			 * segment.
13596 			 */
13597 			if (flags & TH_RST) {
13598 				freemsg(mp);
13599 				return;
13600 			}
13601 
13602 			/* Per RFC 793, we need to send back an ACK. */
13603 			flags |= TH_ACK_NEEDED;
13604 
13605 			/*
13606 			 * Send SIGURG as soon as possible i.e. even
13607 			 * if the TH_URG was delivered in a window probe
13608 			 * packet (which will be unacceptable).
13609 			 *
13610 			 * We generate a signal if none has been generated
13611 			 * for this connection or if this is a new urgent
13612 			 * byte. Also send a zero-length "unmarked" message
13613 			 * to inform SIOCATMARK that this is not the mark.
13614 			 *
13615 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13616 			 * is sent up. This plus the check for old data
13617 			 * (gap >= 0) handles the wraparound of the sequence
13618 			 * number space without having to always track the
13619 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13620 			 * this max in its rcv_up variable).
13621 			 *
13622 			 * This prevents duplicate SIGURGS due to a "late"
13623 			 * zero-window probe when the T_EXDATA_IND has already
13624 			 * been sent up.
13625 			 */
13626 			if ((flags & TH_URG) &&
13627 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13628 			    tcp->tcp_urp_last))) {
13629 				mp1 = allocb(0, BPRI_MED);
13630 				if (mp1 == NULL) {
13631 					freemsg(mp);
13632 					return;
13633 				}
13634 				if (!TCP_IS_DETACHED(tcp) &&
13635 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13636 				    SIGURG)) {
13637 					/* Try again on the rexmit. */
13638 					freemsg(mp1);
13639 					freemsg(mp);
13640 					return;
13641 				}
13642 				/*
13643 				 * If the next byte would be the mark
13644 				 * then mark with MARKNEXT else mark
13645 				 * with NOTMARKNEXT.
13646 				 */
13647 				if (gap == 0 && urp == 0)
13648 					mp1->b_flag |= MSGMARKNEXT;
13649 				else
13650 					mp1->b_flag |= MSGNOTMARKNEXT;
13651 				freemsg(tcp->tcp_urp_mark_mp);
13652 				tcp->tcp_urp_mark_mp = mp1;
13653 				flags |= TH_SEND_URP_MARK;
13654 				tcp->tcp_urp_last_valid = B_TRUE;
13655 				tcp->tcp_urp_last = urp + seg_seq;
13656 			}
13657 			/*
13658 			 * If this is a zero window probe, continue to
13659 			 * process the ACK part.  But we need to set seg_len
13660 			 * to 0 to avoid data processing.  Otherwise just
13661 			 * drop the segment and send back an ACK.
13662 			 */
13663 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13664 				flags &= ~(TH_SYN | TH_URG);
13665 				seg_len = 0;
13666 				goto process_ack;
13667 			} else {
13668 				freemsg(mp);
13669 				goto ack_check;
13670 			}
13671 		}
13672 		/* Pitch out of window stuff off the end. */
13673 		rgap = seg_len;
13674 		mp2 = mp;
13675 		do {
13676 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13677 			    (uintptr_t)INT_MAX);
13678 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13679 			if (rgap < 0) {
13680 				mp2->b_wptr += rgap;
13681 				if ((mp1 = mp2->b_cont) != NULL) {
13682 					mp2->b_cont = NULL;
13683 					freemsg(mp1);
13684 				}
13685 				break;
13686 			}
13687 		} while ((mp2 = mp2->b_cont) != NULL);
13688 	}
13689 ok:;
13690 	/*
13691 	 * TCP should check ECN info for segments inside the window only.
13692 	 * Therefore the check should be done here.
13693 	 */
13694 	if (tcp->tcp_ecn_ok) {
13695 		if (flags & TH_CWR) {
13696 			tcp->tcp_ecn_echo_on = B_FALSE;
13697 		}
13698 		/*
13699 		 * Note that both ECN_CE and CWR can be set in the
13700 		 * same segment.  In this case, we once again turn
13701 		 * on ECN_ECHO.
13702 		 */
13703 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13704 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13705 
13706 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13707 				tcp->tcp_ecn_echo_on = B_TRUE;
13708 			}
13709 		} else {
13710 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13711 
13712 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13713 			    htonl(IPH_ECN_CE << 20)) {
13714 				tcp->tcp_ecn_echo_on = B_TRUE;
13715 			}
13716 		}
13717 	}
13718 
13719 	/*
13720 	 * Check whether we can update tcp_ts_recent.  This test is
13721 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13722 	 * Extensions for High Performance: An Update", Internet Draft.
13723 	 */
13724 	if (tcp->tcp_snd_ts_ok &&
13725 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13726 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13727 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13728 		tcp->tcp_last_rcv_lbolt = lbolt64;
13729 	}
13730 
13731 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13732 		/*
13733 		 * FIN in an out of order segment.  We record this in
13734 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13735 		 * Clear the FIN so that any check on FIN flag will fail.
13736 		 * Remember that FIN also counts in the sequence number
13737 		 * space.  So we need to ack out of order FIN only segments.
13738 		 */
13739 		if (flags & TH_FIN) {
13740 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13741 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13742 			flags &= ~TH_FIN;
13743 			flags |= TH_ACK_NEEDED;
13744 		}
13745 		if (seg_len > 0) {
13746 			/* Fill in the SACK blk list. */
13747 			if (tcp->tcp_snd_sack_ok) {
13748 				ASSERT(tcp->tcp_sack_info != NULL);
13749 				tcp_sack_insert(tcp->tcp_sack_list,
13750 				    seg_seq, seg_seq + seg_len,
13751 				    &(tcp->tcp_num_sack_blk));
13752 			}
13753 
13754 			/*
13755 			 * Attempt reassembly and see if we have something
13756 			 * ready to go.
13757 			 */
13758 			mp = tcp_reass(tcp, mp, seg_seq);
13759 			/* Always ack out of order packets */
13760 			flags |= TH_ACK_NEEDED | TH_PUSH;
13761 			if (mp) {
13762 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13763 				    (uintptr_t)INT_MAX);
13764 				seg_len = mp->b_cont ? msgdsize(mp) :
13765 					(int)(mp->b_wptr - mp->b_rptr);
13766 				seg_seq = tcp->tcp_rnxt;
13767 				/*
13768 				 * A gap is filled and the seq num and len
13769 				 * of the gap match that of a previously
13770 				 * received FIN, put the FIN flag back in.
13771 				 */
13772 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13773 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13774 					flags |= TH_FIN;
13775 					tcp->tcp_valid_bits &=
13776 					    ~TCP_OFO_FIN_VALID;
13777 				}
13778 			} else {
13779 				/*
13780 				 * Keep going even with NULL mp.
13781 				 * There may be a useful ACK or something else
13782 				 * we don't want to miss.
13783 				 *
13784 				 * But TCP should not perform fast retransmit
13785 				 * because of the ack number.  TCP uses
13786 				 * seg_len == 0 to determine if it is a pure
13787 				 * ACK.  And this is not a pure ACK.
13788 				 */
13789 				seg_len = 0;
13790 				ofo_seg = B_TRUE;
13791 			}
13792 		}
13793 	} else if (seg_len > 0) {
13794 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13795 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13796 		/*
13797 		 * If an out of order FIN was received before, and the seq
13798 		 * num and len of the new segment match that of the FIN,
13799 		 * put the FIN flag back in.
13800 		 */
13801 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13802 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13803 			flags |= TH_FIN;
13804 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13805 		}
13806 	}
13807 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13808 	if (flags & TH_RST) {
13809 		freemsg(mp);
13810 		switch (tcp->tcp_state) {
13811 		case TCPS_SYN_RCVD:
13812 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13813 			break;
13814 		case TCPS_ESTABLISHED:
13815 		case TCPS_FIN_WAIT_1:
13816 		case TCPS_FIN_WAIT_2:
13817 		case TCPS_CLOSE_WAIT:
13818 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13819 			break;
13820 		case TCPS_CLOSING:
13821 		case TCPS_LAST_ACK:
13822 			(void) tcp_clean_death(tcp, 0, 16);
13823 			break;
13824 		default:
13825 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13826 			(void) tcp_clean_death(tcp, ENXIO, 17);
13827 			break;
13828 		}
13829 		return;
13830 	}
13831 	if (flags & TH_SYN) {
13832 		/*
13833 		 * See RFC 793, Page 71
13834 		 *
13835 		 * The seq number must be in the window as it should
13836 		 * be "fixed" above.  If it is outside window, it should
13837 		 * be already rejected.  Note that we allow seg_seq to be
13838 		 * rnxt + rwnd because we want to accept 0 window probe.
13839 		 */
13840 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13841 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13842 		freemsg(mp);
13843 		/*
13844 		 * If the ACK flag is not set, just use our snxt as the
13845 		 * seq number of the RST segment.
13846 		 */
13847 		if (!(flags & TH_ACK)) {
13848 			seg_ack = tcp->tcp_snxt;
13849 		}
13850 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13851 		    TH_RST|TH_ACK);
13852 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13853 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13854 		return;
13855 	}
13856 	/*
13857 	 * urp could be -1 when the urp field in the packet is 0
13858 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13859 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13860 	 */
13861 	if (flags & TH_URG && urp >= 0) {
13862 		if (!tcp->tcp_urp_last_valid ||
13863 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13864 			/*
13865 			 * If we haven't generated the signal yet for this
13866 			 * urgent pointer value, do it now.  Also, send up a
13867 			 * zero-length M_DATA indicating whether or not this is
13868 			 * the mark. The latter is not needed when a
13869 			 * T_EXDATA_IND is sent up. However, if there are
13870 			 * allocation failures this code relies on the sender
13871 			 * retransmitting and the socket code for determining
13872 			 * the mark should not block waiting for the peer to
13873 			 * transmit. Thus, for simplicity we always send up the
13874 			 * mark indication.
13875 			 */
13876 			mp1 = allocb(0, BPRI_MED);
13877 			if (mp1 == NULL) {
13878 				freemsg(mp);
13879 				return;
13880 			}
13881 			if (!TCP_IS_DETACHED(tcp) &&
13882 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13883 				/* Try again on the rexmit. */
13884 				freemsg(mp1);
13885 				freemsg(mp);
13886 				return;
13887 			}
13888 			/*
13889 			 * Mark with NOTMARKNEXT for now.
13890 			 * The code below will change this to MARKNEXT
13891 			 * if we are at the mark.
13892 			 *
13893 			 * If there are allocation failures (e.g. in dupmsg
13894 			 * below) the next time tcp_rput_data sees the urgent
13895 			 * segment it will send up the MSG*MARKNEXT message.
13896 			 */
13897 			mp1->b_flag |= MSGNOTMARKNEXT;
13898 			freemsg(tcp->tcp_urp_mark_mp);
13899 			tcp->tcp_urp_mark_mp = mp1;
13900 			flags |= TH_SEND_URP_MARK;
13901 #ifdef DEBUG
13902 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13903 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13904 			    "last %x, %s",
13905 			    seg_seq, urp, tcp->tcp_urp_last,
13906 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13907 #endif /* DEBUG */
13908 			tcp->tcp_urp_last_valid = B_TRUE;
13909 			tcp->tcp_urp_last = urp + seg_seq;
13910 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13911 			/*
13912 			 * An allocation failure prevented the previous
13913 			 * tcp_rput_data from sending up the allocated
13914 			 * MSG*MARKNEXT message - send it up this time
13915 			 * around.
13916 			 */
13917 			flags |= TH_SEND_URP_MARK;
13918 		}
13919 
13920 		/*
13921 		 * If the urgent byte is in this segment, make sure that it is
13922 		 * all by itself.  This makes it much easier to deal with the
13923 		 * possibility of an allocation failure on the T_exdata_ind.
13924 		 * Note that seg_len is the number of bytes in the segment, and
13925 		 * urp is the offset into the segment of the urgent byte.
13926 		 * urp < seg_len means that the urgent byte is in this segment.
13927 		 */
13928 		if (urp < seg_len) {
13929 			if (seg_len != 1) {
13930 				uint32_t  tmp_rnxt;
13931 				/*
13932 				 * Break it up and feed it back in.
13933 				 * Re-attach the IP header.
13934 				 */
13935 				mp->b_rptr = iphdr;
13936 				if (urp > 0) {
13937 					/*
13938 					 * There is stuff before the urgent
13939 					 * byte.
13940 					 */
13941 					mp1 = dupmsg(mp);
13942 					if (!mp1) {
13943 						/*
13944 						 * Trim from urgent byte on.
13945 						 * The rest will come back.
13946 						 */
13947 						(void) adjmsg(mp,
13948 						    urp - seg_len);
13949 						tcp_rput_data(connp,
13950 						    mp, NULL);
13951 						return;
13952 					}
13953 					(void) adjmsg(mp1, urp - seg_len);
13954 					/* Feed this piece back in. */
13955 					tmp_rnxt = tcp->tcp_rnxt;
13956 					tcp_rput_data(connp, mp1, NULL);
13957 					/*
13958 					 * If the data passed back in was not
13959 					 * processed (ie: bad ACK) sending
13960 					 * the remainder back in will cause a
13961 					 * loop. In this case, drop the
13962 					 * packet and let the sender try
13963 					 * sending a good packet.
13964 					 */
13965 					if (tmp_rnxt == tcp->tcp_rnxt) {
13966 						freemsg(mp);
13967 						return;
13968 					}
13969 				}
13970 				if (urp != seg_len - 1) {
13971 					uint32_t  tmp_rnxt;
13972 					/*
13973 					 * There is stuff after the urgent
13974 					 * byte.
13975 					 */
13976 					mp1 = dupmsg(mp);
13977 					if (!mp1) {
13978 						/*
13979 						 * Trim everything beyond the
13980 						 * urgent byte.  The rest will
13981 						 * come back.
13982 						 */
13983 						(void) adjmsg(mp,
13984 						    urp + 1 - seg_len);
13985 						tcp_rput_data(connp,
13986 						    mp, NULL);
13987 						return;
13988 					}
13989 					(void) adjmsg(mp1, urp + 1 - seg_len);
13990 					tmp_rnxt = tcp->tcp_rnxt;
13991 					tcp_rput_data(connp, mp1, NULL);
13992 					/*
13993 					 * If the data passed back in was not
13994 					 * processed (ie: bad ACK) sending
13995 					 * the remainder back in will cause a
13996 					 * loop. In this case, drop the
13997 					 * packet and let the sender try
13998 					 * sending a good packet.
13999 					 */
14000 					if (tmp_rnxt == tcp->tcp_rnxt) {
14001 						freemsg(mp);
14002 						return;
14003 					}
14004 				}
14005 				tcp_rput_data(connp, mp, NULL);
14006 				return;
14007 			}
14008 			/*
14009 			 * This segment contains only the urgent byte.  We
14010 			 * have to allocate the T_exdata_ind, if we can.
14011 			 */
14012 			if (!tcp->tcp_urp_mp) {
14013 				struct T_exdata_ind *tei;
14014 				mp1 = allocb(sizeof (struct T_exdata_ind),
14015 				    BPRI_MED);
14016 				if (!mp1) {
14017 					/*
14018 					 * Sigh... It'll be back.
14019 					 * Generate any MSG*MARK message now.
14020 					 */
14021 					freemsg(mp);
14022 					seg_len = 0;
14023 					if (flags & TH_SEND_URP_MARK) {
14024 
14025 
14026 						ASSERT(tcp->tcp_urp_mark_mp);
14027 						tcp->tcp_urp_mark_mp->b_flag &=
14028 							~MSGNOTMARKNEXT;
14029 						tcp->tcp_urp_mark_mp->b_flag |=
14030 							MSGMARKNEXT;
14031 					}
14032 					goto ack_check;
14033 				}
14034 				mp1->b_datap->db_type = M_PROTO;
14035 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14036 				tei->PRIM_type = T_EXDATA_IND;
14037 				tei->MORE_flag = 0;
14038 				mp1->b_wptr = (uchar_t *)&tei[1];
14039 				tcp->tcp_urp_mp = mp1;
14040 #ifdef DEBUG
14041 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14042 				    "tcp_rput: allocated exdata_ind %s",
14043 				    tcp_display(tcp, NULL,
14044 				    DISP_PORT_ONLY));
14045 #endif /* DEBUG */
14046 				/*
14047 				 * There is no need to send a separate MSG*MARK
14048 				 * message since the T_EXDATA_IND will be sent
14049 				 * now.
14050 				 */
14051 				flags &= ~TH_SEND_URP_MARK;
14052 				freemsg(tcp->tcp_urp_mark_mp);
14053 				tcp->tcp_urp_mark_mp = NULL;
14054 			}
14055 			/*
14056 			 * Now we are all set.  On the next putnext upstream,
14057 			 * tcp_urp_mp will be non-NULL and will get prepended
14058 			 * to what has to be this piece containing the urgent
14059 			 * byte.  If for any reason we abort this segment below,
14060 			 * if it comes back, we will have this ready, or it
14061 			 * will get blown off in close.
14062 			 */
14063 		} else if (urp == seg_len) {
14064 			/*
14065 			 * The urgent byte is the next byte after this sequence
14066 			 * number. If there is data it is marked with
14067 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14068 			 * since it is not needed. Otherwise, if the code
14069 			 * above just allocated a zero-length tcp_urp_mark_mp
14070 			 * message, that message is tagged with MSGMARKNEXT.
14071 			 * Sending up these MSGMARKNEXT messages makes
14072 			 * SIOCATMARK work correctly even though
14073 			 * the T_EXDATA_IND will not be sent up until the
14074 			 * urgent byte arrives.
14075 			 */
14076 			if (seg_len != 0) {
14077 				flags |= TH_MARKNEXT_NEEDED;
14078 				freemsg(tcp->tcp_urp_mark_mp);
14079 				tcp->tcp_urp_mark_mp = NULL;
14080 				flags &= ~TH_SEND_URP_MARK;
14081 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14082 				flags |= TH_SEND_URP_MARK;
14083 				tcp->tcp_urp_mark_mp->b_flag &=
14084 					~MSGNOTMARKNEXT;
14085 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14086 			}
14087 #ifdef DEBUG
14088 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14089 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14090 			    seg_len, flags,
14091 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14092 #endif /* DEBUG */
14093 		} else {
14094 			/* Data left until we hit mark */
14095 #ifdef DEBUG
14096 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14097 			    "tcp_rput: URP %d bytes left, %s",
14098 			    urp - seg_len, tcp_display(tcp, NULL,
14099 			    DISP_PORT_ONLY));
14100 #endif /* DEBUG */
14101 		}
14102 	}
14103 
14104 process_ack:
14105 	if (!(flags & TH_ACK)) {
14106 		freemsg(mp);
14107 		goto xmit_check;
14108 	}
14109 	}
14110 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14111 
14112 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14113 		tcp->tcp_ip_forward_progress = B_TRUE;
14114 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14115 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
14116 			/* 3-way handshake complete - pass up the T_CONN_IND */
14117 			tcp_t	*listener = tcp->tcp_listener;
14118 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14119 
14120 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14121 			/*
14122 			 * We are here means eager is fine but it can
14123 			 * get a TH_RST at any point between now and till
14124 			 * accept completes and disappear. We need to
14125 			 * ensure that reference to eager is valid after
14126 			 * we get out of eager's perimeter. So we do
14127 			 * an extra refhold.
14128 			 */
14129 			CONN_INC_REF(connp);
14130 
14131 			/*
14132 			 * The listener also exists because of the refhold
14133 			 * done in tcp_conn_request. Its possible that it
14134 			 * might have closed. We will check that once we
14135 			 * get inside listeners context.
14136 			 */
14137 			CONN_INC_REF(listener->tcp_connp);
14138 			if (listener->tcp_connp->conn_sqp ==
14139 			    connp->conn_sqp) {
14140 				tcp_send_conn_ind(listener->tcp_connp, mp,
14141 				    listener->tcp_connp->conn_sqp);
14142 				CONN_DEC_REF(listener->tcp_connp);
14143 			} else if (!tcp->tcp_loopback) {
14144 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14145 				    tcp_send_conn_ind,
14146 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14147 			} else {
14148 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14149 				    tcp_send_conn_ind, listener->tcp_connp,
14150 				    SQTAG_TCP_CONN_IND);
14151 			}
14152 		}
14153 
14154 		if (tcp->tcp_active_open) {
14155 			/*
14156 			 * We are seeing the final ack in the three way
14157 			 * hand shake of a active open'ed connection
14158 			 * so we must send up a T_CONN_CON
14159 			 */
14160 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14161 				freemsg(mp);
14162 				return;
14163 			}
14164 			/*
14165 			 * Don't fuse the loopback endpoints for
14166 			 * simultaneous active opens.
14167 			 */
14168 			if (tcp->tcp_loopback) {
14169 				TCP_STAT(tcp_fusion_unfusable);
14170 				tcp->tcp_unfusable = B_TRUE;
14171 			}
14172 		}
14173 
14174 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14175 		bytes_acked--;
14176 		/* SYN was acked - making progress */
14177 		if (tcp->tcp_ipversion == IPV6_VERSION)
14178 			tcp->tcp_ip_forward_progress = B_TRUE;
14179 
14180 		/*
14181 		 * If SYN was retransmitted, need to reset all
14182 		 * retransmission info as this segment will be
14183 		 * treated as a dup ACK.
14184 		 */
14185 		if (tcp->tcp_rexmit) {
14186 			tcp->tcp_rexmit = B_FALSE;
14187 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14188 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14189 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14190 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14191 			tcp->tcp_ms_we_have_waited = 0;
14192 			tcp->tcp_cwnd = mss;
14193 		}
14194 
14195 		/*
14196 		 * We set the send window to zero here.
14197 		 * This is needed if there is data to be
14198 		 * processed already on the queue.
14199 		 * Later (at swnd_update label), the
14200 		 * "new_swnd > tcp_swnd" condition is satisfied
14201 		 * the XMIT_NEEDED flag is set in the current
14202 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14203 		 * called if there is already data on queue in
14204 		 * this state.
14205 		 */
14206 		tcp->tcp_swnd = 0;
14207 
14208 		if (new_swnd > tcp->tcp_max_swnd)
14209 			tcp->tcp_max_swnd = new_swnd;
14210 		tcp->tcp_swl1 = seg_seq;
14211 		tcp->tcp_swl2 = seg_ack;
14212 		tcp->tcp_state = TCPS_ESTABLISHED;
14213 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14214 
14215 		/* Fuse when both sides are in ESTABLISHED state */
14216 		if (tcp->tcp_loopback && do_tcp_fusion)
14217 			tcp_fuse(tcp, iphdr, tcph);
14218 
14219 	}
14220 	/* This code follows 4.4BSD-Lite2 mostly. */
14221 	if (bytes_acked < 0)
14222 		goto est;
14223 
14224 	/*
14225 	 * If TCP is ECN capable and the congestion experience bit is
14226 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14227 	 * done once per window (or more loosely, per RTT).
14228 	 */
14229 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14230 		tcp->tcp_cwr = B_FALSE;
14231 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14232 		if (!tcp->tcp_cwr) {
14233 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14234 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14235 			tcp->tcp_cwnd = npkt * mss;
14236 			/*
14237 			 * If the cwnd is 0, use the timer to clock out
14238 			 * new segments.  This is required by the ECN spec.
14239 			 */
14240 			if (npkt == 0) {
14241 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14242 				/*
14243 				 * This makes sure that when the ACK comes
14244 				 * back, we will increase tcp_cwnd by 1 MSS.
14245 				 */
14246 				tcp->tcp_cwnd_cnt = 0;
14247 			}
14248 			tcp->tcp_cwr = B_TRUE;
14249 			/*
14250 			 * This marks the end of the current window of in
14251 			 * flight data.  That is why we don't use
14252 			 * tcp_suna + tcp_swnd.  Only data in flight can
14253 			 * provide ECN info.
14254 			 */
14255 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14256 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14257 		}
14258 	}
14259 
14260 	mp1 = tcp->tcp_xmit_head;
14261 	if (bytes_acked == 0) {
14262 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14263 			int dupack_cnt;
14264 
14265 			BUMP_MIB(&tcp_mib, tcpInDupAck);
14266 			/*
14267 			 * Fast retransmit.  When we have seen exactly three
14268 			 * identical ACKs while we have unacked data
14269 			 * outstanding we take it as a hint that our peer
14270 			 * dropped something.
14271 			 *
14272 			 * If TCP is retransmitting, don't do fast retransmit.
14273 			 */
14274 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14275 			    ! tcp->tcp_rexmit) {
14276 				/* Do Limited Transmit */
14277 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14278 				    tcp_dupack_fast_retransmit) {
14279 					/*
14280 					 * RFC 3042
14281 					 *
14282 					 * What we need to do is temporarily
14283 					 * increase tcp_cwnd so that new
14284 					 * data can be sent if it is allowed
14285 					 * by the receive window (tcp_rwnd).
14286 					 * tcp_wput_data() will take care of
14287 					 * the rest.
14288 					 *
14289 					 * If the connection is SACK capable,
14290 					 * only do limited xmit when there
14291 					 * is SACK info.
14292 					 *
14293 					 * Note how tcp_cwnd is incremented.
14294 					 * The first dup ACK will increase
14295 					 * it by 1 MSS.  The second dup ACK
14296 					 * will increase it by 2 MSS.  This
14297 					 * means that only 1 new segment will
14298 					 * be sent for each dup ACK.
14299 					 */
14300 					if (tcp->tcp_unsent > 0 &&
14301 					    (!tcp->tcp_snd_sack_ok ||
14302 					    (tcp->tcp_snd_sack_ok &&
14303 					    tcp->tcp_notsack_list != NULL))) {
14304 						tcp->tcp_cwnd += mss <<
14305 						    (tcp->tcp_dupack_cnt - 1);
14306 						flags |= TH_LIMIT_XMIT;
14307 					}
14308 				} else if (dupack_cnt ==
14309 				    tcp_dupack_fast_retransmit) {
14310 
14311 				/*
14312 				 * If we have reduced tcp_ssthresh
14313 				 * because of ECN, do not reduce it again
14314 				 * unless it is already one window of data
14315 				 * away.  After one window of data, tcp_cwr
14316 				 * should then be cleared.  Note that
14317 				 * for non ECN capable connection, tcp_cwr
14318 				 * should always be false.
14319 				 *
14320 				 * Adjust cwnd since the duplicate
14321 				 * ack indicates that a packet was
14322 				 * dropped (due to congestion.)
14323 				 */
14324 				if (!tcp->tcp_cwr) {
14325 					npkt = ((tcp->tcp_snxt -
14326 					    tcp->tcp_suna) >> 1) / mss;
14327 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14328 					    mss;
14329 					tcp->tcp_cwnd = (npkt +
14330 					    tcp->tcp_dupack_cnt) * mss;
14331 				}
14332 				if (tcp->tcp_ecn_ok) {
14333 					tcp->tcp_cwr = B_TRUE;
14334 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14335 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14336 				}
14337 
14338 				/*
14339 				 * We do Hoe's algorithm.  Refer to her
14340 				 * paper "Improving the Start-up Behavior
14341 				 * of a Congestion Control Scheme for TCP,"
14342 				 * appeared in SIGCOMM'96.
14343 				 *
14344 				 * Save highest seq no we have sent so far.
14345 				 * Be careful about the invisible FIN byte.
14346 				 */
14347 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14348 				    (tcp->tcp_unsent == 0)) {
14349 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14350 				} else {
14351 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14352 				}
14353 
14354 				/*
14355 				 * Do not allow bursty traffic during.
14356 				 * fast recovery.  Refer to Fall and Floyd's
14357 				 * paper "Simulation-based Comparisons of
14358 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14359 				 * This is a best current practise.
14360 				 */
14361 				tcp->tcp_snd_burst = TCP_CWND_SS;
14362 
14363 				/*
14364 				 * For SACK:
14365 				 * Calculate tcp_pipe, which is the
14366 				 * estimated number of bytes in
14367 				 * network.
14368 				 *
14369 				 * tcp_fack is the highest sack'ed seq num
14370 				 * TCP has received.
14371 				 *
14372 				 * tcp_pipe is explained in the above quoted
14373 				 * Fall and Floyd's paper.  tcp_fack is
14374 				 * explained in Mathis and Mahdavi's
14375 				 * "Forward Acknowledgment: Refining TCP
14376 				 * Congestion Control" in SIGCOMM '96.
14377 				 */
14378 				if (tcp->tcp_snd_sack_ok) {
14379 					ASSERT(tcp->tcp_sack_info != NULL);
14380 					if (tcp->tcp_notsack_list != NULL) {
14381 						tcp->tcp_pipe = tcp->tcp_snxt -
14382 						    tcp->tcp_fack;
14383 						tcp->tcp_sack_snxt = seg_ack;
14384 						flags |= TH_NEED_SACK_REXMIT;
14385 					} else {
14386 						/*
14387 						 * Always initialize tcp_pipe
14388 						 * even though we don't have
14389 						 * any SACK info.  If later
14390 						 * we get SACK info and
14391 						 * tcp_pipe is not initialized,
14392 						 * funny things will happen.
14393 						 */
14394 						tcp->tcp_pipe =
14395 						    tcp->tcp_cwnd_ssthresh;
14396 					}
14397 				} else {
14398 					flags |= TH_REXMIT_NEEDED;
14399 				} /* tcp_snd_sack_ok */
14400 
14401 				} else {
14402 					/*
14403 					 * Here we perform congestion
14404 					 * avoidance, but NOT slow start.
14405 					 * This is known as the Fast
14406 					 * Recovery Algorithm.
14407 					 */
14408 					if (tcp->tcp_snd_sack_ok &&
14409 					    tcp->tcp_notsack_list != NULL) {
14410 						flags |= TH_NEED_SACK_REXMIT;
14411 						tcp->tcp_pipe -= mss;
14412 						if (tcp->tcp_pipe < 0)
14413 							tcp->tcp_pipe = 0;
14414 					} else {
14415 					/*
14416 					 * We know that one more packet has
14417 					 * left the pipe thus we can update
14418 					 * cwnd.
14419 					 */
14420 					cwnd = tcp->tcp_cwnd + mss;
14421 					if (cwnd > tcp->tcp_cwnd_max)
14422 						cwnd = tcp->tcp_cwnd_max;
14423 					tcp->tcp_cwnd = cwnd;
14424 					if (tcp->tcp_unsent > 0)
14425 						flags |= TH_XMIT_NEEDED;
14426 					}
14427 				}
14428 			}
14429 		} else if (tcp->tcp_zero_win_probe) {
14430 			/*
14431 			 * If the window has opened, need to arrange
14432 			 * to send additional data.
14433 			 */
14434 			if (new_swnd != 0) {
14435 				/* tcp_suna != tcp_snxt */
14436 				/* Packet contains a window update */
14437 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
14438 				tcp->tcp_zero_win_probe = 0;
14439 				tcp->tcp_timer_backoff = 0;
14440 				tcp->tcp_ms_we_have_waited = 0;
14441 
14442 				/*
14443 				 * Transmit starting with tcp_suna since
14444 				 * the one byte probe is not ack'ed.
14445 				 * If TCP has sent more than one identical
14446 				 * probe, tcp_rexmit will be set.  That means
14447 				 * tcp_ss_rexmit() will send out the one
14448 				 * byte along with new data.  Otherwise,
14449 				 * fake the retransmission.
14450 				 */
14451 				flags |= TH_XMIT_NEEDED;
14452 				if (!tcp->tcp_rexmit) {
14453 					tcp->tcp_rexmit = B_TRUE;
14454 					tcp->tcp_dupack_cnt = 0;
14455 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14456 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14457 				}
14458 			}
14459 		}
14460 		goto swnd_update;
14461 	}
14462 
14463 	/*
14464 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14465 	 * If the ACK value acks something that we have not yet sent, it might
14466 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14467 	 * other side.
14468 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14469 	 * state is handled above, so we can always just drop the segment and
14470 	 * send an ACK here.
14471 	 *
14472 	 * Should we send ACKs in response to ACK only segments?
14473 	 */
14474 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14475 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
14476 		/* drop the received segment */
14477 		freemsg(mp);
14478 
14479 		/*
14480 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14481 		 * greater than 0, check if the number of such
14482 		 * bogus ACks is greater than that count.  If yes,
14483 		 * don't send back any ACK.  This prevents TCP from
14484 		 * getting into an ACK storm if somehow an attacker
14485 		 * successfully spoofs an acceptable segment to our
14486 		 * peer.
14487 		 */
14488 		if (tcp_drop_ack_unsent_cnt > 0 &&
14489 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14490 			TCP_STAT(tcp_in_ack_unsent_drop);
14491 			return;
14492 		}
14493 		mp = tcp_ack_mp(tcp);
14494 		if (mp != NULL) {
14495 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14496 			BUMP_LOCAL(tcp->tcp_obsegs);
14497 			BUMP_MIB(&tcp_mib, tcpOutAck);
14498 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14499 		}
14500 		return;
14501 	}
14502 
14503 	/*
14504 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14505 	 * blocks that are covered by this ACK.
14506 	 */
14507 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14508 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14509 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14510 	}
14511 
14512 	/*
14513 	 * If we got an ACK after fast retransmit, check to see
14514 	 * if it is a partial ACK.  If it is not and the congestion
14515 	 * window was inflated to account for the other side's
14516 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14517 	 */
14518 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
14519 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14520 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14521 			tcp->tcp_dupack_cnt = 0;
14522 			/*
14523 			 * Restore the orig tcp_cwnd_ssthresh after
14524 			 * fast retransmit phase.
14525 			 */
14526 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14527 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14528 			}
14529 			tcp->tcp_rexmit_max = seg_ack;
14530 			tcp->tcp_cwnd_cnt = 0;
14531 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14532 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14533 
14534 			/*
14535 			 * Remove all notsack info to avoid confusion with
14536 			 * the next fast retrasnmit/recovery phase.
14537 			 */
14538 			if (tcp->tcp_snd_sack_ok &&
14539 			    tcp->tcp_notsack_list != NULL) {
14540 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14541 			}
14542 		} else {
14543 			if (tcp->tcp_snd_sack_ok &&
14544 			    tcp->tcp_notsack_list != NULL) {
14545 				flags |= TH_NEED_SACK_REXMIT;
14546 				tcp->tcp_pipe -= mss;
14547 				if (tcp->tcp_pipe < 0)
14548 					tcp->tcp_pipe = 0;
14549 			} else {
14550 				/*
14551 				 * Hoe's algorithm:
14552 				 *
14553 				 * Retransmit the unack'ed segment and
14554 				 * restart fast recovery.  Note that we
14555 				 * need to scale back tcp_cwnd to the
14556 				 * original value when we started fast
14557 				 * recovery.  This is to prevent overly
14558 				 * aggressive behaviour in sending new
14559 				 * segments.
14560 				 */
14561 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14562 					tcp_dupack_fast_retransmit * mss;
14563 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14564 				flags |= TH_REXMIT_NEEDED;
14565 			}
14566 		}
14567 	} else {
14568 		tcp->tcp_dupack_cnt = 0;
14569 		if (tcp->tcp_rexmit) {
14570 			/*
14571 			 * TCP is retranmitting.  If the ACK ack's all
14572 			 * outstanding data, update tcp_rexmit_max and
14573 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14574 			 * to the correct value.
14575 			 *
14576 			 * Note that SEQ_LEQ() is used.  This is to avoid
14577 			 * unnecessary fast retransmit caused by dup ACKs
14578 			 * received when TCP does slow start retransmission
14579 			 * after a time out.  During this phase, TCP may
14580 			 * send out segments which are already received.
14581 			 * This causes dup ACKs to be sent back.
14582 			 */
14583 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14584 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14585 					tcp->tcp_rexmit_nxt = seg_ack;
14586 				}
14587 				if (seg_ack != tcp->tcp_rexmit_max) {
14588 					flags |= TH_XMIT_NEEDED;
14589 				}
14590 			} else {
14591 				tcp->tcp_rexmit = B_FALSE;
14592 				tcp->tcp_xmit_zc_clean = B_FALSE;
14593 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14594 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14595 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14596 			}
14597 			tcp->tcp_ms_we_have_waited = 0;
14598 		}
14599 	}
14600 
14601 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14602 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14603 	tcp->tcp_suna = seg_ack;
14604 	if (tcp->tcp_zero_win_probe != 0) {
14605 		tcp->tcp_zero_win_probe = 0;
14606 		tcp->tcp_timer_backoff = 0;
14607 	}
14608 
14609 	/*
14610 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14611 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14612 	 * will not reach here.
14613 	 */
14614 	if (mp1 == NULL) {
14615 		goto fin_acked;
14616 	}
14617 
14618 	/*
14619 	 * Update the congestion window.
14620 	 *
14621 	 * If TCP is not ECN capable or TCP is ECN capable but the
14622 	 * congestion experience bit is not set, increase the tcp_cwnd as
14623 	 * usual.
14624 	 */
14625 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14626 		cwnd = tcp->tcp_cwnd;
14627 		add = mss;
14628 
14629 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14630 			/*
14631 			 * This is to prevent an increase of less than 1 MSS of
14632 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14633 			 * may send out tinygrams in order to preserve mblk
14634 			 * boundaries.
14635 			 *
14636 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14637 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14638 			 * increased by 1 MSS for every RTTs.
14639 			 */
14640 			if (tcp->tcp_cwnd_cnt <= 0) {
14641 				tcp->tcp_cwnd_cnt = cwnd + add;
14642 			} else {
14643 				tcp->tcp_cwnd_cnt -= add;
14644 				add = 0;
14645 			}
14646 		}
14647 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14648 	}
14649 
14650 	/* See if the latest urgent data has been acknowledged */
14651 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14652 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14653 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14654 
14655 	/* Can we update the RTT estimates? */
14656 	if (tcp->tcp_snd_ts_ok) {
14657 		/* Ignore zero timestamp echo-reply. */
14658 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14659 			tcp_set_rto(tcp, (int32_t)lbolt -
14660 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14661 		}
14662 
14663 		/* If needed, restart the timer. */
14664 		if (tcp->tcp_set_timer == 1) {
14665 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14666 			tcp->tcp_set_timer = 0;
14667 		}
14668 		/*
14669 		 * Update tcp_csuna in case the other side stops sending
14670 		 * us timestamps.
14671 		 */
14672 		tcp->tcp_csuna = tcp->tcp_snxt;
14673 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14674 		/*
14675 		 * An ACK sequence we haven't seen before, so get the RTT
14676 		 * and update the RTO. But first check if the timestamp is
14677 		 * valid to use.
14678 		 */
14679 		if ((mp1->b_next != NULL) &&
14680 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14681 			tcp_set_rto(tcp, (int32_t)lbolt -
14682 			    (int32_t)(intptr_t)mp1->b_prev);
14683 		else
14684 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14685 
14686 		/* Remeber the last sequence to be ACKed */
14687 		tcp->tcp_csuna = seg_ack;
14688 		if (tcp->tcp_set_timer == 1) {
14689 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14690 			tcp->tcp_set_timer = 0;
14691 		}
14692 	} else {
14693 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14694 	}
14695 
14696 	/* Eat acknowledged bytes off the xmit queue. */
14697 	for (;;) {
14698 		mblk_t	*mp2;
14699 		uchar_t	*wptr;
14700 
14701 		wptr = mp1->b_wptr;
14702 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14703 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14704 		if (bytes_acked < 0) {
14705 			mp1->b_rptr = wptr + bytes_acked;
14706 			/*
14707 			 * Set a new timestamp if all the bytes timed by the
14708 			 * old timestamp have been ack'ed.
14709 			 */
14710 			if (SEQ_GT(seg_ack,
14711 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14712 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14713 				mp1->b_next = NULL;
14714 			}
14715 			break;
14716 		}
14717 		mp1->b_next = NULL;
14718 		mp1->b_prev = NULL;
14719 		mp2 = mp1;
14720 		mp1 = mp1->b_cont;
14721 
14722 		/*
14723 		 * This notification is required for some zero-copy
14724 		 * clients to maintain a copy semantic. After the data
14725 		 * is ack'ed, client is safe to modify or reuse the buffer.
14726 		 */
14727 		if (tcp->tcp_snd_zcopy_aware &&
14728 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14729 			tcp_zcopy_notify(tcp);
14730 		freeb(mp2);
14731 		if (bytes_acked == 0) {
14732 			if (mp1 == NULL) {
14733 				/* Everything is ack'ed, clear the tail. */
14734 				tcp->tcp_xmit_tail = NULL;
14735 				/*
14736 				 * Cancel the timer unless we are still
14737 				 * waiting for an ACK for the FIN packet.
14738 				 */
14739 				if (tcp->tcp_timer_tid != 0 &&
14740 				    tcp->tcp_snxt == tcp->tcp_suna) {
14741 					(void) TCP_TIMER_CANCEL(tcp,
14742 					    tcp->tcp_timer_tid);
14743 					tcp->tcp_timer_tid = 0;
14744 				}
14745 				goto pre_swnd_update;
14746 			}
14747 			if (mp2 != tcp->tcp_xmit_tail)
14748 				break;
14749 			tcp->tcp_xmit_tail = mp1;
14750 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14751 			    (uintptr_t)INT_MAX);
14752 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14753 			    mp1->b_rptr);
14754 			break;
14755 		}
14756 		if (mp1 == NULL) {
14757 			/*
14758 			 * More was acked but there is nothing more
14759 			 * outstanding.  This means that the FIN was
14760 			 * just acked or that we're talking to a clown.
14761 			 */
14762 fin_acked:
14763 			ASSERT(tcp->tcp_fin_sent);
14764 			tcp->tcp_xmit_tail = NULL;
14765 			if (tcp->tcp_fin_sent) {
14766 				/* FIN was acked - making progress */
14767 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14768 				    !tcp->tcp_fin_acked)
14769 					tcp->tcp_ip_forward_progress = B_TRUE;
14770 				tcp->tcp_fin_acked = B_TRUE;
14771 				if (tcp->tcp_linger_tid != 0 &&
14772 				    TCP_TIMER_CANCEL(tcp,
14773 					tcp->tcp_linger_tid) >= 0) {
14774 					tcp_stop_lingering(tcp);
14775 				}
14776 			} else {
14777 				/*
14778 				 * We should never get here because
14779 				 * we have already checked that the
14780 				 * number of bytes ack'ed should be
14781 				 * smaller than or equal to what we
14782 				 * have sent so far (it is the
14783 				 * acceptability check of the ACK).
14784 				 * We can only get here if the send
14785 				 * queue is corrupted.
14786 				 *
14787 				 * Terminate the connection and
14788 				 * panic the system.  It is better
14789 				 * for us to panic instead of
14790 				 * continuing to avoid other disaster.
14791 				 */
14792 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14793 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14794 				panic("Memory corruption "
14795 				    "detected for connection %s.",
14796 				    tcp_display(tcp, NULL,
14797 					DISP_ADDR_AND_PORT));
14798 				/*NOTREACHED*/
14799 			}
14800 			goto pre_swnd_update;
14801 		}
14802 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14803 	}
14804 	if (tcp->tcp_unsent) {
14805 		flags |= TH_XMIT_NEEDED;
14806 	}
14807 pre_swnd_update:
14808 	tcp->tcp_xmit_head = mp1;
14809 swnd_update:
14810 	/*
14811 	 * The following check is different from most other implementations.
14812 	 * For bi-directional transfer, when segments are dropped, the
14813 	 * "normal" check will not accept a window update in those
14814 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14815 	 * segments which are outside receiver's window.  As TCP accepts
14816 	 * the ack in those retransmitted segments, if the window update in
14817 	 * the same segment is not accepted, TCP will incorrectly calculates
14818 	 * that it can send more segments.  This can create a deadlock
14819 	 * with the receiver if its window becomes zero.
14820 	 */
14821 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14822 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14823 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14824 		/*
14825 		 * The criteria for update is:
14826 		 *
14827 		 * 1. the segment acknowledges some data.  Or
14828 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14829 		 * 3. the segment is not old and the advertised window is
14830 		 * larger than the previous advertised window.
14831 		 */
14832 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14833 			flags |= TH_XMIT_NEEDED;
14834 		tcp->tcp_swnd = new_swnd;
14835 		if (new_swnd > tcp->tcp_max_swnd)
14836 			tcp->tcp_max_swnd = new_swnd;
14837 		tcp->tcp_swl1 = seg_seq;
14838 		tcp->tcp_swl2 = seg_ack;
14839 	}
14840 est:
14841 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14842 		switch (tcp->tcp_state) {
14843 		case TCPS_FIN_WAIT_1:
14844 			if (tcp->tcp_fin_acked) {
14845 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14846 				/*
14847 				 * We implement the non-standard BSD/SunOS
14848 				 * FIN_WAIT_2 flushing algorithm.
14849 				 * If there is no user attached to this
14850 				 * TCP endpoint, then this TCP struct
14851 				 * could hang around forever in FIN_WAIT_2
14852 				 * state if the peer forgets to send us
14853 				 * a FIN.  To prevent this, we wait only
14854 				 * 2*MSL (a convenient time value) for
14855 				 * the FIN to arrive.  If it doesn't show up,
14856 				 * we flush the TCP endpoint.  This algorithm,
14857 				 * though a violation of RFC-793, has worked
14858 				 * for over 10 years in BSD systems.
14859 				 * Note: SunOS 4.x waits 675 seconds before
14860 				 * flushing the FIN_WAIT_2 connection.
14861 				 */
14862 				TCP_TIMER_RESTART(tcp,
14863 				    tcp_fin_wait_2_flush_interval);
14864 			}
14865 			break;
14866 		case TCPS_FIN_WAIT_2:
14867 			break;	/* Shutdown hook? */
14868 		case TCPS_LAST_ACK:
14869 			freemsg(mp);
14870 			if (tcp->tcp_fin_acked) {
14871 				(void) tcp_clean_death(tcp, 0, 19);
14872 				return;
14873 			}
14874 			goto xmit_check;
14875 		case TCPS_CLOSING:
14876 			if (tcp->tcp_fin_acked) {
14877 				tcp->tcp_state = TCPS_TIME_WAIT;
14878 				if (!TCP_IS_DETACHED(tcp)) {
14879 					TCP_TIMER_RESTART(tcp,
14880 					    tcp_time_wait_interval);
14881 				} else {
14882 					tcp_time_wait_append(tcp);
14883 					TCP_DBGSTAT(tcp_rput_time_wait);
14884 				}
14885 			}
14886 			/*FALLTHRU*/
14887 		case TCPS_CLOSE_WAIT:
14888 			freemsg(mp);
14889 			goto xmit_check;
14890 		default:
14891 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14892 			break;
14893 		}
14894 	}
14895 	if (flags & TH_FIN) {
14896 		/* Make sure we ack the fin */
14897 		flags |= TH_ACK_NEEDED;
14898 		if (!tcp->tcp_fin_rcvd) {
14899 			tcp->tcp_fin_rcvd = B_TRUE;
14900 			tcp->tcp_rnxt++;
14901 			tcph = tcp->tcp_tcph;
14902 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14903 
14904 			/*
14905 			 * Generate the ordrel_ind at the end unless we
14906 			 * are an eager guy.
14907 			 * In the eager case tcp_rsrv will do this when run
14908 			 * after tcp_accept is done.
14909 			 */
14910 			if (tcp->tcp_listener == NULL &&
14911 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14912 				flags |= TH_ORDREL_NEEDED;
14913 			switch (tcp->tcp_state) {
14914 			case TCPS_SYN_RCVD:
14915 			case TCPS_ESTABLISHED:
14916 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14917 				/* Keepalive? */
14918 				break;
14919 			case TCPS_FIN_WAIT_1:
14920 				if (!tcp->tcp_fin_acked) {
14921 					tcp->tcp_state = TCPS_CLOSING;
14922 					break;
14923 				}
14924 				/* FALLTHRU */
14925 			case TCPS_FIN_WAIT_2:
14926 				tcp->tcp_state = TCPS_TIME_WAIT;
14927 				if (!TCP_IS_DETACHED(tcp)) {
14928 					TCP_TIMER_RESTART(tcp,
14929 					    tcp_time_wait_interval);
14930 				} else {
14931 					tcp_time_wait_append(tcp);
14932 					TCP_DBGSTAT(tcp_rput_time_wait);
14933 				}
14934 				if (seg_len) {
14935 					/*
14936 					 * implies data piggybacked on FIN.
14937 					 * break to handle data.
14938 					 */
14939 					break;
14940 				}
14941 				freemsg(mp);
14942 				goto ack_check;
14943 			}
14944 		}
14945 	}
14946 	if (mp == NULL)
14947 		goto xmit_check;
14948 	if (seg_len == 0) {
14949 		freemsg(mp);
14950 		goto xmit_check;
14951 	}
14952 	if (mp->b_rptr == mp->b_wptr) {
14953 		/*
14954 		 * The header has been consumed, so we remove the
14955 		 * zero-length mblk here.
14956 		 */
14957 		mp1 = mp;
14958 		mp = mp->b_cont;
14959 		freeb(mp1);
14960 	}
14961 	tcph = tcp->tcp_tcph;
14962 	tcp->tcp_rack_cnt++;
14963 	{
14964 		uint32_t cur_max;
14965 
14966 		cur_max = tcp->tcp_rack_cur_max;
14967 		if (tcp->tcp_rack_cnt >= cur_max) {
14968 			/*
14969 			 * We have more unacked data than we should - send
14970 			 * an ACK now.
14971 			 */
14972 			flags |= TH_ACK_NEEDED;
14973 			cur_max++;
14974 			if (cur_max > tcp->tcp_rack_abs_max)
14975 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14976 			else
14977 				tcp->tcp_rack_cur_max = cur_max;
14978 		} else if (TCP_IS_DETACHED(tcp)) {
14979 			/* We don't have an ACK timer for detached TCP. */
14980 			flags |= TH_ACK_NEEDED;
14981 		} else if (seg_len < mss) {
14982 			/*
14983 			 * If we get a segment that is less than an mss, and we
14984 			 * already have unacknowledged data, and the amount
14985 			 * unacknowledged is not a multiple of mss, then we
14986 			 * better generate an ACK now.  Otherwise, this may be
14987 			 * the tail piece of a transaction, and we would rather
14988 			 * wait for the response.
14989 			 */
14990 			uint32_t udif;
14991 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14992 			    (uintptr_t)INT_MAX);
14993 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14994 			if (udif && (udif % mss))
14995 				flags |= TH_ACK_NEEDED;
14996 			else
14997 				flags |= TH_ACK_TIMER_NEEDED;
14998 		} else {
14999 			/* Start delayed ack timer */
15000 			flags |= TH_ACK_TIMER_NEEDED;
15001 		}
15002 	}
15003 	tcp->tcp_rnxt += seg_len;
15004 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15005 
15006 	/* Update SACK list */
15007 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15008 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15009 		    &(tcp->tcp_num_sack_blk));
15010 	}
15011 
15012 	if (tcp->tcp_urp_mp) {
15013 		tcp->tcp_urp_mp->b_cont = mp;
15014 		mp = tcp->tcp_urp_mp;
15015 		tcp->tcp_urp_mp = NULL;
15016 		/* Ready for a new signal. */
15017 		tcp->tcp_urp_last_valid = B_FALSE;
15018 #ifdef DEBUG
15019 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15020 		    "tcp_rput: sending exdata_ind %s",
15021 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15022 #endif /* DEBUG */
15023 	}
15024 
15025 	/*
15026 	 * Check for ancillary data changes compared to last segment.
15027 	 */
15028 	if (tcp->tcp_ipv6_recvancillary != 0) {
15029 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15030 		if (mp == NULL)
15031 			return;
15032 	}
15033 
15034 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15035 		/*
15036 		 * Side queue inbound data until the accept happens.
15037 		 * tcp_accept/tcp_rput drains this when the accept happens.
15038 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15039 		 * T_EXDATA_IND) it is queued on b_next.
15040 		 * XXX Make urgent data use this. Requires:
15041 		 *	Removing tcp_listener check for TH_URG
15042 		 *	Making M_PCPROTO and MARK messages skip the eager case
15043 		 */
15044 		tcp_rcv_enqueue(tcp, mp, seg_len);
15045 	} else {
15046 		if (mp->b_datap->db_type != M_DATA ||
15047 		    (flags & TH_MARKNEXT_NEEDED)) {
15048 			if (tcp->tcp_rcv_list != NULL) {
15049 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15050 			}
15051 			ASSERT(tcp->tcp_rcv_list == NULL ||
15052 			    tcp->tcp_fused_sigurg);
15053 			if (flags & TH_MARKNEXT_NEEDED) {
15054 #ifdef DEBUG
15055 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15056 				    "tcp_rput: sending MSGMARKNEXT %s",
15057 				    tcp_display(tcp, NULL,
15058 				    DISP_PORT_ONLY));
15059 #endif /* DEBUG */
15060 				mp->b_flag |= MSGMARKNEXT;
15061 				flags &= ~TH_MARKNEXT_NEEDED;
15062 			}
15063 			putnext(tcp->tcp_rq, mp);
15064 			if (!canputnext(tcp->tcp_rq))
15065 				tcp->tcp_rwnd -= seg_len;
15066 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
15067 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
15068 		    (sqp != NULL)) {
15069 			if (tcp->tcp_rcv_list != NULL) {
15070 				/*
15071 				 * Enqueue the new segment first and then
15072 				 * call tcp_rcv_drain() to send all data
15073 				 * up.  The other way to do this is to
15074 				 * send all queued data up and then call
15075 				 * putnext() to send the new segment up.
15076 				 * This way can remove the else part later
15077 				 * on.
15078 				 *
15079 				 * We don't this to avoid one more call to
15080 				 * canputnext() as tcp_rcv_drain() needs to
15081 				 * call canputnext().
15082 				 */
15083 				tcp_rcv_enqueue(tcp, mp, seg_len);
15084 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15085 			} else {
15086 				putnext(tcp->tcp_rq, mp);
15087 				if (!canputnext(tcp->tcp_rq))
15088 					tcp->tcp_rwnd -= seg_len;
15089 			}
15090 		} else {
15091 			/*
15092 			 * Enqueue all packets when processing an mblk
15093 			 * from the co queue and also enqueue normal packets.
15094 			 */
15095 			tcp_rcv_enqueue(tcp, mp, seg_len);
15096 		}
15097 		/*
15098 		 * Make sure the timer is running if we have data waiting
15099 		 * for a push bit. This provides resiliency against
15100 		 * implementations that do not correctly generate push bits.
15101 		 */
15102 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
15103 		    tcp->tcp_push_tid == 0) {
15104 			/*
15105 			 * The connection may be closed at this point, so don't
15106 			 * do anything for a detached tcp.
15107 			 */
15108 			if (!TCP_IS_DETACHED(tcp))
15109 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15110 				    tcp_push_timer,
15111 				    MSEC_TO_TICK(tcp_push_timer_interval));
15112 		}
15113 	}
15114 xmit_check:
15115 	/* Is there anything left to do? */
15116 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15117 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15118 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15119 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15120 		goto done;
15121 
15122 	/* Any transmit work to do and a non-zero window? */
15123 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15124 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15125 		if (flags & TH_REXMIT_NEEDED) {
15126 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15127 
15128 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
15129 			if (snd_size > mss)
15130 				snd_size = mss;
15131 			if (snd_size > tcp->tcp_swnd)
15132 				snd_size = tcp->tcp_swnd;
15133 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15134 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15135 			    B_TRUE);
15136 
15137 			if (mp1 != NULL) {
15138 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15139 				tcp->tcp_csuna = tcp->tcp_snxt;
15140 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
15141 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
15142 				TCP_RECORD_TRACE(tcp, mp1,
15143 				    TCP_TRACE_SEND_PKT);
15144 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15145 			}
15146 		}
15147 		if (flags & TH_NEED_SACK_REXMIT) {
15148 			tcp_sack_rxmit(tcp, &flags);
15149 		}
15150 		/*
15151 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15152 		 * out new segment.  Note that tcp_rexmit should not be
15153 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15154 		 */
15155 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15156 			if (!tcp->tcp_rexmit) {
15157 				tcp_wput_data(tcp, NULL, B_FALSE);
15158 			} else {
15159 				tcp_ss_rexmit(tcp);
15160 			}
15161 		}
15162 		/*
15163 		 * Adjust tcp_cwnd back to normal value after sending
15164 		 * new data segments.
15165 		 */
15166 		if (flags & TH_LIMIT_XMIT) {
15167 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15168 			/*
15169 			 * This will restart the timer.  Restarting the
15170 			 * timer is used to avoid a timeout before the
15171 			 * limited transmitted segment's ACK gets back.
15172 			 */
15173 			if (tcp->tcp_xmit_head != NULL)
15174 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15175 		}
15176 
15177 		/* Anything more to do? */
15178 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15179 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15180 			goto done;
15181 	}
15182 ack_check:
15183 	if (flags & TH_SEND_URP_MARK) {
15184 		ASSERT(tcp->tcp_urp_mark_mp);
15185 		/*
15186 		 * Send up any queued data and then send the mark message
15187 		 */
15188 		if (tcp->tcp_rcv_list != NULL) {
15189 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15190 		}
15191 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15192 
15193 		mp1 = tcp->tcp_urp_mark_mp;
15194 		tcp->tcp_urp_mark_mp = NULL;
15195 #ifdef DEBUG
15196 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15197 		    "tcp_rput: sending zero-length %s %s",
15198 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15199 		    "MSGNOTMARKNEXT"),
15200 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15201 #endif /* DEBUG */
15202 		putnext(tcp->tcp_rq, mp1);
15203 		flags &= ~TH_SEND_URP_MARK;
15204 	}
15205 	if (flags & TH_ACK_NEEDED) {
15206 		/*
15207 		 * Time to send an ack for some reason.
15208 		 */
15209 		mp1 = tcp_ack_mp(tcp);
15210 
15211 		if (mp1 != NULL) {
15212 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15213 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15214 			BUMP_LOCAL(tcp->tcp_obsegs);
15215 			BUMP_MIB(&tcp_mib, tcpOutAck);
15216 		}
15217 		if (tcp->tcp_ack_tid != 0) {
15218 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15219 			tcp->tcp_ack_tid = 0;
15220 		}
15221 	}
15222 	if (flags & TH_ACK_TIMER_NEEDED) {
15223 		/*
15224 		 * Arrange for deferred ACK or push wait timeout.
15225 		 * Start timer if it is not already running.
15226 		 */
15227 		if (tcp->tcp_ack_tid == 0) {
15228 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15229 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15230 			    (clock_t)tcp_local_dack_interval :
15231 			    (clock_t)tcp_deferred_ack_interval));
15232 		}
15233 	}
15234 	if (flags & TH_ORDREL_NEEDED) {
15235 		/*
15236 		 * Send up the ordrel_ind unless we are an eager guy.
15237 		 * In the eager case tcp_rsrv will do this when run
15238 		 * after tcp_accept is done.
15239 		 */
15240 		ASSERT(tcp->tcp_listener == NULL);
15241 		if (tcp->tcp_rcv_list != NULL) {
15242 			/*
15243 			 * Push any mblk(s) enqueued from co processing.
15244 			 */
15245 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15246 		}
15247 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15248 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15249 			tcp->tcp_ordrel_done = B_TRUE;
15250 			putnext(tcp->tcp_rq, mp1);
15251 			if (tcp->tcp_deferred_clean_death) {
15252 				/*
15253 				 * tcp_clean_death was deferred
15254 				 * for T_ORDREL_IND - do it now
15255 				 */
15256 				(void) tcp_clean_death(tcp,
15257 				    tcp->tcp_client_errno, 20);
15258 				tcp->tcp_deferred_clean_death =	B_FALSE;
15259 			}
15260 		} else {
15261 			/*
15262 			 * Run the orderly release in the
15263 			 * service routine.
15264 			 */
15265 			qenable(tcp->tcp_rq);
15266 			/*
15267 			 * Caveat(XXX): The machine may be so
15268 			 * overloaded that tcp_rsrv() is not scheduled
15269 			 * until after the endpoint has transitioned
15270 			 * to TCPS_TIME_WAIT
15271 			 * and tcp_time_wait_interval expires. Then
15272 			 * tcp_timer() will blow away state in tcp_t
15273 			 * and T_ORDREL_IND will never be delivered
15274 			 * upstream. Unlikely but potentially
15275 			 * a problem.
15276 			 */
15277 		}
15278 	}
15279 done:
15280 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15281 }
15282 
15283 /*
15284  * This function does PAWS protection check. Returns B_TRUE if the
15285  * segment passes the PAWS test, else returns B_FALSE.
15286  */
15287 boolean_t
15288 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15289 {
15290 	uint8_t	flags;
15291 	int	options;
15292 	uint8_t *up;
15293 
15294 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15295 	/*
15296 	 * If timestamp option is aligned nicely, get values inline,
15297 	 * otherwise call general routine to parse.  Only do that
15298 	 * if timestamp is the only option.
15299 	 */
15300 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15301 	    TCPOPT_REAL_TS_LEN &&
15302 	    OK_32PTR((up = ((uint8_t *)tcph) +
15303 	    TCP_MIN_HEADER_LENGTH)) &&
15304 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15305 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15306 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15307 
15308 		options = TCP_OPT_TSTAMP_PRESENT;
15309 	} else {
15310 		if (tcp->tcp_snd_sack_ok) {
15311 			tcpoptp->tcp = tcp;
15312 		} else {
15313 			tcpoptp->tcp = NULL;
15314 		}
15315 		options = tcp_parse_options(tcph, tcpoptp);
15316 	}
15317 
15318 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15319 		/*
15320 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15321 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15322 		 */
15323 		if ((flags & TH_RST) == 0 &&
15324 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15325 		    tcp->tcp_ts_recent)) {
15326 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15327 			    PAWS_TIMEOUT)) {
15328 				/* This segment is not acceptable. */
15329 				return (B_FALSE);
15330 			} else {
15331 				/*
15332 				 * Connection has been idle for
15333 				 * too long.  Reset the timestamp
15334 				 * and assume the segment is valid.
15335 				 */
15336 				tcp->tcp_ts_recent =
15337 				    tcpoptp->tcp_opt_ts_val;
15338 			}
15339 		}
15340 	} else {
15341 		/*
15342 		 * If we don't get a timestamp on every packet, we
15343 		 * figure we can't really trust 'em, so we stop sending
15344 		 * and parsing them.
15345 		 */
15346 		tcp->tcp_snd_ts_ok = B_FALSE;
15347 
15348 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15349 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15350 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15351 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
15352 		if (tcp->tcp_snd_sack_ok) {
15353 			ASSERT(tcp->tcp_sack_info != NULL);
15354 			tcp->tcp_max_sack_blk = 4;
15355 		}
15356 	}
15357 	return (B_TRUE);
15358 }
15359 
15360 /*
15361  * Attach ancillary data to a received TCP segments for the
15362  * ancillary pieces requested by the application that are
15363  * different than they were in the previous data segment.
15364  *
15365  * Save the "current" values once memory allocation is ok so that
15366  * when memory allocation fails we can just wait for the next data segment.
15367  */
15368 static mblk_t *
15369 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15370 {
15371 	struct T_optdata_ind *todi;
15372 	int optlen;
15373 	uchar_t *optptr;
15374 	struct T_opthdr *toh;
15375 	uint_t addflag;	/* Which pieces to add */
15376 	mblk_t *mp1;
15377 
15378 	optlen = 0;
15379 	addflag = 0;
15380 	/* If app asked for pktinfo and the index has changed ... */
15381 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15382 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15383 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15384 		optlen += sizeof (struct T_opthdr) +
15385 		    sizeof (struct in6_pktinfo);
15386 		addflag |= TCP_IPV6_RECVPKTINFO;
15387 	}
15388 	/* If app asked for hoplimit and it has changed ... */
15389 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15390 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15391 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15392 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15393 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15394 	}
15395 	/* If app asked for tclass and it has changed ... */
15396 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15397 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15398 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15399 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15400 		addflag |= TCP_IPV6_RECVTCLASS;
15401 	}
15402 	/* If app asked for hopbyhop headers and it has changed ... */
15403 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15404 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15405 		(ipp->ipp_fields & IPPF_HOPOPTS),
15406 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15407 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
15408 		addflag |= TCP_IPV6_RECVHOPOPTS;
15409 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
15410 		    &tcp->tcp_hopoptslen,
15411 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15412 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15413 			return (mp);
15414 	}
15415 	/* If app asked for dst headers before routing headers ... */
15416 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15417 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15418 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15419 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15420 		optlen += sizeof (struct T_opthdr) +
15421 		    ipp->ipp_rtdstoptslen;
15422 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15423 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
15424 		    &tcp->tcp_rtdstoptslen,
15425 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15426 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15427 			return (mp);
15428 	}
15429 	/* If app asked for routing headers and it has changed ... */
15430 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15431 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15432 		(ipp->ipp_fields & IPPF_RTHDR),
15433 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15434 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15435 		addflag |= TCP_IPV6_RECVRTHDR;
15436 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
15437 		    &tcp->tcp_rthdrlen,
15438 		    (ipp->ipp_fields & IPPF_RTHDR),
15439 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15440 			return (mp);
15441 	}
15442 	/* If app asked for dest headers and it has changed ... */
15443 	if ((tcp->tcp_ipv6_recvancillary &
15444 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15445 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15446 		(ipp->ipp_fields & IPPF_DSTOPTS),
15447 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15448 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15449 		addflag |= TCP_IPV6_RECVDSTOPTS;
15450 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
15451 		    &tcp->tcp_dstoptslen,
15452 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15453 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15454 			return (mp);
15455 	}
15456 
15457 	if (optlen == 0) {
15458 		/* Nothing to add */
15459 		return (mp);
15460 	}
15461 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15462 	if (mp1 == NULL) {
15463 		/*
15464 		 * Defer sending ancillary data until the next TCP segment
15465 		 * arrives.
15466 		 */
15467 		return (mp);
15468 	}
15469 	mp1->b_cont = mp;
15470 	mp = mp1;
15471 	mp->b_wptr += sizeof (*todi) + optlen;
15472 	mp->b_datap->db_type = M_PROTO;
15473 	todi = (struct T_optdata_ind *)mp->b_rptr;
15474 	todi->PRIM_type = T_OPTDATA_IND;
15475 	todi->DATA_flag = 1;	/* MORE data */
15476 	todi->OPT_length = optlen;
15477 	todi->OPT_offset = sizeof (*todi);
15478 	optptr = (uchar_t *)&todi[1];
15479 	/*
15480 	 * If app asked for pktinfo and the index has changed ...
15481 	 * Note that the local address never changes for the connection.
15482 	 */
15483 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15484 		struct in6_pktinfo *pkti;
15485 
15486 		toh = (struct T_opthdr *)optptr;
15487 		toh->level = IPPROTO_IPV6;
15488 		toh->name = IPV6_PKTINFO;
15489 		toh->len = sizeof (*toh) + sizeof (*pkti);
15490 		toh->status = 0;
15491 		optptr += sizeof (*toh);
15492 		pkti = (struct in6_pktinfo *)optptr;
15493 		if (tcp->tcp_ipversion == IPV6_VERSION)
15494 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15495 		else
15496 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15497 			    &pkti->ipi6_addr);
15498 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15499 		optptr += sizeof (*pkti);
15500 		ASSERT(OK_32PTR(optptr));
15501 		/* Save as "last" value */
15502 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15503 	}
15504 	/* If app asked for hoplimit and it has changed ... */
15505 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15506 		toh = (struct T_opthdr *)optptr;
15507 		toh->level = IPPROTO_IPV6;
15508 		toh->name = IPV6_HOPLIMIT;
15509 		toh->len = sizeof (*toh) + sizeof (uint_t);
15510 		toh->status = 0;
15511 		optptr += sizeof (*toh);
15512 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15513 		optptr += sizeof (uint_t);
15514 		ASSERT(OK_32PTR(optptr));
15515 		/* Save as "last" value */
15516 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15517 	}
15518 	/* If app asked for tclass and it has changed ... */
15519 	if (addflag & TCP_IPV6_RECVTCLASS) {
15520 		toh = (struct T_opthdr *)optptr;
15521 		toh->level = IPPROTO_IPV6;
15522 		toh->name = IPV6_TCLASS;
15523 		toh->len = sizeof (*toh) + sizeof (uint_t);
15524 		toh->status = 0;
15525 		optptr += sizeof (*toh);
15526 		*(uint_t *)optptr = ipp->ipp_tclass;
15527 		optptr += sizeof (uint_t);
15528 		ASSERT(OK_32PTR(optptr));
15529 		/* Save as "last" value */
15530 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15531 	}
15532 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15533 		toh = (struct T_opthdr *)optptr;
15534 		toh->level = IPPROTO_IPV6;
15535 		toh->name = IPV6_HOPOPTS;
15536 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
15537 		toh->status = 0;
15538 		optptr += sizeof (*toh);
15539 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
15540 		optptr += ipp->ipp_hopoptslen;
15541 		ASSERT(OK_32PTR(optptr));
15542 		/* Save as last value */
15543 		tcp_savebuf((void **)&tcp->tcp_hopopts,
15544 		    &tcp->tcp_hopoptslen,
15545 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15546 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15547 	}
15548 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15549 		toh = (struct T_opthdr *)optptr;
15550 		toh->level = IPPROTO_IPV6;
15551 		toh->name = IPV6_RTHDRDSTOPTS;
15552 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15553 		toh->status = 0;
15554 		optptr += sizeof (*toh);
15555 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15556 		optptr += ipp->ipp_rtdstoptslen;
15557 		ASSERT(OK_32PTR(optptr));
15558 		/* Save as last value */
15559 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
15560 		    &tcp->tcp_rtdstoptslen,
15561 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15562 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15563 	}
15564 	if (addflag & TCP_IPV6_RECVRTHDR) {
15565 		toh = (struct T_opthdr *)optptr;
15566 		toh->level = IPPROTO_IPV6;
15567 		toh->name = IPV6_RTHDR;
15568 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15569 		toh->status = 0;
15570 		optptr += sizeof (*toh);
15571 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15572 		optptr += ipp->ipp_rthdrlen;
15573 		ASSERT(OK_32PTR(optptr));
15574 		/* Save as last value */
15575 		tcp_savebuf((void **)&tcp->tcp_rthdr,
15576 		    &tcp->tcp_rthdrlen,
15577 		    (ipp->ipp_fields & IPPF_RTHDR),
15578 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15579 	}
15580 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15581 		toh = (struct T_opthdr *)optptr;
15582 		toh->level = IPPROTO_IPV6;
15583 		toh->name = IPV6_DSTOPTS;
15584 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15585 		toh->status = 0;
15586 		optptr += sizeof (*toh);
15587 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15588 		optptr += ipp->ipp_dstoptslen;
15589 		ASSERT(OK_32PTR(optptr));
15590 		/* Save as last value */
15591 		tcp_savebuf((void **)&tcp->tcp_dstopts,
15592 		    &tcp->tcp_dstoptslen,
15593 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15594 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15595 	}
15596 	ASSERT(optptr == mp->b_wptr);
15597 	return (mp);
15598 }
15599 
15600 
15601 /*
15602  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15603  * or a "bad" IRE detected by tcp_adapt_ire.
15604  * We can't tell if the failure was due to the laddr or the faddr
15605  * thus we clear out all addresses and ports.
15606  */
15607 static void
15608 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15609 {
15610 	queue_t	*q = tcp->tcp_rq;
15611 	tcph_t	*tcph;
15612 	struct T_error_ack *tea;
15613 	conn_t	*connp = tcp->tcp_connp;
15614 
15615 
15616 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15617 
15618 	if (mp->b_cont) {
15619 		freemsg(mp->b_cont);
15620 		mp->b_cont = NULL;
15621 	}
15622 	tea = (struct T_error_ack *)mp->b_rptr;
15623 	switch (tea->PRIM_type) {
15624 	case T_BIND_ACK:
15625 		/*
15626 		 * Need to unbind with classifier since we were just told that
15627 		 * our bind succeeded.
15628 		 */
15629 		tcp->tcp_hard_bound = B_FALSE;
15630 		tcp->tcp_hard_binding = B_FALSE;
15631 
15632 		ipcl_hash_remove(connp);
15633 		/* Reuse the mblk if possible */
15634 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15635 			sizeof (*tea));
15636 		mp->b_rptr = mp->b_datap->db_base;
15637 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15638 		tea = (struct T_error_ack *)mp->b_rptr;
15639 		tea->PRIM_type = T_ERROR_ACK;
15640 		tea->TLI_error = TSYSERR;
15641 		tea->UNIX_error = error;
15642 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15643 			tea->ERROR_prim = T_CONN_REQ;
15644 		} else {
15645 			tea->ERROR_prim = O_T_BIND_REQ;
15646 		}
15647 		break;
15648 
15649 	case T_ERROR_ACK:
15650 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15651 			tea->ERROR_prim = T_CONN_REQ;
15652 		break;
15653 	default:
15654 		panic("tcp_bind_failed: unexpected TPI type");
15655 		/*NOTREACHED*/
15656 	}
15657 
15658 	tcp->tcp_state = TCPS_IDLE;
15659 	if (tcp->tcp_ipversion == IPV4_VERSION)
15660 		tcp->tcp_ipha->ipha_src = 0;
15661 	else
15662 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15663 	/*
15664 	 * Copy of the src addr. in tcp_t is needed since
15665 	 * the lookup funcs. can only look at tcp_t
15666 	 */
15667 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15668 
15669 	tcph = tcp->tcp_tcph;
15670 	tcph->th_lport[0] = 0;
15671 	tcph->th_lport[1] = 0;
15672 	tcp_bind_hash_remove(tcp);
15673 	bzero(&connp->u_port, sizeof (connp->u_port));
15674 	/* blow away saved option results if any */
15675 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15676 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15677 
15678 	conn_delete_ire(tcp->tcp_connp, NULL);
15679 	putnext(q, mp);
15680 }
15681 
15682 /*
15683  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15684  * messages.
15685  */
15686 void
15687 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15688 {
15689 	mblk_t	*mp1;
15690 	uchar_t	*rptr = mp->b_rptr;
15691 	queue_t	*q = tcp->tcp_rq;
15692 	struct T_error_ack *tea;
15693 	uint32_t mss;
15694 	mblk_t *syn_mp;
15695 	mblk_t *mdti;
15696 	int	retval;
15697 	mblk_t *ire_mp;
15698 
15699 	switch (mp->b_datap->db_type) {
15700 	case M_PROTO:
15701 	case M_PCPROTO:
15702 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15703 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15704 			break;
15705 		tea = (struct T_error_ack *)rptr;
15706 		switch (tea->PRIM_type) {
15707 		case T_BIND_ACK:
15708 			/*
15709 			 * Adapt Multidata information, if any.  The
15710 			 * following tcp_mdt_update routine will free
15711 			 * the message.
15712 			 */
15713 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15714 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15715 				    b_rptr)->mdt_capab, B_TRUE);
15716 				freemsg(mdti);
15717 			}
15718 
15719 			/* Get the IRE, if we had requested for it */
15720 			ire_mp = tcp_ire_mp(mp);
15721 
15722 			if (tcp->tcp_hard_binding) {
15723 				tcp->tcp_hard_binding = B_FALSE;
15724 				tcp->tcp_hard_bound = B_TRUE;
15725 				CL_INET_CONNECT(tcp);
15726 			} else {
15727 				if (ire_mp != NULL)
15728 					freeb(ire_mp);
15729 				goto after_syn_sent;
15730 			}
15731 
15732 			retval = tcp_adapt_ire(tcp, ire_mp);
15733 			if (ire_mp != NULL)
15734 				freeb(ire_mp);
15735 			if (retval == 0) {
15736 				tcp_bind_failed(tcp, mp,
15737 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15738 				    ENETUNREACH : EADDRNOTAVAIL));
15739 				return;
15740 			}
15741 			/*
15742 			 * Don't let an endpoint connect to itself.
15743 			 * Also checked in tcp_connect() but that
15744 			 * check can't handle the case when the
15745 			 * local IP address is INADDR_ANY.
15746 			 */
15747 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15748 				if ((tcp->tcp_ipha->ipha_dst ==
15749 				    tcp->tcp_ipha->ipha_src) &&
15750 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15751 				    tcp->tcp_tcph->th_fport))) {
15752 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15753 					return;
15754 				}
15755 			} else {
15756 				if (IN6_ARE_ADDR_EQUAL(
15757 				    &tcp->tcp_ip6h->ip6_dst,
15758 				    &tcp->tcp_ip6h->ip6_src) &&
15759 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15760 				    tcp->tcp_tcph->th_fport))) {
15761 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15762 					return;
15763 				}
15764 			}
15765 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15766 			/*
15767 			 * This should not be possible!  Just for
15768 			 * defensive coding...
15769 			 */
15770 			if (tcp->tcp_state != TCPS_SYN_SENT)
15771 				goto after_syn_sent;
15772 
15773 			ASSERT(q == tcp->tcp_rq);
15774 			/*
15775 			 * tcp_adapt_ire() does not adjust
15776 			 * for TCP/IP header length.
15777 			 */
15778 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15779 
15780 			/*
15781 			 * Just make sure our rwnd is at
15782 			 * least tcp_recv_hiwat_mss * MSS
15783 			 * large, and round up to the nearest
15784 			 * MSS.
15785 			 *
15786 			 * We do the round up here because
15787 			 * we need to get the interface
15788 			 * MTU first before we can do the
15789 			 * round up.
15790 			 */
15791 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15792 			    tcp_recv_hiwat_minmss * mss);
15793 			q->q_hiwat = tcp->tcp_rwnd;
15794 			tcp_set_ws_value(tcp);
15795 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15796 			    tcp->tcp_tcph->th_win);
15797 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15798 				tcp->tcp_snd_ws_ok = B_TRUE;
15799 
15800 			/*
15801 			 * Set tcp_snd_ts_ok to true
15802 			 * so that tcp_xmit_mp will
15803 			 * include the timestamp
15804 			 * option in the SYN segment.
15805 			 */
15806 			if (tcp_tstamp_always ||
15807 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15808 				tcp->tcp_snd_ts_ok = B_TRUE;
15809 			}
15810 
15811 			/*
15812 			 * tcp_snd_sack_ok can be set in
15813 			 * tcp_adapt_ire() if the sack metric
15814 			 * is set.  So check it here also.
15815 			 */
15816 			if (tcp_sack_permitted == 2 ||
15817 			    tcp->tcp_snd_sack_ok) {
15818 				if (tcp->tcp_sack_info == NULL) {
15819 					tcp->tcp_sack_info =
15820 					kmem_cache_alloc(tcp_sack_info_cache,
15821 					    KM_SLEEP);
15822 				}
15823 				tcp->tcp_snd_sack_ok = B_TRUE;
15824 			}
15825 
15826 			/*
15827 			 * Should we use ECN?  Note that the current
15828 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15829 			 * is 1.  The reason for doing this is that there
15830 			 * are equipments out there that will drop ECN
15831 			 * enabled IP packets.  Setting it to 1 avoids
15832 			 * compatibility problems.
15833 			 */
15834 			if (tcp_ecn_permitted == 2)
15835 				tcp->tcp_ecn_ok = B_TRUE;
15836 
15837 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15838 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15839 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15840 			if (syn_mp) {
15841 				cred_t *cr;
15842 				pid_t pid;
15843 
15844 				/*
15845 				 * Obtain the credential from the
15846 				 * thread calling connect(); the credential
15847 				 * lives on in the second mblk which
15848 				 * originated from T_CONN_REQ and is echoed
15849 				 * with the T_BIND_ACK from ip.  If none
15850 				 * can be found, default to the creator
15851 				 * of the socket.
15852 				 */
15853 				if (mp->b_cont == NULL ||
15854 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15855 					cr = tcp->tcp_cred;
15856 					pid = tcp->tcp_cpid;
15857 				} else {
15858 					pid = DB_CPID(mp->b_cont);
15859 				}
15860 
15861 				TCP_RECORD_TRACE(tcp, syn_mp,
15862 				    TCP_TRACE_SEND_PKT);
15863 				mblk_setcred(syn_mp, cr);
15864 				DB_CPID(syn_mp) = pid;
15865 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15866 			}
15867 		after_syn_sent:
15868 			/*
15869 			 * A trailer mblk indicates a waiting client upstream.
15870 			 * We complete here the processing begun in
15871 			 * either tcp_bind() or tcp_connect() by passing
15872 			 * upstream the reply message they supplied.
15873 			 */
15874 			mp1 = mp;
15875 			mp = mp->b_cont;
15876 			freeb(mp1);
15877 			if (mp)
15878 				break;
15879 			return;
15880 		case T_ERROR_ACK:
15881 			if (tcp->tcp_debug) {
15882 				(void) strlog(TCP_MODULE_ID, 0, 1,
15883 				    SL_TRACE|SL_ERROR,
15884 				    "tcp_rput_other: case T_ERROR_ACK, "
15885 				    "ERROR_prim == %d",
15886 				    tea->ERROR_prim);
15887 			}
15888 			switch (tea->ERROR_prim) {
15889 			case O_T_BIND_REQ:
15890 			case T_BIND_REQ:
15891 				tcp_bind_failed(tcp, mp,
15892 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15893 				    ENETUNREACH : EADDRNOTAVAIL));
15894 				return;
15895 			case T_UNBIND_REQ:
15896 				tcp->tcp_hard_binding = B_FALSE;
15897 				tcp->tcp_hard_bound = B_FALSE;
15898 				if (mp->b_cont) {
15899 					freemsg(mp->b_cont);
15900 					mp->b_cont = NULL;
15901 				}
15902 				if (tcp->tcp_unbind_pending)
15903 					tcp->tcp_unbind_pending = 0;
15904 				else {
15905 					/* From tcp_ip_unbind() - free */
15906 					freemsg(mp);
15907 					return;
15908 				}
15909 				break;
15910 			case T_SVR4_OPTMGMT_REQ:
15911 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15912 					/* T_OPTMGMT_REQ generated by TCP */
15913 					printf("T_SVR4_OPTMGMT_REQ failed "
15914 					    "%d/%d - dropped (cnt %d)\n",
15915 					    tea->TLI_error, tea->UNIX_error,
15916 					    tcp->tcp_drop_opt_ack_cnt);
15917 					freemsg(mp);
15918 					tcp->tcp_drop_opt_ack_cnt--;
15919 					return;
15920 				}
15921 				break;
15922 			}
15923 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15924 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15925 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15926 				    "- dropped (cnt %d)\n",
15927 				    tea->TLI_error, tea->UNIX_error,
15928 				    tcp->tcp_drop_opt_ack_cnt);
15929 				freemsg(mp);
15930 				tcp->tcp_drop_opt_ack_cnt--;
15931 				return;
15932 			}
15933 			break;
15934 		case T_OPTMGMT_ACK:
15935 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15936 				/* T_OPTMGMT_REQ generated by TCP */
15937 				freemsg(mp);
15938 				tcp->tcp_drop_opt_ack_cnt--;
15939 				return;
15940 			}
15941 			break;
15942 		default:
15943 			break;
15944 		}
15945 		break;
15946 	case M_CTL:
15947 		/*
15948 		 * ICMP messages.
15949 		 */
15950 		tcp_icmp_error(tcp, mp);
15951 		return;
15952 	case M_FLUSH:
15953 		if (*rptr & FLUSHR)
15954 			flushq(q, FLUSHDATA);
15955 		break;
15956 	default:
15957 		break;
15958 	}
15959 	/*
15960 	 * Make sure we set this bit before sending the ACK for
15961 	 * bind. Otherwise accept could possibly run and free
15962 	 * this tcp struct.
15963 	 */
15964 	putnext(q, mp);
15965 }
15966 
15967 /*
15968  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15969  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15970  * tcp_rsrv() try again.
15971  */
15972 static void
15973 tcp_ordrel_kick(void *arg)
15974 {
15975 	conn_t 	*connp = (conn_t *)arg;
15976 	tcp_t	*tcp = connp->conn_tcp;
15977 
15978 	tcp->tcp_ordrelid = 0;
15979 	tcp->tcp_timeout = B_FALSE;
15980 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15981 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15982 		qenable(tcp->tcp_rq);
15983 	}
15984 }
15985 
15986 /* ARGSUSED */
15987 static void
15988 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15989 {
15990 	conn_t	*connp = (conn_t *)arg;
15991 	tcp_t	*tcp = connp->conn_tcp;
15992 	queue_t	*q = tcp->tcp_rq;
15993 	uint_t	thwin;
15994 
15995 	freeb(mp);
15996 
15997 	TCP_STAT(tcp_rsrv_calls);
15998 
15999 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16000 		return;
16001 	}
16002 
16003 	if (tcp->tcp_fused) {
16004 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16005 
16006 		ASSERT(tcp->tcp_fused);
16007 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16008 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16009 		ASSERT(!TCP_IS_DETACHED(tcp));
16010 		ASSERT(tcp->tcp_connp->conn_sqp ==
16011 		    peer_tcp->tcp_connp->conn_sqp);
16012 
16013 		if (tcp->tcp_rcv_list != NULL)
16014 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16015 
16016 		tcp_clrqfull(peer_tcp);
16017 		TCP_STAT(tcp_fusion_backenabled);
16018 		return;
16019 	}
16020 
16021 	if (canputnext(q)) {
16022 		tcp->tcp_rwnd = q->q_hiwat;
16023 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16024 		    << tcp->tcp_rcv_ws;
16025 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16026 		/*
16027 		 * Send back a window update immediately if TCP is above
16028 		 * ESTABLISHED state and the increase of the rcv window
16029 		 * that the other side knows is at least 1 MSS after flow
16030 		 * control is lifted.
16031 		 */
16032 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16033 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16034 			tcp_xmit_ctl(NULL, tcp,
16035 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16036 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16037 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
16038 		}
16039 	}
16040 	/* Handle a failure to allocate a T_ORDREL_IND here */
16041 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16042 		ASSERT(tcp->tcp_listener == NULL);
16043 		if (tcp->tcp_rcv_list != NULL) {
16044 			(void) tcp_rcv_drain(q, tcp);
16045 		}
16046 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
16047 		mp = mi_tpi_ordrel_ind();
16048 		if (mp) {
16049 			tcp->tcp_ordrel_done = B_TRUE;
16050 			putnext(q, mp);
16051 			if (tcp->tcp_deferred_clean_death) {
16052 				/*
16053 				 * tcp_clean_death was deferred for
16054 				 * T_ORDREL_IND - do it now
16055 				 */
16056 				tcp->tcp_deferred_clean_death = B_FALSE;
16057 				(void) tcp_clean_death(tcp,
16058 				    tcp->tcp_client_errno, 22);
16059 			}
16060 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16061 			/*
16062 			 * If there isn't already a timer running
16063 			 * start one.  Use a 4 second
16064 			 * timer as a fallback since it can't fail.
16065 			 */
16066 			tcp->tcp_timeout = B_TRUE;
16067 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16068 			    MSEC_TO_TICK(4000));
16069 		}
16070 	}
16071 }
16072 
16073 /*
16074  * The read side service routine is called mostly when we get back-enabled as a
16075  * result of flow control relief.  Since we don't actually queue anything in
16076  * TCP, we have no data to send out of here.  What we do is clear the receive
16077  * window, and send out a window update.
16078  * This routine is also called to drive an orderly release message upstream
16079  * if the attempt in tcp_rput failed.
16080  */
16081 static void
16082 tcp_rsrv(queue_t *q)
16083 {
16084 	conn_t *connp = Q_TO_CONN(q);
16085 	tcp_t	*tcp = connp->conn_tcp;
16086 	mblk_t	*mp;
16087 
16088 	/* No code does a putq on the read side */
16089 	ASSERT(q->q_first == NULL);
16090 
16091 	/* Nothing to do for the default queue */
16092 	if (q == tcp_g_q) {
16093 		return;
16094 	}
16095 
16096 	mp = allocb(0, BPRI_HI);
16097 	if (mp == NULL) {
16098 		/*
16099 		 * We are under memory pressure. Return for now and we
16100 		 * we will be called again later.
16101 		 */
16102 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16103 			/*
16104 			 * If there isn't already a timer running
16105 			 * start one.  Use a 4 second
16106 			 * timer as a fallback since it can't fail.
16107 			 */
16108 			tcp->tcp_timeout = B_TRUE;
16109 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16110 			    MSEC_TO_TICK(4000));
16111 		}
16112 		return;
16113 	}
16114 	CONN_INC_REF(connp);
16115 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16116 	    SQTAG_TCP_RSRV);
16117 }
16118 
16119 /*
16120  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16121  * We do not allow the receive window to shrink.  After setting rwnd,
16122  * set the flow control hiwat of the stream.
16123  *
16124  * This function is called in 2 cases:
16125  *
16126  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16127  *    connection (passive open) and in tcp_rput_data() for active connect.
16128  *    This is called after tcp_mss_set() when the desired MSS value is known.
16129  *    This makes sure that our window size is a mutiple of the other side's
16130  *    MSS.
16131  * 2) Handling SO_RCVBUF option.
16132  *
16133  * It is ASSUMED that the requested size is a multiple of the current MSS.
16134  *
16135  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16136  * user requests so.
16137  */
16138 static int
16139 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16140 {
16141 	uint32_t	mss = tcp->tcp_mss;
16142 	uint32_t	old_max_rwnd;
16143 	uint32_t	max_transmittable_rwnd;
16144 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16145 
16146 	if (tcp_detached)
16147 		old_max_rwnd = tcp->tcp_rwnd;
16148 	else
16149 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16150 
16151 	/*
16152 	 * Insist on a receive window that is at least
16153 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16154 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16155 	 * and delayed acknowledgement.
16156 	 */
16157 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
16158 
16159 	/*
16160 	 * If window size info has already been exchanged, TCP should not
16161 	 * shrink the window.  Shrinking window is doable if done carefully.
16162 	 * We may add that support later.  But so far there is not a real
16163 	 * need to do that.
16164 	 */
16165 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16166 		/* MSS may have changed, do a round up again. */
16167 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16168 	}
16169 
16170 	/*
16171 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16172 	 * can be applied even before the window scale option is decided.
16173 	 */
16174 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16175 	if (rwnd > max_transmittable_rwnd) {
16176 		rwnd = max_transmittable_rwnd -
16177 		    (max_transmittable_rwnd % mss);
16178 		if (rwnd < mss)
16179 			rwnd = max_transmittable_rwnd;
16180 		/*
16181 		 * If we're over the limit we may have to back down tcp_rwnd.
16182 		 * The increment below won't work for us. So we set all three
16183 		 * here and the increment below will have no effect.
16184 		 */
16185 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16186 	}
16187 	if (tcp->tcp_localnet) {
16188 		tcp->tcp_rack_abs_max =
16189 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
16190 	} else {
16191 		/*
16192 		 * For a remote host on a different subnet (through a router),
16193 		 * we ack every other packet to be conforming to RFC1122.
16194 		 * tcp_deferred_acks_max is default to 2.
16195 		 */
16196 		tcp->tcp_rack_abs_max =
16197 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
16198 	}
16199 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16200 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16201 	else
16202 		tcp->tcp_rack_cur_max = 0;
16203 	/*
16204 	 * Increment the current rwnd by the amount the maximum grew (we
16205 	 * can not overwrite it since we might be in the middle of a
16206 	 * connection.)
16207 	 */
16208 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16209 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16210 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16211 		tcp->tcp_cwnd_max = rwnd;
16212 
16213 	if (tcp_detached)
16214 		return (rwnd);
16215 	/*
16216 	 * We set the maximum receive window into rq->q_hiwat.
16217 	 * This is not actually used for flow control.
16218 	 */
16219 	tcp->tcp_rq->q_hiwat = rwnd;
16220 	/*
16221 	 * Set the Stream head high water mark. This doesn't have to be
16222 	 * here, since we are simply using default values, but we would
16223 	 * prefer to choose these values algorithmically, with a likely
16224 	 * relationship to rwnd.  For fused loopback tcp, we double the
16225 	 * amount of buffer in order to simulate the normal tcp case.
16226 	 */
16227 	if (tcp->tcp_fused) {
16228 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd << 1,
16229 		    tcp_sth_rcv_hiwat));
16230 	} else {
16231 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd,
16232 		    tcp_sth_rcv_hiwat));
16233 	}
16234 	return (rwnd);
16235 }
16236 
16237 /*
16238  * Return SNMP stuff in buffer in mpdata.
16239  */
16240 static int
16241 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16242 {
16243 	mblk_t			*mpdata;
16244 	mblk_t			*mp_conn_ctl = NULL;
16245 	mblk_t			*mp_conn_data;
16246 	mblk_t			*mp6_conn_ctl = NULL;
16247 	mblk_t			*mp6_conn_data;
16248 	mblk_t			*mp_conn_tail = NULL;
16249 	mblk_t			*mp6_conn_tail = NULL;
16250 	struct opthdr		*optp;
16251 	mib2_tcpConnEntry_t	tce;
16252 	mib2_tcp6ConnEntry_t	tce6;
16253 	connf_t			*connfp;
16254 	conn_t			*connp;
16255 	int			i;
16256 	boolean_t 		ispriv;
16257 	zoneid_t 		zoneid;
16258 
16259 	if (mpctl == NULL ||
16260 	    (mpdata = mpctl->b_cont) == NULL ||
16261 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16262 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
16263 		if (mp_conn_ctl != NULL)
16264 			freemsg(mp_conn_ctl);
16265 		if (mp6_conn_ctl != NULL)
16266 			freemsg(mp6_conn_ctl);
16267 		return (0);
16268 	}
16269 
16270 	/* build table of connections -- need count in fixed part */
16271 	mp_conn_data = mp_conn_ctl->b_cont;
16272 	mp6_conn_data = mp6_conn_ctl->b_cont;
16273 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
16274 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
16275 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
16276 	SET_MIB(tcp_mib.tcpMaxConn, -1);
16277 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
16278 
16279 	ispriv =
16280 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16281 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16282 
16283 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16284 
16285 		connfp = &ipcl_globalhash_fanout[i];
16286 
16287 		connp = NULL;
16288 
16289 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16290 			tcp_t *tcp;
16291 
16292 			if (connp->conn_zoneid != zoneid)
16293 				continue;	/* not in this zone */
16294 
16295 			tcp = connp->conn_tcp;
16296 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
16297 			tcp->tcp_ibsegs = 0;
16298 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
16299 			tcp->tcp_obsegs = 0;
16300 
16301 			tce6.tcp6ConnState = tce.tcpConnState =
16302 			    tcp_snmp_state(tcp);
16303 			if (tce.tcpConnState == MIB2_TCP_established ||
16304 			    tce.tcpConnState == MIB2_TCP_closeWait)
16305 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
16306 
16307 			/* Create a message to report on IPv6 entries */
16308 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16309 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16310 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16311 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16312 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16313 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16314 			/* Don't want just anybody seeing these... */
16315 			if (ispriv) {
16316 				tce6.tcp6ConnEntryInfo.ce_snxt =
16317 				    tcp->tcp_snxt;
16318 				tce6.tcp6ConnEntryInfo.ce_suna =
16319 				    tcp->tcp_suna;
16320 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16321 				    tcp->tcp_rnxt;
16322 				tce6.tcp6ConnEntryInfo.ce_rack =
16323 				    tcp->tcp_rack;
16324 			} else {
16325 				/*
16326 				 * Netstat, unfortunately, uses this to
16327 				 * get send/receive queue sizes.  How to fix?
16328 				 * Why not compute the difference only?
16329 				 */
16330 				tce6.tcp6ConnEntryInfo.ce_snxt =
16331 				    tcp->tcp_snxt - tcp->tcp_suna;
16332 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16333 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16334 				    tcp->tcp_rnxt - tcp->tcp_rack;
16335 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16336 			}
16337 
16338 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16339 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16340 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16341 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16342 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16343 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
16344 			    (char *)&tce6, sizeof (tce6));
16345 			}
16346 			/*
16347 			 * Create an IPv4 table entry for IPv4 entries and also
16348 			 * for IPv6 entries which are bound to in6addr_any
16349 			 * but don't have IPV6_V6ONLY set.
16350 			 * (i.e. anything an IPv4 peer could connect to)
16351 			 */
16352 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16353 			    (tcp->tcp_state <= TCPS_LISTEN &&
16354 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16355 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16356 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16357 					tce.tcpConnRemAddress = INADDR_ANY;
16358 					tce.tcpConnLocalAddress = INADDR_ANY;
16359 				} else {
16360 					tce.tcpConnRemAddress =
16361 					    tcp->tcp_remote;
16362 					tce.tcpConnLocalAddress =
16363 					    tcp->tcp_ip_src;
16364 				}
16365 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16366 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16367 				/* Don't want just anybody seeing these... */
16368 				if (ispriv) {
16369 					tce.tcpConnEntryInfo.ce_snxt =
16370 					    tcp->tcp_snxt;
16371 					tce.tcpConnEntryInfo.ce_suna =
16372 					    tcp->tcp_suna;
16373 					tce.tcpConnEntryInfo.ce_rnxt =
16374 					    tcp->tcp_rnxt;
16375 					tce.tcpConnEntryInfo.ce_rack =
16376 					    tcp->tcp_rack;
16377 				} else {
16378 					/*
16379 					 * Netstat, unfortunately, uses this to
16380 					 * get send/receive queue sizes.  How
16381 					 * to fix?
16382 					 * Why not compute the difference only?
16383 					 */
16384 					tce.tcpConnEntryInfo.ce_snxt =
16385 					    tcp->tcp_snxt - tcp->tcp_suna;
16386 					tce.tcpConnEntryInfo.ce_suna = 0;
16387 					tce.tcpConnEntryInfo.ce_rnxt =
16388 					    tcp->tcp_rnxt - tcp->tcp_rack;
16389 					tce.tcpConnEntryInfo.ce_rack = 0;
16390 				}
16391 
16392 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16393 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16394 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16395 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16396 				tce.tcpConnEntryInfo.ce_state =
16397 				    tcp->tcp_state;
16398 				(void) snmp_append_data2(mp_conn_data,
16399 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16400 			}
16401 		}
16402 	}
16403 
16404 	/* fixed length structure for IPv4 and IPv6 counters */
16405 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16406 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
16407 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16408 	optp->level = MIB2_TCP;
16409 	optp->name = 0;
16410 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
16411 	optp->len = msgdsize(mpdata);
16412 	qreply(q, mpctl);
16413 
16414 	/* table of connections... */
16415 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16416 	    sizeof (struct T_optmgmt_ack)];
16417 	optp->level = MIB2_TCP;
16418 	optp->name = MIB2_TCP_CONN;
16419 	optp->len = msgdsize(mp_conn_data);
16420 	qreply(q, mp_conn_ctl);
16421 
16422 	/* table of IPv6 connections... */
16423 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16424 	    sizeof (struct T_optmgmt_ack)];
16425 	optp->level = MIB2_TCP6;
16426 	optp->name = MIB2_TCP6_CONN;
16427 	optp->len = msgdsize(mp6_conn_data);
16428 	qreply(q, mp6_conn_ctl);
16429 	return (1);
16430 }
16431 
16432 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16433 /* ARGSUSED */
16434 static int
16435 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16436 {
16437 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16438 
16439 	switch (level) {
16440 	case MIB2_TCP:
16441 		switch (name) {
16442 		case 13:
16443 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16444 				return (0);
16445 			/* TODO: delete entry defined by tce */
16446 			return (1);
16447 		default:
16448 			return (0);
16449 		}
16450 	default:
16451 		return (1);
16452 	}
16453 }
16454 
16455 /* Translate TCP state to MIB2 TCP state. */
16456 static int
16457 tcp_snmp_state(tcp_t *tcp)
16458 {
16459 	if (tcp == NULL)
16460 		return (0);
16461 
16462 	switch (tcp->tcp_state) {
16463 	case TCPS_CLOSED:
16464 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16465 	case TCPS_BOUND:
16466 		return (MIB2_TCP_closed);
16467 	case TCPS_LISTEN:
16468 		return (MIB2_TCP_listen);
16469 	case TCPS_SYN_SENT:
16470 		return (MIB2_TCP_synSent);
16471 	case TCPS_SYN_RCVD:
16472 		return (MIB2_TCP_synReceived);
16473 	case TCPS_ESTABLISHED:
16474 		return (MIB2_TCP_established);
16475 	case TCPS_CLOSE_WAIT:
16476 		return (MIB2_TCP_closeWait);
16477 	case TCPS_FIN_WAIT_1:
16478 		return (MIB2_TCP_finWait1);
16479 	case TCPS_CLOSING:
16480 		return (MIB2_TCP_closing);
16481 	case TCPS_LAST_ACK:
16482 		return (MIB2_TCP_lastAck);
16483 	case TCPS_FIN_WAIT_2:
16484 		return (MIB2_TCP_finWait2);
16485 	case TCPS_TIME_WAIT:
16486 		return (MIB2_TCP_timeWait);
16487 	default:
16488 		return (0);
16489 	}
16490 }
16491 
16492 static char tcp_report_header[] =
16493 	"TCP     " MI_COL_HDRPAD_STR
16494 	"zone dest            snxt     suna     "
16495 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16496 	"recent   [lport,fport] state";
16497 
16498 /*
16499  * TCP status report triggered via the Named Dispatch mechanism.
16500  */
16501 /* ARGSUSED */
16502 static void
16503 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16504     cred_t *cr)
16505 {
16506 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16507 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16508 	char cflag;
16509 	in6_addr_t	v6dst;
16510 	char buf[80];
16511 	uint_t print_len, buf_len;
16512 
16513 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16514 	if (buf_len <= 0)
16515 		return;
16516 
16517 	if (hashval >= 0)
16518 		(void) sprintf(hash, "%03d ", hashval);
16519 	else
16520 		hash[0] = '\0';
16521 
16522 	/*
16523 	 * Note that we use the remote address in the tcp_b  structure.
16524 	 * This means that it will print out the real destination address,
16525 	 * not the next hop's address if source routing is used.  This
16526 	 * avoid the confusion on the output because user may not
16527 	 * know that source routing is used for a connection.
16528 	 */
16529 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16530 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16531 	} else {
16532 		v6dst = tcp->tcp_remote_v6;
16533 	}
16534 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16535 	/*
16536 	 * the ispriv checks are so that normal users cannot determine
16537 	 * sequence number information using NDD.
16538 	 */
16539 
16540 	if (TCP_IS_DETACHED(tcp))
16541 		cflag = '*';
16542 	else
16543 		cflag = ' ';
16544 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16545 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16546 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16547 	    hash,
16548 	    (void *)tcp,
16549 	    tcp->tcp_connp->conn_zoneid,
16550 	    addrbuf,
16551 	    (ispriv) ? tcp->tcp_snxt : 0,
16552 	    (ispriv) ? tcp->tcp_suna : 0,
16553 	    tcp->tcp_swnd,
16554 	    (ispriv) ? tcp->tcp_rnxt : 0,
16555 	    (ispriv) ? tcp->tcp_rack : 0,
16556 	    tcp->tcp_rwnd,
16557 	    tcp->tcp_rto,
16558 	    tcp->tcp_mss,
16559 	    tcp->tcp_snd_ws_ok,
16560 	    tcp->tcp_snd_ws,
16561 	    tcp->tcp_rcv_ws,
16562 	    tcp->tcp_snd_ts_ok,
16563 	    tcp->tcp_ts_recent,
16564 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16565 	if (print_len < buf_len) {
16566 		((mblk_t *)mp)->b_wptr += print_len;
16567 	} else {
16568 		((mblk_t *)mp)->b_wptr += buf_len;
16569 	}
16570 }
16571 
16572 /*
16573  * TCP status report (for listeners only) triggered via the Named Dispatch
16574  * mechanism.
16575  */
16576 /* ARGSUSED */
16577 static void
16578 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16579 {
16580 	char addrbuf[INET6_ADDRSTRLEN];
16581 	in6_addr_t	v6dst;
16582 	uint_t print_len, buf_len;
16583 
16584 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16585 	if (buf_len <= 0)
16586 		return;
16587 
16588 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16589 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16590 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16591 	} else {
16592 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16593 		    addrbuf, sizeof (addrbuf));
16594 	}
16595 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16596 	    "%03d "
16597 	    MI_COL_PTRFMT_STR
16598 	    "%d %s %05u %08u %d/%d/%d%c\n",
16599 	    hashval, (void *)tcp,
16600 	    tcp->tcp_connp->conn_zoneid,
16601 	    addrbuf,
16602 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16603 	    tcp->tcp_conn_req_seqnum,
16604 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16605 	    tcp->tcp_conn_req_max,
16606 	    tcp->tcp_syn_defense ? '*' : ' ');
16607 	if (print_len < buf_len) {
16608 		((mblk_t *)mp)->b_wptr += print_len;
16609 	} else {
16610 		((mblk_t *)mp)->b_wptr += buf_len;
16611 	}
16612 }
16613 
16614 /* TCP status report triggered via the Named Dispatch mechanism. */
16615 /* ARGSUSED */
16616 static int
16617 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16618 {
16619 	tcp_t	*tcp;
16620 	int	i;
16621 	conn_t	*connp;
16622 	connf_t	*connfp;
16623 	zoneid_t zoneid;
16624 
16625 	/*
16626 	 * Because of the ndd constraint, at most we can have 64K buffer
16627 	 * to put in all TCP info.  So to be more efficient, just
16628 	 * allocate a 64K buffer here, assuming we need that large buffer.
16629 	 * This may be a problem as any user can read tcp_status.  Therefore
16630 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16631 	 * This should be OK as normal users should not do this too often.
16632 	 */
16633 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16634 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16635 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16636 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16637 			return (0);
16638 		}
16639 	}
16640 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16641 		/* The following may work even if we cannot get a large buf. */
16642 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16643 		return (0);
16644 	}
16645 
16646 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16647 
16648 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16649 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16650 
16651 		connfp = &ipcl_globalhash_fanout[i];
16652 
16653 		connp = NULL;
16654 
16655 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16656 			tcp = connp->conn_tcp;
16657 			if (zoneid != GLOBAL_ZONEID &&
16658 			    zoneid != connp->conn_zoneid)
16659 				continue;
16660 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16661 			    cr);
16662 		}
16663 
16664 	}
16665 
16666 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16667 	return (0);
16668 }
16669 
16670 /* TCP status report triggered via the Named Dispatch mechanism. */
16671 /* ARGSUSED */
16672 static int
16673 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16674 {
16675 	tf_t	*tbf;
16676 	tcp_t	*tcp;
16677 	int	i;
16678 	zoneid_t zoneid;
16679 
16680 	/* Refer to comments in tcp_status_report(). */
16681 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16682 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16683 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16684 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16685 			return (0);
16686 		}
16687 	}
16688 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16689 		/* The following may work even if we cannot get a large buf. */
16690 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16691 		return (0);
16692 	}
16693 
16694 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16695 
16696 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16697 
16698 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16699 		tbf = &tcp_bind_fanout[i];
16700 		mutex_enter(&tbf->tf_lock);
16701 		for (tcp = tbf->tf_tcp; tcp != NULL;
16702 		    tcp = tcp->tcp_bind_hash) {
16703 			if (zoneid != GLOBAL_ZONEID &&
16704 			    zoneid != tcp->tcp_connp->conn_zoneid)
16705 				continue;
16706 			CONN_INC_REF(tcp->tcp_connp);
16707 			tcp_report_item(mp->b_cont, tcp, i,
16708 			    Q_TO_TCP(q), cr);
16709 			CONN_DEC_REF(tcp->tcp_connp);
16710 		}
16711 		mutex_exit(&tbf->tf_lock);
16712 	}
16713 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16714 	return (0);
16715 }
16716 
16717 /* TCP status report triggered via the Named Dispatch mechanism. */
16718 /* ARGSUSED */
16719 static int
16720 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16721 {
16722 	connf_t	*connfp;
16723 	conn_t	*connp;
16724 	tcp_t	*tcp;
16725 	int	i;
16726 	zoneid_t zoneid;
16727 
16728 	/* Refer to comments in tcp_status_report(). */
16729 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16730 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16731 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16732 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16733 			return (0);
16734 		}
16735 	}
16736 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16737 		/* The following may work even if we cannot get a large buf. */
16738 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16739 		return (0);
16740 	}
16741 
16742 	(void) mi_mpprintf(mp,
16743 	    "    TCP    " MI_COL_HDRPAD_STR
16744 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16745 
16746 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16747 
16748 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16749 		connfp =  &ipcl_bind_fanout[i];
16750 		connp = NULL;
16751 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16752 			tcp = connp->conn_tcp;
16753 			if (zoneid != GLOBAL_ZONEID &&
16754 			    zoneid != connp->conn_zoneid)
16755 				continue;
16756 			tcp_report_listener(mp->b_cont, tcp, i);
16757 		}
16758 	}
16759 
16760 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16761 	return (0);
16762 }
16763 
16764 /* TCP status report triggered via the Named Dispatch mechanism. */
16765 /* ARGSUSED */
16766 static int
16767 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16768 {
16769 	connf_t	*connfp;
16770 	conn_t	*connp;
16771 	tcp_t	*tcp;
16772 	int	i;
16773 	zoneid_t zoneid;
16774 
16775 	/* Refer to comments in tcp_status_report(). */
16776 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16777 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16778 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16779 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16780 			return (0);
16781 		}
16782 	}
16783 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16784 		/* The following may work even if we cannot get a large buf. */
16785 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16786 		return (0);
16787 	}
16788 
16789 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16790 	    ipcl_conn_fanout_size);
16791 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16792 
16793 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16794 
16795 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16796 		connfp =  &ipcl_conn_fanout[i];
16797 		connp = NULL;
16798 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16799 			tcp = connp->conn_tcp;
16800 			if (zoneid != GLOBAL_ZONEID &&
16801 			    zoneid != connp->conn_zoneid)
16802 				continue;
16803 			tcp_report_item(mp->b_cont, tcp, i,
16804 			    Q_TO_TCP(q), cr);
16805 		}
16806 	}
16807 
16808 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16809 	return (0);
16810 }
16811 
16812 /* TCP status report triggered via the Named Dispatch mechanism. */
16813 /* ARGSUSED */
16814 static int
16815 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16816 {
16817 	tf_t	*tf;
16818 	tcp_t	*tcp;
16819 	int	i;
16820 	zoneid_t zoneid;
16821 
16822 	/* Refer to comments in tcp_status_report(). */
16823 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16824 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16825 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16826 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16827 			return (0);
16828 		}
16829 	}
16830 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16831 		/* The following may work even if we cannot get a large buf. */
16832 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16833 		return (0);
16834 	}
16835 
16836 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16837 
16838 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16839 
16840 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16841 		tf = &tcp_acceptor_fanout[i];
16842 		mutex_enter(&tf->tf_lock);
16843 		for (tcp = tf->tf_tcp; tcp != NULL;
16844 		    tcp = tcp->tcp_acceptor_hash) {
16845 			if (zoneid != GLOBAL_ZONEID &&
16846 			    zoneid != tcp->tcp_connp->conn_zoneid)
16847 				continue;
16848 			tcp_report_item(mp->b_cont, tcp, i,
16849 			    Q_TO_TCP(q), cr);
16850 		}
16851 		mutex_exit(&tf->tf_lock);
16852 	}
16853 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16854 	return (0);
16855 }
16856 
16857 /*
16858  * tcp_timer is the timer service routine.  It handles the retransmission,
16859  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16860  * from the state of the tcp instance what kind of action needs to be done
16861  * at the time it is called.
16862  */
16863 static void
16864 tcp_timer(void *arg)
16865 {
16866 	mblk_t		*mp;
16867 	clock_t		first_threshold;
16868 	clock_t		second_threshold;
16869 	clock_t		ms;
16870 	uint32_t	mss;
16871 	conn_t		*connp = (conn_t *)arg;
16872 	tcp_t		*tcp = connp->conn_tcp;
16873 
16874 	tcp->tcp_timer_tid = 0;
16875 
16876 	if (tcp->tcp_fused)
16877 		return;
16878 
16879 	first_threshold =  tcp->tcp_first_timer_threshold;
16880 	second_threshold = tcp->tcp_second_timer_threshold;
16881 	switch (tcp->tcp_state) {
16882 	case TCPS_IDLE:
16883 	case TCPS_BOUND:
16884 	case TCPS_LISTEN:
16885 		return;
16886 	case TCPS_SYN_RCVD: {
16887 		tcp_t	*listener = tcp->tcp_listener;
16888 
16889 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16890 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16891 			/* it's our first timeout */
16892 			tcp->tcp_syn_rcvd_timeout = 1;
16893 			mutex_enter(&listener->tcp_eager_lock);
16894 			listener->tcp_syn_rcvd_timeout++;
16895 			if (!listener->tcp_syn_defense &&
16896 			    (listener->tcp_syn_rcvd_timeout >
16897 			    (tcp_conn_req_max_q0 >> 2)) &&
16898 			    (tcp_conn_req_max_q0 > 200)) {
16899 				/* We may be under attack. Put on a defense. */
16900 				listener->tcp_syn_defense = B_TRUE;
16901 				cmn_err(CE_WARN, "High TCP connect timeout "
16902 				    "rate! System (port %d) may be under a "
16903 				    "SYN flood attack!",
16904 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16905 
16906 				listener->tcp_ip_addr_cache = kmem_zalloc(
16907 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16908 				    KM_NOSLEEP);
16909 			}
16910 			mutex_exit(&listener->tcp_eager_lock);
16911 		}
16912 	}
16913 		/* FALLTHRU */
16914 	case TCPS_SYN_SENT:
16915 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16916 		second_threshold = tcp->tcp_second_ctimer_threshold;
16917 		break;
16918 	case TCPS_ESTABLISHED:
16919 	case TCPS_FIN_WAIT_1:
16920 	case TCPS_CLOSING:
16921 	case TCPS_CLOSE_WAIT:
16922 	case TCPS_LAST_ACK:
16923 		/* If we have data to rexmit */
16924 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16925 			clock_t	time_to_wait;
16926 
16927 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16928 			if (!tcp->tcp_xmit_head)
16929 				break;
16930 			time_to_wait = lbolt -
16931 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16932 			time_to_wait = tcp->tcp_rto -
16933 			    TICK_TO_MSEC(time_to_wait);
16934 			/*
16935 			 * If the timer fires too early, 1 clock tick earlier,
16936 			 * restart the timer.
16937 			 */
16938 			if (time_to_wait > msec_per_tick) {
16939 				TCP_STAT(tcp_timer_fire_early);
16940 				TCP_TIMER_RESTART(tcp, time_to_wait);
16941 				return;
16942 			}
16943 			/*
16944 			 * When we probe zero windows, we force the swnd open.
16945 			 * If our peer acks with a closed window swnd will be
16946 			 * set to zero by tcp_rput(). As long as we are
16947 			 * receiving acks tcp_rput will
16948 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16949 			 * first and second interval actions.  NOTE: the timer
16950 			 * interval is allowed to continue its exponential
16951 			 * backoff.
16952 			 */
16953 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16954 				if (tcp->tcp_debug) {
16955 					(void) strlog(TCP_MODULE_ID, 0, 1,
16956 					    SL_TRACE, "tcp_timer: zero win");
16957 				}
16958 			} else {
16959 				/*
16960 				 * After retransmission, we need to do
16961 				 * slow start.  Set the ssthresh to one
16962 				 * half of current effective window and
16963 				 * cwnd to one MSS.  Also reset
16964 				 * tcp_cwnd_cnt.
16965 				 *
16966 				 * Note that if tcp_ssthresh is reduced because
16967 				 * of ECN, do not reduce it again unless it is
16968 				 * already one window of data away (tcp_cwr
16969 				 * should then be cleared) or this is a
16970 				 * timeout for a retransmitted segment.
16971 				 */
16972 				uint32_t npkt;
16973 
16974 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16975 					npkt = ((tcp->tcp_timer_backoff ?
16976 					    tcp->tcp_cwnd_ssthresh :
16977 					    tcp->tcp_snxt -
16978 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16979 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16980 					    tcp->tcp_mss;
16981 				}
16982 				tcp->tcp_cwnd = tcp->tcp_mss;
16983 				tcp->tcp_cwnd_cnt = 0;
16984 				if (tcp->tcp_ecn_ok) {
16985 					tcp->tcp_cwr = B_TRUE;
16986 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16987 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16988 				}
16989 			}
16990 			break;
16991 		}
16992 		/*
16993 		 * We have something to send yet we cannot send.  The
16994 		 * reason can be:
16995 		 *
16996 		 * 1. Zero send window: we need to do zero window probe.
16997 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16998 		 * segments.
16999 		 * 3. SWS avoidance: receiver may have shrunk window,
17000 		 * reset our knowledge.
17001 		 *
17002 		 * Note that condition 2 can happen with either 1 or
17003 		 * 3.  But 1 and 3 are exclusive.
17004 		 */
17005 		if (tcp->tcp_unsent != 0) {
17006 			if (tcp->tcp_cwnd == 0) {
17007 				/*
17008 				 * Set tcp_cwnd to 1 MSS so that a
17009 				 * new segment can be sent out.  We
17010 				 * are "clocking out" new data when
17011 				 * the network is really congested.
17012 				 */
17013 				ASSERT(tcp->tcp_ecn_ok);
17014 				tcp->tcp_cwnd = tcp->tcp_mss;
17015 			}
17016 			if (tcp->tcp_swnd == 0) {
17017 				/* Extend window for zero window probe */
17018 				tcp->tcp_swnd++;
17019 				tcp->tcp_zero_win_probe = B_TRUE;
17020 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
17021 			} else {
17022 				/*
17023 				 * Handle timeout from sender SWS avoidance.
17024 				 * Reset our knowledge of the max send window
17025 				 * since the receiver might have reduced its
17026 				 * receive buffer.  Avoid setting tcp_max_swnd
17027 				 * to one since that will essentially disable
17028 				 * the SWS checks.
17029 				 *
17030 				 * Note that since we don't have a SWS
17031 				 * state variable, if the timeout is set
17032 				 * for ECN but not for SWS, this
17033 				 * code will also be executed.  This is
17034 				 * fine as tcp_max_swnd is updated
17035 				 * constantly and it will not affect
17036 				 * anything.
17037 				 */
17038 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17039 			}
17040 			tcp_wput_data(tcp, NULL, B_FALSE);
17041 			return;
17042 		}
17043 		/* Is there a FIN that needs to be to re retransmitted? */
17044 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17045 		    !tcp->tcp_fin_acked)
17046 			break;
17047 		/* Nothing to do, return without restarting timer. */
17048 		TCP_STAT(tcp_timer_fire_miss);
17049 		return;
17050 	case TCPS_FIN_WAIT_2:
17051 		/*
17052 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17053 		 * We waited some time for for peer's FIN, but it hasn't
17054 		 * arrived.  We flush the connection now to avoid
17055 		 * case where the peer has rebooted.
17056 		 */
17057 		if (TCP_IS_DETACHED(tcp)) {
17058 			(void) tcp_clean_death(tcp, 0, 23);
17059 		} else {
17060 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
17061 		}
17062 		return;
17063 	case TCPS_TIME_WAIT:
17064 		(void) tcp_clean_death(tcp, 0, 24);
17065 		return;
17066 	default:
17067 		if (tcp->tcp_debug) {
17068 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
17069 			    "tcp_timer: strange state (%d) %s",
17070 			    tcp->tcp_state, tcp_display(tcp, NULL,
17071 			    DISP_PORT_ONLY));
17072 		}
17073 		return;
17074 	}
17075 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17076 		/*
17077 		 * For zero window probe, we need to send indefinitely,
17078 		 * unless we have not heard from the other side for some
17079 		 * time...
17080 		 */
17081 		if ((tcp->tcp_zero_win_probe == 0) ||
17082 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17083 		    second_threshold)) {
17084 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
17085 			/*
17086 			 * If TCP is in SYN_RCVD state, send back a
17087 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17088 			 * should be zero in TCPS_SYN_RCVD state.
17089 			 */
17090 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17091 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17092 				    "in SYN_RCVD",
17093 				    tcp, tcp->tcp_snxt,
17094 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17095 			}
17096 			(void) tcp_clean_death(tcp,
17097 			    tcp->tcp_client_errno ?
17098 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17099 			return;
17100 		} else {
17101 			/*
17102 			 * Set tcp_ms_we_have_waited to second_threshold
17103 			 * so that in next timeout, we will do the above
17104 			 * check (lbolt - tcp_last_recv_time).  This is
17105 			 * also to avoid overflow.
17106 			 *
17107 			 * We don't need to decrement tcp_timer_backoff
17108 			 * to avoid overflow because it will be decremented
17109 			 * later if new timeout value is greater than
17110 			 * tcp_rexmit_interval_max.  In the case when
17111 			 * tcp_rexmit_interval_max is greater than
17112 			 * second_threshold, it means that we will wait
17113 			 * longer than second_threshold to send the next
17114 			 * window probe.
17115 			 */
17116 			tcp->tcp_ms_we_have_waited = second_threshold;
17117 		}
17118 	} else if (ms > first_threshold) {
17119 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17120 		    tcp->tcp_xmit_head != NULL) {
17121 			tcp->tcp_xmit_head =
17122 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17123 		}
17124 		/*
17125 		 * We have been retransmitting for too long...  The RTT
17126 		 * we calculated is probably incorrect.  Reinitialize it.
17127 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17128 		 * tcp_rtt_update so that we won't accidentally cache a
17129 		 * bad value.  But only do this if this is not a zero
17130 		 * window probe.
17131 		 */
17132 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17133 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17134 			    (tcp->tcp_rtt_sa >> 5);
17135 			tcp->tcp_rtt_sa = 0;
17136 			tcp_ip_notify(tcp);
17137 			tcp->tcp_rtt_update = 0;
17138 		}
17139 	}
17140 	tcp->tcp_timer_backoff++;
17141 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17142 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17143 	    tcp_rexmit_interval_min) {
17144 		/*
17145 		 * This means the original RTO is tcp_rexmit_interval_min.
17146 		 * So we will use tcp_rexmit_interval_min as the RTO value
17147 		 * and do the backoff.
17148 		 */
17149 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
17150 	} else {
17151 		ms <<= tcp->tcp_timer_backoff;
17152 	}
17153 	if (ms > tcp_rexmit_interval_max) {
17154 		ms = tcp_rexmit_interval_max;
17155 		/*
17156 		 * ms is at max, decrement tcp_timer_backoff to avoid
17157 		 * overflow.
17158 		 */
17159 		tcp->tcp_timer_backoff--;
17160 	}
17161 	tcp->tcp_ms_we_have_waited += ms;
17162 	if (tcp->tcp_zero_win_probe == 0) {
17163 		tcp->tcp_rto = ms;
17164 	}
17165 	TCP_TIMER_RESTART(tcp, ms);
17166 	/*
17167 	 * This is after a timeout and tcp_rto is backed off.  Set
17168 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17169 	 * restart the timer with a correct value.
17170 	 */
17171 	tcp->tcp_set_timer = 1;
17172 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17173 	if (mss > tcp->tcp_mss)
17174 		mss = tcp->tcp_mss;
17175 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17176 		mss = tcp->tcp_swnd;
17177 
17178 	if ((mp = tcp->tcp_xmit_head) != NULL)
17179 		mp->b_prev = (mblk_t *)lbolt;
17180 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17181 	    B_TRUE);
17182 
17183 	/*
17184 	 * When slow start after retransmission begins, start with
17185 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17186 	 * start phase.  tcp_snd_burst controls how many segments
17187 	 * can be sent because of an ack.
17188 	 */
17189 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17190 	tcp->tcp_snd_burst = TCP_CWND_SS;
17191 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17192 	    (tcp->tcp_unsent == 0)) {
17193 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17194 	} else {
17195 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17196 	}
17197 	tcp->tcp_rexmit = B_TRUE;
17198 	tcp->tcp_dupack_cnt = 0;
17199 
17200 	/*
17201 	 * Remove all rexmit SACK blk to start from fresh.
17202 	 */
17203 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17204 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17205 		tcp->tcp_num_notsack_blk = 0;
17206 		tcp->tcp_cnt_notsack_list = 0;
17207 	}
17208 	if (mp == NULL) {
17209 		return;
17210 	}
17211 	/* Attach credentials to retransmitted initial SYNs. */
17212 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17213 		mblk_setcred(mp, tcp->tcp_cred);
17214 		DB_CPID(mp) = tcp->tcp_cpid;
17215 	}
17216 
17217 	tcp->tcp_csuna = tcp->tcp_snxt;
17218 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
17219 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
17220 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17221 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17222 
17223 }
17224 
17225 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17226 static void
17227 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17228 {
17229 	conn_t	*connp;
17230 
17231 	switch (tcp->tcp_state) {
17232 	case TCPS_BOUND:
17233 	case TCPS_LISTEN:
17234 		break;
17235 	default:
17236 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17237 		return;
17238 	}
17239 
17240 	/*
17241 	 * Need to clean up all the eagers since after the unbind, segments
17242 	 * will no longer be delivered to this listener stream.
17243 	 */
17244 	mutex_enter(&tcp->tcp_eager_lock);
17245 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17246 		tcp_eager_cleanup(tcp, 0);
17247 	}
17248 	mutex_exit(&tcp->tcp_eager_lock);
17249 
17250 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17251 		tcp->tcp_ipha->ipha_src = 0;
17252 	} else {
17253 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17254 	}
17255 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17256 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17257 	tcp_bind_hash_remove(tcp);
17258 	tcp->tcp_state = TCPS_IDLE;
17259 	tcp->tcp_mdt = B_FALSE;
17260 	/* Send M_FLUSH according to TPI */
17261 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17262 	connp = tcp->tcp_connp;
17263 	connp->conn_mdt_ok = B_FALSE;
17264 	ipcl_hash_remove(connp);
17265 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17266 	mp = mi_tpi_ok_ack_alloc(mp);
17267 	putnext(tcp->tcp_rq, mp);
17268 }
17269 
17270 /*
17271  * Don't let port fall into the privileged range.
17272  * Since the extra privileged ports can be arbitrary we also
17273  * ensure that we exclude those from consideration.
17274  * tcp_g_epriv_ports is not sorted thus we loop over it until
17275  * there are no changes.
17276  *
17277  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17278  * but instead the code relies on:
17279  * - the fact that the address of the array and its size never changes
17280  * - the atomic assignment of the elements of the array
17281  */
17282 static in_port_t
17283 tcp_update_next_port(in_port_t port, boolean_t random)
17284 {
17285 	int i;
17286 
17287 	if (random && tcp_random_anon_port != 0) {
17288 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17289 		    sizeof (in_port_t));
17290 		/*
17291 		 * Unless changed by a sys admin, the smallest anon port
17292 		 * is 32768 and the largest anon port is 65535.  It is
17293 		 * very likely (50%) for the random port to be smaller
17294 		 * than the smallest anon port.  When that happens,
17295 		 * add port % (anon port range) to the smallest anon
17296 		 * port to get the random port.  It should fall into the
17297 		 * valid anon port range.
17298 		 */
17299 		if (port < tcp_smallest_anon_port) {
17300 			port = tcp_smallest_anon_port +
17301 			    port % (tcp_largest_anon_port -
17302 				tcp_smallest_anon_port);
17303 		}
17304 	}
17305 
17306 retry:
17307 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
17308 		port = (in_port_t)tcp_smallest_anon_port;
17309 
17310 	if (port < tcp_smallest_nonpriv_port)
17311 		port = (in_port_t)tcp_smallest_nonpriv_port;
17312 
17313 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
17314 		if (port == tcp_g_epriv_ports[i]) {
17315 			port++;
17316 			/*
17317 			 * Make sure whether the port is in the
17318 			 * valid range.
17319 			 *
17320 			 * XXX Note that if tcp_g_epriv_ports contains
17321 			 * all the anonymous ports this will be an
17322 			 * infinite loop.
17323 			 */
17324 			goto retry;
17325 		}
17326 	}
17327 	return (port);
17328 }
17329 
17330 /*
17331  * Return the next anonymous port in the priviledged port range for
17332  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17333  * downwards.  This is the same behavior as documented in the userland
17334  * library call rresvport(3N).
17335  */
17336 static in_port_t
17337 tcp_get_next_priv_port(void)
17338 {
17339 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17340 
17341 	if (next_priv_port < tcp_min_anonpriv_port) {
17342 		next_priv_port = IPPORT_RESERVED - 1;
17343 	}
17344 	return (next_priv_port--);
17345 }
17346 
17347 /* The write side r/w procedure. */
17348 
17349 #if CCS_STATS
17350 struct {
17351 	struct {
17352 		int64_t count, bytes;
17353 	} tot, hit;
17354 } wrw_stats;
17355 #endif
17356 
17357 /*
17358  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17359  * messages.
17360  */
17361 /* ARGSUSED */
17362 static void
17363 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17364 {
17365 	conn_t	*connp = (conn_t *)arg;
17366 	tcp_t	*tcp = connp->conn_tcp;
17367 	queue_t	*q = tcp->tcp_wq;
17368 
17369 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17370 	/*
17371 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17372 	 * Once the close starts, streamhead and sockfs will not let any data
17373 	 * packets come down (close ensures that there are no threads using the
17374 	 * queue and no new threads will come down) but since qprocsoff()
17375 	 * hasn't happened yet, a M_FLUSH or some non data message might
17376 	 * get reflected back (in response to our own FLUSHRW) and get
17377 	 * processed after tcp_close() is done. The conn would still be valid
17378 	 * because a ref would have added but we need to check the state
17379 	 * before actually processing the packet.
17380 	 */
17381 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17382 		freemsg(mp);
17383 		return;
17384 	}
17385 
17386 	switch (DB_TYPE(mp)) {
17387 	case M_IOCDATA:
17388 		tcp_wput_iocdata(tcp, mp);
17389 		break;
17390 	case M_FLUSH:
17391 		tcp_wput_flush(tcp, mp);
17392 		break;
17393 	default:
17394 		CALL_IP_WPUT(connp, q, mp);
17395 		break;
17396 	}
17397 }
17398 
17399 /*
17400  * Write side put procedure for TCP module instance.
17401  * TCP as a module is only used for MIB browsers that push TCP over IP or
17402  * ARP. The only supported primitives are T_SVR4_OPTMGMT_REQ and
17403  * T_OPTMGMT_REQ. M_FLUSH messages are only passed downstream; we don't flush
17404  * our queues as we never enqueue messages there. All ioctls are NAKed and
17405  * everything else is freed.
17406  */
17407 static void
17408 tcp_wput_mod(queue_t *q, mblk_t *mp)
17409 {
17410 	switch (DB_TYPE(mp)) {
17411 	case M_PROTO:
17412 	case M_PCPROTO:
17413 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
17414 		    ((((union T_primitives *)mp->b_rptr)->type ==
17415 			T_SVR4_OPTMGMT_REQ) ||
17416 		    (((union T_primitives *)mp->b_rptr)->type ==
17417 			T_OPTMGMT_REQ))) {
17418 			/*
17419 			 * This is the only TPI primitive supported. Its
17420 			 * handling does not require tcp_t, but it does require
17421 			 * conn_t to check permissions.
17422 			 */
17423 			cred_t	*cr = DB_CREDDEF(mp, Q_TO_CONN(q)->conn_cred);
17424 			if (!snmpcom_req(q, mp, tcp_snmp_set,
17425 			    tcp_snmp_get, cr)) {
17426 				freemsg(mp);
17427 				return;
17428 			}
17429 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
17430 		    != NULL)
17431 			qreply(q, mp);
17432 		break;
17433 	case M_FLUSH:
17434 		putnext(q, mp);
17435 		break;
17436 	case M_IOCTL:
17437 		miocnak(q, mp, 0, ENOTSUP);
17438 		break;
17439 	default:
17440 		freemsg(mp);
17441 		break;
17442 	}
17443 }
17444 
17445 /*
17446  * The TCP fast path write put procedure.
17447  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17448  */
17449 /* ARGSUSED */
17450 static void
17451 tcp_output(void *arg, mblk_t *mp, void *arg2)
17452 {
17453 	int		len;
17454 	int		hdrlen;
17455 	int		plen;
17456 	mblk_t		*mp1;
17457 	uchar_t		*rptr;
17458 	uint32_t	snxt;
17459 	tcph_t		*tcph;
17460 	struct datab	*db;
17461 	uint32_t	suna;
17462 	uint32_t	mss;
17463 	ipaddr_t	*dst;
17464 	ipaddr_t	*src;
17465 	uint32_t	sum;
17466 	int		usable;
17467 	conn_t		*connp = (conn_t *)arg;
17468 	tcp_t		*tcp = connp->conn_tcp;
17469 	uint32_t	msize;
17470 
17471 	/*
17472 	 * Try and ASSERT the minimum possible references on the
17473 	 * conn early enough. Since we are executing on write side,
17474 	 * the connection is obviously not detached and that means
17475 	 * there is a ref each for TCP and IP. Since we are behind
17476 	 * the squeue, the minimum references needed are 3. If the
17477 	 * conn is in classifier hash list, there should be an
17478 	 * extra ref for that (we check both the possibilities).
17479 	 */
17480 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17481 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17482 
17483 	/* Bypass tcp protocol for fused tcp loopback */
17484 	if (tcp->tcp_fused) {
17485 		msize = msgdsize(mp);
17486 		mutex_enter(&connp->conn_lock);
17487 		tcp->tcp_squeue_bytes -= msize;
17488 		mutex_exit(&connp->conn_lock);
17489 
17490 		if (tcp_fuse_output(tcp, mp))
17491 			return;
17492 	}
17493 
17494 	mss = tcp->tcp_mss;
17495 	if (tcp->tcp_xmit_zc_clean)
17496 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17497 
17498 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17499 	len = (int)(mp->b_wptr - mp->b_rptr);
17500 
17501 	/*
17502 	 * Criteria for fast path:
17503 	 *
17504 	 *   1. no unsent data
17505 	 *   2. single mblk in request
17506 	 *   3. connection established
17507 	 *   4. data in mblk
17508 	 *   5. len <= mss
17509 	 *   6. no tcp_valid bits
17510 	 */
17511 	if ((tcp->tcp_unsent != 0) ||
17512 	    (tcp->tcp_cork) ||
17513 	    (mp->b_cont != NULL) ||
17514 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17515 	    (len == 0) ||
17516 	    (len > mss) ||
17517 	    (tcp->tcp_valid_bits != 0)) {
17518 		msize = msgdsize(mp);
17519 		mutex_enter(&connp->conn_lock);
17520 		tcp->tcp_squeue_bytes -= msize;
17521 		mutex_exit(&connp->conn_lock);
17522 
17523 		tcp_wput_data(tcp, mp, B_FALSE);
17524 		return;
17525 	}
17526 
17527 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17528 	ASSERT(tcp->tcp_fin_sent == 0);
17529 
17530 	mutex_enter(&connp->conn_lock);
17531 	tcp->tcp_squeue_bytes -= len;
17532 	mutex_exit(&connp->conn_lock);
17533 
17534 	/* queue new packet onto retransmission queue */
17535 	if (tcp->tcp_xmit_head == NULL) {
17536 		tcp->tcp_xmit_head = mp;
17537 	} else {
17538 		tcp->tcp_xmit_last->b_cont = mp;
17539 	}
17540 	tcp->tcp_xmit_last = mp;
17541 	tcp->tcp_xmit_tail = mp;
17542 
17543 	/* find out how much we can send */
17544 	/* BEGIN CSTYLED */
17545 	/*
17546 	 *    un-acked           usable
17547 	 *  |--------------|-----------------|
17548 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17549 	 */
17550 	/* END CSTYLED */
17551 
17552 	/* start sending from tcp_snxt */
17553 	snxt = tcp->tcp_snxt;
17554 
17555 	/*
17556 	 * Check to see if this connection has been idled for some
17557 	 * time and no ACK is expected.  If it is, we need to slow
17558 	 * start again to get back the connection's "self-clock" as
17559 	 * described in VJ's paper.
17560 	 *
17561 	 * Refer to the comment in tcp_mss_set() for the calculation
17562 	 * of tcp_cwnd after idle.
17563 	 */
17564 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17565 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17566 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17567 	}
17568 
17569 	usable = tcp->tcp_swnd;		/* tcp window size */
17570 	if (usable > tcp->tcp_cwnd)
17571 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17572 	usable -= snxt;		/* subtract stuff already sent */
17573 	suna = tcp->tcp_suna;
17574 	usable += suna;
17575 	/* usable can be < 0 if the congestion window is smaller */
17576 	if (len > usable) {
17577 		/* Can't send complete M_DATA in one shot */
17578 		goto slow;
17579 	}
17580 
17581 	if (tcp->tcp_flow_stopped &&
17582 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17583 		tcp_clrqfull(tcp);
17584 	}
17585 
17586 	/*
17587 	 * determine if anything to send (Nagle).
17588 	 *
17589 	 *   1. len < tcp_mss (i.e. small)
17590 	 *   2. unacknowledged data present
17591 	 *   3. len < nagle limit
17592 	 *   4. last packet sent < nagle limit (previous packet sent)
17593 	 */
17594 	if ((len < mss) && (snxt != suna) &&
17595 	    (len < (int)tcp->tcp_naglim) &&
17596 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17597 		/*
17598 		 * This was the first unsent packet and normally
17599 		 * mss < xmit_hiwater so there is no need to worry
17600 		 * about flow control. The next packet will go
17601 		 * through the flow control check in tcp_wput_data().
17602 		 */
17603 		/* leftover work from above */
17604 		tcp->tcp_unsent = len;
17605 		tcp->tcp_xmit_tail_unsent = len;
17606 
17607 		return;
17608 	}
17609 
17610 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17611 
17612 	if (snxt == suna) {
17613 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17614 	}
17615 
17616 	/* we have always sent something */
17617 	tcp->tcp_rack_cnt = 0;
17618 
17619 	tcp->tcp_snxt = snxt + len;
17620 	tcp->tcp_rack = tcp->tcp_rnxt;
17621 
17622 	if ((mp1 = dupb(mp)) == 0)
17623 		goto no_memory;
17624 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17625 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17626 
17627 	/* adjust tcp header information */
17628 	tcph = tcp->tcp_tcph;
17629 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17630 
17631 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17632 	sum = (sum >> 16) + (sum & 0xFFFF);
17633 	U16_TO_ABE16(sum, tcph->th_sum);
17634 
17635 	U32_TO_ABE32(snxt, tcph->th_seq);
17636 
17637 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17638 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17639 	BUMP_LOCAL(tcp->tcp_obsegs);
17640 
17641 	/* Update the latest receive window size in TCP header. */
17642 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17643 	    tcph->th_win);
17644 
17645 	tcp->tcp_last_sent_len = (ushort_t)len;
17646 
17647 	plen = len + tcp->tcp_hdr_len;
17648 
17649 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17650 		tcp->tcp_ipha->ipha_length = htons(plen);
17651 	} else {
17652 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17653 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17654 	}
17655 
17656 	/* see if we need to allocate a mblk for the headers */
17657 	hdrlen = tcp->tcp_hdr_len;
17658 	rptr = mp1->b_rptr - hdrlen;
17659 	db = mp1->b_datap;
17660 	if ((db->db_ref != 2) || rptr < db->db_base ||
17661 	    (!OK_32PTR(rptr))) {
17662 		/* NOTE: we assume allocb returns an OK_32PTR */
17663 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17664 		    tcp_wroff_xtra, BPRI_MED);
17665 		if (!mp) {
17666 			freemsg(mp1);
17667 			goto no_memory;
17668 		}
17669 		mp->b_cont = mp1;
17670 		mp1 = mp;
17671 		/* Leave room for Link Level header */
17672 		/* hdrlen = tcp->tcp_hdr_len; */
17673 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17674 		mp1->b_wptr = &rptr[hdrlen];
17675 	}
17676 	mp1->b_rptr = rptr;
17677 
17678 	/* Fill in the timestamp option. */
17679 	if (tcp->tcp_snd_ts_ok) {
17680 		U32_TO_BE32((uint32_t)lbolt,
17681 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17682 		U32_TO_BE32(tcp->tcp_ts_recent,
17683 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17684 	} else {
17685 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17686 	}
17687 
17688 	/* copy header into outgoing packet */
17689 	dst = (ipaddr_t *)rptr;
17690 	src = (ipaddr_t *)tcp->tcp_iphc;
17691 	dst[0] = src[0];
17692 	dst[1] = src[1];
17693 	dst[2] = src[2];
17694 	dst[3] = src[3];
17695 	dst[4] = src[4];
17696 	dst[5] = src[5];
17697 	dst[6] = src[6];
17698 	dst[7] = src[7];
17699 	dst[8] = src[8];
17700 	dst[9] = src[9];
17701 	if (hdrlen -= 40) {
17702 		hdrlen >>= 2;
17703 		dst += 10;
17704 		src += 10;
17705 		do {
17706 			*dst++ = *src++;
17707 		} while (--hdrlen);
17708 	}
17709 
17710 	/*
17711 	 * Set the ECN info in the TCP header.  Note that this
17712 	 * is not the template header.
17713 	 */
17714 	if (tcp->tcp_ecn_ok) {
17715 		SET_ECT(tcp, rptr);
17716 
17717 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17718 		if (tcp->tcp_ecn_echo_on)
17719 			tcph->th_flags[0] |= TH_ECE;
17720 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17721 			tcph->th_flags[0] |= TH_CWR;
17722 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17723 		}
17724 	}
17725 
17726 	if (tcp->tcp_ip_forward_progress) {
17727 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17728 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17729 		tcp->tcp_ip_forward_progress = B_FALSE;
17730 	}
17731 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17732 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17733 	return;
17734 
17735 	/*
17736 	 * If we ran out of memory, we pretend to have sent the packet
17737 	 * and that it was lost on the wire.
17738 	 */
17739 no_memory:
17740 	return;
17741 
17742 slow:
17743 	/* leftover work from above */
17744 	tcp->tcp_unsent = len;
17745 	tcp->tcp_xmit_tail_unsent = len;
17746 	tcp_wput_data(tcp, NULL, B_FALSE);
17747 }
17748 
17749 /*
17750  * The function called through squeue to get behind eager's perimeter to
17751  * finish the accept processing.
17752  */
17753 /* ARGSUSED */
17754 void
17755 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17756 {
17757 	conn_t			*connp = (conn_t *)arg;
17758 	tcp_t			*tcp = connp->conn_tcp;
17759 	queue_t			*q = tcp->tcp_rq;
17760 	mblk_t			*mp1;
17761 	mblk_t			*stropt_mp = mp;
17762 	struct  stroptions	*stropt;
17763 	uint_t			thwin;
17764 
17765 	/*
17766 	 * Drop the eager's ref on the listener, that was placed when
17767 	 * this eager began life in tcp_conn_request.
17768 	 */
17769 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17770 
17771 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17772 		/*
17773 		 * Someone blewoff the eager before we could finish
17774 		 * the accept.
17775 		 *
17776 		 * The only reason eager exists it because we put in
17777 		 * a ref on it when conn ind went up. We need to send
17778 		 * a disconnect indication up while the last reference
17779 		 * on the eager will be dropped by the squeue when we
17780 		 * return.
17781 		 */
17782 		ASSERT(tcp->tcp_listener == NULL);
17783 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17784 			struct	T_discon_ind	*tdi;
17785 
17786 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17787 			/*
17788 			 * Let us reuse the incoming mblk to avoid memory
17789 			 * allocation failure problems. We know that the
17790 			 * size of the incoming mblk i.e. stroptions is greater
17791 			 * than sizeof T_discon_ind. So the reallocb below
17792 			 * can't fail.
17793 			 */
17794 			freemsg(mp->b_cont);
17795 			mp->b_cont = NULL;
17796 			ASSERT(DB_REF(mp) == 1);
17797 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17798 			    B_FALSE);
17799 			ASSERT(mp != NULL);
17800 			DB_TYPE(mp) = M_PROTO;
17801 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17802 			tdi = (struct T_discon_ind *)mp->b_rptr;
17803 			if (tcp->tcp_issocket) {
17804 				tdi->DISCON_reason = ECONNREFUSED;
17805 				tdi->SEQ_number = 0;
17806 			} else {
17807 				tdi->DISCON_reason = ENOPROTOOPT;
17808 				tdi->SEQ_number =
17809 				    tcp->tcp_conn_req_seqnum;
17810 			}
17811 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17812 			putnext(q, mp);
17813 		} else {
17814 			freemsg(mp);
17815 		}
17816 		if (tcp->tcp_hard_binding) {
17817 			tcp->tcp_hard_binding = B_FALSE;
17818 			tcp->tcp_hard_bound = B_TRUE;
17819 		}
17820 		tcp->tcp_detached = B_FALSE;
17821 		return;
17822 	}
17823 
17824 	mp1 = stropt_mp->b_cont;
17825 	stropt_mp->b_cont = NULL;
17826 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17827 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17828 
17829 	while (mp1 != NULL) {
17830 		mp = mp1;
17831 		mp1 = mp1->b_cont;
17832 		mp->b_cont = NULL;
17833 		tcp->tcp_drop_opt_ack_cnt++;
17834 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17835 	}
17836 	mp = NULL;
17837 
17838 	/*
17839 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17840 	 * properly.  This is the first time we know of the acceptor'
17841 	 * queue.  So we do it here.
17842 	 */
17843 	if (tcp->tcp_rcv_list == NULL) {
17844 		/*
17845 		 * Recv queue is empty, tcp_rwnd should not have changed.
17846 		 * That means it should be equal to the listener's tcp_rwnd.
17847 		 */
17848 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17849 	} else {
17850 #ifdef DEBUG
17851 		uint_t cnt = 0;
17852 
17853 		mp1 = tcp->tcp_rcv_list;
17854 		while ((mp = mp1) != NULL) {
17855 			mp1 = mp->b_next;
17856 			cnt += msgdsize(mp);
17857 		}
17858 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17859 #endif
17860 		/* There is some data, add them back to get the max. */
17861 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17862 	}
17863 
17864 	stropt->so_flags = SO_HIWAT;
17865 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17866 
17867 	stropt->so_flags |= SO_MAXBLK;
17868 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17869 
17870 	/*
17871 	 * This is the first time we run on the correct
17872 	 * queue after tcp_accept. So fix all the q parameters
17873 	 * here.
17874 	 */
17875 	/* Allocate room for SACK options if needed. */
17876 	stropt->so_flags |= SO_WROFF;
17877 	if (tcp->tcp_fused) {
17878 		size_t sth_hiwat;
17879 
17880 		ASSERT(tcp->tcp_loopback);
17881 		/*
17882 		 * For fused tcp loopback, set the stream head's write
17883 		 * offset value to zero since we won't be needing any room
17884 		 * for TCP/IP headers.  This would also improve performance
17885 		 * since it would reduce the amount of work done by kmem.
17886 		 * Non-fused tcp loopback case is handled separately below.
17887 		 */
17888 		stropt->so_wroff = 0;
17889 
17890 		/*
17891 		 * Override q_hiwat and set it to be twice that of the
17892 		 * previous value; this is to simulate non-fusion case.
17893 		 */
17894 		sth_hiwat = q->q_hiwat << 1;
17895 		if (sth_hiwat > tcp_max_buf)
17896 			sth_hiwat = tcp_max_buf;
17897 
17898 		stropt->so_hiwat = MAX(sth_hiwat, tcp_sth_rcv_hiwat);
17899 	} else if (tcp->tcp_snd_sack_ok) {
17900 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17901 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17902 	} else {
17903 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17904 		    tcp_wroff_xtra);
17905 	}
17906 
17907 	/*
17908 	 * If loopback, set COPYCACHED option to make sure NOT to use
17909 	 * non-temporal access.
17910 	 */
17911 	if (tcp->tcp_loopback) {
17912 		stropt->so_flags |= SO_COPYOPT;
17913 		stropt->so_copyopt = COPYCACHED;
17914 	}
17915 
17916 	/* Send the options up */
17917 	putnext(q, stropt_mp);
17918 
17919 	/*
17920 	 * Pass up any data and/or a fin that has been received.
17921 	 *
17922 	 * Adjust receive window in case it had decreased
17923 	 * (because there is data <=> tcp_rcv_list != NULL)
17924 	 * while the connection was detached. Note that
17925 	 * in case the eager was flow-controlled, w/o this
17926 	 * code, the rwnd may never open up again!
17927 	 */
17928 	if (tcp->tcp_rcv_list != NULL) {
17929 		/* We drain directly in case of fused tcp loopback */
17930 		if (!tcp->tcp_fused && canputnext(q)) {
17931 			tcp->tcp_rwnd = q->q_hiwat;
17932 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17933 			    << tcp->tcp_rcv_ws;
17934 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17935 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17936 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17937 				tcp_xmit_ctl(NULL,
17938 				    tcp, (tcp->tcp_swnd == 0) ?
17939 				    tcp->tcp_suna : tcp->tcp_snxt,
17940 				    tcp->tcp_rnxt, TH_ACK);
17941 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17942 			}
17943 
17944 		}
17945 		(void) tcp_rcv_drain(q, tcp);
17946 
17947 		/*
17948 		 * For fused tcp loopback, back-enable peer endpoint
17949 		 * if it's currently flow-controlled.
17950 		 */
17951 		if (tcp->tcp_fused &&
17952 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17953 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17954 
17955 			ASSERT(peer_tcp != NULL);
17956 			ASSERT(peer_tcp->tcp_fused);
17957 
17958 			tcp_clrqfull(peer_tcp);
17959 			TCP_STAT(tcp_fusion_backenabled);
17960 		}
17961 	}
17962 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17963 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17964 		mp = mi_tpi_ordrel_ind();
17965 		if (mp) {
17966 			tcp->tcp_ordrel_done = B_TRUE;
17967 			putnext(q, mp);
17968 			if (tcp->tcp_deferred_clean_death) {
17969 				/*
17970 				 * tcp_clean_death was deferred
17971 				 * for T_ORDREL_IND - do it now
17972 				 */
17973 				(void) tcp_clean_death(
17974 					tcp,
17975 					    tcp->tcp_client_errno, 21);
17976 				tcp->tcp_deferred_clean_death =
17977 				    B_FALSE;
17978 			}
17979 		} else {
17980 			/*
17981 			 * Run the orderly release in the
17982 			 * service routine.
17983 			 */
17984 			qenable(q);
17985 		}
17986 	}
17987 	if (tcp->tcp_hard_binding) {
17988 		tcp->tcp_hard_binding = B_FALSE;
17989 		tcp->tcp_hard_bound = B_TRUE;
17990 	}
17991 	tcp->tcp_detached = B_FALSE;
17992 
17993 	if (tcp->tcp_ka_enabled) {
17994 		tcp->tcp_ka_last_intrvl = 0;
17995 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17996 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17997 	}
17998 
17999 	/*
18000 	 * At this point, eager is fully established and will
18001 	 * have the following references -
18002 	 *
18003 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18004 	 * 1 reference for the squeue which will be dropped by the squeue as
18005 	 *	soon as this function returns.
18006 	 * There will be 1 additonal reference for being in classifier
18007 	 *	hash list provided something bad hasn't happened.
18008 	 */
18009 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18010 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18011 }
18012 
18013 /*
18014  * The function called through squeue to get behind listener's perimeter to
18015  * send a deffered conn_ind.
18016  */
18017 /* ARGSUSED */
18018 void
18019 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18020 {
18021 	conn_t	*connp = (conn_t *)arg;
18022 	tcp_t *listener = connp->conn_tcp;
18023 
18024 	if (listener->tcp_state == TCPS_CLOSED ||
18025 	    TCP_IS_DETACHED(listener)) {
18026 		/*
18027 		 * If listener has closed, it would have caused a
18028 		 * a cleanup/blowoff to happen for the eager.
18029 		 */
18030 		tcp_t *tcp;
18031 		struct T_conn_ind	*conn_ind;
18032 
18033 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18034 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18035 		    conn_ind->OPT_length);
18036 		/*
18037 		 * We need to drop the ref on eager that was put
18038 		 * tcp_rput_data() before trying to send the conn_ind
18039 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18040 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18041 		 * listener is closed so we drop the ref.
18042 		 */
18043 		CONN_DEC_REF(tcp->tcp_connp);
18044 		freemsg(mp);
18045 		return;
18046 	}
18047 	putnext(listener->tcp_rq, mp);
18048 }
18049 
18050 
18051 /*
18052  * This is the STREAMS entry point for T_CONN_RES coming down on
18053  * Acceptor STREAM when  sockfs listener does accept processing.
18054  * Read the block comment on top pf tcp_conn_request().
18055  */
18056 void
18057 tcp_wput_accept(queue_t *q, mblk_t *mp)
18058 {
18059 	queue_t *rq = RD(q);
18060 	struct T_conn_res *conn_res;
18061 	tcp_t *eager;
18062 	tcp_t *listener;
18063 	struct T_ok_ack *ok;
18064 	t_scalar_t PRIM_type;
18065 	mblk_t *opt_mp;
18066 	conn_t *econnp;
18067 
18068 	ASSERT(DB_TYPE(mp) == M_PROTO);
18069 
18070 	conn_res = (struct T_conn_res *)mp->b_rptr;
18071 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18072 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18073 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18074 		if (mp != NULL)
18075 			putnext(rq, mp);
18076 		return;
18077 	}
18078 	switch (conn_res->PRIM_type) {
18079 	case O_T_CONN_RES:
18080 	case T_CONN_RES:
18081 		/*
18082 		 * We pass up an err ack if allocb fails. This will
18083 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18084 		 * tcp_eager_blowoff to be called. sockfs will then call
18085 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18086 		 * we need to do the allocb up here because we have to
18087 		 * make sure rq->q_qinfo->qi_qclose still points to the
18088 		 * correct function (tcpclose_accept) in case allocb
18089 		 * fails.
18090 		 */
18091 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18092 		if (opt_mp == NULL) {
18093 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18094 			if (mp != NULL)
18095 				putnext(rq, mp);
18096 			return;
18097 		}
18098 
18099 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18100 		    &eager, conn_res->OPT_length);
18101 		PRIM_type = conn_res->PRIM_type;
18102 		mp->b_datap->db_type = M_PCPROTO;
18103 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18104 		ok = (struct T_ok_ack *)mp->b_rptr;
18105 		ok->PRIM_type = T_OK_ACK;
18106 		ok->CORRECT_prim = PRIM_type;
18107 		econnp = eager->tcp_connp;
18108 		econnp->conn_dev = (dev_t)q->q_ptr;
18109 		eager->tcp_rq = rq;
18110 		eager->tcp_wq = q;
18111 		rq->q_ptr = econnp;
18112 		rq->q_qinfo = &tcp_rinit;
18113 		q->q_ptr = econnp;
18114 		q->q_qinfo = &tcp_winit;
18115 		listener = eager->tcp_listener;
18116 		eager->tcp_issocket = B_TRUE;
18117 		eager->tcp_cred = econnp->conn_cred =
18118 		    listener->tcp_connp->conn_cred;
18119 		crhold(econnp->conn_cred);
18120 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18121 
18122 		/* Put the ref for IP */
18123 		CONN_INC_REF(econnp);
18124 
18125 		/*
18126 		 * We should have minimum of 3 references on the conn
18127 		 * at this point. One each for TCP and IP and one for
18128 		 * the T_conn_ind that was sent up when the 3-way handshake
18129 		 * completed. In the normal case we would also have another
18130 		 * reference (making a total of 4) for the conn being in the
18131 		 * classifier hash list. However the eager could have received
18132 		 * an RST subsequently and tcp_closei_local could have removed
18133 		 * the eager from the classifier hash list, hence we can't
18134 		 * assert that reference.
18135 		 */
18136 		ASSERT(econnp->conn_ref >= 3);
18137 
18138 		/*
18139 		 * Send the new local address also up to sockfs. There
18140 		 * should already be enough space in the mp that came
18141 		 * down from soaccept().
18142 		 */
18143 		if (eager->tcp_family == AF_INET) {
18144 			sin_t *sin;
18145 
18146 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18147 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18148 			sin = (sin_t *)mp->b_wptr;
18149 			mp->b_wptr += sizeof (sin_t);
18150 			sin->sin_family = AF_INET;
18151 			sin->sin_port = eager->tcp_lport;
18152 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18153 		} else {
18154 			sin6_t *sin6;
18155 
18156 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18157 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18158 			sin6 = (sin6_t *)mp->b_wptr;
18159 			mp->b_wptr += sizeof (sin6_t);
18160 			sin6->sin6_family = AF_INET6;
18161 			sin6->sin6_port = eager->tcp_lport;
18162 			if (eager->tcp_ipversion == IPV4_VERSION) {
18163 				sin6->sin6_flowinfo = 0;
18164 				IN6_IPADDR_TO_V4MAPPED(
18165 					eager->tcp_ipha->ipha_src,
18166 					    &sin6->sin6_addr);
18167 			} else {
18168 				ASSERT(eager->tcp_ip6h != NULL);
18169 				sin6->sin6_flowinfo =
18170 				    eager->tcp_ip6h->ip6_vcf &
18171 				    ~IPV6_VERS_AND_FLOW_MASK;
18172 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18173 			}
18174 			sin6->sin6_scope_id = 0;
18175 			sin6->__sin6_src_id = 0;
18176 		}
18177 
18178 		putnext(rq, mp);
18179 
18180 		opt_mp->b_datap->db_type = M_SETOPTS;
18181 		opt_mp->b_wptr += sizeof (struct stroptions);
18182 
18183 		/*
18184 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18185 		 * from listener to acceptor. The message is chained on the
18186 		 * bind_mp which tcp_rput_other will send down to IP.
18187 		 */
18188 		if (listener->tcp_bound_if != 0) {
18189 			/* allocate optmgmt req */
18190 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18191 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18192 			    sizeof (int));
18193 			if (mp != NULL)
18194 				linkb(opt_mp, mp);
18195 		}
18196 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18197 			uint_t on = 1;
18198 
18199 			/* allocate optmgmt req */
18200 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18201 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18202 			if (mp != NULL)
18203 				linkb(opt_mp, mp);
18204 		}
18205 
18206 
18207 		mutex_enter(&listener->tcp_eager_lock);
18208 
18209 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18210 
18211 			tcp_t *tail;
18212 			tcp_t *tcp;
18213 			mblk_t *mp1;
18214 
18215 			tcp = listener->tcp_eager_prev_q0;
18216 			/*
18217 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18218 			 * deferred T_conn_ind queue. We need to get to the head
18219 			 * of the queue in order to send up T_conn_ind the same
18220 			 * order as how the 3WHS is completed.
18221 			 */
18222 			while (tcp != listener) {
18223 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
18224 					break;
18225 				else
18226 					tcp = tcp->tcp_eager_prev_q0;
18227 			}
18228 			ASSERT(tcp != listener);
18229 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18230 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18231 			/* Move from q0 to q */
18232 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18233 			listener->tcp_conn_req_cnt_q0--;
18234 			listener->tcp_conn_req_cnt_q++;
18235 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18236 			    tcp->tcp_eager_prev_q0;
18237 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18238 			    tcp->tcp_eager_next_q0;
18239 			tcp->tcp_eager_prev_q0 = NULL;
18240 			tcp->tcp_eager_next_q0 = NULL;
18241 			tcp->tcp_conn_def_q0 = B_FALSE;
18242 
18243 			/*
18244 			 * Insert at end of the queue because sockfs sends
18245 			 * down T_CONN_RES in chronological order. Leaving
18246 			 * the older conn indications at front of the queue
18247 			 * helps reducing search time.
18248 			 */
18249 			tail = listener->tcp_eager_last_q;
18250 			if (tail != NULL) {
18251 				tail->tcp_eager_next_q = tcp;
18252 			} else {
18253 				listener->tcp_eager_next_q = tcp;
18254 			}
18255 			listener->tcp_eager_last_q = tcp;
18256 			tcp->tcp_eager_next_q = NULL;
18257 
18258 			/* Need to get inside the listener perimeter */
18259 			CONN_INC_REF(listener->tcp_connp);
18260 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18261 			    tcp_send_pending, listener->tcp_connp,
18262 			    SQTAG_TCP_SEND_PENDING);
18263 		}
18264 		tcp_eager_unlink(eager);
18265 		mutex_exit(&listener->tcp_eager_lock);
18266 
18267 		/*
18268 		 * At this point, the eager is detached from the listener
18269 		 * but we still have an extra refs on eager (apart from the
18270 		 * usual tcp references). The ref was placed in tcp_rput_data
18271 		 * before sending the conn_ind in tcp_send_conn_ind.
18272 		 * The ref will be dropped in tcp_accept_finish().
18273 		 */
18274 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18275 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18276 		return;
18277 	default:
18278 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18279 		if (mp != NULL)
18280 			putnext(rq, mp);
18281 		return;
18282 	}
18283 }
18284 
18285 static void
18286 tcp_wput(queue_t *q, mblk_t *mp)
18287 {
18288 	conn_t	*connp = Q_TO_CONN(q);
18289 	tcp_t	*tcp;
18290 	void (*output_proc)();
18291 	t_scalar_t type;
18292 	uchar_t *rptr;
18293 	struct iocblk	*iocp;
18294 	uint32_t	msize;
18295 
18296 	ASSERT(connp->conn_ref >= 2);
18297 
18298 	switch (DB_TYPE(mp)) {
18299 	case M_DATA:
18300 		tcp = connp->conn_tcp;
18301 		ASSERT(tcp != NULL);
18302 
18303 		msize = msgdsize(mp);
18304 
18305 		mutex_enter(&connp->conn_lock);
18306 		CONN_INC_REF_LOCKED(connp);
18307 
18308 		tcp->tcp_squeue_bytes += msize;
18309 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18310 			mutex_exit(&connp->conn_lock);
18311 			tcp_setqfull(tcp);
18312 		} else
18313 			mutex_exit(&connp->conn_lock);
18314 
18315 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18316 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18317 		return;
18318 	case M_PROTO:
18319 	case M_PCPROTO:
18320 		/*
18321 		 * if it is a snmp message, don't get behind the squeue
18322 		 */
18323 		tcp = connp->conn_tcp;
18324 		rptr = mp->b_rptr;
18325 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18326 			type = ((union T_primitives *)rptr)->type;
18327 		} else {
18328 			if (tcp->tcp_debug) {
18329 				(void) strlog(TCP_MODULE_ID, 0, 1,
18330 				    SL_ERROR|SL_TRACE,
18331 				    "tcp_wput_proto, dropping one...");
18332 			}
18333 			freemsg(mp);
18334 			return;
18335 		}
18336 		if (type == T_SVR4_OPTMGMT_REQ) {
18337 			cred_t	*cr = DB_CREDDEF(mp,
18338 			    tcp->tcp_cred);
18339 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18340 			    cr)) {
18341 				/*
18342 				 * This was a SNMP request
18343 				 */
18344 				return;
18345 			} else {
18346 				output_proc = tcp_wput_proto;
18347 			}
18348 		} else {
18349 			output_proc = tcp_wput_proto;
18350 		}
18351 		break;
18352 	case M_IOCTL:
18353 		/*
18354 		 * Most ioctls can be processed right away without going via
18355 		 * squeues - process them right here. Those that do require
18356 		 * squeue (currently TCP_IOC_DEFAULT_Q and SIOCPOPSOCKFS)
18357 		 * are processed by tcp_wput_ioctl().
18358 		 */
18359 		iocp = (struct iocblk *)mp->b_rptr;
18360 		tcp = connp->conn_tcp;
18361 
18362 		switch (iocp->ioc_cmd) {
18363 		case TCP_IOC_ABORT_CONN:
18364 			tcp_ioctl_abort_conn(q, mp);
18365 			return;
18366 		case TI_GETPEERNAME:
18367 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18368 				iocp->ioc_error = ENOTCONN;
18369 				iocp->ioc_count = 0;
18370 				mp->b_datap->db_type = M_IOCACK;
18371 				qreply(q, mp);
18372 				return;
18373 			}
18374 			/* FALLTHRU */
18375 		case TI_GETMYNAME:
18376 			mi_copyin(q, mp, NULL,
18377 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18378 			return;
18379 		case ND_SET:
18380 			/* nd_getset does the necessary checks */
18381 		case ND_GET:
18382 			if (!nd_getset(q, tcp_g_nd, mp)) {
18383 				CALL_IP_WPUT(connp, q, mp);
18384 				return;
18385 			}
18386 			qreply(q, mp);
18387 			return;
18388 		case TCP_IOC_DEFAULT_Q:
18389 			/*
18390 			 * Wants to be the default wq. Check the credentials
18391 			 * first, the rest is executed via squeue.
18392 			 */
18393 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
18394 				iocp->ioc_error = EPERM;
18395 				iocp->ioc_count = 0;
18396 				mp->b_datap->db_type = M_IOCACK;
18397 				qreply(q, mp);
18398 				return;
18399 			}
18400 			output_proc = tcp_wput_ioctl;
18401 			break;
18402 		default:
18403 			output_proc = tcp_wput_ioctl;
18404 			break;
18405 		}
18406 		break;
18407 	default:
18408 		output_proc = tcp_wput_nondata;
18409 		break;
18410 	}
18411 
18412 	CONN_INC_REF(connp);
18413 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18414 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18415 }
18416 
18417 /*
18418  * Initial STREAMS write side put() procedure for sockets. It tries to
18419  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18420  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18421  * are handled by tcp_wput() as usual.
18422  *
18423  * All further messages will also be handled by tcp_wput() because we cannot
18424  * be sure that the above short cut is safe later.
18425  */
18426 static void
18427 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18428 {
18429 	conn_t			*connp = Q_TO_CONN(wq);
18430 	tcp_t			*tcp = connp->conn_tcp;
18431 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18432 
18433 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18434 	wq->q_qinfo = &tcp_winit;
18435 
18436 	ASSERT(IS_TCP_CONN(connp));
18437 	ASSERT(TCP_IS_SOCKET(tcp));
18438 
18439 	if (DB_TYPE(mp) == M_PCPROTO &&
18440 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18441 	    car->PRIM_type == T_CAPABILITY_REQ) {
18442 		tcp_capability_req(tcp, mp);
18443 		return;
18444 	}
18445 
18446 	tcp_wput(wq, mp);
18447 }
18448 
18449 static boolean_t
18450 tcp_zcopy_check(tcp_t *tcp)
18451 {
18452 	conn_t	*connp = tcp->tcp_connp;
18453 	ire_t	*ire;
18454 	boolean_t	zc_enabled = B_FALSE;
18455 
18456 	if (do_tcpzcopy == 2)
18457 		zc_enabled = B_TRUE;
18458 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18459 	    IPCL_IS_CONNECTED(connp) &&
18460 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18461 	    connp->conn_dontroute == 0 &&
18462 	    connp->conn_xmit_if_ill == NULL &&
18463 	    connp->conn_nofailover_ill == NULL &&
18464 	    do_tcpzcopy == 1) {
18465 		/*
18466 		 * the checks above  closely resemble the fast path checks
18467 		 * in tcp_send_data().
18468 		 */
18469 		mutex_enter(&connp->conn_lock);
18470 		ire = connp->conn_ire_cache;
18471 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18472 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18473 			IRE_REFHOLD(ire);
18474 			if (ire->ire_stq != NULL) {
18475 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18476 
18477 				zc_enabled = ill && (ill->ill_capabilities &
18478 				    ILL_CAPAB_ZEROCOPY) &&
18479 				    (ill->ill_zerocopy_capab->
18480 				    ill_zerocopy_flags != 0);
18481 			}
18482 			IRE_REFRELE(ire);
18483 		}
18484 		mutex_exit(&connp->conn_lock);
18485 	}
18486 	tcp->tcp_snd_zcopy_on = zc_enabled;
18487 	if (!TCP_IS_DETACHED(tcp)) {
18488 		if (zc_enabled) {
18489 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18490 			TCP_STAT(tcp_zcopy_on);
18491 		} else {
18492 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18493 			TCP_STAT(tcp_zcopy_off);
18494 		}
18495 	}
18496 	return (zc_enabled);
18497 }
18498 
18499 static mblk_t *
18500 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18501 {
18502 	if (do_tcpzcopy == 2)
18503 		return (bp);
18504 	else if (tcp->tcp_snd_zcopy_on) {
18505 		tcp->tcp_snd_zcopy_on = B_FALSE;
18506 		if (!TCP_IS_DETACHED(tcp)) {
18507 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18508 			TCP_STAT(tcp_zcopy_disable);
18509 		}
18510 	}
18511 	return (tcp_zcopy_backoff(tcp, bp, 0));
18512 }
18513 
18514 /*
18515  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18516  * the original desballoca'ed segmapped mblk.
18517  */
18518 static mblk_t *
18519 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18520 {
18521 	mblk_t *head, *tail, *nbp;
18522 	if (IS_VMLOANED_MBLK(bp)) {
18523 		TCP_STAT(tcp_zcopy_backoff);
18524 		if ((head = copyb(bp)) == NULL) {
18525 			/* fail to backoff; leave it for the next backoff */
18526 			tcp->tcp_xmit_zc_clean = B_FALSE;
18527 			return (bp);
18528 		}
18529 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18530 			if (fix_xmitlist)
18531 				tcp_zcopy_notify(tcp);
18532 			else
18533 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18534 		}
18535 		nbp = bp->b_cont;
18536 		if (fix_xmitlist) {
18537 			head->b_prev = bp->b_prev;
18538 			head->b_next = bp->b_next;
18539 			if (tcp->tcp_xmit_tail == bp)
18540 				tcp->tcp_xmit_tail = head;
18541 		}
18542 		bp->b_next = NULL;
18543 		bp->b_prev = NULL;
18544 		freeb(bp);
18545 	} else {
18546 		head = bp;
18547 		nbp = bp->b_cont;
18548 	}
18549 	tail = head;
18550 	while (nbp) {
18551 		if (IS_VMLOANED_MBLK(nbp)) {
18552 			TCP_STAT(tcp_zcopy_backoff);
18553 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18554 				tcp->tcp_xmit_zc_clean = B_FALSE;
18555 				tail->b_cont = nbp;
18556 				return (head);
18557 			}
18558 			tail = tail->b_cont;
18559 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18560 				if (fix_xmitlist)
18561 					tcp_zcopy_notify(tcp);
18562 				else
18563 					tail->b_datap->db_struioflag |=
18564 					    STRUIO_ZCNOTIFY;
18565 			}
18566 			bp = nbp;
18567 			nbp = nbp->b_cont;
18568 			if (fix_xmitlist) {
18569 				tail->b_prev = bp->b_prev;
18570 				tail->b_next = bp->b_next;
18571 				if (tcp->tcp_xmit_tail == bp)
18572 					tcp->tcp_xmit_tail = tail;
18573 			}
18574 			bp->b_next = NULL;
18575 			bp->b_prev = NULL;
18576 			freeb(bp);
18577 		} else {
18578 			tail->b_cont = nbp;
18579 			tail = nbp;
18580 			nbp = nbp->b_cont;
18581 		}
18582 	}
18583 	if (fix_xmitlist) {
18584 		tcp->tcp_xmit_last = tail;
18585 		tcp->tcp_xmit_zc_clean = B_TRUE;
18586 	}
18587 	return (head);
18588 }
18589 
18590 static void
18591 tcp_zcopy_notify(tcp_t *tcp)
18592 {
18593 	struct stdata	*stp;
18594 
18595 	if (tcp->tcp_detached)
18596 		return;
18597 	stp = STREAM(tcp->tcp_rq);
18598 	mutex_enter(&stp->sd_lock);
18599 	stp->sd_flag |= STZCNOTIFY;
18600 	cv_broadcast(&stp->sd_zcopy_wait);
18601 	mutex_exit(&stp->sd_lock);
18602 }
18603 
18604 
18605 static void
18606 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18607 {
18608 	ipha_t		*ipha;
18609 	ipaddr_t	src;
18610 	ipaddr_t	dst;
18611 	uint32_t	cksum;
18612 	ire_t		*ire;
18613 	uint16_t	*up;
18614 	ill_t		*ill;
18615 	conn_t		*connp = tcp->tcp_connp;
18616 	uint32_t	hcksum_txflags = 0;
18617 	mblk_t		*ire_fp_mp;
18618 	uint_t		ire_fp_mp_len;
18619 	ill_poll_capab_t *ill_poll;
18620 
18621 	ASSERT(DB_TYPE(mp) == M_DATA);
18622 
18623 	ipha = (ipha_t *)mp->b_rptr;
18624 	src = ipha->ipha_src;
18625 	dst = ipha->ipha_dst;
18626 
18627 	/*
18628 	 * Drop off slow path for IPv6 and also if options are present.
18629 	 */
18630 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18631 	    !IPCL_IS_CONNECTED(connp) ||
18632 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18633 	    connp->conn_dontroute ||
18634 	    connp->conn_xmit_if_ill != NULL ||
18635 	    connp->conn_nofailover_ill != NULL ||
18636 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18637 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18638 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18639 		if (tcp->tcp_snd_zcopy_aware)
18640 			mp = tcp_zcopy_disable(tcp, mp);
18641 		TCP_STAT(tcp_ip_send);
18642 		CALL_IP_WPUT(connp, q, mp);
18643 		return;
18644 	}
18645 
18646 	mutex_enter(&connp->conn_lock);
18647 	ire = connp->conn_ire_cache;
18648 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18649 	if (ire != NULL && ire->ire_addr == dst &&
18650 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18651 		IRE_REFHOLD(ire);
18652 		mutex_exit(&connp->conn_lock);
18653 	} else {
18654 		boolean_t cached = B_FALSE;
18655 
18656 		/* force a recheck later on */
18657 		tcp->tcp_ire_ill_check_done = B_FALSE;
18658 
18659 		TCP_DBGSTAT(tcp_ire_null1);
18660 		connp->conn_ire_cache = NULL;
18661 		mutex_exit(&connp->conn_lock);
18662 		if (ire != NULL)
18663 			IRE_REFRELE_NOTR(ire);
18664 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
18665 		if (ire == NULL) {
18666 			if (tcp->tcp_snd_zcopy_aware)
18667 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18668 			TCP_STAT(tcp_ire_null);
18669 			CALL_IP_WPUT(connp, q, mp);
18670 			return;
18671 		}
18672 		IRE_REFHOLD_NOTR(ire);
18673 		/*
18674 		 * Since we are inside the squeue, there cannot be another
18675 		 * thread in TCP trying to set the conn_ire_cache now.  The
18676 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18677 		 * unplumb thread has not yet started cleaning up the conns.
18678 		 * Hence we don't need to grab the conn lock.
18679 		 */
18680 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18681 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18682 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18683 				connp->conn_ire_cache = ire;
18684 				cached = B_TRUE;
18685 			}
18686 			rw_exit(&ire->ire_bucket->irb_lock);
18687 		}
18688 
18689 		/*
18690 		 * We can continue to use the ire but since it was
18691 		 * not cached, we should drop the extra reference.
18692 		 */
18693 		if (!cached)
18694 			IRE_REFRELE_NOTR(ire);
18695 	}
18696 
18697 	if (ire->ire_flags & RTF_MULTIRT ||
18698 	    ire->ire_stq == NULL ||
18699 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18700 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18701 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18702 		if (tcp->tcp_snd_zcopy_aware)
18703 			mp = tcp_zcopy_disable(tcp, mp);
18704 		TCP_STAT(tcp_ip_ire_send);
18705 		IRE_REFRELE(ire);
18706 		CALL_IP_WPUT(connp, q, mp);
18707 		return;
18708 	}
18709 
18710 	ill = ire_to_ill(ire);
18711 	if (connp->conn_outgoing_ill != NULL) {
18712 		ill_t *conn_outgoing_ill = NULL;
18713 		/*
18714 		 * Choose a good ill in the group to send the packets on.
18715 		 */
18716 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18717 		ill = ire_to_ill(ire);
18718 	}
18719 	ASSERT(ill != NULL);
18720 
18721 	if (!tcp->tcp_ire_ill_check_done) {
18722 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18723 		tcp->tcp_ire_ill_check_done = B_TRUE;
18724 	}
18725 
18726 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18727 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18728 #ifndef _BIG_ENDIAN
18729 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18730 #endif
18731 
18732 	/*
18733 	 * Check to see if we need to re-enable MDT for this connection
18734 	 * because it was previously disabled due to changes in the ill;
18735 	 * note that by doing it here, this re-enabling only applies when
18736 	 * the packet is not dispatched through CALL_IP_WPUT().
18737 	 *
18738 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18739 	 * case, since that's how we ended up here.  For IPv6, we do the
18740 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18741 	 */
18742 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18743 		/*
18744 		 * Restore MDT for this connection, so that next time around
18745 		 * it is eligible to go through tcp_multisend() path again.
18746 		 */
18747 		TCP_STAT(tcp_mdt_conn_resumed1);
18748 		tcp->tcp_mdt = B_TRUE;
18749 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18750 		    "interface %s\n", (void *)connp, ill->ill_name));
18751 	}
18752 
18753 	if (tcp->tcp_snd_zcopy_aware) {
18754 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18755 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18756 			mp = tcp_zcopy_disable(tcp, mp);
18757 		/*
18758 		 * we shouldn't need to reset ipha as the mp containing
18759 		 * ipha should never be a zero-copy mp.
18760 		 */
18761 	}
18762 
18763 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) && dohwcksum) {
18764 		ASSERT(ill->ill_hcksum_capab != NULL);
18765 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18766 	}
18767 
18768 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18769 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18770 
18771 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18772 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18773 
18774 	/*
18775 	 * Underlying interface supports hardware checksum offload for
18776 	 * the tcp payload, along with M_DATA fast path; leave the payload
18777 	 * checksum for the hardware to calculate.
18778 	 *
18779 	 * N.B: We only need to set up checksum info on the first mblk.
18780 	 */
18781 	if (hcksum_txflags & HCKSUM_INET_FULL_V4) {
18782 		/*
18783 		 * Hardware calculates pseudo-header, header and payload
18784 		 * checksums, so clear checksum field in TCP header.
18785 		 */
18786 		*up = 0;
18787 		mp->b_datap->db_struioun.cksum.flags |= HCK_FULLCKSUM;
18788 	} else if (hcksum_txflags & HCKSUM_INET_PARTIAL) {
18789 		uint32_t sum;
18790 		/*
18791 		 * Partial checksum offload has been enabled.  Fill the
18792 		 * checksum field in the TCP header with the pseudo-header
18793 		 * checksum value.
18794 		 */
18795 		sum = *up + cksum + IP_TCP_CSUM_COMP;
18796 		sum = (sum & 0xFFFF) + (sum >> 16);
18797 		*up = (sum & 0xFFFF) + (sum >> 16);
18798 		mp->b_datap->db_cksumstart = IP_SIMPLE_HDR_LENGTH;
18799 		mp->b_datap->db_cksumstuff = IP_SIMPLE_HDR_LENGTH + 16;
18800 		mp->b_datap->db_cksumend = ntohs(ipha->ipha_length);
18801 		mp->b_datap->db_struioun.cksum.flags |= HCK_PARTIALCKSUM;
18802 	} else {
18803 		/* software checksumming */
18804 		TCP_STAT(tcp_out_sw_cksum);
18805 		*up = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH,
18806 		    cksum + IP_TCP_CSUM_COMP);
18807 		mp->b_datap->db_struioun.cksum.flags = 0;
18808 	}
18809 
18810 	ipha->ipha_fragment_offset_and_flags |=
18811 	    (uint32_t)htons(ire->ire_frag_flag);
18812 
18813 	/*
18814 	 * Hardware supports IP header checksum offload; clear contents
18815 	 * of IP header checksum field.  Otherwise we calculate it.
18816 	 */
18817 	if (hcksum_txflags & HCKSUM_IPHDRCKSUM) {
18818 		ipha->ipha_hdr_checksum = 0;
18819 		mp->b_datap->db_struioun.cksum.flags |= HCK_IPV4_HDRCKSUM;
18820 	} else {
18821 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18822 		    ((uint16_t *)ipha)[4]);
18823 	}
18824 
18825 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18826 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18827 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18828 
18829 	UPDATE_OB_PKT_COUNT(ire);
18830 	ire->ire_last_used_time = lbolt;
18831 	BUMP_MIB(&ip_mib, ipOutRequests);
18832 
18833 	if (ill->ill_capabilities & ILL_CAPAB_POLL) {
18834 		ill_poll = ill->ill_poll_capab;
18835 		ASSERT(ill_poll != NULL);
18836 		ASSERT(ill_poll->ill_tx != NULL);
18837 		ASSERT(ill_poll->ill_tx_handle != NULL);
18838 
18839 		ill_poll->ill_tx(ill_poll->ill_tx_handle, mp);
18840 	} else {
18841 		putnext(ire->ire_stq, mp);
18842 	}
18843 	IRE_REFRELE(ire);
18844 }
18845 
18846 /*
18847  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18848  * if the receiver shrinks the window, i.e. moves the right window to the
18849  * left, the we should not send new data, but should retransmit normally the
18850  * old unacked data between suna and suna + swnd. We might has sent data
18851  * that is now outside the new window, pretend that we didn't send  it.
18852  */
18853 static void
18854 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18855 {
18856 	uint32_t	snxt = tcp->tcp_snxt;
18857 	mblk_t		*xmit_tail;
18858 	int32_t		offset;
18859 
18860 	ASSERT(shrunk_count > 0);
18861 
18862 	/* Pretend we didn't send the data outside the window */
18863 	snxt -= shrunk_count;
18864 
18865 	/* Get the mblk and the offset in it per the shrunk window */
18866 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18867 
18868 	ASSERT(xmit_tail != NULL);
18869 
18870 	/* Reset all the values per the now shrunk window */
18871 	tcp->tcp_snxt = snxt;
18872 	tcp->tcp_xmit_tail = xmit_tail;
18873 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18874 	    offset;
18875 	tcp->tcp_unsent += shrunk_count;
18876 
18877 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18878 		/*
18879 		 * Make sure the timer is running so that we will probe a zero
18880 		 * window.
18881 		 */
18882 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18883 }
18884 
18885 
18886 /*
18887  * The TCP normal data output path.
18888  * NOTE: the logic of the fast path is duplicated from this function.
18889  */
18890 static void
18891 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18892 {
18893 	int		len;
18894 	mblk_t		*local_time;
18895 	mblk_t		*mp1;
18896 	uint32_t	snxt;
18897 	int		tail_unsent;
18898 	int		tcpstate;
18899 	int		usable = 0;
18900 	mblk_t		*xmit_tail;
18901 	queue_t		*q = tcp->tcp_wq;
18902 	int32_t		mss;
18903 	int32_t		num_sack_blk = 0;
18904 	int32_t		tcp_hdr_len;
18905 	int32_t		tcp_tcp_hdr_len;
18906 	int		mdt_thres;
18907 	int		rc;
18908 
18909 	tcpstate = tcp->tcp_state;
18910 	if (mp == NULL) {
18911 		/*
18912 		 * tcp_wput_data() with NULL mp should only be called when
18913 		 * there is unsent data.
18914 		 */
18915 		ASSERT(tcp->tcp_unsent > 0);
18916 		/* Really tacky... but we need this for detached closes. */
18917 		len = tcp->tcp_unsent;
18918 		goto data_null;
18919 	}
18920 
18921 #if CCS_STATS
18922 	wrw_stats.tot.count++;
18923 	wrw_stats.tot.bytes += msgdsize(mp);
18924 #endif
18925 	ASSERT(mp->b_datap->db_type == M_DATA);
18926 	/*
18927 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18928 	 * or before a connection attempt has begun.
18929 	 */
18930 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18931 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18932 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18933 #ifdef DEBUG
18934 			cmn_err(CE_WARN,
18935 			    "tcp_wput_data: data after ordrel, %s",
18936 			    tcp_display(tcp, NULL,
18937 			    DISP_ADDR_AND_PORT));
18938 #else
18939 			if (tcp->tcp_debug) {
18940 				(void) strlog(TCP_MODULE_ID, 0, 1,
18941 				    SL_TRACE|SL_ERROR,
18942 				    "tcp_wput_data: data after ordrel, %s\n",
18943 				    tcp_display(tcp, NULL,
18944 				    DISP_ADDR_AND_PORT));
18945 			}
18946 #endif /* DEBUG */
18947 		}
18948 		if (tcp->tcp_snd_zcopy_aware &&
18949 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18950 			tcp_zcopy_notify(tcp);
18951 		freemsg(mp);
18952 		return;
18953 	}
18954 
18955 	/* Strip empties */
18956 	for (;;) {
18957 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18958 		    (uintptr_t)INT_MAX);
18959 		len = (int)(mp->b_wptr - mp->b_rptr);
18960 		if (len > 0)
18961 			break;
18962 		mp1 = mp;
18963 		mp = mp->b_cont;
18964 		freeb(mp1);
18965 		if (!mp) {
18966 			return;
18967 		}
18968 	}
18969 
18970 	/* If we are the first on the list ... */
18971 	if (tcp->tcp_xmit_head == NULL) {
18972 		tcp->tcp_xmit_head = mp;
18973 		tcp->tcp_xmit_tail = mp;
18974 		tcp->tcp_xmit_tail_unsent = len;
18975 	} else {
18976 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18977 		struct datab *dp;
18978 
18979 		mp1 = tcp->tcp_xmit_last;
18980 		if (len < tcp_tx_pull_len &&
18981 		    (dp = mp1->b_datap)->db_ref == 1 &&
18982 		    dp->db_lim - mp1->b_wptr >= len) {
18983 			ASSERT(len > 0);
18984 			ASSERT(!mp1->b_cont);
18985 			if (len == 1) {
18986 				*mp1->b_wptr++ = *mp->b_rptr;
18987 			} else {
18988 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18989 				mp1->b_wptr += len;
18990 			}
18991 			if (mp1 == tcp->tcp_xmit_tail)
18992 				tcp->tcp_xmit_tail_unsent += len;
18993 			mp1->b_cont = mp->b_cont;
18994 			if (tcp->tcp_snd_zcopy_aware &&
18995 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18996 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18997 			freeb(mp);
18998 			mp = mp1;
18999 		} else {
19000 			tcp->tcp_xmit_last->b_cont = mp;
19001 		}
19002 		len += tcp->tcp_unsent;
19003 	}
19004 
19005 	/* Tack on however many more positive length mblks we have */
19006 	if ((mp1 = mp->b_cont) != NULL) {
19007 		do {
19008 			int tlen;
19009 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19010 			    (uintptr_t)INT_MAX);
19011 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19012 			if (tlen <= 0) {
19013 				mp->b_cont = mp1->b_cont;
19014 				freeb(mp1);
19015 			} else {
19016 				len += tlen;
19017 				mp = mp1;
19018 			}
19019 		} while ((mp1 = mp->b_cont) != NULL);
19020 	}
19021 	tcp->tcp_xmit_last = mp;
19022 	tcp->tcp_unsent = len;
19023 
19024 	if (urgent)
19025 		usable = 1;
19026 
19027 data_null:
19028 	snxt = tcp->tcp_snxt;
19029 	xmit_tail = tcp->tcp_xmit_tail;
19030 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19031 
19032 	/*
19033 	 * Note that tcp_mss has been adjusted to take into account the
19034 	 * timestamp option if applicable.  Because SACK options do not
19035 	 * appear in every TCP segments and they are of variable lengths,
19036 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19037 	 * the actual segment length when we need to send a segment which
19038 	 * includes SACK options.
19039 	 */
19040 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19041 		int32_t	opt_len;
19042 
19043 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19044 		    tcp->tcp_num_sack_blk);
19045 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19046 		    2 + TCPOPT_HEADER_LEN;
19047 		mss = tcp->tcp_mss - opt_len;
19048 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19049 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19050 	} else {
19051 		mss = tcp->tcp_mss;
19052 		tcp_hdr_len = tcp->tcp_hdr_len;
19053 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19054 	}
19055 
19056 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19057 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19058 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
19059 	}
19060 	if (tcpstate == TCPS_SYN_RCVD) {
19061 		/*
19062 		 * The three-way connection establishment handshake is not
19063 		 * complete yet. We want to queue the data for transmission
19064 		 * after entering ESTABLISHED state (RFC793). A jump to
19065 		 * "done" label effectively leaves data on the queue.
19066 		 */
19067 		goto done;
19068 	} else {
19069 		int usable_r = tcp->tcp_swnd;
19070 
19071 		/*
19072 		 * In the special case when cwnd is zero, which can only
19073 		 * happen if the connection is ECN capable, return now.
19074 		 * New segments is sent using tcp_timer().  The timer
19075 		 * is set in tcp_rput_data().
19076 		 */
19077 		if (tcp->tcp_cwnd == 0) {
19078 			/*
19079 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19080 			 * finished.
19081 			 */
19082 			ASSERT(tcp->tcp_ecn_ok ||
19083 			    tcp->tcp_state < TCPS_ESTABLISHED);
19084 			return;
19085 		}
19086 
19087 		/* NOTE: trouble if xmitting while SYN not acked? */
19088 		usable_r -= snxt;
19089 		usable_r += tcp->tcp_suna;
19090 
19091 		/*
19092 		 * Check if the receiver has shrunk the window.  If
19093 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19094 		 * cannot be set as there is unsent data, so FIN cannot
19095 		 * be sent out.  Otherwise, we need to take into account
19096 		 * of FIN as it consumes an "invisible" sequence number.
19097 		 */
19098 		ASSERT(tcp->tcp_fin_sent == 0);
19099 		if (usable_r < 0) {
19100 			/*
19101 			 * The receiver has shrunk the window and we have sent
19102 			 * -usable_r date beyond the window, re-adjust.
19103 			 *
19104 			 * If TCP window scaling is enabled, there can be
19105 			 * round down error as the advertised receive window
19106 			 * is actually right shifted n bits.  This means that
19107 			 * the lower n bits info is wiped out.  It will look
19108 			 * like the window is shrunk.  Do a check here to
19109 			 * see if the shrunk amount is actually within the
19110 			 * error in window calculation.  If it is, just
19111 			 * return.  Note that this check is inside the
19112 			 * shrunk window check.  This makes sure that even
19113 			 * though tcp_process_shrunk_swnd() is not called,
19114 			 * we will stop further processing.
19115 			 */
19116 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19117 				tcp_process_shrunk_swnd(tcp, -usable_r);
19118 			}
19119 			return;
19120 		}
19121 
19122 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19123 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19124 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19125 
19126 		/* usable = MIN(usable, unsent) */
19127 		if (usable_r > len)
19128 			usable_r = len;
19129 
19130 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19131 		if (usable_r > 0) {
19132 			usable = usable_r;
19133 		} else {
19134 			/* Bypass all other unnecessary processing. */
19135 			goto done;
19136 		}
19137 	}
19138 
19139 	local_time = (mblk_t *)lbolt;
19140 
19141 	/*
19142 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19143 	 * BSD.  This is more in line with the true intent of Nagle.
19144 	 *
19145 	 * The conditions are:
19146 	 * 1. The amount of unsent data (or amount of data which can be
19147 	 *    sent, whichever is smaller) is less than Nagle limit.
19148 	 * 2. The last sent size is also less than Nagle limit.
19149 	 * 3. There is unack'ed data.
19150 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19151 	 *    Nagle algorithm.  This reduces the probability that urgent
19152 	 *    bytes get "merged" together.
19153 	 * 5. The app has not closed the connection.  This eliminates the
19154 	 *    wait time of the receiving side waiting for the last piece of
19155 	 *    (small) data.
19156 	 *
19157 	 * If all are satisified, exit without sending anything.  Note
19158 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19159 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19160 	 * 4095).
19161 	 */
19162 	if (usable < (int)tcp->tcp_naglim &&
19163 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19164 	    snxt != tcp->tcp_suna &&
19165 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19166 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19167 		goto done;
19168 	}
19169 
19170 	if (tcp->tcp_cork) {
19171 		/*
19172 		 * if the tcp->tcp_cork option is set, then we have to force
19173 		 * TCP not to send partial segment (smaller than MSS bytes).
19174 		 * We are calculating the usable now based on full mss and
19175 		 * will save the rest of remaining data for later.
19176 		 */
19177 		if (usable < mss)
19178 			goto done;
19179 		usable = (usable / mss) * mss;
19180 	}
19181 
19182 	/* Update the latest receive window size in TCP header. */
19183 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19184 	    tcp->tcp_tcph->th_win);
19185 
19186 	/*
19187 	 * Determine if it's worthwhile to attempt MDT, based on:
19188 	 *
19189 	 * 1. Simple TCP/IP{v4,v6} (no options).
19190 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19191 	 * 3. If the TCP connection is in ESTABLISHED state.
19192 	 * 4. The TCP is not detached.
19193 	 *
19194 	 * If any of the above conditions have changed during the
19195 	 * connection, stop using MDT and restore the stream head
19196 	 * parameters accordingly.
19197 	 */
19198 	if (tcp->tcp_mdt &&
19199 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19200 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19201 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19202 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19203 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19204 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
19205 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19206 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
19207 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19208 		tcp->tcp_mdt = B_FALSE;
19209 
19210 		/* Anything other than detached is considered pathological */
19211 		if (!TCP_IS_DETACHED(tcp)) {
19212 			TCP_STAT(tcp_mdt_conn_halted1);
19213 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19214 		}
19215 	}
19216 
19217 	/* Use MDT if sendable amount is greater than the threshold */
19218 	if (tcp->tcp_mdt &&
19219 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19220 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19221 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19222 	    (tcp->tcp_valid_bits == 0 ||
19223 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19224 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19225 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19226 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19227 		    local_time, mdt_thres);
19228 	} else {
19229 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19230 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19231 		    local_time, INT_MAX);
19232 	}
19233 
19234 	/* Pretend that all we were trying to send really got sent */
19235 	if (rc < 0 && tail_unsent < 0) {
19236 		do {
19237 			xmit_tail = xmit_tail->b_cont;
19238 			xmit_tail->b_prev = local_time;
19239 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19240 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19241 			tail_unsent += (int)(xmit_tail->b_wptr -
19242 			    xmit_tail->b_rptr);
19243 		} while (tail_unsent < 0);
19244 	}
19245 done:;
19246 	tcp->tcp_xmit_tail = xmit_tail;
19247 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19248 	len = tcp->tcp_snxt - snxt;
19249 	if (len) {
19250 		/*
19251 		 * If new data was sent, need to update the notsack
19252 		 * list, which is, afterall, data blocks that have
19253 		 * not been sack'ed by the receiver.  New data is
19254 		 * not sack'ed.
19255 		 */
19256 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19257 			/* len is a negative value. */
19258 			tcp->tcp_pipe -= len;
19259 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19260 			    tcp->tcp_snxt, snxt,
19261 			    &(tcp->tcp_num_notsack_blk),
19262 			    &(tcp->tcp_cnt_notsack_list));
19263 		}
19264 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19265 		tcp->tcp_rack = tcp->tcp_rnxt;
19266 		tcp->tcp_rack_cnt = 0;
19267 		if ((snxt + len) == tcp->tcp_suna) {
19268 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19269 		}
19270 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19271 		/*
19272 		 * Didn't send anything. Make sure the timer is running
19273 		 * so that we will probe a zero window.
19274 		 */
19275 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19276 	}
19277 	/* Note that len is the amount we just sent but with a negative sign */
19278 	tcp->tcp_unsent += len;
19279 	if (tcp->tcp_flow_stopped) {
19280 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19281 			tcp_clrqfull(tcp);
19282 		}
19283 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19284 		tcp_setqfull(tcp);
19285 	}
19286 }
19287 
19288 /*
19289  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19290  * outgoing TCP header with the template header, as well as other
19291  * options such as time-stamp, ECN and/or SACK.
19292  */
19293 static void
19294 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19295 {
19296 	tcph_t *tcp_tmpl, *tcp_h;
19297 	uint32_t *dst, *src;
19298 	int hdrlen;
19299 
19300 	ASSERT(OK_32PTR(rptr));
19301 
19302 	/* Template header */
19303 	tcp_tmpl = tcp->tcp_tcph;
19304 
19305 	/* Header of outgoing packet */
19306 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19307 
19308 	/* dst and src are opaque 32-bit fields, used for copying */
19309 	dst = (uint32_t *)rptr;
19310 	src = (uint32_t *)tcp->tcp_iphc;
19311 	hdrlen = tcp->tcp_hdr_len;
19312 
19313 	/* Fill time-stamp option if needed */
19314 	if (tcp->tcp_snd_ts_ok) {
19315 		U32_TO_BE32((uint32_t)now,
19316 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19317 		U32_TO_BE32(tcp->tcp_ts_recent,
19318 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19319 	} else {
19320 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19321 	}
19322 
19323 	/*
19324 	 * Copy the template header; is this really more efficient than
19325 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19326 	 * but perhaps not for other scenarios.
19327 	 */
19328 	dst[0] = src[0];
19329 	dst[1] = src[1];
19330 	dst[2] = src[2];
19331 	dst[3] = src[3];
19332 	dst[4] = src[4];
19333 	dst[5] = src[5];
19334 	dst[6] = src[6];
19335 	dst[7] = src[7];
19336 	dst[8] = src[8];
19337 	dst[9] = src[9];
19338 	if (hdrlen -= 40) {
19339 		hdrlen >>= 2;
19340 		dst += 10;
19341 		src += 10;
19342 		do {
19343 			*dst++ = *src++;
19344 		} while (--hdrlen);
19345 	}
19346 
19347 	/*
19348 	 * Set the ECN info in the TCP header if it is not a zero
19349 	 * window probe.  Zero window probe is only sent in
19350 	 * tcp_wput_data() and tcp_timer().
19351 	 */
19352 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19353 		SET_ECT(tcp, rptr);
19354 
19355 		if (tcp->tcp_ecn_echo_on)
19356 			tcp_h->th_flags[0] |= TH_ECE;
19357 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19358 			tcp_h->th_flags[0] |= TH_CWR;
19359 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19360 		}
19361 	}
19362 
19363 	/* Fill in SACK options */
19364 	if (num_sack_blk > 0) {
19365 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19366 		sack_blk_t *tmp;
19367 		int32_t	i;
19368 
19369 		wptr[0] = TCPOPT_NOP;
19370 		wptr[1] = TCPOPT_NOP;
19371 		wptr[2] = TCPOPT_SACK;
19372 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19373 		    sizeof (sack_blk_t);
19374 		wptr += TCPOPT_REAL_SACK_LEN;
19375 
19376 		tmp = tcp->tcp_sack_list;
19377 		for (i = 0; i < num_sack_blk; i++) {
19378 			U32_TO_BE32(tmp[i].begin, wptr);
19379 			wptr += sizeof (tcp_seq);
19380 			U32_TO_BE32(tmp[i].end, wptr);
19381 			wptr += sizeof (tcp_seq);
19382 		}
19383 		tcp_h->th_offset_and_rsrvd[0] +=
19384 		    ((num_sack_blk * 2 + 1) << 4);
19385 	}
19386 }
19387 
19388 /*
19389  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19390  * the destination address and SAP attribute, and if necessary, the
19391  * hardware checksum offload attribute to a Multidata message.
19392  */
19393 static int
19394 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19395     const uint32_t start, const uint32_t stuff, const uint32_t end,
19396     const uint32_t flags)
19397 {
19398 	/* Add global destination address & SAP attribute */
19399 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19400 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19401 		    "destination address+SAP\n"));
19402 
19403 		if (dlmp != NULL)
19404 			TCP_STAT(tcp_mdt_allocfail);
19405 		return (-1);
19406 	}
19407 
19408 	/* Add global hwcksum attribute */
19409 	if (hwcksum &&
19410 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19411 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19412 		    "checksum attribute\n"));
19413 
19414 		TCP_STAT(tcp_mdt_allocfail);
19415 		return (-1);
19416 	}
19417 
19418 	return (0);
19419 }
19420 
19421 /*
19422  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19423  * scheme, and returns one the following:
19424  *
19425  * -1 = failed allocation.
19426  *  0 = success; burst count reached, or usable send window is too small,
19427  *      and that we'd rather wait until later before sending again.
19428  */
19429 static int
19430 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19431     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19432     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19433     const int mdt_thres)
19434 {
19435 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19436 	multidata_t	*mmd;
19437 	uint_t		obsegs, obbytes, hdr_frag_sz;
19438 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19439 	int		num_burst_seg, max_pld;
19440 	pdesc_t		*pkt;
19441 	tcp_pdescinfo_t	tcp_pkt_info;
19442 	pdescinfo_t	*pkt_info;
19443 	int		pbuf_idx, pbuf_idx_nxt;
19444 	int		seg_len, len, spill, af;
19445 	boolean_t	add_buffer, zcopy, clusterwide;
19446 	boolean_t	rconfirm = B_FALSE;
19447 	boolean_t	done = B_FALSE;
19448 	uint32_t	cksum;
19449 	uint32_t	hwcksum_flags;
19450 	ire_t		*ire;
19451 	ill_t		*ill;
19452 	ipha_t		*ipha;
19453 	ip6_t		*ip6h;
19454 	ipaddr_t	src, dst;
19455 	ill_zerocopy_capab_t *zc_cap = NULL;
19456 	uint16_t	*up;
19457 	int		err;
19458 
19459 #ifdef	_BIG_ENDIAN
19460 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19461 #else
19462 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19463 #endif
19464 
19465 #define	TCP_CSUM_OFFSET	16
19466 #define	TCP_CSUM_SIZE	2
19467 
19468 #define	PREP_NEW_MULTIDATA() {			\
19469 	mmd = NULL;				\
19470 	md_mp = md_hbuf = NULL;			\
19471 	cur_hdr_off = 0;			\
19472 	max_pld = tcp->tcp_mdt_max_pld;		\
19473 	pbuf_idx = pbuf_idx_nxt = -1;		\
19474 	add_buffer = B_TRUE;			\
19475 	zcopy = B_FALSE;			\
19476 }
19477 
19478 #define	PREP_NEW_PBUF() {			\
19479 	md_pbuf = md_pbuf_nxt = NULL;		\
19480 	pbuf_idx = pbuf_idx_nxt = -1;		\
19481 	cur_pld_off = 0;			\
19482 	first_snxt = *snxt;			\
19483 	ASSERT(*tail_unsent > 0);		\
19484 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19485 }
19486 
19487 	ASSERT(mdt_thres >= mss);
19488 	ASSERT(*usable > 0 && *usable > mdt_thres);
19489 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19490 	ASSERT(!TCP_IS_DETACHED(tcp));
19491 	ASSERT(tcp->tcp_valid_bits == 0 ||
19492 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19493 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19494 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19495 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19496 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19497 	ASSERT(tcp->tcp_connp != NULL);
19498 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
19499 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
19500 
19501 	/*
19502 	 * Note that tcp will only declare at most 2 payload spans per
19503 	 * packet, which is much lower than the maximum allowable number
19504 	 * of packet spans per Multidata.  For this reason, we use the
19505 	 * privately declared and smaller descriptor info structure, in
19506 	 * order to save some stack space.
19507 	 */
19508 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19509 
19510 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19511 	if (af == AF_INET) {
19512 		dst = tcp->tcp_ipha->ipha_dst;
19513 		src = tcp->tcp_ipha->ipha_src;
19514 		ASSERT(!CLASSD(dst));
19515 	}
19516 	ASSERT(af == AF_INET ||
19517 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19518 
19519 	obsegs = obbytes = 0;
19520 	num_burst_seg = tcp->tcp_snd_burst;
19521 	md_mp_head = NULL;
19522 	PREP_NEW_MULTIDATA();
19523 
19524 	/*
19525 	 * Before we go on further, make sure there is an IRE that we can
19526 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19527 	 * in proceeding any further, and we should just hand everything
19528 	 * off to the legacy path.
19529 	 */
19530 	mutex_enter(&tcp->tcp_connp->conn_lock);
19531 	ire = tcp->tcp_connp->conn_ire_cache;
19532 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
19533 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19534 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19535 	    &tcp->tcp_ip6h->ip6_dst))) &&
19536 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19537 		IRE_REFHOLD(ire);
19538 		mutex_exit(&tcp->tcp_connp->conn_lock);
19539 	} else {
19540 		boolean_t cached = B_FALSE;
19541 
19542 		/* force a recheck later on */
19543 		tcp->tcp_ire_ill_check_done = B_FALSE;
19544 
19545 		TCP_DBGSTAT(tcp_ire_null1);
19546 		tcp->tcp_connp->conn_ire_cache = NULL;
19547 		mutex_exit(&tcp->tcp_connp->conn_lock);
19548 
19549 		/* Release the old ire */
19550 		if (ire != NULL)
19551 			IRE_REFRELE_NOTR(ire);
19552 
19553 		ire = (af == AF_INET) ?
19554 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
19555 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19556 		    tcp->tcp_connp->conn_zoneid);
19557 
19558 		if (ire == NULL) {
19559 			TCP_STAT(tcp_ire_null);
19560 			goto legacy_send_no_md;
19561 		}
19562 
19563 		IRE_REFHOLD_NOTR(ire);
19564 		/*
19565 		 * Since we are inside the squeue, there cannot be another
19566 		 * thread in TCP trying to set the conn_ire_cache now. The
19567 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19568 		 * unplumb thread has not yet started cleaning up the conns.
19569 		 * Hence we don't need to grab the conn lock.
19570 		 */
19571 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
19572 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19573 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19574 				tcp->tcp_connp->conn_ire_cache = ire;
19575 				cached = B_TRUE;
19576 			}
19577 			rw_exit(&ire->ire_bucket->irb_lock);
19578 		}
19579 
19580 		/*
19581 		 * We can continue to use the ire but since it was not
19582 		 * cached, we should drop the extra reference.
19583 		 */
19584 		if (!cached)
19585 			IRE_REFRELE_NOTR(ire);
19586 	}
19587 
19588 	ASSERT(ire != NULL);
19589 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19590 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19591 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19592 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19593 	/*
19594 	 * If we do support loopback for MDT (which requires modifications
19595 	 * to the receiving paths), the following assertions should go away,
19596 	 * and we would be sending the Multidata to loopback conn later on.
19597 	 */
19598 	ASSERT(!IRE_IS_LOCAL(ire));
19599 	ASSERT(ire->ire_stq != NULL);
19600 
19601 	ill = ire_to_ill(ire);
19602 	ASSERT(ill != NULL);
19603 	ASSERT((ill->ill_capabilities & ILL_CAPAB_MDT) == 0 ||
19604 	    ill->ill_mdt_capab != NULL);
19605 
19606 	if (!tcp->tcp_ire_ill_check_done) {
19607 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19608 		tcp->tcp_ire_ill_check_done = B_TRUE;
19609 	}
19610 
19611 	/*
19612 	 * If the underlying interface conditions have changed, or if the
19613 	 * new interface does not support MDT, go back to legacy path.
19614 	 */
19615 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19616 		/* don't go through this path anymore for this connection */
19617 		TCP_STAT(tcp_mdt_conn_halted2);
19618 		tcp->tcp_mdt = B_FALSE;
19619 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19620 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
19621 		/* IRE will be released prior to returning */
19622 		goto legacy_send_no_md;
19623 	}
19624 
19625 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19626 		zc_cap = ill->ill_zerocopy_capab;
19627 
19628 	/* go to legacy path if interface doesn't support zerocopy */
19629 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19630 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19631 		/* IRE will be released prior to returning */
19632 		goto legacy_send_no_md;
19633 	}
19634 
19635 	/* does the interface support hardware checksum offload? */
19636 	hwcksum_flags = 0;
19637 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&
19638 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19639 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM)) &&
19640 	    dohwcksum) {
19641 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19642 		    HCKSUM_IPHDRCKSUM)
19643 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19644 
19645 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19646 		    HCKSUM_INET_FULL_V4)
19647 			hwcksum_flags |= HCK_FULLCKSUM;
19648 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19649 		    HCKSUM_INET_PARTIAL)
19650 			hwcksum_flags |= HCK_PARTIALCKSUM;
19651 	}
19652 
19653 	/*
19654 	 * Each header fragment consists of the leading extra space,
19655 	 * followed by the TCP/IP header, and the trailing extra space.
19656 	 * We make sure that each header fragment begins on a 32-bit
19657 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19658 	 * aligned in tcp_mdt_update).
19659 	 */
19660 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19661 	    tcp->tcp_mdt_hdr_tail), 4);
19662 
19663 	/* are we starting from the beginning of data block? */
19664 	if (*tail_unsent == 0) {
19665 		*xmit_tail = (*xmit_tail)->b_cont;
19666 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19667 		*tail_unsent = (int)MBLKL(*xmit_tail);
19668 	}
19669 
19670 	/*
19671 	 * Here we create one or more Multidata messages, each made up of
19672 	 * one header buffer and up to N payload buffers.  This entire
19673 	 * operation is done within two loops:
19674 	 *
19675 	 * The outer loop mostly deals with creating the Multidata message,
19676 	 * as well as the header buffer that gets added to it.  It also
19677 	 * links the Multidata messages together such that all of them can
19678 	 * be sent down to the lower layer in a single putnext call; this
19679 	 * linking behavior depends on the tcp_mdt_chain tunable.
19680 	 *
19681 	 * The inner loop takes an existing Multidata message, and adds
19682 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19683 	 * packetizes those buffers by filling up the corresponding header
19684 	 * buffer fragments with the proper IP and TCP headers, and by
19685 	 * describing the layout of each packet in the packet descriptors
19686 	 * that get added to the Multidata.
19687 	 */
19688 	do {
19689 		/*
19690 		 * If usable send window is too small, or data blocks in
19691 		 * transmit list are smaller than our threshold (i.e. app
19692 		 * performs large writes followed by small ones), we hand
19693 		 * off the control over to the legacy path.  Note that we'll
19694 		 * get back the control once it encounters a large block.
19695 		 */
19696 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19697 		    (*xmit_tail)->b_cont != NULL &&
19698 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19699 			/* send down what we've got so far */
19700 			if (md_mp_head != NULL) {
19701 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19702 				    obsegs, obbytes, &rconfirm);
19703 			}
19704 			/*
19705 			 * Pass control over to tcp_send(), but tell it to
19706 			 * return to us once a large-size transmission is
19707 			 * possible.
19708 			 */
19709 			TCP_STAT(tcp_mdt_legacy_small);
19710 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19711 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19712 			    tail_unsent, xmit_tail, local_time,
19713 			    mdt_thres)) <= 0) {
19714 				/* burst count reached, or alloc failed */
19715 				IRE_REFRELE(ire);
19716 				return (err);
19717 			}
19718 
19719 			/* tcp_send() may have sent everything, so check */
19720 			if (*usable <= 0) {
19721 				IRE_REFRELE(ire);
19722 				return (0);
19723 			}
19724 
19725 			TCP_STAT(tcp_mdt_legacy_ret);
19726 			/*
19727 			 * We may have delivered the Multidata, so make sure
19728 			 * to re-initialize before the next round.
19729 			 */
19730 			md_mp_head = NULL;
19731 			obsegs = obbytes = 0;
19732 			num_burst_seg = tcp->tcp_snd_burst;
19733 			PREP_NEW_MULTIDATA();
19734 
19735 			/* are we starting from the beginning of data block? */
19736 			if (*tail_unsent == 0) {
19737 				*xmit_tail = (*xmit_tail)->b_cont;
19738 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19739 				    (uintptr_t)INT_MAX);
19740 				*tail_unsent = (int)MBLKL(*xmit_tail);
19741 			}
19742 		}
19743 
19744 		/*
19745 		 * max_pld limits the number of mblks in tcp's transmit
19746 		 * queue that can be added to a Multidata message.  Once
19747 		 * this counter reaches zero, no more additional mblks
19748 		 * can be added to it.  What happens afterwards depends
19749 		 * on whether or not we are set to chain the Multidata
19750 		 * messages.  If we are to link them together, reset
19751 		 * max_pld to its original value (tcp_mdt_max_pld) and
19752 		 * prepare to create a new Multidata message which will
19753 		 * get linked to md_mp_head.  Else, leave it alone and
19754 		 * let the inner loop break on its own.
19755 		 */
19756 		if (tcp_mdt_chain && max_pld == 0)
19757 			PREP_NEW_MULTIDATA();
19758 
19759 		/* adding a payload buffer; re-initialize values */
19760 		if (add_buffer)
19761 			PREP_NEW_PBUF();
19762 
19763 		/*
19764 		 * If we don't have a Multidata, either because we just
19765 		 * (re)entered this outer loop, or after we branched off
19766 		 * to tcp_send above, setup the Multidata and header
19767 		 * buffer to be used.
19768 		 */
19769 		if (md_mp == NULL) {
19770 			int md_hbuflen;
19771 			uint32_t start, stuff;
19772 
19773 			/*
19774 			 * Calculate Multidata header buffer size large enough
19775 			 * to hold all of the headers that can possibly be
19776 			 * sent at this moment.  We'd rather over-estimate
19777 			 * the size than running out of space; this is okay
19778 			 * since this buffer is small anyway.
19779 			 */
19780 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19781 
19782 			/*
19783 			 * Start and stuff offset for partial hardware
19784 			 * checksum offload; these are currently for IPv4.
19785 			 * For full checksum offload, they are set to zero.
19786 			 */
19787 			if (af == AF_INET &&
19788 			    (hwcksum_flags & HCK_PARTIALCKSUM)) {
19789 				start = IP_SIMPLE_HDR_LENGTH;
19790 				stuff = IP_SIMPLE_HDR_LENGTH + TCP_CSUM_OFFSET;
19791 			} else {
19792 				start = stuff = 0;
19793 			}
19794 
19795 			/*
19796 			 * Create the header buffer, Multidata, as well as
19797 			 * any necessary attributes (destination address,
19798 			 * SAP and hardware checksum offload) that should
19799 			 * be associated with the Multidata message.
19800 			 */
19801 			ASSERT(cur_hdr_off == 0);
19802 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19803 			    ((md_hbuf->b_wptr += md_hbuflen),
19804 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19805 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19806 			    /* fastpath mblk */
19807 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19808 			    ire->ire_nce->nce_res_mp,
19809 			    /* hardware checksum enabled (IPv4 only) */
19810 			    (af == AF_INET && hwcksum_flags != 0),
19811 			    /* hardware checksum offsets */
19812 			    start, stuff, 0,
19813 			    /* hardware checksum flag */
19814 			    hwcksum_flags) != 0)) {
19815 legacy_send:
19816 				if (md_mp != NULL) {
19817 					/* Unlink message from the chain */
19818 					if (md_mp_head != NULL) {
19819 						err = (intptr_t)rmvb(md_mp_head,
19820 						    md_mp);
19821 						/*
19822 						 * We can't assert that rmvb
19823 						 * did not return -1, since we
19824 						 * may get here before linkb
19825 						 * happens.  We do, however,
19826 						 * check if we just removed the
19827 						 * only element in the list.
19828 						 */
19829 						if (err == 0)
19830 							md_mp_head = NULL;
19831 					}
19832 					/* md_hbuf gets freed automatically */
19833 					TCP_STAT(tcp_mdt_discarded);
19834 					freeb(md_mp);
19835 				} else {
19836 					/* Either allocb or mmd_alloc failed */
19837 					TCP_STAT(tcp_mdt_allocfail);
19838 					if (md_hbuf != NULL)
19839 						freeb(md_hbuf);
19840 				}
19841 
19842 				/* send down what we've got so far */
19843 				if (md_mp_head != NULL) {
19844 					tcp_multisend_data(tcp, ire, ill,
19845 					    md_mp_head, obsegs, obbytes,
19846 					    &rconfirm);
19847 				}
19848 legacy_send_no_md:
19849 				if (ire != NULL)
19850 					IRE_REFRELE(ire);
19851 				/*
19852 				 * Too bad; let the legacy path handle this.
19853 				 * We specify INT_MAX for the threshold, since
19854 				 * we gave up with the Multidata processings
19855 				 * and let the old path have it all.
19856 				 */
19857 				TCP_STAT(tcp_mdt_legacy_all);
19858 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19859 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19860 				    snxt, tail_unsent, xmit_tail, local_time,
19861 				    INT_MAX));
19862 			}
19863 
19864 			/* link to any existing ones, if applicable */
19865 			TCP_STAT(tcp_mdt_allocd);
19866 			if (md_mp_head == NULL) {
19867 				md_mp_head = md_mp;
19868 			} else if (tcp_mdt_chain) {
19869 				TCP_STAT(tcp_mdt_linked);
19870 				linkb(md_mp_head, md_mp);
19871 			}
19872 		}
19873 
19874 		ASSERT(md_mp_head != NULL);
19875 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19876 		ASSERT(md_mp != NULL && mmd != NULL);
19877 		ASSERT(md_hbuf != NULL);
19878 
19879 		/*
19880 		 * Packetize the transmittable portion of the data block;
19881 		 * each data block is essentially added to the Multidata
19882 		 * as a payload buffer.  We also deal with adding more
19883 		 * than one payload buffers, which happens when the remaining
19884 		 * packetized portion of the current payload buffer is less
19885 		 * than MSS, while the next data block in transmit queue
19886 		 * has enough data to make up for one.  This "spillover"
19887 		 * case essentially creates a split-packet, where portions
19888 		 * of the packet's payload fragments may span across two
19889 		 * virtually discontiguous address blocks.
19890 		 */
19891 		seg_len = mss;
19892 		do {
19893 			len = seg_len;
19894 
19895 			ASSERT(len > 0);
19896 			ASSERT(max_pld >= 0);
19897 			ASSERT(!add_buffer || cur_pld_off == 0);
19898 
19899 			/*
19900 			 * First time around for this payload buffer; note
19901 			 * in the case of a spillover, the following has
19902 			 * been done prior to adding the split-packet
19903 			 * descriptor to Multidata, and we don't want to
19904 			 * repeat the process.
19905 			 */
19906 			if (add_buffer) {
19907 				ASSERT(mmd != NULL);
19908 				ASSERT(md_pbuf == NULL);
19909 				ASSERT(md_pbuf_nxt == NULL);
19910 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19911 
19912 				/*
19913 				 * Have we reached the limit?  We'd get to
19914 				 * this case when we're not chaining the
19915 				 * Multidata messages together, and since
19916 				 * we're done, terminate this loop.
19917 				 */
19918 				if (max_pld == 0)
19919 					break; /* done */
19920 
19921 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19922 					TCP_STAT(tcp_mdt_allocfail);
19923 					goto legacy_send; /* out_of_mem */
19924 				}
19925 
19926 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19927 				    zc_cap != NULL) {
19928 					if (!ip_md_zcopy_attr(mmd, NULL,
19929 					    zc_cap->ill_zerocopy_flags)) {
19930 						freeb(md_pbuf);
19931 						TCP_STAT(tcp_mdt_allocfail);
19932 						/* out_of_mem */
19933 						goto legacy_send;
19934 					}
19935 					zcopy = B_TRUE;
19936 				}
19937 
19938 				md_pbuf->b_rptr += base_pld_off;
19939 
19940 				/*
19941 				 * Add a payload buffer to the Multidata; this
19942 				 * operation must not fail, or otherwise our
19943 				 * logic in this routine is broken.  There
19944 				 * is no memory allocation done by the
19945 				 * routine, so any returned failure simply
19946 				 * tells us that we've done something wrong.
19947 				 *
19948 				 * A failure tells us that either we're adding
19949 				 * the same payload buffer more than once, or
19950 				 * we're trying to add more buffers than
19951 				 * allowed (max_pld calculation is wrong).
19952 				 * None of the above cases should happen, and
19953 				 * we panic because either there's horrible
19954 				 * heap corruption, and/or programming mistake.
19955 				 */
19956 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19957 				if (pbuf_idx < 0) {
19958 					cmn_err(CE_PANIC, "tcp_multisend: "
19959 					    "payload buffer logic error "
19960 					    "detected for tcp %p mmd %p "
19961 					    "pbuf %p (%d)\n",
19962 					    (void *)tcp, (void *)mmd,
19963 					    (void *)md_pbuf, pbuf_idx);
19964 				}
19965 
19966 				ASSERT(max_pld > 0);
19967 				--max_pld;
19968 				add_buffer = B_FALSE;
19969 			}
19970 
19971 			ASSERT(md_mp_head != NULL);
19972 			ASSERT(md_pbuf != NULL);
19973 			ASSERT(md_pbuf_nxt == NULL);
19974 			ASSERT(pbuf_idx != -1);
19975 			ASSERT(pbuf_idx_nxt == -1);
19976 			ASSERT(*usable > 0);
19977 
19978 			/*
19979 			 * We spillover to the next payload buffer only
19980 			 * if all of the following is true:
19981 			 *
19982 			 *   1. There is not enough data on the current
19983 			 *	payload buffer to make up `len',
19984 			 *   2. We are allowed to send `len',
19985 			 *   3. The next payload buffer length is large
19986 			 *	enough to accomodate `spill'.
19987 			 */
19988 			if ((spill = len - *tail_unsent) > 0 &&
19989 			    *usable >= len &&
19990 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19991 			    max_pld > 0) {
19992 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19993 				if (md_pbuf_nxt == NULL) {
19994 					TCP_STAT(tcp_mdt_allocfail);
19995 					goto legacy_send; /* out_of_mem */
19996 				}
19997 
19998 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19999 				    zc_cap != NULL) {
20000 					if (!ip_md_zcopy_attr(mmd, NULL,
20001 					    zc_cap->ill_zerocopy_flags)) {
20002 						freeb(md_pbuf_nxt);
20003 						TCP_STAT(tcp_mdt_allocfail);
20004 						/* out_of_mem */
20005 						goto legacy_send;
20006 					}
20007 					zcopy = B_TRUE;
20008 				}
20009 
20010 				/*
20011 				 * See comments above on the first call to
20012 				 * mmd_addpldbuf for explanation on the panic.
20013 				 */
20014 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20015 				if (pbuf_idx_nxt < 0) {
20016 					panic("tcp_multisend: "
20017 					    "next payload buffer logic error "
20018 					    "detected for tcp %p mmd %p "
20019 					    "pbuf %p (%d)\n",
20020 					    (void *)tcp, (void *)mmd,
20021 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20022 				}
20023 
20024 				ASSERT(max_pld > 0);
20025 				--max_pld;
20026 			} else if (spill > 0) {
20027 				/*
20028 				 * If there's a spillover, but the following
20029 				 * xmit_tail couldn't give us enough octets
20030 				 * to reach "len", then stop the current
20031 				 * Multidata creation and let the legacy
20032 				 * tcp_send() path take over.  We don't want
20033 				 * to send the tiny segment as part of this
20034 				 * Multidata for performance reasons; instead,
20035 				 * we let the legacy path deal with grouping
20036 				 * it with the subsequent small mblks.
20037 				 */
20038 				if (*usable >= len &&
20039 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20040 					max_pld = 0;
20041 					break;	/* done */
20042 				}
20043 
20044 				/*
20045 				 * We can't spillover, and we are near
20046 				 * the end of the current payload buffer,
20047 				 * so send what's left.
20048 				 */
20049 				ASSERT(*tail_unsent > 0);
20050 				len = *tail_unsent;
20051 			}
20052 
20053 			/* tail_unsent is negated if there is a spillover */
20054 			*tail_unsent -= len;
20055 			*usable -= len;
20056 			ASSERT(*usable >= 0);
20057 
20058 			if (*usable < mss)
20059 				seg_len = *usable;
20060 			/*
20061 			 * Sender SWS avoidance; see comments in tcp_send();
20062 			 * everything else is the same, except that we only
20063 			 * do this here if there is no more data to be sent
20064 			 * following the current xmit_tail.  We don't check
20065 			 * for 1-byte urgent data because we shouldn't get
20066 			 * here if TCP_URG_VALID is set.
20067 			 */
20068 			if (*usable > 0 && *usable < mss &&
20069 			    ((md_pbuf_nxt == NULL &&
20070 			    (*xmit_tail)->b_cont == NULL) ||
20071 			    (md_pbuf_nxt != NULL &&
20072 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20073 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20074 			    (tcp->tcp_unsent -
20075 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20076 			    !tcp->tcp_zero_win_probe) {
20077 				if ((*snxt + len) == tcp->tcp_snxt &&
20078 				    (*snxt + len) == tcp->tcp_suna) {
20079 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20080 				}
20081 				done = B_TRUE;
20082 			}
20083 
20084 			/*
20085 			 * Prime pump for IP's checksumming on our behalf;
20086 			 * include the adjustment for a source route if any.
20087 			 * Do this only for software/partial hardware checksum
20088 			 * offload, as this field gets zeroed out later for
20089 			 * the full hardware checksum offload case.
20090 			 */
20091 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20092 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20093 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20094 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20095 			}
20096 
20097 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20098 			*snxt += len;
20099 
20100 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20101 			/*
20102 			 * We set the PUSH bit only if TCP has no more buffered
20103 			 * data to be transmitted (or if sender SWS avoidance
20104 			 * takes place), as opposed to setting it for every
20105 			 * last packet in the burst.
20106 			 */
20107 			if (done ||
20108 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20109 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20110 
20111 			/*
20112 			 * Set FIN bit if this is our last segment; snxt
20113 			 * already includes its length, and it will not
20114 			 * be adjusted after this point.
20115 			 */
20116 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20117 			    *snxt == tcp->tcp_fss) {
20118 				if (!tcp->tcp_fin_acked) {
20119 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20120 					BUMP_MIB(&tcp_mib, tcpOutControl);
20121 				}
20122 				if (!tcp->tcp_fin_sent) {
20123 					tcp->tcp_fin_sent = B_TRUE;
20124 					/*
20125 					 * tcp state must be ESTABLISHED
20126 					 * in order for us to get here in
20127 					 * the first place.
20128 					 */
20129 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20130 
20131 					/*
20132 					 * Upon returning from this routine,
20133 					 * tcp_wput_data() will set tcp_snxt
20134 					 * to be equal to snxt + tcp_fin_sent.
20135 					 * This is essentially the same as
20136 					 * setting it to tcp_fss + 1.
20137 					 */
20138 				}
20139 			}
20140 
20141 			tcp->tcp_last_sent_len = (ushort_t)len;
20142 
20143 			len += tcp_hdr_len;
20144 			if (tcp->tcp_ipversion == IPV4_VERSION)
20145 				tcp->tcp_ipha->ipha_length = htons(len);
20146 			else
20147 				tcp->tcp_ip6h->ip6_plen = htons(len -
20148 				    ((char *)&tcp->tcp_ip6h[1] -
20149 				    tcp->tcp_iphc));
20150 
20151 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20152 
20153 			/* setup header fragment */
20154 			PDESC_HDR_ADD(pkt_info,
20155 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20156 			    tcp->tcp_mdt_hdr_head,		/* head room */
20157 			    tcp_hdr_len,			/* len */
20158 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20159 
20160 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20161 			    hdr_frag_sz);
20162 			ASSERT(MBLKIN(md_hbuf,
20163 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20164 			    PDESC_HDRSIZE(pkt_info)));
20165 
20166 			/* setup first payload fragment */
20167 			PDESC_PLD_INIT(pkt_info);
20168 			PDESC_PLD_SPAN_ADD(pkt_info,
20169 			    pbuf_idx,				/* index */
20170 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20171 			    tcp->tcp_last_sent_len);		/* len */
20172 
20173 			/* create a split-packet in case of a spillover */
20174 			if (md_pbuf_nxt != NULL) {
20175 				ASSERT(spill > 0);
20176 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20177 				ASSERT(!add_buffer);
20178 
20179 				md_pbuf = md_pbuf_nxt;
20180 				md_pbuf_nxt = NULL;
20181 				pbuf_idx = pbuf_idx_nxt;
20182 				pbuf_idx_nxt = -1;
20183 				cur_pld_off = spill;
20184 
20185 				/* trim out first payload fragment */
20186 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20187 
20188 				/* setup second payload fragment */
20189 				PDESC_PLD_SPAN_ADD(pkt_info,
20190 				    pbuf_idx,			/* index */
20191 				    md_pbuf->b_rptr,		/* start */
20192 				    spill);			/* len */
20193 
20194 				if ((*xmit_tail)->b_next == NULL) {
20195 					/*
20196 					 * Store the lbolt used for RTT
20197 					 * estimation. We can only record one
20198 					 * timestamp per mblk so we do it when
20199 					 * we reach the end of the payload
20200 					 * buffer.  Also we only take a new
20201 					 * timestamp sample when the previous
20202 					 * timed data from the same mblk has
20203 					 * been ack'ed.
20204 					 */
20205 					(*xmit_tail)->b_prev = local_time;
20206 					(*xmit_tail)->b_next =
20207 					    (mblk_t *)(uintptr_t)first_snxt;
20208 				}
20209 
20210 				first_snxt = *snxt - spill;
20211 
20212 				/*
20213 				 * Advance xmit_tail; usable could be 0 by
20214 				 * the time we got here, but we made sure
20215 				 * above that we would only spillover to
20216 				 * the next data block if usable includes
20217 				 * the spilled-over amount prior to the
20218 				 * subtraction.  Therefore, we are sure
20219 				 * that xmit_tail->b_cont can't be NULL.
20220 				 */
20221 				ASSERT((*xmit_tail)->b_cont != NULL);
20222 				*xmit_tail = (*xmit_tail)->b_cont;
20223 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20224 				    (uintptr_t)INT_MAX);
20225 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20226 			} else {
20227 				cur_pld_off += tcp->tcp_last_sent_len;
20228 			}
20229 
20230 			/*
20231 			 * Fill in the header using the template header, and
20232 			 * add options such as time-stamp, ECN and/or SACK,
20233 			 * as needed.
20234 			 */
20235 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20236 			    (clock_t)local_time, num_sack_blk);
20237 
20238 			/* take care of some IP header businesses */
20239 			if (af == AF_INET) {
20240 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20241 
20242 				ASSERT(OK_32PTR((uchar_t *)ipha));
20243 				ASSERT(PDESC_HDRL(pkt_info) >=
20244 				    IP_SIMPLE_HDR_LENGTH);
20245 				ASSERT(ipha->ipha_version_and_hdr_length ==
20246 				    IP_SIMPLE_HDR_VERSION);
20247 
20248 				/*
20249 				 * Assign ident value for current packet; see
20250 				 * related comments in ip_wput_ire() about the
20251 				 * contract private interface with clustering
20252 				 * group.
20253 				 */
20254 				clusterwide = B_FALSE;
20255 				if (cl_inet_ipident != NULL) {
20256 					ASSERT(cl_inet_isclusterwide != NULL);
20257 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20258 					    AF_INET,
20259 					    (uint8_t *)(uintptr_t)src)) {
20260 						ipha->ipha_ident =
20261 						    (*cl_inet_ipident)
20262 						    (IPPROTO_IP, AF_INET,
20263 						    (uint8_t *)(uintptr_t)src,
20264 						    (uint8_t *)(uintptr_t)dst);
20265 						clusterwide = B_TRUE;
20266 					}
20267 				}
20268 
20269 				if (!clusterwide) {
20270 					ipha->ipha_ident = (uint16_t)
20271 					    atomic_add_32_nv(
20272 						&ire->ire_ident, 1);
20273 				}
20274 #ifndef _BIG_ENDIAN
20275 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20276 				    (ipha->ipha_ident >> 8);
20277 #endif
20278 			} else {
20279 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20280 
20281 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20282 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20283 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20284 				ASSERT(PDESC_HDRL(pkt_info) >=
20285 				    (IPV6_HDR_LEN + TCP_CSUM_OFFSET +
20286 				    TCP_CSUM_SIZE));
20287 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20288 
20289 				if (tcp->tcp_ip_forward_progress) {
20290 					rconfirm = B_TRUE;
20291 					tcp->tcp_ip_forward_progress = B_FALSE;
20292 				}
20293 			}
20294 
20295 			/* at least one payload span, and at most two */
20296 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20297 
20298 			/* add the packet descriptor to Multidata */
20299 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20300 			    KM_NOSLEEP)) == NULL) {
20301 				/*
20302 				 * Any failure other than ENOMEM indicates
20303 				 * that we have passed in invalid pkt_info
20304 				 * or parameters to mmd_addpdesc, which must
20305 				 * not happen.
20306 				 *
20307 				 * EINVAL is a result of failure on boundary
20308 				 * checks against the pkt_info contents.  It
20309 				 * should not happen, and we panic because
20310 				 * either there's horrible heap corruption,
20311 				 * and/or programming mistake.
20312 				 */
20313 				if (err != ENOMEM) {
20314 					cmn_err(CE_PANIC, "tcp_multisend: "
20315 					    "pdesc logic error detected for "
20316 					    "tcp %p mmd %p pinfo %p (%d)\n",
20317 					    (void *)tcp, (void *)mmd,
20318 					    (void *)pkt_info, err);
20319 				}
20320 				TCP_STAT(tcp_mdt_addpdescfail);
20321 				goto legacy_send; /* out_of_mem */
20322 			}
20323 			ASSERT(pkt != NULL);
20324 
20325 			/* calculate IP header and TCP checksums */
20326 			if (af == AF_INET) {
20327 				/* calculate pseudo-header checksum */
20328 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20329 				    (src >> 16) + (src & 0xFFFF);
20330 
20331 				/* offset for TCP header checksum */
20332 				up = IPH_TCPH_CHECKSUMP(ipha,
20333 				    IP_SIMPLE_HDR_LENGTH);
20334 
20335 				if (hwcksum_flags & HCK_FULLCKSUM) {
20336 					/*
20337 					 * Hardware calculates pseudo-header,
20338 					 * header and payload checksums, so
20339 					 * zero out this field.
20340 					 */
20341 					*up = 0;
20342 				} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20343 					uint32_t sum;
20344 
20345 					/* pseudo-header checksumming */
20346 					sum = *up + cksum + IP_TCP_CSUM_COMP;
20347 					sum = (sum & 0xFFFF) + (sum >> 16);
20348 					*up = (sum & 0xFFFF) + (sum >> 16);
20349 				} else {
20350 					/* software checksumming */
20351 					TCP_STAT(tcp_out_sw_cksum);
20352 					*up = IP_MD_CSUM(pkt,
20353 					    IP_SIMPLE_HDR_LENGTH,
20354 					    cksum + IP_TCP_CSUM_COMP);
20355 				}
20356 
20357 				ipha->ipha_fragment_offset_and_flags |=
20358 				    (uint32_t)htons(ire->ire_frag_flag);
20359 
20360 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20361 					ipha->ipha_hdr_checksum = 0;
20362 				} else {
20363 					IP_HDR_CKSUM(ipha, cksum,
20364 					    ((uint32_t *)ipha)[0],
20365 					    ((uint16_t *)ipha)[4]);
20366 				}
20367 			} else {
20368 				up = (uint16_t *)(((uchar_t *)ip6h) +
20369 				    IPV6_HDR_LEN + TCP_CSUM_OFFSET);
20370 
20371 				/*
20372 				 * Software checksumming (hardware checksum
20373 				 * offload for IPv6 will hopefully be
20374 				 * implemented one day).
20375 				 */
20376 				TCP_STAT(tcp_out_sw_cksum);
20377 				*up = IP_MD_CSUM(pkt,
20378 				    IPV6_HDR_LEN - 2 * sizeof (in6_addr_t),
20379 				    htons(IPPROTO_TCP));
20380 			}
20381 
20382 			/* advance header offset */
20383 			cur_hdr_off += hdr_frag_sz;
20384 
20385 			obbytes += tcp->tcp_last_sent_len;
20386 			++obsegs;
20387 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20388 		    *tail_unsent > 0);
20389 
20390 		if ((*xmit_tail)->b_next == NULL) {
20391 			/*
20392 			 * Store the lbolt used for RTT estimation. We can only
20393 			 * record one timestamp per mblk so we do it when we
20394 			 * reach the end of the payload buffer. Also we only
20395 			 * take a new timestamp sample when the previous timed
20396 			 * data from the same mblk has been ack'ed.
20397 			 */
20398 			(*xmit_tail)->b_prev = local_time;
20399 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20400 		}
20401 
20402 		ASSERT(*tail_unsent >= 0);
20403 		if (*tail_unsent > 0) {
20404 			/*
20405 			 * We got here because we broke out of the above
20406 			 * loop due to of one of the following cases:
20407 			 *
20408 			 *   1. len < adjusted MSS (i.e. small),
20409 			 *   2. Sender SWS avoidance,
20410 			 *   3. max_pld is zero.
20411 			 *
20412 			 * We are done for this Multidata, so trim our
20413 			 * last payload buffer (if any) accordingly.
20414 			 */
20415 			if (md_pbuf != NULL)
20416 				md_pbuf->b_wptr -= *tail_unsent;
20417 		} else if (*usable > 0) {
20418 			*xmit_tail = (*xmit_tail)->b_cont;
20419 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20420 			    (uintptr_t)INT_MAX);
20421 			*tail_unsent = (int)MBLKL(*xmit_tail);
20422 			add_buffer = B_TRUE;
20423 		}
20424 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20425 	    (tcp_mdt_chain || max_pld > 0));
20426 
20427 	/* send everything down */
20428 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20429 	    &rconfirm);
20430 
20431 #undef PREP_NEW_MULTIDATA
20432 #undef PREP_NEW_PBUF
20433 #undef IPVER
20434 #undef TCP_CSUM_OFFSET
20435 #undef TCP_CSUM_SIZE
20436 
20437 	IRE_REFRELE(ire);
20438 	return (0);
20439 }
20440 
20441 /*
20442  * A wrapper function for sending one or more Multidata messages down to
20443  * the module below ip; this routine does not release the reference of the
20444  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20445  */
20446 static void
20447 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20448     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20449 {
20450 	uint64_t delta;
20451 	nce_t *nce;
20452 
20453 	ASSERT(ire != NULL && ill != NULL);
20454 	ASSERT(ire->ire_stq != NULL);
20455 	ASSERT(md_mp_head != NULL);
20456 	ASSERT(rconfirm != NULL);
20457 
20458 	/* adjust MIBs and IRE timestamp */
20459 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20460 	tcp->tcp_obsegs += obsegs;
20461 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20462 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20463 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20464 
20465 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20466 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20467 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20468 	} else {
20469 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20470 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20471 	}
20472 
20473 	ire->ire_ob_pkt_count += obsegs;
20474 	if (ire->ire_ipif != NULL)
20475 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20476 	ire->ire_last_used_time = lbolt;
20477 
20478 	/* send it down */
20479 	putnext(ire->ire_stq, md_mp_head);
20480 
20481 	/* we're done for TCP/IPv4 */
20482 	if (tcp->tcp_ipversion == IPV4_VERSION)
20483 		return;
20484 
20485 	nce = ire->ire_nce;
20486 
20487 	ASSERT(nce != NULL);
20488 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20489 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20490 
20491 	/* reachability confirmation? */
20492 	if (*rconfirm) {
20493 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20494 		if (nce->nce_state != ND_REACHABLE) {
20495 			mutex_enter(&nce->nce_lock);
20496 			nce->nce_state = ND_REACHABLE;
20497 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20498 			mutex_exit(&nce->nce_lock);
20499 			(void) untimeout(nce->nce_timeout_id);
20500 			if (ip_debug > 2) {
20501 				/* ip1dbg */
20502 				pr_addr_dbg("tcp_multisend_data: state "
20503 				    "for %s changed to REACHABLE\n",
20504 				    AF_INET6, &ire->ire_addr_v6);
20505 			}
20506 		}
20507 		/* reset transport reachability confirmation */
20508 		*rconfirm = B_FALSE;
20509 	}
20510 
20511 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20512 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20513 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20514 
20515 	if (delta > (uint64_t)ill->ill_reachable_time) {
20516 		mutex_enter(&nce->nce_lock);
20517 		switch (nce->nce_state) {
20518 		case ND_REACHABLE:
20519 		case ND_STALE:
20520 			/*
20521 			 * ND_REACHABLE is identical to ND_STALE in this
20522 			 * specific case. If reachable time has expired for
20523 			 * this neighbor (delta is greater than reachable
20524 			 * time), conceptually, the neighbor cache is no
20525 			 * longer in REACHABLE state, but already in STALE
20526 			 * state.  So the correct transition here is to
20527 			 * ND_DELAY.
20528 			 */
20529 			nce->nce_state = ND_DELAY;
20530 			mutex_exit(&nce->nce_lock);
20531 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20532 			if (ip_debug > 3) {
20533 				/* ip2dbg */
20534 				pr_addr_dbg("tcp_multisend_data: state "
20535 				    "for %s changed to DELAY\n",
20536 				    AF_INET6, &ire->ire_addr_v6);
20537 			}
20538 			break;
20539 		case ND_DELAY:
20540 		case ND_PROBE:
20541 			mutex_exit(&nce->nce_lock);
20542 			/* Timers have already started */
20543 			break;
20544 		case ND_UNREACHABLE:
20545 			/*
20546 			 * ndp timer has detected that this nce is
20547 			 * unreachable and initiated deleting this nce
20548 			 * and all its associated IREs. This is a race
20549 			 * where we found the ire before it was deleted
20550 			 * and have just sent out a packet using this
20551 			 * unreachable nce.
20552 			 */
20553 			mutex_exit(&nce->nce_lock);
20554 			break;
20555 		default:
20556 			ASSERT(0);
20557 		}
20558 	}
20559 }
20560 
20561 /*
20562  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20563  * scheme, and returns one of the following:
20564  *
20565  * -1 = failed allocation.
20566  *  0 = success; burst count reached, or usable send window is too small,
20567  *      and that we'd rather wait until later before sending again.
20568  *  1 = success; we are called from tcp_multisend(), and both usable send
20569  *      window and tail_unsent are greater than the MDT threshold, and thus
20570  *      Multidata Transmit should be used instead.
20571  */
20572 static int
20573 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20574     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20575     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20576     const int mdt_thres)
20577 {
20578 	int num_burst_seg = tcp->tcp_snd_burst;
20579 
20580 	for (;;) {
20581 		struct datab	*db;
20582 		tcph_t		*tcph;
20583 		uint32_t	sum;
20584 		mblk_t		*mp, *mp1;
20585 		uchar_t		*rptr;
20586 		int		len;
20587 
20588 		/*
20589 		 * If we're called by tcp_multisend(), and the amount of
20590 		 * sendable data as well as the size of current xmit_tail
20591 		 * is beyond the MDT threshold, return to the caller and
20592 		 * let the large data transmit be done using MDT.
20593 		 */
20594 		if (*usable > 0 && *usable > mdt_thres &&
20595 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20596 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20597 			ASSERT(tcp->tcp_mdt);
20598 			return (1);	/* success; do large send */
20599 		}
20600 
20601 		if (num_burst_seg-- == 0)
20602 			break;		/* success; burst count reached */
20603 
20604 		len = mss;
20605 		if (len > *usable) {
20606 			len = *usable;
20607 			if (len <= 0) {
20608 				/* Terminate the loop */
20609 				break;	/* success; too small */
20610 			}
20611 			/*
20612 			 * Sender silly-window avoidance.
20613 			 * Ignore this if we are going to send a
20614 			 * zero window probe out.
20615 			 *
20616 			 * TODO: force data into microscopic window?
20617 			 *	==> (!pushed || (unsent > usable))
20618 			 */
20619 			if (len < (tcp->tcp_max_swnd >> 1) &&
20620 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20621 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20622 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20623 				/*
20624 				 * If the retransmit timer is not running
20625 				 * we start it so that we will retransmit
20626 				 * in the case when the the receiver has
20627 				 * decremented the window.
20628 				 */
20629 				if (*snxt == tcp->tcp_snxt &&
20630 				    *snxt == tcp->tcp_suna) {
20631 					/*
20632 					 * We are not supposed to send
20633 					 * anything.  So let's wait a little
20634 					 * bit longer before breaking SWS
20635 					 * avoidance.
20636 					 *
20637 					 * What should the value be?
20638 					 * Suggestion: MAX(init rexmit time,
20639 					 * tcp->tcp_rto)
20640 					 */
20641 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20642 				}
20643 				break;	/* success; too small */
20644 			}
20645 		}
20646 
20647 		tcph = tcp->tcp_tcph;
20648 
20649 		*usable -= len; /* Approximate - can be adjusted later */
20650 		if (*usable > 0)
20651 			tcph->th_flags[0] = TH_ACK;
20652 		else
20653 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20654 
20655 		/*
20656 		 * Prime pump for IP's checksumming on our behalf
20657 		 * Include the adjustment for a source route if any.
20658 		 */
20659 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20660 		sum = (sum >> 16) + (sum & 0xFFFF);
20661 		U16_TO_ABE16(sum, tcph->th_sum);
20662 
20663 		U32_TO_ABE32(*snxt, tcph->th_seq);
20664 
20665 		/*
20666 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20667 		 * set.  For the case when TCP_FSS_VALID is the only valid
20668 		 * bit (normal active close), branch off only when we think
20669 		 * that the FIN flag needs to be set.  Note for this case,
20670 		 * that (snxt + len) may not reflect the actual seg_len,
20671 		 * as len may be further reduced in tcp_xmit_mp().  If len
20672 		 * gets modified, we will end up here again.
20673 		 */
20674 		if (tcp->tcp_valid_bits != 0 &&
20675 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20676 		    ((*snxt + len) == tcp->tcp_fss))) {
20677 			uchar_t		*prev_rptr;
20678 			uint32_t	prev_snxt = tcp->tcp_snxt;
20679 
20680 			if (*tail_unsent == 0) {
20681 				ASSERT((*xmit_tail)->b_cont != NULL);
20682 				*xmit_tail = (*xmit_tail)->b_cont;
20683 				prev_rptr = (*xmit_tail)->b_rptr;
20684 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20685 				    (*xmit_tail)->b_rptr);
20686 			} else {
20687 				prev_rptr = (*xmit_tail)->b_rptr;
20688 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20689 				    *tail_unsent;
20690 			}
20691 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20692 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20693 			/* Restore tcp_snxt so we get amount sent right. */
20694 			tcp->tcp_snxt = prev_snxt;
20695 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20696 				/*
20697 				 * If the previous timestamp is still in use,
20698 				 * don't stomp on it.
20699 				 */
20700 				if ((*xmit_tail)->b_next == NULL) {
20701 					(*xmit_tail)->b_prev = local_time;
20702 					(*xmit_tail)->b_next =
20703 					    (mblk_t *)(uintptr_t)(*snxt);
20704 				}
20705 			} else
20706 				(*xmit_tail)->b_rptr = prev_rptr;
20707 
20708 			if (mp == NULL)
20709 				return (-1);
20710 			mp1 = mp->b_cont;
20711 
20712 			tcp->tcp_last_sent_len = (ushort_t)len;
20713 			while (mp1->b_cont) {
20714 				*xmit_tail = (*xmit_tail)->b_cont;
20715 				(*xmit_tail)->b_prev = local_time;
20716 				(*xmit_tail)->b_next =
20717 				    (mblk_t *)(uintptr_t)(*snxt);
20718 				mp1 = mp1->b_cont;
20719 			}
20720 			*snxt += len;
20721 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20722 			BUMP_LOCAL(tcp->tcp_obsegs);
20723 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20724 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20725 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20726 			tcp_send_data(tcp, q, mp);
20727 			continue;
20728 		}
20729 
20730 		*snxt += len;	/* Adjust later if we don't send all of len */
20731 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20732 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20733 
20734 		if (*tail_unsent) {
20735 			/* Are the bytes above us in flight? */
20736 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20737 			if (rptr != (*xmit_tail)->b_rptr) {
20738 				*tail_unsent -= len;
20739 				tcp->tcp_last_sent_len = (ushort_t)len;
20740 				len += tcp_hdr_len;
20741 				if (tcp->tcp_ipversion == IPV4_VERSION)
20742 					tcp->tcp_ipha->ipha_length = htons(len);
20743 				else
20744 					tcp->tcp_ip6h->ip6_plen =
20745 					    htons(len -
20746 					    ((char *)&tcp->tcp_ip6h[1] -
20747 					    tcp->tcp_iphc));
20748 				mp = dupb(*xmit_tail);
20749 				if (!mp)
20750 					return (-1);	/* out_of_mem */
20751 				mp->b_rptr = rptr;
20752 				/*
20753 				 * If the old timestamp is no longer in use,
20754 				 * sample a new timestamp now.
20755 				 */
20756 				if ((*xmit_tail)->b_next == NULL) {
20757 					(*xmit_tail)->b_prev = local_time;
20758 					(*xmit_tail)->b_next =
20759 					    (mblk_t *)(uintptr_t)(*snxt-len);
20760 				}
20761 				goto must_alloc;
20762 			}
20763 		} else {
20764 			*xmit_tail = (*xmit_tail)->b_cont;
20765 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20766 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20767 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20768 			    (*xmit_tail)->b_rptr);
20769 		}
20770 
20771 		(*xmit_tail)->b_prev = local_time;
20772 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20773 
20774 		*tail_unsent -= len;
20775 		tcp->tcp_last_sent_len = (ushort_t)len;
20776 
20777 		len += tcp_hdr_len;
20778 		if (tcp->tcp_ipversion == IPV4_VERSION)
20779 			tcp->tcp_ipha->ipha_length = htons(len);
20780 		else
20781 			tcp->tcp_ip6h->ip6_plen = htons(len -
20782 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20783 
20784 		mp = dupb(*xmit_tail);
20785 		if (!mp)
20786 			return (-1);	/* out_of_mem */
20787 
20788 		len = tcp_hdr_len;
20789 		/*
20790 		 * There are four reasons to allocate a new hdr mblk:
20791 		 *  1) The bytes above us are in use by another packet
20792 		 *  2) We don't have good alignment
20793 		 *  3) The mblk is being shared
20794 		 *  4) We don't have enough room for a header
20795 		 */
20796 		rptr = mp->b_rptr - len;
20797 		if (!OK_32PTR(rptr) ||
20798 		    ((db = mp->b_datap), db->db_ref != 2) ||
20799 		    rptr < db->db_base) {
20800 			/* NOTE: we assume allocb returns an OK_32PTR */
20801 
20802 		must_alloc:;
20803 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20804 			    tcp_wroff_xtra, BPRI_MED);
20805 			if (!mp1) {
20806 				freemsg(mp);
20807 				return (-1);	/* out_of_mem */
20808 			}
20809 			mp1->b_cont = mp;
20810 			mp = mp1;
20811 			/* Leave room for Link Level header */
20812 			len = tcp_hdr_len;
20813 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20814 			mp->b_wptr = &rptr[len];
20815 		}
20816 
20817 		/*
20818 		 * Fill in the header using the template header, and add
20819 		 * options such as time-stamp, ECN and/or SACK, as needed.
20820 		 */
20821 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20822 
20823 		mp->b_rptr = rptr;
20824 
20825 		if (*tail_unsent) {
20826 			int spill = *tail_unsent;
20827 
20828 			mp1 = mp->b_cont;
20829 			if (!mp1)
20830 				mp1 = mp;
20831 
20832 			/*
20833 			 * If we're a little short, tack on more mblks until
20834 			 * there is no more spillover.
20835 			 */
20836 			while (spill < 0) {
20837 				mblk_t *nmp;
20838 				int nmpsz;
20839 
20840 				nmp = (*xmit_tail)->b_cont;
20841 				nmpsz = MBLKL(nmp);
20842 
20843 				/*
20844 				 * Excess data in mblk; can we split it?
20845 				 * If MDT is enabled for the connection,
20846 				 * keep on splitting as this is a transient
20847 				 * send path.
20848 				 */
20849 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20850 					/*
20851 					 * Don't split if stream head was
20852 					 * told to break up larger writes
20853 					 * into smaller ones.
20854 					 */
20855 					if (tcp->tcp_maxpsz > 0)
20856 						break;
20857 
20858 					/*
20859 					 * Next mblk is less than SMSS/2
20860 					 * rounded up to nearest 64-byte;
20861 					 * let it get sent as part of the
20862 					 * next segment.
20863 					 */
20864 					if (tcp->tcp_localnet &&
20865 					    !tcp->tcp_cork &&
20866 					    (nmpsz < roundup((mss >> 1), 64)))
20867 						break;
20868 				}
20869 
20870 				*xmit_tail = nmp;
20871 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20872 				/* Stash for rtt use later */
20873 				(*xmit_tail)->b_prev = local_time;
20874 				(*xmit_tail)->b_next =
20875 				    (mblk_t *)(uintptr_t)(*snxt - len);
20876 				mp1->b_cont = dupb(*xmit_tail);
20877 				mp1 = mp1->b_cont;
20878 
20879 				spill += nmpsz;
20880 				if (mp1 == NULL) {
20881 					*tail_unsent = spill;
20882 					freemsg(mp);
20883 					return (-1);	/* out_of_mem */
20884 				}
20885 			}
20886 
20887 			/* Trim back any surplus on the last mblk */
20888 			if (spill >= 0) {
20889 				mp1->b_wptr -= spill;
20890 				*tail_unsent = spill;
20891 			} else {
20892 				/*
20893 				 * We did not send everything we could in
20894 				 * order to remain within the b_cont limit.
20895 				 */
20896 				*usable -= spill;
20897 				*snxt += spill;
20898 				tcp->tcp_last_sent_len += spill;
20899 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20900 				/*
20901 				 * Adjust the checksum
20902 				 */
20903 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20904 				sum += spill;
20905 				sum = (sum >> 16) + (sum & 0xFFFF);
20906 				U16_TO_ABE16(sum, tcph->th_sum);
20907 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20908 					sum = ntohs(
20909 					    ((ipha_t *)rptr)->ipha_length) +
20910 					    spill;
20911 					((ipha_t *)rptr)->ipha_length =
20912 					    htons(sum);
20913 				} else {
20914 					sum = ntohs(
20915 					    ((ip6_t *)rptr)->ip6_plen) +
20916 					    spill;
20917 					((ip6_t *)rptr)->ip6_plen =
20918 					    htons(sum);
20919 				}
20920 				*tail_unsent = 0;
20921 			}
20922 		}
20923 		if (tcp->tcp_ip_forward_progress) {
20924 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20925 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20926 			tcp->tcp_ip_forward_progress = B_FALSE;
20927 		}
20928 
20929 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20930 		tcp_send_data(tcp, q, mp);
20931 		BUMP_LOCAL(tcp->tcp_obsegs);
20932 	}
20933 
20934 	return (0);
20935 }
20936 
20937 /* Unlink and return any mblk that looks like it contains a MDT info */
20938 static mblk_t *
20939 tcp_mdt_info_mp(mblk_t *mp)
20940 {
20941 	mblk_t	*prev_mp;
20942 
20943 	for (;;) {
20944 		prev_mp = mp;
20945 		/* no more to process? */
20946 		if ((mp = mp->b_cont) == NULL)
20947 			break;
20948 
20949 		switch (DB_TYPE(mp)) {
20950 		case M_CTL:
20951 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20952 				continue;
20953 			ASSERT(prev_mp != NULL);
20954 			prev_mp->b_cont = mp->b_cont;
20955 			mp->b_cont = NULL;
20956 			return (mp);
20957 		default:
20958 			break;
20959 		}
20960 	}
20961 	return (mp);
20962 }
20963 
20964 /* MDT info update routine, called when IP notifies us about MDT */
20965 static void
20966 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20967 {
20968 	boolean_t prev_state;
20969 
20970 	/*
20971 	 * IP is telling us to abort MDT on this connection?  We know
20972 	 * this because the capability is only turned off when IP
20973 	 * encounters some pathological cases, e.g. link-layer change
20974 	 * where the new driver doesn't support MDT, or in situation
20975 	 * where MDT usage on the link-layer has been switched off.
20976 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20977 	 * if the link-layer doesn't support MDT, and if it does, it
20978 	 * will indicate that the feature is to be turned on.
20979 	 */
20980 	prev_state = tcp->tcp_mdt;
20981 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20982 	if (!tcp->tcp_mdt && !first) {
20983 		TCP_STAT(tcp_mdt_conn_halted3);
20984 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20985 		    (void *)tcp->tcp_connp));
20986 	}
20987 
20988 	/*
20989 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20990 	 * so disable MDT otherwise.  The checks are done here
20991 	 * and in tcp_wput_data().
20992 	 */
20993 	if (tcp->tcp_mdt &&
20994 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20995 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20996 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20997 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20998 		tcp->tcp_mdt = B_FALSE;
20999 
21000 	if (tcp->tcp_mdt) {
21001 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21002 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21003 			    "version (%d), expected version is %d",
21004 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21005 			tcp->tcp_mdt = B_FALSE;
21006 			return;
21007 		}
21008 
21009 		/*
21010 		 * We need the driver to be able to handle at least three
21011 		 * spans per packet in order for tcp MDT to be utilized.
21012 		 * The first is for the header portion, while the rest are
21013 		 * needed to handle a packet that straddles across two
21014 		 * virtually non-contiguous buffers; a typical tcp packet
21015 		 * therefore consists of only two spans.  Note that we take
21016 		 * a zero as "don't care".
21017 		 */
21018 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21019 		    mdt_capab->ill_mdt_span_limit < 3) {
21020 			tcp->tcp_mdt = B_FALSE;
21021 			return;
21022 		}
21023 
21024 		/* a zero means driver wants default value */
21025 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21026 		    tcp_mdt_max_pbufs);
21027 		if (tcp->tcp_mdt_max_pld == 0)
21028 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
21029 
21030 		/* ensure 32-bit alignment */
21031 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
21032 		    mdt_capab->ill_mdt_hdr_head), 4);
21033 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
21034 		    mdt_capab->ill_mdt_hdr_tail), 4);
21035 
21036 		if (!first && !prev_state) {
21037 			TCP_STAT(tcp_mdt_conn_resumed2);
21038 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21039 			    (void *)tcp->tcp_connp));
21040 		}
21041 	}
21042 }
21043 
21044 static void
21045 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
21046 {
21047 	conn_t *connp = tcp->tcp_connp;
21048 
21049 	ASSERT(ire != NULL);
21050 
21051 	/*
21052 	 * We may be in the fastpath here, and although we essentially do
21053 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
21054 	 * we try to keep things as brief as possible.  After all, these
21055 	 * are only best-effort checks, and we do more thorough ones prior
21056 	 * to calling tcp_multisend().
21057 	 */
21058 	if (ip_multidata_outbound && check_mdt &&
21059 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21060 	    ill != NULL && (ill->ill_capabilities & ILL_CAPAB_MDT) &&
21061 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21062 	    !(ire->ire_flags & RTF_MULTIRT) &&
21063 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
21064 	    CONN_IS_MD_FASTPATH(connp)) {
21065 		/* Remember the result */
21066 		connp->conn_mdt_ok = B_TRUE;
21067 
21068 		ASSERT(ill->ill_mdt_capab != NULL);
21069 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21070 			/*
21071 			 * If MDT has been previously turned off in the past,
21072 			 * and we currently can do MDT (due to IPQoS policy
21073 			 * removal, etc.) then enable it for this interface.
21074 			 */
21075 			ill->ill_mdt_capab->ill_mdt_on = 1;
21076 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
21077 			    "interface %s\n", (void *)connp, ill->ill_name));
21078 		}
21079 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21080 	}
21081 
21082 	/*
21083 	 * The goal is to reduce the number of generated tcp segments by
21084 	 * setting the maxpsz multiplier to 0; this will have an affect on
21085 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21086 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21087 	 * of outbound segments and incoming ACKs, thus allowing for better
21088 	 * network and system performance.  In contrast the legacy behavior
21089 	 * may result in sending less than SMSS size, because the last mblk
21090 	 * for some packets may have more data than needed to make up SMSS,
21091 	 * and the legacy code refused to "split" it.
21092 	 *
21093 	 * We apply the new behavior on following situations:
21094 	 *
21095 	 *   1) Loopback connections,
21096 	 *   2) Connections in which the remote peer is not on local subnet,
21097 	 *   3) Local subnet connections over the bge interface (see below).
21098 	 *
21099 	 * Ideally, we would like this behavior to apply for interfaces other
21100 	 * than bge.  However, doing so would negatively impact drivers which
21101 	 * perform dynamic mapping and unmapping of DMA resources, which are
21102 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21103 	 * packet will be generated by tcp).  The bge driver does not suffer
21104 	 * from this, as it copies the mblks into pre-mapped buffers, and
21105 	 * therefore does not require more I/O resources than before.
21106 	 *
21107 	 * Otherwise, this behavior is present on all network interfaces when
21108 	 * the destination endpoint is non-local, since reducing the number
21109 	 * of packets in general is good for the network.
21110 	 *
21111 	 * TODO We need to remove this hard-coded conditional for bge once
21112 	 *	a better "self-tuning" mechanism, or a way to comprehend
21113 	 *	the driver transmit strategy is devised.  Until the solution
21114 	 *	is found and well understood, we live with this hack.
21115 	 */
21116 	if (!tcp_static_maxpsz &&
21117 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21118 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21119 		/* override the default value */
21120 		tcp->tcp_maxpsz = 0;
21121 
21122 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21123 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21124 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21125 	}
21126 
21127 	/* set the stream head parameters accordingly */
21128 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21129 }
21130 
21131 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21132 static void
21133 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21134 {
21135 	uchar_t	fval = *mp->b_rptr;
21136 	mblk_t	*tail;
21137 	queue_t	*q = tcp->tcp_wq;
21138 
21139 	/* TODO: How should flush interact with urgent data? */
21140 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21141 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21142 		/*
21143 		 * Flush only data that has not yet been put on the wire.  If
21144 		 * we flush data that we have already transmitted, life, as we
21145 		 * know it, may come to an end.
21146 		 */
21147 		tail = tcp->tcp_xmit_tail;
21148 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21149 		tcp->tcp_xmit_tail_unsent = 0;
21150 		tcp->tcp_unsent = 0;
21151 		if (tail->b_wptr != tail->b_rptr)
21152 			tail = tail->b_cont;
21153 		if (tail) {
21154 			mblk_t **excess = &tcp->tcp_xmit_head;
21155 			for (;;) {
21156 				mblk_t *mp1 = *excess;
21157 				if (mp1 == tail)
21158 					break;
21159 				tcp->tcp_xmit_tail = mp1;
21160 				tcp->tcp_xmit_last = mp1;
21161 				excess = &mp1->b_cont;
21162 			}
21163 			*excess = NULL;
21164 			tcp_close_mpp(&tail);
21165 			if (tcp->tcp_snd_zcopy_aware)
21166 				tcp_zcopy_notify(tcp);
21167 		}
21168 		/*
21169 		 * We have no unsent data, so unsent must be less than
21170 		 * tcp_xmit_lowater, so re-enable flow.
21171 		 */
21172 		if (tcp->tcp_flow_stopped) {
21173 			tcp_clrqfull(tcp);
21174 		}
21175 	}
21176 	/*
21177 	 * TODO: you can't just flush these, you have to increase rwnd for one
21178 	 * thing.  For another, how should urgent data interact?
21179 	 */
21180 	if (fval & FLUSHR) {
21181 		*mp->b_rptr = fval & ~FLUSHW;
21182 		/* XXX */
21183 		qreply(q, mp);
21184 		return;
21185 	}
21186 	freemsg(mp);
21187 }
21188 
21189 /*
21190  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21191  * messages.
21192  */
21193 static void
21194 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21195 {
21196 	mblk_t	*mp1;
21197 	STRUCT_HANDLE(strbuf, sb);
21198 	uint16_t port;
21199 	queue_t 	*q = tcp->tcp_wq;
21200 	in6_addr_t	v6addr;
21201 	ipaddr_t	v4addr;
21202 	uint32_t	flowinfo = 0;
21203 	int		addrlen;
21204 
21205 	/* Make sure it is one of ours. */
21206 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21207 	case TI_GETMYNAME:
21208 	case TI_GETPEERNAME:
21209 		break;
21210 	default:
21211 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21212 		return;
21213 	}
21214 	switch (mi_copy_state(q, mp, &mp1)) {
21215 	case -1:
21216 		return;
21217 	case MI_COPY_CASE(MI_COPY_IN, 1):
21218 		break;
21219 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21220 		/* Copy out the strbuf. */
21221 		mi_copyout(q, mp);
21222 		return;
21223 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21224 		/* All done. */
21225 		mi_copy_done(q, mp, 0);
21226 		return;
21227 	default:
21228 		mi_copy_done(q, mp, EPROTO);
21229 		return;
21230 	}
21231 	/* Check alignment of the strbuf */
21232 	if (!OK_32PTR(mp1->b_rptr)) {
21233 		mi_copy_done(q, mp, EINVAL);
21234 		return;
21235 	}
21236 
21237 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21238 	    (void *)mp1->b_rptr);
21239 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21240 
21241 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21242 		mi_copy_done(q, mp, EINVAL);
21243 		return;
21244 	}
21245 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21246 	case TI_GETMYNAME:
21247 		if (tcp->tcp_family == AF_INET) {
21248 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21249 				v4addr = tcp->tcp_ipha->ipha_src;
21250 			} else {
21251 				/* can't return an address in this case */
21252 				v4addr = 0;
21253 			}
21254 		} else {
21255 			/* tcp->tcp_family == AF_INET6 */
21256 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21257 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21258 				    &v6addr);
21259 			} else {
21260 				v6addr = tcp->tcp_ip6h->ip6_src;
21261 			}
21262 		}
21263 		port = tcp->tcp_lport;
21264 		break;
21265 	case TI_GETPEERNAME:
21266 		if (tcp->tcp_family == AF_INET) {
21267 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21268 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21269 				    v4addr);
21270 			} else {
21271 				/* can't return an address in this case */
21272 				v4addr = 0;
21273 			}
21274 		} else {
21275 			/* tcp->tcp_family == AF_INET6) */
21276 			v6addr = tcp->tcp_remote_v6;
21277 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21278 				/*
21279 				 * No flowinfo if tcp->tcp_ipversion is v4.
21280 				 *
21281 				 * flowinfo was already initialized to zero
21282 				 * where it was declared above, so only
21283 				 * set it if ipversion is v6.
21284 				 */
21285 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21286 				    ~IPV6_VERS_AND_FLOW_MASK;
21287 			}
21288 		}
21289 		port = tcp->tcp_fport;
21290 		break;
21291 	default:
21292 		mi_copy_done(q, mp, EPROTO);
21293 		return;
21294 	}
21295 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21296 	if (!mp1)
21297 		return;
21298 
21299 	if (tcp->tcp_family == AF_INET) {
21300 		sin_t *sin;
21301 
21302 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21303 		sin = (sin_t *)mp1->b_rptr;
21304 		mp1->b_wptr = (uchar_t *)&sin[1];
21305 		*sin = sin_null;
21306 		sin->sin_family = AF_INET;
21307 		sin->sin_addr.s_addr = v4addr;
21308 		sin->sin_port = port;
21309 	} else {
21310 		/* tcp->tcp_family == AF_INET6 */
21311 		sin6_t *sin6;
21312 
21313 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21314 		sin6 = (sin6_t *)mp1->b_rptr;
21315 		mp1->b_wptr = (uchar_t *)&sin6[1];
21316 		*sin6 = sin6_null;
21317 		sin6->sin6_family = AF_INET6;
21318 		sin6->sin6_flowinfo = flowinfo;
21319 		sin6->sin6_addr = v6addr;
21320 		sin6->sin6_port = port;
21321 	}
21322 	/* Copy out the address */
21323 	mi_copyout(q, mp);
21324 }
21325 
21326 /*
21327  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21328  * messages.
21329  */
21330 /* ARGSUSED */
21331 static void
21332 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21333 {
21334 	conn_t 	*connp = (conn_t *)arg;
21335 	tcp_t	*tcp = connp->conn_tcp;
21336 	queue_t	*q = tcp->tcp_wq;
21337 	struct iocblk	*iocp;
21338 
21339 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21340 	/*
21341 	 * Try and ASSERT the minimum possible references on the
21342 	 * conn early enough. Since we are executing on write side,
21343 	 * the connection is obviously not detached and that means
21344 	 * there is a ref each for TCP and IP. Since we are behind
21345 	 * the squeue, the minimum references needed are 3. If the
21346 	 * conn is in classifier hash list, there should be an
21347 	 * extra ref for that (we check both the possibilities).
21348 	 */
21349 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21350 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21351 
21352 	iocp = (struct iocblk *)mp->b_rptr;
21353 	switch (iocp->ioc_cmd) {
21354 	case TCP_IOC_DEFAULT_Q:
21355 		/* Wants to be the default wq. */
21356 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
21357 			iocp->ioc_error = EPERM;
21358 			iocp->ioc_count = 0;
21359 			mp->b_datap->db_type = M_IOCACK;
21360 			qreply(q, mp);
21361 			return;
21362 		}
21363 		tcp_def_q_set(tcp, mp);
21364 		return;
21365 	case SIOCPOPSOCKFS:
21366 		/*
21367 		 * sockfs is being I_POP'ed, reset the flag
21368 		 * indicating this
21369 		 */
21370 		tcp->tcp_issocket = B_FALSE;
21371 
21372 		/*
21373 		 * Insert this socket into the acceptor hash.
21374 		 * We might need it for T_CONN_RES message
21375 		 */
21376 #ifdef	_ILP32
21377 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21378 #else
21379 		tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21380 #endif
21381 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21382 		mp->b_datap->db_type = M_IOCACK;
21383 		iocp->ioc_count = 0;
21384 		iocp->ioc_error = 0;
21385 		iocp->ioc_rval = 0;
21386 		qreply(q, mp);
21387 		return;
21388 	}
21389 	CALL_IP_WPUT(connp, q, mp);
21390 }
21391 
21392 /*
21393  * This routine is called by tcp_wput() to handle all TPI requests.
21394  */
21395 /* ARGSUSED */
21396 static void
21397 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21398 {
21399 	conn_t 	*connp = (conn_t *)arg;
21400 	tcp_t	*tcp = connp->conn_tcp;
21401 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21402 	uchar_t *rptr;
21403 	t_scalar_t type;
21404 	int len;
21405 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21406 
21407 	/*
21408 	 * Try and ASSERT the minimum possible references on the
21409 	 * conn early enough. Since we are executing on write side,
21410 	 * the connection is obviously not detached and that means
21411 	 * there is a ref each for TCP and IP. Since we are behind
21412 	 * the squeue, the minimum references needed are 3. If the
21413 	 * conn is in classifier hash list, there should be an
21414 	 * extra ref for that (we check both the possibilities).
21415 	 */
21416 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21417 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21418 
21419 	rptr = mp->b_rptr;
21420 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21421 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21422 		type = ((union T_primitives *)rptr)->type;
21423 		if (type == T_EXDATA_REQ) {
21424 			len = msgdsize(mp->b_cont) - 1;
21425 			if (len < 0) {
21426 				freemsg(mp);
21427 				return;
21428 			}
21429 			/*
21430 			 * Try to force urgent data out on the wire.
21431 			 * Even if we have unsent data this will
21432 			 * at least send the urgent flag.
21433 			 * XXX does not handle more flag correctly.
21434 			 */
21435 			len += tcp->tcp_unsent;
21436 			len += tcp->tcp_snxt;
21437 			tcp->tcp_urg = len;
21438 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21439 
21440 			/* Bypass tcp protocol for fused tcp loopback */
21441 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp))
21442 				return;
21443 		} else if (type != T_DATA_REQ) {
21444 			goto non_urgent_data;
21445 		}
21446 		/* TODO: options, flags, ... from user */
21447 		/* Set length to zero for reclamation below */
21448 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21449 		freeb(mp);
21450 		return;
21451 	} else {
21452 		if (tcp->tcp_debug) {
21453 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21454 			    "tcp_wput_proto, dropping one...");
21455 		}
21456 		freemsg(mp);
21457 		return;
21458 	}
21459 
21460 non_urgent_data:
21461 
21462 	switch ((int)tprim->type) {
21463 	case O_T_BIND_REQ:	/* bind request */
21464 	case T_BIND_REQ:	/* new semantics bind request */
21465 		tcp_bind(tcp, mp);
21466 		break;
21467 	case T_UNBIND_REQ:	/* unbind request */
21468 		tcp_unbind(tcp, mp);
21469 		break;
21470 	case O_T_CONN_RES:	/* old connection response XXX */
21471 	case T_CONN_RES:	/* connection response */
21472 		tcp_accept(tcp, mp);
21473 		break;
21474 	case T_CONN_REQ:	/* connection request */
21475 		tcp_connect(tcp, mp);
21476 		break;
21477 	case T_DISCON_REQ:	/* disconnect request */
21478 		tcp_disconnect(tcp, mp);
21479 		break;
21480 	case T_CAPABILITY_REQ:
21481 		tcp_capability_req(tcp, mp);	/* capability request */
21482 		break;
21483 	case T_INFO_REQ:	/* information request */
21484 		tcp_info_req(tcp, mp);
21485 		break;
21486 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21487 		/* Only IP is allowed to return meaningful value */
21488 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21489 		break;
21490 	case T_OPTMGMT_REQ:
21491 		/*
21492 		 * Note:  no support for snmpcom_req() through new
21493 		 * T_OPTMGMT_REQ. See comments in ip.c
21494 		 */
21495 		/* Only IP is allowed to return meaningful value */
21496 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21497 		break;
21498 
21499 	case T_UNITDATA_REQ:	/* unitdata request */
21500 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21501 		break;
21502 	case T_ORDREL_REQ:	/* orderly release req */
21503 		freemsg(mp);
21504 
21505 		if (tcp->tcp_fused)
21506 			tcp_unfuse(tcp);
21507 
21508 		if (tcp_xmit_end(tcp) != 0) {
21509 			/*
21510 			 * We were crossing FINs and got a reset from
21511 			 * the other side. Just ignore it.
21512 			 */
21513 			if (tcp->tcp_debug) {
21514 				(void) strlog(TCP_MODULE_ID, 0, 1,
21515 				    SL_ERROR|SL_TRACE,
21516 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21517 				    "state %s",
21518 				    tcp_display(tcp, NULL,
21519 				    DISP_ADDR_AND_PORT));
21520 			}
21521 		}
21522 		break;
21523 	case T_ADDR_REQ:
21524 		tcp_addr_req(tcp, mp);
21525 		break;
21526 	default:
21527 		if (tcp->tcp_debug) {
21528 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21529 			    "tcp_wput_proto, bogus TPI msg, type %d",
21530 			    tprim->type);
21531 		}
21532 		/*
21533 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21534 		 * to recover.
21535 		 */
21536 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21537 		break;
21538 	}
21539 }
21540 
21541 /*
21542  * The TCP write service routine should never be called...
21543  */
21544 /* ARGSUSED */
21545 static void
21546 tcp_wsrv(queue_t *q)
21547 {
21548 	TCP_STAT(tcp_wsrv_called);
21549 }
21550 
21551 /* Non overlapping byte exchanger */
21552 static void
21553 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21554 {
21555 	uchar_t	uch;
21556 
21557 	while (len-- > 0) {
21558 		uch = a[len];
21559 		a[len] = b[len];
21560 		b[len] = uch;
21561 	}
21562 }
21563 
21564 /*
21565  * Send out a control packet on the tcp connection specified.  This routine
21566  * is typically called where we need a simple ACK or RST generated.
21567  */
21568 static void
21569 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21570 {
21571 	uchar_t		*rptr;
21572 	tcph_t		*tcph;
21573 	ipha_t		*ipha = NULL;
21574 	ip6_t		*ip6h = NULL;
21575 	uint32_t	sum;
21576 	int		tcp_hdr_len;
21577 	int		tcp_ip_hdr_len;
21578 	mblk_t		*mp;
21579 
21580 	/*
21581 	 * Save sum for use in source route later.
21582 	 */
21583 	ASSERT(tcp != NULL);
21584 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21585 	tcp_hdr_len = tcp->tcp_hdr_len;
21586 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21587 
21588 	/* If a text string is passed in with the request, pass it to strlog. */
21589 	if (str != NULL && tcp->tcp_debug) {
21590 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21591 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21592 		    str, seq, ack, ctl);
21593 	}
21594 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21595 	    BPRI_MED);
21596 	if (mp == NULL) {
21597 		return;
21598 	}
21599 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21600 	mp->b_rptr = rptr;
21601 	mp->b_wptr = &rptr[tcp_hdr_len];
21602 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21603 
21604 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21605 		ipha = (ipha_t *)rptr;
21606 		ipha->ipha_length = htons(tcp_hdr_len);
21607 	} else {
21608 		ip6h = (ip6_t *)rptr;
21609 		ASSERT(tcp != NULL);
21610 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21611 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21612 	}
21613 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21614 	tcph->th_flags[0] = (uint8_t)ctl;
21615 	if (ctl & TH_RST) {
21616 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21617 		BUMP_MIB(&tcp_mib, tcpOutControl);
21618 		/*
21619 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21620 		 */
21621 		if (tcp->tcp_snd_ts_ok &&
21622 		    tcp->tcp_state > TCPS_SYN_SENT) {
21623 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21624 			*(mp->b_wptr) = TCPOPT_EOL;
21625 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21626 				ipha->ipha_length = htons(tcp_hdr_len -
21627 				    TCPOPT_REAL_TS_LEN);
21628 			} else {
21629 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21630 				    TCPOPT_REAL_TS_LEN);
21631 			}
21632 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21633 			sum -= TCPOPT_REAL_TS_LEN;
21634 		}
21635 	}
21636 	if (ctl & TH_ACK) {
21637 		if (tcp->tcp_snd_ts_ok) {
21638 			U32_TO_BE32(lbolt,
21639 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21640 			U32_TO_BE32(tcp->tcp_ts_recent,
21641 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21642 		}
21643 
21644 		/* Update the latest receive window size in TCP header. */
21645 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21646 		    tcph->th_win);
21647 		tcp->tcp_rack = ack;
21648 		tcp->tcp_rack_cnt = 0;
21649 		BUMP_MIB(&tcp_mib, tcpOutAck);
21650 	}
21651 	BUMP_LOCAL(tcp->tcp_obsegs);
21652 	U32_TO_BE32(seq, tcph->th_seq);
21653 	U32_TO_BE32(ack, tcph->th_ack);
21654 	/*
21655 	 * Include the adjustment for a source route if any.
21656 	 */
21657 	sum = (sum >> 16) + (sum & 0xFFFF);
21658 	U16_TO_BE16(sum, tcph->th_sum);
21659 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21660 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21661 }
21662 
21663 /*
21664  * If this routine returns B_TRUE, TCP can generate a RST in response
21665  * to a segment.  If it returns B_FALSE, TCP should not respond.
21666  */
21667 static boolean_t
21668 tcp_send_rst_chk(void)
21669 {
21670 	clock_t	now;
21671 
21672 	/*
21673 	 * TCP needs to protect itself from generating too many RSTs.
21674 	 * This can be a DoS attack by sending us random segments
21675 	 * soliciting RSTs.
21676 	 *
21677 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21678 	 * in each 1 second interval.  In this way, TCP still generate
21679 	 * RSTs in normal cases but when under attack, the impact is
21680 	 * limited.
21681 	 */
21682 	if (tcp_rst_sent_rate_enabled != 0) {
21683 		now = lbolt;
21684 		/* lbolt can wrap around. */
21685 		if ((tcp_last_rst_intrvl > now) ||
21686 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21687 			tcp_last_rst_intrvl = now;
21688 			tcp_rst_cnt = 1;
21689 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21690 			return (B_FALSE);
21691 		}
21692 	}
21693 	return (B_TRUE);
21694 }
21695 
21696 /*
21697  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21698  */
21699 static void
21700 tcp_ip_ire_mark_advice(tcp_t *tcp)
21701 {
21702 	mblk_t *mp;
21703 	ipic_t *ipic;
21704 
21705 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21706 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21707 		    &ipic);
21708 	} else {
21709 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21710 		    &ipic);
21711 	}
21712 	if (mp == NULL)
21713 		return;
21714 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21715 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21716 }
21717 
21718 /*
21719  * Return an IP advice ioctl mblk and set ipic to be the pointer
21720  * to the advice structure.
21721  */
21722 static mblk_t *
21723 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21724 {
21725 	struct iocblk *ioc;
21726 	mblk_t *mp, *mp1;
21727 
21728 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21729 	if (mp == NULL)
21730 		return (NULL);
21731 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21732 	*ipic = (ipic_t *)mp->b_rptr;
21733 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21734 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21735 
21736 	bcopy(addr, *ipic + 1, addr_len);
21737 
21738 	(*ipic)->ipic_addr_length = addr_len;
21739 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21740 
21741 	mp1 = mkiocb(IP_IOCTL);
21742 	if (mp1 == NULL) {
21743 		freemsg(mp);
21744 		return (NULL);
21745 	}
21746 	mp1->b_cont = mp;
21747 	ioc = (struct iocblk *)mp1->b_rptr;
21748 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21749 
21750 	return (mp1);
21751 }
21752 
21753 /*
21754  * Generate a reset based on an inbound packet for which there is no active
21755  * tcp state that we can find.
21756  *
21757  * IPSEC NOTE : Try to send the reply with the same protection as it came
21758  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21759  * the packet will go out at the same level of protection as it came in by
21760  * converting the IPSEC_IN to IPSEC_OUT.
21761  */
21762 static void
21763 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21764     uint32_t ack, int ctl, uint_t ip_hdr_len)
21765 {
21766 	ipha_t		*ipha = NULL;
21767 	ip6_t		*ip6h = NULL;
21768 	ushort_t	len;
21769 	tcph_t		*tcph;
21770 	int		i;
21771 	mblk_t		*ipsec_mp;
21772 	boolean_t	mctl_present;
21773 	ipic_t		*ipic;
21774 	ipaddr_t	v4addr;
21775 	in6_addr_t	v6addr;
21776 	int		addr_len;
21777 	void		*addr;
21778 	queue_t		*q = tcp_g_q;
21779 	tcp_t		*tcp = Q_TO_TCP(q);
21780 
21781 	if (!tcp_send_rst_chk()) {
21782 		tcp_rst_unsent++;
21783 		freemsg(mp);
21784 		return;
21785 	}
21786 
21787 	if (mp->b_datap->db_type == M_CTL) {
21788 		ipsec_mp = mp;
21789 		mp = mp->b_cont;
21790 		mctl_present = B_TRUE;
21791 	} else {
21792 		ipsec_mp = mp;
21793 		mctl_present = B_FALSE;
21794 	}
21795 
21796 	if (str && q && tcp_dbg) {
21797 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21798 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21799 		    "flags 0x%x",
21800 		    str, seq, ack, ctl);
21801 	}
21802 	if (mp->b_datap->db_ref != 1) {
21803 		mblk_t *mp1 = copyb(mp);
21804 		freemsg(mp);
21805 		mp = mp1;
21806 		if (!mp) {
21807 			if (mctl_present)
21808 				freeb(ipsec_mp);
21809 			return;
21810 		} else {
21811 			if (mctl_present) {
21812 				ipsec_mp->b_cont = mp;
21813 			} else {
21814 				ipsec_mp = mp;
21815 			}
21816 		}
21817 	} else if (mp->b_cont) {
21818 		freemsg(mp->b_cont);
21819 		mp->b_cont = NULL;
21820 	}
21821 	/*
21822 	 * We skip reversing source route here.
21823 	 * (for now we replace all IP options with EOL)
21824 	 */
21825 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21826 		ipha = (ipha_t *)mp->b_rptr;
21827 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21828 			mp->b_rptr[i] = IPOPT_EOL;
21829 		/*
21830 		 * Make sure that src address isn't flagrantly invalid.
21831 		 * Not all broadcast address checking for the src address
21832 		 * is possible, since we don't know the netmask of the src
21833 		 * addr.  No check for destination address is done, since
21834 		 * IP will not pass up a packet with a broadcast dest
21835 		 * address to TCP.  Similar checks are done below for IPv6.
21836 		 */
21837 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21838 		    CLASSD(ipha->ipha_src)) {
21839 			freemsg(ipsec_mp);
21840 			BUMP_MIB(&ip_mib, ipInDiscards);
21841 			return;
21842 		}
21843 	} else {
21844 		ip6h = (ip6_t *)mp->b_rptr;
21845 
21846 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21847 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21848 			freemsg(ipsec_mp);
21849 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21850 			return;
21851 		}
21852 
21853 		/* Remove any extension headers assuming partial overlay */
21854 		if (ip_hdr_len > IPV6_HDR_LEN) {
21855 			uint8_t *to;
21856 
21857 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21858 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21859 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21860 			ip_hdr_len = IPV6_HDR_LEN;
21861 			ip6h = (ip6_t *)mp->b_rptr;
21862 			ip6h->ip6_nxt = IPPROTO_TCP;
21863 		}
21864 	}
21865 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21866 	if (tcph->th_flags[0] & TH_RST) {
21867 		freemsg(ipsec_mp);
21868 		return;
21869 	}
21870 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21871 	len = ip_hdr_len + sizeof (tcph_t);
21872 	mp->b_wptr = &mp->b_rptr[len];
21873 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21874 		ipha->ipha_length = htons(len);
21875 		/* Swap addresses */
21876 		v4addr = ipha->ipha_src;
21877 		ipha->ipha_src = ipha->ipha_dst;
21878 		ipha->ipha_dst = v4addr;
21879 		ipha->ipha_ident = 0;
21880 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21881 		addr_len = IP_ADDR_LEN;
21882 		addr = &v4addr;
21883 	} else {
21884 		/* No ip6i_t in this case */
21885 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21886 		/* Swap addresses */
21887 		v6addr = ip6h->ip6_src;
21888 		ip6h->ip6_src = ip6h->ip6_dst;
21889 		ip6h->ip6_dst = v6addr;
21890 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21891 		addr_len = IPV6_ADDR_LEN;
21892 		addr = &v6addr;
21893 	}
21894 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21895 	U32_TO_BE32(ack, tcph->th_ack);
21896 	U32_TO_BE32(seq, tcph->th_seq);
21897 	U16_TO_BE16(0, tcph->th_win);
21898 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21899 	tcph->th_flags[0] = (uint8_t)ctl;
21900 	if (ctl & TH_RST) {
21901 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21902 		BUMP_MIB(&tcp_mib, tcpOutControl);
21903 	}
21904 	if (mctl_present) {
21905 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21906 
21907 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21908 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21909 			return;
21910 		}
21911 	}
21912 	/*
21913 	 * NOTE:  one might consider tracing a TCP packet here, but
21914 	 * this function has no active TCP state nd no tcp structure
21915 	 * which has trace buffer.  If we traced here, we would have
21916 	 * to keep a local trace buffer in tcp_record_trace().
21917 	 */
21918 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21919 
21920 	/*
21921 	 * Tell IP to mark the IRE used for this destination temporary.
21922 	 * This way, we can limit our exposure to DoS attack because IP
21923 	 * creates an IRE for each destination.  If there are too many,
21924 	 * the time to do any routing lookup will be extremely long.  And
21925 	 * the lookup can be in interrupt context.
21926 	 *
21927 	 * Note that in normal circumstances, this marking should not
21928 	 * affect anything.  It would be nice if only 1 message is
21929 	 * needed to inform IP that the IRE created for this RST should
21930 	 * not be added to the cache table.  But there is currently
21931 	 * not such communication mechanism between TCP and IP.  So
21932 	 * the best we can do now is to send the advice ioctl to IP
21933 	 * to mark the IRE temporary.
21934 	 */
21935 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21936 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21937 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21938 	}
21939 }
21940 
21941 /*
21942  * Initiate closedown sequence on an active connection.  (May be called as
21943  * writer.)  Return value zero for OK return, non-zero for error return.
21944  */
21945 static int
21946 tcp_xmit_end(tcp_t *tcp)
21947 {
21948 	ipic_t	*ipic;
21949 	mblk_t	*mp;
21950 
21951 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21952 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21953 		/*
21954 		 * Invalid state, only states TCPS_SYN_RCVD,
21955 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21956 		 */
21957 		return (-1);
21958 	}
21959 
21960 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21961 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21962 	/*
21963 	 * If there is nothing more unsent, send the FIN now.
21964 	 * Otherwise, it will go out with the last segment.
21965 	 */
21966 	if (tcp->tcp_unsent == 0) {
21967 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21968 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21969 
21970 		if (mp) {
21971 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21972 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21973 		} else {
21974 			/*
21975 			 * Couldn't allocate msg.  Pretend we got it out.
21976 			 * Wait for rexmit timeout.
21977 			 */
21978 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21979 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21980 		}
21981 
21982 		/*
21983 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21984 		 * changed.
21985 		 */
21986 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21987 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21988 		}
21989 	} else {
21990 		/*
21991 		 * If tcp->tcp_cork is set, then the data will not get sent,
21992 		 * so we have to check that and unset it first.
21993 		 */
21994 		if (tcp->tcp_cork)
21995 			tcp->tcp_cork = B_FALSE;
21996 		tcp_wput_data(tcp, NULL, B_FALSE);
21997 	}
21998 
21999 	/*
22000 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
22001 	 * is 0, don't update the cache.
22002 	 */
22003 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
22004 		return (0);
22005 
22006 	/*
22007 	 * NOTE: should not update if source routes i.e. if tcp_remote if
22008 	 * different from the destination.
22009 	 */
22010 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22011 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
22012 			return (0);
22013 		}
22014 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22015 		    &ipic);
22016 	} else {
22017 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
22018 		    &tcp->tcp_ip6h->ip6_dst))) {
22019 			return (0);
22020 		}
22021 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22022 		    &ipic);
22023 	}
22024 
22025 	/* Record route attributes in the IRE for use by future connections. */
22026 	if (mp == NULL)
22027 		return (0);
22028 
22029 	/*
22030 	 * We do not have a good algorithm to update ssthresh at this time.
22031 	 * So don't do any update.
22032 	 */
22033 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22034 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22035 
22036 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22037 	return (0);
22038 }
22039 
22040 /*
22041  * Generate a "no listener here" RST in response to an "unknown" segment.
22042  * Note that we are reusing the incoming mp to construct the outgoing
22043  * RST.
22044  */
22045 void
22046 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
22047 {
22048 	uchar_t		*rptr;
22049 	uint32_t	seg_len;
22050 	tcph_t		*tcph;
22051 	uint32_t	seg_seq;
22052 	uint32_t	seg_ack;
22053 	uint_t		flags;
22054 	mblk_t		*ipsec_mp;
22055 	ipha_t 		*ipha;
22056 	ip6_t 		*ip6h;
22057 	boolean_t	mctl_present = B_FALSE;
22058 	boolean_t	check = B_TRUE;
22059 	boolean_t	policy_present;
22060 
22061 	TCP_STAT(tcp_no_listener);
22062 
22063 	ipsec_mp = mp;
22064 
22065 	if (mp->b_datap->db_type == M_CTL) {
22066 		ipsec_in_t *ii;
22067 
22068 		mctl_present = B_TRUE;
22069 		mp = mp->b_cont;
22070 
22071 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22072 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22073 		if (ii->ipsec_in_dont_check) {
22074 			check = B_FALSE;
22075 			if (!ii->ipsec_in_secure) {
22076 				freeb(ipsec_mp);
22077 				mctl_present = B_FALSE;
22078 				ipsec_mp = mp;
22079 			}
22080 		}
22081 	}
22082 
22083 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22084 		policy_present = ipsec_inbound_v4_policy_present;
22085 		ipha = (ipha_t *)mp->b_rptr;
22086 		ip6h = NULL;
22087 	} else {
22088 		policy_present = ipsec_inbound_v6_policy_present;
22089 		ipha = NULL;
22090 		ip6h = (ip6_t *)mp->b_rptr;
22091 	}
22092 
22093 	if (check && policy_present) {
22094 		/*
22095 		 * The conn_t parameter is NULL because we already know
22096 		 * nobody's home.
22097 		 */
22098 		ipsec_mp = ipsec_check_global_policy(
22099 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
22100 		if (ipsec_mp == NULL)
22101 			return;
22102 	}
22103 
22104 
22105 	rptr = mp->b_rptr;
22106 
22107 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22108 	seg_seq = BE32_TO_U32(tcph->th_seq);
22109 	seg_ack = BE32_TO_U32(tcph->th_ack);
22110 	flags = tcph->th_flags[0];
22111 
22112 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22113 	if (flags & TH_RST) {
22114 		freemsg(ipsec_mp);
22115 	} else if (flags & TH_ACK) {
22116 		tcp_xmit_early_reset("no tcp, reset",
22117 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
22118 	} else {
22119 		if (flags & TH_SYN) {
22120 			seg_len++;
22121 		} else {
22122 			/*
22123 			 * Here we violate the RFC.  Note that a normal
22124 			 * TCP will never send a segment without the ACK
22125 			 * flag, except for RST or SYN segment.  This
22126 			 * segment is neither.  Just drop it on the
22127 			 * floor.
22128 			 */
22129 			freemsg(ipsec_mp);
22130 			tcp_rst_unsent++;
22131 			return;
22132 		}
22133 
22134 		tcp_xmit_early_reset("no tcp, reset/ack",
22135 		    ipsec_mp, 0, seg_seq + seg_len,
22136 		    TH_RST | TH_ACK, ip_hdr_len);
22137 	}
22138 }
22139 
22140 /*
22141  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22142  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22143  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22144  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22145  * otherwise it will dup partial mblks.)
22146  * Otherwise, an appropriate ACK packet will be generated.  This
22147  * routine is not usually called to send new data for the first time.  It
22148  * is mostly called out of the timer for retransmits, and to generate ACKs.
22149  *
22150  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22151  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22152  * of the original mblk chain will be returned in *offset and *end_mp.
22153  */
22154 static mblk_t *
22155 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22156     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22157     boolean_t rexmit)
22158 {
22159 	int	data_length;
22160 	int32_t	off = 0;
22161 	uint_t	flags;
22162 	mblk_t	*mp1;
22163 	mblk_t	*mp2;
22164 	uchar_t	*rptr;
22165 	tcph_t	*tcph;
22166 	int32_t	num_sack_blk = 0;
22167 	int32_t	sack_opt_len = 0;
22168 
22169 	/* Allocate for our maximum TCP header + link-level */
22170 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22171 	    BPRI_MED);
22172 	if (!mp1)
22173 		return (NULL);
22174 	data_length = 0;
22175 
22176 	/*
22177 	 * Note that tcp_mss has been adjusted to take into account the
22178 	 * timestamp option if applicable.  Because SACK options do not
22179 	 * appear in every TCP segments and they are of variable lengths,
22180 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22181 	 * the actual segment length when we need to send a segment which
22182 	 * includes SACK options.
22183 	 */
22184 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22185 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22186 		    tcp->tcp_num_sack_blk);
22187 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22188 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22189 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22190 			max_to_send -= sack_opt_len;
22191 	}
22192 
22193 	if (offset != NULL) {
22194 		off = *offset;
22195 		/* We use offset as an indicator that end_mp is not NULL. */
22196 		*end_mp = NULL;
22197 	}
22198 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22199 		/* This could be faster with cooperation from downstream */
22200 		if (mp2 != mp1 && !sendall &&
22201 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22202 		    max_to_send)
22203 			/*
22204 			 * Don't send the next mblk since the whole mblk
22205 			 * does not fit.
22206 			 */
22207 			break;
22208 		mp2->b_cont = dupb(mp);
22209 		mp2 = mp2->b_cont;
22210 		if (!mp2) {
22211 			freemsg(mp1);
22212 			return (NULL);
22213 		}
22214 		mp2->b_rptr += off;
22215 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22216 		    (uintptr_t)INT_MAX);
22217 
22218 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22219 		if (data_length > max_to_send) {
22220 			mp2->b_wptr -= data_length - max_to_send;
22221 			data_length = max_to_send;
22222 			off = mp2->b_wptr - mp->b_rptr;
22223 			break;
22224 		} else {
22225 			off = 0;
22226 		}
22227 	}
22228 	if (offset != NULL) {
22229 		*offset = off;
22230 		*end_mp = mp;
22231 	}
22232 	if (seg_len != NULL) {
22233 		*seg_len = data_length;
22234 	}
22235 
22236 	/* Update the latest receive window size in TCP header. */
22237 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22238 	    tcp->tcp_tcph->th_win);
22239 
22240 	rptr = mp1->b_rptr + tcp_wroff_xtra;
22241 	mp1->b_rptr = rptr;
22242 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22243 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22244 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22245 	U32_TO_ABE32(seq, tcph->th_seq);
22246 
22247 	/*
22248 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22249 	 * that this function was called from tcp_wput_data. Thus, when called
22250 	 * to retransmit data the setting of the PUSH bit may appear some
22251 	 * what random in that it might get set when it should not. This
22252 	 * should not pose any performance issues.
22253 	 */
22254 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22255 	    tcp->tcp_unsent == data_length)) {
22256 		flags = TH_ACK | TH_PUSH;
22257 	} else {
22258 		flags = TH_ACK;
22259 	}
22260 
22261 	if (tcp->tcp_ecn_ok) {
22262 		if (tcp->tcp_ecn_echo_on)
22263 			flags |= TH_ECE;
22264 
22265 		/*
22266 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22267 		 * There is no TCP flow control for non-data segments, and
22268 		 * only data segment is transmitted reliably.
22269 		 */
22270 		if (data_length > 0 && !rexmit) {
22271 			SET_ECT(tcp, rptr);
22272 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22273 				flags |= TH_CWR;
22274 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22275 			}
22276 		}
22277 	}
22278 
22279 	if (tcp->tcp_valid_bits) {
22280 		uint32_t u1;
22281 
22282 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22283 		    seq == tcp->tcp_iss) {
22284 			uchar_t	*wptr;
22285 
22286 			/*
22287 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22288 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22289 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22290 			 * our SYN is not ack'ed but the app closes this
22291 			 * TCP connection.
22292 			 */
22293 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22294 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22295 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22296 
22297 			/*
22298 			 * Tack on the MSS option.  It is always needed
22299 			 * for both active and passive open.
22300 			 *
22301 			 * MSS option value should be interface MTU - MIN
22302 			 * TCP/IP header according to RFC 793 as it means
22303 			 * the maximum segment size TCP can receive.  But
22304 			 * to get around some broken middle boxes/end hosts
22305 			 * out there, we allow the option value to be the
22306 			 * same as the MSS option size on the peer side.
22307 			 * In this way, the other side will not send
22308 			 * anything larger than they can receive.
22309 			 *
22310 			 * Note that for SYN_SENT state, the ndd param
22311 			 * tcp_use_smss_as_mss_opt has no effect as we
22312 			 * don't know the peer's MSS option value. So
22313 			 * the only case we need to take care of is in
22314 			 * SYN_RCVD state, which is done later.
22315 			 */
22316 			wptr = mp1->b_wptr;
22317 			wptr[0] = TCPOPT_MAXSEG;
22318 			wptr[1] = TCPOPT_MAXSEG_LEN;
22319 			wptr += 2;
22320 			u1 = tcp->tcp_if_mtu -
22321 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22322 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22323 			    TCP_MIN_HEADER_LENGTH;
22324 			U16_TO_BE16(u1, wptr);
22325 			mp1->b_wptr = wptr + 2;
22326 			/* Update the offset to cover the additional word */
22327 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22328 
22329 			/*
22330 			 * Note that the following way of filling in
22331 			 * TCP options are not optimal.  Some NOPs can
22332 			 * be saved.  But there is no need at this time
22333 			 * to optimize it.  When it is needed, we will
22334 			 * do it.
22335 			 */
22336 			switch (tcp->tcp_state) {
22337 			case TCPS_SYN_SENT:
22338 				flags = TH_SYN;
22339 
22340 				if (tcp->tcp_snd_ts_ok) {
22341 					uint32_t llbolt = (uint32_t)lbolt;
22342 
22343 					wptr = mp1->b_wptr;
22344 					wptr[0] = TCPOPT_NOP;
22345 					wptr[1] = TCPOPT_NOP;
22346 					wptr[2] = TCPOPT_TSTAMP;
22347 					wptr[3] = TCPOPT_TSTAMP_LEN;
22348 					wptr += 4;
22349 					U32_TO_BE32(llbolt, wptr);
22350 					wptr += 4;
22351 					ASSERT(tcp->tcp_ts_recent == 0);
22352 					U32_TO_BE32(0L, wptr);
22353 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22354 					tcph->th_offset_and_rsrvd[0] +=
22355 					    (3 << 4);
22356 				}
22357 
22358 				/*
22359 				 * Set up all the bits to tell other side
22360 				 * we are ECN capable.
22361 				 */
22362 				if (tcp->tcp_ecn_ok) {
22363 					flags |= (TH_ECE | TH_CWR);
22364 				}
22365 				break;
22366 			case TCPS_SYN_RCVD:
22367 				flags |= TH_SYN;
22368 
22369 				/*
22370 				 * Reset the MSS option value to be SMSS
22371 				 * We should probably add back the bytes
22372 				 * for timestamp option and IPsec.  We
22373 				 * don't do that as this is a workaround
22374 				 * for broken middle boxes/end hosts, it
22375 				 * is better for us to be more cautious.
22376 				 * They may not take these things into
22377 				 * account in their SMSS calculation.  Thus
22378 				 * the peer's calculated SMSS may be smaller
22379 				 * than what it can be.  This should be OK.
22380 				 */
22381 				if (tcp_use_smss_as_mss_opt) {
22382 					u1 = tcp->tcp_mss;
22383 					U16_TO_BE16(u1, wptr);
22384 				}
22385 
22386 				/*
22387 				 * If the other side is ECN capable, reply
22388 				 * that we are also ECN capable.
22389 				 */
22390 				if (tcp->tcp_ecn_ok)
22391 					flags |= TH_ECE;
22392 				break;
22393 			default:
22394 				/*
22395 				 * The above ASSERT() makes sure that this
22396 				 * must be FIN-WAIT-1 state.  Our SYN has
22397 				 * not been ack'ed so retransmit it.
22398 				 */
22399 				flags |= TH_SYN;
22400 				break;
22401 			}
22402 
22403 			if (tcp->tcp_snd_ws_ok) {
22404 				wptr = mp1->b_wptr;
22405 				wptr[0] =  TCPOPT_NOP;
22406 				wptr[1] =  TCPOPT_WSCALE;
22407 				wptr[2] =  TCPOPT_WS_LEN;
22408 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22409 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22410 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22411 			}
22412 
22413 			if (tcp->tcp_snd_sack_ok) {
22414 				wptr = mp1->b_wptr;
22415 				wptr[0] = TCPOPT_NOP;
22416 				wptr[1] = TCPOPT_NOP;
22417 				wptr[2] = TCPOPT_SACK_PERMITTED;
22418 				wptr[3] = TCPOPT_SACK_OK_LEN;
22419 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22420 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22421 			}
22422 
22423 			/* allocb() of adequate mblk assures space */
22424 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22425 			    (uintptr_t)INT_MAX);
22426 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22427 			/*
22428 			 * Get IP set to checksum on our behalf
22429 			 * Include the adjustment for a source route if any.
22430 			 */
22431 			u1 += tcp->tcp_sum;
22432 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22433 			U16_TO_BE16(u1, tcph->th_sum);
22434 			BUMP_MIB(&tcp_mib, tcpOutControl);
22435 		}
22436 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22437 		    (seq + data_length) == tcp->tcp_fss) {
22438 			if (!tcp->tcp_fin_acked) {
22439 				flags |= TH_FIN;
22440 				BUMP_MIB(&tcp_mib, tcpOutControl);
22441 			}
22442 			if (!tcp->tcp_fin_sent) {
22443 				tcp->tcp_fin_sent = B_TRUE;
22444 				switch (tcp->tcp_state) {
22445 				case TCPS_SYN_RCVD:
22446 				case TCPS_ESTABLISHED:
22447 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22448 					break;
22449 				case TCPS_CLOSE_WAIT:
22450 					tcp->tcp_state = TCPS_LAST_ACK;
22451 					break;
22452 				}
22453 				if (tcp->tcp_suna == tcp->tcp_snxt)
22454 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22455 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22456 			}
22457 		}
22458 		/*
22459 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22460 		 * is smaller than seq, u1 will become a very huge value.
22461 		 * So the comparison will fail.  Also note that tcp_urp
22462 		 * should be positive, see RFC 793 page 17.
22463 		 */
22464 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22465 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22466 		    u1 < (uint32_t)(64 * 1024)) {
22467 			flags |= TH_URG;
22468 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22469 			U32_TO_ABE16(u1, tcph->th_urp);
22470 		}
22471 	}
22472 	tcph->th_flags[0] = (uchar_t)flags;
22473 	tcp->tcp_rack = tcp->tcp_rnxt;
22474 	tcp->tcp_rack_cnt = 0;
22475 
22476 	if (tcp->tcp_snd_ts_ok) {
22477 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22478 			uint32_t llbolt = (uint32_t)lbolt;
22479 
22480 			U32_TO_BE32(llbolt,
22481 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22482 			U32_TO_BE32(tcp->tcp_ts_recent,
22483 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22484 		}
22485 	}
22486 
22487 	if (num_sack_blk > 0) {
22488 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22489 		sack_blk_t *tmp;
22490 		int32_t	i;
22491 
22492 		wptr[0] = TCPOPT_NOP;
22493 		wptr[1] = TCPOPT_NOP;
22494 		wptr[2] = TCPOPT_SACK;
22495 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22496 		    sizeof (sack_blk_t);
22497 		wptr += TCPOPT_REAL_SACK_LEN;
22498 
22499 		tmp = tcp->tcp_sack_list;
22500 		for (i = 0; i < num_sack_blk; i++) {
22501 			U32_TO_BE32(tmp[i].begin, wptr);
22502 			wptr += sizeof (tcp_seq);
22503 			U32_TO_BE32(tmp[i].end, wptr);
22504 			wptr += sizeof (tcp_seq);
22505 		}
22506 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22507 	}
22508 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22509 	data_length += (int)(mp1->b_wptr - rptr);
22510 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22511 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22512 	} else {
22513 		ip6_t *ip6 = (ip6_t *)(rptr +
22514 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22515 		    sizeof (ip6i_t) : 0));
22516 
22517 		ip6->ip6_plen = htons(data_length -
22518 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22519 	}
22520 
22521 	/*
22522 	 * Prime pump for IP
22523 	 * Include the adjustment for a source route if any.
22524 	 */
22525 	data_length -= tcp->tcp_ip_hdr_len;
22526 	data_length += tcp->tcp_sum;
22527 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22528 	U16_TO_ABE16(data_length, tcph->th_sum);
22529 	if (tcp->tcp_ip_forward_progress) {
22530 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22531 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22532 		tcp->tcp_ip_forward_progress = B_FALSE;
22533 	}
22534 	return (mp1);
22535 }
22536 
22537 /* This function handles the push timeout. */
22538 static void
22539 tcp_push_timer(void *arg)
22540 {
22541 	conn_t	*connp = (conn_t *)arg;
22542 	tcp_t *tcp = connp->conn_tcp;
22543 
22544 	TCP_DBGSTAT(tcp_push_timer_cnt);
22545 
22546 	ASSERT(tcp->tcp_listener == NULL);
22547 
22548 	tcp->tcp_push_tid = 0;
22549 	if ((tcp->tcp_rcv_list != NULL) &&
22550 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22551 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22552 }
22553 
22554 /*
22555  * This function handles delayed ACK timeout.
22556  */
22557 static void
22558 tcp_ack_timer(void *arg)
22559 {
22560 	conn_t	*connp = (conn_t *)arg;
22561 	tcp_t *tcp = connp->conn_tcp;
22562 	mblk_t *mp;
22563 
22564 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22565 
22566 	tcp->tcp_ack_tid = 0;
22567 
22568 	if (tcp->tcp_fused)
22569 		return;
22570 
22571 	/*
22572 	 * Do not send ACK if there is no outstanding unack'ed data.
22573 	 */
22574 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22575 		return;
22576 	}
22577 
22578 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22579 		/*
22580 		 * Make sure we don't allow deferred ACKs to result in
22581 		 * timer-based ACKing.  If we have held off an ACK
22582 		 * when there was more than an mss here, and the timer
22583 		 * goes off, we have to worry about the possibility
22584 		 * that the sender isn't doing slow-start, or is out
22585 		 * of step with us for some other reason.  We fall
22586 		 * permanently back in the direction of
22587 		 * ACK-every-other-packet as suggested in RFC 1122.
22588 		 */
22589 		if (tcp->tcp_rack_abs_max > 2)
22590 			tcp->tcp_rack_abs_max--;
22591 		tcp->tcp_rack_cur_max = 2;
22592 	}
22593 	mp = tcp_ack_mp(tcp);
22594 
22595 	if (mp != NULL) {
22596 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22597 		BUMP_LOCAL(tcp->tcp_obsegs);
22598 		BUMP_MIB(&tcp_mib, tcpOutAck);
22599 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22600 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22601 	}
22602 }
22603 
22604 
22605 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22606 static mblk_t *
22607 tcp_ack_mp(tcp_t *tcp)
22608 {
22609 	uint32_t	seq_no;
22610 
22611 	/*
22612 	 * There are a few cases to be considered while setting the sequence no.
22613 	 * Essentially, we can come here while processing an unacceptable pkt
22614 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22615 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22616 	 * If we are here for a zero window probe, stick with suna. In all
22617 	 * other cases, we check if suna + swnd encompasses snxt and set
22618 	 * the sequence number to snxt, if so. If snxt falls outside the
22619 	 * window (the receiver probably shrunk its window), we will go with
22620 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22621 	 * receiver.
22622 	 */
22623 	if (tcp->tcp_zero_win_probe) {
22624 		seq_no = tcp->tcp_suna;
22625 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22626 		ASSERT(tcp->tcp_swnd == 0);
22627 		seq_no = tcp->tcp_snxt;
22628 	} else {
22629 		seq_no = SEQ_GT(tcp->tcp_snxt,
22630 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22631 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22632 	}
22633 
22634 	if (tcp->tcp_valid_bits) {
22635 		/*
22636 		 * For the complex case where we have to send some
22637 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22638 		 */
22639 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22640 		    NULL, B_FALSE));
22641 	} else {
22642 		/* Generate a simple ACK */
22643 		int	data_length;
22644 		uchar_t	*rptr;
22645 		tcph_t	*tcph;
22646 		mblk_t	*mp1;
22647 		int32_t	tcp_hdr_len;
22648 		int32_t	tcp_tcp_hdr_len;
22649 		int32_t	num_sack_blk = 0;
22650 		int32_t sack_opt_len;
22651 
22652 		/*
22653 		 * Allocate space for TCP + IP headers
22654 		 * and link-level header
22655 		 */
22656 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22657 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22658 			    tcp->tcp_num_sack_blk);
22659 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22660 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22661 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22662 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22663 		} else {
22664 			tcp_hdr_len = tcp->tcp_hdr_len;
22665 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22666 		}
22667 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22668 		if (!mp1)
22669 			return (NULL);
22670 
22671 		/* Update the latest receive window size in TCP header. */
22672 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22673 		    tcp->tcp_tcph->th_win);
22674 		/* copy in prototype TCP + IP header */
22675 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22676 		mp1->b_rptr = rptr;
22677 		mp1->b_wptr = rptr + tcp_hdr_len;
22678 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22679 
22680 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22681 
22682 		/* Set the TCP sequence number. */
22683 		U32_TO_ABE32(seq_no, tcph->th_seq);
22684 
22685 		/* Set up the TCP flag field. */
22686 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22687 		if (tcp->tcp_ecn_echo_on)
22688 			tcph->th_flags[0] |= TH_ECE;
22689 
22690 		tcp->tcp_rack = tcp->tcp_rnxt;
22691 		tcp->tcp_rack_cnt = 0;
22692 
22693 		/* fill in timestamp option if in use */
22694 		if (tcp->tcp_snd_ts_ok) {
22695 			uint32_t llbolt = (uint32_t)lbolt;
22696 
22697 			U32_TO_BE32(llbolt,
22698 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22699 			U32_TO_BE32(tcp->tcp_ts_recent,
22700 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22701 		}
22702 
22703 		/* Fill in SACK options */
22704 		if (num_sack_blk > 0) {
22705 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22706 			sack_blk_t *tmp;
22707 			int32_t	i;
22708 
22709 			wptr[0] = TCPOPT_NOP;
22710 			wptr[1] = TCPOPT_NOP;
22711 			wptr[2] = TCPOPT_SACK;
22712 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22713 			    sizeof (sack_blk_t);
22714 			wptr += TCPOPT_REAL_SACK_LEN;
22715 
22716 			tmp = tcp->tcp_sack_list;
22717 			for (i = 0; i < num_sack_blk; i++) {
22718 				U32_TO_BE32(tmp[i].begin, wptr);
22719 				wptr += sizeof (tcp_seq);
22720 				U32_TO_BE32(tmp[i].end, wptr);
22721 				wptr += sizeof (tcp_seq);
22722 			}
22723 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22724 			    << 4);
22725 		}
22726 
22727 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22728 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22729 		} else {
22730 			/* Check for ip6i_t header in sticky hdrs */
22731 			ip6_t *ip6 = (ip6_t *)(rptr +
22732 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22733 			    sizeof (ip6i_t) : 0));
22734 
22735 			ip6->ip6_plen = htons(tcp_hdr_len -
22736 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22737 		}
22738 
22739 		/*
22740 		 * Prime pump for checksum calculation in IP.  Include the
22741 		 * adjustment for a source route if any.
22742 		 */
22743 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22744 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22745 		U16_TO_ABE16(data_length, tcph->th_sum);
22746 
22747 		if (tcp->tcp_ip_forward_progress) {
22748 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22749 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22750 			tcp->tcp_ip_forward_progress = B_FALSE;
22751 		}
22752 		return (mp1);
22753 	}
22754 }
22755 
22756 /*
22757  * To create a temporary tcp structure for inserting into bind hash list.
22758  * The parameter is assumed to be in network byte order, ready for use.
22759  */
22760 /* ARGSUSED */
22761 static tcp_t *
22762 tcp_alloc_temp_tcp(in_port_t port)
22763 {
22764 	conn_t	*connp;
22765 	tcp_t	*tcp;
22766 
22767 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22768 	if (connp == NULL)
22769 		return (NULL);
22770 
22771 	tcp = connp->conn_tcp;
22772 
22773 	/*
22774 	 * Only initialize the necessary info in those structures.  Note
22775 	 * that since INADDR_ANY is all 0, we do not need to set
22776 	 * tcp_bound_source to INADDR_ANY here.
22777 	 */
22778 	tcp->tcp_state = TCPS_BOUND;
22779 	tcp->tcp_lport = port;
22780 	tcp->tcp_exclbind = 1;
22781 	tcp->tcp_reserved_port = 1;
22782 
22783 	/* Just for place holding... */
22784 	tcp->tcp_ipversion = IPV4_VERSION;
22785 
22786 	return (tcp);
22787 }
22788 
22789 /*
22790  * To remove a port range specified by lo_port and hi_port from the
22791  * reserved port ranges.  This is one of the three public functions of
22792  * the reserved port interface.  Note that a port range has to be removed
22793  * as a whole.  Ports in a range cannot be removed individually.
22794  *
22795  * Params:
22796  *	in_port_t lo_port: the beginning port of the reserved port range to
22797  *		be deleted.
22798  *	in_port_t hi_port: the ending port of the reserved port range to
22799  *		be deleted.
22800  *
22801  * Return:
22802  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22803  */
22804 boolean_t
22805 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22806 {
22807 	int	i, j;
22808 	int	size;
22809 	tcp_t	**temp_tcp_array;
22810 	tcp_t	*tcp;
22811 
22812 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22813 
22814 	/* First make sure that the port ranage is indeed reserved. */
22815 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22816 		if (tcp_reserved_port[i].lo_port == lo_port) {
22817 			hi_port = tcp_reserved_port[i].hi_port;
22818 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22819 			break;
22820 		}
22821 	}
22822 	if (i == tcp_reserved_port_array_size) {
22823 		rw_exit(&tcp_reserved_port_lock);
22824 		return (B_FALSE);
22825 	}
22826 
22827 	/*
22828 	 * Remove the range from the array.  This simple loop is possible
22829 	 * because port ranges are inserted in ascending order.
22830 	 */
22831 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22832 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22833 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22834 		tcp_reserved_port[j].temp_tcp_array =
22835 		    tcp_reserved_port[j+1].temp_tcp_array;
22836 	}
22837 
22838 	/* Remove all the temporary tcp structures. */
22839 	size = hi_port - lo_port + 1;
22840 	while (size > 0) {
22841 		tcp = temp_tcp_array[size - 1];
22842 		ASSERT(tcp != NULL);
22843 		tcp_bind_hash_remove(tcp);
22844 		CONN_DEC_REF(tcp->tcp_connp);
22845 		size--;
22846 	}
22847 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22848 	tcp_reserved_port_array_size--;
22849 	rw_exit(&tcp_reserved_port_lock);
22850 	return (B_TRUE);
22851 }
22852 
22853 /*
22854  * Macro to remove temporary tcp structure from the bind hash list.  The
22855  * first parameter is the list of tcp to be removed.  The second parameter
22856  * is the number of tcps in the array.
22857  */
22858 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22859 { \
22860 	while ((num) > 0) { \
22861 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22862 		tf_t *tbf; \
22863 		tcp_t *tcpnext; \
22864 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22865 		mutex_enter(&tbf->tf_lock); \
22866 		tcpnext = tcp->tcp_bind_hash; \
22867 		if (tcpnext) { \
22868 			tcpnext->tcp_ptpbhn = \
22869 				tcp->tcp_ptpbhn; \
22870 		} \
22871 		*tcp->tcp_ptpbhn = tcpnext; \
22872 		mutex_exit(&tbf->tf_lock); \
22873 		kmem_free(tcp, sizeof (tcp_t)); \
22874 		(tcp_array)[(num) - 1] = NULL; \
22875 		(num)--; \
22876 	} \
22877 }
22878 
22879 /*
22880  * The public interface for other modules to call to reserve a port range
22881  * in TCP.  The caller passes in how large a port range it wants.  TCP
22882  * will try to find a range and return it via lo_port and hi_port.  This is
22883  * used by NCA's nca_conn_init.
22884  * NCA can only be used in the global zone so this only affects the global
22885  * zone's ports.
22886  *
22887  * Params:
22888  *	int size: the size of the port range to be reserved.
22889  *	in_port_t *lo_port (referenced): returns the beginning port of the
22890  *		reserved port range added.
22891  *	in_port_t *hi_port (referenced): returns the ending port of the
22892  *		reserved port range added.
22893  *
22894  * Return:
22895  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22896  */
22897 boolean_t
22898 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22899 {
22900 	tcp_t		*tcp;
22901 	tcp_t		*tmp_tcp;
22902 	tcp_t		**temp_tcp_array;
22903 	tf_t		*tbf;
22904 	in_port_t	net_port;
22905 	in_port_t	port;
22906 	int32_t		cur_size;
22907 	int		i, j;
22908 	boolean_t	used;
22909 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22910 	zoneid_t	zoneid = GLOBAL_ZONEID;
22911 
22912 	/* Sanity check. */
22913 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22914 		return (B_FALSE);
22915 	}
22916 
22917 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22918 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22919 		rw_exit(&tcp_reserved_port_lock);
22920 		return (B_FALSE);
22921 	}
22922 
22923 	/*
22924 	 * Find the starting port to try.  Since the port ranges are ordered
22925 	 * in the reserved port array, we can do a simple search here.
22926 	 */
22927 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22928 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22929 	for (i = 0; i < tcp_reserved_port_array_size;
22930 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22931 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22932 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22933 			break;
22934 		}
22935 	}
22936 	/* No available port range. */
22937 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22938 		rw_exit(&tcp_reserved_port_lock);
22939 		return (B_FALSE);
22940 	}
22941 
22942 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22943 	if (temp_tcp_array == NULL) {
22944 		rw_exit(&tcp_reserved_port_lock);
22945 		return (B_FALSE);
22946 	}
22947 
22948 	/* Go thru the port range to see if some ports are already bound. */
22949 	for (port = *lo_port, cur_size = 0;
22950 	    cur_size < size && port <= *hi_port;
22951 	    cur_size++, port++) {
22952 		used = B_FALSE;
22953 		net_port = htons(port);
22954 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22955 		mutex_enter(&tbf->tf_lock);
22956 		for (tcp = tbf->tf_tcp; tcp != NULL;
22957 		    tcp = tcp->tcp_bind_hash) {
22958 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22959 			    net_port == tcp->tcp_lport) {
22960 				/*
22961 				 * A port is already bound.  Search again
22962 				 * starting from port + 1.  Release all
22963 				 * temporary tcps.
22964 				 */
22965 				mutex_exit(&tbf->tf_lock);
22966 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22967 				*lo_port = port + 1;
22968 				cur_size = -1;
22969 				used = B_TRUE;
22970 				break;
22971 			}
22972 		}
22973 		if (!used) {
22974 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22975 				/*
22976 				 * Allocation failure.  Just fail the request.
22977 				 * Need to remove all those temporary tcp
22978 				 * structures.
22979 				 */
22980 				mutex_exit(&tbf->tf_lock);
22981 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22982 				rw_exit(&tcp_reserved_port_lock);
22983 				kmem_free(temp_tcp_array,
22984 				    (hi_port - lo_port + 1) *
22985 				    sizeof (tcp_t *));
22986 				return (B_FALSE);
22987 			}
22988 			temp_tcp_array[cur_size] = tmp_tcp;
22989 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22990 			mutex_exit(&tbf->tf_lock);
22991 		}
22992 	}
22993 
22994 	/*
22995 	 * The current range is not large enough.  We can actually do another
22996 	 * search if this search is done between 2 reserved port ranges.  But
22997 	 * for first release, we just stop here and return saying that no port
22998 	 * range is available.
22999 	 */
23000 	if (cur_size < size) {
23001 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
23002 		rw_exit(&tcp_reserved_port_lock);
23003 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
23004 		return (B_FALSE);
23005 	}
23006 	*hi_port = port - 1;
23007 
23008 	/*
23009 	 * Insert range into array in ascending order.  Since this function
23010 	 * must not be called often, we choose to use the simplest method.
23011 	 * The above array should not consume excessive stack space as
23012 	 * the size must be very small.  If in future releases, we find
23013 	 * that we should provide more reserved port ranges, this function
23014 	 * has to be modified to be more efficient.
23015 	 */
23016 	if (tcp_reserved_port_array_size == 0) {
23017 		tcp_reserved_port[0].lo_port = *lo_port;
23018 		tcp_reserved_port[0].hi_port = *hi_port;
23019 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
23020 	} else {
23021 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
23022 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
23023 				tmp_ports[j].lo_port = *lo_port;
23024 				tmp_ports[j].hi_port = *hi_port;
23025 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23026 				j++;
23027 			}
23028 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
23029 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
23030 			tmp_ports[j].temp_tcp_array =
23031 			    tcp_reserved_port[i].temp_tcp_array;
23032 		}
23033 		if (j == i) {
23034 			tmp_ports[j].lo_port = *lo_port;
23035 			tmp_ports[j].hi_port = *hi_port;
23036 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23037 		}
23038 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
23039 	}
23040 	tcp_reserved_port_array_size++;
23041 	rw_exit(&tcp_reserved_port_lock);
23042 	return (B_TRUE);
23043 }
23044 
23045 /*
23046  * Check to see if a port is in any reserved port range.
23047  *
23048  * Params:
23049  *	in_port_t port: the port to be verified.
23050  *
23051  * Return:
23052  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23053  */
23054 boolean_t
23055 tcp_reserved_port_check(in_port_t port)
23056 {
23057 	int i;
23058 
23059 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23060 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23061 		if (port >= tcp_reserved_port[i].lo_port ||
23062 		    port <= tcp_reserved_port[i].hi_port) {
23063 			rw_exit(&tcp_reserved_port_lock);
23064 			return (B_TRUE);
23065 		}
23066 	}
23067 	rw_exit(&tcp_reserved_port_lock);
23068 	return (B_FALSE);
23069 }
23070 
23071 /*
23072  * To list all reserved port ranges.  This is the function to handle
23073  * ndd tcp_reserved_port_list.
23074  */
23075 /* ARGSUSED */
23076 static int
23077 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23078 {
23079 	int i;
23080 
23081 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23082 	if (tcp_reserved_port_array_size > 0)
23083 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23084 	else
23085 		(void) mi_mpprintf(mp, "No port is reserved.");
23086 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23087 		(void) mi_mpprintf(mp, "%d-%d",
23088 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
23089 	}
23090 	rw_exit(&tcp_reserved_port_lock);
23091 	return (0);
23092 }
23093 
23094 /*
23095  * Hash list insertion routine for tcp_t structures.
23096  * Inserts entries with the ones bound to a specific IP address first
23097  * followed by those bound to INADDR_ANY.
23098  */
23099 static void
23100 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23101 {
23102 	tcp_t	**tcpp;
23103 	tcp_t	*tcpnext;
23104 
23105 	if (tcp->tcp_ptpbhn != NULL) {
23106 		ASSERT(!caller_holds_lock);
23107 		tcp_bind_hash_remove(tcp);
23108 	}
23109 	tcpp = &tbf->tf_tcp;
23110 	if (!caller_holds_lock) {
23111 		mutex_enter(&tbf->tf_lock);
23112 	} else {
23113 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23114 	}
23115 	tcpnext = tcpp[0];
23116 	if (tcpnext) {
23117 		/*
23118 		 * If the new tcp bound to the INADDR_ANY address
23119 		 * and the first one in the list is not bound to
23120 		 * INADDR_ANY we skip all entries until we find the
23121 		 * first one bound to INADDR_ANY.
23122 		 * This makes sure that applications binding to a
23123 		 * specific address get preference over those binding to
23124 		 * INADDR_ANY.
23125 		 */
23126 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23127 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23128 			while ((tcpnext = tcpp[0]) != NULL &&
23129 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23130 				tcpp = &(tcpnext->tcp_bind_hash);
23131 			if (tcpnext)
23132 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23133 		} else
23134 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23135 	}
23136 	tcp->tcp_bind_hash = tcpnext;
23137 	tcp->tcp_ptpbhn = tcpp;
23138 	tcpp[0] = tcp;
23139 	if (!caller_holds_lock)
23140 		mutex_exit(&tbf->tf_lock);
23141 }
23142 
23143 /*
23144  * Hash list removal routine for tcp_t structures.
23145  */
23146 static void
23147 tcp_bind_hash_remove(tcp_t *tcp)
23148 {
23149 	tcp_t	*tcpnext;
23150 	kmutex_t *lockp;
23151 
23152 	if (tcp->tcp_ptpbhn == NULL)
23153 		return;
23154 
23155 	/*
23156 	 * Extract the lock pointer in case there are concurrent
23157 	 * hash_remove's for this instance.
23158 	 */
23159 	ASSERT(tcp->tcp_lport != 0);
23160 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23161 
23162 	ASSERT(lockp != NULL);
23163 	mutex_enter(lockp);
23164 	if (tcp->tcp_ptpbhn) {
23165 		tcpnext = tcp->tcp_bind_hash;
23166 		if (tcpnext) {
23167 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23168 			tcp->tcp_bind_hash = NULL;
23169 		}
23170 		*tcp->tcp_ptpbhn = tcpnext;
23171 		tcp->tcp_ptpbhn = NULL;
23172 	}
23173 	mutex_exit(lockp);
23174 }
23175 
23176 
23177 /*
23178  * Hash list lookup routine for tcp_t structures.
23179  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23180  */
23181 static tcp_t *
23182 tcp_acceptor_hash_lookup(t_uscalar_t id)
23183 {
23184 	tf_t	*tf;
23185 	tcp_t	*tcp;
23186 
23187 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23188 	mutex_enter(&tf->tf_lock);
23189 	for (tcp = tf->tf_tcp; tcp != NULL;
23190 	    tcp = tcp->tcp_acceptor_hash) {
23191 		if (tcp->tcp_acceptor_id == id) {
23192 			CONN_INC_REF(tcp->tcp_connp);
23193 			mutex_exit(&tf->tf_lock);
23194 			return (tcp);
23195 		}
23196 	}
23197 	mutex_exit(&tf->tf_lock);
23198 	return (NULL);
23199 }
23200 
23201 
23202 /*
23203  * Hash list insertion routine for tcp_t structures.
23204  */
23205 void
23206 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23207 {
23208 	tf_t	*tf;
23209 	tcp_t	**tcpp;
23210 	tcp_t	*tcpnext;
23211 
23212 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23213 
23214 	if (tcp->tcp_ptpahn != NULL)
23215 		tcp_acceptor_hash_remove(tcp);
23216 	tcpp = &tf->tf_tcp;
23217 	mutex_enter(&tf->tf_lock);
23218 	tcpnext = tcpp[0];
23219 	if (tcpnext)
23220 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23221 	tcp->tcp_acceptor_hash = tcpnext;
23222 	tcp->tcp_ptpahn = tcpp;
23223 	tcpp[0] = tcp;
23224 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23225 	mutex_exit(&tf->tf_lock);
23226 }
23227 
23228 /*
23229  * Hash list removal routine for tcp_t structures.
23230  */
23231 static void
23232 tcp_acceptor_hash_remove(tcp_t *tcp)
23233 {
23234 	tcp_t	*tcpnext;
23235 	kmutex_t *lockp;
23236 
23237 	/*
23238 	 * Extract the lock pointer in case there are concurrent
23239 	 * hash_remove's for this instance.
23240 	 */
23241 	lockp = tcp->tcp_acceptor_lockp;
23242 
23243 	if (tcp->tcp_ptpahn == NULL)
23244 		return;
23245 
23246 	ASSERT(lockp != NULL);
23247 	mutex_enter(lockp);
23248 	if (tcp->tcp_ptpahn) {
23249 		tcpnext = tcp->tcp_acceptor_hash;
23250 		if (tcpnext) {
23251 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23252 			tcp->tcp_acceptor_hash = NULL;
23253 		}
23254 		*tcp->tcp_ptpahn = tcpnext;
23255 		tcp->tcp_ptpahn = NULL;
23256 	}
23257 	mutex_exit(lockp);
23258 	tcp->tcp_acceptor_lockp = NULL;
23259 }
23260 
23261 /* ARGSUSED */
23262 static int
23263 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
23264 {
23265 	int error = 0;
23266 	int retval;
23267 	char *end;
23268 
23269 	tcp_hsp_t *hsp;
23270 	tcp_hsp_t *hspprev;
23271 
23272 	ipaddr_t addr = 0;		/* Address we're looking for */
23273 	in6_addr_t v6addr;		/* Address we're looking for */
23274 	uint32_t hash;			/* Hash of that address */
23275 
23276 	/*
23277 	 * If the following variables are still zero after parsing the input
23278 	 * string, the user didn't specify them and we don't change them in
23279 	 * the HSP.
23280 	 */
23281 
23282 	ipaddr_t mask = 0;		/* Subnet mask */
23283 	in6_addr_t v6mask;
23284 	long sendspace = 0;		/* Send buffer size */
23285 	long recvspace = 0;		/* Receive buffer size */
23286 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
23287 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
23288 
23289 	rw_enter(&tcp_hsp_lock, RW_WRITER);
23290 
23291 	/* Parse and validate address */
23292 	if (af == AF_INET) {
23293 		retval = inet_pton(af, value, &addr);
23294 		if (retval == 1)
23295 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
23296 	} else if (af == AF_INET6) {
23297 		retval = inet_pton(af, value, &v6addr);
23298 	} else {
23299 		error = EINVAL;
23300 		goto done;
23301 	}
23302 	if (retval == 0) {
23303 		error = EINVAL;
23304 		goto done;
23305 	}
23306 
23307 	while ((*value) && *value != ' ')
23308 		value++;
23309 
23310 	/* Parse individual keywords, set variables if found */
23311 	while (*value) {
23312 		/* Skip leading blanks */
23313 
23314 		while (*value == ' ' || *value == '\t')
23315 			value++;
23316 
23317 		/* If at end of string, we're done */
23318 
23319 		if (!*value)
23320 			break;
23321 
23322 		/* We have a word, figure out what it is */
23323 
23324 		if (strncmp("mask", value, 4) == 0) {
23325 			value += 4;
23326 			while (*value == ' ' || *value == '\t')
23327 				value++;
23328 			/* Parse subnet mask */
23329 			if (af == AF_INET) {
23330 				retval = inet_pton(af, value, &mask);
23331 				if (retval == 1) {
23332 					V4MASK_TO_V6(mask, v6mask);
23333 				}
23334 			} else if (af == AF_INET6) {
23335 				retval = inet_pton(af, value, &v6mask);
23336 			}
23337 			if (retval != 1) {
23338 				error = EINVAL;
23339 				goto done;
23340 			}
23341 			while ((*value) && *value != ' ')
23342 				value++;
23343 		} else if (strncmp("sendspace", value, 9) == 0) {
23344 			value += 9;
23345 
23346 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23347 			    sendspace < TCP_XMIT_HIWATER ||
23348 			    sendspace >= (1L<<30)) {
23349 				error = EINVAL;
23350 				goto done;
23351 			}
23352 			value = end;
23353 		} else if (strncmp("recvspace", value, 9) == 0) {
23354 			value += 9;
23355 
23356 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23357 			    recvspace < TCP_RECV_HIWATER ||
23358 			    recvspace >= (1L<<30)) {
23359 				error = EINVAL;
23360 				goto done;
23361 			}
23362 			value = end;
23363 		} else if (strncmp("timestamp", value, 9) == 0) {
23364 			value += 9;
23365 
23366 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23367 			    timestamp < 0 || timestamp > 1) {
23368 				error = EINVAL;
23369 				goto done;
23370 			}
23371 
23372 			/*
23373 			 * We increment timestamp so we know it's been set;
23374 			 * this is undone when we put it in the HSP
23375 			 */
23376 			timestamp++;
23377 			value = end;
23378 		} else if (strncmp("delete", value, 6) == 0) {
23379 			value += 6;
23380 			delete = B_TRUE;
23381 		} else {
23382 			error = EINVAL;
23383 			goto done;
23384 		}
23385 	}
23386 
23387 	/* Hash address for lookup */
23388 
23389 	hash = TCP_HSP_HASH(addr);
23390 
23391 	if (delete) {
23392 		/*
23393 		 * Note that deletes don't return an error if the thing
23394 		 * we're trying to delete isn't there.
23395 		 */
23396 		if (tcp_hsp_hash == NULL)
23397 			goto done;
23398 		hsp = tcp_hsp_hash[hash];
23399 
23400 		if (hsp) {
23401 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23402 			    &v6addr)) {
23403 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23404 				mi_free((char *)hsp);
23405 			} else {
23406 				hspprev = hsp;
23407 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23408 					if (IN6_ARE_ADDR_EQUAL(
23409 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23410 						hspprev->tcp_hsp_next =
23411 						    hsp->tcp_hsp_next;
23412 						mi_free((char *)hsp);
23413 						break;
23414 					}
23415 					hspprev = hsp;
23416 				}
23417 			}
23418 		}
23419 	} else {
23420 		/*
23421 		 * We're adding/modifying an HSP.  If we haven't already done
23422 		 * so, allocate the hash table.
23423 		 */
23424 
23425 		if (!tcp_hsp_hash) {
23426 			tcp_hsp_hash = (tcp_hsp_t **)
23427 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23428 			if (!tcp_hsp_hash) {
23429 				error = EINVAL;
23430 				goto done;
23431 			}
23432 		}
23433 
23434 		/* Get head of hash chain */
23435 
23436 		hsp = tcp_hsp_hash[hash];
23437 
23438 		/* Try to find pre-existing hsp on hash chain */
23439 		/* Doesn't handle CIDR prefixes. */
23440 		while (hsp) {
23441 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23442 				break;
23443 			hsp = hsp->tcp_hsp_next;
23444 		}
23445 
23446 		/*
23447 		 * If we didn't, create one with default values and put it
23448 		 * at head of hash chain
23449 		 */
23450 
23451 		if (!hsp) {
23452 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23453 			if (!hsp) {
23454 				error = EINVAL;
23455 				goto done;
23456 			}
23457 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23458 			tcp_hsp_hash[hash] = hsp;
23459 		}
23460 
23461 		/* Set values that the user asked us to change */
23462 
23463 		hsp->tcp_hsp_addr_v6 = v6addr;
23464 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23465 			hsp->tcp_hsp_vers = IPV4_VERSION;
23466 		else
23467 			hsp->tcp_hsp_vers = IPV6_VERSION;
23468 		hsp->tcp_hsp_subnet_v6 = v6mask;
23469 		if (sendspace > 0)
23470 			hsp->tcp_hsp_sendspace = sendspace;
23471 		if (recvspace > 0)
23472 			hsp->tcp_hsp_recvspace = recvspace;
23473 		if (timestamp > 0)
23474 			hsp->tcp_hsp_tstamp = timestamp - 1;
23475 	}
23476 
23477 done:
23478 	rw_exit(&tcp_hsp_lock);
23479 	return (error);
23480 }
23481 
23482 /* Set callback routine passed to nd_load by tcp_param_register. */
23483 /* ARGSUSED */
23484 static int
23485 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23486 {
23487 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23488 }
23489 /* ARGSUSED */
23490 static int
23491 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23492     cred_t *cr)
23493 {
23494 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23495 }
23496 
23497 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23498 /* ARGSUSED */
23499 static int
23500 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23501 {
23502 	tcp_hsp_t *hsp;
23503 	int i;
23504 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23505 
23506 	rw_enter(&tcp_hsp_lock, RW_READER);
23507 	(void) mi_mpprintf(mp,
23508 	    "Hash HSP     " MI_COL_HDRPAD_STR
23509 	    "Address         Subnet Mask     Send       Receive    TStamp");
23510 	if (tcp_hsp_hash) {
23511 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23512 			hsp = tcp_hsp_hash[i];
23513 			while (hsp) {
23514 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23515 					(void) inet_ntop(AF_INET,
23516 					    &hsp->tcp_hsp_addr,
23517 					    addrbuf, sizeof (addrbuf));
23518 					(void) inet_ntop(AF_INET,
23519 					    &hsp->tcp_hsp_subnet,
23520 					    subnetbuf, sizeof (subnetbuf));
23521 				} else {
23522 					(void) inet_ntop(AF_INET6,
23523 					    &hsp->tcp_hsp_addr_v6,
23524 					    addrbuf, sizeof (addrbuf));
23525 					(void) inet_ntop(AF_INET6,
23526 					    &hsp->tcp_hsp_subnet_v6,
23527 					    subnetbuf, sizeof (subnetbuf));
23528 				}
23529 				(void) mi_mpprintf(mp,
23530 				    " %03d " MI_COL_PTRFMT_STR
23531 				    "%s %s %010d %010d      %d",
23532 				    i,
23533 				    (void *)hsp,
23534 				    addrbuf,
23535 				    subnetbuf,
23536 				    hsp->tcp_hsp_sendspace,
23537 				    hsp->tcp_hsp_recvspace,
23538 				    hsp->tcp_hsp_tstamp);
23539 
23540 				hsp = hsp->tcp_hsp_next;
23541 			}
23542 		}
23543 	}
23544 	rw_exit(&tcp_hsp_lock);
23545 	return (0);
23546 }
23547 
23548 
23549 /* Data for fast netmask macro used by tcp_hsp_lookup */
23550 
23551 static ipaddr_t netmasks[] = {
23552 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23553 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23554 };
23555 
23556 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23557 
23558 /*
23559  * XXX This routine should go away and instead we should use the metrics
23560  * associated with the routes to determine the default sndspace and rcvspace.
23561  */
23562 static tcp_hsp_t *
23563 tcp_hsp_lookup(ipaddr_t addr)
23564 {
23565 	tcp_hsp_t *hsp = NULL;
23566 
23567 	/* Quick check without acquiring the lock. */
23568 	if (tcp_hsp_hash == NULL)
23569 		return (NULL);
23570 
23571 	rw_enter(&tcp_hsp_lock, RW_READER);
23572 
23573 	/* This routine finds the best-matching HSP for address addr. */
23574 
23575 	if (tcp_hsp_hash) {
23576 		int i;
23577 		ipaddr_t srchaddr;
23578 		tcp_hsp_t *hsp_net;
23579 
23580 		/* We do three passes: host, network, and subnet. */
23581 
23582 		srchaddr = addr;
23583 
23584 		for (i = 1; i <= 3; i++) {
23585 			/* Look for exact match on srchaddr */
23586 
23587 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23588 			while (hsp) {
23589 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23590 				    hsp->tcp_hsp_addr == srchaddr)
23591 					break;
23592 				hsp = hsp->tcp_hsp_next;
23593 			}
23594 			ASSERT(hsp == NULL ||
23595 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23596 
23597 			/*
23598 			 * If this is the first pass:
23599 			 *   If we found a match, great, return it.
23600 			 *   If not, search for the network on the second pass.
23601 			 */
23602 
23603 			if (i == 1)
23604 				if (hsp)
23605 					break;
23606 				else
23607 				{
23608 					srchaddr = addr & netmask(addr);
23609 					continue;
23610 				}
23611 
23612 			/*
23613 			 * If this is the second pass:
23614 			 *   If we found a match, but there's a subnet mask,
23615 			 *    save the match but try again using the subnet
23616 			 *    mask on the third pass.
23617 			 *   Otherwise, return whatever we found.
23618 			 */
23619 
23620 			if (i == 2) {
23621 				if (hsp && hsp->tcp_hsp_subnet) {
23622 					hsp_net = hsp;
23623 					srchaddr = addr & hsp->tcp_hsp_subnet;
23624 					continue;
23625 				} else {
23626 					break;
23627 				}
23628 			}
23629 
23630 			/*
23631 			 * This must be the third pass.  If we didn't find
23632 			 * anything, return the saved network HSP instead.
23633 			 */
23634 
23635 			if (!hsp)
23636 				hsp = hsp_net;
23637 		}
23638 	}
23639 
23640 	rw_exit(&tcp_hsp_lock);
23641 	return (hsp);
23642 }
23643 
23644 /*
23645  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23646  * match lookup.
23647  */
23648 static tcp_hsp_t *
23649 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23650 {
23651 	tcp_hsp_t *hsp = NULL;
23652 
23653 	/* Quick check without acquiring the lock. */
23654 	if (tcp_hsp_hash == NULL)
23655 		return (NULL);
23656 
23657 	rw_enter(&tcp_hsp_lock, RW_READER);
23658 
23659 	/* This routine finds the best-matching HSP for address addr. */
23660 
23661 	if (tcp_hsp_hash) {
23662 		int i;
23663 		in6_addr_t v6srchaddr;
23664 		tcp_hsp_t *hsp_net;
23665 
23666 		/* We do three passes: host, network, and subnet. */
23667 
23668 		v6srchaddr = *v6addr;
23669 
23670 		for (i = 1; i <= 3; i++) {
23671 			/* Look for exact match on srchaddr */
23672 
23673 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23674 			    V4_PART_OF_V6(v6srchaddr))];
23675 			while (hsp) {
23676 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23677 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23678 				    &v6srchaddr))
23679 					break;
23680 				hsp = hsp->tcp_hsp_next;
23681 			}
23682 
23683 			/*
23684 			 * If this is the first pass:
23685 			 *   If we found a match, great, return it.
23686 			 *   If not, search for the network on the second pass.
23687 			 */
23688 
23689 			if (i == 1)
23690 				if (hsp)
23691 					break;
23692 				else {
23693 					/* Assume a 64 bit mask */
23694 					v6srchaddr.s6_addr32[0] =
23695 					    v6addr->s6_addr32[0];
23696 					v6srchaddr.s6_addr32[1] =
23697 					    v6addr->s6_addr32[1];
23698 					v6srchaddr.s6_addr32[2] = 0;
23699 					v6srchaddr.s6_addr32[3] = 0;
23700 					continue;
23701 				}
23702 
23703 			/*
23704 			 * If this is the second pass:
23705 			 *   If we found a match, but there's a subnet mask,
23706 			 *    save the match but try again using the subnet
23707 			 *    mask on the third pass.
23708 			 *   Otherwise, return whatever we found.
23709 			 */
23710 
23711 			if (i == 2) {
23712 				ASSERT(hsp == NULL ||
23713 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23714 				if (hsp &&
23715 				    !IN6_IS_ADDR_UNSPECIFIED(
23716 				    &hsp->tcp_hsp_subnet_v6)) {
23717 					hsp_net = hsp;
23718 					V6_MASK_COPY(*v6addr,
23719 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23720 					continue;
23721 				} else {
23722 					break;
23723 				}
23724 			}
23725 
23726 			/*
23727 			 * This must be the third pass.  If we didn't find
23728 			 * anything, return the saved network HSP instead.
23729 			 */
23730 
23731 			if (!hsp)
23732 				hsp = hsp_net;
23733 		}
23734 	}
23735 
23736 	rw_exit(&tcp_hsp_lock);
23737 	return (hsp);
23738 }
23739 
23740 /*
23741  * Type three generator adapted from the random() function in 4.4 BSD:
23742  */
23743 
23744 /*
23745  * Copyright (c) 1983, 1993
23746  *	The Regents of the University of California.  All rights reserved.
23747  *
23748  * Redistribution and use in source and binary forms, with or without
23749  * modification, are permitted provided that the following conditions
23750  * are met:
23751  * 1. Redistributions of source code must retain the above copyright
23752  *    notice, this list of conditions and the following disclaimer.
23753  * 2. Redistributions in binary form must reproduce the above copyright
23754  *    notice, this list of conditions and the following disclaimer in the
23755  *    documentation and/or other materials provided with the distribution.
23756  * 3. All advertising materials mentioning features or use of this software
23757  *    must display the following acknowledgement:
23758  *	This product includes software developed by the University of
23759  *	California, Berkeley and its contributors.
23760  * 4. Neither the name of the University nor the names of its contributors
23761  *    may be used to endorse or promote products derived from this software
23762  *    without specific prior written permission.
23763  *
23764  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23765  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23766  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23767  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23768  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23769  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23770  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23771  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23772  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23773  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23774  * SUCH DAMAGE.
23775  */
23776 
23777 /* Type 3 -- x**31 + x**3 + 1 */
23778 #define	DEG_3		31
23779 #define	SEP_3		3
23780 
23781 
23782 /* Protected by tcp_random_lock */
23783 static int tcp_randtbl[DEG_3 + 1];
23784 
23785 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23786 static int *tcp_random_rptr = &tcp_randtbl[1];
23787 
23788 static int *tcp_random_state = &tcp_randtbl[1];
23789 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23790 
23791 kmutex_t tcp_random_lock;
23792 
23793 void
23794 tcp_random_init(void)
23795 {
23796 	int i;
23797 	hrtime_t hrt;
23798 	time_t wallclock;
23799 	uint64_t result;
23800 
23801 	/*
23802 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23803 	 * a longlong, which may contain resolution down to nanoseconds.
23804 	 * The current time will either be a 32-bit or a 64-bit quantity.
23805 	 * XOR the two together in a 64-bit result variable.
23806 	 * Convert the result to a 32-bit value by multiplying the high-order
23807 	 * 32-bits by the low-order 32-bits.
23808 	 */
23809 
23810 	hrt = gethrtime();
23811 	(void) drv_getparm(TIME, &wallclock);
23812 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23813 	mutex_enter(&tcp_random_lock);
23814 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23815 	    (result & 0xffffffff);
23816 
23817 	for (i = 1; i < DEG_3; i++)
23818 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23819 			+ 12345;
23820 	tcp_random_fptr = &tcp_random_state[SEP_3];
23821 	tcp_random_rptr = &tcp_random_state[0];
23822 	mutex_exit(&tcp_random_lock);
23823 	for (i = 0; i < 10 * DEG_3; i++)
23824 		(void) tcp_random();
23825 }
23826 
23827 /*
23828  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23829  * This range is selected to be approximately centered on TCP_ISS / 2,
23830  * and easy to compute. We get this value by generating a 32-bit random
23831  * number, selecting out the high-order 17 bits, and then adding one so
23832  * that we never return zero.
23833  */
23834 int
23835 tcp_random(void)
23836 {
23837 	int i;
23838 
23839 	mutex_enter(&tcp_random_lock);
23840 	*tcp_random_fptr += *tcp_random_rptr;
23841 
23842 	/*
23843 	 * The high-order bits are more random than the low-order bits,
23844 	 * so we select out the high-order 17 bits and add one so that
23845 	 * we never return zero.
23846 	 */
23847 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23848 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23849 		tcp_random_fptr = tcp_random_state;
23850 		++tcp_random_rptr;
23851 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23852 		tcp_random_rptr = tcp_random_state;
23853 
23854 	mutex_exit(&tcp_random_lock);
23855 	return (i);
23856 }
23857 
23858 /*
23859  * XXX This will go away when TPI is extended to send
23860  * info reqs to sockfs/timod .....
23861  * Given a queue, set the max packet size for the write
23862  * side of the queue below stream head.  This value is
23863  * cached on the stream head.
23864  * Returns 1 on success, 0 otherwise.
23865  */
23866 static int
23867 setmaxps(queue_t *q, int maxpsz)
23868 {
23869 	struct stdata	*stp;
23870 	queue_t		*wq;
23871 	stp = STREAM(q);
23872 
23873 	/*
23874 	 * At this point change of a queue parameter is not allowed
23875 	 * when a multiplexor is sitting on top.
23876 	 */
23877 	if (stp->sd_flag & STPLEX)
23878 		return (0);
23879 
23880 	claimstr(stp->sd_wrq);
23881 	wq = stp->sd_wrq->q_next;
23882 	ASSERT(wq != NULL);
23883 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23884 	releasestr(stp->sd_wrq);
23885 	return (1);
23886 }
23887 
23888 static int
23889 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23890     int *t_errorp, int *sys_errorp)
23891 {
23892 	int error;
23893 	int is_absreq_failure;
23894 	t_scalar_t *opt_lenp;
23895 	t_scalar_t opt_offset;
23896 	int prim_type;
23897 	struct T_conn_req *tcreqp;
23898 	struct T_conn_res *tcresp;
23899 	cred_t *cr;
23900 
23901 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23902 
23903 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23904 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23905 	    prim_type == T_CONN_RES);
23906 
23907 	switch (prim_type) {
23908 	case T_CONN_REQ:
23909 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23910 		opt_offset = tcreqp->OPT_offset;
23911 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23912 		break;
23913 	case O_T_CONN_RES:
23914 	case T_CONN_RES:
23915 		tcresp = (struct T_conn_res *)mp->b_rptr;
23916 		opt_offset = tcresp->OPT_offset;
23917 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23918 		break;
23919 	}
23920 
23921 	*t_errorp = 0;
23922 	*sys_errorp = 0;
23923 	*do_disconnectp = 0;
23924 
23925 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23926 	    opt_offset, cr, &tcp_opt_obj,
23927 	    NULL, &is_absreq_failure);
23928 
23929 	switch (error) {
23930 	case  0:		/* no error */
23931 		ASSERT(is_absreq_failure == 0);
23932 		return (0);
23933 	case ENOPROTOOPT:
23934 		*t_errorp = TBADOPT;
23935 		break;
23936 	case EACCES:
23937 		*t_errorp = TACCES;
23938 		break;
23939 	default:
23940 		*t_errorp = TSYSERR; *sys_errorp = error;
23941 		break;
23942 	}
23943 	if (is_absreq_failure != 0) {
23944 		/*
23945 		 * The connection request should get the local ack
23946 		 * T_OK_ACK and then a T_DISCON_IND.
23947 		 */
23948 		*do_disconnectp = 1;
23949 	}
23950 	return (-1);
23951 }
23952 
23953 /*
23954  * Split this function out so that if the secret changes, I'm okay.
23955  *
23956  * Initialize the tcp_iss_cookie and tcp_iss_key.
23957  */
23958 
23959 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23960 
23961 static void
23962 tcp_iss_key_init(uint8_t *phrase, int len)
23963 {
23964 	struct {
23965 		int32_t current_time;
23966 		uint32_t randnum;
23967 		uint16_t pad;
23968 		uint8_t ether[6];
23969 		uint8_t passwd[PASSWD_SIZE];
23970 	} tcp_iss_cookie;
23971 	time_t t;
23972 
23973 	/*
23974 	 * Start with the current absolute time.
23975 	 */
23976 	(void) drv_getparm(TIME, &t);
23977 	tcp_iss_cookie.current_time = t;
23978 
23979 	/*
23980 	 * XXX - Need a more random number per RFC 1750, not this crap.
23981 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23982 	 */
23983 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23984 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23985 
23986 	/*
23987 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23988 	 * as a good template.
23989 	 */
23990 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23991 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23992 
23993 	/*
23994 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23995 	 */
23996 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23997 
23998 	/*
23999 	 * See 4010593 if this section becomes a problem again,
24000 	 * but the local ethernet address is useful here.
24001 	 */
24002 	(void) localetheraddr(NULL,
24003 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24004 
24005 	/*
24006 	 * Hash 'em all together.  The MD5Final is called per-connection.
24007 	 */
24008 	mutex_enter(&tcp_iss_key_lock);
24009 	MD5Init(&tcp_iss_key);
24010 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
24011 	    sizeof (tcp_iss_cookie));
24012 	mutex_exit(&tcp_iss_key_lock);
24013 }
24014 
24015 /*
24016  * Set the RFC 1948 pass phrase
24017  */
24018 /* ARGSUSED */
24019 static int
24020 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24021     cred_t *cr)
24022 {
24023 	/*
24024 	 * Basically, value contains a new pass phrase.  Pass it along!
24025 	 */
24026 	tcp_iss_key_init((uint8_t *)value, strlen(value));
24027 	return (0);
24028 }
24029 
24030 /* ARGSUSED */
24031 static int
24032 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24033 {
24034 	bzero(buf, sizeof (tcp_sack_info_t));
24035 	return (0);
24036 }
24037 
24038 /* ARGSUSED */
24039 static int
24040 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24041 {
24042 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24043 	return (0);
24044 }
24045 
24046 void
24047 tcp_ddi_init(void)
24048 {
24049 	int i;
24050 
24051 	/* Initialize locks */
24052 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
24053 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24054 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24055 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24056 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24057 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
24058 
24059 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24060 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
24061 		    MUTEX_DEFAULT, NULL);
24062 	}
24063 
24064 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24065 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
24066 		    MUTEX_DEFAULT, NULL);
24067 	}
24068 
24069 	/* TCP's IPsec code calls the packet dropper. */
24070 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
24071 
24072 	if (!tcp_g_nd) {
24073 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
24074 			nd_free(&tcp_g_nd);
24075 		}
24076 	}
24077 
24078 	/*
24079 	 * Note: To really walk the device tree you need the devinfo
24080 	 * pointer to your device which is only available after probe/attach.
24081 	 * The following is safe only because it uses ddi_root_node()
24082 	 */
24083 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24084 	    tcp_opt_obj.odb_opt_arr_cnt);
24085 
24086 	tcp_timercache = kmem_cache_create("tcp_timercache",
24087 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24088 	    NULL, NULL, NULL, NULL, NULL, 0);
24089 
24090 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24091 	    sizeof (tcp_sack_info_t), 0,
24092 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24093 
24094 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24095 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24096 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24097 
24098 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24099 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24100 
24101 	ip_squeue_init(tcp_squeue_add);
24102 
24103 	/* Initialize the random number generator */
24104 	tcp_random_init();
24105 
24106 	/*
24107 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24108 	 * by the boot scripts.
24109 	 *
24110 	 * Use NULL name, as the name is caught by the new lockstats.
24111 	 *
24112 	 * Initialize with some random, non-guessable string, like the global
24113 	 * T_INFO_ACK.
24114 	 */
24115 
24116 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24117 	    sizeof (tcp_g_t_info_ack));
24118 
24119 #if TCP_COUNTERS || TCP_DEBUG_COUNTER
24120 	if ((tcp_kstat = kstat_create("tcp", 0, "tcpstat",
24121 		"net", KSTAT_TYPE_NAMED,
24122 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
24123 		KSTAT_FLAG_VIRTUAL)) != NULL) {
24124 		tcp_kstat->ks_data = &tcp_statistics;
24125 		kstat_install(tcp_kstat);
24126 	}
24127 #endif
24128 	tcp_kstat_init();
24129 }
24130 
24131 void
24132 tcp_ddi_destroy(void)
24133 {
24134 	int i;
24135 
24136 	nd_free(&tcp_g_nd);
24137 
24138 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24139 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
24140 	}
24141 
24142 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24143 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
24144 	}
24145 
24146 	mutex_destroy(&tcp_iss_key_lock);
24147 	rw_destroy(&tcp_hsp_lock);
24148 	mutex_destroy(&tcp_g_q_lock);
24149 	mutex_destroy(&tcp_random_lock);
24150 	mutex_destroy(&tcp_epriv_port_lock);
24151 	rw_destroy(&tcp_reserved_port_lock);
24152 
24153 	ip_drop_unregister(&tcp_dropper);
24154 
24155 	kmem_cache_destroy(tcp_timercache);
24156 	kmem_cache_destroy(tcp_sack_info_cache);
24157 	kmem_cache_destroy(tcp_iphc_cache);
24158 
24159 	tcp_kstat_fini();
24160 }
24161 
24162 /*
24163  * Generate ISS, taking into account NDD changes may happen halfway through.
24164  * (If the iss is not zero, set it.)
24165  */
24166 
24167 static void
24168 tcp_iss_init(tcp_t *tcp)
24169 {
24170 	MD5_CTX context;
24171 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24172 	uint32_t answer[4];
24173 
24174 	tcp_iss_incr_extra += (ISS_INCR >> 1);
24175 	tcp->tcp_iss = tcp_iss_incr_extra;
24176 	switch (tcp_strong_iss) {
24177 	case 2:
24178 		mutex_enter(&tcp_iss_key_lock);
24179 		context = tcp_iss_key;
24180 		mutex_exit(&tcp_iss_key_lock);
24181 		arg.ports = tcp->tcp_ports;
24182 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24183 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24184 			    &arg.src);
24185 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24186 			    &arg.dst);
24187 		} else {
24188 			arg.src = tcp->tcp_ip6h->ip6_src;
24189 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24190 		}
24191 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24192 		MD5Final((uchar_t *)answer, &context);
24193 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24194 		/*
24195 		 * Now that we've hashed into a unique per-connection sequence
24196 		 * space, add a random increment per strong_iss == 1.  So I
24197 		 * guess we'll have to...
24198 		 */
24199 		/* FALLTHRU */
24200 	case 1:
24201 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24202 		break;
24203 	default:
24204 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24205 		break;
24206 	}
24207 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24208 	tcp->tcp_fss = tcp->tcp_iss - 1;
24209 	tcp->tcp_suna = tcp->tcp_iss;
24210 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24211 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24212 	tcp->tcp_csuna = tcp->tcp_snxt;
24213 }
24214 
24215 /*
24216  * Exported routine for extracting active tcp connection status.
24217  *
24218  * This is used by the Solaris Cluster Networking software to
24219  * gather a list of connections that need to be forwarded to
24220  * specific nodes in the cluster when configuration changes occur.
24221  *
24222  * The callback is invoked for each tcp_t structure. Returning
24223  * non-zero from the callback routine terminates the search.
24224  */
24225 int
24226 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
24227 {
24228 	tcp_t *tcp;
24229 	cl_tcp_info_t	cl_tcpi;
24230 	connf_t	*connfp;
24231 	conn_t	*connp;
24232 	int	i;
24233 
24234 	ASSERT(callback != NULL);
24235 
24236 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24237 
24238 		connfp = &ipcl_globalhash_fanout[i];
24239 		connp = NULL;
24240 
24241 		while ((connp = tcp_get_next_conn(connfp, connp))) {
24242 
24243 			tcp = connp->conn_tcp;
24244 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24245 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24246 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24247 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24248 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24249 			/*
24250 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24251 			 * addresses. They are copied implicitly below as
24252 			 * mapped addresses.
24253 			 */
24254 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24255 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24256 				cl_tcpi.cl_tcpi_faddr =
24257 				    tcp->tcp_ipha->ipha_dst;
24258 			} else {
24259 				cl_tcpi.cl_tcpi_faddr_v6 =
24260 				    tcp->tcp_ip6h->ip6_dst;
24261 			}
24262 
24263 			/*
24264 			 * If the callback returns non-zero
24265 			 * we terminate the traversal.
24266 			 */
24267 			if ((*callback)(&cl_tcpi, arg) != 0) {
24268 				CONN_DEC_REF(tcp->tcp_connp);
24269 				return (1);
24270 			}
24271 		}
24272 	}
24273 
24274 	return (0);
24275 }
24276 
24277 /*
24278  * Macros used for accessing the different types of sockaddr
24279  * structures inside a tcp_ioc_abort_conn_t.
24280  */
24281 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24282 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24283 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24284 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24285 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24286 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24287 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24288 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24289 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24290 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24291 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24292 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24293 
24294 /*
24295  * Return the correct error code to mimic the behavior
24296  * of a connection reset.
24297  */
24298 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24299 		switch ((state)) {		\
24300 		case TCPS_SYN_SENT:		\
24301 		case TCPS_SYN_RCVD:		\
24302 			(err) = ECONNREFUSED;	\
24303 			break;			\
24304 		case TCPS_ESTABLISHED:		\
24305 		case TCPS_FIN_WAIT_1:		\
24306 		case TCPS_FIN_WAIT_2:		\
24307 		case TCPS_CLOSE_WAIT:		\
24308 			(err) = ECONNRESET;	\
24309 			break;			\
24310 		case TCPS_CLOSING:		\
24311 		case TCPS_LAST_ACK:		\
24312 		case TCPS_TIME_WAIT:		\
24313 			(err) = 0;		\
24314 			break;			\
24315 		default:			\
24316 			(err) = ENXIO;		\
24317 		}				\
24318 	}
24319 
24320 /*
24321  * Check if a tcp structure matches the info in acp.
24322  */
24323 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24324 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24325 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24326 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24327 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24328 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24329 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24330 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24331 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24332 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24333 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24334 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24335 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24336 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24337 	&(tcp)->tcp_ip_src_v6)) &&				\
24338 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24339 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24340 	&(tcp)->tcp_remote_v6)) &&				\
24341 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24342 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24343 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24344 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24345 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24346 	(acp)->ac_end >= (tcp)->tcp_state))
24347 
24348 #define	TCP_AC_MATCH(acp, tcp)					\
24349 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24350 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24351 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24352 
24353 /*
24354  * Build a message containing a tcp_ioc_abort_conn_t structure
24355  * which is filled in with information from acp and tp.
24356  */
24357 static mblk_t *
24358 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24359 {
24360 	mblk_t *mp;
24361 	tcp_ioc_abort_conn_t *tacp;
24362 
24363 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24364 	if (mp == NULL)
24365 		return (NULL);
24366 
24367 	mp->b_datap->db_type = M_CTL;
24368 
24369 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24370 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24371 		sizeof (uint32_t));
24372 
24373 	tacp->ac_start = acp->ac_start;
24374 	tacp->ac_end = acp->ac_end;
24375 	tacp->ac_zoneid = acp->ac_zoneid;
24376 
24377 	if (acp->ac_local.ss_family == AF_INET) {
24378 		tacp->ac_local.ss_family = AF_INET;
24379 		tacp->ac_remote.ss_family = AF_INET;
24380 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24381 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24382 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24383 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24384 	} else {
24385 		tacp->ac_local.ss_family = AF_INET6;
24386 		tacp->ac_remote.ss_family = AF_INET6;
24387 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24388 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24389 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24390 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24391 	}
24392 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24393 	return (mp);
24394 }
24395 
24396 /*
24397  * Print a tcp_ioc_abort_conn_t structure.
24398  */
24399 static void
24400 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24401 {
24402 	char lbuf[128];
24403 	char rbuf[128];
24404 	sa_family_t af;
24405 	in_port_t lport, rport;
24406 	ushort_t logflags;
24407 
24408 	af = acp->ac_local.ss_family;
24409 
24410 	if (af == AF_INET) {
24411 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24412 				lbuf, 128);
24413 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24414 				rbuf, 128);
24415 		lport = ntohs(TCP_AC_V4LPORT(acp));
24416 		rport = ntohs(TCP_AC_V4RPORT(acp));
24417 	} else {
24418 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24419 				lbuf, 128);
24420 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24421 				rbuf, 128);
24422 		lport = ntohs(TCP_AC_V6LPORT(acp));
24423 		rport = ntohs(TCP_AC_V6RPORT(acp));
24424 	}
24425 
24426 	logflags = SL_TRACE | SL_NOTE;
24427 	/*
24428 	 * Don't print this message to the console if the operation was done
24429 	 * to a non-global zone.
24430 	 */
24431 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24432 		logflags |= SL_CONSOLE;
24433 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags,
24434 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24435 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24436 		acp->ac_start, acp->ac_end);
24437 }
24438 
24439 /*
24440  * Called inside tcp_rput when a message built using
24441  * tcp_ioctl_abort_build_msg is put into a queue.
24442  * Note that when we get here there is no wildcard in acp any more.
24443  */
24444 static void
24445 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24446 {
24447 	tcp_ioc_abort_conn_t *acp;
24448 
24449 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24450 	if (tcp->tcp_state <= acp->ac_end) {
24451 		/*
24452 		 * If we get here, we are already on the correct
24453 		 * squeue. This ioctl follows the following path
24454 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24455 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24456 		 * different squeue)
24457 		 */
24458 		int errcode;
24459 
24460 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24461 		(void) tcp_clean_death(tcp, errcode, 26);
24462 	}
24463 	freemsg(mp);
24464 }
24465 
24466 /*
24467  * Abort all matching connections on a hash chain.
24468  */
24469 static int
24470 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24471     boolean_t exact)
24472 {
24473 	int nmatch, err = 0;
24474 	tcp_t *tcp;
24475 	MBLKP mp, last, listhead = NULL;
24476 	conn_t	*tconnp;
24477 	connf_t	*connfp = &ipcl_conn_fanout[index];
24478 
24479 startover:
24480 	nmatch = 0;
24481 
24482 	mutex_enter(&connfp->connf_lock);
24483 	for (tconnp = connfp->connf_head; tconnp != NULL;
24484 	    tconnp = tconnp->conn_next) {
24485 		tcp = tconnp->conn_tcp;
24486 		if (TCP_AC_MATCH(acp, tcp)) {
24487 			CONN_INC_REF(tcp->tcp_connp);
24488 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24489 			if (mp == NULL) {
24490 				err = ENOMEM;
24491 				CONN_DEC_REF(tcp->tcp_connp);
24492 				break;
24493 			}
24494 			mp->b_prev = (mblk_t *)tcp;
24495 
24496 			if (listhead == NULL) {
24497 				listhead = mp;
24498 				last = mp;
24499 			} else {
24500 				last->b_next = mp;
24501 				last = mp;
24502 			}
24503 			nmatch++;
24504 			if (exact)
24505 				break;
24506 		}
24507 
24508 		/* Avoid holding lock for too long. */
24509 		if (nmatch >= 500)
24510 			break;
24511 	}
24512 	mutex_exit(&connfp->connf_lock);
24513 
24514 	/* Pass mp into the correct tcp */
24515 	while ((mp = listhead) != NULL) {
24516 		listhead = listhead->b_next;
24517 		tcp = (tcp_t *)mp->b_prev;
24518 		mp->b_next = mp->b_prev = NULL;
24519 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24520 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24521 	}
24522 
24523 	*count += nmatch;
24524 	if (nmatch >= 500 && err == 0)
24525 		goto startover;
24526 	return (err);
24527 }
24528 
24529 /*
24530  * Abort all connections that matches the attributes specified in acp.
24531  */
24532 static int
24533 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24534 {
24535 	sa_family_t af;
24536 	uint32_t  ports;
24537 	uint16_t *pports;
24538 	int err = 0, count = 0;
24539 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24540 	int index = -1;
24541 	ushort_t logflags;
24542 
24543 	af = acp->ac_local.ss_family;
24544 
24545 	if (af == AF_INET) {
24546 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24547 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24548 			pports = (uint16_t *)&ports;
24549 			pports[1] = TCP_AC_V4LPORT(acp);
24550 			pports[0] = TCP_AC_V4RPORT(acp);
24551 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24552 		}
24553 	} else {
24554 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24555 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24556 			pports = (uint16_t *)&ports;
24557 			pports[1] = TCP_AC_V6LPORT(acp);
24558 			pports[0] = TCP_AC_V6RPORT(acp);
24559 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24560 		}
24561 	}
24562 
24563 	/*
24564 	 * For cases where remote addr, local port, and remote port are non-
24565 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24566 	 */
24567 	if (index != -1) {
24568 		err = tcp_ioctl_abort_bucket(acp, index,
24569 			    &count, exact);
24570 	} else {
24571 		/*
24572 		 * loop through all entries for wildcard case
24573 		 */
24574 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24575 			err = tcp_ioctl_abort_bucket(acp, index,
24576 			    &count, exact);
24577 			if (err != 0)
24578 				break;
24579 		}
24580 	}
24581 
24582 	logflags = SL_TRACE | SL_NOTE;
24583 	/*
24584 	 * Don't print this message to the console if the operation was done
24585 	 * to a non-global zone.
24586 	 */
24587 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24588 		logflags |= SL_CONSOLE;
24589 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24590 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24591 	if (err == 0 && count == 0)
24592 		err = ENOENT;
24593 	return (err);
24594 }
24595 
24596 /*
24597  * Process the TCP_IOC_ABORT_CONN ioctl request.
24598  */
24599 static void
24600 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24601 {
24602 	int	err;
24603 	IOCP    iocp;
24604 	MBLKP   mp1;
24605 	sa_family_t laf, raf;
24606 	tcp_ioc_abort_conn_t *acp;
24607 	zone_t *zptr;
24608 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24609 
24610 	iocp = (IOCP)mp->b_rptr;
24611 
24612 	if ((mp1 = mp->b_cont) == NULL ||
24613 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24614 		err = EINVAL;
24615 		goto out;
24616 	}
24617 
24618 	/* check permissions */
24619 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24620 		err = EPERM;
24621 		goto out;
24622 	}
24623 
24624 	if (mp1->b_cont != NULL) {
24625 		freemsg(mp1->b_cont);
24626 		mp1->b_cont = NULL;
24627 	}
24628 
24629 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24630 	laf = acp->ac_local.ss_family;
24631 	raf = acp->ac_remote.ss_family;
24632 
24633 	/* check that a zone with the supplied zoneid exists */
24634 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24635 		zptr = zone_find_by_id(zoneid);
24636 		if (zptr != NULL) {
24637 			zone_rele(zptr);
24638 		} else {
24639 			err = EINVAL;
24640 			goto out;
24641 		}
24642 	}
24643 
24644 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24645 	    acp->ac_start > acp->ac_end || laf != raf ||
24646 	    (laf != AF_INET && laf != AF_INET6)) {
24647 		err = EINVAL;
24648 		goto out;
24649 	}
24650 
24651 	tcp_ioctl_abort_dump(acp);
24652 	err = tcp_ioctl_abort(acp);
24653 
24654 out:
24655 	if (mp1 != NULL) {
24656 		freemsg(mp1);
24657 		mp->b_cont = NULL;
24658 	}
24659 
24660 	if (err != 0)
24661 		miocnak(q, mp, 0, err);
24662 	else
24663 		miocack(q, mp, 0, 0);
24664 }
24665 
24666 /*
24667  * tcp_time_wait_processing() handles processing of incoming packets when
24668  * the tcp is in the TIME_WAIT state.
24669  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24670  * on the time wait list.
24671  */
24672 void
24673 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24674     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24675 {
24676 	int32_t		bytes_acked;
24677 	int32_t		gap;
24678 	int32_t		rgap;
24679 	tcp_opt_t	tcpopt;
24680 	uint_t		flags;
24681 	uint32_t	new_swnd = 0;
24682 	conn_t		*connp;
24683 
24684 	BUMP_LOCAL(tcp->tcp_ibsegs);
24685 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24686 
24687 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24688 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24689 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24690 	if (tcp->tcp_snd_ts_ok) {
24691 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24692 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24693 			    tcp->tcp_rnxt, TH_ACK);
24694 			goto done;
24695 		}
24696 	}
24697 	gap = seg_seq - tcp->tcp_rnxt;
24698 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24699 	if (gap < 0) {
24700 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24701 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24702 		    (seg_len > -gap ? -gap : seg_len));
24703 		seg_len += gap;
24704 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24705 			if (flags & TH_RST) {
24706 				goto done;
24707 			}
24708 			if ((flags & TH_FIN) && seg_len == -1) {
24709 				/*
24710 				 * When TCP receives a duplicate FIN in
24711 				 * TIME_WAIT state, restart the 2 MSL timer.
24712 				 * See page 73 in RFC 793. Make sure this TCP
24713 				 * is already on the TIME_WAIT list. If not,
24714 				 * just restart the timer.
24715 				 */
24716 				if (TCP_IS_DETACHED(tcp)) {
24717 					tcp_time_wait_remove(tcp, NULL);
24718 					tcp_time_wait_append(tcp);
24719 					TCP_DBGSTAT(tcp_rput_time_wait);
24720 				} else {
24721 					ASSERT(tcp != NULL);
24722 					TCP_TIMER_RESTART(tcp,
24723 					    tcp_time_wait_interval);
24724 				}
24725 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24726 				    tcp->tcp_rnxt, TH_ACK);
24727 				goto done;
24728 			}
24729 			flags |=  TH_ACK_NEEDED;
24730 			seg_len = 0;
24731 			goto process_ack;
24732 		}
24733 
24734 		/* Fix seg_seq, and chew the gap off the front. */
24735 		seg_seq = tcp->tcp_rnxt;
24736 	}
24737 
24738 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24739 		/*
24740 		 * Make sure that when we accept the connection, pick
24741 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24742 		 * old connection.
24743 		 *
24744 		 * The next ISS generated is equal to tcp_iss_incr_extra
24745 		 * + ISS_INCR/2 + other components depending on the
24746 		 * value of tcp_strong_iss.  We pre-calculate the new
24747 		 * ISS here and compare with tcp_snxt to determine if
24748 		 * we need to make adjustment to tcp_iss_incr_extra.
24749 		 *
24750 		 * The above calculation is ugly and is a
24751 		 * waste of CPU cycles...
24752 		 */
24753 		uint32_t new_iss = tcp_iss_incr_extra;
24754 		int32_t adj;
24755 
24756 		switch (tcp_strong_iss) {
24757 		case 2: {
24758 			/* Add time and MD5 components. */
24759 			uint32_t answer[4];
24760 			struct {
24761 				uint32_t ports;
24762 				in6_addr_t src;
24763 				in6_addr_t dst;
24764 			} arg;
24765 			MD5_CTX context;
24766 
24767 			mutex_enter(&tcp_iss_key_lock);
24768 			context = tcp_iss_key;
24769 			mutex_exit(&tcp_iss_key_lock);
24770 			arg.ports = tcp->tcp_ports;
24771 			/* We use MAPPED addresses in tcp_iss_init */
24772 			arg.src = tcp->tcp_ip_src_v6;
24773 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24774 				IN6_IPADDR_TO_V4MAPPED(
24775 					tcp->tcp_ipha->ipha_dst,
24776 					    &arg.dst);
24777 			} else {
24778 				arg.dst =
24779 				    tcp->tcp_ip6h->ip6_dst;
24780 			}
24781 			MD5Update(&context, (uchar_t *)&arg,
24782 			    sizeof (arg));
24783 			MD5Final((uchar_t *)answer, &context);
24784 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24785 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24786 			break;
24787 		}
24788 		case 1:
24789 			/* Add time component and min random (i.e. 1). */
24790 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24791 			break;
24792 		default:
24793 			/* Add only time component. */
24794 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24795 			break;
24796 		}
24797 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24798 			/*
24799 			 * New ISS not guaranteed to be ISS_INCR/2
24800 			 * ahead of the current tcp_snxt, so add the
24801 			 * difference to tcp_iss_incr_extra.
24802 			 */
24803 			tcp_iss_incr_extra += adj;
24804 		}
24805 		/*
24806 		 * If tcp_clean_death() can not perform the task now,
24807 		 * drop the SYN packet and let the other side re-xmit.
24808 		 * Otherwise pass the SYN packet back in, since the
24809 		 * old tcp state has been cleaned up or freed.
24810 		 */
24811 		if (tcp_clean_death(tcp, 0, 27) == -1)
24812 			goto done;
24813 		/*
24814 		 * We will come back to tcp_rput_data
24815 		 * on the global queue. Packets destined
24816 		 * for the global queue will be checked
24817 		 * with global policy. But the policy for
24818 		 * this packet has already been checked as
24819 		 * this was destined for the detached
24820 		 * connection. We need to bypass policy
24821 		 * check this time by attaching a dummy
24822 		 * ipsec_in with ipsec_in_dont_check set.
24823 		 */
24824 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24825 		    NULL) {
24826 			TCP_STAT(tcp_time_wait_syn_success);
24827 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24828 			return;
24829 		}
24830 		goto done;
24831 	}
24832 
24833 	/*
24834 	 * rgap is the amount of stuff received out of window.  A negative
24835 	 * value is the amount out of window.
24836 	 */
24837 	if (rgap < 0) {
24838 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24839 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24840 		/* Fix seg_len and make sure there is something left. */
24841 		seg_len += rgap;
24842 		if (seg_len <= 0) {
24843 			if (flags & TH_RST) {
24844 				goto done;
24845 			}
24846 			flags |=  TH_ACK_NEEDED;
24847 			seg_len = 0;
24848 			goto process_ack;
24849 		}
24850 	}
24851 	/*
24852 	 * Check whether we can update tcp_ts_recent.  This test is
24853 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24854 	 * Extensions for High Performance: An Update", Internet Draft.
24855 	 */
24856 	if (tcp->tcp_snd_ts_ok &&
24857 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24858 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24859 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24860 		tcp->tcp_last_rcv_lbolt = lbolt64;
24861 	}
24862 
24863 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24864 		/* Always ack out of order packets */
24865 		flags |= TH_ACK_NEEDED;
24866 		seg_len = 0;
24867 	} else if (seg_len > 0) {
24868 		BUMP_MIB(&tcp_mib, tcpInClosed);
24869 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24870 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24871 	}
24872 	if (flags & TH_RST) {
24873 		(void) tcp_clean_death(tcp, 0, 28);
24874 		goto done;
24875 	}
24876 	if (flags & TH_SYN) {
24877 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24878 		    TH_RST|TH_ACK);
24879 		/*
24880 		 * Do not delete the TCP structure if it is in
24881 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24882 		 */
24883 		goto done;
24884 	}
24885 process_ack:
24886 	if (flags & TH_ACK) {
24887 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24888 		if (bytes_acked <= 0) {
24889 			if (bytes_acked == 0 && seg_len == 0 &&
24890 			    new_swnd == tcp->tcp_swnd)
24891 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24892 		} else {
24893 			/* Acks something not sent */
24894 			flags |= TH_ACK_NEEDED;
24895 		}
24896 	}
24897 	if (flags & TH_ACK_NEEDED) {
24898 		/*
24899 		 * Time to send an ack for some reason.
24900 		 */
24901 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24902 		    tcp->tcp_rnxt, TH_ACK);
24903 	}
24904 done:
24905 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24906 		mp->b_datap->db_cksumstart = 0;
24907 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24908 		TCP_STAT(tcp_time_wait_syn_fail);
24909 	}
24910 	freemsg(mp);
24911 }
24912 
24913 /*
24914  * Return zero if the buffers are identical in length and content.
24915  * This is used for comparing extension header buffers.
24916  * Note that an extension header would be declared different
24917  * even if all that changed was the next header value in that header i.e.
24918  * what really changed is the next extension header.
24919  */
24920 static boolean_t
24921 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24922 {
24923 	if (!b_valid)
24924 		blen = 0;
24925 
24926 	if (alen != blen)
24927 		return (B_TRUE);
24928 	if (alen == 0)
24929 		return (B_FALSE);	/* Both zero length */
24930 	return (bcmp(a, b, alen));
24931 }
24932 
24933 /*
24934  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24935  * Return B_FALSE if memory allocation fails - don't change any state!
24936  */
24937 static boolean_t
24938 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24939     void *src, uint_t srclen)
24940 {
24941 	void *dst;
24942 
24943 	if (!src_valid)
24944 		srclen = 0;
24945 
24946 	ASSERT(*dstlenp == 0);
24947 	if (src != NULL && srclen != 0) {
24948 		dst = mi_alloc(srclen, BPRI_MED);
24949 		if (dst == NULL)
24950 			return (B_FALSE);
24951 	} else {
24952 		dst = NULL;
24953 	}
24954 	if (*dstp != NULL) {
24955 		mi_free(*dstp);
24956 		*dstp = NULL;
24957 		*dstlenp = 0;
24958 	}
24959 	*dstp = dst;
24960 	if (dst != NULL)
24961 		*dstlenp = srclen;
24962 	else
24963 		*dstlenp = 0;
24964 	return (B_TRUE);
24965 }
24966 
24967 /*
24968  * Replace what is in *dst, *dstlen with the source.
24969  * Assumes tcp_allocbuf has already been called.
24970  */
24971 static void
24972 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24973     void *src, uint_t srclen)
24974 {
24975 	if (!src_valid)
24976 		srclen = 0;
24977 
24978 	ASSERT(*dstlenp == srclen);
24979 	if (src != NULL && srclen != 0) {
24980 		bcopy(src, *dstp, srclen);
24981 	}
24982 }
24983 
24984 /*
24985  * Allocate a T_SVR4_OPTMGMT_REQ.
24986  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24987  * that tcp_rput_other can drop the acks.
24988  */
24989 static mblk_t *
24990 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24991 {
24992 	mblk_t *mp;
24993 	struct T_optmgmt_req *tor;
24994 	struct opthdr *oh;
24995 	uint_t size;
24996 	char *optptr;
24997 
24998 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24999 	mp = allocb(size, BPRI_MED);
25000 	if (mp == NULL)
25001 		return (NULL);
25002 
25003 	mp->b_wptr += size;
25004 	mp->b_datap->db_type = M_PROTO;
25005 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25006 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25007 	tor->MGMT_flags = T_NEGOTIATE;
25008 	tor->OPT_length = sizeof (*oh) + optlen;
25009 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25010 
25011 	oh = (struct opthdr *)&tor[1];
25012 	oh->level = level;
25013 	oh->name = cmd;
25014 	oh->len = optlen;
25015 	if (optlen != 0) {
25016 		optptr = (char *)&oh[1];
25017 		bcopy(opt, optptr, optlen);
25018 	}
25019 	return (mp);
25020 }
25021 
25022 /*
25023  * TCP Timers Implementation.
25024  */
25025 static timeout_id_t
25026 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25027 {
25028 	mblk_t *mp;
25029 	tcp_timer_t *tcpt;
25030 	tcp_t *tcp = connp->conn_tcp;
25031 
25032 	ASSERT(connp->conn_sqp != NULL);
25033 
25034 	TCP_DBGSTAT(tcp_timeout_calls);
25035 
25036 	if (tcp->tcp_timercache == NULL) {
25037 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25038 	} else {
25039 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
25040 		mp = tcp->tcp_timercache;
25041 		tcp->tcp_timercache = mp->b_next;
25042 		mp->b_next = NULL;
25043 		ASSERT(mp->b_wptr == NULL);
25044 	}
25045 
25046 	CONN_INC_REF(connp);
25047 	tcpt = (tcp_timer_t *)mp->b_rptr;
25048 	tcpt->connp = connp;
25049 	tcpt->tcpt_proc = f;
25050 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
25051 	return ((timeout_id_t)mp);
25052 }
25053 
25054 static void
25055 tcp_timer_callback(void *arg)
25056 {
25057 	mblk_t *mp = (mblk_t *)arg;
25058 	tcp_timer_t *tcpt;
25059 	conn_t	*connp;
25060 
25061 	tcpt = (tcp_timer_t *)mp->b_rptr;
25062 	connp = tcpt->connp;
25063 	squeue_fill(connp->conn_sqp, mp,
25064 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25065 }
25066 
25067 static void
25068 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25069 {
25070 	tcp_timer_t *tcpt;
25071 	conn_t *connp = (conn_t *)arg;
25072 	tcp_t *tcp = connp->conn_tcp;
25073 
25074 	tcpt = (tcp_timer_t *)mp->b_rptr;
25075 	ASSERT(connp == tcpt->connp);
25076 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25077 
25078 	/*
25079 	 * If the TCP has reached the closed state, don't proceed any
25080 	 * further. This TCP logically does not exist on the system.
25081 	 * tcpt_proc could for example access queues, that have already
25082 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25083 	 */
25084 	if (tcp->tcp_state != TCPS_CLOSED) {
25085 		(*tcpt->tcpt_proc)(connp);
25086 	} else {
25087 		tcp->tcp_timer_tid = 0;
25088 	}
25089 	tcp_timer_free(connp->conn_tcp, mp);
25090 }
25091 
25092 /*
25093  * There is potential race with untimeout and the handler firing at the same
25094  * time. The mblock may be freed by the handler while we are trying to use
25095  * it. But since both should execute on the same squeue, this race should not
25096  * occur.
25097  */
25098 static clock_t
25099 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25100 {
25101 	mblk_t	*mp = (mblk_t *)id;
25102 	tcp_timer_t *tcpt;
25103 	clock_t delta;
25104 
25105 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
25106 
25107 	if (mp == NULL)
25108 		return (-1);
25109 
25110 	tcpt = (tcp_timer_t *)mp->b_rptr;
25111 	ASSERT(tcpt->connp == connp);
25112 
25113 	delta = untimeout(tcpt->tcpt_tid);
25114 
25115 	if (delta >= 0) {
25116 		TCP_DBGSTAT(tcp_timeout_canceled);
25117 		tcp_timer_free(connp->conn_tcp, mp);
25118 		CONN_DEC_REF(connp);
25119 	}
25120 
25121 	return (delta);
25122 }
25123 
25124 /*
25125  * Allocate space for the timer event. The allocation looks like mblk, but it is
25126  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25127  *
25128  * Dealing with failures: If we can't allocate from the timer cache we try
25129  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25130  * points to b_rptr.
25131  * If we can't allocate anything using allocb_tryhard(), we perform a last
25132  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25133  * save the actual allocation size in b_datap.
25134  */
25135 mblk_t *
25136 tcp_timermp_alloc(int kmflags)
25137 {
25138 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25139 	    kmflags & ~KM_PANIC);
25140 
25141 	if (mp != NULL) {
25142 		mp->b_next = mp->b_prev = NULL;
25143 		mp->b_rptr = (uchar_t *)(&mp[1]);
25144 		mp->b_wptr = NULL;
25145 		mp->b_datap = NULL;
25146 		mp->b_queue = NULL;
25147 	} else if (kmflags & KM_PANIC) {
25148 		/*
25149 		 * Failed to allocate memory for the timer. Try allocating from
25150 		 * dblock caches.
25151 		 */
25152 		TCP_STAT(tcp_timermp_allocfail);
25153 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25154 		if (mp == NULL) {
25155 			size_t size = 0;
25156 			/*
25157 			 * Memory is really low. Try tryhard allocation.
25158 			 */
25159 			TCP_STAT(tcp_timermp_allocdblfail);
25160 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25161 			    sizeof (tcp_timer_t), &size, kmflags);
25162 			mp->b_rptr = (uchar_t *)(&mp[1]);
25163 			mp->b_next = mp->b_prev = NULL;
25164 			mp->b_wptr = (uchar_t *)-1;
25165 			mp->b_datap = (dblk_t *)size;
25166 			mp->b_queue = NULL;
25167 		}
25168 		ASSERT(mp->b_wptr != NULL);
25169 	}
25170 	TCP_DBGSTAT(tcp_timermp_alloced);
25171 
25172 	return (mp);
25173 }
25174 
25175 /*
25176  * Free per-tcp timer cache.
25177  * It can only contain entries from tcp_timercache.
25178  */
25179 void
25180 tcp_timermp_free(tcp_t *tcp)
25181 {
25182 	mblk_t *mp;
25183 
25184 	while ((mp = tcp->tcp_timercache) != NULL) {
25185 		ASSERT(mp->b_wptr == NULL);
25186 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25187 		kmem_cache_free(tcp_timercache, mp);
25188 	}
25189 }
25190 
25191 /*
25192  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25193  * events there already (currently at most two events are cached).
25194  * If the event is not allocated from the timer cache, free it right away.
25195  */
25196 static void
25197 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25198 {
25199 	mblk_t *mp1 = tcp->tcp_timercache;
25200 
25201 	if (mp->b_wptr != NULL) {
25202 		/*
25203 		 * This allocation is not from a timer cache, free it right
25204 		 * away.
25205 		 */
25206 		if (mp->b_wptr != (uchar_t *)-1)
25207 			freeb(mp);
25208 		else
25209 			kmem_free(mp, (size_t)mp->b_datap);
25210 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25211 		/* Cache this timer block for future allocations */
25212 		mp->b_rptr = (uchar_t *)(&mp[1]);
25213 		mp->b_next = mp1;
25214 		tcp->tcp_timercache = mp;
25215 	} else {
25216 		kmem_cache_free(tcp_timercache, mp);
25217 		TCP_DBGSTAT(tcp_timermp_freed);
25218 	}
25219 }
25220 
25221 /*
25222  * End of TCP Timers implementation.
25223  */
25224 
25225 /*
25226  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
25227  * on the specified backing STREAMS q. Note, the caller may make the
25228  * decision to call based on the tcp_t.tcp_flow_stopped value which
25229  * when check outside the q's lock is only an advisory check ...
25230  */
25231 
25232 static void
25233 tcp_setqfull(tcp_t *tcp)
25234 {
25235 	queue_t *q = tcp->tcp_wq;
25236 
25237 	if (!(q->q_flag & QFULL)) {
25238 		mutex_enter(QLOCK(q));
25239 		if (!(q->q_flag & QFULL)) {
25240 			/* still need to set QFULL */
25241 			q->q_flag |= QFULL;
25242 			tcp->tcp_flow_stopped = B_TRUE;
25243 			mutex_exit(QLOCK(q));
25244 			TCP_STAT(tcp_flwctl_on);
25245 		} else {
25246 			mutex_exit(QLOCK(q));
25247 		}
25248 	}
25249 }
25250 
25251 static void
25252 tcp_clrqfull(tcp_t *tcp)
25253 {
25254 	queue_t *q = tcp->tcp_wq;
25255 
25256 	if (q->q_flag & QFULL) {
25257 		mutex_enter(QLOCK(q));
25258 		if (q->q_flag & QFULL) {
25259 			q->q_flag &= ~QFULL;
25260 			tcp->tcp_flow_stopped = B_FALSE;
25261 			mutex_exit(QLOCK(q));
25262 			if (q->q_flag & QWANTW)
25263 				qbackenable(q, 0);
25264 		} else
25265 			mutex_exit(QLOCK(q));
25266 	}
25267 }
25268 
25269 /*
25270  * TCP Kstats implementation
25271  */
25272 static void
25273 tcp_kstat_init(void)
25274 {
25275 	tcp_named_kstat_t template = {
25276 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25277 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25278 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25279 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25280 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25281 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25282 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25283 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25284 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25285 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
25286 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
25287 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25288 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25289 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25290 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25291 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25292 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25293 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25294 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25295 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25296 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25297 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25298 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25299 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25300 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25301 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25302 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25303 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25304 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25305 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25306 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25307 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25308 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25309 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25310 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25311 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25312 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25313 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25314 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25315 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25316 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25317 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25318 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25319 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25320 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25321 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25322 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25323 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25324 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25325 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25326 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25327 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25328 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25329 	};
25330 
25331 	tcp_mibkp = kstat_create("tcp", 0, "tcp", "mib2", KSTAT_TYPE_NAMED,
25332 	    NUM_OF_FIELDS(tcp_named_kstat_t), 0);
25333 
25334 	if (tcp_mibkp == NULL)
25335 		return;
25336 
25337 	template.rtoAlgorithm.value.ui32 = 4;
25338 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
25339 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
25340 	template.maxConn.value.i32 = -1;
25341 
25342 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
25343 
25344 	tcp_mibkp->ks_update = tcp_kstat_update;
25345 
25346 	kstat_install(tcp_mibkp);
25347 }
25348 
25349 static void
25350 tcp_kstat_fini(void)
25351 {
25352 
25353 	if (tcp_mibkp != NULL) {
25354 		kstat_delete(tcp_mibkp);
25355 		tcp_mibkp = NULL;
25356 	}
25357 }
25358 
25359 static int
25360 tcp_kstat_update(kstat_t *kp, int rw)
25361 {
25362 	tcp_named_kstat_t	*tcpkp;
25363 	tcp_t			*tcp;
25364 	connf_t			*connfp;
25365 	conn_t			*connp;
25366 	int 			i;
25367 
25368 	if (!kp || !kp->ks_data)
25369 		return (EIO);
25370 
25371 	if (rw == KSTAT_WRITE)
25372 		return (EACCES);
25373 
25374 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25375 
25376 	tcpkp->currEstab.value.ui32 = 0;
25377 
25378 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25379 		connfp = &ipcl_globalhash_fanout[i];
25380 		connp = NULL;
25381 		while ((connp = tcp_get_next_conn(connfp, connp))) {
25382 			tcp = connp->conn_tcp;
25383 			switch (tcp_snmp_state(tcp)) {
25384 			case MIB2_TCP_established:
25385 			case MIB2_TCP_closeWait:
25386 				tcpkp->currEstab.value.ui32++;
25387 				break;
25388 			}
25389 		}
25390 	}
25391 
25392 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25393 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25394 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25395 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25396 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
25397 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
25398 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25399 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25400 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25401 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25402 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25403 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25404 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25405 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25406 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25407 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25408 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25409 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25410 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25411 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25412 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25413 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25414 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25415 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25416 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25417 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25418 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25419 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25420 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25421 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25422 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25423 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25424 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25425 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25426 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25427 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25428 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25429 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25430 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25431 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25432 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25433 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25434 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25435 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25436 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25437 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25438 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25439 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25440 
25441 	return (0);
25442 }
25443 
25444 void
25445 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25446 {
25447 	uint16_t	hdr_len;
25448 	ipha_t		*ipha;
25449 	uint8_t		*nexthdrp;
25450 	tcph_t		*tcph;
25451 
25452 	/* Already has an eager */
25453 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25454 		TCP_STAT(tcp_reinput_syn);
25455 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25456 		    connp, SQTAG_TCP_REINPUT_EAGER);
25457 		return;
25458 	}
25459 
25460 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25461 	case IPV4_VERSION:
25462 		ipha = (ipha_t *)mp->b_rptr;
25463 		hdr_len = IPH_HDR_LENGTH(ipha);
25464 		break;
25465 	case IPV6_VERSION:
25466 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25467 		    &hdr_len, &nexthdrp)) {
25468 			CONN_DEC_REF(connp);
25469 			freemsg(mp);
25470 			return;
25471 		}
25472 		break;
25473 	}
25474 
25475 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25476 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25477 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25478 		mp->b_datap->db_cksumstart = (intptr_t)sqp;
25479 	}
25480 
25481 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25482 	    SQTAG_TCP_REINPUT);
25483 }
25484 
25485 static squeue_func_t
25486 tcp_squeue_switch(int val)
25487 {
25488 	squeue_func_t rval = squeue_fill;
25489 
25490 	switch (val) {
25491 	case 1:
25492 		rval = squeue_enter_nodrain;
25493 		break;
25494 	case 2:
25495 		rval = squeue_enter;
25496 		break;
25497 	default:
25498 		break;
25499 	}
25500 	return (rval);
25501 }
25502 
25503 static void
25504 tcp_squeue_add(squeue_t *sqp)
25505 {
25506 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25507 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25508 
25509 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25510 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25511 	    sqp, TCP_TIME_WAIT_DELAY);
25512 }
25513