xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision 1cb6af97c6f66f456d4f726ef056e1ebc0f73305)
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 static void	tcp_clrqfull(tcp_t *);
1160 static void	tcp_setqfull(tcp_t *);
1161 
1162 static struct module_info tcp_rinfo =  {
1163 #define	TCP_MODULE_ID	5105
1164 	TCP_MODULE_ID, "tcp", 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1165 };
1166 
1167 static struct module_info tcp_winfo =  {
1168 	TCP_MODULE_ID, "tcp", 0, INFPSZ, 127, 16
1169 };
1170 
1171 /*
1172  * Entry points for TCP as a module. It only allows SNMP requests
1173  * to pass through.
1174  */
1175 struct qinit tcp_mod_rinit = {
1176 	(pfi_t)putnext, NULL, tcp_open, tcp_modclose, NULL, &tcp_rinfo
1177 };
1178 
1179 struct qinit tcp_mod_winit = {
1180 	(pfi_t)tcp_wput_mod, NULL, tcp_open, tcp_modclose, NULL, &tcp_rinfo
1181 };
1182 
1183 /*
1184  * Entry points for TCP as a device. The normal case which supports
1185  * the TCP functionality.
1186  */
1187 struct qinit tcp_rinit = {
1188 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1189 };
1190 
1191 struct qinit tcp_winit = {
1192 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1193 };
1194 
1195 /* Initial entry point for TCP in socket mode. */
1196 struct qinit tcp_sock_winit = {
1197 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1198 };
1199 
1200 /*
1201  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1202  * an accept. Avoid allocating data structures since eager has already
1203  * been created.
1204  */
1205 struct qinit tcp_acceptor_rinit = {
1206 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1207 };
1208 
1209 struct qinit tcp_acceptor_winit = {
1210 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1211 };
1212 
1213 struct streamtab tcpinfo = {
1214 	&tcp_rinit, &tcp_winit
1215 };
1216 
1217 
1218 extern squeue_func_t tcp_squeue_wput_proc;
1219 extern squeue_func_t tcp_squeue_timer_proc;
1220 
1221 /* Protected by tcp_g_q_lock */
1222 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1223 kmutex_t tcp_g_q_lock;
1224 
1225 /* Protected by tcp_hsp_lock */
1226 /*
1227  * XXX The host param mechanism should go away and instead we should use
1228  * the metrics associated with the routes to determine the default sndspace
1229  * and rcvspace.
1230  */
1231 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1232 krwlock_t tcp_hsp_lock;
1233 
1234 /*
1235  * Extra privileged ports. In host byte order.
1236  * Protected by tcp_epriv_port_lock.
1237  */
1238 #define	TCP_NUM_EPRIV_PORTS	64
1239 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1240 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1241 kmutex_t tcp_epriv_port_lock;
1242 
1243 /*
1244  * The smallest anonymous port in the priviledged port range which TCP
1245  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1246  */
1247 static in_port_t tcp_min_anonpriv_port = 512;
1248 
1249 /* Only modified during _init and _fini thus no locking is needed. */
1250 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1251 
1252 /* Hint not protected by any lock */
1253 static uint_t	tcp_next_port_to_try;
1254 
1255 
1256 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1257 static tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1258 
1259 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1260 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1261 
1262 /*
1263  * TCP has a private interface for other kernel modules to reserve a
1264  * port range for them to use.  Once reserved, TCP will not use any ports
1265  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1266  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1267  * has to be verified.
1268  *
1269  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1270  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1271  * range is [port a, port b] inclusive.  And each port range is between
1272  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1273  *
1274  * Note that the default anonymous port range starts from 32768.  There is
1275  * no port "collision" between that and the reserved port range.  If there
1276  * is port collision (because the default smallest anonymous port is lowered
1277  * or some apps specifically bind to ports in the reserved port range), the
1278  * system may not be able to reserve a port range even there are enough
1279  * unbound ports as a reserved port range contains consecutive ports .
1280  */
1281 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1282 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1283 #define	TCP_SMALLEST_RESERVED_PORT		10240
1284 #define	TCP_LARGEST_RESERVED_PORT		20480
1285 
1286 /* Structure to represent those reserved port ranges. */
1287 typedef struct tcp_rport_s {
1288 	in_port_t	lo_port;
1289 	in_port_t	hi_port;
1290 	tcp_t		**temp_tcp_array;
1291 } tcp_rport_t;
1292 
1293 /* The reserved port array. */
1294 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1295 
1296 /* Locks to protect the tcp_reserved_ports array. */
1297 static krwlock_t tcp_reserved_port_lock;
1298 
1299 /* The number of ranges in the array. */
1300 uint32_t tcp_reserved_port_array_size = 0;
1301 
1302 /*
1303  * MIB-2 stuff for SNMP
1304  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1305  */
1306 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1307 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1308 
1309 /*
1310  * Object to represent database of options to search passed to
1311  * {sock,tpi}optcom_req() interface routine to take care of option
1312  * management and associated methods.
1313  * XXX These and other externs should ideally move to a TCP header
1314  */
1315 extern optdb_obj_t	tcp_opt_obj;
1316 extern uint_t		tcp_max_optsize;
1317 
1318 boolean_t tcp_icmp_source_quench = B_FALSE;
1319 /*
1320  * Following assumes TPI alignment requirements stay along 32 bit
1321  * boundaries
1322  */
1323 #define	ROUNDUP32(x) \
1324 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1325 
1326 /* Template for response to info request. */
1327 static struct T_info_ack tcp_g_t_info_ack = {
1328 	T_INFO_ACK,		/* PRIM_type */
1329 	0,			/* TSDU_size */
1330 	T_INFINITE,		/* ETSDU_size */
1331 	T_INVALID,		/* CDATA_size */
1332 	T_INVALID,		/* DDATA_size */
1333 	sizeof (sin_t),		/* ADDR_size */
1334 	0,			/* OPT_size - not initialized here */
1335 	TIDUSZ,			/* TIDU_size */
1336 	T_COTS_ORD,		/* SERV_type */
1337 	TCPS_IDLE,		/* CURRENT_state */
1338 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1339 };
1340 
1341 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1342 	T_INFO_ACK,		/* PRIM_type */
1343 	0,			/* TSDU_size */
1344 	T_INFINITE,		/* ETSDU_size */
1345 	T_INVALID,		/* CDATA_size */
1346 	T_INVALID,		/* DDATA_size */
1347 	sizeof (sin6_t),	/* ADDR_size */
1348 	0,			/* OPT_size - not initialized here */
1349 	TIDUSZ,		/* TIDU_size */
1350 	T_COTS_ORD,		/* SERV_type */
1351 	TCPS_IDLE,		/* CURRENT_state */
1352 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1353 };
1354 
1355 #define	MS	1L
1356 #define	SECONDS	(1000 * MS)
1357 #define	MINUTES	(60 * SECONDS)
1358 #define	HOURS	(60 * MINUTES)
1359 #define	DAYS	(24 * HOURS)
1360 
1361 #define	PARAM_MAX (~(uint32_t)0)
1362 
1363 /* Max size IP datagram is 64k - 1 */
1364 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1365 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1366 /* Max of the above */
1367 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1368 
1369 /* Largest TCP port number */
1370 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1371 
1372 /*
1373  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1374  * layer header.  It has to be a multiple of 4.
1375  */
1376 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1377 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1378 
1379 /*
1380  * All of these are alterable, within the min/max values given, at run time.
1381  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1382  * per the TCP spec.
1383  */
1384 /* BEGIN CSTYLED */
1385 tcpparam_t	tcp_param_arr[] = {
1386  /*min		max		value		name */
1387  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1388  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1389  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1390  { 1,		1024,		1,		"tcp_conn_req_min" },
1391  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1392  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1393  { 0,		10,		0,		"tcp_debug" },
1394  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1395  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1396  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1397  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1398  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1399  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1400  { 1,		255,		64,		"tcp_ipv4_ttl"},
1401  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1402  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1403  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1404  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1405  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1406  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1407  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1408  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1409  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1410  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1411  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1412  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1413  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1414  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1415  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1416  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1417  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1418  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1419  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1420  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1421  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1422  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1423  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1424  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1425 /*
1426  * Question:  What default value should I set for tcp_strong_iss?
1427  */
1428  { 0,		2,		1,		"tcp_strong_iss"},
1429  { 0,		65536,		20,		"tcp_rtt_updates"},
1430  { 0,		1,		1,		"tcp_wscale_always"},
1431  { 0,		1,		0,		"tcp_tstamp_always"},
1432  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1433  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1434  { 0,		16,		2,		"tcp_deferred_acks_max"},
1435  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1436  { 1,		4,		4,		"tcp_slow_start_initial"},
1437  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1438  { 0,		2,		2,		"tcp_sack_permitted"},
1439  { 0,		1,		0,		"tcp_trace"},
1440  { 0,		1,		1,		"tcp_compression_enabled"},
1441  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1442  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1443  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1444  { 0,		1,		0,		"tcp_rev_src_routes"},
1445  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1446  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1447  { 0,		16,		8,		"tcp_local_dacks_max"},
1448  { 0,		2,		1,		"tcp_ecn_permitted"},
1449  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1450  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1451  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1452  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1453  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1454 };
1455 /* END CSTYLED */
1456 
1457 
1458 #define	tcp_time_wait_interval			tcp_param_arr[0].tcp_param_val
1459 #define	tcp_conn_req_max_q			tcp_param_arr[1].tcp_param_val
1460 #define	tcp_conn_req_max_q0			tcp_param_arr[2].tcp_param_val
1461 #define	tcp_conn_req_min			tcp_param_arr[3].tcp_param_val
1462 #define	tcp_conn_grace_period			tcp_param_arr[4].tcp_param_val
1463 #define	tcp_cwnd_max_				tcp_param_arr[5].tcp_param_val
1464 #define	tcp_dbg					tcp_param_arr[6].tcp_param_val
1465 #define	tcp_smallest_nonpriv_port		tcp_param_arr[7].tcp_param_val
1466 #define	tcp_ip_abort_cinterval			tcp_param_arr[8].tcp_param_val
1467 #define	tcp_ip_abort_linterval			tcp_param_arr[9].tcp_param_val
1468 #define	tcp_ip_abort_interval			tcp_param_arr[10].tcp_param_val
1469 #define	tcp_ip_notify_cinterval			tcp_param_arr[11].tcp_param_val
1470 #define	tcp_ip_notify_interval			tcp_param_arr[12].tcp_param_val
1471 #define	tcp_ipv4_ttl				tcp_param_arr[13].tcp_param_val
1472 #define	tcp_keepalive_interval_high		tcp_param_arr[14].tcp_param_max
1473 #define	tcp_keepalive_interval			tcp_param_arr[14].tcp_param_val
1474 #define	tcp_keepalive_interval_low		tcp_param_arr[14].tcp_param_min
1475 #define	tcp_maxpsz_multiplier			tcp_param_arr[15].tcp_param_val
1476 #define	tcp_mss_def_ipv4			tcp_param_arr[16].tcp_param_val
1477 #define	tcp_mss_max_ipv4			tcp_param_arr[17].tcp_param_val
1478 #define	tcp_mss_min				tcp_param_arr[18].tcp_param_val
1479 #define	tcp_naglim_def				tcp_param_arr[19].tcp_param_val
1480 #define	tcp_rexmit_interval_initial		tcp_param_arr[20].tcp_param_val
1481 #define	tcp_rexmit_interval_max			tcp_param_arr[21].tcp_param_val
1482 #define	tcp_rexmit_interval_min			tcp_param_arr[22].tcp_param_val
1483 #define	tcp_deferred_ack_interval		tcp_param_arr[23].tcp_param_val
1484 #define	tcp_snd_lowat_fraction			tcp_param_arr[24].tcp_param_val
1485 #define	tcp_sth_rcv_hiwat			tcp_param_arr[25].tcp_param_val
1486 #define	tcp_sth_rcv_lowat			tcp_param_arr[26].tcp_param_val
1487 #define	tcp_dupack_fast_retransmit		tcp_param_arr[27].tcp_param_val
1488 #define	tcp_ignore_path_mtu			tcp_param_arr[28].tcp_param_val
1489 #define	tcp_smallest_anon_port			tcp_param_arr[29].tcp_param_val
1490 #define	tcp_largest_anon_port			tcp_param_arr[30].tcp_param_val
1491 #define	tcp_xmit_hiwat				tcp_param_arr[31].tcp_param_val
1492 #define	tcp_xmit_lowat				tcp_param_arr[32].tcp_param_val
1493 #define	tcp_recv_hiwat				tcp_param_arr[33].tcp_param_val
1494 #define	tcp_recv_hiwat_minmss			tcp_param_arr[34].tcp_param_val
1495 #define	tcp_fin_wait_2_flush_interval		tcp_param_arr[35].tcp_param_val
1496 #define	tcp_co_min				tcp_param_arr[36].tcp_param_val
1497 #define	tcp_max_buf				tcp_param_arr[37].tcp_param_val
1498 #define	tcp_strong_iss				tcp_param_arr[38].tcp_param_val
1499 #define	tcp_rtt_updates				tcp_param_arr[39].tcp_param_val
1500 #define	tcp_wscale_always			tcp_param_arr[40].tcp_param_val
1501 #define	tcp_tstamp_always			tcp_param_arr[41].tcp_param_val
1502 #define	tcp_tstamp_if_wscale			tcp_param_arr[42].tcp_param_val
1503 #define	tcp_rexmit_interval_extra		tcp_param_arr[43].tcp_param_val
1504 #define	tcp_deferred_acks_max			tcp_param_arr[44].tcp_param_val
1505 #define	tcp_slow_start_after_idle		tcp_param_arr[45].tcp_param_val
1506 #define	tcp_slow_start_initial			tcp_param_arr[46].tcp_param_val
1507 #define	tcp_co_timer_interval			tcp_param_arr[47].tcp_param_val
1508 #define	tcp_sack_permitted			tcp_param_arr[48].tcp_param_val
1509 #define	tcp_trace				tcp_param_arr[49].tcp_param_val
1510 #define	tcp_compression_enabled			tcp_param_arr[50].tcp_param_val
1511 #define	tcp_ipv6_hoplimit			tcp_param_arr[51].tcp_param_val
1512 #define	tcp_mss_def_ipv6			tcp_param_arr[52].tcp_param_val
1513 #define	tcp_mss_max_ipv6			tcp_param_arr[53].tcp_param_val
1514 #define	tcp_rev_src_routes			tcp_param_arr[54].tcp_param_val
1515 #define	tcp_local_dack_interval			tcp_param_arr[55].tcp_param_val
1516 #define	tcp_ndd_get_info_interval		tcp_param_arr[56].tcp_param_val
1517 #define	tcp_local_dacks_max			tcp_param_arr[57].tcp_param_val
1518 #define	tcp_ecn_permitted			tcp_param_arr[58].tcp_param_val
1519 #define	tcp_rst_sent_rate_enabled		tcp_param_arr[59].tcp_param_val
1520 #define	tcp_rst_sent_rate			tcp_param_arr[60].tcp_param_val
1521 #define	tcp_push_timer_interval			tcp_param_arr[61].tcp_param_val
1522 #define	tcp_use_smss_as_mss_opt			tcp_param_arr[62].tcp_param_val
1523 #define	tcp_keepalive_abort_interval_high	tcp_param_arr[63].tcp_param_max
1524 #define	tcp_keepalive_abort_interval		tcp_param_arr[63].tcp_param_val
1525 #define	tcp_keepalive_abort_interval_low	tcp_param_arr[63].tcp_param_min
1526 
1527 /*
1528  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1529  * each header fragment in the header buffer.  Each parameter value has
1530  * to be a multiple of 4 (32-bit aligned).
1531  */
1532 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1533 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1534 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1535 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1536 
1537 /*
1538  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1539  * the maximum number of payload buffers associated per Multidata.
1540  */
1541 static tcpparam_t tcp_mdt_max_pbufs_param =
1542 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1543 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1544 
1545 /* Round up the value to the nearest mss. */
1546 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1547 
1548 /*
1549  * Set ECN capable transport (ECT) code point in IP header.
1550  *
1551  * Note that there are 2 ECT code points '01' and '10', which are called
1552  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1553  * point ECT(0) for TCP as described in RFC 2481.
1554  */
1555 #define	SET_ECT(tcp, iph) \
1556 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1557 		/* We need to clear the code point first. */ \
1558 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1559 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1560 	} else { \
1561 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1562 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1563 	}
1564 
1565 /*
1566  * The format argument to pass to tcp_display().
1567  * DISP_PORT_ONLY means that the returned string has only port info.
1568  * DISP_ADDR_AND_PORT means that the returned string also contains the
1569  * remote and local IP address.
1570  */
1571 #define	DISP_PORT_ONLY		1
1572 #define	DISP_ADDR_AND_PORT	2
1573 
1574 /*
1575  * This controls the rate some ndd info report functions can be used
1576  * by non-priviledged users.  It stores the last time such info is
1577  * requested.  When those report functions are called again, this
1578  * is checked with the current time and compare with the ndd param
1579  * tcp_ndd_get_info_interval.
1580  */
1581 static clock_t tcp_last_ndd_get_info_time = 0;
1582 #define	NDD_TOO_QUICK_MSG \
1583 	"ndd get info rate too high for non-priviledged users, try again " \
1584 	"later.\n"
1585 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1586 
1587 #define	IS_VMLOANED_MBLK(mp) \
1588 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1589 
1590 /*
1591  * These two variables control the rate for TCP to generate RSTs in
1592  * response to segments not belonging to any connections.  We limit
1593  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1594  * each 1 second interval.  This is to protect TCP against DoS attack.
1595  */
1596 static clock_t tcp_last_rst_intrvl;
1597 static uint32_t tcp_rst_cnt;
1598 
1599 /* The number of RST not sent because of the rate limit. */
1600 static uint32_t tcp_rst_unsent;
1601 
1602 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1603 boolean_t tcp_mdt_chain = B_TRUE;
1604 
1605 /*
1606  * MDT threshold in the form of effective send MSS multiplier; we take
1607  * the MDT path if the amount of unsent data exceeds the threshold value
1608  * (default threshold is 1*SMSS).
1609  */
1610 uint_t tcp_mdt_smss_threshold = 1;
1611 
1612 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1613 
1614 /*
1615  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1616  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1617  * determined dynamically during tcp_adapt_ire(), which is the default.
1618  */
1619 boolean_t tcp_static_maxpsz = B_FALSE;
1620 
1621 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1622 uint32_t tcp_random_anon_port = 1;
1623 
1624 /*
1625  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1626  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1627  * data, TCP will not respond with an ACK.  RFC 793 requires that
1628  * TCP responds with an ACK for such a bogus ACK.  By not following
1629  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1630  * an attacker successfully spoofs an acceptable segment to our
1631  * peer; or when our peer is "confused."
1632  */
1633 uint32_t tcp_drop_ack_unsent_cnt = 10;
1634 
1635 /*
1636  * Hook functions to enable cluster networking
1637  * On non-clustered systems these vectors must always be NULL.
1638  */
1639 
1640 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1641 			    uint8_t *laddrp, in_port_t lport) = NULL;
1642 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1643 			    uint8_t *laddrp, in_port_t lport) = NULL;
1644 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1645 			    uint8_t *laddrp, in_port_t lport,
1646 			    uint8_t *faddrp, in_port_t fport) = NULL;
1647 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1648 			    uint8_t *laddrp, in_port_t lport,
1649 			    uint8_t *faddrp, in_port_t fport) = NULL;
1650 
1651 /*
1652  * The following are defined in ip.c
1653  */
1654 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1655 				uint8_t *laddrp);
1656 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1657 				uint8_t *laddrp, uint8_t *faddrp);
1658 
1659 #define	CL_INET_CONNECT(tcp)		{			\
1660 	if (cl_inet_connect != NULL) {				\
1661 		/*						\
1662 		 * Running in cluster mode - register active connection	\
1663 		 * information						\
1664 		 */							\
1665 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1666 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1667 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1668 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1669 				    (in_port_t)(tcp)->tcp_lport,	\
1670 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1671 				    (in_port_t)(tcp)->tcp_fport);	\
1672 			}						\
1673 		} else {						\
1674 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1675 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1676 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1677 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1678 				    (in_port_t)(tcp)->tcp_lport,	\
1679 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1680 				    (in_port_t)(tcp)->tcp_fport);	\
1681 			}						\
1682 		}							\
1683 	}								\
1684 }
1685 
1686 #define	CL_INET_DISCONNECT(tcp)	{				\
1687 	if (cl_inet_disconnect != NULL) {				\
1688 		/*							\
1689 		 * Running in cluster mode - deregister active		\
1690 		 * connection information				\
1691 		 */							\
1692 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1693 			if ((tcp)->tcp_ip_src != 0) {			\
1694 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1695 				    AF_INET,				\
1696 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1697 				    (in_port_t)(tcp)->tcp_lport,	\
1698 				    (uint8_t *)				\
1699 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1700 				    (in_port_t)(tcp)->tcp_fport);	\
1701 			}						\
1702 		} else {						\
1703 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1704 			    &(tcp)->tcp_ip_src_v6)) {			\
1705 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1706 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1707 				    (in_port_t)(tcp)->tcp_lport,	\
1708 				    (uint8_t *)				\
1709 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1710 				    (in_port_t)(tcp)->tcp_fport);	\
1711 			}						\
1712 		}							\
1713 	}								\
1714 }
1715 
1716 /*
1717  * Cluster networking hook for traversing current connection list.
1718  * This routine is used to extract the current list of live connections
1719  * which must continue to to be dispatched to this node.
1720  */
1721 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1722 
1723 #define	IPH_TCPH_CHECKSUMP(ipha, hlen) \
1724 	((uint16_t *)(((uchar_t *)(ipha)) + ((hlen) + 16)))
1725 
1726 #ifdef  _BIG_ENDIAN
1727 #define	IP_TCP_CSUM_COMP	IPPROTO_TCP
1728 #else
1729 #define	IP_TCP_CSUM_COMP	(IPPROTO_TCP << 8)
1730 #endif
1731 
1732 #define	IP_HDR_CKSUM(ipha, sum, v_hlen_tos_len, ttl_protocol) {		\
1733 	(sum) += (ttl_protocol) + (ipha)->ipha_ident +			\
1734 	    ((v_hlen_tos_len) >> 16) +					\
1735 	    ((v_hlen_tos_len) & 0xFFFF) +				\
1736 	    (ipha)->ipha_fragment_offset_and_flags;			\
1737 	(sum) = (((sum) & 0xFFFF) + ((sum) >> 16));			\
1738 	(sum) = ~((sum) + ((sum) >> 16));				\
1739 	(ipha)->ipha_hdr_checksum = (uint16_t)(sum);			\
1740 }
1741 
1742 /*
1743  * Macros that determine whether or not IP processing is needed for TCP.
1744  */
1745 #define	TCP_IPOPT_POLICY_V4(tcp)					\
1746 	((tcp)->tcp_ipversion == IPV4_VERSION &&			\
1747 	((tcp)->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH ||		\
1748 	CONN_OUTBOUND_POLICY_PRESENT((tcp)->tcp_connp) ||		\
1749 	CONN_INBOUND_POLICY_PRESENT((tcp)->tcp_connp)))
1750 
1751 #define	TCP_IPOPT_POLICY_V6(tcp)					\
1752 	((tcp)->tcp_ipversion == IPV6_VERSION &&			\
1753 	((tcp)->tcp_ip_hdr_len != IPV6_HDR_LEN ||			\
1754 	CONN_OUTBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp) ||		\
1755 	CONN_INBOUND_POLICY_PRESENT_V6((tcp)->tcp_connp)))
1756 
1757 #define	TCP_LOOPBACK_IP(tcp)						\
1758 	(TCP_IPOPT_POLICY_V4(tcp) || TCP_IPOPT_POLICY_V6(tcp) ||	\
1759 	!CONN_IS_MD_FASTPATH((tcp)->tcp_connp))
1760 
1761 boolean_t do_tcp_fusion = B_TRUE;
1762 
1763 /*
1764  * This routine gets called by the eager tcp upon changing state from
1765  * SYN_RCVD to ESTABLISHED.  It fuses a direct path between itself
1766  * and the active connect tcp such that the regular tcp processings
1767  * may be bypassed under allowable circumstances.  Because the fusion
1768  * requires both endpoints to be in the same squeue, it does not work
1769  * for simultaneous active connects because there is no easy way to
1770  * switch from one squeue to another once the connection is created.
1771  * This is different from the eager tcp case where we assign it the
1772  * same squeue as the one given to the active connect tcp during open.
1773  */
1774 static void
1775 tcp_fuse(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph)
1776 {
1777 	conn_t *peer_connp, *connp = tcp->tcp_connp;
1778 	tcp_t *peer_tcp;
1779 
1780 	ASSERT(!tcp->tcp_fused);
1781 	ASSERT(tcp->tcp_loopback);
1782 	ASSERT(tcp->tcp_loopback_peer == NULL);
1783 	/*
1784 	 * We need to check the listener tcp to make sure it's a socket
1785 	 * endpoint, but we can't really use tcp_listener since we get
1786 	 * here after sending up T_CONN_IND and tcp_wput_accept() may be
1787 	 * called independently, at which point tcp_listener is cleared;
1788 	 * this is why we use tcp_saved_listener.  The listener itself
1789 	 * is guaranteed to be around until tcp_accept_finish() is called
1790 	 * on this eager -- this won't happen until we're done since
1791 	 * we're inside the eager's perimeter now.
1792 	 */
1793 	ASSERT(tcp->tcp_saved_listener != NULL);
1794 
1795 	/*
1796 	 * Lookup peer endpoint; search for the remote endpoint having
1797 	 * the reversed address-port quadruplet in ESTABLISHED state,
1798 	 * which is guaranteed to be unique in the system.  Zone check
1799 	 * is applied accordingly for loopback address, but not for
1800 	 * local address since we want fusion to happen across Zones.
1801 	 */
1802 	if (tcp->tcp_ipversion == IPV4_VERSION) {
1803 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv4(connp,
1804 		    (ipha_t *)iphdr, tcph);
1805 	} else {
1806 		peer_connp = ipcl_conn_tcp_lookup_reversed_ipv6(connp,
1807 		    (ip6_t *)iphdr, tcph);
1808 	}
1809 
1810 	/*
1811 	 * We can only proceed if peer exists, resides in the same squeue
1812 	 * as our conn and is not raw-socket.  The squeue assignment of
1813 	 * this eager tcp was done earlier at the time of SYN processing
1814 	 * in ip_fanout_tcp{_v6}.  Note that similar squeues by itself
1815 	 * doesn't guarantee a safe condition to fuse, hence we perform
1816 	 * additional tests below.
1817 	 */
1818 	ASSERT(peer_connp == NULL || peer_connp != connp);
1819 	if (peer_connp == NULL || peer_connp->conn_sqp != connp->conn_sqp ||
1820 	    !IPCL_IS_TCP(peer_connp)) {
1821 		if (peer_connp != NULL) {
1822 			TCP_STAT(tcp_fusion_unqualified);
1823 			CONN_DEC_REF(peer_connp);
1824 		}
1825 		return;
1826 	}
1827 	peer_tcp = peer_connp->conn_tcp;	/* active connect tcp */
1828 
1829 	ASSERT(peer_tcp != NULL && peer_tcp != tcp && !peer_tcp->tcp_fused);
1830 	ASSERT(peer_tcp->tcp_loopback && peer_tcp->tcp_loopback_peer == NULL);
1831 	ASSERT(peer_connp->conn_sqp == connp->conn_sqp);
1832 
1833 	/*
1834 	 * Fuse the endpoints; we perform further checks against both
1835 	 * tcp endpoints to ensure that a fusion is allowed to happen.
1836 	 * In particular we bail out for TPI, non-simple TCP/IP or if
1837 	 * IPsec/IPQoS policy exists.  We could actually do it for the
1838 	 * XTI/TLI/TPI case but this requires more testing, so for now
1839 	 * we handle only the socket case.
1840 	 */
1841 	if (!tcp->tcp_unfusable && !peer_tcp->tcp_unfusable &&
1842 	    TCP_IS_SOCKET(tcp->tcp_saved_listener) && TCP_IS_SOCKET(peer_tcp) &&
1843 	    !TCP_LOOPBACK_IP(tcp) && !TCP_LOOPBACK_IP(peer_tcp) &&
1844 	    !IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
1845 		mblk_t *mp;
1846 		struct stroptions *stropt;
1847 		queue_t *peer_rq = peer_tcp->tcp_rq;
1848 		size_t sth_hiwat;
1849 
1850 		ASSERT(!TCP_IS_DETACHED(peer_tcp) && peer_rq != NULL);
1851 
1852 		/*
1853 		 * We need to drain data on both endpoints during unfuse.
1854 		 * If we need to send up SIGURG at the time of draining,
1855 		 * we want to be sure that an mblk is readily available.
1856 		 * This is why we pre-allocate the M_PCSIG mblks for both
1857 		 * endpoints which will only be used during/after unfuse.
1858 		 */
1859 		if ((mp = allocb(1, BPRI_HI)) == NULL) {
1860 			CONN_DEC_REF(peer_connp);
1861 			return;
1862 		}
1863 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
1864 		tcp->tcp_fused_sigurg_mp = mp;
1865 
1866 		if ((mp = allocb(1, BPRI_HI)) == NULL) {
1867 			freeb(tcp->tcp_fused_sigurg_mp);
1868 			tcp->tcp_fused_sigurg_mp = NULL;
1869 			CONN_DEC_REF(peer_connp);
1870 			return;
1871 		}
1872 		ASSERT(peer_tcp->tcp_fused_sigurg_mp == NULL);
1873 		peer_tcp->tcp_fused_sigurg_mp = mp;
1874 
1875 		/* Allocate M_SETOPTS mblk */
1876 		mp = allocb(sizeof (*stropt), BPRI_HI);
1877 		if (mp == NULL) {
1878 			freeb(tcp->tcp_fused_sigurg_mp);
1879 			tcp->tcp_fused_sigurg_mp = NULL;
1880 			freeb(peer_tcp->tcp_fused_sigurg_mp);
1881 			peer_tcp->tcp_fused_sigurg_mp = NULL;
1882 			CONN_DEC_REF(peer_connp);
1883 			return;
1884 		}
1885 
1886 		/* Fuse both endpoints */
1887 		peer_tcp->tcp_loopback_peer = tcp;
1888 		tcp->tcp_loopback_peer = peer_tcp;
1889 		peer_tcp->tcp_fused = tcp->tcp_fused = B_TRUE;
1890 
1891 		/*
1892 		 * We never use regular tcp paths in fusion and should
1893 		 * therefore clear tcp_unsent on both endpoints.  Having
1894 		 * them set to non-zero values means asking for trouble
1895 		 * especially after unfuse, where we may end up sending
1896 		 * through regular tcp paths which expect xmit_list and
1897 		 * friends to be correctly setup.
1898 		 */
1899 		peer_tcp->tcp_unsent = tcp->tcp_unsent = 0;
1900 
1901 		tcp_timers_stop(tcp);
1902 		tcp_timers_stop(peer_tcp);
1903 
1904 		/*
1905 		 * Set the stream head's write offset value to zero, since we
1906 		 * won't be needing any room for TCP/IP headers, and tell it
1907 		 * to not break up the writes.  This would reduce the amount
1908 		 * of work done by kmem.  In addition, we set the receive
1909 		 * buffer to twice that of q_hiwat in order to simulate the
1910 		 * non-fusion case.  Note that we can only do this for the
1911 		 * active connect tcp since our eager is still detached;
1912 		 * it will be dealt with later in tcp_accept_finish().
1913 		 */
1914 		DB_TYPE(mp) = M_SETOPTS;
1915 		mp->b_wptr += sizeof (*stropt);
1916 
1917 		sth_hiwat = peer_rq->q_hiwat << 1;
1918 		if (sth_hiwat > tcp_max_buf)
1919 			sth_hiwat = tcp_max_buf;
1920 
1921 		stropt = (struct stroptions *)mp->b_rptr;
1922 		stropt->so_flags = SO_MAXBLK | SO_WROFF | SO_HIWAT;
1923 		stropt->so_maxblk = tcp_maxpsz_set(peer_tcp, B_FALSE);
1924 		stropt->so_wroff = 0;
1925 		stropt->so_hiwat = MAX(sth_hiwat, tcp_sth_rcv_hiwat);
1926 
1927 		/* Send the options up */
1928 		putnext(peer_rq, mp);
1929 	} else {
1930 		TCP_STAT(tcp_fusion_unqualified);
1931 	}
1932 	CONN_DEC_REF(peer_connp);
1933 }
1934 
1935 /*
1936  * Unfuse a previously-fused pair of tcp loopback endpoints.
1937  */
1938 static void
1939 tcp_unfuse(tcp_t *tcp)
1940 {
1941 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
1942 
1943 	ASSERT(tcp->tcp_fused && peer_tcp != NULL);
1944 	ASSERT(peer_tcp->tcp_fused && peer_tcp->tcp_loopback_peer == tcp);
1945 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
1946 	ASSERT(tcp->tcp_unsent == 0 && peer_tcp->tcp_unsent == 0);
1947 	ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
1948 	ASSERT(peer_tcp->tcp_fused_sigurg_mp != NULL);
1949 
1950 	/*
1951 	 * Drain any pending data; the detached check is needed because
1952 	 * we may be called from tcp_fuse_output().  Note that in case of
1953 	 * a detached tcp, the draining will happen later after the tcp
1954 	 * is unfused.  For non-urgent data, this can be handled by the
1955 	 * regular tcp_rcv_drain().  If we have urgent data sitting in
1956 	 * the receive list, we will need to send up a SIGURG signal first
1957 	 * before draining the data.  All of these will be handled by the
1958 	 * code in tcp_fuse_rcv_drain() when called from tcp_rcv_drain().
1959 	 */
1960 	if (!TCP_IS_DETACHED(tcp)) {
1961 		(void) tcp_fuse_rcv_drain(tcp->tcp_rq, tcp,
1962 		    &tcp->tcp_fused_sigurg_mp);
1963 	}
1964 	if (!TCP_IS_DETACHED(peer_tcp)) {
1965 		(void) tcp_fuse_rcv_drain(peer_tcp->tcp_rq, peer_tcp,
1966 		    &peer_tcp->tcp_fused_sigurg_mp);
1967 	}
1968 	/* Lift up any flow-control conditions */
1969 	if (tcp->tcp_flow_stopped) {
1970 		tcp_clrqfull(tcp);
1971 		tcp->tcp_flow_stopped = B_FALSE;
1972 		TCP_STAT(tcp_fusion_backenabled);
1973 	}
1974 	if (peer_tcp->tcp_flow_stopped) {
1975 		tcp_clrqfull(peer_tcp);
1976 		peer_tcp->tcp_flow_stopped = B_FALSE;
1977 		TCP_STAT(tcp_fusion_backenabled);
1978 	}
1979 
1980 	/* Free up M_PCSIG mblk(s) if not needed */
1981 	if (!tcp->tcp_fused_sigurg && tcp->tcp_fused_sigurg_mp != NULL) {
1982 		freeb(tcp->tcp_fused_sigurg_mp);
1983 		tcp->tcp_fused_sigurg_mp = NULL;
1984 	}
1985 	if (!peer_tcp->tcp_fused_sigurg &&
1986 	    peer_tcp->tcp_fused_sigurg_mp != NULL) {
1987 		freeb(peer_tcp->tcp_fused_sigurg_mp);
1988 		peer_tcp->tcp_fused_sigurg_mp = NULL;
1989 	}
1990 
1991 	/*
1992 	 * Update th_seq and th_ack in the header template
1993 	 */
1994 	U32_TO_ABE32(tcp->tcp_snxt, tcp->tcp_tcph->th_seq);
1995 	U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
1996 	U32_TO_ABE32(peer_tcp->tcp_snxt, peer_tcp->tcp_tcph->th_seq);
1997 	U32_TO_ABE32(peer_tcp->tcp_rnxt, peer_tcp->tcp_tcph->th_ack);
1998 
1999 	/* Unfuse the endpoints */
2000 	peer_tcp->tcp_fused = tcp->tcp_fused = B_FALSE;
2001 	peer_tcp->tcp_loopback_peer = tcp->tcp_loopback_peer = NULL;
2002 }
2003 
2004 /*
2005  * Fusion output routine for urgent data.  This routine is called by
2006  * tcp_fuse_output() for handling non-M_DATA mblks.
2007  */
2008 static void
2009 tcp_fuse_output_urg(tcp_t *tcp, mblk_t *mp)
2010 {
2011 	mblk_t *mp1;
2012 	struct T_exdata_ind *tei;
2013 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2014 	mblk_t *head, *prev_head = NULL;
2015 
2016 	ASSERT(tcp->tcp_fused);
2017 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
2018 	ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
2019 	ASSERT(mp->b_cont != NULL && DB_TYPE(mp->b_cont) == M_DATA);
2020 	ASSERT(MBLKL(mp) >= sizeof (*tei) && MBLKL(mp->b_cont) > 0);
2021 
2022 	/*
2023 	 * Urgent data arrives in the form of T_EXDATA_REQ from above.
2024 	 * Each occurence denotes a new urgent pointer.  For each new
2025 	 * urgent pointer we signal (SIGURG) the receiving app to indicate
2026 	 * that it needs to go into urgent mode.  This is similar to the
2027 	 * urgent data handling in the regular tcp.  We don't need to keep
2028 	 * track of where the urgent pointer is, because each T_EXDATA_REQ
2029 	 * "advances" the urgent pointer for us.
2030 	 *
2031 	 * The actual urgent data carried by T_EXDATA_REQ is then prepended
2032 	 * by a T_EXDATA_IND before being enqueued behind any existing data
2033 	 * destined for the receiving app.  There is only a single urgent
2034 	 * pointer (out-of-band mark) for a given tcp.  If the new urgent
2035 	 * data arrives before the receiving app reads some existing urgent
2036 	 * data, the previous marker is lost.  This behavior is emulated
2037 	 * accordingly below, by removing any existing T_EXDATA_IND messages
2038 	 * and essentially converting old urgent data into non-urgent.
2039 	 */
2040 	ASSERT(tcp->tcp_valid_bits & TCP_URG_VALID);
2041 	/* Let sender get out of urgent mode */
2042 	tcp->tcp_valid_bits &= ~TCP_URG_VALID;
2043 
2044 	/*
2045 	 * Send up SIGURG to the receiving peer; if the peer is detached
2046 	 * or if we can't allocate the M_PCSIG, indicate that we need to
2047 	 * signal upon draining to the peer by marking tcp_fused_sigurg.
2048 	 * This flag will only get cleared once SIGURG is delivered and
2049 	 * is not affected by the tcp_fused flag -- delivery will still
2050 	 * happen even after an endpoint is unfused, to handle the case
2051 	 * where the sending endpoint immediately closes/unfuses after
2052 	 * sending urgent data and the accept is not yet finished.
2053 	 */
2054 	if (!TCP_IS_DETACHED(peer_tcp) &&
2055 	    ((mp1 = allocb(1, BPRI_HI)) != NULL ||
2056 	    (mp1 = allocb_tryhard(1)) != NULL)) {
2057 		peer_tcp->tcp_fused_sigurg = B_FALSE;
2058 		/* Send up the signal */
2059 		DB_TYPE(mp1) = M_PCSIG;
2060 		*mp1->b_wptr++ = (uchar_t)SIGURG;
2061 		putnext(peer_tcp->tcp_rq, mp1);
2062 	} else {
2063 		peer_tcp->tcp_fused_sigurg = B_TRUE;
2064 	}
2065 
2066 	/* Reuse T_EXDATA_REQ mblk for T_EXDATA_IND */
2067 	DB_TYPE(mp) = M_PROTO;
2068 	tei = (struct T_exdata_ind *)mp->b_rptr;
2069 	tei->PRIM_type = T_EXDATA_IND;
2070 	tei->MORE_flag = 0;
2071 	mp->b_wptr = (uchar_t *)&tei[1];
2072 
2073 	TCP_STAT(tcp_fusion_urg);
2074 	BUMP_MIB(&tcp_mib, tcpOutUrg);
2075 
2076 	head = peer_tcp->tcp_rcv_list;
2077 	while (head != NULL) {
2078 		/*
2079 		 * Remove existing T_EXDATA_IND, keep the data which follows
2080 		 * it and relink our list.  Note that we don't modify the
2081 		 * tcp_rcv_last_tail since it never points to T_EXDATA_IND.
2082 		 */
2083 		if (DB_TYPE(head) != M_DATA) {
2084 			mp1 = head;
2085 
2086 			ASSERT(DB_TYPE(mp1->b_cont) == M_DATA);
2087 			head = mp1->b_cont;
2088 			mp1->b_cont = NULL;
2089 			head->b_next = mp1->b_next;
2090 			mp1->b_next = NULL;
2091 			if (prev_head != NULL)
2092 				prev_head->b_next = head;
2093 			if (peer_tcp->tcp_rcv_list == mp1)
2094 				peer_tcp->tcp_rcv_list = head;
2095 			if (peer_tcp->tcp_rcv_last_head == mp1)
2096 				peer_tcp->tcp_rcv_last_head = head;
2097 			freeb(mp1);
2098 		}
2099 		prev_head = head;
2100 		head = head->b_next;
2101 	}
2102 }
2103 
2104 /*
2105  * Fusion output routine, called by tcp_output() and tcp_wput_proto().
2106  */
2107 static boolean_t
2108 tcp_fuse_output(tcp_t *tcp, mblk_t *mp)
2109 {
2110 	tcp_t *peer_tcp = tcp->tcp_loopback_peer;
2111 	queue_t *peer_rq;
2112 	mblk_t *mp_tail = mp;
2113 	uint32_t send_size = 0;
2114 
2115 	ASSERT(tcp->tcp_fused);
2116 	ASSERT(peer_tcp != NULL && peer_tcp->tcp_loopback_peer == tcp);
2117 	ASSERT(tcp->tcp_connp->conn_sqp == peer_tcp->tcp_connp->conn_sqp);
2118 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_PROTO ||
2119 	    DB_TYPE(mp) == M_PCPROTO);
2120 
2121 	peer_rq = peer_tcp->tcp_rq;
2122 
2123 	/* If this connection requires IP, unfuse and use regular path */
2124 	if (TCP_LOOPBACK_IP(tcp) || TCP_LOOPBACK_IP(peer_tcp) ||
2125 	    IPP_ENABLED(IPP_LOCAL_OUT|IPP_LOCAL_IN)) {
2126 		TCP_STAT(tcp_fusion_aborted);
2127 		tcp_unfuse(tcp);
2128 		return (B_FALSE);
2129 	}
2130 
2131 	for (;;) {
2132 		if (DB_TYPE(mp_tail) == M_DATA)
2133 			send_size += MBLKL(mp_tail);
2134 		if (mp_tail->b_cont == NULL)
2135 			break;
2136 		mp_tail = mp_tail->b_cont;
2137 	}
2138 
2139 	if (send_size == 0) {
2140 		freemsg(mp);
2141 		return (B_TRUE);
2142 	}
2143 
2144 	/*
2145 	 * Handle urgent data; we either send up SIGURG to the peer now
2146 	 * or do it later when we drain, in case the peer is detached
2147 	 * or if we're short of memory for M_PCSIG mblk.
2148 	 */
2149 	if (DB_TYPE(mp) != M_DATA)
2150 		tcp_fuse_output_urg(tcp, mp);
2151 
2152 	/*
2153 	 * Enqueue data into the peer's receive list; we may or may not
2154 	 * drain the contents depending on the conditions below.
2155 	 */
2156 	tcp_rcv_enqueue(peer_tcp, mp, send_size);
2157 
2158 	/* In case it wrapped around and also to keep it constant */
2159 	peer_tcp->tcp_rwnd += send_size;
2160 
2161 	/*
2162 	 * If peer is detached, exercise flow-control when needed; we will
2163 	 * get back-enabled either in tcp_accept_finish() or tcp_unfuse().
2164 	 */
2165 	if (TCP_IS_DETACHED(peer_tcp) &&
2166 	    peer_tcp->tcp_rcv_cnt > peer_rq->q_hiwat) {
2167 		tcp_setqfull(tcp);
2168 		tcp->tcp_flow_stopped = B_TRUE;
2169 		TCP_STAT(tcp_fusion_flowctl);
2170 	}
2171 
2172 	loopback_packets++;
2173 	tcp->tcp_last_sent_len = send_size;
2174 
2175 	/* Need to adjust the following SNMP MIB-related variables */
2176 	tcp->tcp_snxt += send_size;
2177 	tcp->tcp_suna = tcp->tcp_snxt;
2178 	peer_tcp->tcp_rnxt += send_size;
2179 	peer_tcp->tcp_rack = peer_tcp->tcp_rnxt;
2180 
2181 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
2182 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, send_size);
2183 
2184 	BUMP_MIB(&tcp_mib, tcpInSegs);
2185 	BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
2186 	UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, send_size);
2187 
2188 	BUMP_LOCAL(tcp->tcp_obsegs);
2189 	BUMP_LOCAL(peer_tcp->tcp_ibsegs);
2190 
2191 	if (!TCP_IS_DETACHED(peer_tcp)) {
2192 		/*
2193 		 * If we can't send SIGURG above due to lack of memory,
2194 		 * schedule push timer and try again.  Otherwise drain
2195 		 * the data if we're not flow-controlled.
2196 		 */
2197 		if (peer_tcp->tcp_fused_sigurg) {
2198 			if (peer_tcp->tcp_push_tid == 0) {
2199 				peer_tcp->tcp_push_tid =
2200 				    TCP_TIMER(peer_tcp, tcp_push_timer,
2201 				    MSEC_TO_TICK(tcp_push_timer_interval));
2202 			}
2203 		} else if (!tcp->tcp_flow_stopped) {
2204 			if (!canputnext(peer_rq)) {
2205 				tcp_setqfull(tcp);
2206 				tcp->tcp_flow_stopped = B_TRUE;
2207 				TCP_STAT(tcp_fusion_flowctl);
2208 			} else {
2209 				ASSERT(peer_tcp->tcp_rcv_list != NULL);
2210 				(void) tcp_fuse_rcv_drain(peer_rq,
2211 				    peer_tcp, NULL);
2212 				TCP_STAT(tcp_fusion_putnext);
2213 			}
2214 		}
2215 	}
2216 	return (B_TRUE);
2217 }
2218 
2219 /*
2220  * This routine gets called to deliver data upstream on a fused or
2221  * previously fused tcp loopback endpoint; the latter happens only
2222  * when there is a pending SIGURG signal plus urgent data that can't
2223  * be sent upstream in the past.
2224  */
2225 static boolean_t
2226 tcp_fuse_rcv_drain(queue_t *q, tcp_t *tcp, mblk_t **sigurg_mpp)
2227 {
2228 	mblk_t *mp;
2229 #ifdef DEBUG
2230 	uint_t cnt = 0;
2231 #endif
2232 
2233 	ASSERT(tcp->tcp_loopback);
2234 	ASSERT(tcp->tcp_fused || tcp->tcp_fused_sigurg);
2235 	ASSERT(!tcp->tcp_fused || tcp->tcp_loopback_peer != NULL);
2236 	ASSERT(sigurg_mpp != NULL || tcp->tcp_fused);
2237 
2238 	/* No need for the push timer now, in case it was scheduled */
2239 	if (tcp->tcp_push_tid != 0) {
2240 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
2241 		tcp->tcp_push_tid = 0;
2242 	}
2243 	/*
2244 	 * If there's urgent data sitting in receive list and we didn't
2245 	 * get a chance to send up a SIGURG signal, make sure we send
2246 	 * it first before draining in order to ensure that SIOCATMARK
2247 	 * works properly.
2248 	 */
2249 	if (tcp->tcp_fused_sigurg) {
2250 		/*
2251 		 * sigurg_mpp is normally NULL, i.e. when we're still
2252 		 * fused and didn't get here because of tcp_unfuse().
2253 		 * In this case try hard to allocate the M_PCSIG mblk.
2254 		 */
2255 		if (sigurg_mpp == NULL &&
2256 		    (mp = allocb(1, BPRI_HI)) == NULL &&
2257 		    (mp = allocb_tryhard(1)) == NULL) {
2258 			/* Alloc failed; try again next time */
2259 			tcp->tcp_push_tid = TCP_TIMER(tcp, tcp_push_timer,
2260 			    MSEC_TO_TICK(tcp_push_timer_interval));
2261 			return (B_TRUE);
2262 		} else if (sigurg_mpp != NULL) {
2263 			/*
2264 			 * Use the supplied M_PCSIG mblk; it means we're
2265 			 * either unfused or in the process of unfusing,
2266 			 * and the drain must happen now.
2267 			 */
2268 			mp = *sigurg_mpp;
2269 			*sigurg_mpp = NULL;
2270 		}
2271 		ASSERT(mp != NULL);
2272 
2273 		tcp->tcp_fused_sigurg = B_FALSE;
2274 		/* Send up the signal */
2275 		DB_TYPE(mp) = M_PCSIG;
2276 		*mp->b_wptr++ = (uchar_t)SIGURG;
2277 		putnext(q, mp);
2278 		/*
2279 		 * Let the regular tcp_rcv_drain() path handle
2280 		 * draining the data if we're no longer fused.
2281 		 */
2282 		if (!tcp->tcp_fused)
2283 			return (B_FALSE);
2284 	}
2285 
2286 	/* Drain the data */
2287 	while ((mp = tcp->tcp_rcv_list) != NULL) {
2288 		tcp->tcp_rcv_list = mp->b_next;
2289 		mp->b_next = NULL;
2290 #ifdef DEBUG
2291 		cnt += msgdsize(mp);
2292 #endif
2293 		putnext(q, mp);
2294 	}
2295 
2296 	ASSERT(cnt == tcp->tcp_rcv_cnt);
2297 	tcp->tcp_rcv_last_head = NULL;
2298 	tcp->tcp_rcv_last_tail = NULL;
2299 	tcp->tcp_rcv_cnt = 0;
2300 	tcp->tcp_rwnd = q->q_hiwat;
2301 
2302 	return (B_TRUE);
2303 }
2304 
2305 /*
2306  * This is the walker function, which is TCP specific.
2307  * It walks through the conn_hash bucket searching for the
2308  * next valid connp/tcp in the list, selecting connp/tcp
2309  * which haven't closed or condemned. It also REFHOLDS the
2310  * reference for the tcp, ensuring that the tcp exists
2311  * when the caller uses the tcp.
2312  *
2313  * tcp_get_next_conn
2314  * 	get the next entry in the conn global list
2315  * 	and put a reference on the next_conn.
2316  * 	decrement the reference on the current conn.
2317  */
2318 conn_t *
2319 tcp_get_next_conn(connf_t *connfp, conn_t *connp)
2320 {
2321 	conn_t	*next_connp;
2322 
2323 	if (connfp == NULL)
2324 		return (NULL);
2325 
2326 	mutex_enter(&connfp->connf_lock);
2327 
2328 	next_connp = (connp == NULL) ?
2329 	    connfp->connf_head : connp->conn_g_next;
2330 
2331 	while (next_connp != NULL) {
2332 		mutex_enter(&next_connp->conn_lock);
2333 		if ((next_connp->conn_state_flags &
2334 		    (CONN_CONDEMNED | CONN_INCIPIENT)) ||
2335 			!IPCL_IS_TCP(next_connp)) {
2336 			/*
2337 			 * This conn has been condemned or
2338 			 * is closing.
2339 			 */
2340 			mutex_exit(&next_connp->conn_lock);
2341 			next_connp = next_connp->conn_g_next;
2342 			continue;
2343 		}
2344 		ASSERT(next_connp->conn_tcp != NULL);
2345 		CONN_INC_REF_LOCKED(next_connp);
2346 		mutex_exit(&next_connp->conn_lock);
2347 		break;
2348 	}
2349 
2350 	mutex_exit(&connfp->connf_lock);
2351 
2352 	if (connp != NULL) {
2353 		CONN_DEC_REF(connp);
2354 	}
2355 
2356 	return (next_connp);
2357 }
2358 
2359 /*
2360  * Figure out the value of window scale opton.  Note that the rwnd is
2361  * ASSUMED to be rounded up to the nearest MSS before the calculation.
2362  * We cannot find the scale value and then do a round up of tcp_rwnd
2363  * because the scale value may not be correct after that.
2364  *
2365  * Set the compiler flag to make this function inline.
2366  */
2367 static void
2368 tcp_set_ws_value(tcp_t *tcp)
2369 {
2370 	int i;
2371 	uint32_t rwnd = tcp->tcp_rwnd;
2372 
2373 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
2374 	    i++, rwnd >>= 1)
2375 		;
2376 	tcp->tcp_rcv_ws = i;
2377 }
2378 
2379 /*
2380  * Remove a connection from the list of detached TIME_WAIT connections.
2381  */
2382 static void
2383 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
2384 {
2385 	boolean_t	locked = B_FALSE;
2386 
2387 	if (tcp_time_wait == NULL) {
2388 		tcp_time_wait = *((tcp_squeue_priv_t **)
2389 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
2390 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2391 		locked = B_TRUE;
2392 	}
2393 
2394 	if (tcp->tcp_time_wait_expire == 0) {
2395 		ASSERT(tcp->tcp_time_wait_next == NULL);
2396 		ASSERT(tcp->tcp_time_wait_prev == NULL);
2397 		if (locked)
2398 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2399 		return;
2400 	}
2401 	ASSERT(TCP_IS_DETACHED(tcp));
2402 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
2403 
2404 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
2405 		ASSERT(tcp->tcp_time_wait_prev == NULL);
2406 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
2407 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
2408 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
2409 			    NULL;
2410 		} else {
2411 			tcp_time_wait->tcp_time_wait_tail = NULL;
2412 		}
2413 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
2414 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
2415 		ASSERT(tcp->tcp_time_wait_next == NULL);
2416 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
2417 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
2418 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
2419 	} else {
2420 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
2421 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
2422 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
2423 		    tcp->tcp_time_wait_next;
2424 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
2425 		    tcp->tcp_time_wait_prev;
2426 	}
2427 	tcp->tcp_time_wait_next = NULL;
2428 	tcp->tcp_time_wait_prev = NULL;
2429 	tcp->tcp_time_wait_expire = 0;
2430 
2431 	if (locked)
2432 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2433 }
2434 
2435 /*
2436  * Add a connection to the list of detached TIME_WAIT connections
2437  * and set its time to expire.
2438  */
2439 static void
2440 tcp_time_wait_append(tcp_t *tcp)
2441 {
2442 	tcp_squeue_priv_t *tcp_time_wait =
2443 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
2444 		SQPRIVATE_TCP));
2445 
2446 	tcp_timers_stop(tcp);
2447 
2448 	/* Freed above */
2449 	ASSERT(tcp->tcp_timer_tid == 0);
2450 	ASSERT(tcp->tcp_ack_tid == 0);
2451 
2452 	/* must have happened at the time of detaching the tcp */
2453 	ASSERT(tcp->tcp_ptpahn == NULL);
2454 	ASSERT(tcp->tcp_flow_stopped == 0);
2455 	ASSERT(tcp->tcp_time_wait_next == NULL);
2456 	ASSERT(tcp->tcp_time_wait_prev == NULL);
2457 	ASSERT(tcp->tcp_time_wait_expire == NULL);
2458 	ASSERT(tcp->tcp_listener == NULL);
2459 
2460 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
2461 	/*
2462 	 * The value computed below in tcp->tcp_time_wait_expire may
2463 	 * appear negative or wrap around. That is ok since our
2464 	 * interest is only in the difference between the current lbolt
2465 	 * value and tcp->tcp_time_wait_expire. But the value should not
2466 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
2467 	 * The corresponding comparison in tcp_time_wait_collector() uses
2468 	 * modular arithmetic.
2469 	 */
2470 	tcp->tcp_time_wait_expire +=
2471 	    drv_usectohz(tcp_time_wait_interval * 1000);
2472 	if (tcp->tcp_time_wait_expire == 0)
2473 		tcp->tcp_time_wait_expire = 1;
2474 
2475 	ASSERT(TCP_IS_DETACHED(tcp));
2476 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
2477 	ASSERT(tcp->tcp_time_wait_next == NULL);
2478 	ASSERT(tcp->tcp_time_wait_prev == NULL);
2479 	TCP_DBGSTAT(tcp_time_wait);
2480 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2481 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
2482 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
2483 		tcp_time_wait->tcp_time_wait_head = tcp;
2484 	} else {
2485 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
2486 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
2487 		    TCPS_TIME_WAIT);
2488 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
2489 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
2490 	}
2491 	tcp_time_wait->tcp_time_wait_tail = tcp;
2492 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2493 }
2494 
2495 /* ARGSUSED */
2496 void
2497 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
2498 {
2499 	conn_t	*connp = (conn_t *)arg;
2500 	tcp_t	*tcp = connp->conn_tcp;
2501 
2502 	ASSERT(tcp != NULL);
2503 	if (tcp->tcp_state == TCPS_CLOSED) {
2504 		return;
2505 	}
2506 
2507 	ASSERT((tcp->tcp_family == AF_INET &&
2508 	    tcp->tcp_ipversion == IPV4_VERSION) ||
2509 	    (tcp->tcp_family == AF_INET6 &&
2510 	    (tcp->tcp_ipversion == IPV4_VERSION ||
2511 	    tcp->tcp_ipversion == IPV6_VERSION)));
2512 	ASSERT(!tcp->tcp_listener);
2513 
2514 	TCP_STAT(tcp_time_wait_reap);
2515 	ASSERT(TCP_IS_DETACHED(tcp));
2516 
2517 	/*
2518 	 * Because they have no upstream client to rebind or tcp_close()
2519 	 * them later, we axe the connection here and now.
2520 	 */
2521 	tcp_close_detached(tcp);
2522 }
2523 
2524 void
2525 tcp_cleanup(tcp_t *tcp)
2526 {
2527 	mblk_t		*mp;
2528 	char		*tcp_iphc;
2529 	int		tcp_iphc_len;
2530 	int		tcp_hdr_grown;
2531 	tcp_sack_info_t	*tcp_sack_info;
2532 	conn_t		*connp = tcp->tcp_connp;
2533 
2534 	tcp_bind_hash_remove(tcp);
2535 	tcp_free(tcp);
2536 
2537 	conn_delete_ire(connp, NULL);
2538 	if (connp->conn_flags & IPCL_TCPCONN) {
2539 		if (connp->conn_latch != NULL)
2540 			IPLATCH_REFRELE(connp->conn_latch);
2541 		if (connp->conn_policy != NULL)
2542 			IPPH_REFRELE(connp->conn_policy);
2543 	}
2544 
2545 	/*
2546 	 * Since we will bzero the entire structure, we need to
2547 	 * remove it and reinsert it in global hash list. We
2548 	 * know the walkers can't get to this conn because we
2549 	 * had set CONDEMNED flag earlier and checked reference
2550 	 * under conn_lock so walker won't pick it and when we
2551 	 * go the ipcl_globalhash_remove() below, no walker
2552 	 * can get to it.
2553 	 */
2554 	ipcl_globalhash_remove(connp);
2555 
2556 	/* Save some state */
2557 	mp = tcp->tcp_timercache;
2558 
2559 	tcp_sack_info = tcp->tcp_sack_info;
2560 	tcp_iphc = tcp->tcp_iphc;
2561 	tcp_iphc_len = tcp->tcp_iphc_len;
2562 	tcp_hdr_grown = tcp->tcp_hdr_grown;
2563 
2564 	bzero(connp, sizeof (conn_t));
2565 	bzero(tcp, sizeof (tcp_t));
2566 
2567 	/* restore the state */
2568 	tcp->tcp_timercache = mp;
2569 
2570 	tcp->tcp_sack_info = tcp_sack_info;
2571 	tcp->tcp_iphc = tcp_iphc;
2572 	tcp->tcp_iphc_len = tcp_iphc_len;
2573 	tcp->tcp_hdr_grown = tcp_hdr_grown;
2574 
2575 
2576 	tcp->tcp_connp = connp;
2577 
2578 	connp->conn_tcp = tcp;
2579 	connp->conn_flags = IPCL_TCPCONN;
2580 	connp->conn_state_flags = CONN_INCIPIENT;
2581 	connp->conn_ulp = IPPROTO_TCP;
2582 	connp->conn_ref = 1;
2583 
2584 	ipcl_globalhash_insert(connp);
2585 }
2586 
2587 /*
2588  * Blows away all tcps whose TIME_WAIT has expired. List traversal
2589  * is done forwards from the head.
2590  */
2591 /* ARGSUSED */
2592 void
2593 tcp_time_wait_collector(void *arg)
2594 {
2595 	tcp_t *tcp;
2596 	clock_t now;
2597 	mblk_t *mp;
2598 	conn_t *connp;
2599 	kmutex_t *lock;
2600 
2601 	squeue_t *sqp = (squeue_t *)arg;
2602 	tcp_squeue_priv_t *tcp_time_wait =
2603 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
2604 
2605 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2606 	tcp_time_wait->tcp_time_wait_tid = 0;
2607 
2608 	if (tcp_time_wait->tcp_free_list != NULL &&
2609 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
2610 		TCP_STAT(tcp_freelist_cleanup);
2611 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
2612 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
2613 			CONN_DEC_REF(tcp->tcp_connp);
2614 		}
2615 	}
2616 
2617 	/*
2618 	 * In order to reap time waits reliably, we should use a
2619 	 * source of time that is not adjustable by the user -- hence
2620 	 * the call to ddi_get_lbolt().
2621 	 */
2622 	now = ddi_get_lbolt();
2623 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
2624 		/*
2625 		 * Compare times using modular arithmetic, since
2626 		 * lbolt can wrapover.
2627 		 */
2628 		if ((now - tcp->tcp_time_wait_expire) < 0) {
2629 			break;
2630 		}
2631 
2632 		tcp_time_wait_remove(tcp, tcp_time_wait);
2633 
2634 		connp = tcp->tcp_connp;
2635 		ASSERT(connp->conn_fanout != NULL);
2636 		lock = &connp->conn_fanout->connf_lock;
2637 		/*
2638 		 * This is essentially a TW reclaim fast path optimization for
2639 		 * performance where the timewait collector checks under the
2640 		 * fanout lock (so that no one else can get access to the
2641 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
2642 		 * the classifier hash list. If ref count is indeed 2, we can
2643 		 * just remove the conn under the fanout lock and avoid
2644 		 * cleaning up the conn under the squeue, provided that
2645 		 * clustering callbacks are not enabled. If clustering is
2646 		 * enabled, we need to make the clustering callback before
2647 		 * setting the CONDEMNED flag and after dropping all locks and
2648 		 * so we forego this optimization and fall back to the slow
2649 		 * path. Also please see the comments in tcp_closei_local
2650 		 * regarding the refcnt logic.
2651 		 *
2652 		 * Since we are holding the tcp_time_wait_lock, its better
2653 		 * not to block on the fanout_lock because other connections
2654 		 * can't add themselves to time_wait list. So we do a
2655 		 * tryenter instead of mutex_enter.
2656 		 */
2657 		if (mutex_tryenter(lock)) {
2658 			mutex_enter(&connp->conn_lock);
2659 			if ((connp->conn_ref == 2) &&
2660 			    (cl_inet_disconnect == NULL)) {
2661 				ipcl_hash_remove_locked(connp,
2662 				    connp->conn_fanout);
2663 				/*
2664 				 * Set the CONDEMNED flag now itself so that
2665 				 * the refcnt cannot increase due to any
2666 				 * walker. But we have still not cleaned up
2667 				 * conn_ire_cache. This is still ok since
2668 				 * we are going to clean it up in tcp_cleanup
2669 				 * immediately and any interface unplumb
2670 				 * thread will wait till the ire is blown away
2671 				 */
2672 				connp->conn_state_flags |= CONN_CONDEMNED;
2673 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2674 				mutex_exit(lock);
2675 				mutex_exit(&connp->conn_lock);
2676 				tcp_cleanup(tcp);
2677 				mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2678 				tcp->tcp_time_wait_next =
2679 				    tcp_time_wait->tcp_free_list;
2680 				tcp_time_wait->tcp_free_list = tcp;
2681 				continue;
2682 			} else {
2683 				CONN_INC_REF_LOCKED(connp);
2684 				mutex_exit(lock);
2685 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2686 				mutex_exit(&connp->conn_lock);
2687 				/*
2688 				 * We can reuse the closemp here since conn has
2689 				 * detached (otherwise we wouldn't even be in
2690 				 * time_wait list).
2691 				 */
2692 				mp = &tcp->tcp_closemp;
2693 				squeue_fill(connp->conn_sqp, mp,
2694 				    tcp_timewait_output, connp,
2695 				    SQTAG_TCP_TIMEWAIT);
2696 			}
2697 		} else {
2698 			mutex_enter(&connp->conn_lock);
2699 			CONN_INC_REF_LOCKED(connp);
2700 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2701 			mutex_exit(&connp->conn_lock);
2702 			/*
2703 			 * We can reuse the closemp here since conn has
2704 			 * detached (otherwise we wouldn't even be in
2705 			 * time_wait list).
2706 			 */
2707 			mp = &tcp->tcp_closemp;
2708 			squeue_fill(connp->conn_sqp, mp,
2709 			    tcp_timewait_output, connp, 0);
2710 		}
2711 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
2712 	}
2713 
2714 	if (tcp_time_wait->tcp_free_list != NULL)
2715 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
2716 
2717 	tcp_time_wait->tcp_time_wait_tid =
2718 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
2719 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
2720 }
2721 
2722 /*
2723  * Reply to a clients T_CONN_RES TPI message. This function
2724  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
2725  * on the acceptor STREAM and processed in tcp_wput_accept().
2726  * Read the block comment on top of tcp_conn_request().
2727  */
2728 static void
2729 tcp_accept(tcp_t *listener, mblk_t *mp)
2730 {
2731 	tcp_t	*acceptor;
2732 	tcp_t	*eager;
2733 	tcp_t   *tcp;
2734 	struct T_conn_res	*tcr;
2735 	t_uscalar_t	acceptor_id;
2736 	t_scalar_t	seqnum;
2737 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
2738 	mblk_t	*ok_mp;
2739 	mblk_t	*mp1;
2740 
2741 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
2742 		tcp_err_ack(listener, mp, TPROTO, 0);
2743 		return;
2744 	}
2745 	tcr = (struct T_conn_res *)mp->b_rptr;
2746 
2747 	/*
2748 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
2749 	 * read side queue of the streams device underneath us i.e. the
2750 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
2751 	 * look it up in the queue_hash.  Under LP64 it sends down the
2752 	 * minor_t of the accepting endpoint.
2753 	 *
2754 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
2755 	 * fanout hash lock is held.
2756 	 * This prevents any thread from entering the acceptor queue from
2757 	 * below (since it has not been hard bound yet i.e. any inbound
2758 	 * packets will arrive on the listener or default tcp queue and
2759 	 * go through tcp_lookup).
2760 	 * The CONN_INC_REF will prevent the acceptor from closing.
2761 	 *
2762 	 * XXX It is still possible for a tli application to send down data
2763 	 * on the accepting stream while another thread calls t_accept.
2764 	 * This should not be a problem for well-behaved applications since
2765 	 * the T_OK_ACK is sent after the queue swapping is completed.
2766 	 *
2767 	 * If the accepting fd is the same as the listening fd, avoid
2768 	 * queue hash lookup since that will return an eager listener in a
2769 	 * already established state.
2770 	 */
2771 	acceptor_id = tcr->ACCEPTOR_id;
2772 	mutex_enter(&listener->tcp_eager_lock);
2773 	if (listener->tcp_acceptor_id == acceptor_id) {
2774 		eager = listener->tcp_eager_next_q;
2775 		/* only count how many T_CONN_INDs so don't count q0 */
2776 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2777 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2778 			mutex_exit(&listener->tcp_eager_lock);
2779 			tcp_err_ack(listener, mp, TBADF, 0);
2780 			return;
2781 		}
2782 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2783 			/* Throw away all the eagers on q0. */
2784 			tcp_eager_cleanup(listener, 1);
2785 		}
2786 		if (listener->tcp_syn_defense) {
2787 			listener->tcp_syn_defense = B_FALSE;
2788 			if (listener->tcp_ip_addr_cache != NULL) {
2789 				kmem_free(listener->tcp_ip_addr_cache,
2790 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2791 				listener->tcp_ip_addr_cache = NULL;
2792 			}
2793 		}
2794 		/*
2795 		 * Transfer tcp_conn_req_max to the eager so that when
2796 		 * a disconnect occurs we can revert the endpoint to the
2797 		 * listen state.
2798 		 */
2799 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2800 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2801 		/*
2802 		 * Get a reference on the acceptor just like the
2803 		 * tcp_acceptor_hash_lookup below.
2804 		 */
2805 		acceptor = listener;
2806 		CONN_INC_REF(acceptor->tcp_connp);
2807 	} else {
2808 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
2809 		if (acceptor == NULL) {
2810 			if (listener->tcp_debug) {
2811 				(void) strlog(TCP_MODULE_ID, 0, 1,
2812 				    SL_ERROR|SL_TRACE,
2813 				    "tcp_accept: did not find acceptor 0x%x\n",
2814 				    acceptor_id);
2815 			}
2816 			mutex_exit(&listener->tcp_eager_lock);
2817 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2818 			return;
2819 		}
2820 		/*
2821 		 * Verify acceptor state. The acceptable states for an acceptor
2822 		 * include TCPS_IDLE and TCPS_BOUND.
2823 		 */
2824 		switch (acceptor->tcp_state) {
2825 		case TCPS_IDLE:
2826 			/* FALLTHRU */
2827 		case TCPS_BOUND:
2828 			break;
2829 		default:
2830 			CONN_DEC_REF(acceptor->tcp_connp);
2831 			mutex_exit(&listener->tcp_eager_lock);
2832 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2833 			return;
2834 		}
2835 	}
2836 
2837 	/* The listener must be in TCPS_LISTEN */
2838 	if (listener->tcp_state != TCPS_LISTEN) {
2839 		CONN_DEC_REF(acceptor->tcp_connp);
2840 		mutex_exit(&listener->tcp_eager_lock);
2841 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2842 		return;
2843 	}
2844 
2845 	/*
2846 	 * Rendezvous with an eager connection request packet hanging off
2847 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2848 	 * tcp structure when the connection packet arrived in
2849 	 * tcp_conn_request().
2850 	 */
2851 	seqnum = tcr->SEQ_number;
2852 	eager = listener;
2853 	do {
2854 		eager = eager->tcp_eager_next_q;
2855 		if (eager == NULL) {
2856 			CONN_DEC_REF(acceptor->tcp_connp);
2857 			mutex_exit(&listener->tcp_eager_lock);
2858 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2859 			return;
2860 		}
2861 	} while (eager->tcp_conn_req_seqnum != seqnum);
2862 	mutex_exit(&listener->tcp_eager_lock);
2863 
2864 	/*
2865 	 * At this point, both acceptor and listener have 2 ref
2866 	 * that they begin with. Acceptor has one additional ref
2867 	 * we placed in lookup while listener has 3 additional
2868 	 * ref for being behind the squeue (tcp_accept() is
2869 	 * done on listener's squeue); being in classifier hash;
2870 	 * and eager's ref on listener.
2871 	 */
2872 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2873 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2874 
2875 	/*
2876 	 * The eager at this point is set in its own squeue and
2877 	 * could easily have been killed (tcp_accept_finish will
2878 	 * deal with that) because of a TH_RST so we can only
2879 	 * ASSERT for a single ref.
2880 	 */
2881 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2882 
2883 	/* Pre allocate the stroptions mblk also */
2884 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2885 	if (opt_mp == NULL) {
2886 		CONN_DEC_REF(acceptor->tcp_connp);
2887 		CONN_DEC_REF(eager->tcp_connp);
2888 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2889 		return;
2890 	}
2891 	DB_TYPE(opt_mp) = M_SETOPTS;
2892 	opt_mp->b_wptr += sizeof (struct stroptions);
2893 
2894 	/*
2895 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2896 	 * from listener to acceptor. The message is chained on opt_mp
2897 	 * which will be sent onto eager's squeue.
2898 	 */
2899 	if (listener->tcp_bound_if != 0) {
2900 		/* allocate optmgmt req */
2901 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2902 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2903 		    sizeof (int));
2904 		if (mp1 != NULL)
2905 			linkb(opt_mp, mp1);
2906 	}
2907 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2908 		uint_t on = 1;
2909 
2910 		/* allocate optmgmt req */
2911 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2912 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2913 		if (mp1 != NULL)
2914 			linkb(opt_mp, mp1);
2915 	}
2916 
2917 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2918 	if ((mp1 = copymsg(mp)) == NULL) {
2919 		CONN_DEC_REF(acceptor->tcp_connp);
2920 		CONN_DEC_REF(eager->tcp_connp);
2921 		freemsg(opt_mp);
2922 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2923 		return;
2924 	}
2925 
2926 	tcr = (struct T_conn_res *)mp1->b_rptr;
2927 
2928 	/*
2929 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2930 	 * which allocates a larger mblk and appends the new
2931 	 * local address to the ok_ack.  The address is copied by
2932 	 * soaccept() for getsockname().
2933 	 */
2934 	{
2935 		int extra;
2936 
2937 		extra = (eager->tcp_family == AF_INET) ?
2938 		    sizeof (sin_t) : sizeof (sin6_t);
2939 
2940 		/*
2941 		 * Try to re-use mp, if possible.  Otherwise, allocate
2942 		 * an mblk and return it as ok_mp.  In any case, mp
2943 		 * is no longer usable upon return.
2944 		 */
2945 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2946 			CONN_DEC_REF(acceptor->tcp_connp);
2947 			CONN_DEC_REF(eager->tcp_connp);
2948 			freemsg(opt_mp);
2949 			/* Original mp has been freed by now, so use mp1 */
2950 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2951 			return;
2952 		}
2953 
2954 		mp = NULL;	/* We should never use mp after this point */
2955 
2956 		switch (extra) {
2957 		case sizeof (sin_t): {
2958 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2959 
2960 				ok_mp->b_wptr += extra;
2961 				sin->sin_family = AF_INET;
2962 				sin->sin_port = eager->tcp_lport;
2963 				sin->sin_addr.s_addr =
2964 				    eager->tcp_ipha->ipha_src;
2965 				break;
2966 			}
2967 		case sizeof (sin6_t): {
2968 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2969 
2970 				ok_mp->b_wptr += extra;
2971 				sin6->sin6_family = AF_INET6;
2972 				sin6->sin6_port = eager->tcp_lport;
2973 				if (eager->tcp_ipversion == IPV4_VERSION) {
2974 					sin6->sin6_flowinfo = 0;
2975 					IN6_IPADDR_TO_V4MAPPED(
2976 					    eager->tcp_ipha->ipha_src,
2977 					    &sin6->sin6_addr);
2978 				} else {
2979 					ASSERT(eager->tcp_ip6h != NULL);
2980 					sin6->sin6_flowinfo =
2981 					    eager->tcp_ip6h->ip6_vcf &
2982 					    ~IPV6_VERS_AND_FLOW_MASK;
2983 					sin6->sin6_addr =
2984 					    eager->tcp_ip6h->ip6_src;
2985 				}
2986 				break;
2987 			}
2988 		default:
2989 			break;
2990 		}
2991 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2992 	}
2993 
2994 	/*
2995 	 * If there are no options we know that the T_CONN_RES will
2996 	 * succeed. However, we can't send the T_OK_ACK upstream until
2997 	 * the tcp_accept_swap is done since it would be dangerous to
2998 	 * let the application start using the new fd prior to the swap.
2999 	 */
3000 	tcp_accept_swap(listener, acceptor, eager);
3001 
3002 	/*
3003 	 * tcp_accept_swap unlinks eager from listener but does not drop
3004 	 * the eager's reference on the listener.
3005 	 */
3006 	ASSERT(eager->tcp_listener == NULL);
3007 	ASSERT(listener->tcp_connp->conn_ref >= 5);
3008 
3009 	/*
3010 	 * The eager is now associated with its own queue. Insert in
3011 	 * the hash so that the connection can be reused for a future
3012 	 * T_CONN_RES.
3013 	 */
3014 	tcp_acceptor_hash_insert(acceptor_id, eager);
3015 
3016 	/*
3017 	 * We now do the processing of options with T_CONN_RES.
3018 	 * We delay till now since we wanted to have queue to pass to
3019 	 * option processing routines that points back to the right
3020 	 * instance structure which does not happen until after
3021 	 * tcp_accept_swap().
3022 	 *
3023 	 * Note:
3024 	 * The sanity of the logic here assumes that whatever options
3025 	 * are appropriate to inherit from listner=>eager are done
3026 	 * before this point, and whatever were to be overridden (or not)
3027 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
3028 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
3029 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
3030 	 * This may not be true at this point in time but can be fixed
3031 	 * independently. This option processing code starts with
3032 	 * the instantiated acceptor instance and the final queue at
3033 	 * this point.
3034 	 */
3035 
3036 	if (tcr->OPT_length != 0) {
3037 		/* Options to process */
3038 		int t_error = 0;
3039 		int sys_error = 0;
3040 		int do_disconnect = 0;
3041 
3042 		if (tcp_conprim_opt_process(eager, mp1,
3043 		    &do_disconnect, &t_error, &sys_error) < 0) {
3044 			eager->tcp_accept_error = 1;
3045 			if (do_disconnect) {
3046 				/*
3047 				 * An option failed which does not allow
3048 				 * connection to be accepted.
3049 				 *
3050 				 * We allow T_CONN_RES to succeed and
3051 				 * put a T_DISCON_IND on the eager queue.
3052 				 */
3053 				ASSERT(t_error == 0 && sys_error == 0);
3054 				eager->tcp_send_discon_ind = 1;
3055 			} else {
3056 				ASSERT(t_error != 0);
3057 				freemsg(ok_mp);
3058 				/*
3059 				 * Original mp was either freed or set
3060 				 * to ok_mp above, so use mp1 instead.
3061 				 */
3062 				tcp_err_ack(listener, mp1, t_error, sys_error);
3063 				goto finish;
3064 			}
3065 		}
3066 		/*
3067 		 * Most likely success in setting options (except if
3068 		 * eager->tcp_send_discon_ind set).
3069 		 * mp1 option buffer represented by OPT_length/offset
3070 		 * potentially modified and contains results of setting
3071 		 * options at this point
3072 		 */
3073 	}
3074 
3075 	/* We no longer need mp1, since all options processing has passed */
3076 	freemsg(mp1);
3077 
3078 	putnext(listener->tcp_rq, ok_mp);
3079 
3080 	mutex_enter(&listener->tcp_eager_lock);
3081 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
3082 		tcp_t	*tail;
3083 		mblk_t	*conn_ind;
3084 
3085 		/*
3086 		 * This path should not be executed if listener and
3087 		 * acceptor streams are the same.
3088 		 */
3089 		ASSERT(listener != acceptor);
3090 
3091 		tcp = listener->tcp_eager_prev_q0;
3092 		/*
3093 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
3094 		 * deferred T_conn_ind queue. We need to get to the head of
3095 		 * the queue in order to send up T_conn_ind the same order as
3096 		 * how the 3WHS is completed.
3097 		 */
3098 		while (tcp != listener) {
3099 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
3100 				break;
3101 			else
3102 				tcp = tcp->tcp_eager_prev_q0;
3103 		}
3104 		ASSERT(tcp != listener);
3105 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
3106 		ASSERT(conn_ind != NULL);
3107 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
3108 
3109 		/* Move from q0 to q */
3110 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
3111 		listener->tcp_conn_req_cnt_q0--;
3112 		listener->tcp_conn_req_cnt_q++;
3113 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
3114 		    tcp->tcp_eager_prev_q0;
3115 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
3116 		    tcp->tcp_eager_next_q0;
3117 		tcp->tcp_eager_prev_q0 = NULL;
3118 		tcp->tcp_eager_next_q0 = NULL;
3119 		tcp->tcp_conn_def_q0 = B_FALSE;
3120 
3121 		/*
3122 		 * Insert at end of the queue because sockfs sends
3123 		 * down T_CONN_RES in chronological order. Leaving
3124 		 * the older conn indications at front of the queue
3125 		 * helps reducing search time.
3126 		 */
3127 		tail = listener->tcp_eager_last_q;
3128 		if (tail != NULL)
3129 			tail->tcp_eager_next_q = tcp;
3130 		else
3131 			listener->tcp_eager_next_q = tcp;
3132 		listener->tcp_eager_last_q = tcp;
3133 		tcp->tcp_eager_next_q = NULL;
3134 		mutex_exit(&listener->tcp_eager_lock);
3135 		putnext(tcp->tcp_rq, conn_ind);
3136 	} else {
3137 		mutex_exit(&listener->tcp_eager_lock);
3138 	}
3139 
3140 	/*
3141 	 * Done with the acceptor - free it
3142 	 *
3143 	 * Note: from this point on, no access to listener should be made
3144 	 * as listener can be equal to acceptor.
3145 	 */
3146 finish:
3147 	ASSERT(acceptor->tcp_detached);
3148 	acceptor->tcp_rq = tcp_g_q;
3149 	acceptor->tcp_wq = WR(tcp_g_q);
3150 	(void) tcp_clean_death(acceptor, 0, 2);
3151 	CONN_DEC_REF(acceptor->tcp_connp);
3152 
3153 	/*
3154 	 * In case we already received a FIN we have to make tcp_rput send
3155 	 * the ordrel_ind. This will also send up a window update if the window
3156 	 * has opened up.
3157 	 *
3158 	 * In the normal case of a successful connection acceptance
3159 	 * we give the O_T_BIND_REQ to the read side put procedure as an
3160 	 * indication that this was just accepted. This tells tcp_rput to
3161 	 * pass up any data queued in tcp_rcv_list.
3162 	 *
3163 	 * In the fringe case where options sent with T_CONN_RES failed and
3164 	 * we required, we would be indicating a T_DISCON_IND to blow
3165 	 * away this connection.
3166 	 */
3167 
3168 	/*
3169 	 * XXX: we currently have a problem if XTI application closes the
3170 	 * acceptor stream in between. This problem exists in on10-gate also
3171 	 * and is well know but nothing can be done short of major rewrite
3172 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
3173 	 * eager same squeue as listener (we can distinguish non socket
3174 	 * listeners at the time of handling a SYN in tcp_conn_request)
3175 	 * and do most of the work that tcp_accept_finish does here itself
3176 	 * and then get behind the acceptor squeue to access the acceptor
3177 	 * queue.
3178 	 */
3179 	/*
3180 	 * We already have a ref on tcp so no need to do one before squeue_fill
3181 	 */
3182 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
3183 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
3184 }
3185 
3186 /*
3187  * Swap information between the eager and acceptor for a TLI/XTI client.
3188  * The sockfs accept is done on the acceptor stream and control goes
3189  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
3190  * called. In either case, both the eager and listener are in their own
3191  * perimeter (squeue) and the code has to deal with potential race.
3192  *
3193  * See the block comment on top of tcp_accept() and tcp_wput_accept().
3194  */
3195 static void
3196 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
3197 {
3198 	conn_t	*econnp, *aconnp;
3199 
3200 	ASSERT(eager->tcp_rq == listener->tcp_rq);
3201 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
3202 	ASSERT(!eager->tcp_hard_bound);
3203 	ASSERT(!TCP_IS_SOCKET(acceptor));
3204 	ASSERT(!TCP_IS_SOCKET(eager));
3205 	ASSERT(!TCP_IS_SOCKET(listener));
3206 
3207 	acceptor->tcp_detached = B_TRUE;
3208 	/*
3209 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
3210 	 * the acceptor id.
3211 	 */
3212 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
3213 
3214 	/* remove eager from listen list... */
3215 	mutex_enter(&listener->tcp_eager_lock);
3216 	tcp_eager_unlink(eager);
3217 	ASSERT(eager->tcp_eager_next_q == NULL &&
3218 	    eager->tcp_eager_last_q == NULL);
3219 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
3220 	    eager->tcp_eager_prev_q0 == NULL);
3221 	mutex_exit(&listener->tcp_eager_lock);
3222 	eager->tcp_rq = acceptor->tcp_rq;
3223 	eager->tcp_wq = acceptor->tcp_wq;
3224 
3225 	econnp = eager->tcp_connp;
3226 	aconnp = acceptor->tcp_connp;
3227 
3228 	eager->tcp_rq->q_ptr = econnp;
3229 	eager->tcp_wq->q_ptr = econnp;
3230 	eager->tcp_detached = B_FALSE;
3231 
3232 	ASSERT(eager->tcp_ack_tid == 0);
3233 
3234 	econnp->conn_dev = aconnp->conn_dev;
3235 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
3236 	econnp->conn_zoneid = aconnp->conn_zoneid;
3237 	aconnp->conn_cred = NULL;
3238 
3239 	/* Do the IPC initialization */
3240 	CONN_INC_REF(econnp);
3241 
3242 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
3243 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
3244 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
3245 	econnp->conn_ulp = aconnp->conn_ulp;
3246 
3247 	/* Done with old IPC. Drop its ref on its connp */
3248 	CONN_DEC_REF(aconnp);
3249 }
3250 
3251 
3252 /*
3253  * Adapt to the information, such as rtt and rtt_sd, provided from the
3254  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
3255  *
3256  * Checks for multicast and broadcast destination address.
3257  * Returns zero on failure; non-zero if ok.
3258  *
3259  * Note that the MSS calculation here is based on the info given in
3260  * the IRE.  We do not do any calculation based on TCP options.  They
3261  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
3262  * knows which options to use.
3263  *
3264  * Note on how TCP gets its parameters for a connection.
3265  *
3266  * When a tcp_t structure is allocated, it gets all the default parameters.
3267  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
3268  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
3269  * default.  But if there is an associated tcp_host_param, it will override
3270  * the metrics.
3271  *
3272  * An incoming SYN with a multicast or broadcast destination address, is dropped
3273  * in 1 of 2 places.
3274  *
3275  * 1. If the packet was received over the wire it is dropped in
3276  * ip_rput_process_broadcast()
3277  *
3278  * 2. If the packet was received through internal IP loopback, i.e. the packet
3279  * was generated and received on the same machine, it is dropped in
3280  * ip_wput_local()
3281  *
3282  * An incoming SYN with a multicast or broadcast source address is always
3283  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
3284  * reject an attempt to connect to a broadcast or multicast (destination)
3285  * address.
3286  */
3287 static int
3288 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
3289 {
3290 	tcp_hsp_t	*hsp;
3291 	ire_t		*ire;
3292 	ire_t		*sire = NULL;
3293 	iulp_t		*ire_uinfo;
3294 	uint32_t	mss_max;
3295 	uint32_t	mss;
3296 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
3297 	conn_t		*connp = tcp->tcp_connp;
3298 	boolean_t	ire_cacheable = B_FALSE;
3299 	zoneid_t	zoneid = connp->conn_zoneid;
3300 	ill_t		*ill = NULL;
3301 	boolean_t	incoming = (ire_mp == NULL);
3302 
3303 	ASSERT(connp->conn_ire_cache == NULL);
3304 
3305 	if (tcp->tcp_ipversion == IPV4_VERSION) {
3306 
3307 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
3308 			BUMP_MIB(&ip_mib, ipInDiscards);
3309 			return (0);
3310 		}
3311 
3312 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
3313 		if (ire != NULL) {
3314 			ire_cacheable = B_TRUE;
3315 			ire_uinfo = (ire_mp != NULL) ?
3316 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
3317 			    &ire->ire_uinfo;
3318 
3319 		} else {
3320 			if (ire_mp == NULL) {
3321 				ire = ire_ftable_lookup(
3322 				    tcp->tcp_connp->conn_rem,
3323 				    0, 0, 0, NULL, &sire, zoneid, 0,
3324 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
3325 				if (ire == NULL)
3326 					return (0);
3327 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
3328 				    &ire->ire_uinfo;
3329 			} else {
3330 				ire = (ire_t *)ire_mp->b_rptr;
3331 				ire_uinfo =
3332 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
3333 			}
3334 		}
3335 		ASSERT(ire != NULL);
3336 		ASSERT(ire_uinfo != NULL);
3337 
3338 		if ((ire->ire_src_addr == INADDR_ANY) ||
3339 		    (ire->ire_type & IRE_BROADCAST)) {
3340 			/*
3341 			 * ire->ire_mp is non null when ire_mp passed in is used
3342 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
3343 			 */
3344 			if (ire->ire_mp == NULL)
3345 				ire_refrele(ire);
3346 			if (sire != NULL)
3347 				ire_refrele(sire);
3348 			return (0);
3349 		}
3350 
3351 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
3352 			ipaddr_t src_addr;
3353 
3354 			/*
3355 			 * ip_bind_connected() has stored the correct source
3356 			 * address in conn_src.
3357 			 */
3358 			src_addr = tcp->tcp_connp->conn_src;
3359 			tcp->tcp_ipha->ipha_src = src_addr;
3360 			/*
3361 			 * Copy of the src addr. in tcp_t is needed
3362 			 * for the lookup funcs.
3363 			 */
3364 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
3365 		}
3366 		/*
3367 		 * Set the fragment bit so that IP will tell us if the MTU
3368 		 * should change. IP tells us the latest setting of
3369 		 * ip_path_mtu_discovery through ire_frag_flag.
3370 		 */
3371 		if (ip_path_mtu_discovery) {
3372 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
3373 			    htons(IPH_DF);
3374 		}
3375 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
3376 	} else {
3377 		/*
3378 		 * For incoming connection ire_mp = NULL
3379 		 * For outgoing connection ire_mp != NULL
3380 		 * Technically we should check conn_incoming_ill
3381 		 * when ire_mp is NULL and conn_outgoing_ill when
3382 		 * ire_mp is non-NULL. But this is performance
3383 		 * critical path and for IPV*_BOUND_IF, outgoing
3384 		 * and incoming ill are always set to the same value.
3385 		 */
3386 		ill_t	*dst_ill = NULL;
3387 		ipif_t  *dst_ipif = NULL;
3388 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
3389 
3390 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
3391 
3392 		if (connp->conn_outgoing_ill != NULL) {
3393 			/* Outgoing or incoming path */
3394 			int   err;
3395 
3396 			dst_ill = conn_get_held_ill(connp,
3397 			    &connp->conn_outgoing_ill, &err);
3398 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
3399 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
3400 				return (0);
3401 			}
3402 			match_flags |= MATCH_IRE_ILL;
3403 			dst_ipif = dst_ill->ill_ipif;
3404 		}
3405 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
3406 		    0, 0, dst_ipif, zoneid, match_flags);
3407 
3408 		if (ire != NULL) {
3409 			ire_cacheable = B_TRUE;
3410 			ire_uinfo = (ire_mp != NULL) ?
3411 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
3412 			    &ire->ire_uinfo;
3413 		} else {
3414 			if (ire_mp == NULL) {
3415 				ire = ire_ftable_lookup_v6(
3416 				    &tcp->tcp_connp->conn_remv6,
3417 				    0, 0, 0, dst_ipif, &sire, zoneid,
3418 				    0, match_flags);
3419 				if (ire == NULL) {
3420 					if (dst_ill != NULL)
3421 						ill_refrele(dst_ill);
3422 					return (0);
3423 				}
3424 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
3425 				    &ire->ire_uinfo;
3426 			} else {
3427 				ire = (ire_t *)ire_mp->b_rptr;
3428 				ire_uinfo =
3429 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
3430 			}
3431 		}
3432 		if (dst_ill != NULL)
3433 			ill_refrele(dst_ill);
3434 
3435 		ASSERT(ire != NULL);
3436 		ASSERT(ire_uinfo != NULL);
3437 
3438 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
3439 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
3440 			/*
3441 			 * ire->ire_mp is non null when ire_mp passed in is used
3442 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
3443 			 */
3444 			if (ire->ire_mp == NULL)
3445 				ire_refrele(ire);
3446 			if (sire != NULL)
3447 				ire_refrele(sire);
3448 			return (0);
3449 		}
3450 
3451 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
3452 			in6_addr_t	src_addr;
3453 
3454 			/*
3455 			 * ip_bind_connected_v6() has stored the correct source
3456 			 * address per IPv6 addr. selection policy in
3457 			 * conn_src_v6.
3458 			 */
3459 			src_addr = tcp->tcp_connp->conn_srcv6;
3460 
3461 			tcp->tcp_ip6h->ip6_src = src_addr;
3462 			/*
3463 			 * Copy of the src addr. in tcp_t is needed
3464 			 * for the lookup funcs.
3465 			 */
3466 			tcp->tcp_ip_src_v6 = src_addr;
3467 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
3468 			    &connp->conn_srcv6));
3469 		}
3470 		tcp->tcp_localnet =
3471 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
3472 	}
3473 
3474 	/*
3475 	 * This allows applications to fail quickly when connections are made
3476 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
3477 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
3478 	 */
3479 	if ((ire->ire_flags & RTF_REJECT) &&
3480 	    (ire->ire_flags & RTF_PRIVATE))
3481 		goto error;
3482 
3483 	/*
3484 	 * Make use of the cached rtt and rtt_sd values to calculate the
3485 	 * initial RTO.  Note that they are already initialized in
3486 	 * tcp_init_values().
3487 	 */
3488 	if (ire_uinfo->iulp_rtt != 0) {
3489 		clock_t	rto;
3490 
3491 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
3492 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
3493 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
3494 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
3495 
3496 		if (rto > tcp_rexmit_interval_max) {
3497 			tcp->tcp_rto = tcp_rexmit_interval_max;
3498 		} else if (rto < tcp_rexmit_interval_min) {
3499 			tcp->tcp_rto = tcp_rexmit_interval_min;
3500 		} else {
3501 			tcp->tcp_rto = rto;
3502 		}
3503 	}
3504 	if (ire_uinfo->iulp_ssthresh != 0)
3505 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
3506 	else
3507 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
3508 	if (ire_uinfo->iulp_spipe > 0) {
3509 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
3510 		    tcp_max_buf);
3511 		if (tcp_snd_lowat_fraction != 0)
3512 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
3513 			    tcp_snd_lowat_fraction;
3514 		(void) tcp_maxpsz_set(tcp, B_TRUE);
3515 	}
3516 	/*
3517 	 * Note that up till now, acceptor always inherits receive
3518 	 * window from the listener.  But if there is a metrics associated
3519 	 * with a host, we should use that instead of inheriting it from
3520 	 * listener.  Thus we need to pass this info back to the caller.
3521 	 */
3522 	if (ire_uinfo->iulp_rpipe > 0) {
3523 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
3524 	} else {
3525 		/*
3526 		 * For passive open, set tcp_rwnd to 0 so that the caller
3527 		 * knows that there is no rpipe metric for this connection.
3528 		 */
3529 		if (tcp_detached)
3530 			tcp->tcp_rwnd = 0;
3531 	}
3532 	if (ire_uinfo->iulp_rtomax > 0) {
3533 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
3534 	}
3535 
3536 	/*
3537 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
3538 	 * only for active open.  What this means is that if the other side
3539 	 * uses timestamp or window scale option, TCP will also use those
3540 	 * options.  That is for passive open.  If the application sets a
3541 	 * large window, window scale is enabled regardless of the value in
3542 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
3543 	 * The only case left in passive open processing is the check for SACK.
3544 	 *
3545 	 * For ECN, it should probably be like SACK.  But the current
3546 	 * value is binary, so we treat it like the other cases.  The
3547 	 * metric only controls active open.  For passive open, the ndd
3548 	 * param, tcp_ecn_permitted, controls the behavior.
3549 	 */
3550 	if (!tcp_detached) {
3551 		/*
3552 		 * The if check means that the following can only be turned
3553 		 * on by the metrics only IRE, but not off.
3554 		 */
3555 		if (ire_uinfo->iulp_tstamp_ok)
3556 			tcp->tcp_snd_ts_ok = B_TRUE;
3557 		if (ire_uinfo->iulp_wscale_ok)
3558 			tcp->tcp_snd_ws_ok = B_TRUE;
3559 		if (ire_uinfo->iulp_sack == 2)
3560 			tcp->tcp_snd_sack_ok = B_TRUE;
3561 		if (ire_uinfo->iulp_ecn_ok)
3562 			tcp->tcp_ecn_ok = B_TRUE;
3563 	} else {
3564 		/*
3565 		 * Passive open.
3566 		 *
3567 		 * As above, the if check means that SACK can only be
3568 		 * turned on by the metric only IRE.
3569 		 */
3570 		if (ire_uinfo->iulp_sack > 0) {
3571 			tcp->tcp_snd_sack_ok = B_TRUE;
3572 		}
3573 	}
3574 
3575 	/*
3576 	 * XXX: Note that currently, ire_max_frag can be as small as 68
3577 	 * because of PMTUd.  So tcp_mss may go to negative if combined
3578 	 * length of all those options exceeds 28 bytes.  But because
3579 	 * of the tcp_mss_min check below, we may not have a problem if
3580 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
3581 	 * the negative problem still exists.  And the check defeats PMTUd.
3582 	 * In fact, if PMTUd finds that the MSS should be smaller than
3583 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
3584 	 * value.
3585 	 *
3586 	 * We do not deal with that now.  All those problems related to
3587 	 * PMTUd will be fixed later.
3588 	 */
3589 	ASSERT(ire->ire_max_frag != 0);
3590 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
3591 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
3592 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
3593 			mss = MIN(mss, IPV6_MIN_MTU);
3594 		}
3595 	}
3596 
3597 	/* Sanity check for MSS value. */
3598 	if (tcp->tcp_ipversion == IPV4_VERSION)
3599 		mss_max = tcp_mss_max_ipv4;
3600 	else
3601 		mss_max = tcp_mss_max_ipv6;
3602 
3603 	if (tcp->tcp_ipversion == IPV6_VERSION &&
3604 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
3605 		/*
3606 		 * After receiving an ICMPv6 "packet too big" message with a
3607 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3608 		 * will insert a 8-byte fragment header in every packet; we
3609 		 * reduce the MSS by that amount here.
3610 		 */
3611 		mss -= sizeof (ip6_frag_t);
3612 	}
3613 
3614 	if (tcp->tcp_ipsec_overhead == 0)
3615 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
3616 
3617 	mss -= tcp->tcp_ipsec_overhead;
3618 
3619 	if (mss < tcp_mss_min)
3620 		mss = tcp_mss_min;
3621 	if (mss > mss_max)
3622 		mss = mss_max;
3623 
3624 	/* Note that this is the maximum MSS, excluding all options. */
3625 	tcp->tcp_mss = mss;
3626 
3627 	/*
3628 	 * Initialize the ISS here now that we have the full connection ID.
3629 	 * The RFC 1948 method of initial sequence number generation requires
3630 	 * knowledge of the full connection ID before setting the ISS.
3631 	 */
3632 
3633 	tcp_iss_init(tcp);
3634 
3635 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
3636 		tcp->tcp_loopback = B_TRUE;
3637 
3638 	if (tcp->tcp_ipversion == IPV4_VERSION) {
3639 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
3640 	} else {
3641 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
3642 	}
3643 
3644 	if (hsp != NULL) {
3645 		/* Only modify if we're going to make them bigger */
3646 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
3647 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
3648 			if (tcp_snd_lowat_fraction != 0)
3649 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
3650 					tcp_snd_lowat_fraction;
3651 		}
3652 
3653 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
3654 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
3655 		}
3656 
3657 		/* Copy timestamp flag only for active open */
3658 		if (!tcp_detached)
3659 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
3660 	}
3661 
3662 	if (sire != NULL)
3663 		IRE_REFRELE(sire);
3664 
3665 	/*
3666 	 * If we got an IRE_CACHE and an ILL, go through their properties;
3667 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
3668 	 */
3669 	if (tcp->tcp_loopback ||
3670 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
3671 		/*
3672 		 * For incoming, see if this tcp may be MDT-capable.  For
3673 		 * outgoing, this process has been taken care of through
3674 		 * tcp_rput_other.
3675 		 */
3676 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3677 		tcp->tcp_ire_ill_check_done = B_TRUE;
3678 	}
3679 
3680 	mutex_enter(&connp->conn_lock);
3681 	/*
3682 	 * Make sure that conn is not marked incipient
3683 	 * for incoming connections. A blind
3684 	 * removal of incipient flag is cheaper than
3685 	 * check and removal.
3686 	 */
3687 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3688 
3689 	/* Must not cache forwarding table routes. */
3690 	if (ire_cacheable) {
3691 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3692 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3693 			connp->conn_ire_cache = ire;
3694 			IRE_UNTRACE_REF(ire);
3695 			rw_exit(&ire->ire_bucket->irb_lock);
3696 			mutex_exit(&connp->conn_lock);
3697 			return (1);
3698 		}
3699 		rw_exit(&ire->ire_bucket->irb_lock);
3700 	}
3701 	mutex_exit(&connp->conn_lock);
3702 
3703 	if (ire->ire_mp == NULL)
3704 		ire_refrele(ire);
3705 	return (1);
3706 
3707 error:
3708 	if (ire->ire_mp == NULL)
3709 		ire_refrele(ire);
3710 	if (sire != NULL)
3711 		ire_refrele(sire);
3712 	return (0);
3713 }
3714 
3715 /*
3716  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3717  * O_T_BIND_REQ/T_BIND_REQ message.
3718  */
3719 static void
3720 tcp_bind(tcp_t *tcp, mblk_t *mp)
3721 {
3722 	sin_t	*sin;
3723 	sin6_t	*sin6;
3724 	mblk_t	*mp1;
3725 	in_port_t requested_port;
3726 	in_port_t allocated_port;
3727 	struct T_bind_req *tbr;
3728 	boolean_t	bind_to_req_port_only;
3729 	boolean_t	backlog_update = B_FALSE;
3730 	boolean_t	user_specified;
3731 	in6_addr_t	v6addr;
3732 	ipaddr_t	v4addr;
3733 	uint_t	origipversion;
3734 	int	err;
3735 	queue_t *q = tcp->tcp_wq;
3736 
3737 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3738 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3739 		if (tcp->tcp_debug) {
3740 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3741 			    "tcp_bind: bad req, len %u",
3742 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3743 		}
3744 		tcp_err_ack(tcp, mp, TPROTO, 0);
3745 		return;
3746 	}
3747 	/* Make sure the largest address fits */
3748 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3749 	if (mp1 == NULL) {
3750 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3751 		return;
3752 	}
3753 	mp = mp1;
3754 	tbr = (struct T_bind_req *)mp->b_rptr;
3755 	if (tcp->tcp_state >= TCPS_BOUND) {
3756 		if ((tcp->tcp_state == TCPS_BOUND ||
3757 		    tcp->tcp_state == TCPS_LISTEN) &&
3758 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3759 		    tbr->CONIND_number > 0) {
3760 			/*
3761 			 * Handle listen() increasing CONIND_number.
3762 			 * This is more "liberal" then what the TPI spec
3763 			 * requires but is needed to avoid a t_unbind
3764 			 * when handling listen() since the port number
3765 			 * might be "stolen" between the unbind and bind.
3766 			 */
3767 			backlog_update = B_TRUE;
3768 			goto do_bind;
3769 		}
3770 		if (tcp->tcp_debug) {
3771 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3772 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3773 		}
3774 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3775 		return;
3776 	}
3777 	origipversion = tcp->tcp_ipversion;
3778 
3779 	switch (tbr->ADDR_length) {
3780 	case 0:			/* request for a generic port */
3781 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3782 		if (tcp->tcp_family == AF_INET) {
3783 			tbr->ADDR_length = sizeof (sin_t);
3784 			sin = (sin_t *)&tbr[1];
3785 			*sin = sin_null;
3786 			sin->sin_family = AF_INET;
3787 			mp->b_wptr = (uchar_t *)&sin[1];
3788 			tcp->tcp_ipversion = IPV4_VERSION;
3789 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3790 		} else {
3791 			ASSERT(tcp->tcp_family == AF_INET6);
3792 			tbr->ADDR_length = sizeof (sin6_t);
3793 			sin6 = (sin6_t *)&tbr[1];
3794 			*sin6 = sin6_null;
3795 			sin6->sin6_family = AF_INET6;
3796 			mp->b_wptr = (uchar_t *)&sin6[1];
3797 			tcp->tcp_ipversion = IPV6_VERSION;
3798 			V6_SET_ZERO(v6addr);
3799 		}
3800 		requested_port = 0;
3801 		break;
3802 
3803 	case sizeof (sin_t):	/* Complete IPv4 address */
3804 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3805 		    sizeof (sin_t));
3806 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3807 			if (tcp->tcp_debug) {
3808 				(void) strlog(TCP_MODULE_ID, 0, 1,
3809 				    SL_ERROR|SL_TRACE,
3810 				    "tcp_bind: bad address parameter, "
3811 				    "offset %d, len %d",
3812 				    tbr->ADDR_offset, tbr->ADDR_length);
3813 			}
3814 			tcp_err_ack(tcp, mp, TPROTO, 0);
3815 			return;
3816 		}
3817 		/*
3818 		 * With sockets sockfs will accept bogus sin_family in
3819 		 * bind() and replace it with the family used in the socket
3820 		 * call.
3821 		 */
3822 		if (sin->sin_family != AF_INET ||
3823 		    tcp->tcp_family != AF_INET) {
3824 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3825 			return;
3826 		}
3827 		requested_port = ntohs(sin->sin_port);
3828 		tcp->tcp_ipversion = IPV4_VERSION;
3829 		v4addr = sin->sin_addr.s_addr;
3830 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3831 		break;
3832 
3833 	case sizeof (sin6_t): /* Complete IPv6 address */
3834 		sin6 = (sin6_t *)mi_offset_param(mp,
3835 		    tbr->ADDR_offset, sizeof (sin6_t));
3836 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3837 			if (tcp->tcp_debug) {
3838 				(void) strlog(TCP_MODULE_ID, 0, 1,
3839 				    SL_ERROR|SL_TRACE,
3840 				    "tcp_bind: bad IPv6 address parameter, "
3841 				    "offset %d, len %d", tbr->ADDR_offset,
3842 				    tbr->ADDR_length);
3843 			}
3844 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3845 			return;
3846 		}
3847 		if (sin6->sin6_family != AF_INET6 ||
3848 		    tcp->tcp_family != AF_INET6) {
3849 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3850 			return;
3851 		}
3852 		requested_port = ntohs(sin6->sin6_port);
3853 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3854 		    IPV4_VERSION : IPV6_VERSION;
3855 		v6addr = sin6->sin6_addr;
3856 		break;
3857 
3858 	default:
3859 		if (tcp->tcp_debug) {
3860 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
3861 			    "tcp_bind: bad address length, %d",
3862 			    tbr->ADDR_length);
3863 		}
3864 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3865 		return;
3866 	}
3867 	tcp->tcp_bound_source_v6 = v6addr;
3868 
3869 	/* Check for change in ipversion */
3870 	if (origipversion != tcp->tcp_ipversion) {
3871 		ASSERT(tcp->tcp_family == AF_INET6);
3872 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3873 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3874 		if (err) {
3875 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3876 			return;
3877 		}
3878 	}
3879 
3880 	/*
3881 	 * Initialize family specific fields. Copy of the src addr.
3882 	 * in tcp_t is needed for the lookup funcs.
3883 	 */
3884 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3885 		tcp->tcp_ip6h->ip6_src = v6addr;
3886 	} else {
3887 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3888 	}
3889 	tcp->tcp_ip_src_v6 = v6addr;
3890 
3891 	/*
3892 	 * For O_T_BIND_REQ:
3893 	 * Verify that the target port/addr is available, or choose
3894 	 * another.
3895 	 * For  T_BIND_REQ:
3896 	 * Verify that the target port/addr is available or fail.
3897 	 * In both cases when it succeeds the tcp is inserted in the
3898 	 * bind hash table. This ensures that the operation is atomic
3899 	 * under the lock on the hash bucket.
3900 	 */
3901 	bind_to_req_port_only = requested_port != 0 &&
3902 	    tbr->PRIM_type != O_T_BIND_REQ;
3903 	/*
3904 	 * Get a valid port (within the anonymous range and should not
3905 	 * be a privileged one) to use if the user has not given a port.
3906 	 * If multiple threads are here, they may all start with
3907 	 * with the same initial port. But, it should be fine as long as
3908 	 * tcp_bindi will ensure that no two threads will be assigned
3909 	 * the same port.
3910 	 *
3911 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3912 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3913 	 * unless TCP_ANONPRIVBIND option is set.
3914 	 */
3915 	if (requested_port == 0) {
3916 		requested_port = tcp->tcp_anon_priv_bind ?
3917 		    tcp_get_next_priv_port() :
3918 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3919 		user_specified = B_FALSE;
3920 	} else {
3921 		int i;
3922 		boolean_t priv = B_FALSE;
3923 		/*
3924 		 * If the requested_port is in the well-known privileged range,
3925 		 * verify that the stream was opened by a privileged user.
3926 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3927 		 * but instead the code relies on:
3928 		 * - the fact that the address of the array and its size never
3929 		 *   changes
3930 		 * - the atomic assignment of the elements of the array
3931 		 */
3932 		if (requested_port < tcp_smallest_nonpriv_port) {
3933 			priv = B_TRUE;
3934 		} else {
3935 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3936 				if (requested_port ==
3937 				    tcp_g_epriv_ports[i]) {
3938 					priv = B_TRUE;
3939 					break;
3940 				}
3941 			}
3942 		}
3943 		if (priv) {
3944 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3945 
3946 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3947 				if (tcp->tcp_debug) {
3948 					(void) strlog(TCP_MODULE_ID, 0, 1,
3949 					    SL_ERROR|SL_TRACE,
3950 					    "tcp_bind: no priv for port %d",
3951 					    requested_port);
3952 				}
3953 				tcp_err_ack(tcp, mp, TACCES, 0);
3954 				return;
3955 			}
3956 		}
3957 		user_specified = B_TRUE;
3958 	}
3959 
3960 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3961 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3962 
3963 	if (allocated_port == 0) {
3964 		if (bind_to_req_port_only) {
3965 			if (tcp->tcp_debug) {
3966 				(void) strlog(TCP_MODULE_ID, 0, 1,
3967 				    SL_ERROR|SL_TRACE,
3968 				    "tcp_bind: requested addr busy");
3969 			}
3970 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3971 		} else {
3972 			/* If we are out of ports, fail the bind. */
3973 			if (tcp->tcp_debug) {
3974 				(void) strlog(TCP_MODULE_ID, 0, 1,
3975 				    SL_ERROR|SL_TRACE,
3976 				    "tcp_bind: out of ports?");
3977 			}
3978 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3979 		}
3980 		return;
3981 	}
3982 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3983 do_bind:
3984 	if (!backlog_update) {
3985 		if (tcp->tcp_family == AF_INET)
3986 			sin->sin_port = htons(allocated_port);
3987 		else
3988 			sin6->sin6_port = htons(allocated_port);
3989 	}
3990 	if (tcp->tcp_family == AF_INET) {
3991 		if (tbr->CONIND_number != 0) {
3992 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3993 			    sizeof (sin_t));
3994 		} else {
3995 			/* Just verify the local IP address */
3996 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3997 		}
3998 	} else {
3999 		if (tbr->CONIND_number != 0) {
4000 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
4001 			    sizeof (sin6_t));
4002 		} else {
4003 			/* Just verify the local IP address */
4004 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
4005 			    IPV6_ADDR_LEN);
4006 		}
4007 	}
4008 	if (!mp1) {
4009 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
4010 		return;
4011 	}
4012 
4013 	tbr->PRIM_type = T_BIND_ACK;
4014 	mp->b_datap->db_type = M_PCPROTO;
4015 
4016 	/* Chain in the reply mp for tcp_rput() */
4017 	mp1->b_cont = mp;
4018 	mp = mp1;
4019 
4020 	tcp->tcp_conn_req_max = tbr->CONIND_number;
4021 	if (tcp->tcp_conn_req_max) {
4022 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
4023 			tcp->tcp_conn_req_max = tcp_conn_req_min;
4024 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
4025 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
4026 		/*
4027 		 * If this is a listener, do not reset the eager list
4028 		 * and other stuffs.  Note that we don't check if the
4029 		 * existing eager list meets the new tcp_conn_req_max
4030 		 * requirement.
4031 		 */
4032 		if (tcp->tcp_state != TCPS_LISTEN) {
4033 			tcp->tcp_state = TCPS_LISTEN;
4034 			/* Initialize the chain. Don't need the eager_lock */
4035 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
4036 			tcp->tcp_second_ctimer_threshold =
4037 			    tcp_ip_abort_linterval;
4038 		}
4039 	}
4040 
4041 	/*
4042 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
4043 	 * processing continues in tcp_rput_other().
4044 	 */
4045 	if (tcp->tcp_family == AF_INET6) {
4046 		ASSERT(tcp->tcp_connp->conn_af_isv6);
4047 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
4048 	} else {
4049 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
4050 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
4051 	}
4052 	/*
4053 	 * If the bind cannot complete immediately
4054 	 * IP will arrange to call tcp_rput_other
4055 	 * when the bind completes.
4056 	 */
4057 	if (mp != NULL) {
4058 		tcp_rput_other(tcp, mp);
4059 	} else {
4060 		/*
4061 		 * Bind will be resumed later. Need to ensure
4062 		 * that conn doesn't disappear when that happens.
4063 		 * This will be decremented in ip_resume_tcp_bind().
4064 		 */
4065 		CONN_INC_REF(tcp->tcp_connp);
4066 	}
4067 }
4068 
4069 
4070 /*
4071  * If the "bind_to_req_port_only" parameter is set, if the requested port
4072  * number is available, return it, If not return 0
4073  *
4074  * If "bind_to_req_port_only" parameter is not set and
4075  * If the requested port number is available, return it.  If not, return
4076  * the first anonymous port we happen across.  If no anonymous ports are
4077  * available, return 0. addr is the requested local address, if any.
4078  *
4079  * In either case, when succeeding update the tcp_t to record the port number
4080  * and insert it in the bind hash table.
4081  *
4082  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
4083  * without setting SO_REUSEADDR. This is needed so that they
4084  * can be viewed as two independent transport protocols.
4085  */
4086 static in_port_t
4087 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
4088     int reuseaddr, boolean_t quick_connect,
4089     boolean_t bind_to_req_port_only, boolean_t user_specified)
4090 {
4091 	/* number of times we have run around the loop */
4092 	int count = 0;
4093 	/* maximum number of times to run around the loop */
4094 	int loopmax;
4095 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
4096 
4097 	/*
4098 	 * Lookup for free addresses is done in a loop and "loopmax"
4099 	 * influences how long we spin in the loop
4100 	 */
4101 	if (bind_to_req_port_only) {
4102 		/*
4103 		 * If the requested port is busy, don't bother to look
4104 		 * for a new one. Setting loop maximum count to 1 has
4105 		 * that effect.
4106 		 */
4107 		loopmax = 1;
4108 	} else {
4109 		/*
4110 		 * If the requested port is busy, look for a free one
4111 		 * in the anonymous port range.
4112 		 * Set loopmax appropriately so that one does not look
4113 		 * forever in the case all of the anonymous ports are in use.
4114 		 */
4115 		if (tcp->tcp_anon_priv_bind) {
4116 			/*
4117 			 * loopmax =
4118 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
4119 			 */
4120 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
4121 		} else {
4122 			loopmax = (tcp_largest_anon_port -
4123 			    tcp_smallest_anon_port + 1);
4124 		}
4125 	}
4126 	do {
4127 		uint16_t	lport;
4128 		tf_t		*tbf;
4129 		tcp_t		*ltcp;
4130 
4131 		lport = htons(port);
4132 
4133 		/*
4134 		 * Ensure that the tcp_t is not currently in the bind hash.
4135 		 * Hold the lock on the hash bucket to ensure that
4136 		 * the duplicate check plus the insertion is an atomic
4137 		 * operation.
4138 		 *
4139 		 * This function does an inline lookup on the bind hash list
4140 		 * Make sure that we access only members of tcp_t
4141 		 * and that we don't look at tcp_tcp, since we are not
4142 		 * doing a CONN_INC_REF.
4143 		 */
4144 		tcp_bind_hash_remove(tcp);
4145 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
4146 		mutex_enter(&tbf->tf_lock);
4147 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
4148 		    ltcp = ltcp->tcp_bind_hash) {
4149 			if (lport != ltcp->tcp_lport ||
4150 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
4151 				continue;
4152 			}
4153 
4154 			/*
4155 			 * If TCP_EXCLBIND is set for either the bound or
4156 			 * binding endpoint, the semantics of bind
4157 			 * is changed according to the following.
4158 			 *
4159 			 * spec = specified address (v4 or v6)
4160 			 * unspec = unspecified address (v4 or v6)
4161 			 * A = specified addresses are different for endpoints
4162 			 *
4163 			 * bound	bind to		allowed
4164 			 * -------------------------------------
4165 			 * unspec	unspec		no
4166 			 * unspec	spec		no
4167 			 * spec		unspec		no
4168 			 * spec		spec		yes if A
4169 			 *
4170 			 * Note:
4171 			 *
4172 			 * 1. Because of TLI semantics, an endpoint can go
4173 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
4174 			 * TCPS_BOUND, depending on whether it is originally
4175 			 * a listener or not.  That is why we need to check
4176 			 * for states greater than or equal to TCPS_BOUND
4177 			 * here.
4178 			 *
4179 			 * 2. Ideally, we should only check for state equals
4180 			 * to TCPS_LISTEN. And the following check should be
4181 			 * added.
4182 			 *
4183 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
4184 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
4185 			 *		...
4186 			 * }
4187 			 *
4188 			 * The semantics will be changed to this.  If the
4189 			 * endpoint on the list is in state not equal to
4190 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
4191 			 * set, let the bind succeed.
4192 			 *
4193 			 * But because of (1), we cannot do that now.  If
4194 			 * in future, we can change this going back semantics,
4195 			 * we can add the above check.
4196 			 */
4197 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
4198 				if (V6_OR_V4_INADDR_ANY(
4199 				    ltcp->tcp_bound_source_v6) ||
4200 				    V6_OR_V4_INADDR_ANY(*laddr) ||
4201 				    IN6_ARE_ADDR_EQUAL(laddr,
4202 				    &ltcp->tcp_bound_source_v6)) {
4203 					break;
4204 				}
4205 				continue;
4206 			}
4207 
4208 			/*
4209 			 * Check ipversion to allow IPv4 and IPv6 sockets to
4210 			 * have disjoint port number spaces, if *_EXCLBIND
4211 			 * is not set and only if the application binds to a
4212 			 * specific port. We use the same autoassigned port
4213 			 * number space for IPv4 and IPv6 sockets.
4214 			 */
4215 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
4216 			    bind_to_req_port_only)
4217 				continue;
4218 
4219 			/*
4220 			 * Ideally, we should make sure that the source
4221 			 * address, remote address, and remote port in the
4222 			 * four tuple for this tcp-connection is unique.
4223 			 * However, trying to find out the local source
4224 			 * address would require too much code duplication
4225 			 * with IP, since IP needs needs to have that code
4226 			 * to support userland TCP implementations.
4227 			 */
4228 			if (quick_connect &&
4229 			    (ltcp->tcp_state > TCPS_LISTEN) &&
4230 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
4231 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
4232 				    &ltcp->tcp_remote_v6)))
4233 				continue;
4234 
4235 			if (!reuseaddr) {
4236 				/*
4237 				 * No socket option SO_REUSEADDR.
4238 				 * If existing port is bound to
4239 				 * a non-wildcard IP address
4240 				 * and the requesting stream is
4241 				 * bound to a distinct
4242 				 * different IP addresses
4243 				 * (non-wildcard, also), keep
4244 				 * going.
4245 				 */
4246 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
4247 				    !V6_OR_V4_INADDR_ANY(
4248 				    ltcp->tcp_bound_source_v6) &&
4249 				    !IN6_ARE_ADDR_EQUAL(laddr,
4250 					&ltcp->tcp_bound_source_v6))
4251 					continue;
4252 				if (ltcp->tcp_state >= TCPS_BOUND) {
4253 					/*
4254 					 * This port is being used and
4255 					 * its state is >= TCPS_BOUND,
4256 					 * so we can't bind to it.
4257 					 */
4258 					break;
4259 				}
4260 			} else {
4261 				/*
4262 				 * socket option SO_REUSEADDR is set on the
4263 				 * binding tcp_t.
4264 				 *
4265 				 * If two streams are bound to
4266 				 * same IP address or both addr
4267 				 * and bound source are wildcards
4268 				 * (INADDR_ANY), we want to stop
4269 				 * searching.
4270 				 * We have found a match of IP source
4271 				 * address and source port, which is
4272 				 * refused regardless of the
4273 				 * SO_REUSEADDR setting, so we break.
4274 				 */
4275 				if (IN6_ARE_ADDR_EQUAL(laddr,
4276 				    &ltcp->tcp_bound_source_v6) &&
4277 				    (ltcp->tcp_state == TCPS_LISTEN ||
4278 					ltcp->tcp_state == TCPS_BOUND))
4279 					break;
4280 			}
4281 		}
4282 		if (ltcp != NULL) {
4283 			/* The port number is busy */
4284 			mutex_exit(&tbf->tf_lock);
4285 		} else {
4286 			/*
4287 			 * This port is ours. Insert in fanout and mark as
4288 			 * bound to prevent others from getting the port
4289 			 * number.
4290 			 */
4291 			tcp->tcp_state = TCPS_BOUND;
4292 			tcp->tcp_lport = htons(port);
4293 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
4294 
4295 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
4296 			    tcp->tcp_lport)] == tbf);
4297 			tcp_bind_hash_insert(tbf, tcp, 1);
4298 
4299 			mutex_exit(&tbf->tf_lock);
4300 
4301 			/*
4302 			 * We don't want tcp_next_port_to_try to "inherit"
4303 			 * a port number supplied by the user in a bind.
4304 			 */
4305 			if (user_specified)
4306 				return (port);
4307 
4308 			/*
4309 			 * This is the only place where tcp_next_port_to_try
4310 			 * is updated. After the update, it may or may not
4311 			 * be in the valid range.
4312 			 */
4313 			if (!tcp->tcp_anon_priv_bind)
4314 				tcp_next_port_to_try = port + 1;
4315 			return (port);
4316 		}
4317 
4318 		if (tcp->tcp_anon_priv_bind) {
4319 			port = tcp_get_next_priv_port();
4320 		} else {
4321 			if (count == 0 && user_specified) {
4322 				/*
4323 				 * We may have to return an anonymous port. So
4324 				 * get one to start with.
4325 				 */
4326 				port =
4327 				    tcp_update_next_port(tcp_next_port_to_try,
4328 					B_TRUE);
4329 				user_specified = B_FALSE;
4330 			} else {
4331 				port = tcp_update_next_port(port + 1, B_FALSE);
4332 			}
4333 		}
4334 
4335 		/*
4336 		 * Don't let this loop run forever in the case where
4337 		 * all of the anonymous ports are in use.
4338 		 */
4339 	} while (++count < loopmax);
4340 	return (0);
4341 }
4342 
4343 /*
4344  * We are dying for some reason.  Try to do it gracefully.  (May be called
4345  * as writer.)
4346  *
4347  * Return -1 if the structure was not cleaned up (if the cleanup had to be
4348  * done by a service procedure).
4349  * TBD - Should the return value distinguish between the tcp_t being
4350  * freed and it being reinitialized?
4351  */
4352 static int
4353 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
4354 {
4355 	mblk_t	*mp;
4356 	queue_t	*q;
4357 
4358 	TCP_CLD_STAT(tag);
4359 
4360 #if TCP_TAG_CLEAN_DEATH
4361 	tcp->tcp_cleandeathtag = tag;
4362 #endif
4363 
4364 	if (tcp->tcp_linger_tid != 0 &&
4365 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4366 		tcp_stop_lingering(tcp);
4367 	}
4368 
4369 	ASSERT(tcp != NULL);
4370 	ASSERT((tcp->tcp_family == AF_INET &&
4371 	    tcp->tcp_ipversion == IPV4_VERSION) ||
4372 	    (tcp->tcp_family == AF_INET6 &&
4373 	    (tcp->tcp_ipversion == IPV4_VERSION ||
4374 	    tcp->tcp_ipversion == IPV6_VERSION)));
4375 
4376 	if (TCP_IS_DETACHED(tcp)) {
4377 		if (tcp->tcp_hard_binding) {
4378 			/*
4379 			 * Its an eager that we are dealing with. We close the
4380 			 * eager but in case a conn_ind has already gone to the
4381 			 * listener, let tcp_accept_finish() send a discon_ind
4382 			 * to the listener and drop the last reference. If the
4383 			 * listener doesn't even know about the eager i.e. the
4384 			 * conn_ind hasn't gone up, blow away the eager and drop
4385 			 * the last reference as well. If the conn_ind has gone
4386 			 * up, state should be BOUND. tcp_accept_finish
4387 			 * will figure out that the connection has received a
4388 			 * RST and will send a DISCON_IND to the application.
4389 			 */
4390 			tcp_closei_local(tcp);
4391 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4392 				CONN_DEC_REF(tcp->tcp_connp);
4393 			} else {
4394 				tcp->tcp_state = TCPS_BOUND;
4395 			}
4396 		} else {
4397 			tcp_close_detached(tcp);
4398 		}
4399 		return (0);
4400 	}
4401 
4402 	TCP_STAT(tcp_clean_death_nondetached);
4403 
4404 	/*
4405 	 * If T_ORDREL_IND has not been sent yet (done when service routine
4406 	 * is run) postpone cleaning up the endpoint until service routine
4407 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
4408 	 * client_errno since tcp_close uses the client_errno field.
4409 	 */
4410 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
4411 		if (err != 0)
4412 			tcp->tcp_client_errno = err;
4413 
4414 		tcp->tcp_deferred_clean_death = B_TRUE;
4415 		return (-1);
4416 	}
4417 
4418 	q = tcp->tcp_rq;
4419 
4420 	/* Trash all inbound data */
4421 	flushq(q, FLUSHALL);
4422 
4423 	/*
4424 	 * If we are at least part way open and there is error
4425 	 * (err==0 implies no error)
4426 	 * notify our client by a T_DISCON_IND.
4427 	 */
4428 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
4429 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
4430 		    !TCP_IS_SOCKET(tcp)) {
4431 			/*
4432 			 * Send M_FLUSH according to TPI. Because sockets will
4433 			 * (and must) ignore FLUSHR we do that only for TPI
4434 			 * endpoints and sockets in STREAMS mode.
4435 			 */
4436 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
4437 		}
4438 		if (tcp->tcp_debug) {
4439 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
4440 			    "tcp_clean_death: discon err %d", err);
4441 		}
4442 		mp = mi_tpi_discon_ind(NULL, err, 0);
4443 		if (mp != NULL) {
4444 			putnext(q, mp);
4445 		} else {
4446 			if (tcp->tcp_debug) {
4447 				(void) strlog(TCP_MODULE_ID, 0, 1,
4448 				    SL_ERROR|SL_TRACE,
4449 				    "tcp_clean_death, sending M_ERROR");
4450 			}
4451 			(void) putnextctl1(q, M_ERROR, EPROTO);
4452 		}
4453 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
4454 			/* SYN_SENT or SYN_RCVD */
4455 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4456 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
4457 			/* ESTABLISHED or CLOSE_WAIT */
4458 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4459 		}
4460 	}
4461 
4462 	tcp_reinit(tcp);
4463 	return (-1);
4464 }
4465 
4466 /*
4467  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
4468  * to expire, stop the wait and finish the close.
4469  */
4470 static void
4471 tcp_stop_lingering(tcp_t *tcp)
4472 {
4473 	clock_t	delta = 0;
4474 
4475 	tcp->tcp_linger_tid = 0;
4476 	if (tcp->tcp_state > TCPS_LISTEN) {
4477 		tcp_acceptor_hash_remove(tcp);
4478 		if (tcp->tcp_flow_stopped) {
4479 			tcp->tcp_flow_stopped = B_FALSE;
4480 			tcp_clrqfull(tcp);
4481 		}
4482 
4483 		if (tcp->tcp_timer_tid != 0) {
4484 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4485 			tcp->tcp_timer_tid = 0;
4486 		}
4487 		/*
4488 		 * Need to cancel those timers which will not be used when
4489 		 * TCP is detached.  This has to be done before the tcp_wq
4490 		 * is set to the global queue.
4491 		 */
4492 		tcp_timers_stop(tcp);
4493 
4494 
4495 		tcp->tcp_detached = B_TRUE;
4496 		tcp->tcp_rq = tcp_g_q;
4497 		tcp->tcp_wq = WR(tcp_g_q);
4498 
4499 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4500 			tcp_time_wait_append(tcp);
4501 			TCP_DBGSTAT(tcp_detach_time_wait);
4502 			goto finish;
4503 		}
4504 
4505 		/*
4506 		 * If delta is zero the timer event wasn't executed and was
4507 		 * successfully canceled. In this case we need to restart it
4508 		 * with the minimal delta possible.
4509 		 */
4510 		if (delta >= 0) {
4511 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4512 			    delta ? delta : 1);
4513 		}
4514 	} else {
4515 		tcp_closei_local(tcp);
4516 		CONN_DEC_REF(tcp->tcp_connp);
4517 	}
4518 finish:
4519 	/* Signal closing thread that it can complete close */
4520 	mutex_enter(&tcp->tcp_closelock);
4521 	tcp->tcp_detached = B_TRUE;
4522 	tcp->tcp_rq = tcp_g_q;
4523 	tcp->tcp_wq = WR(tcp_g_q);
4524 	tcp->tcp_closed = 1;
4525 	cv_signal(&tcp->tcp_closecv);
4526 	mutex_exit(&tcp->tcp_closelock);
4527 }
4528 
4529 /*
4530  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
4531  * expires.
4532  */
4533 static void
4534 tcp_close_linger_timeout(void *arg)
4535 {
4536 	conn_t	*connp = (conn_t *)arg;
4537 	tcp_t 	*tcp = connp->conn_tcp;
4538 
4539 	tcp->tcp_client_errno = ETIMEDOUT;
4540 	tcp_stop_lingering(tcp);
4541 }
4542 
4543 static int
4544 tcp_close(queue_t *q, int flags)
4545 {
4546 	conn_t		*connp = Q_TO_CONN(q);
4547 	tcp_t		*tcp = connp->conn_tcp;
4548 	mblk_t 		*mp = &tcp->tcp_closemp;
4549 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4550 
4551 	ASSERT(WR(q)->q_next == NULL);
4552 	ASSERT(connp->conn_ref >= 2);
4553 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
4554 
4555 	/*
4556 	 * We are being closed as /dev/tcp or /dev/tcp6.
4557 	 *
4558 	 * Mark the conn as closing. ill_pending_mp_add will not
4559 	 * add any mp to the pending mp list, after this conn has
4560 	 * started closing. Same for sq_pending_mp_add
4561 	 */
4562 	mutex_enter(&connp->conn_lock);
4563 	connp->conn_state_flags |= CONN_CLOSING;
4564 	if (connp->conn_oper_pending_ill != NULL)
4565 		conn_ioctl_cleanup_reqd = B_TRUE;
4566 	CONN_INC_REF_LOCKED(connp);
4567 	mutex_exit(&connp->conn_lock);
4568 	tcp->tcp_closeflags = (uint8_t)flags;
4569 	ASSERT(connp->conn_ref >= 3);
4570 
4571 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4572 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4573 
4574 	mutex_enter(&tcp->tcp_closelock);
4575 	while (!tcp->tcp_closed)
4576 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4577 	mutex_exit(&tcp->tcp_closelock);
4578 	/*
4579 	 * In the case of listener streams that have eagers in the q or q0
4580 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4581 	 * tcp_wq of the eagers point to our queues. By waiting for the
4582 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4583 	 * up their queue pointers and also dropped their references to us.
4584 	 */
4585 	if (tcp->tcp_wait_for_eagers) {
4586 		mutex_enter(&connp->conn_lock);
4587 		while (connp->conn_ref != 1) {
4588 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4589 		}
4590 		mutex_exit(&connp->conn_lock);
4591 	}
4592 	/*
4593 	 * ioctl cleanup. The mp is queued in the
4594 	 * ill_pending_mp or in the sq_pending_mp.
4595 	 */
4596 	if (conn_ioctl_cleanup_reqd)
4597 		conn_ioctl_cleanup(connp);
4598 
4599 	qprocsoff(q);
4600 	inet_minor_free(ip_minor_arena, connp->conn_dev);
4601 
4602 	ASSERT(connp->conn_cred != NULL);
4603 	crfree(connp->conn_cred);
4604 	tcp->tcp_cred = connp->conn_cred = NULL;
4605 	tcp->tcp_cpid = -1;
4606 
4607 	/*
4608 	 * Drop IP's reference on the conn. This is the last reference
4609 	 * on the connp if the state was less than established. If the
4610 	 * connection has gone into timewait state, then we will have
4611 	 * one ref for the TCP and one more ref (total of two) for the
4612 	 * classifier connected hash list (a timewait connections stays
4613 	 * in connected hash till closed).
4614 	 *
4615 	 * We can't assert the references because there might be other
4616 	 * transient reference places because of some walkers or queued
4617 	 * packets in squeue for the timewait state.
4618 	 */
4619 	CONN_DEC_REF(connp);
4620 	q->q_ptr = WR(q)->q_ptr = NULL;
4621 	return (0);
4622 }
4623 
4624 int
4625 tcp_modclose(queue_t *q)
4626 {
4627 	conn_t *connp = Q_TO_CONN(q);
4628 	ASSERT((connp->conn_flags & IPCL_TCPMOD) != 0);
4629 
4630 	qprocsoff(q);
4631 
4632 	if (connp->conn_cred != NULL) {
4633 		crfree(connp->conn_cred);
4634 		connp->conn_cred = NULL;
4635 	}
4636 	CONN_DEC_REF(connp);
4637 	q->q_ptr = WR(q)->q_ptr = NULL;
4638 	return (0);
4639 }
4640 
4641 static int
4642 tcpclose_accept(queue_t *q)
4643 {
4644 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4645 
4646 	/*
4647 	 * We had opened an acceptor STREAM for sockfs which is
4648 	 * now being closed due to some error.
4649 	 */
4650 	qprocsoff(q);
4651 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4652 	q->q_ptr = WR(q)->q_ptr = NULL;
4653 	return (0);
4654 }
4655 
4656 
4657 /*
4658  * Called by streams close routine via squeues when our client blows off her
4659  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4660  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4661  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4662  * acked.
4663  *
4664  * NOTE: tcp_close potentially returns error when lingering.
4665  * However, the stream head currently does not pass these errors
4666  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4667  * errors to the application (from tsleep()) and not errors
4668  * like ECONNRESET caused by receiving a reset packet.
4669  */
4670 
4671 /* ARGSUSED */
4672 static void
4673 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4674 {
4675 	char	*msg;
4676 	conn_t	*connp = (conn_t *)arg;
4677 	tcp_t	*tcp = connp->conn_tcp;
4678 	clock_t	delta = 0;
4679 
4680 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4681 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4682 
4683 	/* Cancel any pending timeout */
4684 	if (tcp->tcp_ordrelid != 0) {
4685 		if (tcp->tcp_timeout) {
4686 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4687 		}
4688 		tcp->tcp_ordrelid = 0;
4689 		tcp->tcp_timeout = B_FALSE;
4690 	}
4691 
4692 	mutex_enter(&tcp->tcp_eager_lock);
4693 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4694 		/* Cleanup for listener */
4695 		tcp_eager_cleanup(tcp, 0);
4696 		tcp->tcp_wait_for_eagers = 1;
4697 	}
4698 	mutex_exit(&tcp->tcp_eager_lock);
4699 
4700 	connp->conn_mdt_ok = B_FALSE;
4701 	tcp->tcp_mdt = B_FALSE;
4702 
4703 	msg = NULL;
4704 	switch (tcp->tcp_state) {
4705 	case TCPS_CLOSED:
4706 	case TCPS_IDLE:
4707 	case TCPS_BOUND:
4708 	case TCPS_LISTEN:
4709 		break;
4710 	case TCPS_SYN_SENT:
4711 		msg = "tcp_close, during connect";
4712 		break;
4713 	case TCPS_SYN_RCVD:
4714 		/*
4715 		 * Close during the connect 3-way handshake
4716 		 * but here there may or may not be pending data
4717 		 * already on queue. Process almost same as in
4718 		 * the ESTABLISHED state.
4719 		 */
4720 		/* FALLTHRU */
4721 	default:
4722 		if (tcp->tcp_fused)
4723 			tcp_unfuse(tcp);
4724 
4725 		/*
4726 		 * If SO_LINGER has set a zero linger time, abort the
4727 		 * connection with a reset.
4728 		 */
4729 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4730 			msg = "tcp_close, zero lingertime";
4731 			break;
4732 		}
4733 
4734 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4735 		/*
4736 		 * Abort connection if there is unread data queued.
4737 		 */
4738 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4739 			msg = "tcp_close, unread data";
4740 			break;
4741 		}
4742 		/*
4743 		 * tcp_hard_bound is now cleared thus all packets go through
4744 		 * tcp_lookup. This fact is used by tcp_detach below.
4745 		 *
4746 		 * We have done a qwait() above which could have possibly
4747 		 * drained more messages in turn causing transition to a
4748 		 * different state. Check whether we have to do the rest
4749 		 * of the processing or not.
4750 		 */
4751 		if (tcp->tcp_state <= TCPS_LISTEN)
4752 			break;
4753 
4754 		/*
4755 		 * Transmit the FIN before detaching the tcp_t.
4756 		 * After tcp_detach returns this queue/perimeter
4757 		 * no longer owns the tcp_t thus others can modify it.
4758 		 */
4759 		(void) tcp_xmit_end(tcp);
4760 
4761 		/*
4762 		 * If lingering on close then wait until the fin is acked,
4763 		 * the SO_LINGER time passes, or a reset is sent/received.
4764 		 */
4765 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4766 		    !(tcp->tcp_fin_acked) &&
4767 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4768 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4769 				tcp->tcp_client_errno = EWOULDBLOCK;
4770 			} else if (tcp->tcp_client_errno == 0) {
4771 
4772 				ASSERT(tcp->tcp_linger_tid == 0);
4773 
4774 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4775 				    tcp_close_linger_timeout,
4776 				    tcp->tcp_lingertime * hz);
4777 
4778 				/* tcp_close_linger_timeout will finish close */
4779 				if (tcp->tcp_linger_tid == 0)
4780 					tcp->tcp_client_errno = ENOSR;
4781 				else
4782 					return;
4783 			}
4784 
4785 			/*
4786 			 * Check if we need to detach or just close
4787 			 * the instance.
4788 			 */
4789 			if (tcp->tcp_state <= TCPS_LISTEN)
4790 				break;
4791 		}
4792 
4793 		/*
4794 		 * Make sure that no other thread will access the tcp_rq of
4795 		 * this instance (through lookups etc.) as tcp_rq will go
4796 		 * away shortly.
4797 		 */
4798 		tcp_acceptor_hash_remove(tcp);
4799 
4800 		if (tcp->tcp_flow_stopped) {
4801 			tcp->tcp_flow_stopped = B_FALSE;
4802 			tcp_clrqfull(tcp);
4803 		}
4804 
4805 		if (tcp->tcp_timer_tid != 0) {
4806 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4807 			tcp->tcp_timer_tid = 0;
4808 		}
4809 		/*
4810 		 * Need to cancel those timers which will not be used when
4811 		 * TCP is detached.  This has to be done before the tcp_wq
4812 		 * is set to the global queue.
4813 		 */
4814 		tcp_timers_stop(tcp);
4815 
4816 		tcp->tcp_detached = B_TRUE;
4817 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4818 			tcp_time_wait_append(tcp);
4819 			TCP_DBGSTAT(tcp_detach_time_wait);
4820 			ASSERT(connp->conn_ref >= 3);
4821 			goto finish;
4822 		}
4823 
4824 		/*
4825 		 * If delta is zero the timer event wasn't executed and was
4826 		 * successfully canceled. In this case we need to restart it
4827 		 * with the minimal delta possible.
4828 		 */
4829 		if (delta >= 0)
4830 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4831 			    delta ? delta : 1);
4832 
4833 		ASSERT(connp->conn_ref >= 3);
4834 		goto finish;
4835 	}
4836 
4837 	/* Detach did not complete. Still need to remove q from stream. */
4838 	if (msg) {
4839 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4840 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4841 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4842 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4843 		    tcp->tcp_state == TCPS_SYN_RCVD)
4844 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4845 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4846 	}
4847 
4848 	tcp_closei_local(tcp);
4849 	CONN_DEC_REF(connp);
4850 	ASSERT(connp->conn_ref >= 2);
4851 
4852 finish:
4853 	/*
4854 	 * Although packets are always processed on the correct
4855 	 * tcp's perimeter and access is serialized via squeue's,
4856 	 * IP still needs a queue when sending packets in time_wait
4857 	 * state so use WR(tcp_g_q) till ip_output() can be
4858 	 * changed to deal with just connp. For read side, we
4859 	 * could have set tcp_rq to NULL but there are some cases
4860 	 * in tcp_rput_data() from early days of this code which
4861 	 * do a putnext without checking if tcp is closed. Those
4862 	 * need to be identified before both tcp_rq and tcp_wq
4863 	 * can be set to NULL and tcp_q_q can disappear forever.
4864 	 */
4865 	mutex_enter(&tcp->tcp_closelock);
4866 	/*
4867 	 * Don't change the queues in the case of a listener that has
4868 	 * eagers in its q or q0. It could surprise the eagers.
4869 	 * Instead wait for the eagers outside the squeue.
4870 	 */
4871 	if (!tcp->tcp_wait_for_eagers) {
4872 		tcp->tcp_detached = B_TRUE;
4873 		tcp->tcp_rq = tcp_g_q;
4874 		tcp->tcp_wq = WR(tcp_g_q);
4875 	}
4876 	/* Signal tcp_close() to finish closing. */
4877 	tcp->tcp_closed = 1;
4878 	cv_signal(&tcp->tcp_closecv);
4879 	mutex_exit(&tcp->tcp_closelock);
4880 }
4881 
4882 
4883 /*
4884  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4885  * Some stream heads get upset if they see these later on as anything but NULL.
4886  */
4887 static void
4888 tcp_close_mpp(mblk_t **mpp)
4889 {
4890 	mblk_t	*mp;
4891 
4892 	if ((mp = *mpp) != NULL) {
4893 		do {
4894 			mp->b_next = NULL;
4895 			mp->b_prev = NULL;
4896 		} while ((mp = mp->b_cont) != NULL);
4897 
4898 		mp = *mpp;
4899 		*mpp = NULL;
4900 		freemsg(mp);
4901 	}
4902 }
4903 
4904 /* Do detached close. */
4905 static void
4906 tcp_close_detached(tcp_t *tcp)
4907 {
4908 	if (tcp->tcp_fused)
4909 		tcp_unfuse(tcp);
4910 
4911 	/*
4912 	 * Clustering code serializes TCP disconnect callbacks and
4913 	 * cluster tcp list walks by blocking a TCP disconnect callback
4914 	 * if a cluster tcp list walk is in progress. This ensures
4915 	 * accurate accounting of TCPs in the cluster code even though
4916 	 * the TCP list walk itself is not atomic.
4917 	 */
4918 	tcp_closei_local(tcp);
4919 	CONN_DEC_REF(tcp->tcp_connp);
4920 }
4921 
4922 /*
4923  * Stop all TCP timers, and free the timer mblks if requested.
4924  */
4925 static void
4926 tcp_timers_stop(tcp_t *tcp)
4927 {
4928 	if (tcp->tcp_timer_tid != 0) {
4929 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4930 		tcp->tcp_timer_tid = 0;
4931 	}
4932 	if (tcp->tcp_ka_tid != 0) {
4933 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4934 		tcp->tcp_ka_tid = 0;
4935 	}
4936 	if (tcp->tcp_ack_tid != 0) {
4937 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4938 		tcp->tcp_ack_tid = 0;
4939 	}
4940 	if (tcp->tcp_push_tid != 0) {
4941 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4942 		tcp->tcp_push_tid = 0;
4943 	}
4944 }
4945 
4946 /*
4947  * The tcp_t is going away. Remove it from all lists and set it
4948  * to TCPS_CLOSED. The freeing up of memory is deferred until
4949  * tcp_inactive. This is needed since a thread in tcp_rput might have
4950  * done a CONN_INC_REF on this structure before it was removed from the
4951  * hashes.
4952  */
4953 static void
4954 tcp_closei_local(tcp_t *tcp)
4955 {
4956 	ire_t 	*ire;
4957 	conn_t	*connp = tcp->tcp_connp;
4958 
4959 	if (!TCP_IS_SOCKET(tcp))
4960 		tcp_acceptor_hash_remove(tcp);
4961 
4962 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4963 	tcp->tcp_ibsegs = 0;
4964 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4965 	tcp->tcp_obsegs = 0;
4966 	/*
4967 	 * If we are an eager connection hanging off a listener that
4968 	 * hasn't formally accepted the connection yet, get off his
4969 	 * list and blow off any data that we have accumulated.
4970 	 */
4971 	if (tcp->tcp_listener != NULL) {
4972 		tcp_t	*listener = tcp->tcp_listener;
4973 		mutex_enter(&listener->tcp_eager_lock);
4974 		/*
4975 		 * tcp_eager_conn_ind == NULL means that the
4976 		 * conn_ind has already gone to listener. At
4977 		 * this point, eager will be closed but we
4978 		 * leave it in listeners eager list so that
4979 		 * if listener decides to close without doing
4980 		 * accept, we can clean this up. In tcp_wput_accept
4981 		 * we take case of the case of accept on closed
4982 		 * eager.
4983 		 */
4984 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4985 			tcp_eager_unlink(tcp);
4986 			mutex_exit(&listener->tcp_eager_lock);
4987 			/*
4988 			 * We don't want to have any pointers to the
4989 			 * listener queue, after we have released our
4990 			 * reference on the listener
4991 			 */
4992 			tcp->tcp_rq = tcp_g_q;
4993 			tcp->tcp_wq = WR(tcp_g_q);
4994 			CONN_DEC_REF(listener->tcp_connp);
4995 		} else {
4996 			mutex_exit(&listener->tcp_eager_lock);
4997 		}
4998 	}
4999 
5000 	/* Stop all the timers */
5001 	tcp_timers_stop(tcp);
5002 
5003 	if (tcp->tcp_state == TCPS_LISTEN) {
5004 		if (tcp->tcp_ip_addr_cache) {
5005 			kmem_free((void *)tcp->tcp_ip_addr_cache,
5006 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
5007 			tcp->tcp_ip_addr_cache = NULL;
5008 		}
5009 	}
5010 	if (tcp->tcp_flow_stopped)
5011 		tcp_clrqfull(tcp);
5012 
5013 	tcp_bind_hash_remove(tcp);
5014 	/*
5015 	 * If the tcp_time_wait_collector (which runs outside the squeue)
5016 	 * is trying to remove this tcp from the time wait list, we will
5017 	 * block in tcp_time_wait_remove while trying to acquire the
5018 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
5019 	 * requires the ipcl_hash_remove to be ordered after the
5020 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
5021 	 */
5022 	if (tcp->tcp_state == TCPS_TIME_WAIT)
5023 		tcp_time_wait_remove(tcp, NULL);
5024 	CL_INET_DISCONNECT(tcp);
5025 	ipcl_hash_remove(connp);
5026 
5027 	/*
5028 	 * Delete the cached ire in conn_ire_cache and also mark
5029 	 * the conn as CONDEMNED
5030 	 */
5031 	mutex_enter(&connp->conn_lock);
5032 	connp->conn_state_flags |= CONN_CONDEMNED;
5033 	ire = connp->conn_ire_cache;
5034 	connp->conn_ire_cache = NULL;
5035 	mutex_exit(&connp->conn_lock);
5036 	if (ire != NULL)
5037 		IRE_REFRELE_NOTR(ire);
5038 
5039 	/* Need to cleanup any pending ioctls */
5040 	ASSERT(tcp->tcp_time_wait_next == NULL);
5041 	ASSERT(tcp->tcp_time_wait_prev == NULL);
5042 	ASSERT(tcp->tcp_time_wait_expire == 0);
5043 	tcp->tcp_state = TCPS_CLOSED;
5044 }
5045 
5046 /*
5047  * tcp is dying (called from ipcl_conn_destroy and error cases).
5048  * Free the tcp_t in either case.
5049  */
5050 void
5051 tcp_free(tcp_t *tcp)
5052 {
5053 	mblk_t	*mp;
5054 	ip6_pkt_t	*ipp;
5055 
5056 	ASSERT(tcp != NULL);
5057 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
5058 
5059 	tcp->tcp_rq = NULL;
5060 	tcp->tcp_wq = NULL;
5061 
5062 	tcp_close_mpp(&tcp->tcp_xmit_head);
5063 	tcp_close_mpp(&tcp->tcp_reass_head);
5064 	if (tcp->tcp_rcv_list != NULL) {
5065 		/* Free b_next chain */
5066 		tcp_close_mpp(&tcp->tcp_rcv_list);
5067 	}
5068 	if ((mp = tcp->tcp_urp_mp) != NULL) {
5069 		freemsg(mp);
5070 	}
5071 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
5072 		freemsg(mp);
5073 	}
5074 
5075 	if (tcp->tcp_fused_sigurg_mp != NULL) {
5076 		freeb(tcp->tcp_fused_sigurg_mp);
5077 		tcp->tcp_fused_sigurg_mp = NULL;
5078 	}
5079 
5080 	if (tcp->tcp_sack_info != NULL) {
5081 		if (tcp->tcp_notsack_list != NULL) {
5082 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
5083 		}
5084 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
5085 	}
5086 
5087 	if (tcp->tcp_hopopts != NULL) {
5088 		mi_free(tcp->tcp_hopopts);
5089 		tcp->tcp_hopopts = NULL;
5090 		tcp->tcp_hopoptslen = 0;
5091 	}
5092 	ASSERT(tcp->tcp_hopoptslen == 0);
5093 	if (tcp->tcp_dstopts != NULL) {
5094 		mi_free(tcp->tcp_dstopts);
5095 		tcp->tcp_dstopts = NULL;
5096 		tcp->tcp_dstoptslen = 0;
5097 	}
5098 	ASSERT(tcp->tcp_dstoptslen == 0);
5099 	if (tcp->tcp_rtdstopts != NULL) {
5100 		mi_free(tcp->tcp_rtdstopts);
5101 		tcp->tcp_rtdstopts = NULL;
5102 		tcp->tcp_rtdstoptslen = 0;
5103 	}
5104 	ASSERT(tcp->tcp_rtdstoptslen == 0);
5105 	if (tcp->tcp_rthdr != NULL) {
5106 		mi_free(tcp->tcp_rthdr);
5107 		tcp->tcp_rthdr = NULL;
5108 		tcp->tcp_rthdrlen = 0;
5109 	}
5110 	ASSERT(tcp->tcp_rthdrlen == 0);
5111 
5112 	ipp = &tcp->tcp_sticky_ipp;
5113 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
5114 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
5115 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
5116 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
5117 			ipp->ipp_hopopts = NULL;
5118 			ipp->ipp_hopoptslen = 0;
5119 		}
5120 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
5121 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
5122 			ipp->ipp_rtdstopts = NULL;
5123 			ipp->ipp_rtdstoptslen = 0;
5124 		}
5125 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
5126 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
5127 			ipp->ipp_dstopts = NULL;
5128 			ipp->ipp_dstoptslen = 0;
5129 		}
5130 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
5131 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
5132 			ipp->ipp_rthdr = NULL;
5133 			ipp->ipp_rthdrlen = 0;
5134 		}
5135 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
5136 		    IPPF_DSTOPTS | IPPF_RTHDR);
5137 	}
5138 
5139 	/*
5140 	 * Free memory associated with the tcp/ip header template.
5141 	 */
5142 
5143 	if (tcp->tcp_iphc != NULL)
5144 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5145 
5146 	/*
5147 	 * Following is really a blowing away a union.
5148 	 * It happens to have exactly two members of identical size
5149 	 * the following code is enough.
5150 	 */
5151 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
5152 
5153 	if (tcp->tcp_tracebuf != NULL) {
5154 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
5155 		tcp->tcp_tracebuf = NULL;
5156 	}
5157 }
5158 
5159 
5160 /*
5161  * Put a connection confirmation message upstream built from the
5162  * address information within 'iph' and 'tcph'.  Report our success or failure.
5163  */
5164 static boolean_t
5165 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
5166     mblk_t **defermp)
5167 {
5168 	sin_t	sin;
5169 	sin6_t	sin6;
5170 	mblk_t	*mp;
5171 	char	*optp = NULL;
5172 	int	optlen = 0;
5173 	cred_t	*cr;
5174 
5175 	if (defermp != NULL)
5176 		*defermp = NULL;
5177 
5178 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
5179 		/*
5180 		 * Return in T_CONN_CON results of option negotiation through
5181 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
5182 		 * negotiation, then what is received from remote end needs
5183 		 * to be taken into account but there is no such thing (yet?)
5184 		 * in our TCP/IP.
5185 		 * Note: We do not use mi_offset_param() here as
5186 		 * tcp_opts_conn_req contents do not directly come from
5187 		 * an application and are either generated in kernel or
5188 		 * from user input that was already verified.
5189 		 */
5190 		mp = tcp->tcp_conn.tcp_opts_conn_req;
5191 		optp = (char *)(mp->b_rptr +
5192 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
5193 		optlen = (int)
5194 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
5195 	}
5196 
5197 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
5198 		ipha_t *ipha = (ipha_t *)iphdr;
5199 
5200 		/* packet is IPv4 */
5201 		if (tcp->tcp_family == AF_INET) {
5202 			sin = sin_null;
5203 			sin.sin_addr.s_addr = ipha->ipha_src;
5204 			sin.sin_port = *(uint16_t *)tcph->th_lport;
5205 			sin.sin_family = AF_INET;
5206 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
5207 			    (int)sizeof (sin_t), optp, optlen);
5208 		} else {
5209 			sin6 = sin6_null;
5210 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
5211 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5212 			sin6.sin6_family = AF_INET6;
5213 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
5214 			    (int)sizeof (sin6_t), optp, optlen);
5215 
5216 		}
5217 	} else {
5218 		ip6_t	*ip6h = (ip6_t *)iphdr;
5219 
5220 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
5221 		ASSERT(tcp->tcp_family == AF_INET6);
5222 		sin6 = sin6_null;
5223 		sin6.sin6_addr = ip6h->ip6_src;
5224 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5225 		sin6.sin6_family = AF_INET6;
5226 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
5227 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
5228 		    (int)sizeof (sin6_t), optp, optlen);
5229 	}
5230 
5231 	if (!mp)
5232 		return (B_FALSE);
5233 
5234 	if ((cr = DB_CRED(idmp)) != NULL) {
5235 		mblk_setcred(mp, cr);
5236 		DB_CPID(mp) = DB_CPID(idmp);
5237 	}
5238 
5239 	if (defermp == NULL)
5240 		putnext(tcp->tcp_rq, mp);
5241 	else
5242 		*defermp = mp;
5243 
5244 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5245 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5246 	return (B_TRUE);
5247 }
5248 
5249 /*
5250  * Defense for the SYN attack -
5251  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
5252  *    one that doesn't have the dontdrop bit set.
5253  * 2. Don't drop a SYN request before its first timeout. This gives every
5254  *    request at least til the first timeout to complete its 3-way handshake.
5255  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
5256  *    requests currently on the queue that has timed out. This will be used
5257  *    as an indicator of whether an attack is under way, so that appropriate
5258  *    actions can be taken. (It's incremented in tcp_timer() and decremented
5259  *    either when eager goes into ESTABLISHED, or gets freed up.)
5260  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
5261  *    # of timeout drops back to <= q0len/32 => SYN alert off
5262  */
5263 static boolean_t
5264 tcp_drop_q0(tcp_t *tcp)
5265 {
5266 	tcp_t	*eager;
5267 
5268 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
5269 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
5270 	/*
5271 	 * New one is added after next_q0 so prev_q0 points to the oldest
5272 	 * Also do not drop any established connections that are deferred on
5273 	 * q0 due to q being full
5274 	 */
5275 
5276 	eager = tcp->tcp_eager_prev_q0;
5277 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
5278 		eager = eager->tcp_eager_prev_q0;
5279 		if (eager == tcp) {
5280 			eager = tcp->tcp_eager_prev_q0;
5281 			break;
5282 		}
5283 	}
5284 	if (eager->tcp_syn_rcvd_timeout == 0)
5285 		return (B_FALSE);
5286 
5287 	if (tcp->tcp_debug) {
5288 		(void) strlog(TCP_MODULE_ID, 0, 3, SL_TRACE,
5289 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
5290 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
5291 		    tcp->tcp_conn_req_cnt_q0,
5292 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5293 	}
5294 
5295 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
5296 
5297 	/*
5298 	 * need to do refhold here because the selected eager could
5299 	 * be removed by someone else if we release the eager lock.
5300 	 */
5301 	CONN_INC_REF(eager->tcp_connp);
5302 	mutex_exit(&tcp->tcp_eager_lock);
5303 
5304 	/* Mark the IRE created for this SYN request temporary */
5305 	tcp_ip_ire_mark_advice(eager);
5306 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
5307 	CONN_DEC_REF(eager->tcp_connp);
5308 
5309 	mutex_enter(&tcp->tcp_eager_lock);
5310 	return (B_TRUE);
5311 }
5312 
5313 int
5314 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
5315     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
5316 {
5317 	tcp_t 		*ltcp = lconnp->conn_tcp;
5318 	tcp_t		*tcp = connp->conn_tcp;
5319 	mblk_t		*tpi_mp;
5320 	ipha_t		*ipha;
5321 	ip6_t		*ip6h;
5322 	sin6_t 		sin6;
5323 	in6_addr_t 	v6dst;
5324 	int		err;
5325 	int		ifindex = 0;
5326 	cred_t		*cr;
5327 
5328 	if (ipvers == IPV4_VERSION) {
5329 		ipha = (ipha_t *)mp->b_rptr;
5330 
5331 		connp->conn_send = ip_output;
5332 		connp->conn_recv = tcp_input;
5333 
5334 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5335 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5336 
5337 		sin6 = sin6_null;
5338 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
5339 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
5340 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5341 		sin6.sin6_family = AF_INET6;
5342 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
5343 		    lconnp->conn_zoneid);
5344 		if (tcp->tcp_recvdstaddr) {
5345 			sin6_t	sin6d;
5346 
5347 			sin6d = sin6_null;
5348 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
5349 			    &sin6d.sin6_addr);
5350 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
5351 			sin6d.sin6_family = AF_INET;
5352 			tpi_mp = mi_tpi_extconn_ind(NULL,
5353 			    (char *)&sin6d, sizeof (sin6_t),
5354 			    (char *)&tcp,
5355 			    (t_scalar_t)sizeof (intptr_t),
5356 			    (char *)&sin6d, sizeof (sin6_t),
5357 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5358 		} else {
5359 			tpi_mp = mi_tpi_conn_ind(NULL,
5360 			    (char *)&sin6, sizeof (sin6_t),
5361 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5362 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5363 		}
5364 	} else {
5365 		ip6h = (ip6_t *)mp->b_rptr;
5366 
5367 		connp->conn_send = ip_output_v6;
5368 		connp->conn_recv = tcp_input;
5369 
5370 		connp->conn_srcv6 = ip6h->ip6_dst;
5371 		connp->conn_remv6 = ip6h->ip6_src;
5372 
5373 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
5374 		ifindex = (int)mp->b_datap->db_cksumstuff;
5375 		mp->b_datap->db_cksumstuff = 0;
5376 
5377 		sin6 = sin6_null;
5378 		sin6.sin6_addr = ip6h->ip6_src;
5379 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
5380 		sin6.sin6_family = AF_INET6;
5381 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
5382 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
5383 		    lconnp->conn_zoneid);
5384 
5385 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
5386 			/* Pass up the scope_id of remote addr */
5387 			sin6.sin6_scope_id = ifindex;
5388 		} else {
5389 			sin6.sin6_scope_id = 0;
5390 		}
5391 		if (tcp->tcp_recvdstaddr) {
5392 			sin6_t	sin6d;
5393 
5394 			sin6d = sin6_null;
5395 			sin6.sin6_addr = ip6h->ip6_dst;
5396 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
5397 			sin6d.sin6_family = AF_INET;
5398 			tpi_mp = mi_tpi_extconn_ind(NULL,
5399 			    (char *)&sin6d, sizeof (sin6_t),
5400 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5401 			    (char *)&sin6d, sizeof (sin6_t),
5402 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5403 		} else {
5404 			tpi_mp = mi_tpi_conn_ind(NULL,
5405 			    (char *)&sin6, sizeof (sin6_t),
5406 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5407 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5408 		}
5409 	}
5410 
5411 	if (tpi_mp == NULL)
5412 		return (ENOMEM);
5413 
5414 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5415 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5416 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
5417 	connp->conn_fully_bound = B_FALSE;
5418 
5419 	if (tcp_trace)
5420 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5421 
5422 	/* Inherit information from the "parent" */
5423 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5424 	tcp->tcp_family = ltcp->tcp_family;
5425 	tcp->tcp_wq = ltcp->tcp_wq;
5426 	tcp->tcp_rq = ltcp->tcp_rq;
5427 	tcp->tcp_mss = tcp_mss_def_ipv6;
5428 	tcp->tcp_detached = B_TRUE;
5429 	if ((err = tcp_init_values(tcp)) != 0) {
5430 		freemsg(tpi_mp);
5431 		return (err);
5432 	}
5433 
5434 	if (ipvers == IPV4_VERSION) {
5435 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
5436 			freemsg(tpi_mp);
5437 			return (err);
5438 		}
5439 		ASSERT(tcp->tcp_ipha != NULL);
5440 	} else {
5441 		/* ifindex must be already set */
5442 		ASSERT(ifindex != 0);
5443 
5444 		if (ltcp->tcp_bound_if != 0) {
5445 			/*
5446 			 * Set newtcp's bound_if equal to
5447 			 * listener's value. If ifindex is
5448 			 * not the same as ltcp->tcp_bound_if,
5449 			 * it must be a packet for the ipmp group
5450 			 * of interfaces
5451 			 */
5452 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
5453 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
5454 			tcp->tcp_bound_if = ifindex;
5455 		}
5456 
5457 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
5458 		tcp->tcp_recvifindex = 0;
5459 		tcp->tcp_recvhops = 0xffffffffU;
5460 		ASSERT(tcp->tcp_ip6h != NULL);
5461 	}
5462 
5463 	tcp->tcp_lport = ltcp->tcp_lport;
5464 
5465 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
5466 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
5467 			/*
5468 			 * Listener had options of some sort; eager inherits.
5469 			 * Free up the eager template and allocate one
5470 			 * of the right size.
5471 			 */
5472 			if (tcp->tcp_hdr_grown) {
5473 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
5474 			} else {
5475 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5476 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5477 			}
5478 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5479 			    KM_NOSLEEP);
5480 			if (tcp->tcp_iphc == NULL) {
5481 				tcp->tcp_iphc_len = 0;
5482 				freemsg(tpi_mp);
5483 				return (ENOMEM);
5484 			}
5485 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5486 			tcp->tcp_hdr_grown = B_TRUE;
5487 		}
5488 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5489 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5490 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5491 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5492 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5493 
5494 		/*
5495 		 * Copy the IP+TCP header template from listener to eager
5496 		 */
5497 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5498 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5499 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5500 			    IPPROTO_RAW) {
5501 				tcp->tcp_ip6h =
5502 				    (ip6_t *)(tcp->tcp_iphc +
5503 					sizeof (ip6i_t));
5504 			} else {
5505 				tcp->tcp_ip6h =
5506 				    (ip6_t *)(tcp->tcp_iphc);
5507 			}
5508 			tcp->tcp_ipha = NULL;
5509 		} else {
5510 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5511 			tcp->tcp_ip6h = NULL;
5512 		}
5513 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5514 		    tcp->tcp_ip_hdr_len);
5515 	} else {
5516 		/*
5517 		 * only valid case when ipversion of listener and
5518 		 * eager differ is when listener is IPv6 and
5519 		 * eager is IPv4.
5520 		 * Eager header template has been initialized to the
5521 		 * maximum v4 header sizes, which includes space for
5522 		 * TCP and IP options.
5523 		 */
5524 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5525 		    (tcp->tcp_ipversion == IPV4_VERSION));
5526 		ASSERT(tcp->tcp_iphc_len >=
5527 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5528 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5529 		/* copy IP header fields individually */
5530 		tcp->tcp_ipha->ipha_ttl =
5531 		    ltcp->tcp_ip6h->ip6_hops;
5532 		bcopy(ltcp->tcp_tcph->th_lport,
5533 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5534 	}
5535 
5536 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5537 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5538 	    sizeof (in_port_t));
5539 
5540 	if (ltcp->tcp_lport == 0) {
5541 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5542 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5543 		    sizeof (in_port_t));
5544 	}
5545 
5546 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5547 		ASSERT(ipha != NULL);
5548 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5549 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5550 
5551 		/* Source routing option copyover (reverse it) */
5552 		if (tcp_rev_src_routes)
5553 			tcp_opt_reverse(tcp, ipha);
5554 	} else {
5555 		ASSERT(ip6h != NULL);
5556 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5557 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5558 	}
5559 
5560 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5561 	/*
5562 	 * If the SYN contains a credential, it's a loopback packet; attach
5563 	 * the credential to the TPI message.
5564 	 */
5565 	if ((cr = DB_CRED(idmp)) != NULL) {
5566 		mblk_setcred(tpi_mp, cr);
5567 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5568 	}
5569 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5570 
5571 	return (0);
5572 }
5573 
5574 
5575 int
5576 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5577     tcph_t *tcph, mblk_t *idmp)
5578 {
5579 	tcp_t 		*ltcp = lconnp->conn_tcp;
5580 	tcp_t		*tcp = connp->conn_tcp;
5581 	sin_t		sin;
5582 	mblk_t		*tpi_mp = NULL;
5583 	int		err;
5584 	cred_t		*cr;
5585 
5586 	sin = sin_null;
5587 	sin.sin_addr.s_addr = ipha->ipha_src;
5588 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5589 	sin.sin_family = AF_INET;
5590 	if (ltcp->tcp_recvdstaddr) {
5591 		sin_t	sind;
5592 
5593 		sind = sin_null;
5594 		sind.sin_addr.s_addr = ipha->ipha_dst;
5595 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5596 		sind.sin_family = AF_INET;
5597 		tpi_mp = mi_tpi_extconn_ind(NULL,
5598 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5599 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5600 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5601 	} else {
5602 		tpi_mp = mi_tpi_conn_ind(NULL,
5603 		    (char *)&sin, sizeof (sin_t),
5604 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5605 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5606 	}
5607 
5608 	if (tpi_mp == NULL) {
5609 		return (ENOMEM);
5610 	}
5611 
5612 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5613 	connp->conn_send = ip_output;
5614 	connp->conn_recv = tcp_input;
5615 	connp->conn_fully_bound = B_FALSE;
5616 
5617 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5618 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5619 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5620 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5621 
5622 	if (tcp_trace) {
5623 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
5624 	}
5625 
5626 	/* Inherit information from the "parent" */
5627 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5628 	tcp->tcp_family = ltcp->tcp_family;
5629 	tcp->tcp_wq = ltcp->tcp_wq;
5630 	tcp->tcp_rq = ltcp->tcp_rq;
5631 	tcp->tcp_mss = tcp_mss_def_ipv4;
5632 	tcp->tcp_detached = B_TRUE;
5633 	if ((err = tcp_init_values(tcp)) != 0) {
5634 		freemsg(tpi_mp);
5635 		return (err);
5636 	}
5637 
5638 	/*
5639 	 * Let's make sure that eager tcp template has enough space to
5640 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5641 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5642 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5643 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5644 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5645 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5646 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5647 	 */
5648 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5649 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5650 
5651 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5652 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5653 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5654 	tcp->tcp_ttl = ltcp->tcp_ttl;
5655 	tcp->tcp_tos = ltcp->tcp_tos;
5656 
5657 	/* Copy the IP+TCP header template from listener to eager */
5658 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5659 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5660 	tcp->tcp_ip6h = NULL;
5661 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5662 	    tcp->tcp_ip_hdr_len);
5663 
5664 	/* Initialize the IP addresses and Ports */
5665 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5666 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5667 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5668 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5669 
5670 	/* Source routing option copyover (reverse it) */
5671 	if (tcp_rev_src_routes)
5672 		tcp_opt_reverse(tcp, ipha);
5673 
5674 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5675 
5676 	/*
5677 	 * If the SYN contains a credential, it's a loopback packet; attach
5678 	 * the credential to the TPI message.
5679 	 */
5680 	if ((cr = DB_CRED(idmp)) != NULL) {
5681 		mblk_setcred(tpi_mp, cr);
5682 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5683 	}
5684 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5685 
5686 	return (0);
5687 }
5688 
5689 /*
5690  * sets up conn for ipsec.
5691  * if the first mblk is M_CTL it is consumed and mpp is updated.
5692  * in case of error mpp is freed.
5693  */
5694 conn_t *
5695 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5696 {
5697 	conn_t 		*connp = tcp->tcp_connp;
5698 	conn_t 		*econnp;
5699 	squeue_t 	*new_sqp;
5700 	mblk_t 		*first_mp = *mpp;
5701 	mblk_t		*mp = *mpp;
5702 	boolean_t	mctl_present = B_FALSE;
5703 	uint_t		ipvers;
5704 
5705 	econnp = tcp_get_conn(sqp);
5706 	if (econnp == NULL) {
5707 		freemsg(first_mp);
5708 		return (NULL);
5709 	}
5710 	if (DB_TYPE(mp) == M_CTL) {
5711 		if (mp->b_cont == NULL ||
5712 		    mp->b_cont->b_datap->db_type != M_DATA) {
5713 			freemsg(first_mp);
5714 			return (NULL);
5715 		}
5716 		mp = mp->b_cont;
5717 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5718 			freemsg(first_mp);
5719 			return (NULL);
5720 		}
5721 
5722 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5723 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5724 		mctl_present = B_TRUE;
5725 	} else {
5726 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5727 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5728 	}
5729 
5730 	new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
5731 	mp->b_datap->db_cksumstart = 0;
5732 
5733 	ASSERT(OK_32PTR(mp->b_rptr));
5734 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5735 	if (ipvers == IPV4_VERSION) {
5736 		uint16_t  	*up;
5737 		uint32_t	ports;
5738 		ipha_t		*ipha;
5739 
5740 		ipha = (ipha_t *)mp->b_rptr;
5741 		up = (uint16_t *)((uchar_t *)ipha +
5742 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5743 		ports = *(uint32_t *)up;
5744 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5745 		    ipha->ipha_dst, ipha->ipha_src, ports);
5746 	} else {
5747 		uint16_t  	*up;
5748 		uint32_t	ports;
5749 		uint16_t	ip_hdr_len;
5750 		uint8_t		*nexthdrp;
5751 		ip6_t 		*ip6h;
5752 		tcph_t		*tcph;
5753 
5754 		ip6h = (ip6_t *)mp->b_rptr;
5755 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5756 			ip_hdr_len = IPV6_HDR_LEN;
5757 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5758 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5759 			CONN_DEC_REF(econnp);
5760 			freemsg(first_mp);
5761 			return (NULL);
5762 		}
5763 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5764 		up = (uint16_t *)tcph->th_lport;
5765 		ports = *(uint32_t *)up;
5766 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5767 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5768 	}
5769 
5770 	/*
5771 	 * The caller already ensured that there is a sqp present.
5772 	 */
5773 	econnp->conn_sqp = new_sqp;
5774 
5775 	if (connp->conn_policy != NULL) {
5776 		ipsec_in_t *ii;
5777 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5778 		ASSERT(ii->ipsec_in_policy == NULL);
5779 		IPPH_REFHOLD(connp->conn_policy);
5780 		ii->ipsec_in_policy = connp->conn_policy;
5781 
5782 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5783 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5784 			CONN_DEC_REF(econnp);
5785 			freemsg(first_mp);
5786 			return (NULL);
5787 		}
5788 	}
5789 
5790 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5791 		CONN_DEC_REF(econnp);
5792 		freemsg(first_mp);
5793 		return (NULL);
5794 	}
5795 
5796 	/*
5797 	 * If we know we have some policy, pass the "IPSEC"
5798 	 * options size TCP uses this adjust the MSS.
5799 	 */
5800 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5801 	if (mctl_present) {
5802 		freeb(first_mp);
5803 		*mpp = mp;
5804 	}
5805 
5806 	return (econnp);
5807 }
5808 
5809 /*
5810  * tcp_get_conn/tcp_free_conn
5811  *
5812  * tcp_get_conn is used to get a clean tcp connection structure.
5813  * It tries to reuse the connections put on the freelist by the
5814  * time_wait_collector failing which it goes to kmem_cache. This
5815  * way has two benefits compared to just allocating from and
5816  * freeing to kmem_cache.
5817  * 1) The time_wait_collector can free (which includes the cleanup)
5818  * outside the squeue. So when the interrupt comes, we have a clean
5819  * connection sitting in the freelist. Obviously, this buys us
5820  * performance.
5821  *
5822  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5823  * has multiple disadvantages - tying up the squeue during alloc, and the
5824  * fact that IPSec policy initialization has to happen here which
5825  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5826  * But allocating the conn/tcp in IP land is also not the best since
5827  * we can't check the 'q' and 'q0' which are protected by squeue and
5828  * blindly allocate memory which might have to be freed here if we are
5829  * not allowed to accept the connection. By using the freelist and
5830  * putting the conn/tcp back in freelist, we don't pay a penalty for
5831  * allocating memory without checking 'q/q0' and freeing it if we can't
5832  * accept the connection.
5833  *
5834  * Care should be taken to put the conn back in the same squeue's freelist
5835  * from which it was allocated. Best results are obtained if conn is
5836  * allocated from listener's squeue and freed to the same. Time wait
5837  * collector will free up the freelist is the connection ends up sitting
5838  * there for too long.
5839  */
5840 void *
5841 tcp_get_conn(void *arg)
5842 {
5843 	tcp_t			*tcp = NULL;
5844 	conn_t			*connp = NULL;
5845 	squeue_t		*sqp = (squeue_t *)arg;
5846 	tcp_squeue_priv_t 	*tcp_time_wait;
5847 
5848 	tcp_time_wait =
5849 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5850 
5851 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5852 	tcp = tcp_time_wait->tcp_free_list;
5853 	if (tcp != NULL) {
5854 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5855 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5856 		tcp->tcp_time_wait_next = NULL;
5857 		connp = tcp->tcp_connp;
5858 		connp->conn_flags |= IPCL_REUSED;
5859 		return ((void *)connp);
5860 	}
5861 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5862 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5863 		return (NULL);
5864 	return ((void *)connp);
5865 }
5866 
5867 /* BEGIN CSTYLED */
5868 /*
5869  *
5870  * The sockfs ACCEPT path:
5871  * =======================
5872  *
5873  * The eager is now established in its own perimeter as soon as SYN is
5874  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5875  * completes the accept processing on the acceptor STREAM. The sending
5876  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5877  * listener but a TLI/XTI listener completes the accept processing
5878  * on the listener perimeter.
5879  *
5880  * Common control flow for 3 way handshake:
5881  * ----------------------------------------
5882  *
5883  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5884  *					-> tcp_conn_request()
5885  *
5886  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5887  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5888  *
5889  * Sockfs ACCEPT Path:
5890  * -------------------
5891  *
5892  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5893  * as STREAM entry point)
5894  *
5895  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5896  *
5897  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5898  * association (we are not behind eager's squeue but sockfs is protecting us
5899  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5900  * is changed to point at tcp_wput().
5901  *
5902  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5903  * listener (done on listener's perimeter).
5904  *
5905  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5906  * accept.
5907  *
5908  * TLI/XTI client ACCEPT path:
5909  * ---------------------------
5910  *
5911  * soaccept() sends T_CONN_RES on the listener STREAM.
5912  *
5913  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5914  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5915  *
5916  * Locks:
5917  * ======
5918  *
5919  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5920  * and listeners->tcp_eager_next_q.
5921  *
5922  * Referencing:
5923  * ============
5924  *
5925  * 1) We start out in tcp_conn_request by eager placing a ref on
5926  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5927  *
5928  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5929  * doing so we place a ref on the eager. This ref is finally dropped at the
5930  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5931  * reference is dropped by the squeue framework.
5932  *
5933  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5934  *
5935  * The reference must be released by the same entity that added the reference
5936  * In the above scheme, the eager is the entity that adds and releases the
5937  * references. Note that tcp_accept_finish executes in the squeue of the eager
5938  * (albeit after it is attached to the acceptor stream). Though 1. executes
5939  * in the listener's squeue, the eager is nascent at this point and the
5940  * reference can be considered to have been added on behalf of the eager.
5941  *
5942  * Eager getting a Reset or listener closing:
5943  * ==========================================
5944  *
5945  * Once the listener and eager are linked, the listener never does the unlink.
5946  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5947  * a message on all eager perimeter. The eager then does the unlink, clears
5948  * any pointers to the listener's queue and drops the reference to the
5949  * listener. The listener waits in tcp_close outside the squeue until its
5950  * refcount has dropped to 1. This ensures that the listener has waited for
5951  * all eagers to clear their association with the listener.
5952  *
5953  * Similarly, if eager decides to go away, it can unlink itself and close.
5954  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5955  * the reference to eager is still valid because of the extra ref we put
5956  * in tcp_send_conn_ind.
5957  *
5958  * Listener can always locate the eager under the protection
5959  * of the listener->tcp_eager_lock, and then do a refhold
5960  * on the eager during the accept processing.
5961  *
5962  * The acceptor stream accesses the eager in the accept processing
5963  * based on the ref placed on eager before sending T_conn_ind.
5964  * The only entity that can negate this refhold is a listener close
5965  * which is mutually exclusive with an active acceptor stream.
5966  *
5967  * Eager's reference on the listener
5968  * ===================================
5969  *
5970  * If the accept happens (even on a closed eager) the eager drops its
5971  * reference on the listener at the start of tcp_accept_finish. If the
5972  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5973  * the reference is dropped in tcp_closei_local. If the listener closes,
5974  * the reference is dropped in tcp_eager_kill. In all cases the reference
5975  * is dropped while executing in the eager's context (squeue).
5976  */
5977 /* END CSTYLED */
5978 
5979 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5980 
5981 /*
5982  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5983  * tcp_rput_data will not see any SYN packets.
5984  */
5985 /* ARGSUSED */
5986 void
5987 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5988 {
5989 	tcph_t		*tcph;
5990 	uint32_t	seg_seq;
5991 	tcp_t		*eager;
5992 	uint_t		ipvers;
5993 	ipha_t		*ipha;
5994 	ip6_t		*ip6h;
5995 	int		err;
5996 	conn_t		*econnp = NULL;
5997 	squeue_t	*new_sqp;
5998 	mblk_t		*mp1;
5999 	uint_t 		ip_hdr_len;
6000 	conn_t		*connp = (conn_t *)arg;
6001 	tcp_t		*tcp = connp->conn_tcp;
6002 	ire_t		*ire;
6003 
6004 	if (tcp->tcp_state != TCPS_LISTEN)
6005 		goto error2;
6006 
6007 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
6008 
6009 	mutex_enter(&tcp->tcp_eager_lock);
6010 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
6011 		mutex_exit(&tcp->tcp_eager_lock);
6012 		TCP_STAT(tcp_listendrop);
6013 		BUMP_MIB(&tcp_mib, tcpListenDrop);
6014 		if (tcp->tcp_debug) {
6015 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
6016 			    "tcp_conn_request: listen backlog (max=%d) "
6017 			    "overflow (%d pending) on %s",
6018 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
6019 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
6020 		}
6021 		goto error2;
6022 	}
6023 
6024 	if (tcp->tcp_conn_req_cnt_q0 >=
6025 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
6026 		/*
6027 		 * Q0 is full. Drop a pending half-open req from the queue
6028 		 * to make room for the new SYN req. Also mark the time we
6029 		 * drop a SYN.
6030 		 *
6031 		 * A more aggressive defense against SYN attack will
6032 		 * be to set the "tcp_syn_defense" flag now.
6033 		 */
6034 		TCP_STAT(tcp_listendropq0);
6035 		tcp->tcp_last_rcv_lbolt = lbolt64;
6036 		if (!tcp_drop_q0(tcp)) {
6037 			mutex_exit(&tcp->tcp_eager_lock);
6038 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
6039 			if (tcp->tcp_debug) {
6040 				(void) strlog(TCP_MODULE_ID, 0, 3, SL_TRACE,
6041 				    "tcp_conn_request: listen half-open queue "
6042 				    "(max=%d) full (%d pending) on %s",
6043 				    tcp_conn_req_max_q0,
6044 				    tcp->tcp_conn_req_cnt_q0,
6045 				    tcp_display(tcp, NULL,
6046 				    DISP_PORT_ONLY));
6047 			}
6048 			goto error2;
6049 		}
6050 	}
6051 	mutex_exit(&tcp->tcp_eager_lock);
6052 
6053 	/*
6054 	 * IP adds STRUIO_EAGER and ensures that the received packet is
6055 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
6056 	 * link local address.  If IPSec is enabled, db_struioflag has
6057 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
6058 	 * otherwise an error case if neither of them is set.
6059 	 */
6060 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6061 		new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
6062 		mp->b_datap->db_cksumstart = 0;
6063 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
6064 		econnp = (conn_t *)tcp_get_conn(arg2);
6065 		if (econnp == NULL)
6066 			goto error2;
6067 		econnp->conn_sqp = new_sqp;
6068 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
6069 		/*
6070 		 * mp is updated in tcp_get_ipsec_conn().
6071 		 */
6072 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
6073 		if (econnp == NULL) {
6074 			/*
6075 			 * mp freed by tcp_get_ipsec_conn.
6076 			 */
6077 			return;
6078 		}
6079 	} else {
6080 		goto error2;
6081 	}
6082 
6083 	ASSERT(DB_TYPE(mp) == M_DATA);
6084 
6085 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
6086 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
6087 	ASSERT(OK_32PTR(mp->b_rptr));
6088 	if (ipvers == IPV4_VERSION) {
6089 		ipha = (ipha_t *)mp->b_rptr;
6090 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
6091 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6092 	} else {
6093 		ip6h = (ip6_t *)mp->b_rptr;
6094 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
6095 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6096 	}
6097 
6098 	if (tcp->tcp_family == AF_INET) {
6099 		ASSERT(ipvers == IPV4_VERSION);
6100 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
6101 	} else {
6102 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
6103 	}
6104 
6105 	if (err)
6106 		goto error3;
6107 
6108 	eager = econnp->conn_tcp;
6109 
6110 	/* Inherit various TCP parameters from the listener */
6111 	eager->tcp_naglim = tcp->tcp_naglim;
6112 	eager->tcp_first_timer_threshold =
6113 	    tcp->tcp_first_timer_threshold;
6114 	eager->tcp_second_timer_threshold =
6115 	    tcp->tcp_second_timer_threshold;
6116 
6117 	eager->tcp_first_ctimer_threshold =
6118 	    tcp->tcp_first_ctimer_threshold;
6119 	eager->tcp_second_ctimer_threshold =
6120 	    tcp->tcp_second_ctimer_threshold;
6121 
6122 	/*
6123 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
6124 	 * zone id before the accept is completed in tcp_wput_accept().
6125 	 */
6126 	econnp->conn_zoneid = connp->conn_zoneid;
6127 
6128 	eager->tcp_hard_binding = B_TRUE;
6129 
6130 	tcp_bind_hash_insert(&tcp_bind_fanout[
6131 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
6132 
6133 	CL_INET_CONNECT(eager);
6134 
6135 	/*
6136 	 * No need to check for multicast destination since ip will only pass
6137 	 * up multicasts to those that have expressed interest
6138 	 * TODO: what about rejecting broadcasts?
6139 	 * Also check that source is not a multicast or broadcast address.
6140 	 */
6141 	eager->tcp_state = TCPS_SYN_RCVD;
6142 
6143 
6144 	/*
6145 	 * There should be no ire in the mp as we are being called after
6146 	 * receiving the SYN.
6147 	 */
6148 	ASSERT(tcp_ire_mp(mp) == NULL);
6149 
6150 	/*
6151 	 * Adapt our mss, ttl, ... according to information provided in IRE.
6152 	 */
6153 
6154 	if (tcp_adapt_ire(eager, NULL) == 0) {
6155 		/* Undo the bind_hash_insert */
6156 		tcp_bind_hash_remove(eager);
6157 		goto error3;
6158 	}
6159 
6160 	/* Process all TCP options. */
6161 	tcp_process_options(eager, tcph);
6162 
6163 	/* Is the other end ECN capable? */
6164 	if (tcp_ecn_permitted >= 1 &&
6165 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
6166 		eager->tcp_ecn_ok = B_TRUE;
6167 	}
6168 
6169 	/*
6170 	 * listener->tcp_rq->q_hiwat should be the default window size or a
6171 	 * window size changed via SO_RCVBUF option.  First round up the
6172 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
6173 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
6174 	 * setting.
6175 	 *
6176 	 * Note if there is a rpipe metric associated with the remote host,
6177 	 * we should not inherit receive window size from listener.
6178 	 */
6179 	eager->tcp_rwnd = MSS_ROUNDUP(
6180 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
6181 	    eager->tcp_rwnd), eager->tcp_mss);
6182 	if (eager->tcp_snd_ws_ok)
6183 		tcp_set_ws_value(eager);
6184 	/*
6185 	 * Note that this is the only place tcp_rwnd_set() is called for
6186 	 * accepting a connection.  We need to call it here instead of
6187 	 * after the 3-way handshake because we need to tell the other
6188 	 * side our rwnd in the SYN-ACK segment.
6189 	 */
6190 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
6191 
6192 	/*
6193 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
6194 	 * via soaccept()->soinheritoptions() which essentially applies
6195 	 * all the listener options to the new STREAM. The options that we
6196 	 * need to take care of are:
6197 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
6198 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
6199 	 * SO_SNDBUF, SO_RCVBUF.
6200 	 *
6201 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
6202 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
6203 	 *		tcp_maxpsz_set() gets called later from
6204 	 *		tcp_accept_finish(), the option takes effect.
6205 	 *
6206 	 */
6207 	/* Set the TCP options */
6208 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
6209 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
6210 	eager->tcp_oobinline = tcp->tcp_oobinline;
6211 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
6212 	eager->tcp_broadcast = tcp->tcp_broadcast;
6213 	eager->tcp_useloopback = tcp->tcp_useloopback;
6214 	eager->tcp_dontroute = tcp->tcp_dontroute;
6215 	eager->tcp_linger = tcp->tcp_linger;
6216 	eager->tcp_lingertime = tcp->tcp_lingertime;
6217 	if (tcp->tcp_ka_enabled)
6218 		eager->tcp_ka_enabled = 1;
6219 
6220 	/* Set the IP options */
6221 	econnp->conn_broadcast = connp->conn_broadcast;
6222 	econnp->conn_loopback = connp->conn_loopback;
6223 	econnp->conn_dontroute = connp->conn_dontroute;
6224 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
6225 
6226 	/* Put a ref on the listener for the eager. */
6227 	CONN_INC_REF(connp);
6228 	mutex_enter(&tcp->tcp_eager_lock);
6229 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
6230 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
6231 	tcp->tcp_eager_next_q0 = eager;
6232 	eager->tcp_eager_prev_q0 = tcp;
6233 
6234 	/* Set tcp_listener before adding it to tcp_conn_fanout */
6235 	eager->tcp_listener = tcp;
6236 	eager->tcp_saved_listener = tcp;
6237 
6238 	/*
6239 	 * Tag this detached tcp vector for later retrieval
6240 	 * by our listener client in tcp_accept().
6241 	 */
6242 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
6243 	tcp->tcp_conn_req_cnt_q0++;
6244 	if (++tcp->tcp_conn_req_seqnum == -1) {
6245 		/*
6246 		 * -1 is "special" and defined in TPI as something
6247 		 * that should never be used in T_CONN_IND
6248 		 */
6249 		++tcp->tcp_conn_req_seqnum;
6250 	}
6251 	mutex_exit(&tcp->tcp_eager_lock);
6252 
6253 	if (tcp->tcp_syn_defense) {
6254 		/* Don't drop the SYN that comes from a good IP source */
6255 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
6256 		if (addr_cache != NULL && eager->tcp_remote ==
6257 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
6258 			eager->tcp_dontdrop = B_TRUE;
6259 		}
6260 	}
6261 
6262 	/*
6263 	 * We need to insert the eager in its own perimeter but as soon
6264 	 * as we do that, we expose the eager to the classifier and
6265 	 * should not touch any field outside the eager's perimeter.
6266 	 * So do all the work necessary before inserting the eager
6267 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
6268 	 * will succeed but undo everything if it fails.
6269 	 */
6270 	seg_seq = ABE32_TO_U32(tcph->th_seq);
6271 	eager->tcp_irs = seg_seq;
6272 	eager->tcp_rack = seg_seq;
6273 	eager->tcp_rnxt = seg_seq + 1;
6274 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
6275 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
6276 	eager->tcp_state = TCPS_SYN_RCVD;
6277 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
6278 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
6279 	if (mp1 == NULL)
6280 		goto error1;
6281 	mblk_setcred(mp1, tcp->tcp_cred);
6282 	DB_CPID(mp1) = tcp->tcp_cpid;
6283 
6284 	/*
6285 	 * We need to start the rto timer. In normal case, we start
6286 	 * the timer after sending the packet on the wire (or at
6287 	 * least believing that packet was sent by waiting for
6288 	 * CALL_IP_WPUT() to return). Since this is the first packet
6289 	 * being sent on the wire for the eager, our initial tcp_rto
6290 	 * is at least tcp_rexmit_interval_min which is a fairly
6291 	 * large value to allow the algorithm to adjust slowly to large
6292 	 * fluctuations of RTT during first few transmissions.
6293 	 *
6294 	 * Starting the timer first and then sending the packet in this
6295 	 * case shouldn't make much difference since tcp_rexmit_interval_min
6296 	 * is of the order of several 100ms and starting the timer
6297 	 * first and then sending the packet will result in difference
6298 	 * of few micro seconds.
6299 	 *
6300 	 * Without this optimization, we are forced to hold the fanout
6301 	 * lock across the ipcl_bind_insert() and sending the packet
6302 	 * so that we don't race against an incoming packet (maybe RST)
6303 	 * for this eager.
6304 	 */
6305 
6306 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
6307 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6308 
6309 
6310 	/*
6311 	 * Insert the eager in its own perimeter now. We are ready to deal
6312 	 * with any packets on eager.
6313 	 */
6314 	if (eager->tcp_ipversion == IPV4_VERSION) {
6315 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6316 			goto error;
6317 		}
6318 	} else {
6319 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6320 			goto error;
6321 		}
6322 	}
6323 
6324 	/* mark conn as fully-bound */
6325 	econnp->conn_fully_bound = B_TRUE;
6326 
6327 	/* Send the SYN-ACK */
6328 	tcp_send_data(eager, eager->tcp_wq, mp1);
6329 	freemsg(mp);
6330 
6331 	return;
6332 error:
6333 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
6334 	freemsg(mp1);
6335 error1:
6336 	/* Undo what we did above */
6337 	mutex_enter(&tcp->tcp_eager_lock);
6338 	tcp_eager_unlink(eager);
6339 	mutex_exit(&tcp->tcp_eager_lock);
6340 	/* Drop eager's reference on the listener */
6341 	CONN_DEC_REF(connp);
6342 
6343 	/*
6344 	 * Delete the cached ire in conn_ire_cache and also mark
6345 	 * the conn as CONDEMNED
6346 	 */
6347 	mutex_enter(&econnp->conn_lock);
6348 	econnp->conn_state_flags |= CONN_CONDEMNED;
6349 	ire = econnp->conn_ire_cache;
6350 	econnp->conn_ire_cache = NULL;
6351 	mutex_exit(&econnp->conn_lock);
6352 	if (ire != NULL)
6353 		IRE_REFRELE_NOTR(ire);
6354 
6355 	/*
6356 	 * tcp_accept_comm inserts the eager to the bind_hash
6357 	 * we need to remove it from the hash if ipcl_conn_insert
6358 	 * fails.
6359 	 */
6360 	tcp_bind_hash_remove(eager);
6361 	/* Drop the eager ref placed in tcp_open_detached */
6362 	CONN_DEC_REF(econnp);
6363 
6364 	/*
6365 	 * If a connection already exists, send the mp to that connections so
6366 	 * that it can be appropriately dealt with.
6367 	 */
6368 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
6369 		if (!IPCL_IS_CONNECTED(econnp)) {
6370 			/*
6371 			 * Something bad happened. ipcl_conn_insert()
6372 			 * failed because a connection already existed
6373 			 * in connected hash but we can't find it
6374 			 * anymore (someone blew it away). Just
6375 			 * free this message and hopefully remote
6376 			 * will retransmit at which time the SYN can be
6377 			 * treated as a new connection or dealth with
6378 			 * a TH_RST if a connection already exists.
6379 			 */
6380 			freemsg(mp);
6381 		} else {
6382 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6383 			    econnp, SQTAG_TCP_CONN_REQ);
6384 		}
6385 	} else {
6386 		/* Nobody wants this packet */
6387 		freemsg(mp);
6388 	}
6389 	return;
6390 error2:
6391 	freemsg(mp);
6392 	return;
6393 error3:
6394 	CONN_DEC_REF(econnp);
6395 	freemsg(mp);
6396 }
6397 
6398 /*
6399  * In an ideal case of vertical partition in NUMA architecture, its
6400  * beneficial to have the listener and all the incoming connections
6401  * tied to the same squeue. The other constraint is that incoming
6402  * connections should be tied to the squeue attached to interrupted
6403  * CPU for obvious locality reason so this leaves the listener to
6404  * be tied to the same squeue. Our only problem is that when listener
6405  * is binding, the CPU that will get interrupted by the NIC whose
6406  * IP address the listener is binding to is not even known. So
6407  * the code below allows us to change that binding at the time the
6408  * CPU is interrupted by virtue of incoming connection's squeue.
6409  *
6410  * This is usefull only in case of a listener bound to a specific IP
6411  * address. For other kind of listeners, they get bound the
6412  * very first time and there is no attempt to rebind them.
6413  */
6414 void
6415 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6416 {
6417 	conn_t		*connp = (conn_t *)arg;
6418 	squeue_t	*sqp = (squeue_t *)arg2;
6419 	squeue_t	*new_sqp;
6420 	uint32_t	conn_flags;
6421 
6422 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6423 		new_sqp = (squeue_t *)mp->b_datap->db_cksumstart;
6424 	} else {
6425 		goto done;
6426 	}
6427 
6428 	if (connp->conn_fanout == NULL)
6429 		goto done;
6430 
6431 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6432 		mutex_enter(&connp->conn_fanout->connf_lock);
6433 		mutex_enter(&connp->conn_lock);
6434 		/*
6435 		 * No one from read or write side can access us now
6436 		 * except for already queued packets on this squeue.
6437 		 * But since we haven't changed the squeue yet, they
6438 		 * can't execute. If they are processed after we have
6439 		 * changed the squeue, they are sent back to the
6440 		 * correct squeue down below.
6441 		 */
6442 		if (connp->conn_sqp != new_sqp) {
6443 			while (connp->conn_sqp != new_sqp)
6444 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6445 		}
6446 
6447 		do {
6448 			conn_flags = connp->conn_flags;
6449 			conn_flags |= IPCL_FULLY_BOUND;
6450 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6451 			    conn_flags);
6452 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6453 
6454 		mutex_exit(&connp->conn_fanout->connf_lock);
6455 		mutex_exit(&connp->conn_lock);
6456 	}
6457 
6458 done:
6459 	if (connp->conn_sqp != sqp) {
6460 		CONN_INC_REF(connp);
6461 		squeue_fill(connp->conn_sqp, mp,
6462 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6463 	} else {
6464 		tcp_conn_request(connp, mp, sqp);
6465 	}
6466 }
6467 
6468 /*
6469  * Successful connect request processing begins when our client passes
6470  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6471  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6472  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6473  *   upstream <- tcp_rput()                <- IP
6474  * After various error checks are completed, tcp_connect() lays
6475  * the target address and port into the composite header template,
6476  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6477  * request followed by an IRE request, and passes the three mblk message
6478  * down to IP looking like this:
6479  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6480  * Processing continues in tcp_rput() when we receive the following message:
6481  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6482  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6483  * to fire off the connection request, and then passes the T_OK_ACK mblk
6484  * upstream that we filled in below.  There are, of course, numerous
6485  * error conditions along the way which truncate the processing described
6486  * above.
6487  */
6488 static void
6489 tcp_connect(tcp_t *tcp, mblk_t *mp)
6490 {
6491 	sin_t		*sin;
6492 	sin6_t		*sin6;
6493 	queue_t		*q = tcp->tcp_wq;
6494 	struct T_conn_req	*tcr;
6495 	ipaddr_t	*dstaddrp;
6496 	in_port_t	dstport;
6497 	uint_t		srcid;
6498 
6499 	tcr = (struct T_conn_req *)mp->b_rptr;
6500 
6501 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6502 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6503 		tcp_err_ack(tcp, mp, TPROTO, 0);
6504 		return;
6505 	}
6506 
6507 	/*
6508 	 * Determine packet type based on type of address passed in
6509 	 * the request should contain an IPv4 or IPv6 address.
6510 	 * Make sure that address family matches the type of
6511 	 * family of the the address passed down
6512 	 */
6513 	switch (tcr->DEST_length) {
6514 	default:
6515 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6516 		return;
6517 
6518 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6519 		/*
6520 		 * XXX: The check for valid DEST_length was not there
6521 		 * in earlier releases and some buggy
6522 		 * TLI apps (e.g Sybase) got away with not feeding
6523 		 * in sin_zero part of address.
6524 		 * We allow that bug to keep those buggy apps humming.
6525 		 * Test suites require the check on DEST_length.
6526 		 * We construct a new mblk with valid DEST_length
6527 		 * free the original so the rest of the code does
6528 		 * not have to keep track of this special shorter
6529 		 * length address case.
6530 		 */
6531 		mblk_t *nmp;
6532 		struct T_conn_req *ntcr;
6533 		sin_t *nsin;
6534 
6535 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6536 		    tcr->OPT_length, BPRI_HI);
6537 		if (nmp == NULL) {
6538 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6539 			return;
6540 		}
6541 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6542 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6543 		ntcr->PRIM_type = T_CONN_REQ;
6544 		ntcr->DEST_length = sizeof (sin_t);
6545 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6546 
6547 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6548 		*nsin = sin_null;
6549 		/* Get pointer to shorter address to copy from original mp */
6550 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6551 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6552 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6553 			freemsg(nmp);
6554 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6555 			return;
6556 		}
6557 		nsin->sin_family = sin->sin_family;
6558 		nsin->sin_port = sin->sin_port;
6559 		nsin->sin_addr = sin->sin_addr;
6560 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6561 		nmp->b_wptr = (uchar_t *)&nsin[1];
6562 		if (tcr->OPT_length != 0) {
6563 			ntcr->OPT_length = tcr->OPT_length;
6564 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6565 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6566 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6567 			    tcr->OPT_length);
6568 			nmp->b_wptr += tcr->OPT_length;
6569 		}
6570 		freemsg(mp);	/* original mp freed */
6571 		mp = nmp;	/* re-initialize original variables */
6572 		tcr = ntcr;
6573 	}
6574 	/* FALLTHRU */
6575 
6576 	case sizeof (sin_t):
6577 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6578 		    sizeof (sin_t));
6579 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6580 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6581 			return;
6582 		}
6583 		if (tcp->tcp_family != AF_INET ||
6584 		    sin->sin_family != AF_INET) {
6585 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6586 			return;
6587 		}
6588 		if (sin->sin_port == 0) {
6589 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6590 			return;
6591 		}
6592 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6593 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6594 			return;
6595 		}
6596 
6597 		break;
6598 
6599 	case sizeof (sin6_t):
6600 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6601 		    sizeof (sin6_t));
6602 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6603 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6604 			return;
6605 		}
6606 		if (tcp->tcp_family != AF_INET6 ||
6607 		    sin6->sin6_family != AF_INET6) {
6608 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6609 			return;
6610 		}
6611 		if (sin6->sin6_port == 0) {
6612 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6613 			return;
6614 		}
6615 		break;
6616 	}
6617 	/*
6618 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6619 	 * should key on their sequence number and cut them loose.
6620 	 */
6621 
6622 	/*
6623 	 * If options passed in, feed it for verification and handling
6624 	 */
6625 	if (tcr->OPT_length != 0) {
6626 		mblk_t	*ok_mp;
6627 		mblk_t	*discon_mp;
6628 		mblk_t  *conn_opts_mp;
6629 		int t_error, sys_error, do_disconnect;
6630 
6631 		conn_opts_mp = NULL;
6632 
6633 		if (tcp_conprim_opt_process(tcp, mp,
6634 			&do_disconnect, &t_error, &sys_error) < 0) {
6635 			if (do_disconnect) {
6636 				ASSERT(t_error == 0 && sys_error == 0);
6637 				discon_mp = mi_tpi_discon_ind(NULL,
6638 				    ECONNREFUSED, 0);
6639 				if (!discon_mp) {
6640 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6641 					    TSYSERR, ENOMEM);
6642 					return;
6643 				}
6644 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6645 				if (!ok_mp) {
6646 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6647 					    TSYSERR, ENOMEM);
6648 					return;
6649 				}
6650 				qreply(q, ok_mp);
6651 				qreply(q, discon_mp); /* no flush! */
6652 			} else {
6653 				ASSERT(t_error != 0);
6654 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6655 				    sys_error);
6656 			}
6657 			return;
6658 		}
6659 		/*
6660 		 * Success in setting options, the mp option buffer represented
6661 		 * by OPT_length/offset has been potentially modified and
6662 		 * contains results of option processing. We copy it in
6663 		 * another mp to save it for potentially influencing returning
6664 		 * it in T_CONN_CONN.
6665 		 */
6666 		if (tcr->OPT_length != 0) { /* there are resulting options */
6667 			conn_opts_mp = copyb(mp);
6668 			if (!conn_opts_mp) {
6669 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6670 				    TSYSERR, ENOMEM);
6671 				return;
6672 			}
6673 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6674 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6675 			/*
6676 			 * Note:
6677 			 * These resulting option negotiation can include any
6678 			 * end-to-end negotiation options but there no such
6679 			 * thing (yet?) in our TCP/IP.
6680 			 */
6681 		}
6682 	}
6683 
6684 	/*
6685 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6686 	 * make sure that the template IP header in the tcp structure is an
6687 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6688 	 * need to this before we call tcp_bindi() so that the port lookup
6689 	 * code will look for ports in the correct port space (IPv4 and
6690 	 * IPv6 have separate port spaces).
6691 	 */
6692 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6693 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6694 		int err = 0;
6695 
6696 		err = tcp_header_init_ipv4(tcp);
6697 		if (err != 0) {
6698 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6699 			goto connect_failed;
6700 		}
6701 		if (tcp->tcp_lport != 0)
6702 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6703 	}
6704 
6705 	switch (tcp->tcp_state) {
6706 	case TCPS_IDLE:
6707 		/*
6708 		 * We support quick connect, refer to comments in
6709 		 * tcp_connect_*()
6710 		 */
6711 		/* FALLTHRU */
6712 	case TCPS_BOUND:
6713 	case TCPS_LISTEN:
6714 		if (tcp->tcp_family == AF_INET6) {
6715 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6716 				tcp_connect_ipv6(tcp, mp,
6717 				    &sin6->sin6_addr,
6718 				    sin6->sin6_port, sin6->sin6_flowinfo,
6719 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6720 				return;
6721 			}
6722 			/*
6723 			 * Destination adress is mapped IPv6 address.
6724 			 * Source bound address should be unspecified or
6725 			 * IPv6 mapped address as well.
6726 			 */
6727 			if (!IN6_IS_ADDR_UNSPECIFIED(
6728 			    &tcp->tcp_bound_source_v6) &&
6729 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6730 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6731 				    EADDRNOTAVAIL);
6732 				break;
6733 			}
6734 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6735 			dstport = sin6->sin6_port;
6736 			srcid = sin6->__sin6_src_id;
6737 		} else {
6738 			dstaddrp = &sin->sin_addr.s_addr;
6739 			dstport = sin->sin_port;
6740 			srcid = 0;
6741 		}
6742 
6743 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6744 		return;
6745 	default:
6746 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6747 		break;
6748 	}
6749 	/*
6750 	 * Note: Code below is the "failure" case
6751 	 */
6752 	/* return error ack and blow away saved option results if any */
6753 connect_failed:
6754 	if (mp != NULL)
6755 		putnext(tcp->tcp_rq, mp);
6756 	else {
6757 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6758 		    TSYSERR, ENOMEM);
6759 	}
6760 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6761 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6762 }
6763 
6764 /*
6765  * Handle connect to IPv4 destinations, including connections for AF_INET6
6766  * sockets connecting to IPv4 mapped IPv6 destinations.
6767  */
6768 static void
6769 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6770     uint_t srcid)
6771 {
6772 	tcph_t	*tcph;
6773 	mblk_t	*mp1;
6774 	ipaddr_t dstaddr = *dstaddrp;
6775 	int32_t	oldstate;
6776 	uint16_t lport;
6777 
6778 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6779 
6780 	/* Check for attempt to connect to INADDR_ANY */
6781 	if (dstaddr == INADDR_ANY)  {
6782 		/*
6783 		 * SunOS 4.x and 4.3 BSD allow an application
6784 		 * to connect a TCP socket to INADDR_ANY.
6785 		 * When they do this, the kernel picks the
6786 		 * address of one interface and uses it
6787 		 * instead.  The kernel usually ends up
6788 		 * picking the address of the loopback
6789 		 * interface.  This is an undocumented feature.
6790 		 * However, we provide the same thing here
6791 		 * in order to have source and binary
6792 		 * compatibility with SunOS 4.x.
6793 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6794 		 * generate the T_CONN_CON.
6795 		 */
6796 		dstaddr = htonl(INADDR_LOOPBACK);
6797 		*dstaddrp = dstaddr;
6798 	}
6799 
6800 	/* Handle __sin6_src_id if socket not bound to an IP address */
6801 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6802 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6803 		    tcp->tcp_connp->conn_zoneid);
6804 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6805 		    tcp->tcp_ipha->ipha_src);
6806 	}
6807 
6808 	/*
6809 	 * Don't let an endpoint connect to itself.  Note that
6810 	 * the test here does not catch the case where the
6811 	 * source IP addr was left unspecified by the user. In
6812 	 * this case, the source addr is set in tcp_adapt_ire()
6813 	 * using the reply to the T_BIND message that we send
6814 	 * down to IP here and the check is repeated in tcp_rput_other.
6815 	 */
6816 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6817 	    dstport == tcp->tcp_lport) {
6818 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6819 		goto failed;
6820 	}
6821 
6822 	tcp->tcp_ipha->ipha_dst = dstaddr;
6823 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6824 
6825 	/*
6826 	 * Massage a source route if any putting the first hop
6827 	 * in iph_dst. Compute a starting value for the checksum which
6828 	 * takes into account that the original iph_dst should be
6829 	 * included in the checksum but that ip will include the
6830 	 * first hop in the source route in the tcp checksum.
6831 	 */
6832 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6833 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6834 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6835 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6836 	if ((int)tcp->tcp_sum < 0)
6837 		tcp->tcp_sum--;
6838 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6839 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6840 	    (tcp->tcp_sum >> 16));
6841 	tcph = tcp->tcp_tcph;
6842 	*(uint16_t *)tcph->th_fport = dstport;
6843 	tcp->tcp_fport = dstport;
6844 
6845 	oldstate = tcp->tcp_state;
6846 	/*
6847 	 * At this point the remote destination address and remote port fields
6848 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6849 	 * have to see which state tcp was in so we can take apropriate action.
6850 	 */
6851 	if (oldstate == TCPS_IDLE) {
6852 		/*
6853 		 * We support a quick connect capability here, allowing
6854 		 * clients to transition directly from IDLE to SYN_SENT
6855 		 * tcp_bindi will pick an unused port, insert the connection
6856 		 * in the bind hash and transition to BOUND state.
6857 		 */
6858 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6859 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6860 		    B_FALSE, B_FALSE);
6861 		if (lport == 0) {
6862 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6863 			goto failed;
6864 		}
6865 	}
6866 	tcp->tcp_state = TCPS_SYN_SENT;
6867 
6868 	/*
6869 	 * TODO: allow data with connect requests
6870 	 * by unlinking M_DATA trailers here and
6871 	 * linking them in behind the T_OK_ACK mblk.
6872 	 * The tcp_rput() bind ack handler would then
6873 	 * feed them to tcp_wput_data() rather than call
6874 	 * tcp_timer().
6875 	 */
6876 	mp = mi_tpi_ok_ack_alloc(mp);
6877 	if (!mp) {
6878 		tcp->tcp_state = oldstate;
6879 		goto failed;
6880 	}
6881 	if (tcp->tcp_family == AF_INET) {
6882 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6883 		    sizeof (ipa_conn_t));
6884 	} else {
6885 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6886 		    sizeof (ipa6_conn_t));
6887 	}
6888 	if (mp1) {
6889 		/* Hang onto the T_OK_ACK for later. */
6890 		linkb(mp1, mp);
6891 		if (tcp->tcp_family == AF_INET)
6892 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6893 		else {
6894 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6895 			    &tcp->tcp_sticky_ipp);
6896 		}
6897 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6898 		tcp->tcp_active_open = 1;
6899 		/*
6900 		 * If the bind cannot complete immediately
6901 		 * IP will arrange to call tcp_rput_other
6902 		 * when the bind completes.
6903 		 */
6904 		if (mp1 != NULL)
6905 			tcp_rput_other(tcp, mp1);
6906 		return;
6907 	}
6908 	/* Error case */
6909 	tcp->tcp_state = oldstate;
6910 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6911 
6912 failed:
6913 	/* return error ack and blow away saved option results if any */
6914 	if (mp != NULL)
6915 		putnext(tcp->tcp_rq, mp);
6916 	else {
6917 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6918 		    TSYSERR, ENOMEM);
6919 	}
6920 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6921 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6922 
6923 }
6924 
6925 /*
6926  * Handle connect to IPv6 destinations.
6927  */
6928 static void
6929 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6930     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6931 {
6932 	tcph_t	*tcph;
6933 	mblk_t	*mp1;
6934 	ip6_rthdr_t *rth;
6935 	int32_t  oldstate;
6936 	uint16_t lport;
6937 
6938 	ASSERT(tcp->tcp_family == AF_INET6);
6939 
6940 	/*
6941 	 * If we're here, it means that the destination address is a native
6942 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6943 	 * reason why it might not be IPv6 is if the socket was bound to an
6944 	 * IPv4-mapped IPv6 address.
6945 	 */
6946 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6947 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6948 		goto failed;
6949 	}
6950 
6951 	/*
6952 	 * Interpret a zero destination to mean loopback.
6953 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6954 	 * generate the T_CONN_CON.
6955 	 */
6956 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6957 		*dstaddrp = ipv6_loopback;
6958 	}
6959 
6960 	/* Handle __sin6_src_id if socket not bound to an IP address */
6961 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6962 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6963 		    tcp->tcp_connp->conn_zoneid);
6964 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6965 	}
6966 
6967 	/*
6968 	 * Take care of the scope_id now and add ip6i_t
6969 	 * if ip6i_t is not already allocated through TCP
6970 	 * sticky options. At this point tcp_ip6h does not
6971 	 * have dst info, thus use dstaddrp.
6972 	 */
6973 	if (scope_id != 0 &&
6974 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6975 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6976 		ip6i_t  *ip6i;
6977 
6978 		ipp->ipp_ifindex = scope_id;
6979 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6980 
6981 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6982 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6983 			/* Already allocated */
6984 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6985 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6986 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6987 		} else {
6988 			int reterr;
6989 
6990 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6991 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6992 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6993 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6994 			if (reterr != 0)
6995 				goto failed;
6996 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6997 		}
6998 	}
6999 
7000 	/*
7001 	 * Don't let an endpoint connect to itself.  Note that
7002 	 * the test here does not catch the case where the
7003 	 * source IP addr was left unspecified by the user. In
7004 	 * this case, the source addr is set in tcp_adapt_ire()
7005 	 * using the reply to the T_BIND message that we send
7006 	 * down to IP here and the check is repeated in tcp_rput_other.
7007 	 */
7008 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
7009 	    (dstport == tcp->tcp_lport)) {
7010 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
7011 		goto failed;
7012 	}
7013 
7014 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
7015 	tcp->tcp_remote_v6 = *dstaddrp;
7016 	tcp->tcp_ip6h->ip6_vcf =
7017 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
7018 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
7019 
7020 
7021 	/*
7022 	 * Massage a routing header (if present) putting the first hop
7023 	 * in ip6_dst. Compute a starting value for the checksum which
7024 	 * takes into account that the original ip6_dst should be
7025 	 * included in the checksum but that ip will include the
7026 	 * first hop in the source route in the tcp checksum.
7027 	 */
7028 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
7029 	if (rth != NULL) {
7030 
7031 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
7032 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
7033 		    (tcp->tcp_sum >> 16));
7034 	} else {
7035 		tcp->tcp_sum = 0;
7036 	}
7037 
7038 	tcph = tcp->tcp_tcph;
7039 	*(uint16_t *)tcph->th_fport = dstport;
7040 	tcp->tcp_fport = dstport;
7041 
7042 	oldstate = tcp->tcp_state;
7043 	/*
7044 	 * At this point the remote destination address and remote port fields
7045 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
7046 	 * have to see which state tcp was in so we can take apropriate action.
7047 	 */
7048 	if (oldstate == TCPS_IDLE) {
7049 		/*
7050 		 * We support a quick connect capability here, allowing
7051 		 * clients to transition directly from IDLE to SYN_SENT
7052 		 * tcp_bindi will pick an unused port, insert the connection
7053 		 * in the bind hash and transition to BOUND state.
7054 		 */
7055 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
7056 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
7057 		    B_FALSE, B_FALSE);
7058 		if (lport == 0) {
7059 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
7060 			goto failed;
7061 		}
7062 	}
7063 	tcp->tcp_state = TCPS_SYN_SENT;
7064 	/*
7065 	 * TODO: allow data with connect requests
7066 	 * by unlinking M_DATA trailers here and
7067 	 * linking them in behind the T_OK_ACK mblk.
7068 	 * The tcp_rput() bind ack handler would then
7069 	 * feed them to tcp_wput_data() rather than call
7070 	 * tcp_timer().
7071 	 */
7072 	mp = mi_tpi_ok_ack_alloc(mp);
7073 	if (!mp) {
7074 		tcp->tcp_state = oldstate;
7075 		goto failed;
7076 	}
7077 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
7078 	if (mp1) {
7079 		/* Hang onto the T_OK_ACK for later. */
7080 		linkb(mp1, mp);
7081 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
7082 		    &tcp->tcp_sticky_ipp);
7083 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
7084 		tcp->tcp_active_open = 1;
7085 		/* ip_bind_v6() may return ACK or ERROR */
7086 		if (mp1 != NULL)
7087 			tcp_rput_other(tcp, mp1);
7088 		return;
7089 	}
7090 	/* Error case */
7091 	tcp->tcp_state = oldstate;
7092 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
7093 
7094 failed:
7095 	/* return error ack and blow away saved option results if any */
7096 	if (mp != NULL)
7097 		putnext(tcp->tcp_rq, mp);
7098 	else {
7099 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
7100 		    TSYSERR, ENOMEM);
7101 	}
7102 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
7103 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
7104 }
7105 
7106 /*
7107  * We need a stream q for detached closing tcp connections
7108  * to use.  Our client hereby indicates that this q is the
7109  * one to use.
7110  */
7111 static void
7112 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
7113 {
7114 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
7115 	queue_t	*q = tcp->tcp_wq;
7116 
7117 	mp->b_datap->db_type = M_IOCACK;
7118 	iocp->ioc_count = 0;
7119 	mutex_enter(&tcp_g_q_lock);
7120 	if (tcp_g_q != NULL) {
7121 		mutex_exit(&tcp_g_q_lock);
7122 		iocp->ioc_error = EALREADY;
7123 	} else {
7124 		mblk_t *mp1;
7125 
7126 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
7127 		if (mp1 == NULL) {
7128 			mutex_exit(&tcp_g_q_lock);
7129 			iocp->ioc_error = ENOMEM;
7130 		} else {
7131 			tcp_g_q = tcp->tcp_rq;
7132 			mutex_exit(&tcp_g_q_lock);
7133 			iocp->ioc_error = 0;
7134 			iocp->ioc_rval = 0;
7135 			/*
7136 			 * We are passing tcp_sticky_ipp as NULL
7137 			 * as it is not useful for tcp_default queue
7138 			 */
7139 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
7140 			if (mp1 != NULL)
7141 				tcp_rput_other(tcp, mp1);
7142 		}
7143 	}
7144 	qreply(q, mp);
7145 }
7146 
7147 /*
7148  * Our client hereby directs us to reject the connection request
7149  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
7150  * of sending the appropriate RST, not an ICMP error.
7151  */
7152 static void
7153 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
7154 {
7155 	tcp_t	*ltcp = NULL;
7156 	t_scalar_t seqnum;
7157 	conn_t	*connp;
7158 
7159 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
7160 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
7161 		tcp_err_ack(tcp, mp, TPROTO, 0);
7162 		return;
7163 	}
7164 
7165 	/*
7166 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
7167 	 * when the stream is in BOUND state. Do not send a reset,
7168 	 * since the destination IP address is not valid, and it can
7169 	 * be the initialized value of all zeros (broadcast address).
7170 	 *
7171 	 * If TCP has sent down a bind request to IP and has not
7172 	 * received the reply, reject the request.  Otherwise, TCP
7173 	 * will be confused.
7174 	 */
7175 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
7176 		if (tcp->tcp_debug) {
7177 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
7178 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
7179 		}
7180 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
7181 		return;
7182 	}
7183 
7184 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
7185 
7186 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
7187 
7188 		/*
7189 		 * According to TPI, for non-listeners, ignore seqnum
7190 		 * and disconnect.
7191 		 * Following interpretation of -1 seqnum is historical
7192 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
7193 		 * a valid seqnum should not be -1).
7194 		 *
7195 		 *	-1 means disconnect everything
7196 		 *	regardless even on a listener.
7197 		 */
7198 
7199 		int old_state = tcp->tcp_state;
7200 
7201 		/*
7202 		 * The connection can't be on the tcp_time_wait_head list
7203 		 * since it is not detached.
7204 		 */
7205 		ASSERT(tcp->tcp_time_wait_next == NULL);
7206 		ASSERT(tcp->tcp_time_wait_prev == NULL);
7207 		ASSERT(tcp->tcp_time_wait_expire == 0);
7208 		ltcp = NULL;
7209 		/*
7210 		 * If it used to be a listener, check to make sure no one else
7211 		 * has taken the port before switching back to LISTEN state.
7212 		 */
7213 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7214 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
7215 			    tcp->tcp_ipha->ipha_src,
7216 			    tcp->tcp_connp->conn_zoneid);
7217 			if (connp != NULL)
7218 				ltcp = connp->conn_tcp;
7219 		} else {
7220 			/* Allow tcp_bound_if listeners? */
7221 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
7222 			    &tcp->tcp_ip6h->ip6_src, 0,
7223 			    tcp->tcp_connp->conn_zoneid);
7224 			if (connp != NULL)
7225 				ltcp = connp->conn_tcp;
7226 		}
7227 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
7228 			tcp->tcp_state = TCPS_LISTEN;
7229 		} else if (old_state > TCPS_BOUND) {
7230 			tcp->tcp_conn_req_max = 0;
7231 			tcp->tcp_state = TCPS_BOUND;
7232 		}
7233 		if (ltcp != NULL)
7234 			CONN_DEC_REF(ltcp->tcp_connp);
7235 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
7236 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
7237 		} else if (old_state == TCPS_ESTABLISHED ||
7238 		    old_state == TCPS_CLOSE_WAIT) {
7239 			BUMP_MIB(&tcp_mib, tcpEstabResets);
7240 		}
7241 
7242 		if (tcp->tcp_fused)
7243 			tcp_unfuse(tcp);
7244 
7245 		mutex_enter(&tcp->tcp_eager_lock);
7246 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
7247 		    (tcp->tcp_conn_req_cnt_q != 0)) {
7248 			tcp_eager_cleanup(tcp, 0);
7249 		}
7250 		mutex_exit(&tcp->tcp_eager_lock);
7251 
7252 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
7253 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
7254 
7255 		tcp_reinit(tcp);
7256 
7257 		if (old_state >= TCPS_ESTABLISHED) {
7258 			/* Send M_FLUSH according to TPI */
7259 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7260 		}
7261 		mp = mi_tpi_ok_ack_alloc(mp);
7262 		if (mp)
7263 			putnext(tcp->tcp_rq, mp);
7264 		return;
7265 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7266 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7267 		return;
7268 	}
7269 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7270 		/* Send M_FLUSH according to TPI */
7271 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7272 	}
7273 	mp = mi_tpi_ok_ack_alloc(mp);
7274 	if (mp)
7275 		putnext(tcp->tcp_rq, mp);
7276 }
7277 
7278 /*
7279  * Diagnostic routine used to return a string associated with the tcp state.
7280  * Note that if the caller does not supply a buffer, it will use an internal
7281  * static string.  This means that if multiple threads call this function at
7282  * the same time, output can be corrupted...  Note also that this function
7283  * does not check the size of the supplied buffer.  The caller has to make
7284  * sure that it is big enough.
7285  */
7286 static char *
7287 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7288 {
7289 	char		buf1[30];
7290 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7291 	char		*buf;
7292 	char		*cp;
7293 	in6_addr_t	local, remote;
7294 	char		local_addrbuf[INET6_ADDRSTRLEN];
7295 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7296 
7297 	if (sup_buf != NULL)
7298 		buf = sup_buf;
7299 	else
7300 		buf = priv_buf;
7301 
7302 	if (tcp == NULL)
7303 		return ("NULL_TCP");
7304 	switch (tcp->tcp_state) {
7305 	case TCPS_CLOSED:
7306 		cp = "TCP_CLOSED";
7307 		break;
7308 	case TCPS_IDLE:
7309 		cp = "TCP_IDLE";
7310 		break;
7311 	case TCPS_BOUND:
7312 		cp = "TCP_BOUND";
7313 		break;
7314 	case TCPS_LISTEN:
7315 		cp = "TCP_LISTEN";
7316 		break;
7317 	case TCPS_SYN_SENT:
7318 		cp = "TCP_SYN_SENT";
7319 		break;
7320 	case TCPS_SYN_RCVD:
7321 		cp = "TCP_SYN_RCVD";
7322 		break;
7323 	case TCPS_ESTABLISHED:
7324 		cp = "TCP_ESTABLISHED";
7325 		break;
7326 	case TCPS_CLOSE_WAIT:
7327 		cp = "TCP_CLOSE_WAIT";
7328 		break;
7329 	case TCPS_FIN_WAIT_1:
7330 		cp = "TCP_FIN_WAIT_1";
7331 		break;
7332 	case TCPS_CLOSING:
7333 		cp = "TCP_CLOSING";
7334 		break;
7335 	case TCPS_LAST_ACK:
7336 		cp = "TCP_LAST_ACK";
7337 		break;
7338 	case TCPS_FIN_WAIT_2:
7339 		cp = "TCP_FIN_WAIT_2";
7340 		break;
7341 	case TCPS_TIME_WAIT:
7342 		cp = "TCP_TIME_WAIT";
7343 		break;
7344 	default:
7345 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7346 		cp = buf1;
7347 		break;
7348 	}
7349 	switch (format) {
7350 	case DISP_ADDR_AND_PORT:
7351 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7352 			/*
7353 			 * Note that we use the remote address in the tcp_b
7354 			 * structure.  This means that it will print out
7355 			 * the real destination address, not the next hop's
7356 			 * address if source routing is used.
7357 			 */
7358 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7359 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7360 
7361 		} else {
7362 			local = tcp->tcp_ip_src_v6;
7363 			remote = tcp->tcp_remote_v6;
7364 		}
7365 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7366 		    sizeof (local_addrbuf));
7367 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7368 		    sizeof (remote_addrbuf));
7369 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7370 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7371 		    ntohs(tcp->tcp_fport), cp);
7372 		break;
7373 	case DISP_PORT_ONLY:
7374 	default:
7375 		(void) mi_sprintf(buf, "[%u, %u] %s",
7376 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7377 		break;
7378 	}
7379 
7380 	return (buf);
7381 }
7382 
7383 /*
7384  * Called via squeue to get on to eager's perimeter to send a
7385  * TH_RST. The listener wants the eager to disappear either
7386  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
7387  * being called.
7388  */
7389 /* ARGSUSED */
7390 void
7391 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7392 {
7393 	conn_t	*econnp = (conn_t *)arg;
7394 	tcp_t	*eager = econnp->conn_tcp;
7395 	tcp_t	*listener = eager->tcp_listener;
7396 
7397 	/*
7398 	 * We could be called because listener is closing. Since
7399 	 * the eager is using listener's queue's, its not safe.
7400 	 * Better use the default queue just to send the TH_RST
7401 	 * out.
7402 	 */
7403 	eager->tcp_rq = tcp_g_q;
7404 	eager->tcp_wq = WR(tcp_g_q);
7405 
7406 	if (eager->tcp_state > TCPS_LISTEN) {
7407 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7408 		    eager, eager->tcp_snxt, 0, TH_RST);
7409 	}
7410 
7411 	/* We are here because listener wants this eager gone */
7412 	if (listener != NULL) {
7413 		mutex_enter(&listener->tcp_eager_lock);
7414 		tcp_eager_unlink(eager);
7415 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
7416 			/*
7417 			 * The eager has sent a conn_ind up to the
7418 			 * listener but listener decides to close
7419 			 * instead. We need to drop the extra ref
7420 			 * placed on eager in tcp_rput_data() before
7421 			 * sending the conn_ind to listener.
7422 			 */
7423 			CONN_DEC_REF(econnp);
7424 		}
7425 		mutex_exit(&listener->tcp_eager_lock);
7426 		CONN_DEC_REF(listener->tcp_connp);
7427 	}
7428 
7429 	if (eager->tcp_state > TCPS_BOUND)
7430 		tcp_close_detached(eager);
7431 }
7432 
7433 /*
7434  * Reset any eager connection hanging off this listener marked
7435  * with 'seqnum' and then reclaim it's resources.
7436  */
7437 static boolean_t
7438 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7439 {
7440 	tcp_t	*eager;
7441 	mblk_t 	*mp;
7442 
7443 	TCP_STAT(tcp_eager_blowoff_calls);
7444 	eager = listener;
7445 	mutex_enter(&listener->tcp_eager_lock);
7446 	do {
7447 		eager = eager->tcp_eager_next_q;
7448 		if (eager == NULL) {
7449 			mutex_exit(&listener->tcp_eager_lock);
7450 			return (B_FALSE);
7451 		}
7452 	} while (eager->tcp_conn_req_seqnum != seqnum);
7453 	CONN_INC_REF(eager->tcp_connp);
7454 	mutex_exit(&listener->tcp_eager_lock);
7455 	mp = &eager->tcp_closemp;
7456 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7457 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7458 	return (B_TRUE);
7459 }
7460 
7461 /*
7462  * Reset any eager connection hanging off this listener
7463  * and then reclaim it's resources.
7464  */
7465 static void
7466 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7467 {
7468 	tcp_t	*eager;
7469 	mblk_t	*mp;
7470 
7471 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7472 
7473 	if (!q0_only) {
7474 		/* First cleanup q */
7475 		TCP_STAT(tcp_eager_blowoff_q);
7476 		eager = listener->tcp_eager_next_q;
7477 		while (eager != NULL) {
7478 			CONN_INC_REF(eager->tcp_connp);
7479 			mp = &eager->tcp_closemp;
7480 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7481 			    tcp_eager_kill, eager->tcp_connp,
7482 			    SQTAG_TCP_EAGER_CLEANUP);
7483 			eager = eager->tcp_eager_next_q;
7484 		}
7485 	}
7486 	/* Then cleanup q0 */
7487 	TCP_STAT(tcp_eager_blowoff_q0);
7488 	eager = listener->tcp_eager_next_q0;
7489 	while (eager != listener) {
7490 		CONN_INC_REF(eager->tcp_connp);
7491 		mp = &eager->tcp_closemp;
7492 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
7493 		    tcp_eager_kill, eager->tcp_connp,
7494 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
7495 		eager = eager->tcp_eager_next_q0;
7496 	}
7497 }
7498 
7499 /*
7500  * If we are an eager connection hanging off a listener that hasn't
7501  * formally accepted the connection yet, get off his list and blow off
7502  * any data that we have accumulated.
7503  */
7504 static void
7505 tcp_eager_unlink(tcp_t *tcp)
7506 {
7507 	tcp_t	*listener = tcp->tcp_listener;
7508 
7509 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7510 	ASSERT(listener != NULL);
7511 	if (tcp->tcp_eager_next_q0 != NULL) {
7512 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7513 
7514 		/* Remove the eager tcp from q0 */
7515 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7516 		    tcp->tcp_eager_prev_q0;
7517 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7518 		    tcp->tcp_eager_next_q0;
7519 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7520 		listener->tcp_conn_req_cnt_q0--;
7521 
7522 		tcp->tcp_eager_next_q0 = NULL;
7523 		tcp->tcp_eager_prev_q0 = NULL;
7524 
7525 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7526 			/* we have timed out before */
7527 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7528 			listener->tcp_syn_rcvd_timeout--;
7529 		}
7530 	} else {
7531 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7532 		tcp_t	*prev = NULL;
7533 
7534 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7535 			if (tcpp[0] == tcp) {
7536 				if (listener->tcp_eager_last_q == tcp) {
7537 					/*
7538 					 * If we are unlinking the last
7539 					 * element on the list, adjust
7540 					 * tail pointer. Set tail pointer
7541 					 * to nil when list is empty.
7542 					 */
7543 					ASSERT(tcp->tcp_eager_next_q == NULL);
7544 					if (listener->tcp_eager_last_q ==
7545 					    listener->tcp_eager_next_q) {
7546 						listener->tcp_eager_last_q =
7547 						NULL;
7548 					} else {
7549 						/*
7550 						 * We won't get here if there
7551 						 * is only one eager in the
7552 						 * list.
7553 						 */
7554 						ASSERT(prev != NULL);
7555 						listener->tcp_eager_last_q =
7556 						    prev;
7557 					}
7558 				}
7559 				tcpp[0] = tcp->tcp_eager_next_q;
7560 				tcp->tcp_eager_next_q = NULL;
7561 				tcp->tcp_eager_last_q = NULL;
7562 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7563 				listener->tcp_conn_req_cnt_q--;
7564 				break;
7565 			}
7566 			prev = tcpp[0];
7567 		}
7568 	}
7569 	tcp->tcp_listener = NULL;
7570 }
7571 
7572 /* Shorthand to generate and send TPI error acks to our client */
7573 static void
7574 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7575 {
7576 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7577 		putnext(tcp->tcp_rq, mp);
7578 }
7579 
7580 /* Shorthand to generate and send TPI error acks to our client */
7581 static void
7582 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7583     int t_error, int sys_error)
7584 {
7585 	struct T_error_ack	*teackp;
7586 
7587 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7588 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7589 		teackp = (struct T_error_ack *)mp->b_rptr;
7590 		teackp->ERROR_prim = primitive;
7591 		teackp->TLI_error = t_error;
7592 		teackp->UNIX_error = sys_error;
7593 		putnext(tcp->tcp_rq, mp);
7594 	}
7595 }
7596 
7597 /*
7598  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7599  * but instead the code relies on:
7600  * - the fact that the address of the array and its size never changes
7601  * - the atomic assignment of the elements of the array
7602  */
7603 /* ARGSUSED */
7604 static int
7605 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7606 {
7607 	int i;
7608 
7609 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7610 		if (tcp_g_epriv_ports[i] != 0)
7611 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7612 	}
7613 	return (0);
7614 }
7615 
7616 /*
7617  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7618  * threads from changing it at the same time.
7619  */
7620 /* ARGSUSED */
7621 static int
7622 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7623     cred_t *cr)
7624 {
7625 	long	new_value;
7626 	int	i;
7627 
7628 	/*
7629 	 * Fail the request if the new value does not lie within the
7630 	 * port number limits.
7631 	 */
7632 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7633 	    new_value <= 0 || new_value >= 65536) {
7634 		return (EINVAL);
7635 	}
7636 
7637 	mutex_enter(&tcp_epriv_port_lock);
7638 	/* Check if the value is already in the list */
7639 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7640 		if (new_value == tcp_g_epriv_ports[i]) {
7641 			mutex_exit(&tcp_epriv_port_lock);
7642 			return (EEXIST);
7643 		}
7644 	}
7645 	/* Find an empty slot */
7646 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7647 		if (tcp_g_epriv_ports[i] == 0)
7648 			break;
7649 	}
7650 	if (i == tcp_g_num_epriv_ports) {
7651 		mutex_exit(&tcp_epriv_port_lock);
7652 		return (EOVERFLOW);
7653 	}
7654 	/* Set the new value */
7655 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7656 	mutex_exit(&tcp_epriv_port_lock);
7657 	return (0);
7658 }
7659 
7660 /*
7661  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7662  * threads from changing it at the same time.
7663  */
7664 /* ARGSUSED */
7665 static int
7666 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7667     cred_t *cr)
7668 {
7669 	long	new_value;
7670 	int	i;
7671 
7672 	/*
7673 	 * Fail the request if the new value does not lie within the
7674 	 * port number limits.
7675 	 */
7676 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7677 	    new_value >= 65536) {
7678 		return (EINVAL);
7679 	}
7680 
7681 	mutex_enter(&tcp_epriv_port_lock);
7682 	/* Check that the value is already in the list */
7683 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7684 		if (tcp_g_epriv_ports[i] == new_value)
7685 			break;
7686 	}
7687 	if (i == tcp_g_num_epriv_ports) {
7688 		mutex_exit(&tcp_epriv_port_lock);
7689 		return (ESRCH);
7690 	}
7691 	/* Clear the value */
7692 	tcp_g_epriv_ports[i] = 0;
7693 	mutex_exit(&tcp_epriv_port_lock);
7694 	return (0);
7695 }
7696 
7697 /* Return the TPI/TLI equivalent of our current tcp_state */
7698 static int
7699 tcp_tpistate(tcp_t *tcp)
7700 {
7701 	switch (tcp->tcp_state) {
7702 	case TCPS_IDLE:
7703 		return (TS_UNBND);
7704 	case TCPS_LISTEN:
7705 		/*
7706 		 * Return whether there are outstanding T_CONN_IND waiting
7707 		 * for the matching T_CONN_RES. Therefore don't count q0.
7708 		 */
7709 		if (tcp->tcp_conn_req_cnt_q > 0)
7710 			return (TS_WRES_CIND);
7711 		else
7712 			return (TS_IDLE);
7713 	case TCPS_BOUND:
7714 		return (TS_IDLE);
7715 	case TCPS_SYN_SENT:
7716 		return (TS_WCON_CREQ);
7717 	case TCPS_SYN_RCVD:
7718 		/*
7719 		 * Note: assumption: this has to the active open SYN_RCVD.
7720 		 * The passive instance is detached in SYN_RCVD stage of
7721 		 * incoming connection processing so we cannot get request
7722 		 * for T_info_ack on it.
7723 		 */
7724 		return (TS_WACK_CRES);
7725 	case TCPS_ESTABLISHED:
7726 		return (TS_DATA_XFER);
7727 	case TCPS_CLOSE_WAIT:
7728 		return (TS_WREQ_ORDREL);
7729 	case TCPS_FIN_WAIT_1:
7730 		return (TS_WIND_ORDREL);
7731 	case TCPS_FIN_WAIT_2:
7732 		return (TS_WIND_ORDREL);
7733 
7734 	case TCPS_CLOSING:
7735 	case TCPS_LAST_ACK:
7736 	case TCPS_TIME_WAIT:
7737 	case TCPS_CLOSED:
7738 		/*
7739 		 * Following TS_WACK_DREQ7 is a rendition of "not
7740 		 * yet TS_IDLE" TPI state. There is no best match to any
7741 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7742 		 * choose a value chosen that will map to TLI/XTI level
7743 		 * state of TSTATECHNG (state is process of changing) which
7744 		 * captures what this dummy state represents.
7745 		 */
7746 		return (TS_WACK_DREQ7);
7747 	default:
7748 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7749 		    tcp->tcp_state, tcp_display(tcp, NULL,
7750 		    DISP_PORT_ONLY));
7751 		return (TS_UNBND);
7752 	}
7753 }
7754 
7755 static void
7756 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7757 {
7758 	if (tcp->tcp_family == AF_INET6)
7759 		*tia = tcp_g_t_info_ack_v6;
7760 	else
7761 		*tia = tcp_g_t_info_ack;
7762 	tia->CURRENT_state = tcp_tpistate(tcp);
7763 	tia->OPT_size = tcp_max_optsize;
7764 	if (tcp->tcp_mss == 0) {
7765 		/* Not yet set - tcp_open does not set mss */
7766 		if (tcp->tcp_ipversion == IPV4_VERSION)
7767 			tia->TIDU_size = tcp_mss_def_ipv4;
7768 		else
7769 			tia->TIDU_size = tcp_mss_def_ipv6;
7770 	} else {
7771 		tia->TIDU_size = tcp->tcp_mss;
7772 	}
7773 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7774 }
7775 
7776 /*
7777  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7778  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7779  * tcp_g_t_info_ack.  The current state of the stream is copied from
7780  * tcp_state.
7781  */
7782 static void
7783 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7784 {
7785 	t_uscalar_t		cap_bits1;
7786 	struct T_capability_ack	*tcap;
7787 
7788 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7789 		freemsg(mp);
7790 		return;
7791 	}
7792 
7793 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7794 
7795 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7796 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7797 	if (mp == NULL)
7798 		return;
7799 
7800 	tcap = (struct T_capability_ack *)mp->b_rptr;
7801 	tcap->CAP_bits1 = 0;
7802 
7803 	if (cap_bits1 & TC1_INFO) {
7804 		tcp_copy_info(&tcap->INFO_ack, tcp);
7805 		tcap->CAP_bits1 |= TC1_INFO;
7806 	}
7807 
7808 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7809 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7810 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7811 	}
7812 
7813 	putnext(tcp->tcp_rq, mp);
7814 }
7815 
7816 /*
7817  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7818  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7819  * The current state of the stream is copied from tcp_state.
7820  */
7821 static void
7822 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7823 {
7824 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7825 	    T_INFO_ACK);
7826 	if (!mp) {
7827 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7828 		return;
7829 	}
7830 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7831 	putnext(tcp->tcp_rq, mp);
7832 }
7833 
7834 /* Respond to the TPI addr request */
7835 static void
7836 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7837 {
7838 	sin_t	*sin;
7839 	mblk_t	*ackmp;
7840 	struct T_addr_ack *taa;
7841 
7842 	/* Make it large enough for worst case */
7843 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7844 	    2 * sizeof (sin6_t), 1);
7845 	if (ackmp == NULL) {
7846 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7847 		return;
7848 	}
7849 
7850 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7851 		tcp_addr_req_ipv6(tcp, ackmp);
7852 		return;
7853 	}
7854 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7855 
7856 	bzero(taa, sizeof (struct T_addr_ack));
7857 	ackmp->b_wptr = (uchar_t *)&taa[1];
7858 
7859 	taa->PRIM_type = T_ADDR_ACK;
7860 	ackmp->b_datap->db_type = M_PCPROTO;
7861 
7862 	/*
7863 	 * Note: Following code assumes 32 bit alignment of basic
7864 	 * data structures like sin_t and struct T_addr_ack.
7865 	 */
7866 	if (tcp->tcp_state >= TCPS_BOUND) {
7867 		/*
7868 		 * Fill in local address
7869 		 */
7870 		taa->LOCADDR_length = sizeof (sin_t);
7871 		taa->LOCADDR_offset = sizeof (*taa);
7872 
7873 		sin = (sin_t *)&taa[1];
7874 
7875 		/* Fill zeroes and then intialize non-zero fields */
7876 		*sin = sin_null;
7877 
7878 		sin->sin_family = AF_INET;
7879 
7880 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7881 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7882 
7883 		ackmp->b_wptr = (uchar_t *)&sin[1];
7884 
7885 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7886 			/*
7887 			 * Fill in Remote address
7888 			 */
7889 			taa->REMADDR_length = sizeof (sin_t);
7890 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7891 						taa->LOCADDR_length);
7892 
7893 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7894 			*sin = sin_null;
7895 			sin->sin_family = AF_INET;
7896 			sin->sin_addr.s_addr = tcp->tcp_remote;
7897 			sin->sin_port = tcp->tcp_fport;
7898 
7899 			ackmp->b_wptr = (uchar_t *)&sin[1];
7900 		}
7901 	}
7902 	putnext(tcp->tcp_rq, ackmp);
7903 }
7904 
7905 /* Assumes that tcp_addr_req gets enough space and alignment */
7906 static void
7907 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7908 {
7909 	sin6_t	*sin6;
7910 	struct T_addr_ack *taa;
7911 
7912 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7913 	ASSERT(OK_32PTR(ackmp->b_rptr));
7914 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7915 	    2 * sizeof (sin6_t));
7916 
7917 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7918 
7919 	bzero(taa, sizeof (struct T_addr_ack));
7920 	ackmp->b_wptr = (uchar_t *)&taa[1];
7921 
7922 	taa->PRIM_type = T_ADDR_ACK;
7923 	ackmp->b_datap->db_type = M_PCPROTO;
7924 
7925 	/*
7926 	 * Note: Following code assumes 32 bit alignment of basic
7927 	 * data structures like sin6_t and struct T_addr_ack.
7928 	 */
7929 	if (tcp->tcp_state >= TCPS_BOUND) {
7930 		/*
7931 		 * Fill in local address
7932 		 */
7933 		taa->LOCADDR_length = sizeof (sin6_t);
7934 		taa->LOCADDR_offset = sizeof (*taa);
7935 
7936 		sin6 = (sin6_t *)&taa[1];
7937 		*sin6 = sin6_null;
7938 
7939 		sin6->sin6_family = AF_INET6;
7940 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7941 		sin6->sin6_port = tcp->tcp_lport;
7942 
7943 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7944 
7945 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7946 			/*
7947 			 * Fill in Remote address
7948 			 */
7949 			taa->REMADDR_length = sizeof (sin6_t);
7950 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7951 						taa->LOCADDR_length);
7952 
7953 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7954 			*sin6 = sin6_null;
7955 			sin6->sin6_family = AF_INET6;
7956 			sin6->sin6_flowinfo =
7957 			    tcp->tcp_ip6h->ip6_vcf &
7958 			    ~IPV6_VERS_AND_FLOW_MASK;
7959 			sin6->sin6_addr = tcp->tcp_remote_v6;
7960 			sin6->sin6_port = tcp->tcp_fport;
7961 
7962 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7963 		}
7964 	}
7965 	putnext(tcp->tcp_rq, ackmp);
7966 }
7967 
7968 /*
7969  * Handle reinitialization of a tcp structure.
7970  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7971  */
7972 static void
7973 tcp_reinit(tcp_t *tcp)
7974 {
7975 	mblk_t	*mp;
7976 	int 	err;
7977 
7978 	TCP_STAT(tcp_reinit_calls);
7979 
7980 	/* tcp_reinit should never be called for detached tcp_t's */
7981 	ASSERT(tcp->tcp_listener == NULL);
7982 	ASSERT((tcp->tcp_family == AF_INET &&
7983 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7984 	    (tcp->tcp_family == AF_INET6 &&
7985 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7986 	    tcp->tcp_ipversion == IPV6_VERSION)));
7987 
7988 	/* Cancel outstanding timers */
7989 	tcp_timers_stop(tcp);
7990 
7991 	if (tcp->tcp_flow_stopped) {
7992 		tcp->tcp_flow_stopped = B_FALSE;
7993 		tcp_clrqfull(tcp);
7994 	}
7995 	/*
7996 	 * Reset everything in the state vector, after updating global
7997 	 * MIB data from instance counters.
7998 	 */
7999 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
8000 	tcp->tcp_ibsegs = 0;
8001 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
8002 	tcp->tcp_obsegs = 0;
8003 
8004 	tcp_close_mpp(&tcp->tcp_xmit_head);
8005 	if (tcp->tcp_snd_zcopy_aware)
8006 		tcp_zcopy_notify(tcp);
8007 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
8008 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
8009 	tcp_close_mpp(&tcp->tcp_reass_head);
8010 	tcp->tcp_reass_tail = NULL;
8011 	if (tcp->tcp_rcv_list != NULL) {
8012 		/* Free b_next chain */
8013 		tcp_close_mpp(&tcp->tcp_rcv_list);
8014 		tcp->tcp_rcv_last_head = NULL;
8015 		tcp->tcp_rcv_last_tail = NULL;
8016 		tcp->tcp_rcv_cnt = 0;
8017 	}
8018 	tcp->tcp_rcv_last_tail = NULL;
8019 
8020 	if ((mp = tcp->tcp_urp_mp) != NULL) {
8021 		freemsg(mp);
8022 		tcp->tcp_urp_mp = NULL;
8023 	}
8024 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
8025 		freemsg(mp);
8026 		tcp->tcp_urp_mark_mp = NULL;
8027 	}
8028 	if (tcp->tcp_fused_sigurg_mp != NULL) {
8029 		freeb(tcp->tcp_fused_sigurg_mp);
8030 		tcp->tcp_fused_sigurg_mp = NULL;
8031 	}
8032 
8033 	/*
8034 	 * Following is a union with two members which are
8035 	 * identical types and size so the following cleanup
8036 	 * is enough.
8037 	 */
8038 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
8039 
8040 	CL_INET_DISCONNECT(tcp);
8041 
8042 	/*
8043 	 * The connection can't be on the tcp_time_wait_head list
8044 	 * since it is not detached.
8045 	 */
8046 	ASSERT(tcp->tcp_time_wait_next == NULL);
8047 	ASSERT(tcp->tcp_time_wait_prev == NULL);
8048 	ASSERT(tcp->tcp_time_wait_expire == 0);
8049 
8050 	/*
8051 	 * Reset/preserve other values
8052 	 */
8053 	tcp_reinit_values(tcp);
8054 	ipcl_hash_remove(tcp->tcp_connp);
8055 	conn_delete_ire(tcp->tcp_connp, NULL);
8056 
8057 	if (tcp->tcp_conn_req_max != 0) {
8058 		/*
8059 		 * This is the case when a TLI program uses the same
8060 		 * transport end point to accept a connection.  This
8061 		 * makes the TCP both a listener and acceptor.  When
8062 		 * this connection is closed, we need to set the state
8063 		 * back to TCPS_LISTEN.  Make sure that the eager list
8064 		 * is reinitialized.
8065 		 *
8066 		 * Note that this stream is still bound to the four
8067 		 * tuples of the previous connection in IP.  If a new
8068 		 * SYN with different foreign address comes in, IP will
8069 		 * not find it and will send it to the global queue.  In
8070 		 * the global queue, TCP will do a tcp_lookup_listener()
8071 		 * to find this stream.  This works because this stream
8072 		 * is only removed from connected hash.
8073 		 *
8074 		 */
8075 		tcp->tcp_state = TCPS_LISTEN;
8076 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
8077 		tcp->tcp_connp->conn_recv = tcp_conn_request;
8078 		if (tcp->tcp_family == AF_INET6) {
8079 			ASSERT(tcp->tcp_connp->conn_af_isv6);
8080 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
8081 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
8082 		} else {
8083 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
8084 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
8085 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
8086 		}
8087 	} else {
8088 		tcp->tcp_state = TCPS_BOUND;
8089 	}
8090 
8091 	/*
8092 	 * Initialize to default values
8093 	 * Can't fail since enough header template space already allocated
8094 	 * at open().
8095 	 */
8096 	err = tcp_init_values(tcp);
8097 	ASSERT(err == 0);
8098 	/* Restore state in tcp_tcph */
8099 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
8100 	if (tcp->tcp_ipversion == IPV4_VERSION)
8101 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
8102 	else
8103 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
8104 	/*
8105 	 * Copy of the src addr. in tcp_t is needed in tcp_t
8106 	 * since the lookup funcs can only lookup on tcp_t
8107 	 */
8108 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
8109 
8110 	ASSERT(tcp->tcp_ptpbhn != NULL);
8111 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
8112 	tcp->tcp_rwnd = tcp_recv_hiwat;
8113 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
8114 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
8115 }
8116 
8117 /*
8118  * Force values to zero that need be zero.
8119  * Do not touch values asociated with the BOUND or LISTEN state
8120  * since the connection will end up in that state after the reinit.
8121  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
8122  * structure!
8123  */
8124 static void
8125 tcp_reinit_values(tcp)
8126 	tcp_t *tcp;
8127 {
8128 #ifndef	lint
8129 #define	DONTCARE(x)
8130 #define	PRESERVE(x)
8131 #else
8132 #define	DONTCARE(x)	((x) = (x))
8133 #define	PRESERVE(x)	((x) = (x))
8134 #endif	/* lint */
8135 
8136 	PRESERVE(tcp->tcp_bind_hash);
8137 	PRESERVE(tcp->tcp_ptpbhn);
8138 	PRESERVE(tcp->tcp_acceptor_hash);
8139 	PRESERVE(tcp->tcp_ptpahn);
8140 
8141 	/* Should be ASSERT NULL on these with new code! */
8142 	ASSERT(tcp->tcp_time_wait_next == NULL);
8143 	ASSERT(tcp->tcp_time_wait_prev == NULL);
8144 	ASSERT(tcp->tcp_time_wait_expire == 0);
8145 	PRESERVE(tcp->tcp_state);
8146 	PRESERVE(tcp->tcp_rq);
8147 	PRESERVE(tcp->tcp_wq);
8148 
8149 	ASSERT(tcp->tcp_xmit_head == NULL);
8150 	ASSERT(tcp->tcp_xmit_last == NULL);
8151 	ASSERT(tcp->tcp_unsent == 0);
8152 	ASSERT(tcp->tcp_xmit_tail == NULL);
8153 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
8154 
8155 	tcp->tcp_snxt = 0;			/* Displayed in mib */
8156 	tcp->tcp_suna = 0;			/* Displayed in mib */
8157 	tcp->tcp_swnd = 0;
8158 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
8159 
8160 	ASSERT(tcp->tcp_ibsegs == 0);
8161 	ASSERT(tcp->tcp_obsegs == 0);
8162 
8163 	if (tcp->tcp_iphc != NULL) {
8164 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8165 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
8166 	}
8167 
8168 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
8169 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
8170 	DONTCARE(tcp->tcp_ipha);
8171 	DONTCARE(tcp->tcp_ip6h);
8172 	DONTCARE(tcp->tcp_ip_hdr_len);
8173 	DONTCARE(tcp->tcp_tcph);
8174 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
8175 	tcp->tcp_valid_bits = 0;
8176 
8177 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
8178 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
8179 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
8180 	tcp->tcp_last_rcv_lbolt = 0;
8181 
8182 	tcp->tcp_init_cwnd = 0;
8183 
8184 	tcp->tcp_urp_last_valid = 0;
8185 	tcp->tcp_hard_binding = 0;
8186 	tcp->tcp_hard_bound = 0;
8187 	PRESERVE(tcp->tcp_cred);
8188 	PRESERVE(tcp->tcp_cpid);
8189 	PRESERVE(tcp->tcp_exclbind);
8190 
8191 	tcp->tcp_fin_acked = 0;
8192 	tcp->tcp_fin_rcvd = 0;
8193 	tcp->tcp_fin_sent = 0;
8194 	tcp->tcp_ordrel_done = 0;
8195 
8196 	ASSERT(tcp->tcp_flow_stopped == 0);
8197 	tcp->tcp_debug = 0;
8198 	tcp->tcp_dontroute = 0;
8199 	tcp->tcp_broadcast = 0;
8200 
8201 	tcp->tcp_useloopback = 0;
8202 	tcp->tcp_reuseaddr = 0;
8203 	tcp->tcp_oobinline = 0;
8204 	tcp->tcp_dgram_errind = 0;
8205 
8206 	tcp->tcp_detached = 0;
8207 	tcp->tcp_bind_pending = 0;
8208 	tcp->tcp_unbind_pending = 0;
8209 	tcp->tcp_deferred_clean_death = 0;
8210 
8211 	tcp->tcp_snd_ws_ok = B_FALSE;
8212 	tcp->tcp_snd_ts_ok = B_FALSE;
8213 	tcp->tcp_linger = 0;
8214 	tcp->tcp_ka_enabled = 0;
8215 	tcp->tcp_zero_win_probe = 0;
8216 
8217 	tcp->tcp_loopback = 0;
8218 	tcp->tcp_localnet = 0;
8219 	tcp->tcp_syn_defense = 0;
8220 	tcp->tcp_set_timer = 0;
8221 
8222 	tcp->tcp_active_open = 0;
8223 	ASSERT(tcp->tcp_timeout == B_FALSE);
8224 	tcp->tcp_rexmit = B_FALSE;
8225 	tcp->tcp_xmit_zc_clean = B_FALSE;
8226 
8227 	tcp->tcp_snd_sack_ok = B_FALSE;
8228 	PRESERVE(tcp->tcp_recvdstaddr);
8229 	tcp->tcp_hwcksum = B_FALSE;
8230 
8231 	tcp->tcp_ire_ill_check_done = B_FALSE;
8232 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8233 
8234 	tcp->tcp_mdt = B_FALSE;
8235 	tcp->tcp_mdt_hdr_head = 0;
8236 	tcp->tcp_mdt_hdr_tail = 0;
8237 
8238 	tcp->tcp_conn_def_q0 = 0;
8239 	tcp->tcp_ip_forward_progress = B_FALSE;
8240 	tcp->tcp_anon_priv_bind = 0;
8241 	tcp->tcp_ecn_ok = B_FALSE;
8242 
8243 	tcp->tcp_cwr = B_FALSE;
8244 	tcp->tcp_ecn_echo_on = B_FALSE;
8245 
8246 	if (tcp->tcp_sack_info != NULL) {
8247 		if (tcp->tcp_notsack_list != NULL) {
8248 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8249 		}
8250 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8251 		tcp->tcp_sack_info = NULL;
8252 	}
8253 
8254 	tcp->tcp_rcv_ws = 0;
8255 	tcp->tcp_snd_ws = 0;
8256 	tcp->tcp_ts_recent = 0;
8257 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8258 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8259 	tcp->tcp_if_mtu = 0;
8260 
8261 	ASSERT(tcp->tcp_reass_head == NULL);
8262 	ASSERT(tcp->tcp_reass_tail == NULL);
8263 
8264 	tcp->tcp_cwnd_cnt = 0;
8265 
8266 	ASSERT(tcp->tcp_rcv_list == NULL);
8267 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8268 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8269 	ASSERT(tcp->tcp_rcv_cnt == 0);
8270 
8271 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8272 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8273 	tcp->tcp_csuna = 0;
8274 
8275 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8276 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8277 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8278 	tcp->tcp_rtt_update = 0;
8279 
8280 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8281 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8282 
8283 	tcp->tcp_rack = 0;			/* Displayed in mib */
8284 	tcp->tcp_rack_cnt = 0;
8285 	tcp->tcp_rack_cur_max = 0;
8286 	tcp->tcp_rack_abs_max = 0;
8287 
8288 	tcp->tcp_max_swnd = 0;
8289 
8290 	ASSERT(tcp->tcp_listener == NULL);
8291 
8292 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8293 
8294 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8295 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8296 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8297 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8298 
8299 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8300 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8301 	PRESERVE(tcp->tcp_conn_req_max);
8302 	PRESERVE(tcp->tcp_conn_req_seqnum);
8303 
8304 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8305 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8306 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8307 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8308 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8309 
8310 	tcp->tcp_lingertime = 0;
8311 
8312 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8313 	ASSERT(tcp->tcp_urp_mp == NULL);
8314 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8315 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8316 
8317 	ASSERT(tcp->tcp_eager_next_q == NULL);
8318 	ASSERT(tcp->tcp_eager_last_q == NULL);
8319 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8320 	    tcp->tcp_eager_prev_q0 == NULL) ||
8321 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8322 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8323 
8324 	tcp->tcp_client_errno = 0;
8325 
8326 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8327 
8328 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8329 
8330 	PRESERVE(tcp->tcp_bound_source_v6);
8331 	tcp->tcp_last_sent_len = 0;
8332 	tcp->tcp_dupack_cnt = 0;
8333 
8334 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8335 	PRESERVE(tcp->tcp_lport);
8336 
8337 	PRESERVE(tcp->tcp_acceptor_lockp);
8338 
8339 	ASSERT(tcp->tcp_ordrelid == 0);
8340 	PRESERVE(tcp->tcp_acceptor_id);
8341 	DONTCARE(tcp->tcp_ipsec_overhead);
8342 
8343 	/*
8344 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
8345 	 * in tcp structure and now tracing), Re-initialize all
8346 	 * members of tcp_traceinfo.
8347 	 */
8348 	if (tcp->tcp_tracebuf != NULL) {
8349 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
8350 	}
8351 
8352 	PRESERVE(tcp->tcp_family);
8353 	if (tcp->tcp_family == AF_INET6) {
8354 		tcp->tcp_ipversion = IPV6_VERSION;
8355 		tcp->tcp_mss = tcp_mss_def_ipv6;
8356 	} else {
8357 		tcp->tcp_ipversion = IPV4_VERSION;
8358 		tcp->tcp_mss = tcp_mss_def_ipv4;
8359 	}
8360 
8361 	tcp->tcp_bound_if = 0;
8362 	tcp->tcp_ipv6_recvancillary = 0;
8363 	tcp->tcp_recvifindex = 0;
8364 	tcp->tcp_recvhops = 0;
8365 	tcp->tcp_closed = 0;
8366 	tcp->tcp_cleandeathtag = 0;
8367 	if (tcp->tcp_hopopts != NULL) {
8368 		mi_free(tcp->tcp_hopopts);
8369 		tcp->tcp_hopopts = NULL;
8370 		tcp->tcp_hopoptslen = 0;
8371 	}
8372 	ASSERT(tcp->tcp_hopoptslen == 0);
8373 	if (tcp->tcp_dstopts != NULL) {
8374 		mi_free(tcp->tcp_dstopts);
8375 		tcp->tcp_dstopts = NULL;
8376 		tcp->tcp_dstoptslen = 0;
8377 	}
8378 	ASSERT(tcp->tcp_dstoptslen == 0);
8379 	if (tcp->tcp_rtdstopts != NULL) {
8380 		mi_free(tcp->tcp_rtdstopts);
8381 		tcp->tcp_rtdstopts = NULL;
8382 		tcp->tcp_rtdstoptslen = 0;
8383 	}
8384 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8385 	if (tcp->tcp_rthdr != NULL) {
8386 		mi_free(tcp->tcp_rthdr);
8387 		tcp->tcp_rthdr = NULL;
8388 		tcp->tcp_rthdrlen = 0;
8389 	}
8390 	ASSERT(tcp->tcp_rthdrlen == 0);
8391 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8392 
8393 	tcp->tcp_fused = B_FALSE;
8394 	tcp->tcp_unfusable = B_FALSE;
8395 	tcp->tcp_fused_sigurg = B_FALSE;
8396 	tcp->tcp_loopback_peer = NULL;
8397 
8398 	tcp->tcp_in_ack_unsent = 0;
8399 	tcp->tcp_cork = B_FALSE;
8400 
8401 #undef	DONTCARE
8402 #undef	PRESERVE
8403 }
8404 
8405 /*
8406  * Allocate necessary resources and initialize state vector.
8407  * Guaranteed not to fail so that when an error is returned,
8408  * the caller doesn't need to do any additional cleanup.
8409  */
8410 int
8411 tcp_init(tcp_t *tcp, queue_t *q)
8412 {
8413 	int	err;
8414 
8415 	tcp->tcp_rq = q;
8416 	tcp->tcp_wq = WR(q);
8417 	tcp->tcp_state = TCPS_IDLE;
8418 	if ((err = tcp_init_values(tcp)) != 0)
8419 		tcp_timers_stop(tcp);
8420 	return (err);
8421 }
8422 
8423 static int
8424 tcp_init_values(tcp_t *tcp)
8425 {
8426 	int	err;
8427 
8428 	ASSERT((tcp->tcp_family == AF_INET &&
8429 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8430 	    (tcp->tcp_family == AF_INET6 &&
8431 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8432 	    tcp->tcp_ipversion == IPV6_VERSION)));
8433 
8434 	/*
8435 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8436 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8437 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8438 	 * during first few transmissions of a connection as seen in slow
8439 	 * links.
8440 	 */
8441 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
8442 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
8443 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8444 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8445 	    tcp_conn_grace_period;
8446 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
8447 		tcp->tcp_rto = tcp_rexmit_interval_min;
8448 	tcp->tcp_timer_backoff = 0;
8449 	tcp->tcp_ms_we_have_waited = 0;
8450 	tcp->tcp_last_recv_time = lbolt;
8451 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
8452 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8453 
8454 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
8455 
8456 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
8457 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
8458 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
8459 	/*
8460 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8461 	 * passive open.
8462 	 */
8463 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
8464 
8465 	tcp->tcp_naglim = tcp_naglim_def;
8466 
8467 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8468 
8469 	tcp->tcp_mdt_hdr_head = 0;
8470 	tcp->tcp_mdt_hdr_tail = 0;
8471 
8472 	tcp->tcp_fused = B_FALSE;
8473 	tcp->tcp_unfusable = B_FALSE;
8474 	tcp->tcp_fused_sigurg = B_FALSE;
8475 	tcp->tcp_loopback_peer = NULL;
8476 
8477 	/* Initialize the header template */
8478 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8479 		err = tcp_header_init_ipv4(tcp);
8480 	} else {
8481 		err = tcp_header_init_ipv6(tcp);
8482 	}
8483 	if (err)
8484 		return (err);
8485 
8486 	/*
8487 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8488 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8489 	 */
8490 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8491 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
8492 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
8493 
8494 	tcp->tcp_cork = B_FALSE;
8495 	/*
8496 	 * Init the tcp_debug option.  This value determines whether TCP
8497 	 * calls strlog() to print out debug messages.  Doing this
8498 	 * initialization here means that this value is not inherited thru
8499 	 * tcp_reinit().
8500 	 */
8501 	tcp->tcp_debug = tcp_dbg;
8502 
8503 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8504 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8505 
8506 	return (0);
8507 }
8508 
8509 /*
8510  * Initialize the IPv4 header. Loses any record of any IP options.
8511  */
8512 static int
8513 tcp_header_init_ipv4(tcp_t *tcp)
8514 {
8515 	tcph_t		*tcph;
8516 	uint32_t	sum;
8517 
8518 	/*
8519 	 * This is a simple initialization. If there's
8520 	 * already a template, it should never be too small,
8521 	 * so reuse it.  Otherwise, allocate space for the new one.
8522 	 */
8523 	if (tcp->tcp_iphc == NULL) {
8524 		ASSERT(tcp->tcp_iphc_len == 0);
8525 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8526 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8527 		if (tcp->tcp_iphc == NULL) {
8528 			tcp->tcp_iphc_len = 0;
8529 			return (ENOMEM);
8530 		}
8531 	}
8532 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8533 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8534 	tcp->tcp_ip6h = NULL;
8535 	tcp->tcp_ipversion = IPV4_VERSION;
8536 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8537 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8538 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8539 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8540 	tcp->tcp_ipha->ipha_version_and_hdr_length
8541 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8542 	tcp->tcp_ipha->ipha_ident = 0;
8543 
8544 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8545 	tcp->tcp_tos = 0;
8546 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8547 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8548 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8549 
8550 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8551 	tcp->tcp_tcph = tcph;
8552 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8553 	/*
8554 	 * IP wants our header length in the checksum field to
8555 	 * allow it to perform a single pseudo-header+checksum
8556 	 * calculation on behalf of TCP.
8557 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8558 	 */
8559 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8560 	sum = (sum >> 16) + (sum & 0xFFFF);
8561 	U16_TO_ABE16(sum, tcph->th_sum);
8562 	return (0);
8563 }
8564 
8565 /*
8566  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8567  */
8568 static int
8569 tcp_header_init_ipv6(tcp_t *tcp)
8570 {
8571 	tcph_t	*tcph;
8572 	uint32_t	sum;
8573 
8574 	/*
8575 	 * This is a simple initialization. If there's
8576 	 * already a template, it should never be too small,
8577 	 * so reuse it. Otherwise, allocate space for the new one.
8578 	 * Ensure that there is enough space to "downgrade" the tcp_t
8579 	 * to an IPv4 tcp_t. This requires having space for a full load
8580 	 * of IPv4 options, as well as a full load of TCP options
8581 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8582 	 * than a v6 header and a TCP header with a full load of TCP options
8583 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8584 	 * We want to avoid reallocation in the "downgraded" case when
8585 	 * processing outbound IPv4 options.
8586 	 */
8587 	if (tcp->tcp_iphc == NULL) {
8588 		ASSERT(tcp->tcp_iphc_len == 0);
8589 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8590 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8591 		if (tcp->tcp_iphc == NULL) {
8592 			tcp->tcp_iphc_len = 0;
8593 			return (ENOMEM);
8594 		}
8595 	}
8596 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8597 	tcp->tcp_ipversion = IPV6_VERSION;
8598 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8599 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8600 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8601 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8602 	tcp->tcp_ipha = NULL;
8603 
8604 	/* Initialize the header template */
8605 
8606 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8607 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8608 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8609 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8610 
8611 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8612 	tcp->tcp_tcph = tcph;
8613 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8614 	/*
8615 	 * IP wants our header length in the checksum field to
8616 	 * allow it to perform a single psuedo-header+checksum
8617 	 * calculation on behalf of TCP.
8618 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8619 	 */
8620 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8621 	sum = (sum >> 16) + (sum & 0xFFFF);
8622 	U16_TO_ABE16(sum, tcph->th_sum);
8623 	return (0);
8624 }
8625 
8626 /* At minimum we need 4 bytes in the TCP header for the lookup */
8627 #define	ICMP_MIN_TCP_HDR	4
8628 
8629 /*
8630  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8631  * passed up by IP. The message is always received on the correct tcp_t.
8632  * Assumes that IP has pulled up everything up to and including the ICMP header.
8633  */
8634 void
8635 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8636 {
8637 	icmph_t *icmph;
8638 	ipha_t	*ipha;
8639 	int	iph_hdr_length;
8640 	tcph_t	*tcph;
8641 	boolean_t ipsec_mctl = B_FALSE;
8642 	boolean_t secure;
8643 	mblk_t *first_mp = mp;
8644 	uint32_t new_mss;
8645 	uint32_t ratio;
8646 	size_t mp_size = MBLKL(mp);
8647 	uint32_t seg_ack;
8648 	uint32_t seg_seq;
8649 
8650 	/* Assume IP provides aligned packets - otherwise toss */
8651 	if (!OK_32PTR(mp->b_rptr)) {
8652 		freemsg(mp);
8653 		return;
8654 	}
8655 
8656 	/*
8657 	 * Since ICMP errors are normal data marked with M_CTL when sent
8658 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8659 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8660 	 */
8661 	if ((mp_size == sizeof (ipsec_info_t)) &&
8662 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8663 		ASSERT(mp->b_cont != NULL);
8664 		mp = mp->b_cont;
8665 		/* IP should have done this */
8666 		ASSERT(OK_32PTR(mp->b_rptr));
8667 		mp_size = MBLKL(mp);
8668 		ipsec_mctl = B_TRUE;
8669 	}
8670 
8671 	/*
8672 	 * Verify that we have a complete outer IP header. If not, drop it.
8673 	 */
8674 	if (mp_size < sizeof (ipha_t)) {
8675 noticmpv4:
8676 		freemsg(first_mp);
8677 		return;
8678 	}
8679 
8680 	ipha = (ipha_t *)mp->b_rptr;
8681 	/*
8682 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8683 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8684 	 */
8685 	switch (IPH_HDR_VERSION(ipha)) {
8686 	case IPV6_VERSION:
8687 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8688 		return;
8689 	case IPV4_VERSION:
8690 		break;
8691 	default:
8692 		goto noticmpv4;
8693 	}
8694 
8695 	/* Skip past the outer IP and ICMP headers */
8696 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8697 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8698 	/*
8699 	 * If we don't have the correct outer IP header length or if the ULP
8700 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8701 	 * send it upstream.
8702 	 */
8703 	if (iph_hdr_length < sizeof (ipha_t) ||
8704 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8705 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8706 		goto noticmpv4;
8707 	}
8708 	ipha = (ipha_t *)&icmph[1];
8709 
8710 	/* Skip past the inner IP and find the ULP header */
8711 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8712 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8713 	/*
8714 	 * If we don't have the correct inner IP header length or if the ULP
8715 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8716 	 * bytes of TCP header, drop it.
8717 	 */
8718 	if (iph_hdr_length < sizeof (ipha_t) ||
8719 	    ipha->ipha_protocol != IPPROTO_TCP ||
8720 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8721 		goto noticmpv4;
8722 	}
8723 
8724 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8725 		if (ipsec_mctl) {
8726 			secure = ipsec_in_is_secure(first_mp);
8727 		} else {
8728 			secure = B_FALSE;
8729 		}
8730 		if (secure) {
8731 			/*
8732 			 * If we are willing to accept this in clear
8733 			 * we don't have to verify policy.
8734 			 */
8735 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8736 				if (!tcp_check_policy(tcp, first_mp,
8737 				    ipha, NULL, secure, ipsec_mctl)) {
8738 					/*
8739 					 * tcp_check_policy called
8740 					 * ip_drop_packet() on failure.
8741 					 */
8742 					return;
8743 				}
8744 			}
8745 		}
8746 	} else if (ipsec_mctl) {
8747 		/*
8748 		 * This is a hard_bound connection. IP has already
8749 		 * verified policy. We don't have to do it again.
8750 		 */
8751 		freeb(first_mp);
8752 		first_mp = mp;
8753 		ipsec_mctl = B_FALSE;
8754 	}
8755 
8756 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8757 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8758 	/*
8759 	 * TCP SHOULD check that the TCP sequence number contained in
8760 	 * payload of the ICMP error message is within the range
8761 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8762 	 */
8763 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8764 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8765 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8766 		/*
8767 		 * If the ICMP message is bogus, should we kill the
8768 		 * connection, or should we just drop the bogus ICMP
8769 		 * message? It would probably make more sense to just
8770 		 * drop the message so that if this one managed to get
8771 		 * in, the real connection should not suffer.
8772 		 */
8773 		goto noticmpv4;
8774 	}
8775 
8776 	switch (icmph->icmph_type) {
8777 	case ICMP_DEST_UNREACHABLE:
8778 		switch (icmph->icmph_code) {
8779 		case ICMP_FRAGMENTATION_NEEDED:
8780 			/*
8781 			 * Reduce the MSS based on the new MTU.  This will
8782 			 * eliminate any fragmentation locally.
8783 			 * N.B.  There may well be some funny side-effects on
8784 			 * the local send policy and the remote receive policy.
8785 			 * Pending further research, we provide
8786 			 * tcp_ignore_path_mtu just in case this proves
8787 			 * disastrous somewhere.
8788 			 *
8789 			 * After updating the MSS, retransmit part of the
8790 			 * dropped segment using the new mss by calling
8791 			 * tcp_wput_data().  Need to adjust all those
8792 			 * params to make sure tcp_wput_data() work properly.
8793 			 */
8794 			if (tcp_ignore_path_mtu)
8795 				break;
8796 
8797 			/*
8798 			 * Decrease the MSS by time stamp options
8799 			 * IP options and IPSEC options. tcp_hdr_len
8800 			 * includes time stamp option and IP option
8801 			 * length.
8802 			 */
8803 
8804 			new_mss = ntohs(icmph->icmph_du_mtu) -
8805 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8806 
8807 			/*
8808 			 * Only update the MSS if the new one is
8809 			 * smaller than the previous one.  This is
8810 			 * to avoid problems when getting multiple
8811 			 * ICMP errors for the same MTU.
8812 			 */
8813 			if (new_mss >= tcp->tcp_mss)
8814 				break;
8815 
8816 			/*
8817 			 * Stop doing PMTU if new_mss is less than 68
8818 			 * or less than tcp_mss_min.
8819 			 * The value 68 comes from rfc 1191.
8820 			 */
8821 			if (new_mss < MAX(68, tcp_mss_min))
8822 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8823 				    0;
8824 
8825 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8826 			ASSERT(ratio >= 1);
8827 			tcp_mss_set(tcp, new_mss);
8828 
8829 			/*
8830 			 * Make sure we have something to
8831 			 * send.
8832 			 */
8833 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8834 			    (tcp->tcp_xmit_head != NULL)) {
8835 				/*
8836 				 * Shrink tcp_cwnd in
8837 				 * proportion to the old MSS/new MSS.
8838 				 */
8839 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8840 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8841 				    (tcp->tcp_unsent == 0)) {
8842 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8843 				} else {
8844 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8845 				}
8846 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8847 				tcp->tcp_rexmit = B_TRUE;
8848 				tcp->tcp_dupack_cnt = 0;
8849 				tcp->tcp_snd_burst = TCP_CWND_SS;
8850 				tcp_ss_rexmit(tcp);
8851 			}
8852 			break;
8853 		case ICMP_PORT_UNREACHABLE:
8854 		case ICMP_PROTOCOL_UNREACHABLE:
8855 			switch (tcp->tcp_state) {
8856 			case TCPS_SYN_SENT:
8857 			case TCPS_SYN_RCVD:
8858 				/*
8859 				 * ICMP can snipe away incipient
8860 				 * TCP connections as long as
8861 				 * seq number is same as initial
8862 				 * send seq number.
8863 				 */
8864 				if (seg_seq == tcp->tcp_iss) {
8865 					(void) tcp_clean_death(tcp,
8866 					    ECONNREFUSED, 6);
8867 				}
8868 				break;
8869 			}
8870 			break;
8871 		case ICMP_HOST_UNREACHABLE:
8872 		case ICMP_NET_UNREACHABLE:
8873 			/* Record the error in case we finally time out. */
8874 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8875 				tcp->tcp_client_errno = EHOSTUNREACH;
8876 			else
8877 				tcp->tcp_client_errno = ENETUNREACH;
8878 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8879 				if (tcp->tcp_listener != NULL &&
8880 				    tcp->tcp_listener->tcp_syn_defense) {
8881 					/*
8882 					 * Ditch the half-open connection if we
8883 					 * suspect a SYN attack is under way.
8884 					 */
8885 					tcp_ip_ire_mark_advice(tcp);
8886 					(void) tcp_clean_death(tcp,
8887 					    tcp->tcp_client_errno, 7);
8888 				}
8889 			}
8890 			break;
8891 		default:
8892 			break;
8893 		}
8894 		break;
8895 	case ICMP_SOURCE_QUENCH: {
8896 		/*
8897 		 * use a global boolean to control
8898 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8899 		 * The default is false.
8900 		 */
8901 		if (tcp_icmp_source_quench) {
8902 			/*
8903 			 * Reduce the sending rate as if we got a
8904 			 * retransmit timeout
8905 			 */
8906 			uint32_t npkt;
8907 
8908 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8909 			    tcp->tcp_mss;
8910 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8911 			tcp->tcp_cwnd = tcp->tcp_mss;
8912 			tcp->tcp_cwnd_cnt = 0;
8913 		}
8914 		break;
8915 	}
8916 	}
8917 	freemsg(first_mp);
8918 }
8919 
8920 /*
8921  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8922  * error messages passed up by IP.
8923  * Assumes that IP has pulled up all the extension headers as well
8924  * as the ICMPv6 header.
8925  */
8926 static void
8927 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8928 {
8929 	icmp6_t *icmp6;
8930 	ip6_t	*ip6h;
8931 	uint16_t	iph_hdr_length;
8932 	tcpha_t	*tcpha;
8933 	uint8_t	*nexthdrp;
8934 	uint32_t new_mss;
8935 	uint32_t ratio;
8936 	boolean_t secure;
8937 	mblk_t *first_mp = mp;
8938 	size_t mp_size;
8939 	uint32_t seg_ack;
8940 	uint32_t seg_seq;
8941 
8942 	/*
8943 	 * The caller has determined if this is an IPSEC_IN packet and
8944 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8945 	 */
8946 	if (ipsec_mctl)
8947 		mp = mp->b_cont;
8948 
8949 	mp_size = MBLKL(mp);
8950 
8951 	/*
8952 	 * Verify that we have a complete IP header. If not, send it upstream.
8953 	 */
8954 	if (mp_size < sizeof (ip6_t)) {
8955 noticmpv6:
8956 		freemsg(first_mp);
8957 		return;
8958 	}
8959 
8960 	/*
8961 	 * Verify this is an ICMPV6 packet, else send it upstream.
8962 	 */
8963 	ip6h = (ip6_t *)mp->b_rptr;
8964 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8965 		iph_hdr_length = IPV6_HDR_LEN;
8966 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8967 	    &nexthdrp) ||
8968 	    *nexthdrp != IPPROTO_ICMPV6) {
8969 		goto noticmpv6;
8970 	}
8971 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8972 	ip6h = (ip6_t *)&icmp6[1];
8973 	/*
8974 	 * Verify if we have a complete ICMP and inner IP header.
8975 	 */
8976 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8977 		goto noticmpv6;
8978 
8979 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8980 		goto noticmpv6;
8981 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8982 	/*
8983 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8984 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8985 	 * packet.
8986 	 */
8987 	if ((*nexthdrp != IPPROTO_TCP) ||
8988 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8989 		goto noticmpv6;
8990 	}
8991 
8992 	/*
8993 	 * ICMP errors come on the right queue or come on
8994 	 * listener/global queue for detached connections and
8995 	 * get switched to the right queue. If it comes on the
8996 	 * right queue, policy check has already been done by IP
8997 	 * and thus free the first_mp without verifying the policy.
8998 	 * If it has come for a non-hard bound connection, we need
8999 	 * to verify policy as IP may not have done it.
9000 	 */
9001 	if (!tcp->tcp_hard_bound) {
9002 		if (ipsec_mctl) {
9003 			secure = ipsec_in_is_secure(first_mp);
9004 		} else {
9005 			secure = B_FALSE;
9006 		}
9007 		if (secure) {
9008 			/*
9009 			 * If we are willing to accept this in clear
9010 			 * we don't have to verify policy.
9011 			 */
9012 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
9013 				if (!tcp_check_policy(tcp, first_mp,
9014 				    NULL, ip6h, secure, ipsec_mctl)) {
9015 					/*
9016 					 * tcp_check_policy called
9017 					 * ip_drop_packet() on failure.
9018 					 */
9019 					return;
9020 				}
9021 			}
9022 		}
9023 	} else if (ipsec_mctl) {
9024 		/*
9025 		 * This is a hard_bound connection. IP has already
9026 		 * verified policy. We don't have to do it again.
9027 		 */
9028 		freeb(first_mp);
9029 		first_mp = mp;
9030 		ipsec_mctl = B_FALSE;
9031 	}
9032 
9033 	seg_ack = ntohl(tcpha->tha_ack);
9034 	seg_seq = ntohl(tcpha->tha_seq);
9035 	/*
9036 	 * TCP SHOULD check that the TCP sequence number contained in
9037 	 * payload of the ICMP error message is within the range
9038 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
9039 	 */
9040 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
9041 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
9042 		/*
9043 		 * If the ICMP message is bogus, should we kill the
9044 		 * connection, or should we just drop the bogus ICMP
9045 		 * message? It would probably make more sense to just
9046 		 * drop the message so that if this one managed to get
9047 		 * in, the real connection should not suffer.
9048 		 */
9049 		goto noticmpv6;
9050 	}
9051 
9052 	switch (icmp6->icmp6_type) {
9053 	case ICMP6_PACKET_TOO_BIG:
9054 		/*
9055 		 * Reduce the MSS based on the new MTU.  This will
9056 		 * eliminate any fragmentation locally.
9057 		 * N.B.  There may well be some funny side-effects on
9058 		 * the local send policy and the remote receive policy.
9059 		 * Pending further research, we provide
9060 		 * tcp_ignore_path_mtu just in case this proves
9061 		 * disastrous somewhere.
9062 		 *
9063 		 * After updating the MSS, retransmit part of the
9064 		 * dropped segment using the new mss by calling
9065 		 * tcp_wput_data().  Need to adjust all those
9066 		 * params to make sure tcp_wput_data() work properly.
9067 		 */
9068 		if (tcp_ignore_path_mtu)
9069 			break;
9070 
9071 		/*
9072 		 * Decrease the MSS by time stamp options
9073 		 * IP options and IPSEC options. tcp_hdr_len
9074 		 * includes time stamp option and IP option
9075 		 * length.
9076 		 */
9077 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
9078 			    tcp->tcp_ipsec_overhead;
9079 
9080 		/*
9081 		 * Only update the MSS if the new one is
9082 		 * smaller than the previous one.  This is
9083 		 * to avoid problems when getting multiple
9084 		 * ICMP errors for the same MTU.
9085 		 */
9086 		if (new_mss >= tcp->tcp_mss)
9087 			break;
9088 
9089 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
9090 		ASSERT(ratio >= 1);
9091 		tcp_mss_set(tcp, new_mss);
9092 
9093 		/*
9094 		 * Make sure we have something to
9095 		 * send.
9096 		 */
9097 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
9098 		    (tcp->tcp_xmit_head != NULL)) {
9099 			/*
9100 			 * Shrink tcp_cwnd in
9101 			 * proportion to the old MSS/new MSS.
9102 			 */
9103 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
9104 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
9105 			    (tcp->tcp_unsent == 0)) {
9106 				tcp->tcp_rexmit_max = tcp->tcp_fss;
9107 			} else {
9108 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
9109 			}
9110 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
9111 			tcp->tcp_rexmit = B_TRUE;
9112 			tcp->tcp_dupack_cnt = 0;
9113 			tcp->tcp_snd_burst = TCP_CWND_SS;
9114 			tcp_ss_rexmit(tcp);
9115 		}
9116 		break;
9117 
9118 	case ICMP6_DST_UNREACH:
9119 		switch (icmp6->icmp6_code) {
9120 		case ICMP6_DST_UNREACH_NOPORT:
9121 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9122 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9123 			    (tcpha->tha_seq == tcp->tcp_iss)) {
9124 				(void) tcp_clean_death(tcp,
9125 				    ECONNREFUSED, 8);
9126 			}
9127 			break;
9128 
9129 		case ICMP6_DST_UNREACH_ADMIN:
9130 		case ICMP6_DST_UNREACH_NOROUTE:
9131 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
9132 		case ICMP6_DST_UNREACH_ADDR:
9133 			/* Record the error in case we finally time out. */
9134 			tcp->tcp_client_errno = EHOSTUNREACH;
9135 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9136 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9137 			    (tcpha->tha_seq == tcp->tcp_iss)) {
9138 				if (tcp->tcp_listener != NULL &&
9139 				    tcp->tcp_listener->tcp_syn_defense) {
9140 					/*
9141 					 * Ditch the half-open connection if we
9142 					 * suspect a SYN attack is under way.
9143 					 */
9144 					tcp_ip_ire_mark_advice(tcp);
9145 					(void) tcp_clean_death(tcp,
9146 					    tcp->tcp_client_errno, 9);
9147 				}
9148 			}
9149 
9150 
9151 			break;
9152 		default:
9153 			break;
9154 		}
9155 		break;
9156 
9157 	case ICMP6_PARAM_PROB:
9158 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9159 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9160 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9161 		    (uchar_t *)nexthdrp) {
9162 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9163 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9164 				(void) tcp_clean_death(tcp,
9165 				    ECONNREFUSED, 10);
9166 			}
9167 			break;
9168 		}
9169 		break;
9170 
9171 	case ICMP6_TIME_EXCEEDED:
9172 	default:
9173 		break;
9174 	}
9175 	freemsg(first_mp);
9176 }
9177 
9178 /*
9179  * IP recognizes seven kinds of bind requests:
9180  *
9181  * - A zero-length address binds only to the protocol number.
9182  *
9183  * - A 4-byte address is treated as a request to
9184  * validate that the address is a valid local IPv4
9185  * address, appropriate for an application to bind to.
9186  * IP does the verification, but does not make any note
9187  * of the address at this time.
9188  *
9189  * - A 16-byte address contains is treated as a request
9190  * to validate a local IPv6 address, as the 4-byte
9191  * address case above.
9192  *
9193  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9194  * use it for the inbound fanout of packets.
9195  *
9196  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9197  * use it for the inbound fanout of packets.
9198  *
9199  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9200  * information consisting of local and remote addresses
9201  * and ports.  In this case, the addresses are both
9202  * validated as appropriate for this operation, and, if
9203  * so, the information is retained for use in the
9204  * inbound fanout.
9205  *
9206  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9207  * fanout information, like the 12-byte case above.
9208  *
9209  * IP will also fill in the IRE request mblk with information
9210  * regarding our peer.  In all cases, we notify IP of our protocol
9211  * type by appending a single protocol byte to the bind request.
9212  */
9213 static mblk_t *
9214 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9215 {
9216 	char	*cp;
9217 	mblk_t	*mp;
9218 	struct T_bind_req *tbr;
9219 	ipa_conn_t	*ac;
9220 	ipa6_conn_t	*ac6;
9221 	sin_t		*sin;
9222 	sin6_t		*sin6;
9223 
9224 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9225 	ASSERT((tcp->tcp_family == AF_INET &&
9226 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9227 	    (tcp->tcp_family == AF_INET6 &&
9228 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9229 	    tcp->tcp_ipversion == IPV6_VERSION)));
9230 
9231 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9232 	if (!mp)
9233 		return (mp);
9234 	mp->b_datap->db_type = M_PROTO;
9235 	tbr = (struct T_bind_req *)mp->b_rptr;
9236 	tbr->PRIM_type = bind_prim;
9237 	tbr->ADDR_offset = sizeof (*tbr);
9238 	tbr->CONIND_number = 0;
9239 	tbr->ADDR_length = addr_length;
9240 	cp = (char *)&tbr[1];
9241 	switch (addr_length) {
9242 	case sizeof (ipa_conn_t):
9243 		ASSERT(tcp->tcp_family == AF_INET);
9244 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9245 
9246 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9247 		if (mp->b_cont == NULL) {
9248 			freemsg(mp);
9249 			return (NULL);
9250 		}
9251 		mp->b_cont->b_wptr += sizeof (ire_t);
9252 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9253 
9254 		/* cp known to be 32 bit aligned */
9255 		ac = (ipa_conn_t *)cp;
9256 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9257 		ac->ac_faddr = tcp->tcp_remote;
9258 		ac->ac_fport = tcp->tcp_fport;
9259 		ac->ac_lport = tcp->tcp_lport;
9260 		tcp->tcp_hard_binding = 1;
9261 		break;
9262 
9263 	case sizeof (ipa6_conn_t):
9264 		ASSERT(tcp->tcp_family == AF_INET6);
9265 
9266 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9267 		if (mp->b_cont == NULL) {
9268 			freemsg(mp);
9269 			return (NULL);
9270 		}
9271 		mp->b_cont->b_wptr += sizeof (ire_t);
9272 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9273 
9274 		/* cp known to be 32 bit aligned */
9275 		ac6 = (ipa6_conn_t *)cp;
9276 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9277 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9278 			    &ac6->ac6_laddr);
9279 		} else {
9280 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9281 		}
9282 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9283 		ac6->ac6_fport = tcp->tcp_fport;
9284 		ac6->ac6_lport = tcp->tcp_lport;
9285 		tcp->tcp_hard_binding = 1;
9286 		break;
9287 
9288 	case sizeof (sin_t):
9289 		/*
9290 		 * NOTE: IPV6_ADDR_LEN also has same size.
9291 		 * Use family to discriminate.
9292 		 */
9293 		if (tcp->tcp_family == AF_INET) {
9294 			sin = (sin_t *)cp;
9295 
9296 			*sin = sin_null;
9297 			sin->sin_family = AF_INET;
9298 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9299 			sin->sin_port = tcp->tcp_lport;
9300 			break;
9301 		} else {
9302 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9303 		}
9304 		break;
9305 
9306 	case sizeof (sin6_t):
9307 		ASSERT(tcp->tcp_family == AF_INET6);
9308 		sin6 = (sin6_t *)cp;
9309 
9310 		*sin6 = sin6_null;
9311 		sin6->sin6_family = AF_INET6;
9312 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9313 		sin6->sin6_port = tcp->tcp_lport;
9314 		break;
9315 
9316 	case IP_ADDR_LEN:
9317 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9318 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9319 		break;
9320 
9321 	}
9322 	/* Add protocol number to end */
9323 	cp[addr_length] = (char)IPPROTO_TCP;
9324 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9325 	return (mp);
9326 }
9327 
9328 /*
9329  * Notify IP that we are having trouble with this connection.  IP should
9330  * blow the IRE away and start over.
9331  */
9332 static void
9333 tcp_ip_notify(tcp_t *tcp)
9334 {
9335 	struct iocblk	*iocp;
9336 	ipid_t	*ipid;
9337 	mblk_t	*mp;
9338 
9339 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9340 	if (tcp->tcp_ipversion == IPV6_VERSION)
9341 		return;
9342 
9343 	mp = mkiocb(IP_IOCTL);
9344 	if (mp == NULL)
9345 		return;
9346 
9347 	iocp = (struct iocblk *)mp->b_rptr;
9348 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9349 
9350 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9351 	if (!mp->b_cont) {
9352 		freeb(mp);
9353 		return;
9354 	}
9355 
9356 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9357 	mp->b_cont->b_wptr += iocp->ioc_count;
9358 	bzero(ipid, sizeof (*ipid));
9359 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9360 	ipid->ipid_ire_type = IRE_CACHE;
9361 	ipid->ipid_addr_offset = sizeof (ipid_t);
9362 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9363 	/*
9364 	 * Note: in the case of source routing we want to blow away the
9365 	 * route to the first source route hop.
9366 	 */
9367 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9368 	    sizeof (tcp->tcp_ipha->ipha_dst));
9369 
9370 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9371 }
9372 
9373 /* Unlink and return any mblk that looks like it contains an ire */
9374 static mblk_t *
9375 tcp_ire_mp(mblk_t *mp)
9376 {
9377 	mblk_t	*prev_mp;
9378 
9379 	for (;;) {
9380 		prev_mp = mp;
9381 		mp = mp->b_cont;
9382 		if (mp == NULL)
9383 			break;
9384 		switch (DB_TYPE(mp)) {
9385 		case IRE_DB_TYPE:
9386 		case IRE_DB_REQ_TYPE:
9387 			if (prev_mp != NULL)
9388 				prev_mp->b_cont = mp->b_cont;
9389 			mp->b_cont = NULL;
9390 			return (mp);
9391 		default:
9392 			break;
9393 		}
9394 	}
9395 	return (mp);
9396 }
9397 
9398 /*
9399  * Timer callback routine for keepalive probe.  We do a fake resend of
9400  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9401  * check to see if we have heard anything from the other end for the last
9402  * RTO period.  If we have, set the timer to expire for another
9403  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9404  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9405  * the timeout if we have not heard from the other side.  If for more than
9406  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9407  * kill the connection unless the keepalive abort threshold is 0.  In
9408  * that case, we will probe "forever."
9409  */
9410 static void
9411 tcp_keepalive_killer(void *arg)
9412 {
9413 	mblk_t	*mp;
9414 	conn_t	*connp = (conn_t *)arg;
9415 	tcp_t  	*tcp = connp->conn_tcp;
9416 	int32_t	firetime;
9417 	int32_t	idletime;
9418 	int32_t	ka_intrvl;
9419 
9420 	tcp->tcp_ka_tid = 0;
9421 
9422 	if (tcp->tcp_fused)
9423 		return;
9424 
9425 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
9426 	ka_intrvl = tcp->tcp_ka_interval;
9427 
9428 	/*
9429 	 * Keepalive probe should only be sent if the application has not
9430 	 * done a close on the connection.
9431 	 */
9432 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9433 		return;
9434 	}
9435 	/* Timer fired too early, restart it. */
9436 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9437 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9438 		    MSEC_TO_TICK(ka_intrvl));
9439 		return;
9440 	}
9441 
9442 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9443 	/*
9444 	 * If we have not heard from the other side for a long
9445 	 * time, kill the connection unless the keepalive abort
9446 	 * threshold is 0.  In that case, we will probe "forever."
9447 	 */
9448 	if (tcp->tcp_ka_abort_thres != 0 &&
9449 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9450 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
9451 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9452 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9453 		return;
9454 	}
9455 
9456 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9457 	    idletime >= ka_intrvl) {
9458 		/* Fake resend of last ACKed byte. */
9459 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9460 
9461 		if (mp1 != NULL) {
9462 			*mp1->b_wptr++ = '\0';
9463 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9464 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9465 			freeb(mp1);
9466 			/*
9467 			 * if allocation failed, fall through to start the
9468 			 * timer back.
9469 			 */
9470 			if (mp != NULL) {
9471 				TCP_RECORD_TRACE(tcp, mp,
9472 				    TCP_TRACE_SEND_PKT);
9473 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9474 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
9475 				if (tcp->tcp_ka_last_intrvl != 0) {
9476 					/*
9477 					 * We should probe again at least
9478 					 * in ka_intrvl, but not more than
9479 					 * tcp_rexmit_interval_max.
9480 					 */
9481 					firetime = MIN(ka_intrvl - 1,
9482 					    tcp->tcp_ka_last_intrvl << 1);
9483 					if (firetime > tcp_rexmit_interval_max)
9484 						firetime =
9485 						    tcp_rexmit_interval_max;
9486 				} else {
9487 					firetime = tcp->tcp_rto;
9488 				}
9489 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9490 				    tcp_keepalive_killer,
9491 				    MSEC_TO_TICK(firetime));
9492 				tcp->tcp_ka_last_intrvl = firetime;
9493 				return;
9494 			}
9495 		}
9496 	} else {
9497 		tcp->tcp_ka_last_intrvl = 0;
9498 	}
9499 
9500 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9501 	if ((firetime = ka_intrvl - idletime) < 0) {
9502 		firetime = ka_intrvl;
9503 	}
9504 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9505 	    MSEC_TO_TICK(firetime));
9506 }
9507 
9508 static int
9509 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9510 {
9511 	queue_t	*q = tcp->tcp_rq;
9512 	int32_t	mss = tcp->tcp_mss;
9513 	int	maxpsz;
9514 
9515 	if (TCP_IS_DETACHED(tcp))
9516 		return (mss);
9517 
9518 	if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
9519 		/*
9520 		 * Set the sd_qn_maxpsz according to the socket send buffer
9521 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9522 		 * instruct the stream head to copyin user data into contiguous
9523 		 * kernel-allocated buffers without breaking it up into smaller
9524 		 * chunks.  We round up the buffer size to the nearest SMSS.
9525 		 */
9526 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9527 		mss = INFPSZ;
9528 	} else {
9529 		/*
9530 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9531 		 * (and a multiple of the mss).  This instructs the stream
9532 		 * head to break down larger than SMSS writes into SMSS-
9533 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9534 		 */
9535 		maxpsz = tcp->tcp_maxpsz * mss;
9536 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9537 			maxpsz = tcp->tcp_xmit_hiwater/2;
9538 			/* Round up to nearest mss */
9539 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9540 		}
9541 	}
9542 	(void) setmaxps(q, maxpsz);
9543 	tcp->tcp_wq->q_maxpsz = maxpsz;
9544 
9545 	if (set_maxblk)
9546 		(void) mi_set_sth_maxblk(q, mss);
9547 
9548 	if (tcp->tcp_loopback)
9549 		(void) mi_set_sth_copyopt(tcp->tcp_rq, COPYCACHED);
9550 
9551 	return (mss);
9552 }
9553 
9554 /*
9555  * Extract option values from a tcp header.  We put any found values into the
9556  * tcpopt struct and return a bitmask saying which options were found.
9557  */
9558 static int
9559 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9560 {
9561 	uchar_t		*endp;
9562 	int		len;
9563 	uint32_t	mss;
9564 	uchar_t		*up = (uchar_t *)tcph;
9565 	int		found = 0;
9566 	int32_t		sack_len;
9567 	tcp_seq		sack_begin, sack_end;
9568 	tcp_t		*tcp;
9569 
9570 	endp = up + TCP_HDR_LENGTH(tcph);
9571 	up += TCP_MIN_HEADER_LENGTH;
9572 	while (up < endp) {
9573 		len = endp - up;
9574 		switch (*up) {
9575 		case TCPOPT_EOL:
9576 			break;
9577 
9578 		case TCPOPT_NOP:
9579 			up++;
9580 			continue;
9581 
9582 		case TCPOPT_MAXSEG:
9583 			if (len < TCPOPT_MAXSEG_LEN ||
9584 			    up[1] != TCPOPT_MAXSEG_LEN)
9585 				break;
9586 
9587 			mss = BE16_TO_U16(up+2);
9588 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9589 			tcpopt->tcp_opt_mss = mss;
9590 			found |= TCP_OPT_MSS_PRESENT;
9591 
9592 			up += TCPOPT_MAXSEG_LEN;
9593 			continue;
9594 
9595 		case TCPOPT_WSCALE:
9596 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9597 				break;
9598 
9599 			if (up[2] > TCP_MAX_WINSHIFT)
9600 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9601 			else
9602 				tcpopt->tcp_opt_wscale = up[2];
9603 			found |= TCP_OPT_WSCALE_PRESENT;
9604 
9605 			up += TCPOPT_WS_LEN;
9606 			continue;
9607 
9608 		case TCPOPT_SACK_PERMITTED:
9609 			if (len < TCPOPT_SACK_OK_LEN ||
9610 			    up[1] != TCPOPT_SACK_OK_LEN)
9611 				break;
9612 			found |= TCP_OPT_SACK_OK_PRESENT;
9613 			up += TCPOPT_SACK_OK_LEN;
9614 			continue;
9615 
9616 		case TCPOPT_SACK:
9617 			if (len <= 2 || up[1] <= 2 || len < up[1])
9618 				break;
9619 
9620 			/* If TCP is not interested in SACK blks... */
9621 			if ((tcp = tcpopt->tcp) == NULL) {
9622 				up += up[1];
9623 				continue;
9624 			}
9625 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9626 			up += TCPOPT_HEADER_LEN;
9627 
9628 			/*
9629 			 * If the list is empty, allocate one and assume
9630 			 * nothing is sack'ed.
9631 			 */
9632 			ASSERT(tcp->tcp_sack_info != NULL);
9633 			if (tcp->tcp_notsack_list == NULL) {
9634 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9635 				    tcp->tcp_suna, tcp->tcp_snxt,
9636 				    &(tcp->tcp_num_notsack_blk),
9637 				    &(tcp->tcp_cnt_notsack_list));
9638 
9639 				/*
9640 				 * Make sure tcp_notsack_list is not NULL.
9641 				 * This happens when kmem_alloc(KM_NOSLEEP)
9642 				 * returns NULL.
9643 				 */
9644 				if (tcp->tcp_notsack_list == NULL) {
9645 					up += sack_len;
9646 					continue;
9647 				}
9648 				tcp->tcp_fack = tcp->tcp_suna;
9649 			}
9650 
9651 			while (sack_len > 0) {
9652 				if (up + 8 > endp) {
9653 					up = endp;
9654 					break;
9655 				}
9656 				sack_begin = BE32_TO_U32(up);
9657 				up += 4;
9658 				sack_end = BE32_TO_U32(up);
9659 				up += 4;
9660 				sack_len -= 8;
9661 				/*
9662 				 * Bounds checking.  Make sure the SACK
9663 				 * info is within tcp_suna and tcp_snxt.
9664 				 * If this SACK blk is out of bound, ignore
9665 				 * it but continue to parse the following
9666 				 * blks.
9667 				 */
9668 				if (SEQ_LEQ(sack_end, sack_begin) ||
9669 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9670 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9671 					continue;
9672 				}
9673 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9674 				    sack_begin, sack_end,
9675 				    &(tcp->tcp_num_notsack_blk),
9676 				    &(tcp->tcp_cnt_notsack_list));
9677 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9678 					tcp->tcp_fack = sack_end;
9679 				}
9680 			}
9681 			found |= TCP_OPT_SACK_PRESENT;
9682 			continue;
9683 
9684 		case TCPOPT_TSTAMP:
9685 			if (len < TCPOPT_TSTAMP_LEN ||
9686 			    up[1] != TCPOPT_TSTAMP_LEN)
9687 				break;
9688 
9689 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9690 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9691 
9692 			found |= TCP_OPT_TSTAMP_PRESENT;
9693 
9694 			up += TCPOPT_TSTAMP_LEN;
9695 			continue;
9696 
9697 		default:
9698 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9699 				break;
9700 			up += up[1];
9701 			continue;
9702 		}
9703 		break;
9704 	}
9705 	return (found);
9706 }
9707 
9708 /*
9709  * Set the mss associated with a particular tcp based on its current value,
9710  * and a new one passed in. Observe minimums and maximums, and reset
9711  * other state variables that we want to view as multiples of mss.
9712  *
9713  * This function is called in various places mainly because
9714  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9715  *    other side's SYN/SYN-ACK packet arrives.
9716  * 2) PMTUd may get us a new MSS.
9717  * 3) If the other side stops sending us timestamp option, we need to
9718  *    increase the MSS size to use the extra bytes available.
9719  */
9720 static void
9721 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9722 {
9723 	uint32_t	mss_max;
9724 
9725 	if (tcp->tcp_ipversion == IPV4_VERSION)
9726 		mss_max = tcp_mss_max_ipv4;
9727 	else
9728 		mss_max = tcp_mss_max_ipv6;
9729 
9730 	if (mss < tcp_mss_min)
9731 		mss = tcp_mss_min;
9732 	if (mss > mss_max)
9733 		mss = mss_max;
9734 	/*
9735 	 * Unless naglim has been set by our client to
9736 	 * a non-mss value, force naglim to track mss.
9737 	 * This can help to aggregate small writes.
9738 	 */
9739 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9740 		tcp->tcp_naglim = mss;
9741 	/*
9742 	 * TCP should be able to buffer at least 4 MSS data for obvious
9743 	 * performance reason.
9744 	 */
9745 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9746 		tcp->tcp_xmit_hiwater = mss << 2;
9747 
9748 	/*
9749 	 * Check if we need to apply the tcp_init_cwnd here.  If
9750 	 * it is set and the MSS gets bigger (should not happen
9751 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9752 	 * The new tcp_cwnd should not get bigger.
9753 	 */
9754 	if (tcp->tcp_init_cwnd == 0) {
9755 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9756 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9757 	} else {
9758 		if (tcp->tcp_mss < mss) {
9759 			tcp->tcp_cwnd = MAX(1,
9760 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9761 		} else {
9762 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9763 		}
9764 	}
9765 	tcp->tcp_mss = mss;
9766 	tcp->tcp_cwnd_cnt = 0;
9767 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9768 }
9769 
9770 static int
9771 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9772 {
9773 	tcp_t		*tcp = NULL;
9774 	conn_t		*connp;
9775 	int		err;
9776 	dev_t		conn_dev;
9777 	zoneid_t	zoneid = getzoneid();
9778 
9779 	if (q->q_ptr != NULL)
9780 		return (0);
9781 
9782 	if (sflag == MODOPEN) {
9783 		/*
9784 		 * This is a special case. The purpose of a modopen
9785 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9786 		 * through for MIB browsers. Everything else is failed.
9787 		 */
9788 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9789 
9790 		if (connp == NULL)
9791 			return (ENOMEM);
9792 
9793 		connp->conn_flags |= IPCL_TCPMOD;
9794 		connp->conn_cred = credp;
9795 		connp->conn_zoneid = zoneid;
9796 		q->q_ptr = WR(q)->q_ptr = connp;
9797 		crhold(credp);
9798 		q->q_qinfo = &tcp_mod_rinit;
9799 		WR(q)->q_qinfo = &tcp_mod_winit;
9800 		qprocson(q);
9801 		return (0);
9802 	}
9803 
9804 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9805 		return (EBUSY);
9806 
9807 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9808 
9809 	if (flag & SO_ACCEPTOR) {
9810 		q->q_qinfo = &tcp_acceptor_rinit;
9811 		q->q_ptr = (void *)conn_dev;
9812 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9813 		WR(q)->q_ptr = (void *)conn_dev;
9814 		qprocson(q);
9815 		return (0);
9816 	}
9817 
9818 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9819 	if (connp == NULL) {
9820 		inet_minor_free(ip_minor_arena, conn_dev);
9821 		q->q_ptr = NULL;
9822 		return (ENOSR);
9823 	}
9824 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9825 	tcp = connp->conn_tcp;
9826 
9827 	q->q_ptr = WR(q)->q_ptr = connp;
9828 	if (getmajor(*devp) == TCP6_MAJ) {
9829 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9830 		connp->conn_send = ip_output_v6;
9831 		connp->conn_af_isv6 = B_TRUE;
9832 		connp->conn_pkt_isv6 = B_TRUE;
9833 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9834 		tcp->tcp_ipversion = IPV6_VERSION;
9835 		tcp->tcp_family = AF_INET6;
9836 		tcp->tcp_mss = tcp_mss_def_ipv6;
9837 	} else {
9838 		connp->conn_flags |= IPCL_TCP4;
9839 		connp->conn_send = ip_output;
9840 		connp->conn_af_isv6 = B_FALSE;
9841 		connp->conn_pkt_isv6 = B_FALSE;
9842 		tcp->tcp_ipversion = IPV4_VERSION;
9843 		tcp->tcp_family = AF_INET;
9844 		tcp->tcp_mss = tcp_mss_def_ipv4;
9845 	}
9846 
9847 	/*
9848 	 * TCP keeps a copy of cred for cache locality reasons but
9849 	 * we put a reference only once. If connp->conn_cred
9850 	 * becomes invalid, tcp_cred should also be set to NULL.
9851 	 */
9852 	tcp->tcp_cred = connp->conn_cred = credp;
9853 	crhold(connp->conn_cred);
9854 	tcp->tcp_cpid = curproc->p_pid;
9855 	connp->conn_zoneid = zoneid;
9856 
9857 	connp->conn_dev = conn_dev;
9858 
9859 	ASSERT(q->q_qinfo == &tcp_rinit);
9860 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9861 
9862 	if (flag & SO_SOCKSTR) {
9863 		/*
9864 		 * No need to insert a socket in tcp acceptor hash.
9865 		 * If it was a socket acceptor stream, we dealt with
9866 		 * it above. A socket listener can never accept a
9867 		 * connection and doesn't need acceptor_id.
9868 		 */
9869 		connp->conn_flags |= IPCL_SOCKET;
9870 		tcp->tcp_issocket = 1;
9871 
9872 		WR(q)->q_qinfo = &tcp_sock_winit;
9873 	} else {
9874 #ifdef	_ILP32
9875 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9876 #else
9877 		tcp->tcp_acceptor_id = conn_dev;
9878 #endif	/* _ILP32 */
9879 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9880 	}
9881 
9882 	if (tcp_trace)
9883 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9884 
9885 	err = tcp_init(tcp, q);
9886 	if (err != 0) {
9887 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9888 		tcp_acceptor_hash_remove(tcp);
9889 		CONN_DEC_REF(connp);
9890 		q->q_ptr = WR(q)->q_ptr = NULL;
9891 		return (err);
9892 	}
9893 
9894 	RD(q)->q_hiwat = tcp_recv_hiwat;
9895 	tcp->tcp_rwnd = tcp_recv_hiwat;
9896 
9897 	/* Non-zero default values */
9898 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9899 	/*
9900 	 * Put the ref for TCP. Ref for IP was already put
9901 	 * by ipcl_conn_create. Also Make the conn_t globally
9902 	 * visible to walkers
9903 	 */
9904 	mutex_enter(&connp->conn_lock);
9905 	CONN_INC_REF_LOCKED(connp);
9906 	ASSERT(connp->conn_ref == 2);
9907 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9908 	mutex_exit(&connp->conn_lock);
9909 
9910 	qprocson(q);
9911 	return (0);
9912 }
9913 
9914 /*
9915  * Some TCP options can be "set" by requesting them in the option
9916  * buffer. This is needed for XTI feature test though we do not
9917  * allow it in general. We interpret that this mechanism is more
9918  * applicable to OSI protocols and need not be allowed in general.
9919  * This routine filters out options for which it is not allowed (most)
9920  * and lets through those (few) for which it is. [ The XTI interface
9921  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9922  * ever implemented will have to be allowed here ].
9923  */
9924 static boolean_t
9925 tcp_allow_connopt_set(int level, int name)
9926 {
9927 
9928 	switch (level) {
9929 	case IPPROTO_TCP:
9930 		switch (name) {
9931 		case TCP_NODELAY:
9932 			return (B_TRUE);
9933 		default:
9934 			return (B_FALSE);
9935 		}
9936 		/*NOTREACHED*/
9937 	default:
9938 		return (B_FALSE);
9939 	}
9940 	/*NOTREACHED*/
9941 }
9942 
9943 /*
9944  * This routine gets default values of certain options whose default
9945  * values are maintained by protocol specific code
9946  */
9947 /* ARGSUSED */
9948 int
9949 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9950 {
9951 	int32_t	*i1 = (int32_t *)ptr;
9952 
9953 	switch (level) {
9954 	case IPPROTO_TCP:
9955 		switch (name) {
9956 		case TCP_NOTIFY_THRESHOLD:
9957 			*i1 = tcp_ip_notify_interval;
9958 			break;
9959 		case TCP_ABORT_THRESHOLD:
9960 			*i1 = tcp_ip_abort_interval;
9961 			break;
9962 		case TCP_CONN_NOTIFY_THRESHOLD:
9963 			*i1 = tcp_ip_notify_cinterval;
9964 			break;
9965 		case TCP_CONN_ABORT_THRESHOLD:
9966 			*i1 = tcp_ip_abort_cinterval;
9967 			break;
9968 		default:
9969 			return (-1);
9970 		}
9971 		break;
9972 	case IPPROTO_IP:
9973 		switch (name) {
9974 		case IP_TTL:
9975 			*i1 = tcp_ipv4_ttl;
9976 			break;
9977 		default:
9978 			return (-1);
9979 		}
9980 		break;
9981 	case IPPROTO_IPV6:
9982 		switch (name) {
9983 		case IPV6_UNICAST_HOPS:
9984 			*i1 = tcp_ipv6_hoplimit;
9985 			break;
9986 		default:
9987 			return (-1);
9988 		}
9989 		break;
9990 	default:
9991 		return (-1);
9992 	}
9993 	return (sizeof (int));
9994 }
9995 
9996 
9997 /*
9998  * TCP routine to get the values of options.
9999  */
10000 int
10001 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
10002 {
10003 	int		*i1 = (int *)ptr;
10004 	conn_t		*connp = Q_TO_CONN(q);
10005 	tcp_t		*tcp = connp->conn_tcp;
10006 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
10007 
10008 	switch (level) {
10009 	case SOL_SOCKET:
10010 		switch (name) {
10011 		case SO_LINGER:	{
10012 			struct linger *lgr = (struct linger *)ptr;
10013 
10014 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
10015 			lgr->l_linger = tcp->tcp_lingertime;
10016 			}
10017 			return (sizeof (struct linger));
10018 		case SO_DEBUG:
10019 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
10020 			break;
10021 		case SO_KEEPALIVE:
10022 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
10023 			break;
10024 		case SO_DONTROUTE:
10025 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
10026 			break;
10027 		case SO_USELOOPBACK:
10028 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
10029 			break;
10030 		case SO_BROADCAST:
10031 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
10032 			break;
10033 		case SO_REUSEADDR:
10034 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
10035 			break;
10036 		case SO_OOBINLINE:
10037 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
10038 			break;
10039 		case SO_DGRAM_ERRIND:
10040 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
10041 			break;
10042 		case SO_TYPE:
10043 			*i1 = SOCK_STREAM;
10044 			break;
10045 		case SO_SNDBUF:
10046 			*i1 = tcp->tcp_xmit_hiwater;
10047 			break;
10048 		case SO_RCVBUF:
10049 			*i1 = RD(q)->q_hiwat;
10050 			break;
10051 		case SO_SND_COPYAVOID:
10052 			*i1 = tcp->tcp_snd_zcopy_on ?
10053 			    SO_SND_COPYAVOID : 0;
10054 			break;
10055 		default:
10056 			return (-1);
10057 		}
10058 		break;
10059 	case IPPROTO_TCP:
10060 		switch (name) {
10061 		case TCP_NODELAY:
10062 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10063 			break;
10064 		case TCP_MAXSEG:
10065 			*i1 = tcp->tcp_mss;
10066 			break;
10067 		case TCP_NOTIFY_THRESHOLD:
10068 			*i1 = (int)tcp->tcp_first_timer_threshold;
10069 			break;
10070 		case TCP_ABORT_THRESHOLD:
10071 			*i1 = tcp->tcp_second_timer_threshold;
10072 			break;
10073 		case TCP_CONN_NOTIFY_THRESHOLD:
10074 			*i1 = tcp->tcp_first_ctimer_threshold;
10075 			break;
10076 		case TCP_CONN_ABORT_THRESHOLD:
10077 			*i1 = tcp->tcp_second_ctimer_threshold;
10078 			break;
10079 		case TCP_RECVDSTADDR:
10080 			*i1 = tcp->tcp_recvdstaddr;
10081 			break;
10082 		case TCP_ANONPRIVBIND:
10083 			*i1 = tcp->tcp_anon_priv_bind;
10084 			break;
10085 		case TCP_EXCLBIND:
10086 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10087 			break;
10088 		case TCP_INIT_CWND:
10089 			*i1 = tcp->tcp_init_cwnd;
10090 			break;
10091 		case TCP_KEEPALIVE_THRESHOLD:
10092 			*i1 = tcp->tcp_ka_interval;
10093 			break;
10094 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10095 			*i1 = tcp->tcp_ka_abort_thres;
10096 			break;
10097 		case TCP_CORK:
10098 			*i1 = tcp->tcp_cork;
10099 			break;
10100 		default:
10101 			return (-1);
10102 		}
10103 		break;
10104 	case IPPROTO_IP:
10105 		if (tcp->tcp_family != AF_INET)
10106 			return (-1);
10107 		switch (name) {
10108 		case IP_OPTIONS:
10109 		case T_IP_OPTIONS: {
10110 			/*
10111 			 * This is compatible with BSD in that in only return
10112 			 * the reverse source route with the final destination
10113 			 * as the last entry. The first 4 bytes of the option
10114 			 * will contain the final destination.
10115 			 */
10116 			char	*opt_ptr;
10117 			int	opt_len;
10118 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10119 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
10120 			/* Caller ensures enough space */
10121 			if (opt_len > 0) {
10122 				/*
10123 				 * TODO: Do we have to handle getsockopt on an
10124 				 * initiator as well?
10125 				 */
10126 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
10127 			}
10128 			return (0);
10129 			}
10130 		case IP_TOS:
10131 		case T_IP_TOS:
10132 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10133 			break;
10134 		case IP_TTL:
10135 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10136 			break;
10137 		default:
10138 			return (-1);
10139 		}
10140 		break;
10141 	case IPPROTO_IPV6:
10142 		/*
10143 		 * IPPROTO_IPV6 options are only supported for sockets
10144 		 * that are using IPv6 on the wire.
10145 		 */
10146 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10147 			return (-1);
10148 		}
10149 		switch (name) {
10150 		case IPV6_UNICAST_HOPS:
10151 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10152 			break;	/* goto sizeof (int) option return */
10153 		case IPV6_BOUND_IF:
10154 			/* Zero if not set */
10155 			*i1 = tcp->tcp_bound_if;
10156 			break;	/* goto sizeof (int) option return */
10157 		case IPV6_RECVPKTINFO:
10158 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10159 				*i1 = 1;
10160 			else
10161 				*i1 = 0;
10162 			break;	/* goto sizeof (int) option return */
10163 		case IPV6_RECVTCLASS:
10164 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10165 				*i1 = 1;
10166 			else
10167 				*i1 = 0;
10168 			break;	/* goto sizeof (int) option return */
10169 		case IPV6_RECVHOPLIMIT:
10170 			if (tcp->tcp_ipv6_recvancillary &
10171 			    TCP_IPV6_RECVHOPLIMIT)
10172 				*i1 = 1;
10173 			else
10174 				*i1 = 0;
10175 			break;	/* goto sizeof (int) option return */
10176 		case IPV6_RECVHOPOPTS:
10177 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10178 				*i1 = 1;
10179 			else
10180 				*i1 = 0;
10181 			break;	/* goto sizeof (int) option return */
10182 		case IPV6_RECVDSTOPTS:
10183 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10184 				*i1 = 1;
10185 			else
10186 				*i1 = 0;
10187 			break;	/* goto sizeof (int) option return */
10188 		case _OLD_IPV6_RECVDSTOPTS:
10189 			if (tcp->tcp_ipv6_recvancillary &
10190 			    TCP_OLD_IPV6_RECVDSTOPTS)
10191 				*i1 = 1;
10192 			else
10193 				*i1 = 0;
10194 			break;	/* goto sizeof (int) option return */
10195 		case IPV6_RECVRTHDR:
10196 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10197 				*i1 = 1;
10198 			else
10199 				*i1 = 0;
10200 			break;	/* goto sizeof (int) option return */
10201 		case IPV6_RECVRTHDRDSTOPTS:
10202 			if (tcp->tcp_ipv6_recvancillary &
10203 			    TCP_IPV6_RECVRTDSTOPTS)
10204 				*i1 = 1;
10205 			else
10206 				*i1 = 0;
10207 			break;	/* goto sizeof (int) option return */
10208 		case IPV6_PKTINFO: {
10209 			/* XXX assumes that caller has room for max size! */
10210 			struct in6_pktinfo *pkti;
10211 
10212 			pkti = (struct in6_pktinfo *)ptr;
10213 			if (ipp->ipp_fields & IPPF_IFINDEX)
10214 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10215 			else
10216 				pkti->ipi6_ifindex = 0;
10217 			if (ipp->ipp_fields & IPPF_ADDR)
10218 				pkti->ipi6_addr = ipp->ipp_addr;
10219 			else
10220 				pkti->ipi6_addr = ipv6_all_zeros;
10221 			return (sizeof (struct in6_pktinfo));
10222 		}
10223 		case IPV6_TCLASS:
10224 			if (ipp->ipp_fields & IPPF_TCLASS)
10225 				*i1 = ipp->ipp_tclass;
10226 			else
10227 				*i1 = IPV6_FLOW_TCLASS(
10228 				    IPV6_DEFAULT_VERS_AND_FLOW);
10229 			break;	/* goto sizeof (int) option return */
10230 		case IPV6_NEXTHOP: {
10231 			sin6_t *sin6 = (sin6_t *)ptr;
10232 
10233 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10234 				return (0);
10235 			*sin6 = sin6_null;
10236 			sin6->sin6_family = AF_INET6;
10237 			sin6->sin6_addr = ipp->ipp_nexthop;
10238 			return (sizeof (sin6_t));
10239 		}
10240 		case IPV6_HOPOPTS:
10241 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10242 				return (0);
10243 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
10244 			return (ipp->ipp_hopoptslen);
10245 		case IPV6_RTHDRDSTOPTS:
10246 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10247 				return (0);
10248 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10249 			return (ipp->ipp_rtdstoptslen);
10250 		case IPV6_RTHDR:
10251 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10252 				return (0);
10253 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10254 			return (ipp->ipp_rthdrlen);
10255 		case IPV6_DSTOPTS:
10256 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10257 				return (0);
10258 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10259 			return (ipp->ipp_dstoptslen);
10260 		case IPV6_SRC_PREFERENCES:
10261 			return (ip6_get_src_preferences(connp,
10262 			    (uint32_t *)ptr));
10263 		case IPV6_PATHMTU: {
10264 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10265 
10266 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10267 				return (-1);
10268 
10269 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10270 				connp->conn_fport, mtuinfo));
10271 		}
10272 		default:
10273 			return (-1);
10274 		}
10275 		break;
10276 	default:
10277 		return (-1);
10278 	}
10279 	return (sizeof (int));
10280 }
10281 
10282 /*
10283  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10284  * Parameters are assumed to be verified by the caller.
10285  */
10286 /* ARGSUSED */
10287 int
10288 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10289     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10290     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10291 {
10292 	tcp_t	*tcp = Q_TO_TCP(q);
10293 	int	*i1 = (int *)invalp;
10294 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10295 	boolean_t checkonly;
10296 	int	reterr;
10297 
10298 	switch (optset_context) {
10299 	case SETFN_OPTCOM_CHECKONLY:
10300 		checkonly = B_TRUE;
10301 		/*
10302 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10303 		 * inlen != 0 implies value supplied and
10304 		 * 	we have to "pretend" to set it.
10305 		 * inlen == 0 implies that there is no
10306 		 * 	value part in T_CHECK request and just validation
10307 		 * done elsewhere should be enough, we just return here.
10308 		 */
10309 		if (inlen == 0) {
10310 			*outlenp = 0;
10311 			return (0);
10312 		}
10313 		break;
10314 	case SETFN_OPTCOM_NEGOTIATE:
10315 		checkonly = B_FALSE;
10316 		break;
10317 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10318 	case SETFN_CONN_NEGOTIATE:
10319 		checkonly = B_FALSE;
10320 		/*
10321 		 * Negotiating local and "association-related" options
10322 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10323 		 * primitives is allowed by XTI, but we choose
10324 		 * to not implement this style negotiation for Internet
10325 		 * protocols (We interpret it is a must for OSI world but
10326 		 * optional for Internet protocols) for all options.
10327 		 * [ Will do only for the few options that enable test
10328 		 * suites that our XTI implementation of this feature
10329 		 * works for transports that do allow it ]
10330 		 */
10331 		if (!tcp_allow_connopt_set(level, name)) {
10332 			*outlenp = 0;
10333 			return (EINVAL);
10334 		}
10335 		break;
10336 	default:
10337 		/*
10338 		 * We should never get here
10339 		 */
10340 		*outlenp = 0;
10341 		return (EINVAL);
10342 	}
10343 
10344 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10345 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10346 
10347 	/*
10348 	 * For TCP, we should have no ancillary data sent down
10349 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10350 	 * has to be zero.
10351 	 */
10352 	ASSERT(thisdg_attrs == NULL);
10353 
10354 	/*
10355 	 * For fixed length options, no sanity check
10356 	 * of passed in length is done. It is assumed *_optcom_req()
10357 	 * routines do the right thing.
10358 	 */
10359 
10360 	switch (level) {
10361 	case SOL_SOCKET:
10362 		switch (name) {
10363 		case SO_LINGER: {
10364 			struct linger *lgr = (struct linger *)invalp;
10365 
10366 			if (!checkonly) {
10367 				if (lgr->l_onoff) {
10368 					tcp->tcp_linger = 1;
10369 					tcp->tcp_lingertime = lgr->l_linger;
10370 				} else {
10371 					tcp->tcp_linger = 0;
10372 					tcp->tcp_lingertime = 0;
10373 				}
10374 				/* struct copy */
10375 				*(struct linger *)outvalp = *lgr;
10376 			} else {
10377 				if (!lgr->l_onoff) {
10378 				    ((struct linger *)outvalp)->l_onoff = 0;
10379 				    ((struct linger *)outvalp)->l_linger = 0;
10380 				} else {
10381 				    /* struct copy */
10382 				    *(struct linger *)outvalp = *lgr;
10383 				}
10384 			}
10385 			*outlenp = sizeof (struct linger);
10386 			return (0);
10387 		}
10388 		case SO_DEBUG:
10389 			if (!checkonly)
10390 				tcp->tcp_debug = onoff;
10391 			break;
10392 		case SO_KEEPALIVE:
10393 			if (checkonly) {
10394 				/* T_CHECK case */
10395 				break;
10396 			}
10397 
10398 			if (!onoff) {
10399 				if (tcp->tcp_ka_enabled) {
10400 					if (tcp->tcp_ka_tid != 0) {
10401 						(void) TCP_TIMER_CANCEL(tcp,
10402 						    tcp->tcp_ka_tid);
10403 						tcp->tcp_ka_tid = 0;
10404 					}
10405 					tcp->tcp_ka_enabled = 0;
10406 				}
10407 				break;
10408 			}
10409 			if (!tcp->tcp_ka_enabled) {
10410 				/* Crank up the keepalive timer */
10411 				tcp->tcp_ka_last_intrvl = 0;
10412 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10413 				    tcp_keepalive_killer,
10414 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10415 				tcp->tcp_ka_enabled = 1;
10416 			}
10417 			break;
10418 		case SO_DONTROUTE:
10419 			/*
10420 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
10421 			 * only of interest to IP.  We track them here only so
10422 			 * that we can report their current value.
10423 			 */
10424 			if (!checkonly) {
10425 				tcp->tcp_dontroute = onoff;
10426 				tcp->tcp_connp->conn_dontroute = onoff;
10427 			}
10428 			break;
10429 		case SO_USELOOPBACK:
10430 			if (!checkonly) {
10431 				tcp->tcp_useloopback = onoff;
10432 				tcp->tcp_connp->conn_loopback = onoff;
10433 			}
10434 			break;
10435 		case SO_BROADCAST:
10436 			if (!checkonly) {
10437 				tcp->tcp_broadcast = onoff;
10438 				tcp->tcp_connp->conn_broadcast = onoff;
10439 			}
10440 			break;
10441 		case SO_REUSEADDR:
10442 			if (!checkonly) {
10443 				tcp->tcp_reuseaddr = onoff;
10444 				tcp->tcp_connp->conn_reuseaddr = onoff;
10445 			}
10446 			break;
10447 		case SO_OOBINLINE:
10448 			if (!checkonly)
10449 				tcp->tcp_oobinline = onoff;
10450 			break;
10451 		case SO_DGRAM_ERRIND:
10452 			if (!checkonly)
10453 				tcp->tcp_dgram_errind = onoff;
10454 			break;
10455 		case SO_SNDBUF:
10456 			if (*i1 > tcp_max_buf) {
10457 				*outlenp = 0;
10458 				return (ENOBUFS);
10459 			}
10460 			if (!checkonly) {
10461 				tcp->tcp_xmit_hiwater = *i1;
10462 				if (tcp_snd_lowat_fraction != 0)
10463 					tcp->tcp_xmit_lowater =
10464 					    tcp->tcp_xmit_hiwater /
10465 					    tcp_snd_lowat_fraction;
10466 				(void) tcp_maxpsz_set(tcp, B_TRUE);
10467 				/*
10468 				 * If we are flow-controlled, recheck the
10469 				 * condition. There are apps that increase
10470 				 * SO_SNDBUF size when flow-controlled
10471 				 * (EWOULDBLOCK), and expect the flow control
10472 				 * condition to be lifted right away.
10473 				 */
10474 				if (tcp->tcp_flow_stopped &&
10475 				    tcp->tcp_unsent < tcp->tcp_xmit_hiwater) {
10476 					tcp->tcp_flow_stopped = B_FALSE;
10477 					tcp_clrqfull(tcp);
10478 				}
10479 			}
10480 			break;
10481 		case SO_RCVBUF:
10482 			if (*i1 > tcp_max_buf) {
10483 				*outlenp = 0;
10484 				return (ENOBUFS);
10485 			}
10486 			/* Silently ignore zero */
10487 			if (!checkonly && *i1 != 0) {
10488 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10489 				(void) tcp_rwnd_set(tcp, *i1);
10490 			}
10491 			/*
10492 			 * XXX should we return the rwnd here
10493 			 * and tcp_opt_get ?
10494 			 */
10495 			break;
10496 		case SO_SND_COPYAVOID:
10497 			if (!checkonly) {
10498 				/* we only allow enable at most once for now */
10499 				if (tcp->tcp_loopback ||
10500 				    (!tcp->tcp_snd_zcopy_aware &&
10501 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10502 					*outlenp = 0;
10503 					return (EOPNOTSUPP);
10504 				}
10505 				tcp->tcp_snd_zcopy_aware = 1;
10506 			}
10507 			break;
10508 		default:
10509 			*outlenp = 0;
10510 			return (EINVAL);
10511 		}
10512 		break;
10513 	case IPPROTO_TCP:
10514 		switch (name) {
10515 		case TCP_NODELAY:
10516 			if (!checkonly)
10517 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10518 			break;
10519 		case TCP_NOTIFY_THRESHOLD:
10520 			if (!checkonly)
10521 				tcp->tcp_first_timer_threshold = *i1;
10522 			break;
10523 		case TCP_ABORT_THRESHOLD:
10524 			if (!checkonly)
10525 				tcp->tcp_second_timer_threshold = *i1;
10526 			break;
10527 		case TCP_CONN_NOTIFY_THRESHOLD:
10528 			if (!checkonly)
10529 				tcp->tcp_first_ctimer_threshold = *i1;
10530 			break;
10531 		case TCP_CONN_ABORT_THRESHOLD:
10532 			if (!checkonly)
10533 				tcp->tcp_second_ctimer_threshold = *i1;
10534 			break;
10535 		case TCP_RECVDSTADDR:
10536 			if (tcp->tcp_state > TCPS_LISTEN)
10537 				return (EOPNOTSUPP);
10538 			if (!checkonly)
10539 				tcp->tcp_recvdstaddr = onoff;
10540 			break;
10541 		case TCP_ANONPRIVBIND:
10542 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10543 				*outlenp = 0;
10544 				return (reterr);
10545 			}
10546 			if (!checkonly) {
10547 				tcp->tcp_anon_priv_bind = onoff;
10548 			}
10549 			break;
10550 		case TCP_EXCLBIND:
10551 			if (!checkonly)
10552 				tcp->tcp_exclbind = onoff;
10553 			break;	/* goto sizeof (int) option return */
10554 		case TCP_INIT_CWND: {
10555 			uint32_t init_cwnd = *((uint32_t *)invalp);
10556 
10557 			if (checkonly)
10558 				break;
10559 
10560 			/*
10561 			 * Only allow socket with network configuration
10562 			 * privilege to set the initial cwnd to be larger
10563 			 * than allowed by RFC 3390.
10564 			 */
10565 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10566 				tcp->tcp_init_cwnd = init_cwnd;
10567 				break;
10568 			}
10569 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10570 				*outlenp = 0;
10571 				return (reterr);
10572 			}
10573 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10574 				*outlenp = 0;
10575 				return (EINVAL);
10576 			}
10577 			tcp->tcp_init_cwnd = init_cwnd;
10578 			break;
10579 		}
10580 		case TCP_KEEPALIVE_THRESHOLD:
10581 			if (checkonly)
10582 				break;
10583 
10584 			if (*i1 < tcp_keepalive_interval_low ||
10585 			    *i1 > tcp_keepalive_interval_high) {
10586 				*outlenp = 0;
10587 				return (EINVAL);
10588 			}
10589 			if (*i1 != tcp->tcp_ka_interval) {
10590 				tcp->tcp_ka_interval = *i1;
10591 				/*
10592 				 * Check if we need to restart the
10593 				 * keepalive timer.
10594 				 */
10595 				if (tcp->tcp_ka_tid != 0) {
10596 					ASSERT(tcp->tcp_ka_enabled);
10597 					(void) TCP_TIMER_CANCEL(tcp,
10598 					    tcp->tcp_ka_tid);
10599 					tcp->tcp_ka_last_intrvl = 0;
10600 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10601 					    tcp_keepalive_killer,
10602 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10603 				}
10604 			}
10605 			break;
10606 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10607 			if (!checkonly) {
10608 				if (*i1 < tcp_keepalive_abort_interval_low ||
10609 				    *i1 > tcp_keepalive_abort_interval_high) {
10610 					*outlenp = 0;
10611 					return (EINVAL);
10612 				}
10613 				tcp->tcp_ka_abort_thres = *i1;
10614 			}
10615 			break;
10616 		case TCP_CORK:
10617 			if (!checkonly) {
10618 				/*
10619 				 * if tcp->tcp_cork was set and is now
10620 				 * being unset, we have to make sure that
10621 				 * the remaining data gets sent out. Also
10622 				 * unset tcp->tcp_cork so that tcp_wput_data()
10623 				 * can send data even if it is less than mss
10624 				 */
10625 				if (tcp->tcp_cork && onoff == 0 &&
10626 				    tcp->tcp_unsent > 0) {
10627 					tcp->tcp_cork = B_FALSE;
10628 					tcp_wput_data(tcp, NULL, B_FALSE);
10629 				}
10630 				tcp->tcp_cork = onoff;
10631 			}
10632 			break;
10633 		default:
10634 			*outlenp = 0;
10635 			return (EINVAL);
10636 		}
10637 		break;
10638 	case IPPROTO_IP:
10639 		if (tcp->tcp_family != AF_INET) {
10640 			*outlenp = 0;
10641 			return (ENOPROTOOPT);
10642 		}
10643 		switch (name) {
10644 		case IP_OPTIONS:
10645 		case T_IP_OPTIONS:
10646 			reterr = tcp_opt_set_header(tcp, checkonly,
10647 			    invalp, inlen);
10648 			if (reterr) {
10649 				*outlenp = 0;
10650 				return (reterr);
10651 			}
10652 			/* OK return - copy input buffer into output buffer */
10653 			if (invalp != outvalp) {
10654 				/* don't trust bcopy for identical src/dst */
10655 				bcopy(invalp, outvalp, inlen);
10656 			}
10657 			*outlenp = inlen;
10658 			return (0);
10659 		case IP_TOS:
10660 		case T_IP_TOS:
10661 			if (!checkonly) {
10662 				tcp->tcp_ipha->ipha_type_of_service =
10663 				    (uchar_t)*i1;
10664 				tcp->tcp_tos = (uchar_t)*i1;
10665 			}
10666 			break;
10667 		case IP_TTL:
10668 			if (!checkonly) {
10669 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10670 				tcp->tcp_ttl = (uchar_t)*i1;
10671 			}
10672 			break;
10673 		case IP_BOUND_IF:
10674 			/* Handled at the IP level */
10675 			return (-EINVAL);
10676 		case IP_SEC_OPT:
10677 			/*
10678 			 * We should not allow policy setting after
10679 			 * we start listening for connections.
10680 			 */
10681 			if (tcp->tcp_state == TCPS_LISTEN) {
10682 				return (EINVAL);
10683 			} else {
10684 				/* Handled at the IP level */
10685 				return (-EINVAL);
10686 			}
10687 		default:
10688 			*outlenp = 0;
10689 			return (EINVAL);
10690 		}
10691 		break;
10692 	case IPPROTO_IPV6: {
10693 		ip6_pkt_t		*ipp;
10694 
10695 		/*
10696 		 * IPPROTO_IPV6 options are only supported for sockets
10697 		 * that are using IPv6 on the wire.
10698 		 */
10699 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10700 			*outlenp = 0;
10701 			return (ENOPROTOOPT);
10702 		}
10703 		/*
10704 		 * Only sticky options; no ancillary data
10705 		 */
10706 		ASSERT(thisdg_attrs == NULL);
10707 		ipp = &tcp->tcp_sticky_ipp;
10708 
10709 		switch (name) {
10710 		case IPV6_UNICAST_HOPS:
10711 			/* -1 means use default */
10712 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10713 				*outlenp = 0;
10714 				return (EINVAL);
10715 			}
10716 			if (!checkonly) {
10717 				if (*i1 == -1) {
10718 					tcp->tcp_ip6h->ip6_hops =
10719 					    ipp->ipp_unicast_hops =
10720 					    (uint8_t)tcp_ipv6_hoplimit;
10721 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10722 					/* Pass modified value to IP. */
10723 					*i1 = tcp->tcp_ip6h->ip6_hops;
10724 				} else {
10725 					tcp->tcp_ip6h->ip6_hops =
10726 					    ipp->ipp_unicast_hops =
10727 					    (uint8_t)*i1;
10728 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10729 				}
10730 				reterr = tcp_build_hdrs(q, tcp);
10731 				if (reterr != 0)
10732 					return (reterr);
10733 			}
10734 			break;
10735 		case IPV6_BOUND_IF:
10736 			if (!checkonly) {
10737 				int error = 0;
10738 
10739 				tcp->tcp_bound_if = *i1;
10740 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10741 				    B_TRUE, checkonly, level, name, mblk);
10742 				if (error != 0) {
10743 					*outlenp = 0;
10744 					return (error);
10745 				}
10746 			}
10747 			break;
10748 		/*
10749 		 * Set boolean switches for ancillary data delivery
10750 		 */
10751 		case IPV6_RECVPKTINFO:
10752 			if (!checkonly) {
10753 				if (onoff)
10754 					tcp->tcp_ipv6_recvancillary |=
10755 					    TCP_IPV6_RECVPKTINFO;
10756 				else
10757 					tcp->tcp_ipv6_recvancillary &=
10758 					    ~TCP_IPV6_RECVPKTINFO;
10759 				/* Force it to be sent up with the next msg */
10760 				tcp->tcp_recvifindex = 0;
10761 			}
10762 			break;
10763 		case IPV6_RECVTCLASS:
10764 			if (!checkonly) {
10765 				if (onoff)
10766 					tcp->tcp_ipv6_recvancillary |=
10767 					    TCP_IPV6_RECVTCLASS;
10768 				else
10769 					tcp->tcp_ipv6_recvancillary &=
10770 					    ~TCP_IPV6_RECVTCLASS;
10771 			}
10772 			break;
10773 		case IPV6_RECVHOPLIMIT:
10774 			if (!checkonly) {
10775 				if (onoff)
10776 					tcp->tcp_ipv6_recvancillary |=
10777 					    TCP_IPV6_RECVHOPLIMIT;
10778 				else
10779 					tcp->tcp_ipv6_recvancillary &=
10780 					    ~TCP_IPV6_RECVHOPLIMIT;
10781 				/* Force it to be sent up with the next msg */
10782 				tcp->tcp_recvhops = 0xffffffffU;
10783 			}
10784 			break;
10785 		case IPV6_RECVHOPOPTS:
10786 			if (!checkonly) {
10787 				if (onoff)
10788 					tcp->tcp_ipv6_recvancillary |=
10789 					    TCP_IPV6_RECVHOPOPTS;
10790 				else
10791 					tcp->tcp_ipv6_recvancillary &=
10792 					    ~TCP_IPV6_RECVHOPOPTS;
10793 			}
10794 			break;
10795 		case IPV6_RECVDSTOPTS:
10796 			if (!checkonly) {
10797 				if (onoff)
10798 					tcp->tcp_ipv6_recvancillary |=
10799 					    TCP_IPV6_RECVDSTOPTS;
10800 				else
10801 					tcp->tcp_ipv6_recvancillary &=
10802 					    ~TCP_IPV6_RECVDSTOPTS;
10803 			}
10804 			break;
10805 		case _OLD_IPV6_RECVDSTOPTS:
10806 			if (!checkonly) {
10807 				if (onoff)
10808 					tcp->tcp_ipv6_recvancillary |=
10809 					    TCP_OLD_IPV6_RECVDSTOPTS;
10810 				else
10811 					tcp->tcp_ipv6_recvancillary &=
10812 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10813 			}
10814 			break;
10815 		case IPV6_RECVRTHDR:
10816 			if (!checkonly) {
10817 				if (onoff)
10818 					tcp->tcp_ipv6_recvancillary |=
10819 					    TCP_IPV6_RECVRTHDR;
10820 				else
10821 					tcp->tcp_ipv6_recvancillary &=
10822 					    ~TCP_IPV6_RECVRTHDR;
10823 			}
10824 			break;
10825 		case IPV6_RECVRTHDRDSTOPTS:
10826 			if (!checkonly) {
10827 				if (onoff)
10828 					tcp->tcp_ipv6_recvancillary |=
10829 					    TCP_IPV6_RECVRTDSTOPTS;
10830 				else
10831 					tcp->tcp_ipv6_recvancillary &=
10832 					    ~TCP_IPV6_RECVRTDSTOPTS;
10833 			}
10834 			break;
10835 		case IPV6_PKTINFO:
10836 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10837 				return (EINVAL);
10838 			if (checkonly)
10839 				break;
10840 
10841 			if (inlen == 0) {
10842 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10843 			} else {
10844 				struct in6_pktinfo *pkti;
10845 
10846 				pkti = (struct in6_pktinfo *)invalp;
10847 				/*
10848 				 * RFC 3542 states that ipi6_addr must be
10849 				 * the unspecified address when setting the
10850 				 * IPV6_PKTINFO sticky socket option on a
10851 				 * TCP socket.
10852 				 */
10853 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10854 					return (EINVAL);
10855 				/*
10856 				 * ip6_set_pktinfo() validates the source
10857 				 * address and interface index.
10858 				 */
10859 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10860 				    pkti, mblk);
10861 				if (reterr != 0)
10862 					return (reterr);
10863 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10864 				ipp->ipp_addr = pkti->ipi6_addr;
10865 				if (ipp->ipp_ifindex != 0)
10866 					ipp->ipp_fields |= IPPF_IFINDEX;
10867 				else
10868 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10869 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10870 					ipp->ipp_fields |= IPPF_ADDR;
10871 				else
10872 					ipp->ipp_fields &= ~IPPF_ADDR;
10873 			}
10874 			reterr = tcp_build_hdrs(q, tcp);
10875 			if (reterr != 0)
10876 				return (reterr);
10877 			break;
10878 		case IPV6_TCLASS:
10879 			if (inlen != 0 && inlen != sizeof (int))
10880 				return (EINVAL);
10881 			if (checkonly)
10882 				break;
10883 
10884 			if (inlen == 0) {
10885 				ipp->ipp_fields &= ~IPPF_TCLASS;
10886 			} else {
10887 				if (*i1 > 255 || *i1 < -1)
10888 					return (EINVAL);
10889 				if (*i1 == -1) {
10890 					ipp->ipp_tclass = 0;
10891 					*i1 = 0;
10892 				} else {
10893 					ipp->ipp_tclass = *i1;
10894 				}
10895 				ipp->ipp_fields |= IPPF_TCLASS;
10896 			}
10897 			reterr = tcp_build_hdrs(q, tcp);
10898 			if (reterr != 0)
10899 				return (reterr);
10900 			break;
10901 		case IPV6_NEXTHOP:
10902 			/*
10903 			 * IP will verify that the nexthop is reachable
10904 			 * and fail for sticky options.
10905 			 */
10906 			if (inlen != 0 && inlen != sizeof (sin6_t))
10907 				return (EINVAL);
10908 			if (checkonly)
10909 				break;
10910 
10911 			if (inlen == 0) {
10912 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10913 			} else {
10914 				sin6_t *sin6 = (sin6_t *)invalp;
10915 
10916 				if (sin6->sin6_family != AF_INET6)
10917 					return (EAFNOSUPPORT);
10918 				if (IN6_IS_ADDR_V4MAPPED(
10919 				    &sin6->sin6_addr))
10920 					return (EADDRNOTAVAIL);
10921 				ipp->ipp_nexthop = sin6->sin6_addr;
10922 				if (!IN6_IS_ADDR_UNSPECIFIED(
10923 				    &ipp->ipp_nexthop))
10924 					ipp->ipp_fields |= IPPF_NEXTHOP;
10925 				else
10926 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10927 			}
10928 			reterr = tcp_build_hdrs(q, tcp);
10929 			if (reterr != 0)
10930 				return (reterr);
10931 			break;
10932 		case IPV6_HOPOPTS: {
10933 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10934 			/*
10935 			 * Sanity checks - minimum size, size a multiple of
10936 			 * eight bytes, and matching size passed in.
10937 			 */
10938 			if (inlen != 0 &&
10939 			    inlen != (8 * (hopts->ip6h_len + 1)))
10940 				return (EINVAL);
10941 
10942 			if (checkonly)
10943 				break;
10944 
10945 			if (inlen == 0) {
10946 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10947 					kmem_free(ipp->ipp_hopopts,
10948 					    ipp->ipp_hopoptslen);
10949 					ipp->ipp_hopopts = NULL;
10950 					ipp->ipp_hopoptslen = 0;
10951 				}
10952 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10953 			} else {
10954 				reterr = tcp_pkt_set(invalp, inlen,
10955 				    (uchar_t **)&ipp->ipp_hopopts,
10956 				    &ipp->ipp_hopoptslen);
10957 				if (reterr != 0)
10958 					return (reterr);
10959 				ipp->ipp_fields |= IPPF_HOPOPTS;
10960 			}
10961 			reterr = tcp_build_hdrs(q, tcp);
10962 			if (reterr != 0)
10963 				return (reterr);
10964 			break;
10965 		}
10966 		case IPV6_RTHDRDSTOPTS: {
10967 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10968 
10969 			/*
10970 			 * Sanity checks - minimum size, size a multiple of
10971 			 * eight bytes, and matching size passed in.
10972 			 */
10973 			if (inlen != 0 &&
10974 			    inlen != (8 * (dopts->ip6d_len + 1)))
10975 				return (EINVAL);
10976 
10977 			if (checkonly)
10978 				break;
10979 
10980 			if (inlen == 0) {
10981 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10982 					kmem_free(ipp->ipp_rtdstopts,
10983 					    ipp->ipp_rtdstoptslen);
10984 					ipp->ipp_rtdstopts = NULL;
10985 					ipp->ipp_rtdstoptslen = 0;
10986 				}
10987 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10988 			} else {
10989 				reterr = tcp_pkt_set(invalp, inlen,
10990 				    (uchar_t **)&ipp->ipp_rtdstopts,
10991 				    &ipp->ipp_rtdstoptslen);
10992 				if (reterr != 0)
10993 					return (reterr);
10994 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10995 			}
10996 			reterr = tcp_build_hdrs(q, tcp);
10997 			if (reterr != 0)
10998 				return (reterr);
10999 			break;
11000 		}
11001 		case IPV6_DSTOPTS: {
11002 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11003 
11004 			/*
11005 			 * Sanity checks - minimum size, size a multiple of
11006 			 * eight bytes, and matching size passed in.
11007 			 */
11008 			if (inlen != 0 &&
11009 			    inlen != (8 * (dopts->ip6d_len + 1)))
11010 				return (EINVAL);
11011 
11012 			if (checkonly)
11013 				break;
11014 
11015 			if (inlen == 0) {
11016 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
11017 					kmem_free(ipp->ipp_dstopts,
11018 					    ipp->ipp_dstoptslen);
11019 					ipp->ipp_dstopts = NULL;
11020 					ipp->ipp_dstoptslen = 0;
11021 				}
11022 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11023 			} else {
11024 				reterr = tcp_pkt_set(invalp, inlen,
11025 				    (uchar_t **)&ipp->ipp_dstopts,
11026 				    &ipp->ipp_dstoptslen);
11027 				if (reterr != 0)
11028 					return (reterr);
11029 				ipp->ipp_fields |= IPPF_DSTOPTS;
11030 			}
11031 			reterr = tcp_build_hdrs(q, tcp);
11032 			if (reterr != 0)
11033 				return (reterr);
11034 			break;
11035 		}
11036 		case IPV6_RTHDR: {
11037 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11038 
11039 			/*
11040 			 * Sanity checks - minimum size, size a multiple of
11041 			 * eight bytes, and matching size passed in.
11042 			 */
11043 			if (inlen != 0 &&
11044 			    inlen != (8 * (rt->ip6r_len + 1)))
11045 				return (EINVAL);
11046 
11047 			if (checkonly)
11048 				break;
11049 
11050 			if (inlen == 0) {
11051 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
11052 					kmem_free(ipp->ipp_rthdr,
11053 					    ipp->ipp_rthdrlen);
11054 					ipp->ipp_rthdr = NULL;
11055 					ipp->ipp_rthdrlen = 0;
11056 				}
11057 				ipp->ipp_fields &= ~IPPF_RTHDR;
11058 			} else {
11059 				reterr = tcp_pkt_set(invalp, inlen,
11060 				    (uchar_t **)&ipp->ipp_rthdr,
11061 				    &ipp->ipp_rthdrlen);
11062 				if (reterr != 0)
11063 					return (reterr);
11064 				ipp->ipp_fields |= IPPF_RTHDR;
11065 			}
11066 			reterr = tcp_build_hdrs(q, tcp);
11067 			if (reterr != 0)
11068 				return (reterr);
11069 			break;
11070 		}
11071 		case IPV6_V6ONLY:
11072 			if (!checkonly)
11073 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11074 			break;
11075 		case IPV6_USE_MIN_MTU:
11076 			if (inlen != sizeof (int))
11077 				return (EINVAL);
11078 
11079 			if (*i1 < -1 || *i1 > 1)
11080 				return (EINVAL);
11081 
11082 			if (checkonly)
11083 				break;
11084 
11085 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11086 			ipp->ipp_use_min_mtu = *i1;
11087 			break;
11088 		case IPV6_BOUND_PIF:
11089 			/* Handled at the IP level */
11090 			return (-EINVAL);
11091 		case IPV6_SEC_OPT:
11092 			/*
11093 			 * We should not allow policy setting after
11094 			 * we start listening for connections.
11095 			 */
11096 			if (tcp->tcp_state == TCPS_LISTEN) {
11097 				return (EINVAL);
11098 			} else {
11099 				/* Handled at the IP level */
11100 				return (-EINVAL);
11101 			}
11102 		case IPV6_SRC_PREFERENCES:
11103 			if (inlen != sizeof (uint32_t))
11104 				return (EINVAL);
11105 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11106 			    *(uint32_t *)invalp);
11107 			if (reterr != 0) {
11108 				*outlenp = 0;
11109 				return (reterr);
11110 			}
11111 			break;
11112 		default:
11113 			*outlenp = 0;
11114 			return (EINVAL);
11115 		}
11116 		break;
11117 	}		/* end IPPROTO_IPV6 */
11118 	default:
11119 		*outlenp = 0;
11120 		return (EINVAL);
11121 	}
11122 	/*
11123 	 * Common case of OK return with outval same as inval
11124 	 */
11125 	if (invalp != outvalp) {
11126 		/* don't trust bcopy for identical src/dst */
11127 		(void) bcopy(invalp, outvalp, inlen);
11128 	}
11129 	*outlenp = inlen;
11130 	return (0);
11131 }
11132 
11133 /*
11134  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11135  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11136  * headers, and the maximum size tcp header (to avoid reallocation
11137  * on the fly for additional tcp options).
11138  * Returns failure if can't allocate memory.
11139  */
11140 static int
11141 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11142 {
11143 	char	*hdrs;
11144 	uint_t	hdrs_len;
11145 	ip6i_t	*ip6i;
11146 	char	buf[TCP_MAX_HDR_LENGTH];
11147 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11148 	in6_addr_t src, dst;
11149 
11150 	/*
11151 	 * save the existing tcp header and source/dest IP addresses
11152 	 */
11153 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11154 	src = tcp->tcp_ip6h->ip6_src;
11155 	dst = tcp->tcp_ip6h->ip6_dst;
11156 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11157 	ASSERT(hdrs_len != 0);
11158 	if (hdrs_len > tcp->tcp_iphc_len) {
11159 		/* Need to reallocate */
11160 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11161 		if (hdrs == NULL)
11162 			return (ENOMEM);
11163 		if (tcp->tcp_iphc != NULL) {
11164 			if (tcp->tcp_hdr_grown) {
11165 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11166 			} else {
11167 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11168 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11169 			}
11170 			tcp->tcp_iphc_len = 0;
11171 		}
11172 		ASSERT(tcp->tcp_iphc_len == 0);
11173 		tcp->tcp_iphc = hdrs;
11174 		tcp->tcp_iphc_len = hdrs_len;
11175 		tcp->tcp_hdr_grown = B_TRUE;
11176 	}
11177 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11178 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11179 
11180 	/* Set header fields not in ipp */
11181 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11182 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11183 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11184 	} else {
11185 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11186 	}
11187 	/*
11188 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11189 	 *
11190 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11191 	 */
11192 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11193 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11194 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11195 
11196 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11197 
11198 	tcp->tcp_ip6h->ip6_src = src;
11199 	tcp->tcp_ip6h->ip6_dst = dst;
11200 
11201 	/*
11202 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11203 	 * the default value for TCP.
11204 	 */
11205 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11206 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
11207 
11208 	/*
11209 	 * If we're setting extension headers after a connection
11210 	 * has been established, and if we have a routing header
11211 	 * among the extension headers, call ip_massage_options_v6 to
11212 	 * manipulate the routing header/ip6_dst set the checksum
11213 	 * difference in the tcp header template.
11214 	 * (This happens in tcp_connect_ipv6 if the routing header
11215 	 * is set prior to the connect.)
11216 	 * Set the tcp_sum to zero first in case we've cleared a
11217 	 * routing header or don't have one at all.
11218 	 */
11219 	tcp->tcp_sum = 0;
11220 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11221 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11222 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11223 		    (uint8_t *)tcp->tcp_tcph);
11224 		if (rth != NULL) {
11225 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11226 			    rth);
11227 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11228 			    (tcp->tcp_sum >> 16));
11229 		}
11230 	}
11231 
11232 	/* Try to get everything in a single mblk */
11233 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
11234 	return (0);
11235 }
11236 
11237 /*
11238  * Set optbuf and optlen for the option.
11239  * Allocate memory (if not already present).
11240  * Otherwise just point optbuf and optlen at invalp and inlen.
11241  * Returns failure if memory can not be allocated.
11242  */
11243 static int
11244 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
11245 {
11246 	uchar_t *optbuf;
11247 
11248 	if (inlen == *optlenp) {
11249 		/* Unchanged length - no need to realocate */
11250 		bcopy(invalp, *optbufp, inlen);
11251 		return (0);
11252 	}
11253 	if (inlen != 0) {
11254 		/* Allocate new buffer before free */
11255 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
11256 		if (optbuf == NULL)
11257 			return (ENOMEM);
11258 	} else {
11259 		optbuf = NULL;
11260 	}
11261 	/* Free old buffer */
11262 	if (*optlenp != 0)
11263 		kmem_free(*optbufp, *optlenp);
11264 
11265 	bcopy(invalp, optbuf, inlen);
11266 	*optbufp = optbuf;
11267 	*optlenp = inlen;
11268 	return (0);
11269 }
11270 
11271 
11272 /*
11273  * Use the outgoing IP header to create an IP_OPTIONS option the way
11274  * it was passed down from the application.
11275  */
11276 static int
11277 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
11278 {
11279 	ipoptp_t	opts;
11280 	uchar_t		*opt;
11281 	uint8_t		optval;
11282 	uint8_t		optlen;
11283 	uint32_t	len = 0;
11284 	uchar_t	*buf1 = buf;
11285 
11286 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
11287 	len += IP_ADDR_LEN;
11288 	bzero(buf1, IP_ADDR_LEN);
11289 
11290 	for (optval = ipoptp_first(&opts, ipha);
11291 	    optval != IPOPT_EOL;
11292 	    optval = ipoptp_next(&opts)) {
11293 		opt = opts.ipoptp_cur;
11294 		optlen = opts.ipoptp_len;
11295 		switch (optval) {
11296 			int	off;
11297 		case IPOPT_SSRR:
11298 		case IPOPT_LSRR:
11299 
11300 			/*
11301 			 * Insert ipha_dst as the first entry in the source
11302 			 * route and move down the entries on step.
11303 			 * The last entry gets placed at buf1.
11304 			 */
11305 			buf[IPOPT_OPTVAL] = optval;
11306 			buf[IPOPT_OLEN] = optlen;
11307 			buf[IPOPT_OFFSET] = optlen;
11308 
11309 			off = optlen - IP_ADDR_LEN;
11310 			if (off < 0) {
11311 				/* No entries in source route */
11312 				break;
11313 			}
11314 			/* Last entry in source route */
11315 			bcopy(opt + off, buf1, IP_ADDR_LEN);
11316 			off -= IP_ADDR_LEN;
11317 
11318 			while (off > 0) {
11319 				bcopy(opt + off,
11320 				    buf + off + IP_ADDR_LEN,
11321 				    IP_ADDR_LEN);
11322 				off -= IP_ADDR_LEN;
11323 			}
11324 			/* ipha_dst into first slot */
11325 			bcopy(&ipha->ipha_dst,
11326 			    buf + off + IP_ADDR_LEN,
11327 			    IP_ADDR_LEN);
11328 			buf += optlen;
11329 			len += optlen;
11330 			break;
11331 		default:
11332 			bcopy(opt, buf, optlen);
11333 			buf += optlen;
11334 			len += optlen;
11335 			break;
11336 		}
11337 	}
11338 done:
11339 	/* Pad the resulting options */
11340 	while (len & 0x3) {
11341 		*buf++ = IPOPT_EOL;
11342 		len++;
11343 	}
11344 	return (len);
11345 }
11346 
11347 /*
11348  * Transfer any source route option from ipha to buf/dst in reversed form.
11349  */
11350 static int
11351 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11352 {
11353 	ipoptp_t	opts;
11354 	uchar_t		*opt;
11355 	uint8_t		optval;
11356 	uint8_t		optlen;
11357 	uint32_t	len = 0;
11358 
11359 	for (optval = ipoptp_first(&opts, ipha);
11360 	    optval != IPOPT_EOL;
11361 	    optval = ipoptp_next(&opts)) {
11362 		opt = opts.ipoptp_cur;
11363 		optlen = opts.ipoptp_len;
11364 		switch (optval) {
11365 			int	off1, off2;
11366 		case IPOPT_SSRR:
11367 		case IPOPT_LSRR:
11368 
11369 			/* Reverse source route */
11370 			/*
11371 			 * First entry should be the next to last one in the
11372 			 * current source route (the last entry is our
11373 			 * address.)
11374 			 * The last entry should be the final destination.
11375 			 */
11376 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11377 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11378 			off1 = IPOPT_MINOFF_SR - 1;
11379 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11380 			if (off2 < 0) {
11381 				/* No entries in source route */
11382 				break;
11383 			}
11384 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11385 			/*
11386 			 * Note: use src since ipha has not had its src
11387 			 * and dst reversed (it is in the state it was
11388 			 * received.
11389 			 */
11390 			bcopy(&ipha->ipha_src, buf + off2,
11391 			    IP_ADDR_LEN);
11392 			off2 -= IP_ADDR_LEN;
11393 
11394 			while (off2 > 0) {
11395 				bcopy(opt + off2, buf + off1,
11396 				    IP_ADDR_LEN);
11397 				off1 += IP_ADDR_LEN;
11398 				off2 -= IP_ADDR_LEN;
11399 			}
11400 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11401 			buf += optlen;
11402 			len += optlen;
11403 			break;
11404 		}
11405 	}
11406 done:
11407 	/* Pad the resulting options */
11408 	while (len & 0x3) {
11409 		*buf++ = IPOPT_EOL;
11410 		len++;
11411 	}
11412 	return (len);
11413 }
11414 
11415 
11416 /*
11417  * Extract and revert a source route from ipha (if any)
11418  * and then update the relevant fields in both tcp_t and the standard header.
11419  */
11420 static void
11421 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11422 {
11423 	char	buf[TCP_MAX_HDR_LENGTH];
11424 	uint_t	tcph_len;
11425 	int	len;
11426 
11427 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11428 	len = IPH_HDR_LENGTH(ipha);
11429 	if (len == IP_SIMPLE_HDR_LENGTH)
11430 		/* Nothing to do */
11431 		return;
11432 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11433 	    (len & 0x3))
11434 		return;
11435 
11436 	tcph_len = tcp->tcp_tcp_hdr_len;
11437 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11438 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11439 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11440 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11441 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11442 	len += IP_SIMPLE_HDR_LENGTH;
11443 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11444 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11445 	if ((int)tcp->tcp_sum < 0)
11446 		tcp->tcp_sum--;
11447 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11448 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11449 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11450 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11451 	tcp->tcp_ip_hdr_len = len;
11452 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11453 	    (IP_VERSION << 4) | (len >> 2);
11454 	len += tcph_len;
11455 	tcp->tcp_hdr_len = len;
11456 }
11457 
11458 /*
11459  * Copy the standard header into its new location,
11460  * lay in the new options and then update the relevant
11461  * fields in both tcp_t and the standard header.
11462  */
11463 static int
11464 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11465 {
11466 	uint_t	tcph_len;
11467 	char	*ip_optp;
11468 	tcph_t	*new_tcph;
11469 
11470 	if (checkonly) {
11471 		/*
11472 		 * do not really set, just pretend to - T_CHECK
11473 		 */
11474 		if (len != 0) {
11475 			/*
11476 			 * there is value supplied, validate it as if
11477 			 * for a real set operation.
11478 			 */
11479 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11480 				return (EINVAL);
11481 		}
11482 		return (0);
11483 	}
11484 
11485 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11486 		return (EINVAL);
11487 
11488 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11489 	tcph_len = tcp->tcp_tcp_hdr_len;
11490 	new_tcph = (tcph_t *)(ip_optp + len);
11491 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
11492 	tcp->tcp_tcph = new_tcph;
11493 	bcopy(ptr, ip_optp, len);
11494 
11495 	len += IP_SIMPLE_HDR_LENGTH;
11496 
11497 	tcp->tcp_ip_hdr_len = len;
11498 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11499 		(IP_VERSION << 4) | (len >> 2);
11500 	len += tcph_len;
11501 	tcp->tcp_hdr_len = len;
11502 	if (!TCP_IS_DETACHED(tcp)) {
11503 		/* Always allocate room for all options. */
11504 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11505 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
11506 	}
11507 	return (0);
11508 }
11509 
11510 /* Get callback routine passed to nd_load by tcp_param_register */
11511 /* ARGSUSED */
11512 static int
11513 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11514 {
11515 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11516 
11517 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11518 	return (0);
11519 }
11520 
11521 /*
11522  * Walk through the param array specified registering each element with the
11523  * named dispatch handler.
11524  */
11525 static boolean_t
11526 tcp_param_register(tcpparam_t *tcppa, int cnt)
11527 {
11528 	for (; cnt-- > 0; tcppa++) {
11529 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11530 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11531 			    tcp_param_get, tcp_param_set,
11532 			    (caddr_t)tcppa)) {
11533 				nd_free(&tcp_g_nd);
11534 				return (B_FALSE);
11535 			}
11536 		}
11537 	}
11538 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11539 	    tcp_param_get, tcp_param_set_aligned,
11540 	    (caddr_t)&tcp_wroff_xtra_param)) {
11541 		nd_free(&tcp_g_nd);
11542 		return (B_FALSE);
11543 	}
11544 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11545 	    tcp_param_get, tcp_param_set_aligned,
11546 	    (caddr_t)&tcp_mdt_head_param)) {
11547 		nd_free(&tcp_g_nd);
11548 		return (B_FALSE);
11549 	}
11550 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11551 	    tcp_param_get, tcp_param_set_aligned,
11552 	    (caddr_t)&tcp_mdt_tail_param)) {
11553 		nd_free(&tcp_g_nd);
11554 		return (B_FALSE);
11555 	}
11556 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11557 	    tcp_param_get, tcp_param_set,
11558 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11559 		nd_free(&tcp_g_nd);
11560 		return (B_FALSE);
11561 	}
11562 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11563 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11564 		nd_free(&tcp_g_nd);
11565 		return (B_FALSE);
11566 	}
11567 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11568 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11569 		nd_free(&tcp_g_nd);
11570 		return (B_FALSE);
11571 	}
11572 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11573 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11574 		nd_free(&tcp_g_nd);
11575 		return (B_FALSE);
11576 	}
11577 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11578 	    NULL)) {
11579 		nd_free(&tcp_g_nd);
11580 		return (B_FALSE);
11581 	}
11582 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11583 	    NULL, NULL)) {
11584 		nd_free(&tcp_g_nd);
11585 		return (B_FALSE);
11586 	}
11587 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11588 	    NULL, NULL)) {
11589 		nd_free(&tcp_g_nd);
11590 		return (B_FALSE);
11591 	}
11592 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11593 	    NULL, NULL)) {
11594 		nd_free(&tcp_g_nd);
11595 		return (B_FALSE);
11596 	}
11597 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11598 	    NULL, NULL)) {
11599 		nd_free(&tcp_g_nd);
11600 		return (B_FALSE);
11601 	}
11602 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11603 	    tcp_host_param_set, NULL)) {
11604 		nd_free(&tcp_g_nd);
11605 		return (B_FALSE);
11606 	}
11607 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11608 	    tcp_host_param_set_ipv6, NULL)) {
11609 		nd_free(&tcp_g_nd);
11610 		return (B_FALSE);
11611 	}
11612 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11613 	    NULL)) {
11614 		nd_free(&tcp_g_nd);
11615 		return (B_FALSE);
11616 	}
11617 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11618 	    tcp_reserved_port_list, NULL, NULL)) {
11619 		nd_free(&tcp_g_nd);
11620 		return (B_FALSE);
11621 	}
11622 	/*
11623 	 * Dummy ndd variables - only to convey obsolescence information
11624 	 * through printing of their name (no get or set routines)
11625 	 * XXX Remove in future releases ?
11626 	 */
11627 	if (!nd_load(&tcp_g_nd,
11628 	    "tcp_close_wait_interval(obsoleted - "
11629 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11630 		nd_free(&tcp_g_nd);
11631 		return (B_FALSE);
11632 	}
11633 	return (B_TRUE);
11634 }
11635 
11636 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11637 /* ARGSUSED */
11638 static int
11639 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11640     cred_t *cr)
11641 {
11642 	long new_value;
11643 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11644 
11645 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11646 	    new_value < tcppa->tcp_param_min ||
11647 	    new_value > tcppa->tcp_param_max) {
11648 		return (EINVAL);
11649 	}
11650 	/*
11651 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11652 	 * round it up.  For future 64 bit requirement, we actually make it
11653 	 * a multiple of 8.
11654 	 */
11655 	if (new_value & 0x7) {
11656 		new_value = (new_value & ~0x7) + 0x8;
11657 	}
11658 	tcppa->tcp_param_val = new_value;
11659 	return (0);
11660 }
11661 
11662 /* Set callback routine passed to nd_load by tcp_param_register */
11663 /* ARGSUSED */
11664 static int
11665 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11666 {
11667 	long	new_value;
11668 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11669 
11670 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11671 	    new_value < tcppa->tcp_param_min ||
11672 	    new_value > tcppa->tcp_param_max) {
11673 		return (EINVAL);
11674 	}
11675 	tcppa->tcp_param_val = new_value;
11676 	return (0);
11677 }
11678 
11679 /*
11680  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11681  * is filled, return as much as we can.  The message passed in may be
11682  * multi-part, chained using b_cont.  "start" is the starting sequence
11683  * number for this piece.
11684  */
11685 static mblk_t *
11686 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11687 {
11688 	uint32_t	end;
11689 	mblk_t		*mp1;
11690 	mblk_t		*mp2;
11691 	mblk_t		*next_mp;
11692 	uint32_t	u1;
11693 
11694 	/* Walk through all the new pieces. */
11695 	do {
11696 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11697 		    (uintptr_t)INT_MAX);
11698 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11699 		next_mp = mp->b_cont;
11700 		if (start == end) {
11701 			/* Empty.  Blast it. */
11702 			freeb(mp);
11703 			continue;
11704 		}
11705 		mp->b_cont = NULL;
11706 		TCP_REASS_SET_SEQ(mp, start);
11707 		TCP_REASS_SET_END(mp, end);
11708 		mp1 = tcp->tcp_reass_tail;
11709 		if (!mp1) {
11710 			tcp->tcp_reass_tail = mp;
11711 			tcp->tcp_reass_head = mp;
11712 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11713 			UPDATE_MIB(&tcp_mib,
11714 			    tcpInDataUnorderBytes, end - start);
11715 			continue;
11716 		}
11717 		/* New stuff completely beyond tail? */
11718 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11719 			/* Link it on end. */
11720 			mp1->b_cont = mp;
11721 			tcp->tcp_reass_tail = mp;
11722 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11723 			UPDATE_MIB(&tcp_mib,
11724 			    tcpInDataUnorderBytes, end - start);
11725 			continue;
11726 		}
11727 		mp1 = tcp->tcp_reass_head;
11728 		u1 = TCP_REASS_SEQ(mp1);
11729 		/* New stuff at the front? */
11730 		if (SEQ_LT(start, u1)) {
11731 			/* Yes... Check for overlap. */
11732 			mp->b_cont = mp1;
11733 			tcp->tcp_reass_head = mp;
11734 			tcp_reass_elim_overlap(tcp, mp);
11735 			continue;
11736 		}
11737 		/*
11738 		 * The new piece fits somewhere between the head and tail.
11739 		 * We find our slot, where mp1 precedes us and mp2 trails.
11740 		 */
11741 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11742 			u1 = TCP_REASS_SEQ(mp2);
11743 			if (SEQ_LEQ(start, u1))
11744 				break;
11745 		}
11746 		/* Link ourselves in */
11747 		mp->b_cont = mp2;
11748 		mp1->b_cont = mp;
11749 
11750 		/* Trim overlap with following mblk(s) first */
11751 		tcp_reass_elim_overlap(tcp, mp);
11752 
11753 		/* Trim overlap with preceding mblk */
11754 		tcp_reass_elim_overlap(tcp, mp1);
11755 
11756 	} while (start = end, mp = next_mp);
11757 	mp1 = tcp->tcp_reass_head;
11758 	/* Anything ready to go? */
11759 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11760 		return (NULL);
11761 	/* Eat what we can off the queue */
11762 	for (;;) {
11763 		mp = mp1->b_cont;
11764 		end = TCP_REASS_END(mp1);
11765 		TCP_REASS_SET_SEQ(mp1, 0);
11766 		TCP_REASS_SET_END(mp1, 0);
11767 		if (!mp) {
11768 			tcp->tcp_reass_tail = NULL;
11769 			break;
11770 		}
11771 		if (end != TCP_REASS_SEQ(mp)) {
11772 			mp1->b_cont = NULL;
11773 			break;
11774 		}
11775 		mp1 = mp;
11776 	}
11777 	mp1 = tcp->tcp_reass_head;
11778 	tcp->tcp_reass_head = mp;
11779 	return (mp1);
11780 }
11781 
11782 /* Eliminate any overlap that mp may have over later mblks */
11783 static void
11784 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11785 {
11786 	uint32_t	end;
11787 	mblk_t		*mp1;
11788 	uint32_t	u1;
11789 
11790 	end = TCP_REASS_END(mp);
11791 	while ((mp1 = mp->b_cont) != NULL) {
11792 		u1 = TCP_REASS_SEQ(mp1);
11793 		if (!SEQ_GT(end, u1))
11794 			break;
11795 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11796 			mp->b_wptr -= end - u1;
11797 			TCP_REASS_SET_END(mp, u1);
11798 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11799 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11800 			break;
11801 		}
11802 		mp->b_cont = mp1->b_cont;
11803 		TCP_REASS_SET_SEQ(mp1, 0);
11804 		TCP_REASS_SET_END(mp1, 0);
11805 		freeb(mp1);
11806 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11807 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11808 	}
11809 	if (!mp1)
11810 		tcp->tcp_reass_tail = mp;
11811 }
11812 
11813 /*
11814  * Send up all messages queued on tcp_rcv_list.
11815  */
11816 static uint_t
11817 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11818 {
11819 	mblk_t *mp;
11820 	uint_t ret = 0;
11821 	uint_t thwin;
11822 #ifdef DEBUG
11823 	uint_t cnt = 0;
11824 #endif
11825 	/* Can't drain on an eager connection */
11826 	if (tcp->tcp_listener != NULL)
11827 		return (ret);
11828 
11829 	/*
11830 	 * Handle two cases here: we are currently fused or we were
11831 	 * previously fused and have some urgent data to be delivered
11832 	 * upstream.  The latter happens because we either ran out of
11833 	 * memory or were detached and therefore sending the SIGURG was
11834 	 * deferred until this point.  In either case we pass control
11835 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11836 	 * some work.
11837 	 */
11838 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11839 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11840 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11841 		    &tcp->tcp_fused_sigurg_mp))
11842 			return (ret);
11843 	}
11844 
11845 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11846 		tcp->tcp_rcv_list = mp->b_next;
11847 		mp->b_next = NULL;
11848 #ifdef DEBUG
11849 		cnt += msgdsize(mp);
11850 #endif
11851 		putnext(q, mp);
11852 	}
11853 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11854 	tcp->tcp_rcv_last_head = NULL;
11855 	tcp->tcp_rcv_last_tail = NULL;
11856 	tcp->tcp_rcv_cnt = 0;
11857 
11858 	/* Learn the latest rwnd information that we sent to the other side. */
11859 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11860 	    << tcp->tcp_rcv_ws;
11861 	/* This is peer's calculated send window (our receive window). */
11862 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11863 	/*
11864 	 * Increase the receive window to max.  But we need to do receiver
11865 	 * SWS avoidance.  This means that we need to check the increase of
11866 	 * of receive window is at least 1 MSS.
11867 	 */
11868 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11869 		/*
11870 		 * If the window that the other side knows is less than max
11871 		 * deferred acks segments, send an update immediately.
11872 		 */
11873 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11874 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11875 			ret = TH_ACK_NEEDED;
11876 		}
11877 		tcp->tcp_rwnd = q->q_hiwat;
11878 	}
11879 	/* No need for the push timer now. */
11880 	if (tcp->tcp_push_tid != 0) {
11881 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11882 		tcp->tcp_push_tid = 0;
11883 	}
11884 	return (ret);
11885 }
11886 
11887 /*
11888  * Queue data on tcp_rcv_list which is a b_next chain.
11889  * tcp_rcv_last_head/tail is the last element of this chain.
11890  * Each element of the chain is a b_cont chain.
11891  *
11892  * M_DATA messages are added to the current element.
11893  * Other messages are added as new (b_next) elements.
11894  */
11895 static void
11896 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11897 {
11898 	ASSERT(seg_len == msgdsize(mp));
11899 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11900 
11901 	if (tcp->tcp_rcv_list == NULL) {
11902 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11903 		tcp->tcp_rcv_list = mp;
11904 		tcp->tcp_rcv_last_head = mp;
11905 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11906 		tcp->tcp_rcv_last_tail->b_cont = mp;
11907 	} else {
11908 		tcp->tcp_rcv_last_head->b_next = mp;
11909 		tcp->tcp_rcv_last_head = mp;
11910 	}
11911 
11912 	while (mp->b_cont)
11913 		mp = mp->b_cont;
11914 
11915 	tcp->tcp_rcv_last_tail = mp;
11916 	tcp->tcp_rcv_cnt += seg_len;
11917 	tcp->tcp_rwnd -= seg_len;
11918 }
11919 
11920 /*
11921  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11922  *
11923  * This is the default entry function into TCP on the read side. TCP is
11924  * always entered via squeue i.e. using squeue's for mutual exclusion.
11925  * When classifier does a lookup to find the tcp, it also puts a reference
11926  * on the conn structure associated so the tcp is guaranteed to exist
11927  * when we come here. We still need to check the state because it might
11928  * as well has been closed. The squeue processing function i.e. squeue_enter,
11929  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11930  * CONN_DEC_REF.
11931  *
11932  * Apart from the default entry point, IP also sends packets directly to
11933  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11934  * connections.
11935  */
11936 void
11937 tcp_input(void *arg, mblk_t *mp, void *arg2)
11938 {
11939 	conn_t	*connp = (conn_t *)arg;
11940 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11941 
11942 	/* arg2 is the sqp */
11943 	ASSERT(arg2 != NULL);
11944 	ASSERT(mp != NULL);
11945 
11946 	/*
11947 	 * Don't accept any input on a closed tcp as this TCP logically does
11948 	 * not exist on the system. Don't proceed further with this TCP.
11949 	 * For eg. this packet could trigger another close of this tcp
11950 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11951 	 * tcp_clean_death / tcp_closei_local must be called at most once
11952 	 * on a TCP. In this case we need to refeed the packet into the
11953 	 * classifier and figure out where the packet should go. Need to
11954 	 * preserve the recv_ill somehow. Until we figure that out, for
11955 	 * now just drop the packet if we can't classify the packet.
11956 	 */
11957 	if (tcp->tcp_state == TCPS_CLOSED ||
11958 	    tcp->tcp_state == TCPS_BOUND) {
11959 		conn_t	*new_connp;
11960 
11961 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11962 		if (new_connp != NULL) {
11963 			tcp_reinput(new_connp, mp, arg2);
11964 			return;
11965 		}
11966 		/* We failed to classify. For now just drop the packet */
11967 		freemsg(mp);
11968 		return;
11969 	}
11970 
11971 	if (DB_TYPE(mp) == M_DATA)
11972 		tcp_rput_data(connp, mp, arg2);
11973 	else
11974 		tcp_rput_common(tcp, mp);
11975 }
11976 
11977 /*
11978  * The read side put procedure.
11979  * The packets passed up by ip are assume to be aligned according to
11980  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11981  */
11982 static void
11983 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11984 {
11985 	/*
11986 	 * tcp_rput_data() does not expect M_CTL except for the case
11987 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11988 	 * type. Need to make sure that any other M_CTLs don't make
11989 	 * it to tcp_rput_data since it is not expecting any and doesn't
11990 	 * check for it.
11991 	 */
11992 	if (DB_TYPE(mp) == M_CTL) {
11993 		switch (*(uint32_t *)(mp->b_rptr)) {
11994 		case TCP_IOC_ABORT_CONN:
11995 			/*
11996 			 * Handle connection abort request.
11997 			 */
11998 			tcp_ioctl_abort_handler(tcp, mp);
11999 			return;
12000 		case IPSEC_IN:
12001 			/*
12002 			 * Only secure icmp arrive in TCP and they
12003 			 * don't go through data path.
12004 			 */
12005 			tcp_icmp_error(tcp, mp);
12006 			return;
12007 		case IN_PKTINFO:
12008 			/*
12009 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12010 			 * sockets that are receiving IPv4 traffic. tcp
12011 			 */
12012 			ASSERT(tcp->tcp_family == AF_INET6);
12013 			ASSERT(tcp->tcp_ipv6_recvancillary &
12014 			    TCP_IPV6_RECVPKTINFO);
12015 			tcp_rput_data(tcp->tcp_connp, mp,
12016 			    tcp->tcp_connp->conn_sqp);
12017 			return;
12018 		case MDT_IOC_INFO_UPDATE:
12019 			/*
12020 			 * Handle Multidata information update; the
12021 			 * following routine will free the message.
12022 			 */
12023 			if (tcp->tcp_connp->conn_mdt_ok) {
12024 				tcp_mdt_update(tcp,
12025 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12026 				    B_FALSE);
12027 			}
12028 			freemsg(mp);
12029 			return;
12030 		default:
12031 			break;
12032 		}
12033 	}
12034 
12035 	/* No point processing the message if tcp is already closed */
12036 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12037 		freemsg(mp);
12038 		return;
12039 	}
12040 
12041 	tcp_rput_other(tcp, mp);
12042 }
12043 
12044 
12045 /* The minimum of smoothed mean deviation in RTO calculation. */
12046 #define	TCP_SD_MIN	400
12047 
12048 /*
12049  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12050  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12051  * are the same as those in Appendix A.2 of that paper.
12052  *
12053  * m = new measurement
12054  * sa = smoothed RTT average (8 * average estimates).
12055  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12056  */
12057 static void
12058 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12059 {
12060 	long m = TICK_TO_MSEC(rtt);
12061 	clock_t sa = tcp->tcp_rtt_sa;
12062 	clock_t sv = tcp->tcp_rtt_sd;
12063 	clock_t rto;
12064 
12065 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
12066 	tcp->tcp_rtt_update++;
12067 
12068 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12069 	if (sa != 0) {
12070 		/*
12071 		 * Update average estimator:
12072 		 *	new rtt = 7/8 old rtt + 1/8 Error
12073 		 */
12074 
12075 		/* m is now Error in estimate. */
12076 		m -= sa >> 3;
12077 		if ((sa += m) <= 0) {
12078 			/*
12079 			 * Don't allow the smoothed average to be negative.
12080 			 * We use 0 to denote reinitialization of the
12081 			 * variables.
12082 			 */
12083 			sa = 1;
12084 		}
12085 
12086 		/*
12087 		 * Update deviation estimator:
12088 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12089 		 */
12090 		if (m < 0)
12091 			m = -m;
12092 		m -= sv >> 2;
12093 		sv += m;
12094 	} else {
12095 		/*
12096 		 * This follows BSD's implementation.  So the reinitialized
12097 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12098 		 * link is bandwidth dominated, doubling the window size
12099 		 * during slow start means doubling the RTT.  We want to be
12100 		 * more conservative when we reinitialize our estimates.  3
12101 		 * is just a convenient number.
12102 		 */
12103 		sa = m << 3;
12104 		sv = m << 1;
12105 	}
12106 	if (sv < TCP_SD_MIN) {
12107 		/*
12108 		 * We do not know that if sa captures the delay ACK
12109 		 * effect as in a long train of segments, a receiver
12110 		 * does not delay its ACKs.  So set the minimum of sv
12111 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12112 		 * of BSD DATO.  That means the minimum of mean
12113 		 * deviation is 100 ms.
12114 		 *
12115 		 */
12116 		sv = TCP_SD_MIN;
12117 	}
12118 	tcp->tcp_rtt_sa = sa;
12119 	tcp->tcp_rtt_sd = sv;
12120 	/*
12121 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12122 	 *
12123 	 * Add tcp_rexmit_interval extra in case of extreme environment
12124 	 * where the algorithm fails to work.  The default value of
12125 	 * tcp_rexmit_interval_extra should be 0.
12126 	 *
12127 	 * As we use a finer grained clock than BSD and update
12128 	 * RTO for every ACKs, add in another .25 of RTT to the
12129 	 * deviation of RTO to accomodate burstiness of 1/4 of
12130 	 * window size.
12131 	 */
12132 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
12133 
12134 	if (rto > tcp_rexmit_interval_max) {
12135 		tcp->tcp_rto = tcp_rexmit_interval_max;
12136 	} else if (rto < tcp_rexmit_interval_min) {
12137 		tcp->tcp_rto = tcp_rexmit_interval_min;
12138 	} else {
12139 		tcp->tcp_rto = rto;
12140 	}
12141 
12142 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12143 	tcp->tcp_timer_backoff = 0;
12144 }
12145 
12146 /*
12147  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12148  * send queue which starts at the given seq. no.
12149  *
12150  * Parameters:
12151  *	tcp_t *tcp: the tcp instance pointer.
12152  *	uint32_t seq: the starting seq. no of the requested segment.
12153  *	int32_t *off: after the execution, *off will be the offset to
12154  *		the returned mblk which points to the requested seq no.
12155  *		It is the caller's responsibility to send in a non-null off.
12156  *
12157  * Return:
12158  *	A mblk_t pointer pointing to the requested segment in send queue.
12159  */
12160 static mblk_t *
12161 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12162 {
12163 	int32_t	cnt;
12164 	mblk_t	*mp;
12165 
12166 	/* Defensive coding.  Make sure we don't send incorrect data. */
12167 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12168 		return (NULL);
12169 
12170 	cnt = seq - tcp->tcp_suna;
12171 	mp = tcp->tcp_xmit_head;
12172 	while (cnt > 0 && mp != NULL) {
12173 		cnt -= mp->b_wptr - mp->b_rptr;
12174 		if (cnt < 0) {
12175 			cnt += mp->b_wptr - mp->b_rptr;
12176 			break;
12177 		}
12178 		mp = mp->b_cont;
12179 	}
12180 	ASSERT(mp != NULL);
12181 	*off = cnt;
12182 	return (mp);
12183 }
12184 
12185 /*
12186  * This function handles all retransmissions if SACK is enabled for this
12187  * connection.  First it calculates how many segments can be retransmitted
12188  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12189  * segments.  A segment is eligible if sack_cnt for that segment is greater
12190  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12191  * all eligible segments, it checks to see if TCP can send some new segments
12192  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12193  *
12194  * Parameters:
12195  *	tcp_t *tcp: the tcp structure of the connection.
12196  *	uint_t *flags: in return, appropriate value will be set for
12197  *	tcp_rput_data().
12198  */
12199 static void
12200 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12201 {
12202 	notsack_blk_t	*notsack_blk;
12203 	int32_t		usable_swnd;
12204 	int32_t		mss;
12205 	uint32_t	seg_len;
12206 	mblk_t		*xmit_mp;
12207 
12208 	ASSERT(tcp->tcp_sack_info != NULL);
12209 	ASSERT(tcp->tcp_notsack_list != NULL);
12210 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12211 
12212 	/* Defensive coding in case there is a bug... */
12213 	if (tcp->tcp_notsack_list == NULL) {
12214 		return;
12215 	}
12216 	notsack_blk = tcp->tcp_notsack_list;
12217 	mss = tcp->tcp_mss;
12218 
12219 	/*
12220 	 * Limit the num of outstanding data in the network to be
12221 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12222 	 */
12223 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12224 
12225 	/* At least retransmit 1 MSS of data. */
12226 	if (usable_swnd <= 0) {
12227 		usable_swnd = mss;
12228 	}
12229 
12230 	/* Make sure no new RTT samples will be taken. */
12231 	tcp->tcp_csuna = tcp->tcp_snxt;
12232 
12233 	notsack_blk = tcp->tcp_notsack_list;
12234 	while (usable_swnd > 0) {
12235 		mblk_t		*snxt_mp, *tmp_mp;
12236 		tcp_seq		begin = tcp->tcp_sack_snxt;
12237 		tcp_seq		end;
12238 		int32_t		off;
12239 
12240 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12241 			if (SEQ_GT(notsack_blk->end, begin) &&
12242 			    (notsack_blk->sack_cnt >=
12243 			    tcp_dupack_fast_retransmit)) {
12244 				end = notsack_blk->end;
12245 				if (SEQ_LT(begin, notsack_blk->begin)) {
12246 					begin = notsack_blk->begin;
12247 				}
12248 				break;
12249 			}
12250 		}
12251 		/*
12252 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12253 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12254 		 * set to tcp_cwnd_ssthresh.
12255 		 */
12256 		if (notsack_blk == NULL) {
12257 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12258 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12259 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12260 				ASSERT(tcp->tcp_cwnd > 0);
12261 				return;
12262 			} else {
12263 				usable_swnd = usable_swnd / mss;
12264 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12265 				    MAX(usable_swnd * mss, mss);
12266 				*flags |= TH_XMIT_NEEDED;
12267 				return;
12268 			}
12269 		}
12270 
12271 		/*
12272 		 * Note that we may send more than usable_swnd allows here
12273 		 * because of round off, but no more than 1 MSS of data.
12274 		 */
12275 		seg_len = end - begin;
12276 		if (seg_len > mss)
12277 			seg_len = mss;
12278 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12279 		ASSERT(snxt_mp != NULL);
12280 		/* This should not happen.  Defensive coding again... */
12281 		if (snxt_mp == NULL) {
12282 			return;
12283 		}
12284 
12285 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12286 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12287 		if (xmit_mp == NULL)
12288 			return;
12289 
12290 		usable_swnd -= seg_len;
12291 		tcp->tcp_pipe += seg_len;
12292 		tcp->tcp_sack_snxt = begin + seg_len;
12293 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12294 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12295 
12296 		/*
12297 		 * Update the send timestamp to avoid false retransmission.
12298 		 */
12299 		snxt_mp->b_prev = (mblk_t *)lbolt;
12300 
12301 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
12302 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
12303 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
12304 		/*
12305 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12306 		 * This happens when new data sent during fast recovery is
12307 		 * also lost.  If TCP retransmits those new data, it needs
12308 		 * to extend SACK recover phase to avoid starting another
12309 		 * fast retransmit/recovery unnecessarily.
12310 		 */
12311 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12312 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12313 		}
12314 	}
12315 }
12316 
12317 /*
12318  * This function handles policy checking at TCP level for non-hard_bound/
12319  * detached connections.
12320  */
12321 static boolean_t
12322 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12323     boolean_t secure, boolean_t mctl_present)
12324 {
12325 	ipsec_latch_t *ipl = NULL;
12326 	ipsec_action_t *act = NULL;
12327 	mblk_t *data_mp;
12328 	ipsec_in_t *ii;
12329 	const char *reason;
12330 	kstat_named_t *counter;
12331 
12332 	ASSERT(mctl_present || !secure);
12333 
12334 	ASSERT((ipha == NULL && ip6h != NULL) ||
12335 	    (ip6h == NULL && ipha != NULL));
12336 
12337 	/*
12338 	 * We don't necessarily have an ipsec_in_act action to verify
12339 	 * policy because of assymetrical policy where we have only
12340 	 * outbound policy and no inbound policy (possible with global
12341 	 * policy).
12342 	 */
12343 	if (!secure) {
12344 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12345 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12346 			return (B_TRUE);
12347 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
12348 		    "tcp_check_policy", ipha, ip6h, secure);
12349 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12350 		    &ipdrops_tcp_clear, &tcp_dropper);
12351 		return (B_FALSE);
12352 	}
12353 
12354 	/*
12355 	 * We have a secure packet.
12356 	 */
12357 	if (act == NULL) {
12358 		ipsec_log_policy_failure(tcp->tcp_wq,
12359 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
12360 		    secure);
12361 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12362 		    &ipdrops_tcp_secure, &tcp_dropper);
12363 		return (B_FALSE);
12364 	}
12365 
12366 	/*
12367 	 * XXX This whole routine is currently incorrect.  ipl should
12368 	 * be set to the latch pointer, but is currently not set, so
12369 	 * we initialize it to NULL to avoid picking up random garbage.
12370 	 */
12371 	if (ipl == NULL)
12372 		return (B_TRUE);
12373 
12374 	data_mp = first_mp->b_cont;
12375 
12376 	ii = (ipsec_in_t *)first_mp->b_rptr;
12377 
12378 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12379 	    &counter)) {
12380 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
12381 		return (B_TRUE);
12382 	}
12383 	(void) strlog(TCP_MODULE_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12384 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12385 	    reason);
12386 	BUMP_MIB(&ip_mib, ipsecInFailed);
12387 
12388 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
12389 	return (B_FALSE);
12390 }
12391 
12392 /*
12393  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12394  * retransmission after a timeout.
12395  *
12396  * To limit the number of duplicate segments, we limit the number of segment
12397  * to be sent in one time to tcp_snd_burst, the burst variable.
12398  */
12399 static void
12400 tcp_ss_rexmit(tcp_t *tcp)
12401 {
12402 	uint32_t	snxt;
12403 	uint32_t	smax;
12404 	int32_t		win;
12405 	int32_t		mss;
12406 	int32_t		off;
12407 	int32_t		burst = tcp->tcp_snd_burst;
12408 	mblk_t		*snxt_mp;
12409 
12410 	/*
12411 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12412 	 * all unack'ed segments.
12413 	 */
12414 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12415 		smax = tcp->tcp_rexmit_max;
12416 		snxt = tcp->tcp_rexmit_nxt;
12417 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12418 			snxt = tcp->tcp_suna;
12419 		}
12420 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12421 		win -= snxt - tcp->tcp_suna;
12422 		mss = tcp->tcp_mss;
12423 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12424 
12425 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12426 		    (burst > 0) && (snxt_mp != NULL)) {
12427 			mblk_t	*xmit_mp;
12428 			mblk_t	*old_snxt_mp = snxt_mp;
12429 			uint32_t cnt = mss;
12430 
12431 			if (win < cnt) {
12432 				cnt = win;
12433 			}
12434 			if (SEQ_GT(snxt + cnt, smax)) {
12435 				cnt = smax - snxt;
12436 			}
12437 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12438 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12439 			if (xmit_mp == NULL)
12440 				return;
12441 
12442 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12443 
12444 			snxt += cnt;
12445 			win -= cnt;
12446 			/*
12447 			 * Update the send timestamp to avoid false
12448 			 * retransmission.
12449 			 */
12450 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12451 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
12452 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
12453 
12454 			tcp->tcp_rexmit_nxt = snxt;
12455 			burst--;
12456 		}
12457 		/*
12458 		 * If we have transmitted all we have at the time
12459 		 * we started the retranmission, we can leave
12460 		 * the rest of the job to tcp_wput_data().  But we
12461 		 * need to check the send window first.  If the
12462 		 * win is not 0, go on with tcp_wput_data().
12463 		 */
12464 		if (SEQ_LT(snxt, smax) || win == 0) {
12465 			return;
12466 		}
12467 	}
12468 	/* Only call tcp_wput_data() if there is data to be sent. */
12469 	if (tcp->tcp_unsent) {
12470 		tcp_wput_data(tcp, NULL, B_FALSE);
12471 	}
12472 }
12473 
12474 /*
12475  * Process all TCP option in SYN segment.  Note that this function should
12476  * be called after tcp_adapt_ire() is called so that the necessary info
12477  * from IRE is already set in the tcp structure.
12478  *
12479  * This function sets up the correct tcp_mss value according to the
12480  * MSS option value and our header size.  It also sets up the window scale
12481  * and timestamp values, and initialize SACK info blocks.  But it does not
12482  * change receive window size after setting the tcp_mss value.  The caller
12483  * should do the appropriate change.
12484  */
12485 void
12486 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12487 {
12488 	int options;
12489 	tcp_opt_t tcpopt;
12490 	uint32_t mss_max;
12491 	char *tmp_tcph;
12492 
12493 	tcpopt.tcp = NULL;
12494 	options = tcp_parse_options(tcph, &tcpopt);
12495 
12496 	/*
12497 	 * Process MSS option.  Note that MSS option value does not account
12498 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12499 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12500 	 * IPv6.
12501 	 */
12502 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12503 		if (tcp->tcp_ipversion == IPV4_VERSION)
12504 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
12505 		else
12506 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
12507 	} else {
12508 		if (tcp->tcp_ipversion == IPV4_VERSION)
12509 			mss_max = tcp_mss_max_ipv4;
12510 		else
12511 			mss_max = tcp_mss_max_ipv6;
12512 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
12513 			tcpopt.tcp_opt_mss = tcp_mss_min;
12514 		else if (tcpopt.tcp_opt_mss > mss_max)
12515 			tcpopt.tcp_opt_mss = mss_max;
12516 	}
12517 
12518 	/* Process Window Scale option. */
12519 	if (options & TCP_OPT_WSCALE_PRESENT) {
12520 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12521 		tcp->tcp_snd_ws_ok = B_TRUE;
12522 	} else {
12523 		tcp->tcp_snd_ws = B_FALSE;
12524 		tcp->tcp_snd_ws_ok = B_FALSE;
12525 		tcp->tcp_rcv_ws = B_FALSE;
12526 	}
12527 
12528 	/* Process Timestamp option. */
12529 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12530 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12531 		tmp_tcph = (char *)tcp->tcp_tcph;
12532 
12533 		tcp->tcp_snd_ts_ok = B_TRUE;
12534 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12535 		tcp->tcp_last_rcv_lbolt = lbolt64;
12536 		ASSERT(OK_32PTR(tmp_tcph));
12537 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12538 
12539 		/* Fill in our template header with basic timestamp option. */
12540 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12541 		tmp_tcph[0] = TCPOPT_NOP;
12542 		tmp_tcph[1] = TCPOPT_NOP;
12543 		tmp_tcph[2] = TCPOPT_TSTAMP;
12544 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12545 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12546 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12547 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12548 	} else {
12549 		tcp->tcp_snd_ts_ok = B_FALSE;
12550 	}
12551 
12552 	/*
12553 	 * Process SACK options.  If SACK is enabled for this connection,
12554 	 * then allocate the SACK info structure.  Note the following ways
12555 	 * when tcp_snd_sack_ok is set to true.
12556 	 *
12557 	 * For active connection: in tcp_adapt_ire() called in
12558 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12559 	 * is checked.
12560 	 *
12561 	 * For passive connection: in tcp_adapt_ire() called in
12562 	 * tcp_accept_comm().
12563 	 *
12564 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12565 	 * That check makes sure that if we did not send a SACK OK option,
12566 	 * we will not enable SACK for this connection even though the other
12567 	 * side sends us SACK OK option.  For active connection, the SACK
12568 	 * info structure has already been allocated.  So we need to free
12569 	 * it if SACK is disabled.
12570 	 */
12571 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12572 	    (tcp->tcp_snd_sack_ok ||
12573 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12574 		/* This should be true only in the passive case. */
12575 		if (tcp->tcp_sack_info == NULL) {
12576 			ASSERT(TCP_IS_DETACHED(tcp));
12577 			tcp->tcp_sack_info =
12578 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12579 		}
12580 		if (tcp->tcp_sack_info == NULL) {
12581 			tcp->tcp_snd_sack_ok = B_FALSE;
12582 		} else {
12583 			tcp->tcp_snd_sack_ok = B_TRUE;
12584 			if (tcp->tcp_snd_ts_ok) {
12585 				tcp->tcp_max_sack_blk = 3;
12586 			} else {
12587 				tcp->tcp_max_sack_blk = 4;
12588 			}
12589 		}
12590 	} else {
12591 		/*
12592 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12593 		 * no SACK info will be used for this
12594 		 * connection.  This assumes that SACK usage
12595 		 * permission is negotiated.  This may need
12596 		 * to be changed once this is clarified.
12597 		 */
12598 		if (tcp->tcp_sack_info != NULL) {
12599 			ASSERT(tcp->tcp_notsack_list == NULL);
12600 			kmem_cache_free(tcp_sack_info_cache,
12601 			    tcp->tcp_sack_info);
12602 			tcp->tcp_sack_info = NULL;
12603 		}
12604 		tcp->tcp_snd_sack_ok = B_FALSE;
12605 	}
12606 
12607 	/*
12608 	 * Now we know the exact TCP/IP header length, subtract
12609 	 * that from tcp_mss to get our side's MSS.
12610 	 */
12611 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12612 	/*
12613 	 * Here we assume that the other side's header size will be equal to
12614 	 * our header size.  We calculate the real MSS accordingly.  Need to
12615 	 * take into additional stuffs IPsec puts in.
12616 	 *
12617 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12618 	 */
12619 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12620 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12621 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12622 
12623 	/*
12624 	 * Set MSS to the smaller one of both ends of the connection.
12625 	 * We should not have called tcp_mss_set() before, but our
12626 	 * side of the MSS should have been set to a proper value
12627 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12628 	 * STREAM head parameters properly.
12629 	 *
12630 	 * If we have a larger-than-16-bit window but the other side
12631 	 * didn't want to do window scale, tcp_rwnd_set() will take
12632 	 * care of that.
12633 	 */
12634 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12635 }
12636 
12637 /*
12638  * Sends the T_CONN_IND to the listener. The caller calls this
12639  * functions via squeue to get inside the listener's perimeter
12640  * once the 3 way hand shake is done a T_CONN_IND needs to be
12641  * sent. As an optimization, the caller can call this directly
12642  * if listener's perimeter is same as eager's.
12643  */
12644 /* ARGSUSED */
12645 void
12646 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12647 {
12648 	conn_t			*lconnp = (conn_t *)arg;
12649 	tcp_t			*listener = lconnp->conn_tcp;
12650 	tcp_t			*tcp;
12651 	struct T_conn_ind	*conn_ind;
12652 	ipaddr_t 		*addr_cache;
12653 	boolean_t		need_send_conn_ind = B_FALSE;
12654 
12655 	/* retrieve the eager */
12656 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12657 	ASSERT(conn_ind->OPT_offset != 0 &&
12658 	    conn_ind->OPT_length == sizeof (intptr_t));
12659 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12660 		conn_ind->OPT_length);
12661 
12662 	/*
12663 	 * TLI/XTI applications will get confused by
12664 	 * sending eager as an option since it violates
12665 	 * the option semantics. So remove the eager as
12666 	 * option since TLI/XTI app doesn't need it anyway.
12667 	 */
12668 	if (!TCP_IS_SOCKET(listener)) {
12669 		conn_ind->OPT_length = 0;
12670 		conn_ind->OPT_offset = 0;
12671 	}
12672 	if (listener->tcp_state == TCPS_CLOSED ||
12673 	    TCP_IS_DETACHED(listener)) {
12674 		/*
12675 		 * If listener has closed, it would have caused a
12676 		 * a cleanup/blowoff to happen for the eager. We
12677 		 * just need to return.
12678 		 */
12679 		freemsg(mp);
12680 		return;
12681 	}
12682 
12683 
12684 	/*
12685 	 * if the conn_req_q is full defer passing up the
12686 	 * T_CONN_IND until space is availabe after t_accept()
12687 	 * processing
12688 	 */
12689 	mutex_enter(&listener->tcp_eager_lock);
12690 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12691 		tcp_t *tail;
12692 
12693 		/*
12694 		 * The eager already has an extra ref put in tcp_rput_data
12695 		 * so that it stays till accept comes back even though it
12696 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12697 		 */
12698 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12699 		listener->tcp_conn_req_cnt_q0--;
12700 		listener->tcp_conn_req_cnt_q++;
12701 
12702 		/* Move from SYN_RCVD to ESTABLISHED list  */
12703 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12704 		    tcp->tcp_eager_prev_q0;
12705 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12706 		    tcp->tcp_eager_next_q0;
12707 		tcp->tcp_eager_prev_q0 = NULL;
12708 		tcp->tcp_eager_next_q0 = NULL;
12709 
12710 		/*
12711 		 * Insert at end of the queue because sockfs
12712 		 * sends down T_CONN_RES in chronological
12713 		 * order. Leaving the older conn indications
12714 		 * at front of the queue helps reducing search
12715 		 * time.
12716 		 */
12717 		tail = listener->tcp_eager_last_q;
12718 		if (tail != NULL)
12719 			tail->tcp_eager_next_q = tcp;
12720 		else
12721 			listener->tcp_eager_next_q = tcp;
12722 		listener->tcp_eager_last_q = tcp;
12723 		tcp->tcp_eager_next_q = NULL;
12724 		/*
12725 		 * Delay sending up the T_conn_ind until we are
12726 		 * done with the eager. Once we have have sent up
12727 		 * the T_conn_ind, the accept can potentially complete
12728 		 * any time and release the refhold we have on the eager.
12729 		 */
12730 		need_send_conn_ind = B_TRUE;
12731 	} else {
12732 		/*
12733 		 * Defer connection on q0 and set deferred
12734 		 * connection bit true
12735 		 */
12736 		tcp->tcp_conn_def_q0 = B_TRUE;
12737 
12738 		/* take tcp out of q0 ... */
12739 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12740 		    tcp->tcp_eager_next_q0;
12741 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12742 		    tcp->tcp_eager_prev_q0;
12743 
12744 		/* ... and place it at the end of q0 */
12745 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12746 		tcp->tcp_eager_next_q0 = listener;
12747 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12748 		listener->tcp_eager_prev_q0 = tcp;
12749 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12750 	}
12751 
12752 	/* we have timed out before */
12753 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12754 		tcp->tcp_syn_rcvd_timeout = 0;
12755 		listener->tcp_syn_rcvd_timeout--;
12756 		if (listener->tcp_syn_defense &&
12757 		    listener->tcp_syn_rcvd_timeout <=
12758 		    (tcp_conn_req_max_q0 >> 5) &&
12759 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12760 			listener->tcp_last_rcv_lbolt)) {
12761 			/*
12762 			 * Turn off the defense mode if we
12763 			 * believe the SYN attack is over.
12764 			 */
12765 			listener->tcp_syn_defense = B_FALSE;
12766 			if (listener->tcp_ip_addr_cache) {
12767 				kmem_free((void *)listener->tcp_ip_addr_cache,
12768 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12769 				listener->tcp_ip_addr_cache = NULL;
12770 			}
12771 		}
12772 	}
12773 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12774 	if (addr_cache != NULL) {
12775 		/*
12776 		 * We have finished a 3-way handshake with this
12777 		 * remote host. This proves the IP addr is good.
12778 		 * Cache it!
12779 		 */
12780 		addr_cache[IP_ADDR_CACHE_HASH(
12781 			tcp->tcp_remote)] = tcp->tcp_remote;
12782 	}
12783 	mutex_exit(&listener->tcp_eager_lock);
12784 	if (need_send_conn_ind)
12785 		putnext(listener->tcp_rq, mp);
12786 }
12787 
12788 mblk_t *
12789 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12790     uint_t *ifindexp, ip6_pkt_t *ippp)
12791 {
12792 	in_pktinfo_t	*pinfo;
12793 	ip6_t		*ip6h;
12794 	uchar_t		*rptr;
12795 	mblk_t		*first_mp = mp;
12796 	boolean_t	mctl_present = B_FALSE;
12797 	uint_t 		ifindex = 0;
12798 	ip6_pkt_t	ipp;
12799 	uint_t		ipvers;
12800 	uint_t		ip_hdr_len;
12801 
12802 	rptr = mp->b_rptr;
12803 	ASSERT(OK_32PTR(rptr));
12804 	ASSERT(tcp != NULL);
12805 	ipp.ipp_fields = 0;
12806 
12807 	switch DB_TYPE(mp) {
12808 	case M_CTL:
12809 		mp = mp->b_cont;
12810 		if (mp == NULL) {
12811 			freemsg(first_mp);
12812 			return (NULL);
12813 		}
12814 		if (DB_TYPE(mp) != M_DATA) {
12815 			freemsg(first_mp);
12816 			return (NULL);
12817 		}
12818 		mctl_present = B_TRUE;
12819 		break;
12820 	case M_DATA:
12821 		break;
12822 	default:
12823 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12824 		freemsg(mp);
12825 		return (NULL);
12826 	}
12827 	ipvers = IPH_HDR_VERSION(rptr);
12828 	if (ipvers == IPV4_VERSION) {
12829 		if (tcp == NULL) {
12830 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12831 			goto done;
12832 		}
12833 
12834 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12835 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12836 
12837 		/*
12838 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12839 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12840 		 */
12841 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12842 		    mctl_present) {
12843 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12844 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12845 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12846 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12847 				ipp.ipp_fields |= IPPF_IFINDEX;
12848 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12849 				ifindex = pinfo->in_pkt_ifindex;
12850 			}
12851 			freeb(first_mp);
12852 			mctl_present = B_FALSE;
12853 		}
12854 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12855 	} else {
12856 		ip6h = (ip6_t *)rptr;
12857 
12858 		ASSERT(ipvers == IPV6_VERSION);
12859 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12860 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12861 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12862 
12863 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12864 			uint8_t	nexthdrp;
12865 
12866 			/* Look for ifindex information */
12867 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12868 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12869 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12870 					BUMP_MIB(&ip_mib, tcpInErrs);
12871 					freemsg(first_mp);
12872 					return (NULL);
12873 				}
12874 
12875 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12876 					ASSERT(ip6i->ip6i_ifindex != 0);
12877 					ipp.ipp_fields |= IPPF_IFINDEX;
12878 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12879 					ifindex = ip6i->ip6i_ifindex;
12880 				}
12881 				rptr = (uchar_t *)&ip6i[1];
12882 				mp->b_rptr = rptr;
12883 				if (rptr == mp->b_wptr) {
12884 					mblk_t *mp1;
12885 					mp1 = mp->b_cont;
12886 					freeb(mp);
12887 					mp = mp1;
12888 					rptr = mp->b_rptr;
12889 				}
12890 				if (MBLKL(mp) < IPV6_HDR_LEN +
12891 				    sizeof (tcph_t)) {
12892 					BUMP_MIB(&ip_mib, tcpInErrs);
12893 					freemsg(first_mp);
12894 					return (NULL);
12895 				}
12896 				ip6h = (ip6_t *)rptr;
12897 			}
12898 
12899 			/*
12900 			 * Find any potentially interesting extension headers
12901 			 * as well as the length of the IPv6 + extension
12902 			 * headers.
12903 			 */
12904 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12905 			/* Verify if this is a TCP packet */
12906 			if (nexthdrp != IPPROTO_TCP) {
12907 				BUMP_MIB(&ip_mib, tcpInErrs);
12908 				freemsg(first_mp);
12909 				return (NULL);
12910 			}
12911 		} else {
12912 			ip_hdr_len = IPV6_HDR_LEN;
12913 		}
12914 	}
12915 
12916 done:
12917 	if (ipversp != NULL)
12918 		*ipversp = ipvers;
12919 	if (ip_hdr_lenp != NULL)
12920 		*ip_hdr_lenp = ip_hdr_len;
12921 	if (ippp != NULL)
12922 		*ippp = ipp;
12923 	if (ifindexp != NULL)
12924 		*ifindexp = ifindex;
12925 	if (mctl_present) {
12926 		freeb(first_mp);
12927 	}
12928 	return (mp);
12929 }
12930 
12931 /*
12932  * Handle M_DATA messages from IP. Its called directly from IP via
12933  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12934  * in this path.
12935  *
12936  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12937  * v4 and v6), we are called through tcp_input() and a M_CTL can
12938  * be present for options but tcp_find_pktinfo() deals with it. We
12939  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12940  *
12941  * The first argument is always the connp/tcp to which the mp belongs.
12942  * There are no exceptions to this rule. The caller has already put
12943  * a reference on this connp/tcp and once tcp_rput_data() returns,
12944  * the squeue will do the refrele.
12945  *
12946  * The TH_SYN for the listener directly go to tcp_conn_request via
12947  * squeue.
12948  *
12949  * sqp: NULL = recursive, sqp != NULL means called from squeue
12950  */
12951 void
12952 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12953 {
12954 	int32_t		bytes_acked;
12955 	int32_t		gap;
12956 	mblk_t		*mp1;
12957 	uint_t		flags;
12958 	uint32_t	new_swnd = 0;
12959 	uchar_t		*iphdr;
12960 	uchar_t		*rptr;
12961 	int32_t		rgap;
12962 	uint32_t	seg_ack;
12963 	int		seg_len;
12964 	uint_t		ip_hdr_len;
12965 	uint32_t	seg_seq;
12966 	tcph_t		*tcph;
12967 	int		urp;
12968 	tcp_opt_t	tcpopt;
12969 	uint_t		ipvers;
12970 	ip6_pkt_t	ipp;
12971 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12972 	uint32_t	cwnd;
12973 	uint32_t	add;
12974 	int		npkt;
12975 	int		mss;
12976 	conn_t		*connp = (conn_t *)arg;
12977 	squeue_t	*sqp = (squeue_t *)arg2;
12978 	tcp_t		*tcp = connp->conn_tcp;
12979 
12980 	/*
12981 	 * RST from fused tcp loopback peer should trigger an unfuse.
12982 	 */
12983 	if (tcp->tcp_fused) {
12984 		TCP_STAT(tcp_fusion_aborted);
12985 		tcp_unfuse(tcp);
12986 	}
12987 
12988 	iphdr = mp->b_rptr;
12989 	rptr = mp->b_rptr;
12990 	ASSERT(OK_32PTR(rptr));
12991 
12992 	/*
12993 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12994 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12995 	 * necessary information.
12996 	 */
12997 	if (IPCL_IS_TCP4(connp)) {
12998 		ipvers = IPV4_VERSION;
12999 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13000 	} else {
13001 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13002 		    NULL, &ipp);
13003 		if (mp == NULL) {
13004 			TCP_STAT(tcp_rput_v6_error);
13005 			return;
13006 		}
13007 		iphdr = mp->b_rptr;
13008 		rptr = mp->b_rptr;
13009 	}
13010 	ASSERT(DB_TYPE(mp) == M_DATA);
13011 
13012 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13013 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13014 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13015 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13016 	seg_len = (int)(mp->b_wptr - rptr) -
13017 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13018 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13019 		do {
13020 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13021 			    (uintptr_t)INT_MAX);
13022 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13023 		} while ((mp1 = mp1->b_cont) != NULL &&
13024 		    mp1->b_datap->db_type == M_DATA);
13025 	}
13026 
13027 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13028 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13029 		    seg_len, tcph);
13030 		return;
13031 	}
13032 
13033 	if (sqp != NULL) {
13034 		/*
13035 		 * This is the correct place to update tcp_last_recv_time. Note
13036 		 * that it is also updated for tcp structure that belongs to
13037 		 * global and listener queues which do not really need updating.
13038 		 * But that should not cause any harm.  And it is updated for
13039 		 * all kinds of incoming segments, not only for data segments.
13040 		 */
13041 		tcp->tcp_last_recv_time = lbolt;
13042 	}
13043 
13044 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13045 
13046 	BUMP_LOCAL(tcp->tcp_ibsegs);
13047 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
13048 
13049 	if ((flags & TH_URG) && sqp != NULL) {
13050 		/*
13051 		 * TCP can't handle urgent pointers that arrive before
13052 		 * the connection has been accept()ed since it can't
13053 		 * buffer OOB data.  Discard segment if this happens.
13054 		 *
13055 		 * Nor can it reassemble urgent pointers, so discard
13056 		 * if it's not the next segment expected.
13057 		 *
13058 		 * Otherwise, collapse chain into one mblk (discard if
13059 		 * that fails).  This makes sure the headers, retransmitted
13060 		 * data, and new data all are in the same mblk.
13061 		 */
13062 		ASSERT(mp != NULL);
13063 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
13064 			freemsg(mp);
13065 			return;
13066 		}
13067 		/* Update pointers into message */
13068 		iphdr = rptr = mp->b_rptr;
13069 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13070 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13071 			/*
13072 			 * Since we can't handle any data with this urgent
13073 			 * pointer that is out of sequence, we expunge
13074 			 * the data.  This allows us to still register
13075 			 * the urgent mark and generate the M_PCSIG,
13076 			 * which we can do.
13077 			 */
13078 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13079 			seg_len = 0;
13080 		}
13081 	}
13082 
13083 	switch (tcp->tcp_state) {
13084 	case TCPS_SYN_SENT:
13085 		if (flags & TH_ACK) {
13086 			/*
13087 			 * Note that our stack cannot send data before a
13088 			 * connection is established, therefore the
13089 			 * following check is valid.  Otherwise, it has
13090 			 * to be changed.
13091 			 */
13092 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13093 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13094 				freemsg(mp);
13095 				if (flags & TH_RST)
13096 					return;
13097 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13098 				    tcp, seg_ack, 0, TH_RST);
13099 				return;
13100 			}
13101 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13102 		}
13103 		if (flags & TH_RST) {
13104 			freemsg(mp);
13105 			if (flags & TH_ACK)
13106 				(void) tcp_clean_death(tcp,
13107 				    ECONNREFUSED, 13);
13108 			return;
13109 		}
13110 		if (!(flags & TH_SYN)) {
13111 			freemsg(mp);
13112 			return;
13113 		}
13114 
13115 		/* Process all TCP options. */
13116 		tcp_process_options(tcp, tcph);
13117 		/*
13118 		 * The following changes our rwnd to be a multiple of the
13119 		 * MIN(peer MSS, our MSS) for performance reason.
13120 		 */
13121 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13122 		    tcp->tcp_mss));
13123 
13124 		/* Is the other end ECN capable? */
13125 		if (tcp->tcp_ecn_ok) {
13126 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13127 				tcp->tcp_ecn_ok = B_FALSE;
13128 			}
13129 		}
13130 		/*
13131 		 * Clear ECN flags because it may interfere with later
13132 		 * processing.
13133 		 */
13134 		flags &= ~(TH_ECE|TH_CWR);
13135 
13136 		tcp->tcp_irs = seg_seq;
13137 		tcp->tcp_rack = seg_seq;
13138 		tcp->tcp_rnxt = seg_seq + 1;
13139 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13140 		if (!TCP_IS_DETACHED(tcp)) {
13141 			/* Allocate room for SACK options if needed. */
13142 			if (tcp->tcp_snd_sack_ok) {
13143 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13144 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13145 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13146 			} else {
13147 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13148 				    tcp->tcp_hdr_len +
13149 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13150 			}
13151 		}
13152 		if (flags & TH_ACK) {
13153 			/*
13154 			 * If we can't get the confirmation upstream, pretend
13155 			 * we didn't even see this one.
13156 			 *
13157 			 * XXX: how can we pretend we didn't see it if we
13158 			 * have updated rnxt et. al.
13159 			 *
13160 			 * For loopback we defer sending up the T_CONN_CON
13161 			 * until after some checks below.
13162 			 */
13163 			mp1 = NULL;
13164 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13165 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13166 				freemsg(mp);
13167 				return;
13168 			}
13169 			/* SYN was acked - making progress */
13170 			if (tcp->tcp_ipversion == IPV6_VERSION)
13171 				tcp->tcp_ip_forward_progress = B_TRUE;
13172 
13173 			/* One for the SYN */
13174 			tcp->tcp_suna = tcp->tcp_iss + 1;
13175 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13176 			tcp->tcp_state = TCPS_ESTABLISHED;
13177 
13178 			/*
13179 			 * If SYN was retransmitted, need to reset all
13180 			 * retransmission info.  This is because this
13181 			 * segment will be treated as a dup ACK.
13182 			 */
13183 			if (tcp->tcp_rexmit) {
13184 				tcp->tcp_rexmit = B_FALSE;
13185 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13186 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13187 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13188 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13189 				tcp->tcp_ms_we_have_waited = 0;
13190 
13191 				/*
13192 				 * Set tcp_cwnd back to 1 MSS, per
13193 				 * recommendation from
13194 				 * draft-floyd-incr-init-win-01.txt,
13195 				 * Increasing TCP's Initial Window.
13196 				 */
13197 				tcp->tcp_cwnd = tcp->tcp_mss;
13198 			}
13199 
13200 			tcp->tcp_swl1 = seg_seq;
13201 			tcp->tcp_swl2 = seg_ack;
13202 
13203 			new_swnd = BE16_TO_U16(tcph->th_win);
13204 			tcp->tcp_swnd = new_swnd;
13205 			if (new_swnd > tcp->tcp_max_swnd)
13206 				tcp->tcp_max_swnd = new_swnd;
13207 
13208 			/*
13209 			 * Always send the three-way handshake ack immediately
13210 			 * in order to make the connection complete as soon as
13211 			 * possible on the accepting host.
13212 			 */
13213 			flags |= TH_ACK_NEEDED;
13214 
13215 			/*
13216 			 * Special case for loopback.  At this point we have
13217 			 * received SYN-ACK from the remote endpoint.  In
13218 			 * order to ensure that both endpoints reach the
13219 			 * fused state prior to any data exchange, the final
13220 			 * ACK needs to be sent before we indicate T_CONN_CON
13221 			 * to the module upstream.
13222 			 */
13223 			if (tcp->tcp_loopback) {
13224 				mblk_t *ack_mp;
13225 
13226 				ASSERT(!tcp->tcp_unfusable);
13227 				ASSERT(mp1 != NULL);
13228 				/*
13229 				 * For loopback, we always get a pure SYN-ACK
13230 				 * and only need to send back the final ACK
13231 				 * with no data (this is because the other
13232 				 * tcp is ours and we don't do T/TCP).  This
13233 				 * final ACK triggers the passive side to
13234 				 * perform fusion in ESTABLISHED state.
13235 				 */
13236 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13237 					if (tcp->tcp_ack_tid != 0) {
13238 						(void) TCP_TIMER_CANCEL(tcp,
13239 						    tcp->tcp_ack_tid);
13240 						tcp->tcp_ack_tid = 0;
13241 					}
13242 					TCP_RECORD_TRACE(tcp, ack_mp,
13243 					    TCP_TRACE_SEND_PKT);
13244 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13245 					BUMP_LOCAL(tcp->tcp_obsegs);
13246 					BUMP_MIB(&tcp_mib, tcpOutAck);
13247 
13248 					/* Send up T_CONN_CON */
13249 					putnext(tcp->tcp_rq, mp1);
13250 
13251 					freemsg(mp);
13252 					return;
13253 				}
13254 				/*
13255 				 * Forget fusion; we need to handle more
13256 				 * complex cases below.  Send the deferred
13257 				 * T_CONN_CON message upstream and proceed
13258 				 * as usual.  Mark this tcp as not capable
13259 				 * of fusion.
13260 				 */
13261 				TCP_STAT(tcp_fusion_unfusable);
13262 				tcp->tcp_unfusable = B_TRUE;
13263 				putnext(tcp->tcp_rq, mp1);
13264 			}
13265 
13266 			/*
13267 			 * Check to see if there is data to be sent.  If
13268 			 * yes, set the transmit flag.  Then check to see
13269 			 * if received data processing needs to be done.
13270 			 * If not, go straight to xmit_check.  This short
13271 			 * cut is OK as we don't support T/TCP.
13272 			 */
13273 			if (tcp->tcp_unsent)
13274 				flags |= TH_XMIT_NEEDED;
13275 
13276 			if (seg_len == 0 && !(flags & TH_URG)) {
13277 				freemsg(mp);
13278 				goto xmit_check;
13279 			}
13280 
13281 			flags &= ~TH_SYN;
13282 			seg_seq++;
13283 			break;
13284 		}
13285 		tcp->tcp_state = TCPS_SYN_RCVD;
13286 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13287 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13288 		if (mp1) {
13289 			mblk_setcred(mp1, tcp->tcp_cred);
13290 			DB_CPID(mp1) = tcp->tcp_cpid;
13291 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13292 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13293 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13294 		}
13295 		freemsg(mp);
13296 		return;
13297 	case TCPS_SYN_RCVD:
13298 		if (flags & TH_ACK) {
13299 			/*
13300 			 * In this state, a SYN|ACK packet is either bogus
13301 			 * because the other side must be ACKing our SYN which
13302 			 * indicates it has seen the ACK for their SYN and
13303 			 * shouldn't retransmit it or we're crossing SYNs
13304 			 * on active open.
13305 			 */
13306 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13307 				freemsg(mp);
13308 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13309 				    tcp, seg_ack, 0, TH_RST);
13310 				return;
13311 			}
13312 			/*
13313 			 * NOTE: RFC 793 pg. 72 says this should be
13314 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13315 			 * but that would mean we have an ack that ignored
13316 			 * our SYN.
13317 			 */
13318 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13319 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13320 				freemsg(mp);
13321 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13322 				    tcp, seg_ack, 0, TH_RST);
13323 				return;
13324 			}
13325 		}
13326 		break;
13327 	case TCPS_LISTEN:
13328 		/*
13329 		 * Only a TLI listener can come through this path when a
13330 		 * acceptor is going back to be a listener and a packet
13331 		 * for the acceptor hits the classifier. For a socket
13332 		 * listener, this can never happen because a listener
13333 		 * can never accept connection on itself and hence a
13334 		 * socket acceptor can not go back to being a listener.
13335 		 */
13336 		ASSERT(!TCP_IS_SOCKET(tcp));
13337 		/*FALLTHRU*/
13338 	case TCPS_CLOSED:
13339 	case TCPS_BOUND: {
13340 		conn_t	*new_connp;
13341 
13342 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
13343 		if (new_connp != NULL) {
13344 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13345 			return;
13346 		}
13347 		/* We failed to classify. For now just drop the packet */
13348 		freemsg(mp);
13349 		return;
13350 	}
13351 	case TCPS_IDLE:
13352 		/*
13353 		 * Handle the case where the tcp_clean_death() has happened
13354 		 * on a connection (application hasn't closed yet) but a packet
13355 		 * was already queued on squeue before tcp_clean_death()
13356 		 * was processed. Calling tcp_clean_death() twice on same
13357 		 * connection can result in weird behaviour.
13358 		 */
13359 		freemsg(mp);
13360 		return;
13361 	default:
13362 		break;
13363 	}
13364 
13365 	/*
13366 	 * Already on the correct queue/perimeter.
13367 	 * If this is a detached connection and not an eager
13368 	 * connection hanging off a listener then new data
13369 	 * (past the FIN) will cause a reset.
13370 	 * We do a special check here where it
13371 	 * is out of the main line, rather than check
13372 	 * if we are detached every time we see new
13373 	 * data down below.
13374 	 */
13375 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13376 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13377 		BUMP_MIB(&tcp_mib, tcpInClosed);
13378 		TCP_RECORD_TRACE(tcp,
13379 		    mp, TCP_TRACE_RECV_PKT);
13380 		freemsg(mp);
13381 		tcp_xmit_ctl("new data when detached", tcp,
13382 		    tcp->tcp_snxt, 0, TH_RST);
13383 		(void) tcp_clean_death(tcp, EPROTO, 12);
13384 		return;
13385 	}
13386 
13387 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13388 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13389 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13390 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13391 	mss = tcp->tcp_mss;
13392 
13393 	if (tcp->tcp_snd_ts_ok) {
13394 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13395 			/*
13396 			 * This segment is not acceptable.
13397 			 * Drop it and send back an ACK.
13398 			 */
13399 			freemsg(mp);
13400 			flags |= TH_ACK_NEEDED;
13401 			goto ack_check;
13402 		}
13403 	} else if (tcp->tcp_snd_sack_ok) {
13404 		ASSERT(tcp->tcp_sack_info != NULL);
13405 		tcpopt.tcp = tcp;
13406 		/*
13407 		 * SACK info in already updated in tcp_parse_options.  Ignore
13408 		 * all other TCP options...
13409 		 */
13410 		(void) tcp_parse_options(tcph, &tcpopt);
13411 	}
13412 try_again:;
13413 	gap = seg_seq - tcp->tcp_rnxt;
13414 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13415 	/*
13416 	 * gap is the amount of sequence space between what we expect to see
13417 	 * and what we got for seg_seq.  A positive value for gap means
13418 	 * something got lost.  A negative value means we got some old stuff.
13419 	 */
13420 	if (gap < 0) {
13421 		/* Old stuff present.  Is the SYN in there? */
13422 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13423 		    (seg_len != 0)) {
13424 			flags &= ~TH_SYN;
13425 			seg_seq++;
13426 			urp--;
13427 			/* Recompute the gaps after noting the SYN. */
13428 			goto try_again;
13429 		}
13430 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
13431 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
13432 		    (seg_len > -gap ? -gap : seg_len));
13433 		/* Remove the old stuff from seg_len. */
13434 		seg_len += gap;
13435 		/*
13436 		 * Anything left?
13437 		 * Make sure to check for unack'd FIN when rest of data
13438 		 * has been previously ack'd.
13439 		 */
13440 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13441 			/*
13442 			 * Resets are only valid if they lie within our offered
13443 			 * window.  If the RST bit is set, we just ignore this
13444 			 * segment.
13445 			 */
13446 			if (flags & TH_RST) {
13447 				freemsg(mp);
13448 				return;
13449 			}
13450 
13451 			/*
13452 			 * The arriving of dup data packets indicate that we
13453 			 * may have postponed an ack for too long, or the other
13454 			 * side's RTT estimate is out of shape. Start acking
13455 			 * more often.
13456 			 */
13457 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13458 			    tcp->tcp_rack_cnt >= 1 &&
13459 			    tcp->tcp_rack_abs_max > 2) {
13460 				tcp->tcp_rack_abs_max--;
13461 			}
13462 			tcp->tcp_rack_cur_max = 1;
13463 
13464 			/*
13465 			 * This segment is "unacceptable".  None of its
13466 			 * sequence space lies within our advertized window.
13467 			 *
13468 			 * Adjust seg_len to the original value for tracing.
13469 			 */
13470 			seg_len -= gap;
13471 			if (tcp->tcp_debug) {
13472 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13473 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13474 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13475 				    "seg_len %d, rnxt %u, snxt %u, %s",
13476 				    gap, rgap, flags, seg_seq, seg_ack,
13477 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13478 				    tcp_display(tcp, NULL,
13479 				    DISP_ADDR_AND_PORT));
13480 			}
13481 
13482 			/*
13483 			 * Arrange to send an ACK in response to the
13484 			 * unacceptable segment per RFC 793 page 69. There
13485 			 * is only one small difference between ours and the
13486 			 * acceptability test in the RFC - we accept ACK-only
13487 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13488 			 * will be generated.
13489 			 *
13490 			 * Note that we have to ACK an ACK-only packet at least
13491 			 * for stacks that send 0-length keep-alives with
13492 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13493 			 * section 4.2.3.6. As long as we don't ever generate
13494 			 * an unacceptable packet in response to an incoming
13495 			 * packet that is unacceptable, it should not cause
13496 			 * "ACK wars".
13497 			 */
13498 			flags |=  TH_ACK_NEEDED;
13499 
13500 			/*
13501 			 * Continue processing this segment in order to use the
13502 			 * ACK information it contains, but skip all other
13503 			 * sequence-number processing.	Processing the ACK
13504 			 * information is necessary in order to
13505 			 * re-synchronize connections that may have lost
13506 			 * synchronization.
13507 			 *
13508 			 * We clear seg_len and flag fields related to
13509 			 * sequence number processing as they are not
13510 			 * to be trusted for an unacceptable segment.
13511 			 */
13512 			seg_len = 0;
13513 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13514 			goto process_ack;
13515 		}
13516 
13517 		/* Fix seg_seq, and chew the gap off the front. */
13518 		seg_seq = tcp->tcp_rnxt;
13519 		urp += gap;
13520 		do {
13521 			mblk_t	*mp2;
13522 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13523 			    (uintptr_t)UINT_MAX);
13524 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13525 			if (gap > 0) {
13526 				mp->b_rptr = mp->b_wptr - gap;
13527 				break;
13528 			}
13529 			mp2 = mp;
13530 			mp = mp->b_cont;
13531 			freeb(mp2);
13532 		} while (gap < 0);
13533 		/*
13534 		 * If the urgent data has already been acknowledged, we
13535 		 * should ignore TH_URG below
13536 		 */
13537 		if (urp < 0)
13538 			flags &= ~TH_URG;
13539 	}
13540 	/*
13541 	 * rgap is the amount of stuff received out of window.  A negative
13542 	 * value is the amount out of window.
13543 	 */
13544 	if (rgap < 0) {
13545 		mblk_t	*mp2;
13546 
13547 		if (tcp->tcp_rwnd == 0) {
13548 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13549 		} else {
13550 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13551 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13552 		}
13553 
13554 		/*
13555 		 * seg_len does not include the FIN, so if more than
13556 		 * just the FIN is out of window, we act like we don't
13557 		 * see it.  (If just the FIN is out of window, rgap
13558 		 * will be zero and we will go ahead and acknowledge
13559 		 * the FIN.)
13560 		 */
13561 		flags &= ~TH_FIN;
13562 
13563 		/* Fix seg_len and make sure there is something left. */
13564 		seg_len += rgap;
13565 		if (seg_len <= 0) {
13566 			/*
13567 			 * Resets are only valid if they lie within our offered
13568 			 * window.  If the RST bit is set, we just ignore this
13569 			 * segment.
13570 			 */
13571 			if (flags & TH_RST) {
13572 				freemsg(mp);
13573 				return;
13574 			}
13575 
13576 			/* Per RFC 793, we need to send back an ACK. */
13577 			flags |= TH_ACK_NEEDED;
13578 
13579 			/*
13580 			 * Send SIGURG as soon as possible i.e. even
13581 			 * if the TH_URG was delivered in a window probe
13582 			 * packet (which will be unacceptable).
13583 			 *
13584 			 * We generate a signal if none has been generated
13585 			 * for this connection or if this is a new urgent
13586 			 * byte. Also send a zero-length "unmarked" message
13587 			 * to inform SIOCATMARK that this is not the mark.
13588 			 *
13589 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13590 			 * is sent up. This plus the check for old data
13591 			 * (gap >= 0) handles the wraparound of the sequence
13592 			 * number space without having to always track the
13593 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13594 			 * this max in its rcv_up variable).
13595 			 *
13596 			 * This prevents duplicate SIGURGS due to a "late"
13597 			 * zero-window probe when the T_EXDATA_IND has already
13598 			 * been sent up.
13599 			 */
13600 			if ((flags & TH_URG) &&
13601 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13602 			    tcp->tcp_urp_last))) {
13603 				mp1 = allocb(0, BPRI_MED);
13604 				if (mp1 == NULL) {
13605 					freemsg(mp);
13606 					return;
13607 				}
13608 				if (!TCP_IS_DETACHED(tcp) &&
13609 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13610 				    SIGURG)) {
13611 					/* Try again on the rexmit. */
13612 					freemsg(mp1);
13613 					freemsg(mp);
13614 					return;
13615 				}
13616 				/*
13617 				 * If the next byte would be the mark
13618 				 * then mark with MARKNEXT else mark
13619 				 * with NOTMARKNEXT.
13620 				 */
13621 				if (gap == 0 && urp == 0)
13622 					mp1->b_flag |= MSGMARKNEXT;
13623 				else
13624 					mp1->b_flag |= MSGNOTMARKNEXT;
13625 				freemsg(tcp->tcp_urp_mark_mp);
13626 				tcp->tcp_urp_mark_mp = mp1;
13627 				flags |= TH_SEND_URP_MARK;
13628 				tcp->tcp_urp_last_valid = B_TRUE;
13629 				tcp->tcp_urp_last = urp + seg_seq;
13630 			}
13631 			/*
13632 			 * If this is a zero window probe, continue to
13633 			 * process the ACK part.  But we need to set seg_len
13634 			 * to 0 to avoid data processing.  Otherwise just
13635 			 * drop the segment and send back an ACK.
13636 			 */
13637 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13638 				flags &= ~(TH_SYN | TH_URG);
13639 				seg_len = 0;
13640 				goto process_ack;
13641 			} else {
13642 				freemsg(mp);
13643 				goto ack_check;
13644 			}
13645 		}
13646 		/* Pitch out of window stuff off the end. */
13647 		rgap = seg_len;
13648 		mp2 = mp;
13649 		do {
13650 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13651 			    (uintptr_t)INT_MAX);
13652 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13653 			if (rgap < 0) {
13654 				mp2->b_wptr += rgap;
13655 				if ((mp1 = mp2->b_cont) != NULL) {
13656 					mp2->b_cont = NULL;
13657 					freemsg(mp1);
13658 				}
13659 				break;
13660 			}
13661 		} while ((mp2 = mp2->b_cont) != NULL);
13662 	}
13663 ok:;
13664 	/*
13665 	 * TCP should check ECN info for segments inside the window only.
13666 	 * Therefore the check should be done here.
13667 	 */
13668 	if (tcp->tcp_ecn_ok) {
13669 		if (flags & TH_CWR) {
13670 			tcp->tcp_ecn_echo_on = B_FALSE;
13671 		}
13672 		/*
13673 		 * Note that both ECN_CE and CWR can be set in the
13674 		 * same segment.  In this case, we once again turn
13675 		 * on ECN_ECHO.
13676 		 */
13677 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13678 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13679 
13680 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13681 				tcp->tcp_ecn_echo_on = B_TRUE;
13682 			}
13683 		} else {
13684 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13685 
13686 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13687 			    htonl(IPH_ECN_CE << 20)) {
13688 				tcp->tcp_ecn_echo_on = B_TRUE;
13689 			}
13690 		}
13691 	}
13692 
13693 	/*
13694 	 * Check whether we can update tcp_ts_recent.  This test is
13695 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13696 	 * Extensions for High Performance: An Update", Internet Draft.
13697 	 */
13698 	if (tcp->tcp_snd_ts_ok &&
13699 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13700 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13701 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13702 		tcp->tcp_last_rcv_lbolt = lbolt64;
13703 	}
13704 
13705 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13706 		/*
13707 		 * FIN in an out of order segment.  We record this in
13708 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13709 		 * Clear the FIN so that any check on FIN flag will fail.
13710 		 * Remember that FIN also counts in the sequence number
13711 		 * space.  So we need to ack out of order FIN only segments.
13712 		 */
13713 		if (flags & TH_FIN) {
13714 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13715 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13716 			flags &= ~TH_FIN;
13717 			flags |= TH_ACK_NEEDED;
13718 		}
13719 		if (seg_len > 0) {
13720 			/* Fill in the SACK blk list. */
13721 			if (tcp->tcp_snd_sack_ok) {
13722 				ASSERT(tcp->tcp_sack_info != NULL);
13723 				tcp_sack_insert(tcp->tcp_sack_list,
13724 				    seg_seq, seg_seq + seg_len,
13725 				    &(tcp->tcp_num_sack_blk));
13726 			}
13727 
13728 			/*
13729 			 * Attempt reassembly and see if we have something
13730 			 * ready to go.
13731 			 */
13732 			mp = tcp_reass(tcp, mp, seg_seq);
13733 			/* Always ack out of order packets */
13734 			flags |= TH_ACK_NEEDED | TH_PUSH;
13735 			if (mp) {
13736 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13737 				    (uintptr_t)INT_MAX);
13738 				seg_len = mp->b_cont ? msgdsize(mp) :
13739 					(int)(mp->b_wptr - mp->b_rptr);
13740 				seg_seq = tcp->tcp_rnxt;
13741 				/*
13742 				 * A gap is filled and the seq num and len
13743 				 * of the gap match that of a previously
13744 				 * received FIN, put the FIN flag back in.
13745 				 */
13746 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13747 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13748 					flags |= TH_FIN;
13749 					tcp->tcp_valid_bits &=
13750 					    ~TCP_OFO_FIN_VALID;
13751 				}
13752 			} else {
13753 				/*
13754 				 * Keep going even with NULL mp.
13755 				 * There may be a useful ACK or something else
13756 				 * we don't want to miss.
13757 				 *
13758 				 * But TCP should not perform fast retransmit
13759 				 * because of the ack number.  TCP uses
13760 				 * seg_len == 0 to determine if it is a pure
13761 				 * ACK.  And this is not a pure ACK.
13762 				 */
13763 				seg_len = 0;
13764 				ofo_seg = B_TRUE;
13765 			}
13766 		}
13767 	} else if (seg_len > 0) {
13768 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13769 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13770 		/*
13771 		 * If an out of order FIN was received before, and the seq
13772 		 * num and len of the new segment match that of the FIN,
13773 		 * put the FIN flag back in.
13774 		 */
13775 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13776 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13777 			flags |= TH_FIN;
13778 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13779 		}
13780 	}
13781 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13782 	if (flags & TH_RST) {
13783 		freemsg(mp);
13784 		switch (tcp->tcp_state) {
13785 		case TCPS_SYN_RCVD:
13786 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13787 			break;
13788 		case TCPS_ESTABLISHED:
13789 		case TCPS_FIN_WAIT_1:
13790 		case TCPS_FIN_WAIT_2:
13791 		case TCPS_CLOSE_WAIT:
13792 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13793 			break;
13794 		case TCPS_CLOSING:
13795 		case TCPS_LAST_ACK:
13796 			(void) tcp_clean_death(tcp, 0, 16);
13797 			break;
13798 		default:
13799 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13800 			(void) tcp_clean_death(tcp, ENXIO, 17);
13801 			break;
13802 		}
13803 		return;
13804 	}
13805 	if (flags & TH_SYN) {
13806 		/*
13807 		 * See RFC 793, Page 71
13808 		 *
13809 		 * The seq number must be in the window as it should
13810 		 * be "fixed" above.  If it is outside window, it should
13811 		 * be already rejected.  Note that we allow seg_seq to be
13812 		 * rnxt + rwnd because we want to accept 0 window probe.
13813 		 */
13814 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13815 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13816 		freemsg(mp);
13817 		/*
13818 		 * If the ACK flag is not set, just use our snxt as the
13819 		 * seq number of the RST segment.
13820 		 */
13821 		if (!(flags & TH_ACK)) {
13822 			seg_ack = tcp->tcp_snxt;
13823 		}
13824 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13825 		    TH_RST|TH_ACK);
13826 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13827 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13828 		return;
13829 	}
13830 	/*
13831 	 * urp could be -1 when the urp field in the packet is 0
13832 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13833 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13834 	 */
13835 	if (flags & TH_URG && urp >= 0) {
13836 		if (!tcp->tcp_urp_last_valid ||
13837 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13838 			/*
13839 			 * If we haven't generated the signal yet for this
13840 			 * urgent pointer value, do it now.  Also, send up a
13841 			 * zero-length M_DATA indicating whether or not this is
13842 			 * the mark. The latter is not needed when a
13843 			 * T_EXDATA_IND is sent up. However, if there are
13844 			 * allocation failures this code relies on the sender
13845 			 * retransmitting and the socket code for determining
13846 			 * the mark should not block waiting for the peer to
13847 			 * transmit. Thus, for simplicity we always send up the
13848 			 * mark indication.
13849 			 */
13850 			mp1 = allocb(0, BPRI_MED);
13851 			if (mp1 == NULL) {
13852 				freemsg(mp);
13853 				return;
13854 			}
13855 			if (!TCP_IS_DETACHED(tcp) &&
13856 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13857 				/* Try again on the rexmit. */
13858 				freemsg(mp1);
13859 				freemsg(mp);
13860 				return;
13861 			}
13862 			/*
13863 			 * Mark with NOTMARKNEXT for now.
13864 			 * The code below will change this to MARKNEXT
13865 			 * if we are at the mark.
13866 			 *
13867 			 * If there are allocation failures (e.g. in dupmsg
13868 			 * below) the next time tcp_rput_data sees the urgent
13869 			 * segment it will send up the MSG*MARKNEXT message.
13870 			 */
13871 			mp1->b_flag |= MSGNOTMARKNEXT;
13872 			freemsg(tcp->tcp_urp_mark_mp);
13873 			tcp->tcp_urp_mark_mp = mp1;
13874 			flags |= TH_SEND_URP_MARK;
13875 #ifdef DEBUG
13876 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13877 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13878 			    "last %x, %s",
13879 			    seg_seq, urp, tcp->tcp_urp_last,
13880 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13881 #endif /* DEBUG */
13882 			tcp->tcp_urp_last_valid = B_TRUE;
13883 			tcp->tcp_urp_last = urp + seg_seq;
13884 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13885 			/*
13886 			 * An allocation failure prevented the previous
13887 			 * tcp_rput_data from sending up the allocated
13888 			 * MSG*MARKNEXT message - send it up this time
13889 			 * around.
13890 			 */
13891 			flags |= TH_SEND_URP_MARK;
13892 		}
13893 
13894 		/*
13895 		 * If the urgent byte is in this segment, make sure that it is
13896 		 * all by itself.  This makes it much easier to deal with the
13897 		 * possibility of an allocation failure on the T_exdata_ind.
13898 		 * Note that seg_len is the number of bytes in the segment, and
13899 		 * urp is the offset into the segment of the urgent byte.
13900 		 * urp < seg_len means that the urgent byte is in this segment.
13901 		 */
13902 		if (urp < seg_len) {
13903 			if (seg_len != 1) {
13904 				uint32_t  tmp_rnxt;
13905 				/*
13906 				 * Break it up and feed it back in.
13907 				 * Re-attach the IP header.
13908 				 */
13909 				mp->b_rptr = iphdr;
13910 				if (urp > 0) {
13911 					/*
13912 					 * There is stuff before the urgent
13913 					 * byte.
13914 					 */
13915 					mp1 = dupmsg(mp);
13916 					if (!mp1) {
13917 						/*
13918 						 * Trim from urgent byte on.
13919 						 * The rest will come back.
13920 						 */
13921 						(void) adjmsg(mp,
13922 						    urp - seg_len);
13923 						tcp_rput_data(connp,
13924 						    mp, NULL);
13925 						return;
13926 					}
13927 					(void) adjmsg(mp1, urp - seg_len);
13928 					/* Feed this piece back in. */
13929 					tmp_rnxt = tcp->tcp_rnxt;
13930 					tcp_rput_data(connp, mp1, NULL);
13931 					/*
13932 					 * If the data passed back in was not
13933 					 * processed (ie: bad ACK) sending
13934 					 * the remainder back in will cause a
13935 					 * loop. In this case, drop the
13936 					 * packet and let the sender try
13937 					 * sending a good packet.
13938 					 */
13939 					if (tmp_rnxt == tcp->tcp_rnxt) {
13940 						freemsg(mp);
13941 						return;
13942 					}
13943 				}
13944 				if (urp != seg_len - 1) {
13945 					uint32_t  tmp_rnxt;
13946 					/*
13947 					 * There is stuff after the urgent
13948 					 * byte.
13949 					 */
13950 					mp1 = dupmsg(mp);
13951 					if (!mp1) {
13952 						/*
13953 						 * Trim everything beyond the
13954 						 * urgent byte.  The rest will
13955 						 * come back.
13956 						 */
13957 						(void) adjmsg(mp,
13958 						    urp + 1 - seg_len);
13959 						tcp_rput_data(connp,
13960 						    mp, NULL);
13961 						return;
13962 					}
13963 					(void) adjmsg(mp1, urp + 1 - seg_len);
13964 					tmp_rnxt = tcp->tcp_rnxt;
13965 					tcp_rput_data(connp, mp1, NULL);
13966 					/*
13967 					 * If the data passed back in was not
13968 					 * processed (ie: bad ACK) sending
13969 					 * the remainder back in will cause a
13970 					 * loop. In this case, drop the
13971 					 * packet and let the sender try
13972 					 * sending a good packet.
13973 					 */
13974 					if (tmp_rnxt == tcp->tcp_rnxt) {
13975 						freemsg(mp);
13976 						return;
13977 					}
13978 				}
13979 				tcp_rput_data(connp, mp, NULL);
13980 				return;
13981 			}
13982 			/*
13983 			 * This segment contains only the urgent byte.  We
13984 			 * have to allocate the T_exdata_ind, if we can.
13985 			 */
13986 			if (!tcp->tcp_urp_mp) {
13987 				struct T_exdata_ind *tei;
13988 				mp1 = allocb(sizeof (struct T_exdata_ind),
13989 				    BPRI_MED);
13990 				if (!mp1) {
13991 					/*
13992 					 * Sigh... It'll be back.
13993 					 * Generate any MSG*MARK message now.
13994 					 */
13995 					freemsg(mp);
13996 					seg_len = 0;
13997 					if (flags & TH_SEND_URP_MARK) {
13998 
13999 
14000 						ASSERT(tcp->tcp_urp_mark_mp);
14001 						tcp->tcp_urp_mark_mp->b_flag &=
14002 							~MSGNOTMARKNEXT;
14003 						tcp->tcp_urp_mark_mp->b_flag |=
14004 							MSGMARKNEXT;
14005 					}
14006 					goto ack_check;
14007 				}
14008 				mp1->b_datap->db_type = M_PROTO;
14009 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14010 				tei->PRIM_type = T_EXDATA_IND;
14011 				tei->MORE_flag = 0;
14012 				mp1->b_wptr = (uchar_t *)&tei[1];
14013 				tcp->tcp_urp_mp = mp1;
14014 #ifdef DEBUG
14015 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14016 				    "tcp_rput: allocated exdata_ind %s",
14017 				    tcp_display(tcp, NULL,
14018 				    DISP_PORT_ONLY));
14019 #endif /* DEBUG */
14020 				/*
14021 				 * There is no need to send a separate MSG*MARK
14022 				 * message since the T_EXDATA_IND will be sent
14023 				 * now.
14024 				 */
14025 				flags &= ~TH_SEND_URP_MARK;
14026 				freemsg(tcp->tcp_urp_mark_mp);
14027 				tcp->tcp_urp_mark_mp = NULL;
14028 			}
14029 			/*
14030 			 * Now we are all set.  On the next putnext upstream,
14031 			 * tcp_urp_mp will be non-NULL and will get prepended
14032 			 * to what has to be this piece containing the urgent
14033 			 * byte.  If for any reason we abort this segment below,
14034 			 * if it comes back, we will have this ready, or it
14035 			 * will get blown off in close.
14036 			 */
14037 		} else if (urp == seg_len) {
14038 			/*
14039 			 * The urgent byte is the next byte after this sequence
14040 			 * number. If there is data it is marked with
14041 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14042 			 * since it is not needed. Otherwise, if the code
14043 			 * above just allocated a zero-length tcp_urp_mark_mp
14044 			 * message, that message is tagged with MSGMARKNEXT.
14045 			 * Sending up these MSGMARKNEXT messages makes
14046 			 * SIOCATMARK work correctly even though
14047 			 * the T_EXDATA_IND will not be sent up until the
14048 			 * urgent byte arrives.
14049 			 */
14050 			if (seg_len != 0) {
14051 				flags |= TH_MARKNEXT_NEEDED;
14052 				freemsg(tcp->tcp_urp_mark_mp);
14053 				tcp->tcp_urp_mark_mp = NULL;
14054 				flags &= ~TH_SEND_URP_MARK;
14055 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14056 				flags |= TH_SEND_URP_MARK;
14057 				tcp->tcp_urp_mark_mp->b_flag &=
14058 					~MSGNOTMARKNEXT;
14059 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14060 			}
14061 #ifdef DEBUG
14062 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14063 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14064 			    seg_len, flags,
14065 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14066 #endif /* DEBUG */
14067 		} else {
14068 			/* Data left until we hit mark */
14069 #ifdef DEBUG
14070 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14071 			    "tcp_rput: URP %d bytes left, %s",
14072 			    urp - seg_len, tcp_display(tcp, NULL,
14073 			    DISP_PORT_ONLY));
14074 #endif /* DEBUG */
14075 		}
14076 	}
14077 
14078 process_ack:
14079 	if (!(flags & TH_ACK)) {
14080 		freemsg(mp);
14081 		goto xmit_check;
14082 	}
14083 	}
14084 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14085 
14086 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14087 		tcp->tcp_ip_forward_progress = B_TRUE;
14088 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14089 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
14090 			/* 3-way handshake complete - pass up the T_CONN_IND */
14091 			tcp_t	*listener = tcp->tcp_listener;
14092 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14093 
14094 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14095 			/*
14096 			 * We are here means eager is fine but it can
14097 			 * get a TH_RST at any point between now and till
14098 			 * accept completes and disappear. We need to
14099 			 * ensure that reference to eager is valid after
14100 			 * we get out of eager's perimeter. So we do
14101 			 * an extra refhold.
14102 			 */
14103 			CONN_INC_REF(connp);
14104 
14105 			/*
14106 			 * The listener also exists because of the refhold
14107 			 * done in tcp_conn_request. Its possible that it
14108 			 * might have closed. We will check that once we
14109 			 * get inside listeners context.
14110 			 */
14111 			CONN_INC_REF(listener->tcp_connp);
14112 			if (listener->tcp_connp->conn_sqp ==
14113 			    connp->conn_sqp) {
14114 				tcp_send_conn_ind(listener->tcp_connp, mp,
14115 				    listener->tcp_connp->conn_sqp);
14116 				CONN_DEC_REF(listener->tcp_connp);
14117 			} else if (!tcp->tcp_loopback) {
14118 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14119 				    tcp_send_conn_ind,
14120 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14121 			} else {
14122 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14123 				    tcp_send_conn_ind, listener->tcp_connp,
14124 				    SQTAG_TCP_CONN_IND);
14125 			}
14126 		}
14127 
14128 		if (tcp->tcp_active_open) {
14129 			/*
14130 			 * We are seeing the final ack in the three way
14131 			 * hand shake of a active open'ed connection
14132 			 * so we must send up a T_CONN_CON
14133 			 */
14134 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14135 				freemsg(mp);
14136 				return;
14137 			}
14138 			/*
14139 			 * Don't fuse the loopback endpoints for
14140 			 * simultaneous active opens.
14141 			 */
14142 			if (tcp->tcp_loopback) {
14143 				TCP_STAT(tcp_fusion_unfusable);
14144 				tcp->tcp_unfusable = B_TRUE;
14145 			}
14146 		}
14147 
14148 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14149 		bytes_acked--;
14150 		/* SYN was acked - making progress */
14151 		if (tcp->tcp_ipversion == IPV6_VERSION)
14152 			tcp->tcp_ip_forward_progress = B_TRUE;
14153 
14154 		/*
14155 		 * If SYN was retransmitted, need to reset all
14156 		 * retransmission info as this segment will be
14157 		 * treated as a dup ACK.
14158 		 */
14159 		if (tcp->tcp_rexmit) {
14160 			tcp->tcp_rexmit = B_FALSE;
14161 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14162 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14163 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14164 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14165 			tcp->tcp_ms_we_have_waited = 0;
14166 			tcp->tcp_cwnd = mss;
14167 		}
14168 
14169 		/*
14170 		 * We set the send window to zero here.
14171 		 * This is needed if there is data to be
14172 		 * processed already on the queue.
14173 		 * Later (at swnd_update label), the
14174 		 * "new_swnd > tcp_swnd" condition is satisfied
14175 		 * the XMIT_NEEDED flag is set in the current
14176 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14177 		 * called if there is already data on queue in
14178 		 * this state.
14179 		 */
14180 		tcp->tcp_swnd = 0;
14181 
14182 		if (new_swnd > tcp->tcp_max_swnd)
14183 			tcp->tcp_max_swnd = new_swnd;
14184 		tcp->tcp_swl1 = seg_seq;
14185 		tcp->tcp_swl2 = seg_ack;
14186 		tcp->tcp_state = TCPS_ESTABLISHED;
14187 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14188 
14189 		/* Fuse when both sides are in ESTABLISHED state */
14190 		if (tcp->tcp_loopback && do_tcp_fusion)
14191 			tcp_fuse(tcp, iphdr, tcph);
14192 
14193 	}
14194 	/* This code follows 4.4BSD-Lite2 mostly. */
14195 	if (bytes_acked < 0)
14196 		goto est;
14197 
14198 	/*
14199 	 * If TCP is ECN capable and the congestion experience bit is
14200 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14201 	 * done once per window (or more loosely, per RTT).
14202 	 */
14203 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14204 		tcp->tcp_cwr = B_FALSE;
14205 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14206 		if (!tcp->tcp_cwr) {
14207 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14208 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14209 			tcp->tcp_cwnd = npkt * mss;
14210 			/*
14211 			 * If the cwnd is 0, use the timer to clock out
14212 			 * new segments.  This is required by the ECN spec.
14213 			 */
14214 			if (npkt == 0) {
14215 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14216 				/*
14217 				 * This makes sure that when the ACK comes
14218 				 * back, we will increase tcp_cwnd by 1 MSS.
14219 				 */
14220 				tcp->tcp_cwnd_cnt = 0;
14221 			}
14222 			tcp->tcp_cwr = B_TRUE;
14223 			/*
14224 			 * This marks the end of the current window of in
14225 			 * flight data.  That is why we don't use
14226 			 * tcp_suna + tcp_swnd.  Only data in flight can
14227 			 * provide ECN info.
14228 			 */
14229 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14230 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14231 		}
14232 	}
14233 
14234 	mp1 = tcp->tcp_xmit_head;
14235 	if (bytes_acked == 0) {
14236 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14237 			int dupack_cnt;
14238 
14239 			BUMP_MIB(&tcp_mib, tcpInDupAck);
14240 			/*
14241 			 * Fast retransmit.  When we have seen exactly three
14242 			 * identical ACKs while we have unacked data
14243 			 * outstanding we take it as a hint that our peer
14244 			 * dropped something.
14245 			 *
14246 			 * If TCP is retransmitting, don't do fast retransmit.
14247 			 */
14248 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14249 			    ! tcp->tcp_rexmit) {
14250 				/* Do Limited Transmit */
14251 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14252 				    tcp_dupack_fast_retransmit) {
14253 					/*
14254 					 * RFC 3042
14255 					 *
14256 					 * What we need to do is temporarily
14257 					 * increase tcp_cwnd so that new
14258 					 * data can be sent if it is allowed
14259 					 * by the receive window (tcp_rwnd).
14260 					 * tcp_wput_data() will take care of
14261 					 * the rest.
14262 					 *
14263 					 * If the connection is SACK capable,
14264 					 * only do limited xmit when there
14265 					 * is SACK info.
14266 					 *
14267 					 * Note how tcp_cwnd is incremented.
14268 					 * The first dup ACK will increase
14269 					 * it by 1 MSS.  The second dup ACK
14270 					 * will increase it by 2 MSS.  This
14271 					 * means that only 1 new segment will
14272 					 * be sent for each dup ACK.
14273 					 */
14274 					if (tcp->tcp_unsent > 0 &&
14275 					    (!tcp->tcp_snd_sack_ok ||
14276 					    (tcp->tcp_snd_sack_ok &&
14277 					    tcp->tcp_notsack_list != NULL))) {
14278 						tcp->tcp_cwnd += mss <<
14279 						    (tcp->tcp_dupack_cnt - 1);
14280 						flags |= TH_LIMIT_XMIT;
14281 					}
14282 				} else if (dupack_cnt ==
14283 				    tcp_dupack_fast_retransmit) {
14284 
14285 				/*
14286 				 * If we have reduced tcp_ssthresh
14287 				 * because of ECN, do not reduce it again
14288 				 * unless it is already one window of data
14289 				 * away.  After one window of data, tcp_cwr
14290 				 * should then be cleared.  Note that
14291 				 * for non ECN capable connection, tcp_cwr
14292 				 * should always be false.
14293 				 *
14294 				 * Adjust cwnd since the duplicate
14295 				 * ack indicates that a packet was
14296 				 * dropped (due to congestion.)
14297 				 */
14298 				if (!tcp->tcp_cwr) {
14299 					npkt = ((tcp->tcp_snxt -
14300 					    tcp->tcp_suna) >> 1) / mss;
14301 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14302 					    mss;
14303 					tcp->tcp_cwnd = (npkt +
14304 					    tcp->tcp_dupack_cnt) * mss;
14305 				}
14306 				if (tcp->tcp_ecn_ok) {
14307 					tcp->tcp_cwr = B_TRUE;
14308 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14309 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14310 				}
14311 
14312 				/*
14313 				 * We do Hoe's algorithm.  Refer to her
14314 				 * paper "Improving the Start-up Behavior
14315 				 * of a Congestion Control Scheme for TCP,"
14316 				 * appeared in SIGCOMM'96.
14317 				 *
14318 				 * Save highest seq no we have sent so far.
14319 				 * Be careful about the invisible FIN byte.
14320 				 */
14321 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14322 				    (tcp->tcp_unsent == 0)) {
14323 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14324 				} else {
14325 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14326 				}
14327 
14328 				/*
14329 				 * Do not allow bursty traffic during.
14330 				 * fast recovery.  Refer to Fall and Floyd's
14331 				 * paper "Simulation-based Comparisons of
14332 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14333 				 * This is a best current practise.
14334 				 */
14335 				tcp->tcp_snd_burst = TCP_CWND_SS;
14336 
14337 				/*
14338 				 * For SACK:
14339 				 * Calculate tcp_pipe, which is the
14340 				 * estimated number of bytes in
14341 				 * network.
14342 				 *
14343 				 * tcp_fack is the highest sack'ed seq num
14344 				 * TCP has received.
14345 				 *
14346 				 * tcp_pipe is explained in the above quoted
14347 				 * Fall and Floyd's paper.  tcp_fack is
14348 				 * explained in Mathis and Mahdavi's
14349 				 * "Forward Acknowledgment: Refining TCP
14350 				 * Congestion Control" in SIGCOMM '96.
14351 				 */
14352 				if (tcp->tcp_snd_sack_ok) {
14353 					ASSERT(tcp->tcp_sack_info != NULL);
14354 					if (tcp->tcp_notsack_list != NULL) {
14355 						tcp->tcp_pipe = tcp->tcp_snxt -
14356 						    tcp->tcp_fack;
14357 						tcp->tcp_sack_snxt = seg_ack;
14358 						flags |= TH_NEED_SACK_REXMIT;
14359 					} else {
14360 						/*
14361 						 * Always initialize tcp_pipe
14362 						 * even though we don't have
14363 						 * any SACK info.  If later
14364 						 * we get SACK info and
14365 						 * tcp_pipe is not initialized,
14366 						 * funny things will happen.
14367 						 */
14368 						tcp->tcp_pipe =
14369 						    tcp->tcp_cwnd_ssthresh;
14370 					}
14371 				} else {
14372 					flags |= TH_REXMIT_NEEDED;
14373 				} /* tcp_snd_sack_ok */
14374 
14375 				} else {
14376 					/*
14377 					 * Here we perform congestion
14378 					 * avoidance, but NOT slow start.
14379 					 * This is known as the Fast
14380 					 * Recovery Algorithm.
14381 					 */
14382 					if (tcp->tcp_snd_sack_ok &&
14383 					    tcp->tcp_notsack_list != NULL) {
14384 						flags |= TH_NEED_SACK_REXMIT;
14385 						tcp->tcp_pipe -= mss;
14386 						if (tcp->tcp_pipe < 0)
14387 							tcp->tcp_pipe = 0;
14388 					} else {
14389 					/*
14390 					 * We know that one more packet has
14391 					 * left the pipe thus we can update
14392 					 * cwnd.
14393 					 */
14394 					cwnd = tcp->tcp_cwnd + mss;
14395 					if (cwnd > tcp->tcp_cwnd_max)
14396 						cwnd = tcp->tcp_cwnd_max;
14397 					tcp->tcp_cwnd = cwnd;
14398 					if (tcp->tcp_unsent > 0)
14399 						flags |= TH_XMIT_NEEDED;
14400 					}
14401 				}
14402 			}
14403 		} else if (tcp->tcp_zero_win_probe) {
14404 			/*
14405 			 * If the window has opened, need to arrange
14406 			 * to send additional data.
14407 			 */
14408 			if (new_swnd != 0) {
14409 				/* tcp_suna != tcp_snxt */
14410 				/* Packet contains a window update */
14411 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
14412 				tcp->tcp_zero_win_probe = 0;
14413 				tcp->tcp_timer_backoff = 0;
14414 				tcp->tcp_ms_we_have_waited = 0;
14415 
14416 				/*
14417 				 * Transmit starting with tcp_suna since
14418 				 * the one byte probe is not ack'ed.
14419 				 * If TCP has sent more than one identical
14420 				 * probe, tcp_rexmit will be set.  That means
14421 				 * tcp_ss_rexmit() will send out the one
14422 				 * byte along with new data.  Otherwise,
14423 				 * fake the retransmission.
14424 				 */
14425 				flags |= TH_XMIT_NEEDED;
14426 				if (!tcp->tcp_rexmit) {
14427 					tcp->tcp_rexmit = B_TRUE;
14428 					tcp->tcp_dupack_cnt = 0;
14429 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14430 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14431 				}
14432 			}
14433 		}
14434 		goto swnd_update;
14435 	}
14436 
14437 	/*
14438 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14439 	 * If the ACK value acks something that we have not yet sent, it might
14440 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14441 	 * other side.
14442 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14443 	 * state is handled above, so we can always just drop the segment and
14444 	 * send an ACK here.
14445 	 *
14446 	 * Should we send ACKs in response to ACK only segments?
14447 	 */
14448 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14449 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
14450 		/* drop the received segment */
14451 		freemsg(mp);
14452 
14453 		/*
14454 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14455 		 * greater than 0, check if the number of such
14456 		 * bogus ACks is greater than that count.  If yes,
14457 		 * don't send back any ACK.  This prevents TCP from
14458 		 * getting into an ACK storm if somehow an attacker
14459 		 * successfully spoofs an acceptable segment to our
14460 		 * peer.
14461 		 */
14462 		if (tcp_drop_ack_unsent_cnt > 0 &&
14463 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14464 			TCP_STAT(tcp_in_ack_unsent_drop);
14465 			return;
14466 		}
14467 		mp = tcp_ack_mp(tcp);
14468 		if (mp != NULL) {
14469 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14470 			BUMP_LOCAL(tcp->tcp_obsegs);
14471 			BUMP_MIB(&tcp_mib, tcpOutAck);
14472 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14473 		}
14474 		return;
14475 	}
14476 
14477 	/*
14478 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14479 	 * blocks that are covered by this ACK.
14480 	 */
14481 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14482 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14483 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14484 	}
14485 
14486 	/*
14487 	 * If we got an ACK after fast retransmit, check to see
14488 	 * if it is a partial ACK.  If it is not and the congestion
14489 	 * window was inflated to account for the other side's
14490 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14491 	 */
14492 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
14493 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14494 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14495 			tcp->tcp_dupack_cnt = 0;
14496 			/*
14497 			 * Restore the orig tcp_cwnd_ssthresh after
14498 			 * fast retransmit phase.
14499 			 */
14500 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14501 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14502 			}
14503 			tcp->tcp_rexmit_max = seg_ack;
14504 			tcp->tcp_cwnd_cnt = 0;
14505 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14506 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14507 
14508 			/*
14509 			 * Remove all notsack info to avoid confusion with
14510 			 * the next fast retrasnmit/recovery phase.
14511 			 */
14512 			if (tcp->tcp_snd_sack_ok &&
14513 			    tcp->tcp_notsack_list != NULL) {
14514 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14515 			}
14516 		} else {
14517 			if (tcp->tcp_snd_sack_ok &&
14518 			    tcp->tcp_notsack_list != NULL) {
14519 				flags |= TH_NEED_SACK_REXMIT;
14520 				tcp->tcp_pipe -= mss;
14521 				if (tcp->tcp_pipe < 0)
14522 					tcp->tcp_pipe = 0;
14523 			} else {
14524 				/*
14525 				 * Hoe's algorithm:
14526 				 *
14527 				 * Retransmit the unack'ed segment and
14528 				 * restart fast recovery.  Note that we
14529 				 * need to scale back tcp_cwnd to the
14530 				 * original value when we started fast
14531 				 * recovery.  This is to prevent overly
14532 				 * aggressive behaviour in sending new
14533 				 * segments.
14534 				 */
14535 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14536 					tcp_dupack_fast_retransmit * mss;
14537 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14538 				flags |= TH_REXMIT_NEEDED;
14539 			}
14540 		}
14541 	} else {
14542 		tcp->tcp_dupack_cnt = 0;
14543 		if (tcp->tcp_rexmit) {
14544 			/*
14545 			 * TCP is retranmitting.  If the ACK ack's all
14546 			 * outstanding data, update tcp_rexmit_max and
14547 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14548 			 * to the correct value.
14549 			 *
14550 			 * Note that SEQ_LEQ() is used.  This is to avoid
14551 			 * unnecessary fast retransmit caused by dup ACKs
14552 			 * received when TCP does slow start retransmission
14553 			 * after a time out.  During this phase, TCP may
14554 			 * send out segments which are already received.
14555 			 * This causes dup ACKs to be sent back.
14556 			 */
14557 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14558 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14559 					tcp->tcp_rexmit_nxt = seg_ack;
14560 				}
14561 				if (seg_ack != tcp->tcp_rexmit_max) {
14562 					flags |= TH_XMIT_NEEDED;
14563 				}
14564 			} else {
14565 				tcp->tcp_rexmit = B_FALSE;
14566 				tcp->tcp_xmit_zc_clean = B_FALSE;
14567 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14568 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14569 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14570 			}
14571 			tcp->tcp_ms_we_have_waited = 0;
14572 		}
14573 	}
14574 
14575 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14576 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14577 	tcp->tcp_suna = seg_ack;
14578 	if (tcp->tcp_zero_win_probe != 0) {
14579 		tcp->tcp_zero_win_probe = 0;
14580 		tcp->tcp_timer_backoff = 0;
14581 	}
14582 
14583 	/*
14584 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14585 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14586 	 * will not reach here.
14587 	 */
14588 	if (mp1 == NULL) {
14589 		goto fin_acked;
14590 	}
14591 
14592 	/*
14593 	 * Update the congestion window.
14594 	 *
14595 	 * If TCP is not ECN capable or TCP is ECN capable but the
14596 	 * congestion experience bit is not set, increase the tcp_cwnd as
14597 	 * usual.
14598 	 */
14599 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14600 		cwnd = tcp->tcp_cwnd;
14601 		add = mss;
14602 
14603 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14604 			/*
14605 			 * This is to prevent an increase of less than 1 MSS of
14606 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14607 			 * may send out tinygrams in order to preserve mblk
14608 			 * boundaries.
14609 			 *
14610 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14611 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14612 			 * increased by 1 MSS for every RTTs.
14613 			 */
14614 			if (tcp->tcp_cwnd_cnt <= 0) {
14615 				tcp->tcp_cwnd_cnt = cwnd + add;
14616 			} else {
14617 				tcp->tcp_cwnd_cnt -= add;
14618 				add = 0;
14619 			}
14620 		}
14621 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14622 	}
14623 
14624 	/* See if the latest urgent data has been acknowledged */
14625 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14626 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14627 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14628 
14629 	/* Can we update the RTT estimates? */
14630 	if (tcp->tcp_snd_ts_ok) {
14631 		/* Ignore zero timestamp echo-reply. */
14632 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14633 			tcp_set_rto(tcp, (int32_t)lbolt -
14634 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14635 		}
14636 
14637 		/* If needed, restart the timer. */
14638 		if (tcp->tcp_set_timer == 1) {
14639 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14640 			tcp->tcp_set_timer = 0;
14641 		}
14642 		/*
14643 		 * Update tcp_csuna in case the other side stops sending
14644 		 * us timestamps.
14645 		 */
14646 		tcp->tcp_csuna = tcp->tcp_snxt;
14647 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14648 		/*
14649 		 * An ACK sequence we haven't seen before, so get the RTT
14650 		 * and update the RTO. But first check if the timestamp is
14651 		 * valid to use.
14652 		 */
14653 		if ((mp1->b_next != NULL) &&
14654 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14655 			tcp_set_rto(tcp, (int32_t)lbolt -
14656 			    (int32_t)(intptr_t)mp1->b_prev);
14657 		else
14658 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14659 
14660 		/* Remeber the last sequence to be ACKed */
14661 		tcp->tcp_csuna = seg_ack;
14662 		if (tcp->tcp_set_timer == 1) {
14663 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14664 			tcp->tcp_set_timer = 0;
14665 		}
14666 	} else {
14667 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14668 	}
14669 
14670 	/* Eat acknowledged bytes off the xmit queue. */
14671 	for (;;) {
14672 		mblk_t	*mp2;
14673 		uchar_t	*wptr;
14674 
14675 		wptr = mp1->b_wptr;
14676 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14677 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14678 		if (bytes_acked < 0) {
14679 			mp1->b_rptr = wptr + bytes_acked;
14680 			/*
14681 			 * Set a new timestamp if all the bytes timed by the
14682 			 * old timestamp have been ack'ed.
14683 			 */
14684 			if (SEQ_GT(seg_ack,
14685 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14686 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14687 				mp1->b_next = NULL;
14688 			}
14689 			break;
14690 		}
14691 		mp1->b_next = NULL;
14692 		mp1->b_prev = NULL;
14693 		mp2 = mp1;
14694 		mp1 = mp1->b_cont;
14695 
14696 		/*
14697 		 * This notification is required for some zero-copy
14698 		 * clients to maintain a copy semantic. After the data
14699 		 * is ack'ed, client is safe to modify or reuse the buffer.
14700 		 */
14701 		if (tcp->tcp_snd_zcopy_aware &&
14702 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14703 			tcp_zcopy_notify(tcp);
14704 		freeb(mp2);
14705 		if (bytes_acked == 0) {
14706 			if (mp1 == NULL) {
14707 				/* Everything is ack'ed, clear the tail. */
14708 				tcp->tcp_xmit_tail = NULL;
14709 				/*
14710 				 * Cancel the timer unless we are still
14711 				 * waiting for an ACK for the FIN packet.
14712 				 */
14713 				if (tcp->tcp_timer_tid != 0 &&
14714 				    tcp->tcp_snxt == tcp->tcp_suna) {
14715 					(void) TCP_TIMER_CANCEL(tcp,
14716 					    tcp->tcp_timer_tid);
14717 					tcp->tcp_timer_tid = 0;
14718 				}
14719 				goto pre_swnd_update;
14720 			}
14721 			if (mp2 != tcp->tcp_xmit_tail)
14722 				break;
14723 			tcp->tcp_xmit_tail = mp1;
14724 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14725 			    (uintptr_t)INT_MAX);
14726 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14727 			    mp1->b_rptr);
14728 			break;
14729 		}
14730 		if (mp1 == NULL) {
14731 			/*
14732 			 * More was acked but there is nothing more
14733 			 * outstanding.  This means that the FIN was
14734 			 * just acked or that we're talking to a clown.
14735 			 */
14736 fin_acked:
14737 			ASSERT(tcp->tcp_fin_sent);
14738 			tcp->tcp_xmit_tail = NULL;
14739 			if (tcp->tcp_fin_sent) {
14740 				/* FIN was acked - making progress */
14741 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14742 				    !tcp->tcp_fin_acked)
14743 					tcp->tcp_ip_forward_progress = B_TRUE;
14744 				tcp->tcp_fin_acked = B_TRUE;
14745 				if (tcp->tcp_linger_tid != 0 &&
14746 				    TCP_TIMER_CANCEL(tcp,
14747 					tcp->tcp_linger_tid) >= 0) {
14748 					tcp_stop_lingering(tcp);
14749 				}
14750 			} else {
14751 				/*
14752 				 * We should never get here because
14753 				 * we have already checked that the
14754 				 * number of bytes ack'ed should be
14755 				 * smaller than or equal to what we
14756 				 * have sent so far (it is the
14757 				 * acceptability check of the ACK).
14758 				 * We can only get here if the send
14759 				 * queue is corrupted.
14760 				 *
14761 				 * Terminate the connection and
14762 				 * panic the system.  It is better
14763 				 * for us to panic instead of
14764 				 * continuing to avoid other disaster.
14765 				 */
14766 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14767 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14768 				panic("Memory corruption "
14769 				    "detected for connection %s.",
14770 				    tcp_display(tcp, NULL,
14771 					DISP_ADDR_AND_PORT));
14772 				/*NOTREACHED*/
14773 			}
14774 			goto pre_swnd_update;
14775 		}
14776 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14777 	}
14778 	if (tcp->tcp_unsent) {
14779 		flags |= TH_XMIT_NEEDED;
14780 	}
14781 pre_swnd_update:
14782 	tcp->tcp_xmit_head = mp1;
14783 swnd_update:
14784 	/*
14785 	 * The following check is different from most other implementations.
14786 	 * For bi-directional transfer, when segments are dropped, the
14787 	 * "normal" check will not accept a window update in those
14788 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14789 	 * segments which are outside receiver's window.  As TCP accepts
14790 	 * the ack in those retransmitted segments, if the window update in
14791 	 * the same segment is not accepted, TCP will incorrectly calculates
14792 	 * that it can send more segments.  This can create a deadlock
14793 	 * with the receiver if its window becomes zero.
14794 	 */
14795 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14796 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14797 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14798 		/*
14799 		 * The criteria for update is:
14800 		 *
14801 		 * 1. the segment acknowledges some data.  Or
14802 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14803 		 * 3. the segment is not old and the advertised window is
14804 		 * larger than the previous advertised window.
14805 		 */
14806 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14807 			flags |= TH_XMIT_NEEDED;
14808 		tcp->tcp_swnd = new_swnd;
14809 		if (new_swnd > tcp->tcp_max_swnd)
14810 			tcp->tcp_max_swnd = new_swnd;
14811 		tcp->tcp_swl1 = seg_seq;
14812 		tcp->tcp_swl2 = seg_ack;
14813 	}
14814 est:
14815 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14816 		switch (tcp->tcp_state) {
14817 		case TCPS_FIN_WAIT_1:
14818 			if (tcp->tcp_fin_acked) {
14819 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14820 				/*
14821 				 * We implement the non-standard BSD/SunOS
14822 				 * FIN_WAIT_2 flushing algorithm.
14823 				 * If there is no user attached to this
14824 				 * TCP endpoint, then this TCP struct
14825 				 * could hang around forever in FIN_WAIT_2
14826 				 * state if the peer forgets to send us
14827 				 * a FIN.  To prevent this, we wait only
14828 				 * 2*MSL (a convenient time value) for
14829 				 * the FIN to arrive.  If it doesn't show up,
14830 				 * we flush the TCP endpoint.  This algorithm,
14831 				 * though a violation of RFC-793, has worked
14832 				 * for over 10 years in BSD systems.
14833 				 * Note: SunOS 4.x waits 675 seconds before
14834 				 * flushing the FIN_WAIT_2 connection.
14835 				 */
14836 				TCP_TIMER_RESTART(tcp,
14837 				    tcp_fin_wait_2_flush_interval);
14838 			}
14839 			break;
14840 		case TCPS_FIN_WAIT_2:
14841 			break;	/* Shutdown hook? */
14842 		case TCPS_LAST_ACK:
14843 			freemsg(mp);
14844 			if (tcp->tcp_fin_acked) {
14845 				(void) tcp_clean_death(tcp, 0, 19);
14846 				return;
14847 			}
14848 			goto xmit_check;
14849 		case TCPS_CLOSING:
14850 			if (tcp->tcp_fin_acked) {
14851 				tcp->tcp_state = TCPS_TIME_WAIT;
14852 				if (!TCP_IS_DETACHED(tcp)) {
14853 					TCP_TIMER_RESTART(tcp,
14854 					    tcp_time_wait_interval);
14855 				} else {
14856 					tcp_time_wait_append(tcp);
14857 					TCP_DBGSTAT(tcp_rput_time_wait);
14858 				}
14859 			}
14860 			/*FALLTHRU*/
14861 		case TCPS_CLOSE_WAIT:
14862 			freemsg(mp);
14863 			goto xmit_check;
14864 		default:
14865 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14866 			break;
14867 		}
14868 	}
14869 	if (flags & TH_FIN) {
14870 		/* Make sure we ack the fin */
14871 		flags |= TH_ACK_NEEDED;
14872 		if (!tcp->tcp_fin_rcvd) {
14873 			tcp->tcp_fin_rcvd = B_TRUE;
14874 			tcp->tcp_rnxt++;
14875 			tcph = tcp->tcp_tcph;
14876 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14877 
14878 			/*
14879 			 * Generate the ordrel_ind at the end unless we
14880 			 * are an eager guy.
14881 			 * In the eager case tcp_rsrv will do this when run
14882 			 * after tcp_accept is done.
14883 			 */
14884 			if (tcp->tcp_listener == NULL &&
14885 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14886 				flags |= TH_ORDREL_NEEDED;
14887 			switch (tcp->tcp_state) {
14888 			case TCPS_SYN_RCVD:
14889 			case TCPS_ESTABLISHED:
14890 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14891 				/* Keepalive? */
14892 				break;
14893 			case TCPS_FIN_WAIT_1:
14894 				if (!tcp->tcp_fin_acked) {
14895 					tcp->tcp_state = TCPS_CLOSING;
14896 					break;
14897 				}
14898 				/* FALLTHRU */
14899 			case TCPS_FIN_WAIT_2:
14900 				tcp->tcp_state = TCPS_TIME_WAIT;
14901 				if (!TCP_IS_DETACHED(tcp)) {
14902 					TCP_TIMER_RESTART(tcp,
14903 					    tcp_time_wait_interval);
14904 				} else {
14905 					tcp_time_wait_append(tcp);
14906 					TCP_DBGSTAT(tcp_rput_time_wait);
14907 				}
14908 				if (seg_len) {
14909 					/*
14910 					 * implies data piggybacked on FIN.
14911 					 * break to handle data.
14912 					 */
14913 					break;
14914 				}
14915 				freemsg(mp);
14916 				goto ack_check;
14917 			}
14918 		}
14919 	}
14920 	if (mp == NULL)
14921 		goto xmit_check;
14922 	if (seg_len == 0) {
14923 		freemsg(mp);
14924 		goto xmit_check;
14925 	}
14926 	if (mp->b_rptr == mp->b_wptr) {
14927 		/*
14928 		 * The header has been consumed, so we remove the
14929 		 * zero-length mblk here.
14930 		 */
14931 		mp1 = mp;
14932 		mp = mp->b_cont;
14933 		freeb(mp1);
14934 	}
14935 	tcph = tcp->tcp_tcph;
14936 	tcp->tcp_rack_cnt++;
14937 	{
14938 		uint32_t cur_max;
14939 
14940 		cur_max = tcp->tcp_rack_cur_max;
14941 		if (tcp->tcp_rack_cnt >= cur_max) {
14942 			/*
14943 			 * We have more unacked data than we should - send
14944 			 * an ACK now.
14945 			 */
14946 			flags |= TH_ACK_NEEDED;
14947 			cur_max++;
14948 			if (cur_max > tcp->tcp_rack_abs_max)
14949 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14950 			else
14951 				tcp->tcp_rack_cur_max = cur_max;
14952 		} else if (TCP_IS_DETACHED(tcp)) {
14953 			/* We don't have an ACK timer for detached TCP. */
14954 			flags |= TH_ACK_NEEDED;
14955 		} else if (seg_len < mss) {
14956 			/*
14957 			 * If we get a segment that is less than an mss, and we
14958 			 * already have unacknowledged data, and the amount
14959 			 * unacknowledged is not a multiple of mss, then we
14960 			 * better generate an ACK now.  Otherwise, this may be
14961 			 * the tail piece of a transaction, and we would rather
14962 			 * wait for the response.
14963 			 */
14964 			uint32_t udif;
14965 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14966 			    (uintptr_t)INT_MAX);
14967 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14968 			if (udif && (udif % mss))
14969 				flags |= TH_ACK_NEEDED;
14970 			else
14971 				flags |= TH_ACK_TIMER_NEEDED;
14972 		} else {
14973 			/* Start delayed ack timer */
14974 			flags |= TH_ACK_TIMER_NEEDED;
14975 		}
14976 	}
14977 	tcp->tcp_rnxt += seg_len;
14978 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14979 
14980 	/* Update SACK list */
14981 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14982 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14983 		    &(tcp->tcp_num_sack_blk));
14984 	}
14985 
14986 	if (tcp->tcp_urp_mp) {
14987 		tcp->tcp_urp_mp->b_cont = mp;
14988 		mp = tcp->tcp_urp_mp;
14989 		tcp->tcp_urp_mp = NULL;
14990 		/* Ready for a new signal. */
14991 		tcp->tcp_urp_last_valid = B_FALSE;
14992 #ifdef DEBUG
14993 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14994 		    "tcp_rput: sending exdata_ind %s",
14995 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14996 #endif /* DEBUG */
14997 	}
14998 
14999 	/*
15000 	 * Check for ancillary data changes compared to last segment.
15001 	 */
15002 	if (tcp->tcp_ipv6_recvancillary != 0) {
15003 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15004 		if (mp == NULL)
15005 			return;
15006 	}
15007 
15008 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15009 		/*
15010 		 * Side queue inbound data until the accept happens.
15011 		 * tcp_accept/tcp_rput drains this when the accept happens.
15012 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15013 		 * T_EXDATA_IND) it is queued on b_next.
15014 		 * XXX Make urgent data use this. Requires:
15015 		 *	Removing tcp_listener check for TH_URG
15016 		 *	Making M_PCPROTO and MARK messages skip the eager case
15017 		 */
15018 		tcp_rcv_enqueue(tcp, mp, seg_len);
15019 	} else {
15020 		if (mp->b_datap->db_type != M_DATA ||
15021 		    (flags & TH_MARKNEXT_NEEDED)) {
15022 			if (tcp->tcp_rcv_list != NULL) {
15023 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15024 			}
15025 			ASSERT(tcp->tcp_rcv_list == NULL ||
15026 			    tcp->tcp_fused_sigurg);
15027 			if (flags & TH_MARKNEXT_NEEDED) {
15028 #ifdef DEBUG
15029 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15030 				    "tcp_rput: sending MSGMARKNEXT %s",
15031 				    tcp_display(tcp, NULL,
15032 				    DISP_PORT_ONLY));
15033 #endif /* DEBUG */
15034 				mp->b_flag |= MSGMARKNEXT;
15035 				flags &= ~TH_MARKNEXT_NEEDED;
15036 			}
15037 			putnext(tcp->tcp_rq, mp);
15038 			if (!canputnext(tcp->tcp_rq))
15039 				tcp->tcp_rwnd -= seg_len;
15040 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
15041 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
15042 		    (sqp != NULL)) {
15043 			if (tcp->tcp_rcv_list != NULL) {
15044 				/*
15045 				 * Enqueue the new segment first and then
15046 				 * call tcp_rcv_drain() to send all data
15047 				 * up.  The other way to do this is to
15048 				 * send all queued data up and then call
15049 				 * putnext() to send the new segment up.
15050 				 * This way can remove the else part later
15051 				 * on.
15052 				 *
15053 				 * We don't this to avoid one more call to
15054 				 * canputnext() as tcp_rcv_drain() needs to
15055 				 * call canputnext().
15056 				 */
15057 				tcp_rcv_enqueue(tcp, mp, seg_len);
15058 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15059 			} else {
15060 				putnext(tcp->tcp_rq, mp);
15061 				if (!canputnext(tcp->tcp_rq))
15062 					tcp->tcp_rwnd -= seg_len;
15063 			}
15064 		} else {
15065 			/*
15066 			 * Enqueue all packets when processing an mblk
15067 			 * from the co queue and also enqueue normal packets.
15068 			 */
15069 			tcp_rcv_enqueue(tcp, mp, seg_len);
15070 		}
15071 		/*
15072 		 * Make sure the timer is running if we have data waiting
15073 		 * for a push bit. This provides resiliency against
15074 		 * implementations that do not correctly generate push bits.
15075 		 */
15076 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
15077 		    tcp->tcp_push_tid == 0) {
15078 			/*
15079 			 * The connection may be closed at this point, so don't
15080 			 * do anything for a detached tcp.
15081 			 */
15082 			if (!TCP_IS_DETACHED(tcp))
15083 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15084 				    tcp_push_timer,
15085 				    MSEC_TO_TICK(tcp_push_timer_interval));
15086 		}
15087 	}
15088 xmit_check:
15089 	/* Is there anything left to do? */
15090 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15091 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15092 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15093 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15094 		goto done;
15095 
15096 	/* Any transmit work to do and a non-zero window? */
15097 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15098 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15099 		if (flags & TH_REXMIT_NEEDED) {
15100 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15101 
15102 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
15103 			if (snd_size > mss)
15104 				snd_size = mss;
15105 			if (snd_size > tcp->tcp_swnd)
15106 				snd_size = tcp->tcp_swnd;
15107 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15108 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15109 			    B_TRUE);
15110 
15111 			if (mp1 != NULL) {
15112 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15113 				tcp->tcp_csuna = tcp->tcp_snxt;
15114 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
15115 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
15116 				TCP_RECORD_TRACE(tcp, mp1,
15117 				    TCP_TRACE_SEND_PKT);
15118 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15119 			}
15120 		}
15121 		if (flags & TH_NEED_SACK_REXMIT) {
15122 			tcp_sack_rxmit(tcp, &flags);
15123 		}
15124 		/*
15125 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15126 		 * out new segment.  Note that tcp_rexmit should not be
15127 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15128 		 */
15129 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15130 			if (!tcp->tcp_rexmit) {
15131 				tcp_wput_data(tcp, NULL, B_FALSE);
15132 			} else {
15133 				tcp_ss_rexmit(tcp);
15134 			}
15135 		}
15136 		/*
15137 		 * Adjust tcp_cwnd back to normal value after sending
15138 		 * new data segments.
15139 		 */
15140 		if (flags & TH_LIMIT_XMIT) {
15141 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15142 			/*
15143 			 * This will restart the timer.  Restarting the
15144 			 * timer is used to avoid a timeout before the
15145 			 * limited transmitted segment's ACK gets back.
15146 			 */
15147 			if (tcp->tcp_xmit_head != NULL)
15148 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15149 		}
15150 
15151 		/* Anything more to do? */
15152 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15153 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15154 			goto done;
15155 	}
15156 ack_check:
15157 	if (flags & TH_SEND_URP_MARK) {
15158 		ASSERT(tcp->tcp_urp_mark_mp);
15159 		/*
15160 		 * Send up any queued data and then send the mark message
15161 		 */
15162 		if (tcp->tcp_rcv_list != NULL) {
15163 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15164 		}
15165 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15166 
15167 		mp1 = tcp->tcp_urp_mark_mp;
15168 		tcp->tcp_urp_mark_mp = NULL;
15169 #ifdef DEBUG
15170 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15171 		    "tcp_rput: sending zero-length %s %s",
15172 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15173 		    "MSGNOTMARKNEXT"),
15174 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15175 #endif /* DEBUG */
15176 		putnext(tcp->tcp_rq, mp1);
15177 		flags &= ~TH_SEND_URP_MARK;
15178 	}
15179 	if (flags & TH_ACK_NEEDED) {
15180 		/*
15181 		 * Time to send an ack for some reason.
15182 		 */
15183 		mp1 = tcp_ack_mp(tcp);
15184 
15185 		if (mp1 != NULL) {
15186 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15187 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15188 			BUMP_LOCAL(tcp->tcp_obsegs);
15189 			BUMP_MIB(&tcp_mib, tcpOutAck);
15190 		}
15191 		if (tcp->tcp_ack_tid != 0) {
15192 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15193 			tcp->tcp_ack_tid = 0;
15194 		}
15195 	}
15196 	if (flags & TH_ACK_TIMER_NEEDED) {
15197 		/*
15198 		 * Arrange for deferred ACK or push wait timeout.
15199 		 * Start timer if it is not already running.
15200 		 */
15201 		if (tcp->tcp_ack_tid == 0) {
15202 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15203 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15204 			    (clock_t)tcp_local_dack_interval :
15205 			    (clock_t)tcp_deferred_ack_interval));
15206 		}
15207 	}
15208 	if (flags & TH_ORDREL_NEEDED) {
15209 		/*
15210 		 * Send up the ordrel_ind unless we are an eager guy.
15211 		 * In the eager case tcp_rsrv will do this when run
15212 		 * after tcp_accept is done.
15213 		 */
15214 		ASSERT(tcp->tcp_listener == NULL);
15215 		if (tcp->tcp_rcv_list != NULL) {
15216 			/*
15217 			 * Push any mblk(s) enqueued from co processing.
15218 			 */
15219 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15220 		}
15221 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15222 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15223 			tcp->tcp_ordrel_done = B_TRUE;
15224 			putnext(tcp->tcp_rq, mp1);
15225 			if (tcp->tcp_deferred_clean_death) {
15226 				/*
15227 				 * tcp_clean_death was deferred
15228 				 * for T_ORDREL_IND - do it now
15229 				 */
15230 				(void) tcp_clean_death(tcp,
15231 				    tcp->tcp_client_errno, 20);
15232 				tcp->tcp_deferred_clean_death =	B_FALSE;
15233 			}
15234 		} else {
15235 			/*
15236 			 * Run the orderly release in the
15237 			 * service routine.
15238 			 */
15239 			qenable(tcp->tcp_rq);
15240 			/*
15241 			 * Caveat(XXX): The machine may be so
15242 			 * overloaded that tcp_rsrv() is not scheduled
15243 			 * until after the endpoint has transitioned
15244 			 * to TCPS_TIME_WAIT
15245 			 * and tcp_time_wait_interval expires. Then
15246 			 * tcp_timer() will blow away state in tcp_t
15247 			 * and T_ORDREL_IND will never be delivered
15248 			 * upstream. Unlikely but potentially
15249 			 * a problem.
15250 			 */
15251 		}
15252 	}
15253 done:
15254 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15255 }
15256 
15257 /*
15258  * This function does PAWS protection check. Returns B_TRUE if the
15259  * segment passes the PAWS test, else returns B_FALSE.
15260  */
15261 boolean_t
15262 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15263 {
15264 	uint8_t	flags;
15265 	int	options;
15266 	uint8_t *up;
15267 
15268 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15269 	/*
15270 	 * If timestamp option is aligned nicely, get values inline,
15271 	 * otherwise call general routine to parse.  Only do that
15272 	 * if timestamp is the only option.
15273 	 */
15274 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15275 	    TCPOPT_REAL_TS_LEN &&
15276 	    OK_32PTR((up = ((uint8_t *)tcph) +
15277 	    TCP_MIN_HEADER_LENGTH)) &&
15278 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15279 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15280 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15281 
15282 		options = TCP_OPT_TSTAMP_PRESENT;
15283 	} else {
15284 		if (tcp->tcp_snd_sack_ok) {
15285 			tcpoptp->tcp = tcp;
15286 		} else {
15287 			tcpoptp->tcp = NULL;
15288 		}
15289 		options = tcp_parse_options(tcph, tcpoptp);
15290 	}
15291 
15292 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15293 		/*
15294 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15295 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15296 		 */
15297 		if ((flags & TH_RST) == 0 &&
15298 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15299 		    tcp->tcp_ts_recent)) {
15300 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15301 			    PAWS_TIMEOUT)) {
15302 				/* This segment is not acceptable. */
15303 				return (B_FALSE);
15304 			} else {
15305 				/*
15306 				 * Connection has been idle for
15307 				 * too long.  Reset the timestamp
15308 				 * and assume the segment is valid.
15309 				 */
15310 				tcp->tcp_ts_recent =
15311 				    tcpoptp->tcp_opt_ts_val;
15312 			}
15313 		}
15314 	} else {
15315 		/*
15316 		 * If we don't get a timestamp on every packet, we
15317 		 * figure we can't really trust 'em, so we stop sending
15318 		 * and parsing them.
15319 		 */
15320 		tcp->tcp_snd_ts_ok = B_FALSE;
15321 
15322 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15323 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15324 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15325 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
15326 		if (tcp->tcp_snd_sack_ok) {
15327 			ASSERT(tcp->tcp_sack_info != NULL);
15328 			tcp->tcp_max_sack_blk = 4;
15329 		}
15330 	}
15331 	return (B_TRUE);
15332 }
15333 
15334 /*
15335  * Attach ancillary data to a received TCP segments for the
15336  * ancillary pieces requested by the application that are
15337  * different than they were in the previous data segment.
15338  *
15339  * Save the "current" values once memory allocation is ok so that
15340  * when memory allocation fails we can just wait for the next data segment.
15341  */
15342 static mblk_t *
15343 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15344 {
15345 	struct T_optdata_ind *todi;
15346 	int optlen;
15347 	uchar_t *optptr;
15348 	struct T_opthdr *toh;
15349 	uint_t addflag;	/* Which pieces to add */
15350 	mblk_t *mp1;
15351 
15352 	optlen = 0;
15353 	addflag = 0;
15354 	/* If app asked for pktinfo and the index has changed ... */
15355 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15356 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15357 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15358 		optlen += sizeof (struct T_opthdr) +
15359 		    sizeof (struct in6_pktinfo);
15360 		addflag |= TCP_IPV6_RECVPKTINFO;
15361 	}
15362 	/* If app asked for hoplimit and it has changed ... */
15363 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15364 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15365 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15366 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15367 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15368 	}
15369 	/* If app asked for tclass and it has changed ... */
15370 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15371 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15372 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15373 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15374 		addflag |= TCP_IPV6_RECVTCLASS;
15375 	}
15376 	/* If app asked for hopbyhop headers and it has changed ... */
15377 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15378 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15379 		(ipp->ipp_fields & IPPF_HOPOPTS),
15380 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15381 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
15382 		addflag |= TCP_IPV6_RECVHOPOPTS;
15383 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
15384 		    &tcp->tcp_hopoptslen,
15385 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15386 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15387 			return (mp);
15388 	}
15389 	/* If app asked for dst headers before routing headers ... */
15390 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15391 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15392 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15393 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15394 		optlen += sizeof (struct T_opthdr) +
15395 		    ipp->ipp_rtdstoptslen;
15396 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15397 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
15398 		    &tcp->tcp_rtdstoptslen,
15399 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15400 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15401 			return (mp);
15402 	}
15403 	/* If app asked for routing headers and it has changed ... */
15404 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15405 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15406 		(ipp->ipp_fields & IPPF_RTHDR),
15407 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15408 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15409 		addflag |= TCP_IPV6_RECVRTHDR;
15410 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
15411 		    &tcp->tcp_rthdrlen,
15412 		    (ipp->ipp_fields & IPPF_RTHDR),
15413 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15414 			return (mp);
15415 	}
15416 	/* If app asked for dest headers and it has changed ... */
15417 	if ((tcp->tcp_ipv6_recvancillary &
15418 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15419 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15420 		(ipp->ipp_fields & IPPF_DSTOPTS),
15421 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15422 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15423 		addflag |= TCP_IPV6_RECVDSTOPTS;
15424 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
15425 		    &tcp->tcp_dstoptslen,
15426 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15427 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15428 			return (mp);
15429 	}
15430 
15431 	if (optlen == 0) {
15432 		/* Nothing to add */
15433 		return (mp);
15434 	}
15435 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15436 	if (mp1 == NULL) {
15437 		/*
15438 		 * Defer sending ancillary data until the next TCP segment
15439 		 * arrives.
15440 		 */
15441 		return (mp);
15442 	}
15443 	mp1->b_cont = mp;
15444 	mp = mp1;
15445 	mp->b_wptr += sizeof (*todi) + optlen;
15446 	mp->b_datap->db_type = M_PROTO;
15447 	todi = (struct T_optdata_ind *)mp->b_rptr;
15448 	todi->PRIM_type = T_OPTDATA_IND;
15449 	todi->DATA_flag = 1;	/* MORE data */
15450 	todi->OPT_length = optlen;
15451 	todi->OPT_offset = sizeof (*todi);
15452 	optptr = (uchar_t *)&todi[1];
15453 	/*
15454 	 * If app asked for pktinfo and the index has changed ...
15455 	 * Note that the local address never changes for the connection.
15456 	 */
15457 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15458 		struct in6_pktinfo *pkti;
15459 
15460 		toh = (struct T_opthdr *)optptr;
15461 		toh->level = IPPROTO_IPV6;
15462 		toh->name = IPV6_PKTINFO;
15463 		toh->len = sizeof (*toh) + sizeof (*pkti);
15464 		toh->status = 0;
15465 		optptr += sizeof (*toh);
15466 		pkti = (struct in6_pktinfo *)optptr;
15467 		if (tcp->tcp_ipversion == IPV6_VERSION)
15468 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15469 		else
15470 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15471 			    &pkti->ipi6_addr);
15472 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15473 		optptr += sizeof (*pkti);
15474 		ASSERT(OK_32PTR(optptr));
15475 		/* Save as "last" value */
15476 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15477 	}
15478 	/* If app asked for hoplimit and it has changed ... */
15479 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15480 		toh = (struct T_opthdr *)optptr;
15481 		toh->level = IPPROTO_IPV6;
15482 		toh->name = IPV6_HOPLIMIT;
15483 		toh->len = sizeof (*toh) + sizeof (uint_t);
15484 		toh->status = 0;
15485 		optptr += sizeof (*toh);
15486 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15487 		optptr += sizeof (uint_t);
15488 		ASSERT(OK_32PTR(optptr));
15489 		/* Save as "last" value */
15490 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15491 	}
15492 	/* If app asked for tclass and it has changed ... */
15493 	if (addflag & TCP_IPV6_RECVTCLASS) {
15494 		toh = (struct T_opthdr *)optptr;
15495 		toh->level = IPPROTO_IPV6;
15496 		toh->name = IPV6_TCLASS;
15497 		toh->len = sizeof (*toh) + sizeof (uint_t);
15498 		toh->status = 0;
15499 		optptr += sizeof (*toh);
15500 		*(uint_t *)optptr = ipp->ipp_tclass;
15501 		optptr += sizeof (uint_t);
15502 		ASSERT(OK_32PTR(optptr));
15503 		/* Save as "last" value */
15504 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15505 	}
15506 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15507 		toh = (struct T_opthdr *)optptr;
15508 		toh->level = IPPROTO_IPV6;
15509 		toh->name = IPV6_HOPOPTS;
15510 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
15511 		toh->status = 0;
15512 		optptr += sizeof (*toh);
15513 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
15514 		optptr += ipp->ipp_hopoptslen;
15515 		ASSERT(OK_32PTR(optptr));
15516 		/* Save as last value */
15517 		tcp_savebuf((void **)&tcp->tcp_hopopts,
15518 		    &tcp->tcp_hopoptslen,
15519 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15520 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15521 	}
15522 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15523 		toh = (struct T_opthdr *)optptr;
15524 		toh->level = IPPROTO_IPV6;
15525 		toh->name = IPV6_RTHDRDSTOPTS;
15526 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15527 		toh->status = 0;
15528 		optptr += sizeof (*toh);
15529 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15530 		optptr += ipp->ipp_rtdstoptslen;
15531 		ASSERT(OK_32PTR(optptr));
15532 		/* Save as last value */
15533 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
15534 		    &tcp->tcp_rtdstoptslen,
15535 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15536 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15537 	}
15538 	if (addflag & TCP_IPV6_RECVRTHDR) {
15539 		toh = (struct T_opthdr *)optptr;
15540 		toh->level = IPPROTO_IPV6;
15541 		toh->name = IPV6_RTHDR;
15542 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15543 		toh->status = 0;
15544 		optptr += sizeof (*toh);
15545 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15546 		optptr += ipp->ipp_rthdrlen;
15547 		ASSERT(OK_32PTR(optptr));
15548 		/* Save as last value */
15549 		tcp_savebuf((void **)&tcp->tcp_rthdr,
15550 		    &tcp->tcp_rthdrlen,
15551 		    (ipp->ipp_fields & IPPF_RTHDR),
15552 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15553 	}
15554 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15555 		toh = (struct T_opthdr *)optptr;
15556 		toh->level = IPPROTO_IPV6;
15557 		toh->name = IPV6_DSTOPTS;
15558 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15559 		toh->status = 0;
15560 		optptr += sizeof (*toh);
15561 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15562 		optptr += ipp->ipp_dstoptslen;
15563 		ASSERT(OK_32PTR(optptr));
15564 		/* Save as last value */
15565 		tcp_savebuf((void **)&tcp->tcp_dstopts,
15566 		    &tcp->tcp_dstoptslen,
15567 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15568 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15569 	}
15570 	ASSERT(optptr == mp->b_wptr);
15571 	return (mp);
15572 }
15573 
15574 
15575 /*
15576  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15577  * or a "bad" IRE detected by tcp_adapt_ire.
15578  * We can't tell if the failure was due to the laddr or the faddr
15579  * thus we clear out all addresses and ports.
15580  */
15581 static void
15582 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15583 {
15584 	queue_t	*q = tcp->tcp_rq;
15585 	tcph_t	*tcph;
15586 	struct T_error_ack *tea;
15587 	conn_t	*connp = tcp->tcp_connp;
15588 
15589 
15590 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15591 
15592 	if (mp->b_cont) {
15593 		freemsg(mp->b_cont);
15594 		mp->b_cont = NULL;
15595 	}
15596 	tea = (struct T_error_ack *)mp->b_rptr;
15597 	switch (tea->PRIM_type) {
15598 	case T_BIND_ACK:
15599 		/*
15600 		 * Need to unbind with classifier since we were just told that
15601 		 * our bind succeeded.
15602 		 */
15603 		tcp->tcp_hard_bound = B_FALSE;
15604 		tcp->tcp_hard_binding = B_FALSE;
15605 
15606 		ipcl_hash_remove(connp);
15607 		/* Reuse the mblk if possible */
15608 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15609 			sizeof (*tea));
15610 		mp->b_rptr = mp->b_datap->db_base;
15611 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15612 		tea = (struct T_error_ack *)mp->b_rptr;
15613 		tea->PRIM_type = T_ERROR_ACK;
15614 		tea->TLI_error = TSYSERR;
15615 		tea->UNIX_error = error;
15616 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15617 			tea->ERROR_prim = T_CONN_REQ;
15618 		} else {
15619 			tea->ERROR_prim = O_T_BIND_REQ;
15620 		}
15621 		break;
15622 
15623 	case T_ERROR_ACK:
15624 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15625 			tea->ERROR_prim = T_CONN_REQ;
15626 		break;
15627 	default:
15628 		panic("tcp_bind_failed: unexpected TPI type");
15629 		/*NOTREACHED*/
15630 	}
15631 
15632 	tcp->tcp_state = TCPS_IDLE;
15633 	if (tcp->tcp_ipversion == IPV4_VERSION)
15634 		tcp->tcp_ipha->ipha_src = 0;
15635 	else
15636 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15637 	/*
15638 	 * Copy of the src addr. in tcp_t is needed since
15639 	 * the lookup funcs. can only look at tcp_t
15640 	 */
15641 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15642 
15643 	tcph = tcp->tcp_tcph;
15644 	tcph->th_lport[0] = 0;
15645 	tcph->th_lport[1] = 0;
15646 	tcp_bind_hash_remove(tcp);
15647 	bzero(&connp->u_port, sizeof (connp->u_port));
15648 	/* blow away saved option results if any */
15649 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15650 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15651 
15652 	conn_delete_ire(tcp->tcp_connp, NULL);
15653 	putnext(q, mp);
15654 }
15655 
15656 /*
15657  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15658  * messages.
15659  */
15660 void
15661 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15662 {
15663 	mblk_t	*mp1;
15664 	uchar_t	*rptr = mp->b_rptr;
15665 	queue_t	*q = tcp->tcp_rq;
15666 	struct T_error_ack *tea;
15667 	uint32_t mss;
15668 	mblk_t *syn_mp;
15669 	mblk_t *mdti;
15670 	int	retval;
15671 	mblk_t *ire_mp;
15672 
15673 	switch (mp->b_datap->db_type) {
15674 	case M_PROTO:
15675 	case M_PCPROTO:
15676 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15677 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15678 			break;
15679 		tea = (struct T_error_ack *)rptr;
15680 		switch (tea->PRIM_type) {
15681 		case T_BIND_ACK:
15682 			/*
15683 			 * Adapt Multidata information, if any.  The
15684 			 * following tcp_mdt_update routine will free
15685 			 * the message.
15686 			 */
15687 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15688 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15689 				    b_rptr)->mdt_capab, B_TRUE);
15690 				freemsg(mdti);
15691 			}
15692 
15693 			/* Get the IRE, if we had requested for it */
15694 			ire_mp = tcp_ire_mp(mp);
15695 
15696 			if (tcp->tcp_hard_binding) {
15697 				tcp->tcp_hard_binding = B_FALSE;
15698 				tcp->tcp_hard_bound = B_TRUE;
15699 				CL_INET_CONNECT(tcp);
15700 			} else {
15701 				if (ire_mp != NULL)
15702 					freeb(ire_mp);
15703 				goto after_syn_sent;
15704 			}
15705 
15706 			retval = tcp_adapt_ire(tcp, ire_mp);
15707 			if (ire_mp != NULL)
15708 				freeb(ire_mp);
15709 			if (retval == 0) {
15710 				tcp_bind_failed(tcp, mp,
15711 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15712 				    ENETUNREACH : EADDRNOTAVAIL));
15713 				return;
15714 			}
15715 			/*
15716 			 * Don't let an endpoint connect to itself.
15717 			 * Also checked in tcp_connect() but that
15718 			 * check can't handle the case when the
15719 			 * local IP address is INADDR_ANY.
15720 			 */
15721 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15722 				if ((tcp->tcp_ipha->ipha_dst ==
15723 				    tcp->tcp_ipha->ipha_src) &&
15724 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15725 				    tcp->tcp_tcph->th_fport))) {
15726 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15727 					return;
15728 				}
15729 			} else {
15730 				if (IN6_ARE_ADDR_EQUAL(
15731 				    &tcp->tcp_ip6h->ip6_dst,
15732 				    &tcp->tcp_ip6h->ip6_src) &&
15733 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15734 				    tcp->tcp_tcph->th_fport))) {
15735 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15736 					return;
15737 				}
15738 			}
15739 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15740 			/*
15741 			 * This should not be possible!  Just for
15742 			 * defensive coding...
15743 			 */
15744 			if (tcp->tcp_state != TCPS_SYN_SENT)
15745 				goto after_syn_sent;
15746 
15747 			ASSERT(q == tcp->tcp_rq);
15748 			/*
15749 			 * tcp_adapt_ire() does not adjust
15750 			 * for TCP/IP header length.
15751 			 */
15752 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15753 
15754 			/*
15755 			 * Just make sure our rwnd is at
15756 			 * least tcp_recv_hiwat_mss * MSS
15757 			 * large, and round up to the nearest
15758 			 * MSS.
15759 			 *
15760 			 * We do the round up here because
15761 			 * we need to get the interface
15762 			 * MTU first before we can do the
15763 			 * round up.
15764 			 */
15765 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15766 			    tcp_recv_hiwat_minmss * mss);
15767 			q->q_hiwat = tcp->tcp_rwnd;
15768 			tcp_set_ws_value(tcp);
15769 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15770 			    tcp->tcp_tcph->th_win);
15771 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15772 				tcp->tcp_snd_ws_ok = B_TRUE;
15773 
15774 			/*
15775 			 * Set tcp_snd_ts_ok to true
15776 			 * so that tcp_xmit_mp will
15777 			 * include the timestamp
15778 			 * option in the SYN segment.
15779 			 */
15780 			if (tcp_tstamp_always ||
15781 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15782 				tcp->tcp_snd_ts_ok = B_TRUE;
15783 			}
15784 
15785 			/*
15786 			 * tcp_snd_sack_ok can be set in
15787 			 * tcp_adapt_ire() if the sack metric
15788 			 * is set.  So check it here also.
15789 			 */
15790 			if (tcp_sack_permitted == 2 ||
15791 			    tcp->tcp_snd_sack_ok) {
15792 				if (tcp->tcp_sack_info == NULL) {
15793 					tcp->tcp_sack_info =
15794 					kmem_cache_alloc(tcp_sack_info_cache,
15795 					    KM_SLEEP);
15796 				}
15797 				tcp->tcp_snd_sack_ok = B_TRUE;
15798 			}
15799 
15800 			/*
15801 			 * Should we use ECN?  Note that the current
15802 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15803 			 * is 1.  The reason for doing this is that there
15804 			 * are equipments out there that will drop ECN
15805 			 * enabled IP packets.  Setting it to 1 avoids
15806 			 * compatibility problems.
15807 			 */
15808 			if (tcp_ecn_permitted == 2)
15809 				tcp->tcp_ecn_ok = B_TRUE;
15810 
15811 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15812 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15813 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15814 			if (syn_mp) {
15815 				cred_t *cr;
15816 				pid_t pid;
15817 
15818 				/*
15819 				 * Obtain the credential from the
15820 				 * thread calling connect(); the credential
15821 				 * lives on in the second mblk which
15822 				 * originated from T_CONN_REQ and is echoed
15823 				 * with the T_BIND_ACK from ip.  If none
15824 				 * can be found, default to the creator
15825 				 * of the socket.
15826 				 */
15827 				if (mp->b_cont == NULL ||
15828 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15829 					cr = tcp->tcp_cred;
15830 					pid = tcp->tcp_cpid;
15831 				} else {
15832 					pid = DB_CPID(mp->b_cont);
15833 				}
15834 
15835 				TCP_RECORD_TRACE(tcp, syn_mp,
15836 				    TCP_TRACE_SEND_PKT);
15837 				mblk_setcred(syn_mp, cr);
15838 				DB_CPID(syn_mp) = pid;
15839 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15840 			}
15841 		after_syn_sent:
15842 			/*
15843 			 * A trailer mblk indicates a waiting client upstream.
15844 			 * We complete here the processing begun in
15845 			 * either tcp_bind() or tcp_connect() by passing
15846 			 * upstream the reply message they supplied.
15847 			 */
15848 			mp1 = mp;
15849 			mp = mp->b_cont;
15850 			freeb(mp1);
15851 			if (mp)
15852 				break;
15853 			return;
15854 		case T_ERROR_ACK:
15855 			if (tcp->tcp_debug) {
15856 				(void) strlog(TCP_MODULE_ID, 0, 1,
15857 				    SL_TRACE|SL_ERROR,
15858 				    "tcp_rput_other: case T_ERROR_ACK, "
15859 				    "ERROR_prim == %d",
15860 				    tea->ERROR_prim);
15861 			}
15862 			switch (tea->ERROR_prim) {
15863 			case O_T_BIND_REQ:
15864 			case T_BIND_REQ:
15865 				tcp_bind_failed(tcp, mp,
15866 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15867 				    ENETUNREACH : EADDRNOTAVAIL));
15868 				return;
15869 			case T_UNBIND_REQ:
15870 				tcp->tcp_hard_binding = B_FALSE;
15871 				tcp->tcp_hard_bound = B_FALSE;
15872 				if (mp->b_cont) {
15873 					freemsg(mp->b_cont);
15874 					mp->b_cont = NULL;
15875 				}
15876 				if (tcp->tcp_unbind_pending)
15877 					tcp->tcp_unbind_pending = 0;
15878 				else {
15879 					/* From tcp_ip_unbind() - free */
15880 					freemsg(mp);
15881 					return;
15882 				}
15883 				break;
15884 			case T_SVR4_OPTMGMT_REQ:
15885 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15886 					/* T_OPTMGMT_REQ generated by TCP */
15887 					printf("T_SVR4_OPTMGMT_REQ failed "
15888 					    "%d/%d - dropped (cnt %d)\n",
15889 					    tea->TLI_error, tea->UNIX_error,
15890 					    tcp->tcp_drop_opt_ack_cnt);
15891 					freemsg(mp);
15892 					tcp->tcp_drop_opt_ack_cnt--;
15893 					return;
15894 				}
15895 				break;
15896 			}
15897 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15898 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15899 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15900 				    "- dropped (cnt %d)\n",
15901 				    tea->TLI_error, tea->UNIX_error,
15902 				    tcp->tcp_drop_opt_ack_cnt);
15903 				freemsg(mp);
15904 				tcp->tcp_drop_opt_ack_cnt--;
15905 				return;
15906 			}
15907 			break;
15908 		case T_OPTMGMT_ACK:
15909 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15910 				/* T_OPTMGMT_REQ generated by TCP */
15911 				freemsg(mp);
15912 				tcp->tcp_drop_opt_ack_cnt--;
15913 				return;
15914 			}
15915 			break;
15916 		default:
15917 			break;
15918 		}
15919 		break;
15920 	case M_CTL:
15921 		/*
15922 		 * ICMP messages.
15923 		 */
15924 		tcp_icmp_error(tcp, mp);
15925 		return;
15926 	case M_FLUSH:
15927 		if (*rptr & FLUSHR)
15928 			flushq(q, FLUSHDATA);
15929 		break;
15930 	default:
15931 		break;
15932 	}
15933 	/*
15934 	 * Make sure we set this bit before sending the ACK for
15935 	 * bind. Otherwise accept could possibly run and free
15936 	 * this tcp struct.
15937 	 */
15938 	putnext(q, mp);
15939 }
15940 
15941 /*
15942  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15943  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15944  * tcp_rsrv() try again.
15945  */
15946 static void
15947 tcp_ordrel_kick(void *arg)
15948 {
15949 	conn_t 	*connp = (conn_t *)arg;
15950 	tcp_t	*tcp = connp->conn_tcp;
15951 
15952 	tcp->tcp_ordrelid = 0;
15953 	tcp->tcp_timeout = B_FALSE;
15954 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15955 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15956 		qenable(tcp->tcp_rq);
15957 	}
15958 }
15959 
15960 /* ARGSUSED */
15961 static void
15962 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15963 {
15964 	conn_t	*connp = (conn_t *)arg;
15965 	tcp_t	*tcp = connp->conn_tcp;
15966 	queue_t	*q = tcp->tcp_rq;
15967 	uint_t	thwin;
15968 
15969 	freeb(mp);
15970 
15971 	TCP_STAT(tcp_rsrv_calls);
15972 
15973 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15974 		return;
15975 	}
15976 
15977 	if (tcp->tcp_fused) {
15978 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15979 
15980 		ASSERT(tcp->tcp_fused);
15981 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15982 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15983 		ASSERT(!TCP_IS_DETACHED(tcp));
15984 		ASSERT(tcp->tcp_connp->conn_sqp ==
15985 		    peer_tcp->tcp_connp->conn_sqp);
15986 
15987 		if (tcp->tcp_rcv_list != NULL)
15988 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15989 
15990 		tcp_clrqfull(peer_tcp);
15991 		peer_tcp->tcp_flow_stopped = B_FALSE;
15992 		TCP_STAT(tcp_fusion_backenabled);
15993 		return;
15994 	}
15995 
15996 	if (canputnext(q)) {
15997 		tcp->tcp_rwnd = q->q_hiwat;
15998 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15999 		    << tcp->tcp_rcv_ws;
16000 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16001 		/*
16002 		 * Send back a window update immediately if TCP is above
16003 		 * ESTABLISHED state and the increase of the rcv window
16004 		 * that the other side knows is at least 1 MSS after flow
16005 		 * control is lifted.
16006 		 */
16007 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16008 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16009 			tcp_xmit_ctl(NULL, tcp,
16010 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16011 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16012 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
16013 		}
16014 	}
16015 	/* Handle a failure to allocate a T_ORDREL_IND here */
16016 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16017 		ASSERT(tcp->tcp_listener == NULL);
16018 		if (tcp->tcp_rcv_list != NULL) {
16019 			(void) tcp_rcv_drain(q, tcp);
16020 		}
16021 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
16022 		mp = mi_tpi_ordrel_ind();
16023 		if (mp) {
16024 			tcp->tcp_ordrel_done = B_TRUE;
16025 			putnext(q, mp);
16026 			if (tcp->tcp_deferred_clean_death) {
16027 				/*
16028 				 * tcp_clean_death was deferred for
16029 				 * T_ORDREL_IND - do it now
16030 				 */
16031 				tcp->tcp_deferred_clean_death = B_FALSE;
16032 				(void) tcp_clean_death(tcp,
16033 				    tcp->tcp_client_errno, 22);
16034 			}
16035 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16036 			/*
16037 			 * If there isn't already a timer running
16038 			 * start one.  Use a 4 second
16039 			 * timer as a fallback since it can't fail.
16040 			 */
16041 			tcp->tcp_timeout = B_TRUE;
16042 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16043 			    MSEC_TO_TICK(4000));
16044 		}
16045 	}
16046 }
16047 
16048 /*
16049  * The read side service routine is called mostly when we get back-enabled as a
16050  * result of flow control relief.  Since we don't actually queue anything in
16051  * TCP, we have no data to send out of here.  What we do is clear the receive
16052  * window, and send out a window update.
16053  * This routine is also called to drive an orderly release message upstream
16054  * if the attempt in tcp_rput failed.
16055  */
16056 static void
16057 tcp_rsrv(queue_t *q)
16058 {
16059 	conn_t *connp = Q_TO_CONN(q);
16060 	tcp_t	*tcp = connp->conn_tcp;
16061 	mblk_t	*mp;
16062 
16063 	/* No code does a putq on the read side */
16064 	ASSERT(q->q_first == NULL);
16065 
16066 	/* Nothing to do for the default queue */
16067 	if (q == tcp_g_q) {
16068 		return;
16069 	}
16070 
16071 	mp = allocb(0, BPRI_HI);
16072 	if (mp == NULL) {
16073 		/*
16074 		 * We are under memory pressure. Return for now and we
16075 		 * we will be called again later.
16076 		 */
16077 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16078 			/*
16079 			 * If there isn't already a timer running
16080 			 * start one.  Use a 4 second
16081 			 * timer as a fallback since it can't fail.
16082 			 */
16083 			tcp->tcp_timeout = B_TRUE;
16084 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16085 			    MSEC_TO_TICK(4000));
16086 		}
16087 		return;
16088 	}
16089 	CONN_INC_REF(connp);
16090 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16091 	    SQTAG_TCP_RSRV);
16092 }
16093 
16094 /*
16095  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16096  * We do not allow the receive window to shrink.  After setting rwnd,
16097  * set the flow control hiwat of the stream.
16098  *
16099  * This function is called in 2 cases:
16100  *
16101  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16102  *    connection (passive open) and in tcp_rput_data() for active connect.
16103  *    This is called after tcp_mss_set() when the desired MSS value is known.
16104  *    This makes sure that our window size is a mutiple of the other side's
16105  *    MSS.
16106  * 2) Handling SO_RCVBUF option.
16107  *
16108  * It is ASSUMED that the requested size is a multiple of the current MSS.
16109  *
16110  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16111  * user requests so.
16112  */
16113 static int
16114 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16115 {
16116 	uint32_t	mss = tcp->tcp_mss;
16117 	uint32_t	old_max_rwnd;
16118 	uint32_t	max_transmittable_rwnd;
16119 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16120 
16121 	if (tcp_detached)
16122 		old_max_rwnd = tcp->tcp_rwnd;
16123 	else
16124 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16125 
16126 	/*
16127 	 * Insist on a receive window that is at least
16128 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16129 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16130 	 * and delayed acknowledgement.
16131 	 */
16132 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
16133 
16134 	/*
16135 	 * If window size info has already been exchanged, TCP should not
16136 	 * shrink the window.  Shrinking window is doable if done carefully.
16137 	 * We may add that support later.  But so far there is not a real
16138 	 * need to do that.
16139 	 */
16140 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16141 		/* MSS may have changed, do a round up again. */
16142 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16143 	}
16144 
16145 	/*
16146 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16147 	 * can be applied even before the window scale option is decided.
16148 	 */
16149 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16150 	if (rwnd > max_transmittable_rwnd) {
16151 		rwnd = max_transmittable_rwnd -
16152 		    (max_transmittable_rwnd % mss);
16153 		if (rwnd < mss)
16154 			rwnd = max_transmittable_rwnd;
16155 		/*
16156 		 * If we're over the limit we may have to back down tcp_rwnd.
16157 		 * The increment below won't work for us. So we set all three
16158 		 * here and the increment below will have no effect.
16159 		 */
16160 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16161 	}
16162 	if (tcp->tcp_localnet) {
16163 		tcp->tcp_rack_abs_max =
16164 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
16165 	} else {
16166 		/*
16167 		 * For a remote host on a different subnet (through a router),
16168 		 * we ack every other packet to be conforming to RFC1122.
16169 		 * tcp_deferred_acks_max is default to 2.
16170 		 */
16171 		tcp->tcp_rack_abs_max =
16172 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
16173 	}
16174 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16175 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16176 	else
16177 		tcp->tcp_rack_cur_max = 0;
16178 	/*
16179 	 * Increment the current rwnd by the amount the maximum grew (we
16180 	 * can not overwrite it since we might be in the middle of a
16181 	 * connection.)
16182 	 */
16183 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16184 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16185 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16186 		tcp->tcp_cwnd_max = rwnd;
16187 
16188 	if (tcp_detached)
16189 		return (rwnd);
16190 	/*
16191 	 * We set the maximum receive window into rq->q_hiwat.
16192 	 * This is not actually used for flow control.
16193 	 */
16194 	tcp->tcp_rq->q_hiwat = rwnd;
16195 	/*
16196 	 * Set the Stream head high water mark. This doesn't have to be
16197 	 * here, since we are simply using default values, but we would
16198 	 * prefer to choose these values algorithmically, with a likely
16199 	 * relationship to rwnd.  For fused loopback tcp, we double the
16200 	 * amount of buffer in order to simulate the normal tcp case.
16201 	 */
16202 	if (tcp->tcp_fused) {
16203 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd << 1,
16204 		    tcp_sth_rcv_hiwat));
16205 	} else {
16206 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd,
16207 		    tcp_sth_rcv_hiwat));
16208 	}
16209 	return (rwnd);
16210 }
16211 
16212 /*
16213  * Return SNMP stuff in buffer in mpdata.
16214  */
16215 static int
16216 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16217 {
16218 	mblk_t			*mpdata;
16219 	mblk_t			*mp_conn_ctl = NULL;
16220 	mblk_t			*mp_conn_data;
16221 	mblk_t			*mp6_conn_ctl = NULL;
16222 	mblk_t			*mp6_conn_data;
16223 	mblk_t			*mp_conn_tail = NULL;
16224 	mblk_t			*mp6_conn_tail = NULL;
16225 	struct opthdr		*optp;
16226 	mib2_tcpConnEntry_t	tce;
16227 	mib2_tcp6ConnEntry_t	tce6;
16228 	connf_t			*connfp;
16229 	conn_t			*connp;
16230 	int			i;
16231 	boolean_t 		ispriv;
16232 	zoneid_t 		zoneid;
16233 
16234 	if (mpctl == NULL ||
16235 	    (mpdata = mpctl->b_cont) == NULL ||
16236 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16237 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
16238 		if (mp_conn_ctl != NULL)
16239 			freemsg(mp_conn_ctl);
16240 		if (mp6_conn_ctl != NULL)
16241 			freemsg(mp6_conn_ctl);
16242 		return (0);
16243 	}
16244 
16245 	/* build table of connections -- need count in fixed part */
16246 	mp_conn_data = mp_conn_ctl->b_cont;
16247 	mp6_conn_data = mp6_conn_ctl->b_cont;
16248 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
16249 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
16250 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
16251 	SET_MIB(tcp_mib.tcpMaxConn, -1);
16252 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
16253 
16254 	ispriv =
16255 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16256 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16257 
16258 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16259 
16260 		connfp = &ipcl_globalhash_fanout[i];
16261 
16262 		connp = NULL;
16263 
16264 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16265 			tcp_t *tcp;
16266 
16267 			if (connp->conn_zoneid != zoneid)
16268 				continue;	/* not in this zone */
16269 
16270 			tcp = connp->conn_tcp;
16271 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
16272 			tcp->tcp_ibsegs = 0;
16273 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
16274 			tcp->tcp_obsegs = 0;
16275 
16276 			tce6.tcp6ConnState = tce.tcpConnState =
16277 			    tcp_snmp_state(tcp);
16278 			if (tce.tcpConnState == MIB2_TCP_established ||
16279 			    tce.tcpConnState == MIB2_TCP_closeWait)
16280 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
16281 
16282 			/* Create a message to report on IPv6 entries */
16283 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16284 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16285 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16286 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16287 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16288 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16289 			/* Don't want just anybody seeing these... */
16290 			if (ispriv) {
16291 				tce6.tcp6ConnEntryInfo.ce_snxt =
16292 				    tcp->tcp_snxt;
16293 				tce6.tcp6ConnEntryInfo.ce_suna =
16294 				    tcp->tcp_suna;
16295 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16296 				    tcp->tcp_rnxt;
16297 				tce6.tcp6ConnEntryInfo.ce_rack =
16298 				    tcp->tcp_rack;
16299 			} else {
16300 				/*
16301 				 * Netstat, unfortunately, uses this to
16302 				 * get send/receive queue sizes.  How to fix?
16303 				 * Why not compute the difference only?
16304 				 */
16305 				tce6.tcp6ConnEntryInfo.ce_snxt =
16306 				    tcp->tcp_snxt - tcp->tcp_suna;
16307 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16308 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16309 				    tcp->tcp_rnxt - tcp->tcp_rack;
16310 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16311 			}
16312 
16313 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16314 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16315 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16316 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16317 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16318 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
16319 			    (char *)&tce6, sizeof (tce6));
16320 			}
16321 			/*
16322 			 * Create an IPv4 table entry for IPv4 entries and also
16323 			 * for IPv6 entries which are bound to in6addr_any
16324 			 * but don't have IPV6_V6ONLY set.
16325 			 * (i.e. anything an IPv4 peer could connect to)
16326 			 */
16327 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16328 			    (tcp->tcp_state <= TCPS_LISTEN &&
16329 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16330 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16331 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16332 					tce.tcpConnRemAddress = INADDR_ANY;
16333 					tce.tcpConnLocalAddress = INADDR_ANY;
16334 				} else {
16335 					tce.tcpConnRemAddress =
16336 					    tcp->tcp_remote;
16337 					tce.tcpConnLocalAddress =
16338 					    tcp->tcp_ip_src;
16339 				}
16340 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16341 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16342 				/* Don't want just anybody seeing these... */
16343 				if (ispriv) {
16344 					tce.tcpConnEntryInfo.ce_snxt =
16345 					    tcp->tcp_snxt;
16346 					tce.tcpConnEntryInfo.ce_suna =
16347 					    tcp->tcp_suna;
16348 					tce.tcpConnEntryInfo.ce_rnxt =
16349 					    tcp->tcp_rnxt;
16350 					tce.tcpConnEntryInfo.ce_rack =
16351 					    tcp->tcp_rack;
16352 				} else {
16353 					/*
16354 					 * Netstat, unfortunately, uses this to
16355 					 * get send/receive queue sizes.  How
16356 					 * to fix?
16357 					 * Why not compute the difference only?
16358 					 */
16359 					tce.tcpConnEntryInfo.ce_snxt =
16360 					    tcp->tcp_snxt - tcp->tcp_suna;
16361 					tce.tcpConnEntryInfo.ce_suna = 0;
16362 					tce.tcpConnEntryInfo.ce_rnxt =
16363 					    tcp->tcp_rnxt - tcp->tcp_rack;
16364 					tce.tcpConnEntryInfo.ce_rack = 0;
16365 				}
16366 
16367 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16368 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16369 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16370 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16371 				tce.tcpConnEntryInfo.ce_state =
16372 				    tcp->tcp_state;
16373 				(void) snmp_append_data2(mp_conn_data,
16374 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16375 			}
16376 		}
16377 	}
16378 
16379 	/* fixed length structure for IPv4 and IPv6 counters */
16380 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16381 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
16382 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16383 	optp->level = MIB2_TCP;
16384 	optp->name = 0;
16385 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
16386 	optp->len = msgdsize(mpdata);
16387 	qreply(q, mpctl);
16388 
16389 	/* table of connections... */
16390 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16391 	    sizeof (struct T_optmgmt_ack)];
16392 	optp->level = MIB2_TCP;
16393 	optp->name = MIB2_TCP_CONN;
16394 	optp->len = msgdsize(mp_conn_data);
16395 	qreply(q, mp_conn_ctl);
16396 
16397 	/* table of IPv6 connections... */
16398 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16399 	    sizeof (struct T_optmgmt_ack)];
16400 	optp->level = MIB2_TCP6;
16401 	optp->name = MIB2_TCP6_CONN;
16402 	optp->len = msgdsize(mp6_conn_data);
16403 	qreply(q, mp6_conn_ctl);
16404 	return (1);
16405 }
16406 
16407 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16408 /* ARGSUSED */
16409 static int
16410 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16411 {
16412 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16413 
16414 	switch (level) {
16415 	case MIB2_TCP:
16416 		switch (name) {
16417 		case 13:
16418 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16419 				return (0);
16420 			/* TODO: delete entry defined by tce */
16421 			return (1);
16422 		default:
16423 			return (0);
16424 		}
16425 	default:
16426 		return (1);
16427 	}
16428 }
16429 
16430 /* Translate TCP state to MIB2 TCP state. */
16431 static int
16432 tcp_snmp_state(tcp_t *tcp)
16433 {
16434 	if (tcp == NULL)
16435 		return (0);
16436 
16437 	switch (tcp->tcp_state) {
16438 	case TCPS_CLOSED:
16439 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16440 	case TCPS_BOUND:
16441 		return (MIB2_TCP_closed);
16442 	case TCPS_LISTEN:
16443 		return (MIB2_TCP_listen);
16444 	case TCPS_SYN_SENT:
16445 		return (MIB2_TCP_synSent);
16446 	case TCPS_SYN_RCVD:
16447 		return (MIB2_TCP_synReceived);
16448 	case TCPS_ESTABLISHED:
16449 		return (MIB2_TCP_established);
16450 	case TCPS_CLOSE_WAIT:
16451 		return (MIB2_TCP_closeWait);
16452 	case TCPS_FIN_WAIT_1:
16453 		return (MIB2_TCP_finWait1);
16454 	case TCPS_CLOSING:
16455 		return (MIB2_TCP_closing);
16456 	case TCPS_LAST_ACK:
16457 		return (MIB2_TCP_lastAck);
16458 	case TCPS_FIN_WAIT_2:
16459 		return (MIB2_TCP_finWait2);
16460 	case TCPS_TIME_WAIT:
16461 		return (MIB2_TCP_timeWait);
16462 	default:
16463 		return (0);
16464 	}
16465 }
16466 
16467 static char tcp_report_header[] =
16468 	"TCP     " MI_COL_HDRPAD_STR
16469 	"zone dest            snxt     suna     "
16470 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16471 	"recent   [lport,fport] state";
16472 
16473 /*
16474  * TCP status report triggered via the Named Dispatch mechanism.
16475  */
16476 /* ARGSUSED */
16477 static void
16478 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16479     cred_t *cr)
16480 {
16481 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16482 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16483 	char cflag;
16484 	in6_addr_t	v6dst;
16485 	char buf[80];
16486 	uint_t print_len, buf_len;
16487 
16488 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16489 	if (buf_len <= 0)
16490 		return;
16491 
16492 	if (hashval >= 0)
16493 		(void) sprintf(hash, "%03d ", hashval);
16494 	else
16495 		hash[0] = '\0';
16496 
16497 	/*
16498 	 * Note that we use the remote address in the tcp_b  structure.
16499 	 * This means that it will print out the real destination address,
16500 	 * not the next hop's address if source routing is used.  This
16501 	 * avoid the confusion on the output because user may not
16502 	 * know that source routing is used for a connection.
16503 	 */
16504 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16505 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16506 	} else {
16507 		v6dst = tcp->tcp_remote_v6;
16508 	}
16509 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16510 	/*
16511 	 * the ispriv checks are so that normal users cannot determine
16512 	 * sequence number information using NDD.
16513 	 */
16514 
16515 	if (TCP_IS_DETACHED(tcp))
16516 		cflag = '*';
16517 	else
16518 		cflag = ' ';
16519 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16520 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16521 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16522 	    hash,
16523 	    (void *)tcp,
16524 	    tcp->tcp_connp->conn_zoneid,
16525 	    addrbuf,
16526 	    (ispriv) ? tcp->tcp_snxt : 0,
16527 	    (ispriv) ? tcp->tcp_suna : 0,
16528 	    tcp->tcp_swnd,
16529 	    (ispriv) ? tcp->tcp_rnxt : 0,
16530 	    (ispriv) ? tcp->tcp_rack : 0,
16531 	    tcp->tcp_rwnd,
16532 	    tcp->tcp_rto,
16533 	    tcp->tcp_mss,
16534 	    tcp->tcp_snd_ws_ok,
16535 	    tcp->tcp_snd_ws,
16536 	    tcp->tcp_rcv_ws,
16537 	    tcp->tcp_snd_ts_ok,
16538 	    tcp->tcp_ts_recent,
16539 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16540 	if (print_len < buf_len) {
16541 		((mblk_t *)mp)->b_wptr += print_len;
16542 	} else {
16543 		((mblk_t *)mp)->b_wptr += buf_len;
16544 	}
16545 }
16546 
16547 /*
16548  * TCP status report (for listeners only) triggered via the Named Dispatch
16549  * mechanism.
16550  */
16551 /* ARGSUSED */
16552 static void
16553 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16554 {
16555 	char addrbuf[INET6_ADDRSTRLEN];
16556 	in6_addr_t	v6dst;
16557 	uint_t print_len, buf_len;
16558 
16559 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16560 	if (buf_len <= 0)
16561 		return;
16562 
16563 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16564 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16565 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16566 	} else {
16567 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16568 		    addrbuf, sizeof (addrbuf));
16569 	}
16570 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16571 	    "%03d "
16572 	    MI_COL_PTRFMT_STR
16573 	    "%d %s %05u %08u %d/%d/%d%c\n",
16574 	    hashval, (void *)tcp,
16575 	    tcp->tcp_connp->conn_zoneid,
16576 	    addrbuf,
16577 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16578 	    tcp->tcp_conn_req_seqnum,
16579 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16580 	    tcp->tcp_conn_req_max,
16581 	    tcp->tcp_syn_defense ? '*' : ' ');
16582 	if (print_len < buf_len) {
16583 		((mblk_t *)mp)->b_wptr += print_len;
16584 	} else {
16585 		((mblk_t *)mp)->b_wptr += buf_len;
16586 	}
16587 }
16588 
16589 /* TCP status report triggered via the Named Dispatch mechanism. */
16590 /* ARGSUSED */
16591 static int
16592 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16593 {
16594 	tcp_t	*tcp;
16595 	int	i;
16596 	conn_t	*connp;
16597 	connf_t	*connfp;
16598 	zoneid_t zoneid;
16599 
16600 	/*
16601 	 * Because of the ndd constraint, at most we can have 64K buffer
16602 	 * to put in all TCP info.  So to be more efficient, just
16603 	 * allocate a 64K buffer here, assuming we need that large buffer.
16604 	 * This may be a problem as any user can read tcp_status.  Therefore
16605 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16606 	 * This should be OK as normal users should not do this too often.
16607 	 */
16608 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16609 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16610 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16611 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16612 			return (0);
16613 		}
16614 	}
16615 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16616 		/* The following may work even if we cannot get a large buf. */
16617 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16618 		return (0);
16619 	}
16620 
16621 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16622 
16623 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16624 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16625 
16626 		connfp = &ipcl_globalhash_fanout[i];
16627 
16628 		connp = NULL;
16629 
16630 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16631 			tcp = connp->conn_tcp;
16632 			if (zoneid != GLOBAL_ZONEID &&
16633 			    zoneid != connp->conn_zoneid)
16634 				continue;
16635 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16636 			    cr);
16637 		}
16638 
16639 	}
16640 
16641 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16642 	return (0);
16643 }
16644 
16645 /* TCP status report triggered via the Named Dispatch mechanism. */
16646 /* ARGSUSED */
16647 static int
16648 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16649 {
16650 	tf_t	*tbf;
16651 	tcp_t	*tcp;
16652 	int	i;
16653 	zoneid_t zoneid;
16654 
16655 	/* Refer to comments in tcp_status_report(). */
16656 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16657 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16658 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16659 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16660 			return (0);
16661 		}
16662 	}
16663 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16664 		/* The following may work even if we cannot get a large buf. */
16665 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16666 		return (0);
16667 	}
16668 
16669 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16670 
16671 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16672 
16673 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16674 		tbf = &tcp_bind_fanout[i];
16675 		mutex_enter(&tbf->tf_lock);
16676 		for (tcp = tbf->tf_tcp; tcp != NULL;
16677 		    tcp = tcp->tcp_bind_hash) {
16678 			if (zoneid != GLOBAL_ZONEID &&
16679 			    zoneid != tcp->tcp_connp->conn_zoneid)
16680 				continue;
16681 			CONN_INC_REF(tcp->tcp_connp);
16682 			tcp_report_item(mp->b_cont, tcp, i,
16683 			    Q_TO_TCP(q), cr);
16684 			CONN_DEC_REF(tcp->tcp_connp);
16685 		}
16686 		mutex_exit(&tbf->tf_lock);
16687 	}
16688 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16689 	return (0);
16690 }
16691 
16692 /* TCP status report triggered via the Named Dispatch mechanism. */
16693 /* ARGSUSED */
16694 static int
16695 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16696 {
16697 	connf_t	*connfp;
16698 	conn_t	*connp;
16699 	tcp_t	*tcp;
16700 	int	i;
16701 	zoneid_t zoneid;
16702 
16703 	/* Refer to comments in tcp_status_report(). */
16704 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16705 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16706 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16707 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16708 			return (0);
16709 		}
16710 	}
16711 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16712 		/* The following may work even if we cannot get a large buf. */
16713 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16714 		return (0);
16715 	}
16716 
16717 	(void) mi_mpprintf(mp,
16718 	    "    TCP    " MI_COL_HDRPAD_STR
16719 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16720 
16721 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16722 
16723 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16724 		connfp =  &ipcl_bind_fanout[i];
16725 		connp = NULL;
16726 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16727 			tcp = connp->conn_tcp;
16728 			if (zoneid != GLOBAL_ZONEID &&
16729 			    zoneid != connp->conn_zoneid)
16730 				continue;
16731 			tcp_report_listener(mp->b_cont, tcp, i);
16732 		}
16733 	}
16734 
16735 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16736 	return (0);
16737 }
16738 
16739 /* TCP status report triggered via the Named Dispatch mechanism. */
16740 /* ARGSUSED */
16741 static int
16742 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16743 {
16744 	connf_t	*connfp;
16745 	conn_t	*connp;
16746 	tcp_t	*tcp;
16747 	int	i;
16748 	zoneid_t zoneid;
16749 
16750 	/* Refer to comments in tcp_status_report(). */
16751 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16752 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16753 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16754 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16755 			return (0);
16756 		}
16757 	}
16758 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16759 		/* The following may work even if we cannot get a large buf. */
16760 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16761 		return (0);
16762 	}
16763 
16764 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16765 	    ipcl_conn_fanout_size);
16766 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16767 
16768 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16769 
16770 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16771 		connfp =  &ipcl_conn_fanout[i];
16772 		connp = NULL;
16773 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16774 			tcp = connp->conn_tcp;
16775 			if (zoneid != GLOBAL_ZONEID &&
16776 			    zoneid != connp->conn_zoneid)
16777 				continue;
16778 			tcp_report_item(mp->b_cont, tcp, i,
16779 			    Q_TO_TCP(q), cr);
16780 		}
16781 	}
16782 
16783 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16784 	return (0);
16785 }
16786 
16787 /* TCP status report triggered via the Named Dispatch mechanism. */
16788 /* ARGSUSED */
16789 static int
16790 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16791 {
16792 	tf_t	*tf;
16793 	tcp_t	*tcp;
16794 	int	i;
16795 	zoneid_t zoneid;
16796 
16797 	/* Refer to comments in tcp_status_report(). */
16798 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16799 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16800 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16801 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16802 			return (0);
16803 		}
16804 	}
16805 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16806 		/* The following may work even if we cannot get a large buf. */
16807 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16808 		return (0);
16809 	}
16810 
16811 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16812 
16813 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16814 
16815 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16816 		tf = &tcp_acceptor_fanout[i];
16817 		mutex_enter(&tf->tf_lock);
16818 		for (tcp = tf->tf_tcp; tcp != NULL;
16819 		    tcp = tcp->tcp_acceptor_hash) {
16820 			if (zoneid != GLOBAL_ZONEID &&
16821 			    zoneid != tcp->tcp_connp->conn_zoneid)
16822 				continue;
16823 			tcp_report_item(mp->b_cont, tcp, i,
16824 			    Q_TO_TCP(q), cr);
16825 		}
16826 		mutex_exit(&tf->tf_lock);
16827 	}
16828 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16829 	return (0);
16830 }
16831 
16832 /*
16833  * tcp_timer is the timer service routine.  It handles the retransmission,
16834  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16835  * from the state of the tcp instance what kind of action needs to be done
16836  * at the time it is called.
16837  */
16838 static void
16839 tcp_timer(void *arg)
16840 {
16841 	mblk_t		*mp;
16842 	clock_t		first_threshold;
16843 	clock_t		second_threshold;
16844 	clock_t		ms;
16845 	uint32_t	mss;
16846 	conn_t		*connp = (conn_t *)arg;
16847 	tcp_t		*tcp = connp->conn_tcp;
16848 
16849 	tcp->tcp_timer_tid = 0;
16850 
16851 	if (tcp->tcp_fused)
16852 		return;
16853 
16854 	first_threshold =  tcp->tcp_first_timer_threshold;
16855 	second_threshold = tcp->tcp_second_timer_threshold;
16856 	switch (tcp->tcp_state) {
16857 	case TCPS_IDLE:
16858 	case TCPS_BOUND:
16859 	case TCPS_LISTEN:
16860 		return;
16861 	case TCPS_SYN_RCVD: {
16862 		tcp_t	*listener = tcp->tcp_listener;
16863 
16864 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16865 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16866 			/* it's our first timeout */
16867 			tcp->tcp_syn_rcvd_timeout = 1;
16868 			mutex_enter(&listener->tcp_eager_lock);
16869 			listener->tcp_syn_rcvd_timeout++;
16870 			if (!listener->tcp_syn_defense &&
16871 			    (listener->tcp_syn_rcvd_timeout >
16872 			    (tcp_conn_req_max_q0 >> 2)) &&
16873 			    (tcp_conn_req_max_q0 > 200)) {
16874 				/* We may be under attack. Put on a defense. */
16875 				listener->tcp_syn_defense = B_TRUE;
16876 				cmn_err(CE_WARN, "High TCP connect timeout "
16877 				    "rate! System (port %d) may be under a "
16878 				    "SYN flood attack!",
16879 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16880 
16881 				listener->tcp_ip_addr_cache = kmem_zalloc(
16882 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16883 				    KM_NOSLEEP);
16884 			}
16885 			mutex_exit(&listener->tcp_eager_lock);
16886 		}
16887 	}
16888 		/* FALLTHRU */
16889 	case TCPS_SYN_SENT:
16890 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16891 		second_threshold = tcp->tcp_second_ctimer_threshold;
16892 		break;
16893 	case TCPS_ESTABLISHED:
16894 	case TCPS_FIN_WAIT_1:
16895 	case TCPS_CLOSING:
16896 	case TCPS_CLOSE_WAIT:
16897 	case TCPS_LAST_ACK:
16898 		/* If we have data to rexmit */
16899 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16900 			clock_t	time_to_wait;
16901 
16902 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16903 			if (!tcp->tcp_xmit_head)
16904 				break;
16905 			time_to_wait = lbolt -
16906 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16907 			time_to_wait = tcp->tcp_rto -
16908 			    TICK_TO_MSEC(time_to_wait);
16909 			/*
16910 			 * If the timer fires too early, 1 clock tick earlier,
16911 			 * restart the timer.
16912 			 */
16913 			if (time_to_wait > msec_per_tick) {
16914 				TCP_STAT(tcp_timer_fire_early);
16915 				TCP_TIMER_RESTART(tcp, time_to_wait);
16916 				return;
16917 			}
16918 			/*
16919 			 * When we probe zero windows, we force the swnd open.
16920 			 * If our peer acks with a closed window swnd will be
16921 			 * set to zero by tcp_rput(). As long as we are
16922 			 * receiving acks tcp_rput will
16923 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16924 			 * first and second interval actions.  NOTE: the timer
16925 			 * interval is allowed to continue its exponential
16926 			 * backoff.
16927 			 */
16928 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16929 				if (tcp->tcp_debug) {
16930 					(void) strlog(TCP_MODULE_ID, 0, 1,
16931 					    SL_TRACE, "tcp_timer: zero win");
16932 				}
16933 			} else {
16934 				/*
16935 				 * After retransmission, we need to do
16936 				 * slow start.  Set the ssthresh to one
16937 				 * half of current effective window and
16938 				 * cwnd to one MSS.  Also reset
16939 				 * tcp_cwnd_cnt.
16940 				 *
16941 				 * Note that if tcp_ssthresh is reduced because
16942 				 * of ECN, do not reduce it again unless it is
16943 				 * already one window of data away (tcp_cwr
16944 				 * should then be cleared) or this is a
16945 				 * timeout for a retransmitted segment.
16946 				 */
16947 				uint32_t npkt;
16948 
16949 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16950 					npkt = ((tcp->tcp_timer_backoff ?
16951 					    tcp->tcp_cwnd_ssthresh :
16952 					    tcp->tcp_snxt -
16953 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16954 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16955 					    tcp->tcp_mss;
16956 				}
16957 				tcp->tcp_cwnd = tcp->tcp_mss;
16958 				tcp->tcp_cwnd_cnt = 0;
16959 				if (tcp->tcp_ecn_ok) {
16960 					tcp->tcp_cwr = B_TRUE;
16961 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16962 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16963 				}
16964 			}
16965 			break;
16966 		}
16967 		/*
16968 		 * We have something to send yet we cannot send.  The
16969 		 * reason can be:
16970 		 *
16971 		 * 1. Zero send window: we need to do zero window probe.
16972 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16973 		 * segments.
16974 		 * 3. SWS avoidance: receiver may have shrunk window,
16975 		 * reset our knowledge.
16976 		 *
16977 		 * Note that condition 2 can happen with either 1 or
16978 		 * 3.  But 1 and 3 are exclusive.
16979 		 */
16980 		if (tcp->tcp_unsent != 0) {
16981 			if (tcp->tcp_cwnd == 0) {
16982 				/*
16983 				 * Set tcp_cwnd to 1 MSS so that a
16984 				 * new segment can be sent out.  We
16985 				 * are "clocking out" new data when
16986 				 * the network is really congested.
16987 				 */
16988 				ASSERT(tcp->tcp_ecn_ok);
16989 				tcp->tcp_cwnd = tcp->tcp_mss;
16990 			}
16991 			if (tcp->tcp_swnd == 0) {
16992 				/* Extend window for zero window probe */
16993 				tcp->tcp_swnd++;
16994 				tcp->tcp_zero_win_probe = B_TRUE;
16995 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16996 			} else {
16997 				/*
16998 				 * Handle timeout from sender SWS avoidance.
16999 				 * Reset our knowledge of the max send window
17000 				 * since the receiver might have reduced its
17001 				 * receive buffer.  Avoid setting tcp_max_swnd
17002 				 * to one since that will essentially disable
17003 				 * the SWS checks.
17004 				 *
17005 				 * Note that since we don't have a SWS
17006 				 * state variable, if the timeout is set
17007 				 * for ECN but not for SWS, this
17008 				 * code will also be executed.  This is
17009 				 * fine as tcp_max_swnd is updated
17010 				 * constantly and it will not affect
17011 				 * anything.
17012 				 */
17013 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17014 			}
17015 			tcp_wput_data(tcp, NULL, B_FALSE);
17016 			return;
17017 		}
17018 		/* Is there a FIN that needs to be to re retransmitted? */
17019 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17020 		    !tcp->tcp_fin_acked)
17021 			break;
17022 		/* Nothing to do, return without restarting timer. */
17023 		TCP_STAT(tcp_timer_fire_miss);
17024 		return;
17025 	case TCPS_FIN_WAIT_2:
17026 		/*
17027 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17028 		 * We waited some time for for peer's FIN, but it hasn't
17029 		 * arrived.  We flush the connection now to avoid
17030 		 * case where the peer has rebooted.
17031 		 */
17032 		if (TCP_IS_DETACHED(tcp)) {
17033 			(void) tcp_clean_death(tcp, 0, 23);
17034 		} else {
17035 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
17036 		}
17037 		return;
17038 	case TCPS_TIME_WAIT:
17039 		(void) tcp_clean_death(tcp, 0, 24);
17040 		return;
17041 	default:
17042 		if (tcp->tcp_debug) {
17043 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
17044 			    "tcp_timer: strange state (%d) %s",
17045 			    tcp->tcp_state, tcp_display(tcp, NULL,
17046 			    DISP_PORT_ONLY));
17047 		}
17048 		return;
17049 	}
17050 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17051 		/*
17052 		 * For zero window probe, we need to send indefinitely,
17053 		 * unless we have not heard from the other side for some
17054 		 * time...
17055 		 */
17056 		if ((tcp->tcp_zero_win_probe == 0) ||
17057 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17058 		    second_threshold)) {
17059 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
17060 			/*
17061 			 * If TCP is in SYN_RCVD state, send back a
17062 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17063 			 * should be zero in TCPS_SYN_RCVD state.
17064 			 */
17065 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17066 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17067 				    "in SYN_RCVD",
17068 				    tcp, tcp->tcp_snxt,
17069 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17070 			}
17071 			(void) tcp_clean_death(tcp,
17072 			    tcp->tcp_client_errno ?
17073 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17074 			return;
17075 		} else {
17076 			/*
17077 			 * Set tcp_ms_we_have_waited to second_threshold
17078 			 * so that in next timeout, we will do the above
17079 			 * check (lbolt - tcp_last_recv_time).  This is
17080 			 * also to avoid overflow.
17081 			 *
17082 			 * We don't need to decrement tcp_timer_backoff
17083 			 * to avoid overflow because it will be decremented
17084 			 * later if new timeout value is greater than
17085 			 * tcp_rexmit_interval_max.  In the case when
17086 			 * tcp_rexmit_interval_max is greater than
17087 			 * second_threshold, it means that we will wait
17088 			 * longer than second_threshold to send the next
17089 			 * window probe.
17090 			 */
17091 			tcp->tcp_ms_we_have_waited = second_threshold;
17092 		}
17093 	} else if (ms > first_threshold) {
17094 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17095 		    tcp->tcp_xmit_head != NULL) {
17096 			tcp->tcp_xmit_head =
17097 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17098 		}
17099 		/*
17100 		 * We have been retransmitting for too long...  The RTT
17101 		 * we calculated is probably incorrect.  Reinitialize it.
17102 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17103 		 * tcp_rtt_update so that we won't accidentally cache a
17104 		 * bad value.  But only do this if this is not a zero
17105 		 * window probe.
17106 		 */
17107 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17108 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17109 			    (tcp->tcp_rtt_sa >> 5);
17110 			tcp->tcp_rtt_sa = 0;
17111 			tcp_ip_notify(tcp);
17112 			tcp->tcp_rtt_update = 0;
17113 		}
17114 	}
17115 	tcp->tcp_timer_backoff++;
17116 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17117 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17118 	    tcp_rexmit_interval_min) {
17119 		/*
17120 		 * This means the original RTO is tcp_rexmit_interval_min.
17121 		 * So we will use tcp_rexmit_interval_min as the RTO value
17122 		 * and do the backoff.
17123 		 */
17124 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
17125 	} else {
17126 		ms <<= tcp->tcp_timer_backoff;
17127 	}
17128 	if (ms > tcp_rexmit_interval_max) {
17129 		ms = tcp_rexmit_interval_max;
17130 		/*
17131 		 * ms is at max, decrement tcp_timer_backoff to avoid
17132 		 * overflow.
17133 		 */
17134 		tcp->tcp_timer_backoff--;
17135 	}
17136 	tcp->tcp_ms_we_have_waited += ms;
17137 	if (tcp->tcp_zero_win_probe == 0) {
17138 		tcp->tcp_rto = ms;
17139 	}
17140 	TCP_TIMER_RESTART(tcp, ms);
17141 	/*
17142 	 * This is after a timeout and tcp_rto is backed off.  Set
17143 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17144 	 * restart the timer with a correct value.
17145 	 */
17146 	tcp->tcp_set_timer = 1;
17147 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17148 	if (mss > tcp->tcp_mss)
17149 		mss = tcp->tcp_mss;
17150 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17151 		mss = tcp->tcp_swnd;
17152 
17153 	if ((mp = tcp->tcp_xmit_head) != NULL)
17154 		mp->b_prev = (mblk_t *)lbolt;
17155 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17156 	    B_TRUE);
17157 
17158 	/*
17159 	 * When slow start after retransmission begins, start with
17160 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17161 	 * start phase.  tcp_snd_burst controls how many segments
17162 	 * can be sent because of an ack.
17163 	 */
17164 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17165 	tcp->tcp_snd_burst = TCP_CWND_SS;
17166 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17167 	    (tcp->tcp_unsent == 0)) {
17168 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17169 	} else {
17170 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17171 	}
17172 	tcp->tcp_rexmit = B_TRUE;
17173 	tcp->tcp_dupack_cnt = 0;
17174 
17175 	/*
17176 	 * Remove all rexmit SACK blk to start from fresh.
17177 	 */
17178 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17179 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17180 		tcp->tcp_num_notsack_blk = 0;
17181 		tcp->tcp_cnt_notsack_list = 0;
17182 	}
17183 	if (mp == NULL) {
17184 		return;
17185 	}
17186 	/* Attach credentials to retransmitted initial SYNs. */
17187 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17188 		mblk_setcred(mp, tcp->tcp_cred);
17189 		DB_CPID(mp) = tcp->tcp_cpid;
17190 	}
17191 
17192 	tcp->tcp_csuna = tcp->tcp_snxt;
17193 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
17194 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
17195 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17196 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17197 
17198 }
17199 
17200 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17201 static void
17202 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17203 {
17204 	conn_t	*connp;
17205 
17206 	switch (tcp->tcp_state) {
17207 	case TCPS_BOUND:
17208 	case TCPS_LISTEN:
17209 		break;
17210 	default:
17211 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17212 		return;
17213 	}
17214 
17215 	/*
17216 	 * Need to clean up all the eagers since after the unbind, segments
17217 	 * will no longer be delivered to this listener stream.
17218 	 */
17219 	mutex_enter(&tcp->tcp_eager_lock);
17220 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17221 		tcp_eager_cleanup(tcp, 0);
17222 	}
17223 	mutex_exit(&tcp->tcp_eager_lock);
17224 
17225 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17226 		tcp->tcp_ipha->ipha_src = 0;
17227 	} else {
17228 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17229 	}
17230 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17231 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17232 	tcp_bind_hash_remove(tcp);
17233 	tcp->tcp_state = TCPS_IDLE;
17234 	tcp->tcp_mdt = B_FALSE;
17235 	/* Send M_FLUSH according to TPI */
17236 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17237 	connp = tcp->tcp_connp;
17238 	connp->conn_mdt_ok = B_FALSE;
17239 	ipcl_hash_remove(connp);
17240 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17241 	mp = mi_tpi_ok_ack_alloc(mp);
17242 	putnext(tcp->tcp_rq, mp);
17243 }
17244 
17245 /*
17246  * Don't let port fall into the privileged range.
17247  * Since the extra privileged ports can be arbitrary we also
17248  * ensure that we exclude those from consideration.
17249  * tcp_g_epriv_ports is not sorted thus we loop over it until
17250  * there are no changes.
17251  *
17252  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17253  * but instead the code relies on:
17254  * - the fact that the address of the array and its size never changes
17255  * - the atomic assignment of the elements of the array
17256  */
17257 static in_port_t
17258 tcp_update_next_port(in_port_t port, boolean_t random)
17259 {
17260 	int i;
17261 
17262 	if (random && tcp_random_anon_port != 0) {
17263 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17264 		    sizeof (in_port_t));
17265 		/*
17266 		 * Unless changed by a sys admin, the smallest anon port
17267 		 * is 32768 and the largest anon port is 65535.  It is
17268 		 * very likely (50%) for the random port to be smaller
17269 		 * than the smallest anon port.  When that happens,
17270 		 * add port % (anon port range) to the smallest anon
17271 		 * port to get the random port.  It should fall into the
17272 		 * valid anon port range.
17273 		 */
17274 		if (port < tcp_smallest_anon_port) {
17275 			port = tcp_smallest_anon_port +
17276 			    port % (tcp_largest_anon_port -
17277 				tcp_smallest_anon_port);
17278 		}
17279 	}
17280 
17281 retry:
17282 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
17283 		port = (in_port_t)tcp_smallest_anon_port;
17284 
17285 	if (port < tcp_smallest_nonpriv_port)
17286 		port = (in_port_t)tcp_smallest_nonpriv_port;
17287 
17288 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
17289 		if (port == tcp_g_epriv_ports[i]) {
17290 			port++;
17291 			/*
17292 			 * Make sure whether the port is in the
17293 			 * valid range.
17294 			 *
17295 			 * XXX Note that if tcp_g_epriv_ports contains
17296 			 * all the anonymous ports this will be an
17297 			 * infinite loop.
17298 			 */
17299 			goto retry;
17300 		}
17301 	}
17302 	return (port);
17303 }
17304 
17305 /*
17306  * Return the next anonymous port in the priviledged port range for
17307  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17308  * downwards.  This is the same behavior as documented in the userland
17309  * library call rresvport(3N).
17310  */
17311 static in_port_t
17312 tcp_get_next_priv_port(void)
17313 {
17314 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17315 
17316 	if (next_priv_port < tcp_min_anonpriv_port) {
17317 		next_priv_port = IPPORT_RESERVED - 1;
17318 	}
17319 	return (next_priv_port--);
17320 }
17321 
17322 /* The write side r/w procedure. */
17323 
17324 #if CCS_STATS
17325 struct {
17326 	struct {
17327 		int64_t count, bytes;
17328 	} tot, hit;
17329 } wrw_stats;
17330 #endif
17331 
17332 /*
17333  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17334  * messages.
17335  */
17336 /* ARGSUSED */
17337 static void
17338 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17339 {
17340 	conn_t	*connp = (conn_t *)arg;
17341 	tcp_t	*tcp = connp->conn_tcp;
17342 	queue_t	*q = tcp->tcp_wq;
17343 
17344 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17345 	/*
17346 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17347 	 * Once the close starts, streamhead and sockfs will not let any data
17348 	 * packets come down (close ensures that there are no threads using the
17349 	 * queue and no new threads will come down) but since qprocsoff()
17350 	 * hasn't happened yet, a M_FLUSH or some non data message might
17351 	 * get reflected back (in response to our own FLUSHRW) and get
17352 	 * processed after tcp_close() is done. The conn would still be valid
17353 	 * because a ref would have added but we need to check the state
17354 	 * before actually processing the packet.
17355 	 */
17356 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17357 		freemsg(mp);
17358 		return;
17359 	}
17360 
17361 	switch (DB_TYPE(mp)) {
17362 	case M_IOCDATA:
17363 		tcp_wput_iocdata(tcp, mp);
17364 		break;
17365 	case M_FLUSH:
17366 		tcp_wput_flush(tcp, mp);
17367 		break;
17368 	default:
17369 		CALL_IP_WPUT(connp, q, mp);
17370 		break;
17371 	}
17372 }
17373 
17374 /*
17375  * Write side put procedure for TCP module instance.
17376  * TCP as a module is only used for MIB browsers that push TCP over IP or
17377  * ARP. The only supported primitives are T_SVR4_OPTMGMT_REQ and
17378  * T_OPTMGMT_REQ. M_FLUSH messages are only passed downstream; we don't flush
17379  * our queues as we never enqueue messages there. All ioctls are NAKed and
17380  * everything else is freed.
17381  */
17382 static void
17383 tcp_wput_mod(queue_t *q, mblk_t *mp)
17384 {
17385 	switch (DB_TYPE(mp)) {
17386 	case M_PROTO:
17387 	case M_PCPROTO:
17388 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
17389 		    ((((union T_primitives *)mp->b_rptr)->type ==
17390 			T_SVR4_OPTMGMT_REQ) ||
17391 		    (((union T_primitives *)mp->b_rptr)->type ==
17392 			T_OPTMGMT_REQ))) {
17393 			/*
17394 			 * This is the only TPI primitive supported. Its
17395 			 * handling does not require tcp_t, but it does require
17396 			 * conn_t to check permissions.
17397 			 */
17398 			cred_t	*cr = DB_CREDDEF(mp, Q_TO_CONN(q)->conn_cred);
17399 			if (!snmpcom_req(q, mp, tcp_snmp_set,
17400 			    tcp_snmp_get, cr)) {
17401 				freemsg(mp);
17402 				return;
17403 			}
17404 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
17405 		    != NULL)
17406 			qreply(q, mp);
17407 		break;
17408 	case M_FLUSH:
17409 		putnext(q, mp);
17410 		break;
17411 	case M_IOCTL:
17412 		miocnak(q, mp, 0, ENOTSUP);
17413 		break;
17414 	default:
17415 		freemsg(mp);
17416 		break;
17417 	}
17418 }
17419 
17420 /*
17421  * The TCP fast path write put procedure.
17422  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17423  */
17424 /* ARGSUSED */
17425 static void
17426 tcp_output(void *arg, mblk_t *mp, void *arg2)
17427 {
17428 	int		len;
17429 	int		hdrlen;
17430 	int		plen;
17431 	mblk_t		*mp1;
17432 	uchar_t		*rptr;
17433 	uint32_t	snxt;
17434 	tcph_t		*tcph;
17435 	struct datab	*db;
17436 	uint32_t	suna;
17437 	uint32_t	mss;
17438 	ipaddr_t	*dst;
17439 	ipaddr_t	*src;
17440 	uint32_t	sum;
17441 	int		usable;
17442 	conn_t		*connp = (conn_t *)arg;
17443 	tcp_t		*tcp = connp->conn_tcp;
17444 
17445 	/*
17446 	 * Try and ASSERT the minimum possible references on the
17447 	 * conn early enough. Since we are executing on write side,
17448 	 * the connection is obviously not detached and that means
17449 	 * there is a ref each for TCP and IP. Since we are behind
17450 	 * the squeue, the minimum references needed are 3. If the
17451 	 * conn is in classifier hash list, there should be an
17452 	 * extra ref for that (we check both the possibilities).
17453 	 */
17454 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17455 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17456 
17457 	/* Bypass tcp protocol for fused tcp loopback */
17458 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp))
17459 		return;
17460 
17461 	mss = tcp->tcp_mss;
17462 	if (tcp->tcp_xmit_zc_clean)
17463 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17464 
17465 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17466 	len = (int)(mp->b_wptr - mp->b_rptr);
17467 
17468 	/*
17469 	 * Criteria for fast path:
17470 	 *
17471 	 *   1. no unsent data
17472 	 *   2. single mblk in request
17473 	 *   3. connection established
17474 	 *   4. data in mblk
17475 	 *   5. len <= mss
17476 	 *   6. no tcp_valid bits
17477 	 */
17478 	if ((tcp->tcp_unsent != 0) ||
17479 	    (tcp->tcp_cork) ||
17480 	    (mp->b_cont != NULL) ||
17481 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17482 	    (len == 0) ||
17483 	    (len > mss) ||
17484 	    (tcp->tcp_valid_bits != 0)) {
17485 		tcp_wput_data(tcp, mp, B_FALSE);
17486 		return;
17487 	}
17488 
17489 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17490 	ASSERT(tcp->tcp_fin_sent == 0);
17491 
17492 	/* queue new packet onto retransmission queue */
17493 	if (tcp->tcp_xmit_head == NULL) {
17494 		tcp->tcp_xmit_head = mp;
17495 	} else {
17496 		tcp->tcp_xmit_last->b_cont = mp;
17497 	}
17498 	tcp->tcp_xmit_last = mp;
17499 	tcp->tcp_xmit_tail = mp;
17500 
17501 	/* find out how much we can send */
17502 	/* BEGIN CSTYLED */
17503 	/*
17504 	 *    un-acked           usable
17505 	 *  |--------------|-----------------|
17506 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17507 	 */
17508 	/* END CSTYLED */
17509 
17510 	/* start sending from tcp_snxt */
17511 	snxt = tcp->tcp_snxt;
17512 
17513 	/*
17514 	 * Check to see if this connection has been idled for some
17515 	 * time and no ACK is expected.  If it is, we need to slow
17516 	 * start again to get back the connection's "self-clock" as
17517 	 * described in VJ's paper.
17518 	 *
17519 	 * Refer to the comment in tcp_mss_set() for the calculation
17520 	 * of tcp_cwnd after idle.
17521 	 */
17522 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17523 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17524 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17525 	}
17526 
17527 	usable = tcp->tcp_swnd;		/* tcp window size */
17528 	if (usable > tcp->tcp_cwnd)
17529 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17530 	usable -= snxt;		/* subtract stuff already sent */
17531 	suna = tcp->tcp_suna;
17532 	usable += suna;
17533 	/* usable can be < 0 if the congestion window is smaller */
17534 	if (len > usable) {
17535 		/* Can't send complete M_DATA in one shot */
17536 		goto slow;
17537 	}
17538 
17539 	/*
17540 	 * determine if anything to send (Nagle).
17541 	 *
17542 	 *   1. len < tcp_mss (i.e. small)
17543 	 *   2. unacknowledged data present
17544 	 *   3. len < nagle limit
17545 	 *   4. last packet sent < nagle limit (previous packet sent)
17546 	 */
17547 	if ((len < mss) && (snxt != suna) &&
17548 	    (len < (int)tcp->tcp_naglim) &&
17549 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17550 		/*
17551 		 * This was the first unsent packet and normally
17552 		 * mss < xmit_hiwater so there is no need to worry
17553 		 * about flow control. The next packet will go
17554 		 * through the flow control check in tcp_wput_data().
17555 		 */
17556 		/* leftover work from above */
17557 		tcp->tcp_unsent = len;
17558 		tcp->tcp_xmit_tail_unsent = len;
17559 
17560 		return;
17561 	}
17562 
17563 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17564 
17565 	if (snxt == suna) {
17566 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17567 	}
17568 
17569 	/* we have always sent something */
17570 	tcp->tcp_rack_cnt = 0;
17571 
17572 	tcp->tcp_snxt = snxt + len;
17573 	tcp->tcp_rack = tcp->tcp_rnxt;
17574 
17575 	if ((mp1 = dupb(mp)) == 0)
17576 		goto no_memory;
17577 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17578 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17579 
17580 	/* adjust tcp header information */
17581 	tcph = tcp->tcp_tcph;
17582 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17583 
17584 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17585 	sum = (sum >> 16) + (sum & 0xFFFF);
17586 	U16_TO_ABE16(sum, tcph->th_sum);
17587 
17588 	U32_TO_ABE32(snxt, tcph->th_seq);
17589 
17590 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17591 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17592 	BUMP_LOCAL(tcp->tcp_obsegs);
17593 
17594 	/* Update the latest receive window size in TCP header. */
17595 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17596 	    tcph->th_win);
17597 
17598 	tcp->tcp_last_sent_len = (ushort_t)len;
17599 
17600 	plen = len + tcp->tcp_hdr_len;
17601 
17602 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17603 		tcp->tcp_ipha->ipha_length = htons(plen);
17604 	} else {
17605 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17606 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17607 	}
17608 
17609 	/* see if we need to allocate a mblk for the headers */
17610 	hdrlen = tcp->tcp_hdr_len;
17611 	rptr = mp1->b_rptr - hdrlen;
17612 	db = mp1->b_datap;
17613 	if ((db->db_ref != 2) || rptr < db->db_base ||
17614 	    (!OK_32PTR(rptr))) {
17615 		/* NOTE: we assume allocb returns an OK_32PTR */
17616 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17617 		    tcp_wroff_xtra, BPRI_MED);
17618 		if (!mp) {
17619 			freemsg(mp1);
17620 			goto no_memory;
17621 		}
17622 		mp->b_cont = mp1;
17623 		mp1 = mp;
17624 		/* Leave room for Link Level header */
17625 		/* hdrlen = tcp->tcp_hdr_len; */
17626 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17627 		mp1->b_wptr = &rptr[hdrlen];
17628 	}
17629 	mp1->b_rptr = rptr;
17630 
17631 	/* Fill in the timestamp option. */
17632 	if (tcp->tcp_snd_ts_ok) {
17633 		U32_TO_BE32((uint32_t)lbolt,
17634 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17635 		U32_TO_BE32(tcp->tcp_ts_recent,
17636 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17637 	} else {
17638 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17639 	}
17640 
17641 	/* copy header into outgoing packet */
17642 	dst = (ipaddr_t *)rptr;
17643 	src = (ipaddr_t *)tcp->tcp_iphc;
17644 	dst[0] = src[0];
17645 	dst[1] = src[1];
17646 	dst[2] = src[2];
17647 	dst[3] = src[3];
17648 	dst[4] = src[4];
17649 	dst[5] = src[5];
17650 	dst[6] = src[6];
17651 	dst[7] = src[7];
17652 	dst[8] = src[8];
17653 	dst[9] = src[9];
17654 	if (hdrlen -= 40) {
17655 		hdrlen >>= 2;
17656 		dst += 10;
17657 		src += 10;
17658 		do {
17659 			*dst++ = *src++;
17660 		} while (--hdrlen);
17661 	}
17662 
17663 	/*
17664 	 * Set the ECN info in the TCP header.  Note that this
17665 	 * is not the template header.
17666 	 */
17667 	if (tcp->tcp_ecn_ok) {
17668 		SET_ECT(tcp, rptr);
17669 
17670 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17671 		if (tcp->tcp_ecn_echo_on)
17672 			tcph->th_flags[0] |= TH_ECE;
17673 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17674 			tcph->th_flags[0] |= TH_CWR;
17675 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17676 		}
17677 	}
17678 
17679 	if (tcp->tcp_ip_forward_progress) {
17680 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17681 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17682 		tcp->tcp_ip_forward_progress = B_FALSE;
17683 	}
17684 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17685 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17686 	return;
17687 
17688 	/*
17689 	 * If we ran out of memory, we pretend to have sent the packet
17690 	 * and that it was lost on the wire.
17691 	 */
17692 no_memory:
17693 	return;
17694 
17695 slow:
17696 	/* leftover work from above */
17697 	tcp->tcp_unsent = len;
17698 	tcp->tcp_xmit_tail_unsent = len;
17699 	tcp_wput_data(tcp, NULL, B_FALSE);
17700 }
17701 
17702 /*
17703  * The function called through squeue to get behind eager's perimeter to
17704  * finish the accept processing.
17705  */
17706 /* ARGSUSED */
17707 void
17708 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17709 {
17710 	conn_t			*connp = (conn_t *)arg;
17711 	tcp_t			*tcp = connp->conn_tcp;
17712 	queue_t			*q = tcp->tcp_rq;
17713 	mblk_t			*mp1;
17714 	mblk_t			*stropt_mp = mp;
17715 	struct  stroptions	*stropt;
17716 	uint_t			thwin;
17717 
17718 	/*
17719 	 * Drop the eager's ref on the listener, that was placed when
17720 	 * this eager began life in tcp_conn_request.
17721 	 */
17722 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17723 
17724 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17725 		/*
17726 		 * Someone blewoff the eager before we could finish
17727 		 * the accept.
17728 		 *
17729 		 * The only reason eager exists it because we put in
17730 		 * a ref on it when conn ind went up. We need to send
17731 		 * a disconnect indication up while the last reference
17732 		 * on the eager will be dropped by the squeue when we
17733 		 * return.
17734 		 */
17735 		ASSERT(tcp->tcp_listener == NULL);
17736 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17737 			struct	T_discon_ind	*tdi;
17738 
17739 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17740 			/*
17741 			 * Let us reuse the incoming mblk to avoid memory
17742 			 * allocation failure problems. We know that the
17743 			 * size of the incoming mblk i.e. stroptions is greater
17744 			 * than sizeof T_discon_ind. So the reallocb below
17745 			 * can't fail.
17746 			 */
17747 			freemsg(mp->b_cont);
17748 			mp->b_cont = NULL;
17749 			ASSERT(DB_REF(mp) == 1);
17750 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17751 			    B_FALSE);
17752 			ASSERT(mp != NULL);
17753 			DB_TYPE(mp) = M_PROTO;
17754 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17755 			tdi = (struct T_discon_ind *)mp->b_rptr;
17756 			if (tcp->tcp_issocket) {
17757 				tdi->DISCON_reason = ECONNREFUSED;
17758 				tdi->SEQ_number = 0;
17759 			} else {
17760 				tdi->DISCON_reason = ENOPROTOOPT;
17761 				tdi->SEQ_number =
17762 				    tcp->tcp_conn_req_seqnum;
17763 			}
17764 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17765 			putnext(q, mp);
17766 		} else {
17767 			freemsg(mp);
17768 		}
17769 		if (tcp->tcp_hard_binding) {
17770 			tcp->tcp_hard_binding = B_FALSE;
17771 			tcp->tcp_hard_bound = B_TRUE;
17772 		}
17773 		tcp->tcp_detached = B_FALSE;
17774 		return;
17775 	}
17776 
17777 	mp1 = stropt_mp->b_cont;
17778 	stropt_mp->b_cont = NULL;
17779 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17780 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17781 
17782 	while (mp1 != NULL) {
17783 		mp = mp1;
17784 		mp1 = mp1->b_cont;
17785 		mp->b_cont = NULL;
17786 		tcp->tcp_drop_opt_ack_cnt++;
17787 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17788 	}
17789 	mp = NULL;
17790 
17791 	/*
17792 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17793 	 * properly.  This is the first time we know of the acceptor'
17794 	 * queue.  So we do it here.
17795 	 */
17796 	if (tcp->tcp_rcv_list == NULL) {
17797 		/*
17798 		 * Recv queue is empty, tcp_rwnd should not have changed.
17799 		 * That means it should be equal to the listener's tcp_rwnd.
17800 		 */
17801 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17802 	} else {
17803 #ifdef DEBUG
17804 		uint_t cnt = 0;
17805 
17806 		mp1 = tcp->tcp_rcv_list;
17807 		while ((mp = mp1) != NULL) {
17808 			mp1 = mp->b_next;
17809 			cnt += msgdsize(mp);
17810 		}
17811 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17812 #endif
17813 		/* There is some data, add them back to get the max. */
17814 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17815 	}
17816 
17817 	stropt->so_flags = SO_HIWAT;
17818 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17819 
17820 	stropt->so_flags |= SO_MAXBLK;
17821 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17822 
17823 	/*
17824 	 * This is the first time we run on the correct
17825 	 * queue after tcp_accept. So fix all the q parameters
17826 	 * here.
17827 	 */
17828 	/* Allocate room for SACK options if needed. */
17829 	stropt->so_flags |= SO_WROFF;
17830 	if (tcp->tcp_fused) {
17831 		size_t sth_hiwat;
17832 
17833 		ASSERT(tcp->tcp_loopback);
17834 		/*
17835 		 * For fused tcp loopback, set the stream head's write
17836 		 * offset value to zero since we won't be needing any room
17837 		 * for TCP/IP headers.  This would also improve performance
17838 		 * since it would reduce the amount of work done by kmem.
17839 		 * Non-fused tcp loopback case is handled separately below.
17840 		 */
17841 		stropt->so_wroff = 0;
17842 
17843 		/*
17844 		 * Override q_hiwat and set it to be twice that of the
17845 		 * previous value; this is to simulate non-fusion case.
17846 		 */
17847 		sth_hiwat = q->q_hiwat << 1;
17848 		if (sth_hiwat > tcp_max_buf)
17849 			sth_hiwat = tcp_max_buf;
17850 
17851 		stropt->so_hiwat = MAX(sth_hiwat, tcp_sth_rcv_hiwat);
17852 	} else if (tcp->tcp_snd_sack_ok) {
17853 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17854 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17855 	} else {
17856 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17857 		    tcp_wroff_xtra);
17858 	}
17859 
17860 	/*
17861 	 * If loopback, set COPYCACHED option to make sure NOT to use
17862 	 * non-temporal access.
17863 	 */
17864 	if (tcp->tcp_loopback) {
17865 		stropt->so_flags |= SO_COPYOPT;
17866 		stropt->so_copyopt = COPYCACHED;
17867 	}
17868 
17869 	/* Send the options up */
17870 	putnext(q, stropt_mp);
17871 
17872 	/*
17873 	 * Pass up any data and/or a fin that has been received.
17874 	 *
17875 	 * Adjust receive window in case it had decreased
17876 	 * (because there is data <=> tcp_rcv_list != NULL)
17877 	 * while the connection was detached. Note that
17878 	 * in case the eager was flow-controlled, w/o this
17879 	 * code, the rwnd may never open up again!
17880 	 */
17881 	if (tcp->tcp_rcv_list != NULL) {
17882 		/* We drain directly in case of fused tcp loopback */
17883 		if (!tcp->tcp_fused && canputnext(q)) {
17884 			tcp->tcp_rwnd = q->q_hiwat;
17885 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17886 			    << tcp->tcp_rcv_ws;
17887 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17888 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17889 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17890 				tcp_xmit_ctl(NULL,
17891 				    tcp, (tcp->tcp_swnd == 0) ?
17892 				    tcp->tcp_suna : tcp->tcp_snxt,
17893 				    tcp->tcp_rnxt, TH_ACK);
17894 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17895 			}
17896 
17897 		}
17898 		(void) tcp_rcv_drain(q, tcp);
17899 
17900 		/*
17901 		 * For fused tcp loopback, back-enable peer endpoint
17902 		 * if it's currently flow-controlled.
17903 		 */
17904 		if (tcp->tcp_fused &&
17905 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17906 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17907 
17908 			ASSERT(peer_tcp != NULL);
17909 			ASSERT(peer_tcp->tcp_fused);
17910 
17911 			tcp_clrqfull(peer_tcp);
17912 			peer_tcp->tcp_flow_stopped = B_FALSE;
17913 			TCP_STAT(tcp_fusion_backenabled);
17914 		}
17915 	}
17916 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17917 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17918 		mp = mi_tpi_ordrel_ind();
17919 		if (mp) {
17920 			tcp->tcp_ordrel_done = B_TRUE;
17921 			putnext(q, mp);
17922 			if (tcp->tcp_deferred_clean_death) {
17923 				/*
17924 				 * tcp_clean_death was deferred
17925 				 * for T_ORDREL_IND - do it now
17926 				 */
17927 				(void) tcp_clean_death(
17928 					tcp,
17929 					    tcp->tcp_client_errno, 21);
17930 				tcp->tcp_deferred_clean_death =
17931 				    B_FALSE;
17932 			}
17933 		} else {
17934 			/*
17935 			 * Run the orderly release in the
17936 			 * service routine.
17937 			 */
17938 			qenable(q);
17939 		}
17940 	}
17941 	if (tcp->tcp_hard_binding) {
17942 		tcp->tcp_hard_binding = B_FALSE;
17943 		tcp->tcp_hard_bound = B_TRUE;
17944 	}
17945 	tcp->tcp_detached = B_FALSE;
17946 
17947 	if (tcp->tcp_ka_enabled) {
17948 		tcp->tcp_ka_last_intrvl = 0;
17949 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17950 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17951 	}
17952 
17953 	/*
17954 	 * At this point, eager is fully established and will
17955 	 * have the following references -
17956 	 *
17957 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17958 	 * 1 reference for the squeue which will be dropped by the squeue as
17959 	 *	soon as this function returns.
17960 	 * There will be 1 additonal reference for being in classifier
17961 	 *	hash list provided something bad hasn't happened.
17962 	 */
17963 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17964 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17965 }
17966 
17967 /*
17968  * The function called through squeue to get behind listener's perimeter to
17969  * send a deffered conn_ind.
17970  */
17971 /* ARGSUSED */
17972 void
17973 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17974 {
17975 	conn_t	*connp = (conn_t *)arg;
17976 	tcp_t *listener = connp->conn_tcp;
17977 
17978 	if (listener->tcp_state == TCPS_CLOSED ||
17979 	    TCP_IS_DETACHED(listener)) {
17980 		/*
17981 		 * If listener has closed, it would have caused a
17982 		 * a cleanup/blowoff to happen for the eager.
17983 		 */
17984 		tcp_t *tcp;
17985 		struct T_conn_ind	*conn_ind;
17986 
17987 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17988 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17989 		    conn_ind->OPT_length);
17990 		/*
17991 		 * We need to drop the ref on eager that was put
17992 		 * tcp_rput_data() before trying to send the conn_ind
17993 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17994 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17995 		 * listener is closed so we drop the ref.
17996 		 */
17997 		CONN_DEC_REF(tcp->tcp_connp);
17998 		freemsg(mp);
17999 		return;
18000 	}
18001 	putnext(listener->tcp_rq, mp);
18002 }
18003 
18004 
18005 /*
18006  * This is the STREAMS entry point for T_CONN_RES coming down on
18007  * Acceptor STREAM when  sockfs listener does accept processing.
18008  * Read the block comment on top pf tcp_conn_request().
18009  */
18010 void
18011 tcp_wput_accept(queue_t *q, mblk_t *mp)
18012 {
18013 	queue_t *rq = RD(q);
18014 	struct T_conn_res *conn_res;
18015 	tcp_t *eager;
18016 	tcp_t *listener;
18017 	struct T_ok_ack *ok;
18018 	t_scalar_t PRIM_type;
18019 	mblk_t *opt_mp;
18020 	conn_t *econnp;
18021 
18022 	ASSERT(DB_TYPE(mp) == M_PROTO);
18023 
18024 	conn_res = (struct T_conn_res *)mp->b_rptr;
18025 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18026 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18027 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18028 		if (mp != NULL)
18029 			putnext(rq, mp);
18030 		return;
18031 	}
18032 	switch (conn_res->PRIM_type) {
18033 	case O_T_CONN_RES:
18034 	case T_CONN_RES:
18035 		/*
18036 		 * We pass up an err ack if allocb fails. This will
18037 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18038 		 * tcp_eager_blowoff to be called. sockfs will then call
18039 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18040 		 * we need to do the allocb up here because we have to
18041 		 * make sure rq->q_qinfo->qi_qclose still points to the
18042 		 * correct function (tcpclose_accept) in case allocb
18043 		 * fails.
18044 		 */
18045 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18046 		if (opt_mp == NULL) {
18047 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18048 			if (mp != NULL)
18049 				putnext(rq, mp);
18050 			return;
18051 		}
18052 
18053 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18054 		    &eager, conn_res->OPT_length);
18055 		PRIM_type = conn_res->PRIM_type;
18056 		mp->b_datap->db_type = M_PCPROTO;
18057 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18058 		ok = (struct T_ok_ack *)mp->b_rptr;
18059 		ok->PRIM_type = T_OK_ACK;
18060 		ok->CORRECT_prim = PRIM_type;
18061 		econnp = eager->tcp_connp;
18062 		econnp->conn_dev = (dev_t)q->q_ptr;
18063 		eager->tcp_rq = rq;
18064 		eager->tcp_wq = q;
18065 		rq->q_ptr = econnp;
18066 		rq->q_qinfo = &tcp_rinit;
18067 		q->q_ptr = econnp;
18068 		q->q_qinfo = &tcp_winit;
18069 		listener = eager->tcp_listener;
18070 		eager->tcp_issocket = B_TRUE;
18071 		eager->tcp_cred = econnp->conn_cred =
18072 		    listener->tcp_connp->conn_cred;
18073 		crhold(econnp->conn_cred);
18074 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18075 
18076 		/* Put the ref for IP */
18077 		CONN_INC_REF(econnp);
18078 
18079 		/*
18080 		 * We should have minimum of 3 references on the conn
18081 		 * at this point. One each for TCP and IP and one for
18082 		 * the T_conn_ind that was sent up when the 3-way handshake
18083 		 * completed. In the normal case we would also have another
18084 		 * reference (making a total of 4) for the conn being in the
18085 		 * classifier hash list. However the eager could have received
18086 		 * an RST subsequently and tcp_closei_local could have removed
18087 		 * the eager from the classifier hash list, hence we can't
18088 		 * assert that reference.
18089 		 */
18090 		ASSERT(econnp->conn_ref >= 3);
18091 
18092 		/*
18093 		 * Send the new local address also up to sockfs. There
18094 		 * should already be enough space in the mp that came
18095 		 * down from soaccept().
18096 		 */
18097 		if (eager->tcp_family == AF_INET) {
18098 			sin_t *sin;
18099 
18100 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18101 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18102 			sin = (sin_t *)mp->b_wptr;
18103 			mp->b_wptr += sizeof (sin_t);
18104 			sin->sin_family = AF_INET;
18105 			sin->sin_port = eager->tcp_lport;
18106 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18107 		} else {
18108 			sin6_t *sin6;
18109 
18110 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18111 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18112 			sin6 = (sin6_t *)mp->b_wptr;
18113 			mp->b_wptr += sizeof (sin6_t);
18114 			sin6->sin6_family = AF_INET6;
18115 			sin6->sin6_port = eager->tcp_lport;
18116 			if (eager->tcp_ipversion == IPV4_VERSION) {
18117 				sin6->sin6_flowinfo = 0;
18118 				IN6_IPADDR_TO_V4MAPPED(
18119 					eager->tcp_ipha->ipha_src,
18120 					    &sin6->sin6_addr);
18121 			} else {
18122 				ASSERT(eager->tcp_ip6h != NULL);
18123 				sin6->sin6_flowinfo =
18124 				    eager->tcp_ip6h->ip6_vcf &
18125 				    ~IPV6_VERS_AND_FLOW_MASK;
18126 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18127 			}
18128 			sin6->sin6_scope_id = 0;
18129 			sin6->__sin6_src_id = 0;
18130 		}
18131 
18132 		putnext(rq, mp);
18133 
18134 		opt_mp->b_datap->db_type = M_SETOPTS;
18135 		opt_mp->b_wptr += sizeof (struct stroptions);
18136 
18137 		/*
18138 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18139 		 * from listener to acceptor. The message is chained on the
18140 		 * bind_mp which tcp_rput_other will send down to IP.
18141 		 */
18142 		if (listener->tcp_bound_if != 0) {
18143 			/* allocate optmgmt req */
18144 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18145 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18146 			    sizeof (int));
18147 			if (mp != NULL)
18148 				linkb(opt_mp, mp);
18149 		}
18150 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18151 			uint_t on = 1;
18152 
18153 			/* allocate optmgmt req */
18154 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18155 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18156 			if (mp != NULL)
18157 				linkb(opt_mp, mp);
18158 		}
18159 
18160 
18161 		mutex_enter(&listener->tcp_eager_lock);
18162 
18163 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18164 
18165 			tcp_t *tail;
18166 			tcp_t *tcp;
18167 			mblk_t *mp1;
18168 
18169 			tcp = listener->tcp_eager_prev_q0;
18170 			/*
18171 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18172 			 * deferred T_conn_ind queue. We need to get to the head
18173 			 * of the queue in order to send up T_conn_ind the same
18174 			 * order as how the 3WHS is completed.
18175 			 */
18176 			while (tcp != listener) {
18177 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
18178 					break;
18179 				else
18180 					tcp = tcp->tcp_eager_prev_q0;
18181 			}
18182 			ASSERT(tcp != listener);
18183 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18184 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18185 			/* Move from q0 to q */
18186 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18187 			listener->tcp_conn_req_cnt_q0--;
18188 			listener->tcp_conn_req_cnt_q++;
18189 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18190 			    tcp->tcp_eager_prev_q0;
18191 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18192 			    tcp->tcp_eager_next_q0;
18193 			tcp->tcp_eager_prev_q0 = NULL;
18194 			tcp->tcp_eager_next_q0 = NULL;
18195 			tcp->tcp_conn_def_q0 = B_FALSE;
18196 
18197 			/*
18198 			 * Insert at end of the queue because sockfs sends
18199 			 * down T_CONN_RES in chronological order. Leaving
18200 			 * the older conn indications at front of the queue
18201 			 * helps reducing search time.
18202 			 */
18203 			tail = listener->tcp_eager_last_q;
18204 			if (tail != NULL) {
18205 				tail->tcp_eager_next_q = tcp;
18206 			} else {
18207 				listener->tcp_eager_next_q = tcp;
18208 			}
18209 			listener->tcp_eager_last_q = tcp;
18210 			tcp->tcp_eager_next_q = NULL;
18211 
18212 			/* Need to get inside the listener perimeter */
18213 			CONN_INC_REF(listener->tcp_connp);
18214 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18215 			    tcp_send_pending, listener->tcp_connp,
18216 			    SQTAG_TCP_SEND_PENDING);
18217 		}
18218 		tcp_eager_unlink(eager);
18219 		mutex_exit(&listener->tcp_eager_lock);
18220 
18221 		/*
18222 		 * At this point, the eager is detached from the listener
18223 		 * but we still have an extra refs on eager (apart from the
18224 		 * usual tcp references). The ref was placed in tcp_rput_data
18225 		 * before sending the conn_ind in tcp_send_conn_ind.
18226 		 * The ref will be dropped in tcp_accept_finish().
18227 		 */
18228 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18229 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18230 		return;
18231 	default:
18232 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18233 		if (mp != NULL)
18234 			putnext(rq, mp);
18235 		return;
18236 	}
18237 }
18238 
18239 static void
18240 tcp_wput(queue_t *q, mblk_t *mp)
18241 {
18242 	conn_t	*connp = Q_TO_CONN(q);
18243 	tcp_t	*tcp;
18244 	void (*output_proc)();
18245 	t_scalar_t type;
18246 	uchar_t *rptr;
18247 	struct iocblk	*iocp;
18248 
18249 	ASSERT(connp->conn_ref >= 2);
18250 
18251 	switch (DB_TYPE(mp)) {
18252 	case M_DATA:
18253 		CONN_INC_REF(connp);
18254 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18255 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18256 		return;
18257 	case M_PROTO:
18258 	case M_PCPROTO:
18259 		/*
18260 		 * if it is a snmp message, don't get behind the squeue
18261 		 */
18262 		tcp = connp->conn_tcp;
18263 		rptr = mp->b_rptr;
18264 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18265 			type = ((union T_primitives *)rptr)->type;
18266 		} else {
18267 			if (tcp->tcp_debug) {
18268 				(void) strlog(TCP_MODULE_ID, 0, 1,
18269 				    SL_ERROR|SL_TRACE,
18270 				    "tcp_wput_proto, dropping one...");
18271 			}
18272 			freemsg(mp);
18273 			return;
18274 		}
18275 		if (type == T_SVR4_OPTMGMT_REQ) {
18276 			cred_t	*cr = DB_CREDDEF(mp,
18277 			    tcp->tcp_cred);
18278 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18279 			    cr)) {
18280 				/*
18281 				 * This was a SNMP request
18282 				 */
18283 				return;
18284 			} else {
18285 				output_proc = tcp_wput_proto;
18286 			}
18287 		} else {
18288 			output_proc = tcp_wput_proto;
18289 		}
18290 		break;
18291 	case M_IOCTL:
18292 		/*
18293 		 * Most ioctls can be processed right away without going via
18294 		 * squeues - process them right here. Those that do require
18295 		 * squeue (currently TCP_IOC_DEFAULT_Q and SIOCPOPSOCKFS)
18296 		 * are processed by tcp_wput_ioctl().
18297 		 */
18298 		iocp = (struct iocblk *)mp->b_rptr;
18299 		tcp = connp->conn_tcp;
18300 
18301 		switch (iocp->ioc_cmd) {
18302 		case TCP_IOC_ABORT_CONN:
18303 			tcp_ioctl_abort_conn(q, mp);
18304 			return;
18305 		case TI_GETPEERNAME:
18306 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18307 				iocp->ioc_error = ENOTCONN;
18308 				iocp->ioc_count = 0;
18309 				mp->b_datap->db_type = M_IOCACK;
18310 				qreply(q, mp);
18311 				return;
18312 			}
18313 			/* FALLTHRU */
18314 		case TI_GETMYNAME:
18315 			mi_copyin(q, mp, NULL,
18316 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18317 			return;
18318 		case ND_SET:
18319 			/* nd_getset does the necessary checks */
18320 		case ND_GET:
18321 			if (!nd_getset(q, tcp_g_nd, mp)) {
18322 				CALL_IP_WPUT(connp, q, mp);
18323 				return;
18324 			}
18325 			qreply(q, mp);
18326 			return;
18327 		case TCP_IOC_DEFAULT_Q:
18328 			/*
18329 			 * Wants to be the default wq. Check the credentials
18330 			 * first, the rest is executed via squeue.
18331 			 */
18332 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
18333 				iocp->ioc_error = EPERM;
18334 				iocp->ioc_count = 0;
18335 				mp->b_datap->db_type = M_IOCACK;
18336 				qreply(q, mp);
18337 				return;
18338 			}
18339 			output_proc = tcp_wput_ioctl;
18340 			break;
18341 		default:
18342 			output_proc = tcp_wput_ioctl;
18343 			break;
18344 		}
18345 		break;
18346 	default:
18347 		output_proc = tcp_wput_nondata;
18348 		break;
18349 	}
18350 
18351 	CONN_INC_REF(connp);
18352 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18353 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18354 }
18355 
18356 /*
18357  * Initial STREAMS write side put() procedure for sockets. It tries to
18358  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18359  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18360  * are handled by tcp_wput() as usual.
18361  *
18362  * All further messages will also be handled by tcp_wput() because we cannot
18363  * be sure that the above short cut is safe later.
18364  */
18365 static void
18366 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18367 {
18368 	conn_t			*connp = Q_TO_CONN(wq);
18369 	tcp_t			*tcp = connp->conn_tcp;
18370 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18371 
18372 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18373 	wq->q_qinfo = &tcp_winit;
18374 
18375 	ASSERT(IS_TCP_CONN(connp));
18376 	ASSERT(TCP_IS_SOCKET(tcp));
18377 
18378 	if (DB_TYPE(mp) == M_PCPROTO &&
18379 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18380 	    car->PRIM_type == T_CAPABILITY_REQ) {
18381 		tcp_capability_req(tcp, mp);
18382 		return;
18383 	}
18384 
18385 	tcp_wput(wq, mp);
18386 }
18387 
18388 static boolean_t
18389 tcp_zcopy_check(tcp_t *tcp)
18390 {
18391 	conn_t	*connp = tcp->tcp_connp;
18392 	ire_t	*ire;
18393 	boolean_t	zc_enabled = B_FALSE;
18394 
18395 	if (do_tcpzcopy == 2)
18396 		zc_enabled = B_TRUE;
18397 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18398 	    IPCL_IS_CONNECTED(connp) &&
18399 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18400 	    connp->conn_dontroute == 0 &&
18401 	    connp->conn_xmit_if_ill == NULL &&
18402 	    connp->conn_nofailover_ill == NULL &&
18403 	    do_tcpzcopy == 1) {
18404 		/*
18405 		 * the checks above  closely resemble the fast path checks
18406 		 * in tcp_send_data().
18407 		 */
18408 		mutex_enter(&connp->conn_lock);
18409 		ire = connp->conn_ire_cache;
18410 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18411 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18412 			IRE_REFHOLD(ire);
18413 			if (ire->ire_stq != NULL) {
18414 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18415 
18416 				zc_enabled = ill && (ill->ill_capabilities &
18417 				    ILL_CAPAB_ZEROCOPY) &&
18418 				    (ill->ill_zerocopy_capab->
18419 				    ill_zerocopy_flags != 0);
18420 			}
18421 			IRE_REFRELE(ire);
18422 		}
18423 		mutex_exit(&connp->conn_lock);
18424 	}
18425 	tcp->tcp_snd_zcopy_on = zc_enabled;
18426 	if (!TCP_IS_DETACHED(tcp)) {
18427 		if (zc_enabled) {
18428 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18429 			TCP_STAT(tcp_zcopy_on);
18430 		} else {
18431 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18432 			TCP_STAT(tcp_zcopy_off);
18433 		}
18434 	}
18435 	return (zc_enabled);
18436 }
18437 
18438 static mblk_t *
18439 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18440 {
18441 	if (do_tcpzcopy == 2)
18442 		return (bp);
18443 	else if (tcp->tcp_snd_zcopy_on) {
18444 		tcp->tcp_snd_zcopy_on = B_FALSE;
18445 		if (!TCP_IS_DETACHED(tcp)) {
18446 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18447 			TCP_STAT(tcp_zcopy_disable);
18448 		}
18449 	}
18450 	return (tcp_zcopy_backoff(tcp, bp, 0));
18451 }
18452 
18453 /*
18454  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18455  * the original desballoca'ed segmapped mblk.
18456  */
18457 static mblk_t *
18458 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18459 {
18460 	mblk_t *head, *tail, *nbp;
18461 	if (IS_VMLOANED_MBLK(bp)) {
18462 		TCP_STAT(tcp_zcopy_backoff);
18463 		if ((head = copyb(bp)) == NULL) {
18464 			/* fail to backoff; leave it for the next backoff */
18465 			tcp->tcp_xmit_zc_clean = B_FALSE;
18466 			return (bp);
18467 		}
18468 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18469 			if (fix_xmitlist)
18470 				tcp_zcopy_notify(tcp);
18471 			else
18472 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18473 		}
18474 		nbp = bp->b_cont;
18475 		if (fix_xmitlist) {
18476 			head->b_prev = bp->b_prev;
18477 			head->b_next = bp->b_next;
18478 			if (tcp->tcp_xmit_tail == bp)
18479 				tcp->tcp_xmit_tail = head;
18480 		}
18481 		bp->b_next = NULL;
18482 		bp->b_prev = NULL;
18483 		freeb(bp);
18484 	} else {
18485 		head = bp;
18486 		nbp = bp->b_cont;
18487 	}
18488 	tail = head;
18489 	while (nbp) {
18490 		if (IS_VMLOANED_MBLK(nbp)) {
18491 			TCP_STAT(tcp_zcopy_backoff);
18492 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18493 				tcp->tcp_xmit_zc_clean = B_FALSE;
18494 				tail->b_cont = nbp;
18495 				return (head);
18496 			}
18497 			tail = tail->b_cont;
18498 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18499 				if (fix_xmitlist)
18500 					tcp_zcopy_notify(tcp);
18501 				else
18502 					tail->b_datap->db_struioflag |=
18503 					    STRUIO_ZCNOTIFY;
18504 			}
18505 			bp = nbp;
18506 			nbp = nbp->b_cont;
18507 			if (fix_xmitlist) {
18508 				tail->b_prev = bp->b_prev;
18509 				tail->b_next = bp->b_next;
18510 				if (tcp->tcp_xmit_tail == bp)
18511 					tcp->tcp_xmit_tail = tail;
18512 			}
18513 			bp->b_next = NULL;
18514 			bp->b_prev = NULL;
18515 			freeb(bp);
18516 		} else {
18517 			tail->b_cont = nbp;
18518 			tail = nbp;
18519 			nbp = nbp->b_cont;
18520 		}
18521 	}
18522 	if (fix_xmitlist) {
18523 		tcp->tcp_xmit_last = tail;
18524 		tcp->tcp_xmit_zc_clean = B_TRUE;
18525 	}
18526 	return (head);
18527 }
18528 
18529 static void
18530 tcp_zcopy_notify(tcp_t *tcp)
18531 {
18532 	struct stdata	*stp;
18533 
18534 	if (tcp->tcp_detached)
18535 		return;
18536 	stp = STREAM(tcp->tcp_rq);
18537 	mutex_enter(&stp->sd_lock);
18538 	stp->sd_flag |= STZCNOTIFY;
18539 	cv_broadcast(&stp->sd_zcopy_wait);
18540 	mutex_exit(&stp->sd_lock);
18541 }
18542 
18543 
18544 static void
18545 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18546 {
18547 	ipha_t		*ipha;
18548 	ipaddr_t	src;
18549 	ipaddr_t	dst;
18550 	uint32_t	cksum;
18551 	ire_t		*ire;
18552 	uint16_t	*up;
18553 	ill_t		*ill;
18554 	conn_t		*connp = tcp->tcp_connp;
18555 	uint32_t	hcksum_txflags = 0;
18556 	mblk_t		*ire_fp_mp;
18557 	uint_t		ire_fp_mp_len;
18558 	ill_poll_capab_t *ill_poll;
18559 
18560 	ASSERT(DB_TYPE(mp) == M_DATA);
18561 
18562 	ipha = (ipha_t *)mp->b_rptr;
18563 	src = ipha->ipha_src;
18564 	dst = ipha->ipha_dst;
18565 
18566 	/*
18567 	 * Drop off slow path for IPv6 and also if options are present.
18568 	 */
18569 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18570 	    !IPCL_IS_CONNECTED(connp) ||
18571 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18572 	    connp->conn_dontroute ||
18573 	    connp->conn_xmit_if_ill != NULL ||
18574 	    connp->conn_nofailover_ill != NULL ||
18575 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18576 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18577 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18578 		if (tcp->tcp_snd_zcopy_aware)
18579 			mp = tcp_zcopy_disable(tcp, mp);
18580 		TCP_STAT(tcp_ip_send);
18581 		CALL_IP_WPUT(connp, q, mp);
18582 		return;
18583 	}
18584 
18585 	mutex_enter(&connp->conn_lock);
18586 	ire = connp->conn_ire_cache;
18587 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18588 	if (ire != NULL && ire->ire_addr == dst &&
18589 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18590 		IRE_REFHOLD(ire);
18591 		mutex_exit(&connp->conn_lock);
18592 	} else {
18593 		boolean_t cached = B_FALSE;
18594 
18595 		/* force a recheck later on */
18596 		tcp->tcp_ire_ill_check_done = B_FALSE;
18597 
18598 		TCP_DBGSTAT(tcp_ire_null1);
18599 		connp->conn_ire_cache = NULL;
18600 		mutex_exit(&connp->conn_lock);
18601 		if (ire != NULL)
18602 			IRE_REFRELE_NOTR(ire);
18603 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
18604 		if (ire == NULL) {
18605 			if (tcp->tcp_snd_zcopy_aware)
18606 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18607 			TCP_STAT(tcp_ire_null);
18608 			CALL_IP_WPUT(connp, q, mp);
18609 			return;
18610 		}
18611 		IRE_REFHOLD_NOTR(ire);
18612 		/*
18613 		 * Since we are inside the squeue, there cannot be another
18614 		 * thread in TCP trying to set the conn_ire_cache now.  The
18615 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18616 		 * unplumb thread has not yet started cleaning up the conns.
18617 		 * Hence we don't need to grab the conn lock.
18618 		 */
18619 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18620 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18621 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18622 				connp->conn_ire_cache = ire;
18623 				cached = B_TRUE;
18624 			}
18625 			rw_exit(&ire->ire_bucket->irb_lock);
18626 		}
18627 
18628 		/*
18629 		 * We can continue to use the ire but since it was
18630 		 * not cached, we should drop the extra reference.
18631 		 */
18632 		if (!cached)
18633 			IRE_REFRELE_NOTR(ire);
18634 	}
18635 
18636 	if (ire->ire_flags & RTF_MULTIRT ||
18637 	    ire->ire_stq == NULL ||
18638 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18639 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18640 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18641 		if (tcp->tcp_snd_zcopy_aware)
18642 			mp = tcp_zcopy_disable(tcp, mp);
18643 		TCP_STAT(tcp_ip_ire_send);
18644 		IRE_REFRELE(ire);
18645 		CALL_IP_WPUT(connp, q, mp);
18646 		return;
18647 	}
18648 
18649 	ill = ire_to_ill(ire);
18650 	if (connp->conn_outgoing_ill != NULL) {
18651 		ill_t *conn_outgoing_ill = NULL;
18652 		/*
18653 		 * Choose a good ill in the group to send the packets on.
18654 		 */
18655 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18656 		ill = ire_to_ill(ire);
18657 	}
18658 	ASSERT(ill != NULL);
18659 
18660 	if (!tcp->tcp_ire_ill_check_done) {
18661 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18662 		tcp->tcp_ire_ill_check_done = B_TRUE;
18663 	}
18664 
18665 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18666 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18667 #ifndef _BIG_ENDIAN
18668 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18669 #endif
18670 
18671 	/*
18672 	 * Check to see if we need to re-enable MDT for this connection
18673 	 * because it was previously disabled due to changes in the ill;
18674 	 * note that by doing it here, this re-enabling only applies when
18675 	 * the packet is not dispatched through CALL_IP_WPUT().
18676 	 *
18677 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18678 	 * case, since that's how we ended up here.  For IPv6, we do the
18679 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18680 	 */
18681 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18682 		/*
18683 		 * Restore MDT for this connection, so that next time around
18684 		 * it is eligible to go through tcp_multisend() path again.
18685 		 */
18686 		TCP_STAT(tcp_mdt_conn_resumed1);
18687 		tcp->tcp_mdt = B_TRUE;
18688 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18689 		    "interface %s\n", (void *)connp, ill->ill_name));
18690 	}
18691 
18692 	if (tcp->tcp_snd_zcopy_aware) {
18693 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18694 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18695 			mp = tcp_zcopy_disable(tcp, mp);
18696 		/*
18697 		 * we shouldn't need to reset ipha as the mp containing
18698 		 * ipha should never be a zero-copy mp.
18699 		 */
18700 	}
18701 
18702 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) && dohwcksum) {
18703 		ASSERT(ill->ill_hcksum_capab != NULL);
18704 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18705 	}
18706 
18707 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18708 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18709 
18710 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18711 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18712 
18713 	/*
18714 	 * Underlying interface supports hardware checksum offload for
18715 	 * the tcp payload, along with M_DATA fast path; leave the payload
18716 	 * checksum for the hardware to calculate.
18717 	 *
18718 	 * N.B: We only need to set up checksum info on the first mblk.
18719 	 */
18720 	if (hcksum_txflags & HCKSUM_INET_FULL_V4) {
18721 		/*
18722 		 * Hardware calculates pseudo-header, header and payload
18723 		 * checksums, so clear checksum field in TCP header.
18724 		 */
18725 		*up = 0;
18726 		mp->b_datap->db_struioun.cksum.flags |= HCK_FULLCKSUM;
18727 	} else if (hcksum_txflags & HCKSUM_INET_PARTIAL) {
18728 		uint32_t sum;
18729 		/*
18730 		 * Partial checksum offload has been enabled.  Fill the
18731 		 * checksum field in the TCP header with the pseudo-header
18732 		 * checksum value.
18733 		 */
18734 		sum = *up + cksum + IP_TCP_CSUM_COMP;
18735 		sum = (sum & 0xFFFF) + (sum >> 16);
18736 		*up = (sum & 0xFFFF) + (sum >> 16);
18737 		mp->b_datap->db_cksumstart = IP_SIMPLE_HDR_LENGTH;
18738 		mp->b_datap->db_cksumstuff = IP_SIMPLE_HDR_LENGTH + 16;
18739 		mp->b_datap->db_cksumend = ntohs(ipha->ipha_length);
18740 		mp->b_datap->db_struioun.cksum.flags |= HCK_PARTIALCKSUM;
18741 	} else {
18742 		/* software checksumming */
18743 		TCP_STAT(tcp_out_sw_cksum);
18744 		*up = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH,
18745 		    cksum + IP_TCP_CSUM_COMP);
18746 		mp->b_datap->db_struioun.cksum.flags = 0;
18747 	}
18748 
18749 	ipha->ipha_fragment_offset_and_flags |=
18750 	    (uint32_t)htons(ire->ire_frag_flag);
18751 
18752 	/*
18753 	 * Hardware supports IP header checksum offload; clear contents
18754 	 * of IP header checksum field.  Otherwise we calculate it.
18755 	 */
18756 	if (hcksum_txflags & HCKSUM_IPHDRCKSUM) {
18757 		ipha->ipha_hdr_checksum = 0;
18758 		mp->b_datap->db_struioun.cksum.flags |= HCK_IPV4_HDRCKSUM;
18759 	} else {
18760 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18761 		    ((uint16_t *)ipha)[4]);
18762 	}
18763 
18764 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18765 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18766 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18767 
18768 	UPDATE_OB_PKT_COUNT(ire);
18769 	ire->ire_last_used_time = lbolt;
18770 	BUMP_MIB(&ip_mib, ipOutRequests);
18771 
18772 	if (ill->ill_capabilities & ILL_CAPAB_POLL) {
18773 		ill_poll = ill->ill_poll_capab;
18774 		ASSERT(ill_poll != NULL);
18775 		ASSERT(ill_poll->ill_tx != NULL);
18776 		ASSERT(ill_poll->ill_tx_handle != NULL);
18777 
18778 		ill_poll->ill_tx(ill_poll->ill_tx_handle, mp);
18779 	} else {
18780 		putnext(ire->ire_stq, mp);
18781 	}
18782 	IRE_REFRELE(ire);
18783 }
18784 
18785 /*
18786  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18787  * if the receiver shrinks the window, i.e. moves the right window to the
18788  * left, the we should not send new data, but should retransmit normally the
18789  * old unacked data between suna and suna + swnd. We might has sent data
18790  * that is now outside the new window, pretend that we didn't send  it.
18791  */
18792 static void
18793 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18794 {
18795 	uint32_t	snxt = tcp->tcp_snxt;
18796 	mblk_t		*xmit_tail;
18797 	int32_t		offset;
18798 
18799 	ASSERT(shrunk_count > 0);
18800 
18801 	/* Pretend we didn't send the data outside the window */
18802 	snxt -= shrunk_count;
18803 
18804 	/* Get the mblk and the offset in it per the shrunk window */
18805 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18806 
18807 	ASSERT(xmit_tail != NULL);
18808 
18809 	/* Reset all the values per the now shrunk window */
18810 	tcp->tcp_snxt = snxt;
18811 	tcp->tcp_xmit_tail = xmit_tail;
18812 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18813 	    offset;
18814 	tcp->tcp_unsent += shrunk_count;
18815 
18816 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18817 		/*
18818 		 * Make sure the timer is running so that we will probe a zero
18819 		 * window.
18820 		 */
18821 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18822 }
18823 
18824 
18825 /*
18826  * The TCP normal data output path.
18827  * NOTE: the logic of the fast path is duplicated from this function.
18828  */
18829 static void
18830 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18831 {
18832 	int		len;
18833 	mblk_t		*local_time;
18834 	mblk_t		*mp1;
18835 	uint32_t	snxt;
18836 	int		tail_unsent;
18837 	int		tcpstate;
18838 	int		usable = 0;
18839 	mblk_t		*xmit_tail;
18840 	queue_t		*q = tcp->tcp_wq;
18841 	int32_t		mss;
18842 	int32_t		num_sack_blk = 0;
18843 	int32_t		tcp_hdr_len;
18844 	int32_t		tcp_tcp_hdr_len;
18845 	int		mdt_thres;
18846 	int		rc;
18847 
18848 	tcpstate = tcp->tcp_state;
18849 	if (mp == NULL) {
18850 		/*
18851 		 * tcp_wput_data() with NULL mp should only be called when
18852 		 * there is unsent data.
18853 		 */
18854 		ASSERT(tcp->tcp_unsent > 0);
18855 		/* Really tacky... but we need this for detached closes. */
18856 		len = tcp->tcp_unsent;
18857 		goto data_null;
18858 	}
18859 
18860 #if CCS_STATS
18861 	wrw_stats.tot.count++;
18862 	wrw_stats.tot.bytes += msgdsize(mp);
18863 #endif
18864 	ASSERT(mp->b_datap->db_type == M_DATA);
18865 	/*
18866 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18867 	 * or before a connection attempt has begun.
18868 	 */
18869 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18870 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18871 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18872 #ifdef DEBUG
18873 			cmn_err(CE_WARN,
18874 			    "tcp_wput_data: data after ordrel, %s",
18875 			    tcp_display(tcp, NULL,
18876 			    DISP_ADDR_AND_PORT));
18877 #else
18878 			if (tcp->tcp_debug) {
18879 				(void) strlog(TCP_MODULE_ID, 0, 1,
18880 				    SL_TRACE|SL_ERROR,
18881 				    "tcp_wput_data: data after ordrel, %s\n",
18882 				    tcp_display(tcp, NULL,
18883 				    DISP_ADDR_AND_PORT));
18884 			}
18885 #endif /* DEBUG */
18886 		}
18887 		if (tcp->tcp_snd_zcopy_aware &&
18888 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18889 			tcp_zcopy_notify(tcp);
18890 		freemsg(mp);
18891 		return;
18892 	}
18893 
18894 	/* Strip empties */
18895 	for (;;) {
18896 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18897 		    (uintptr_t)INT_MAX);
18898 		len = (int)(mp->b_wptr - mp->b_rptr);
18899 		if (len > 0)
18900 			break;
18901 		mp1 = mp;
18902 		mp = mp->b_cont;
18903 		freeb(mp1);
18904 		if (!mp) {
18905 			return;
18906 		}
18907 	}
18908 
18909 	/* If we are the first on the list ... */
18910 	if (tcp->tcp_xmit_head == NULL) {
18911 		tcp->tcp_xmit_head = mp;
18912 		tcp->tcp_xmit_tail = mp;
18913 		tcp->tcp_xmit_tail_unsent = len;
18914 	} else {
18915 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18916 		struct datab *dp;
18917 
18918 		mp1 = tcp->tcp_xmit_last;
18919 		if (len < tcp_tx_pull_len &&
18920 		    (dp = mp1->b_datap)->db_ref == 1 &&
18921 		    dp->db_lim - mp1->b_wptr >= len) {
18922 			ASSERT(len > 0);
18923 			ASSERT(!mp1->b_cont);
18924 			if (len == 1) {
18925 				*mp1->b_wptr++ = *mp->b_rptr;
18926 			} else {
18927 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18928 				mp1->b_wptr += len;
18929 			}
18930 			if (mp1 == tcp->tcp_xmit_tail)
18931 				tcp->tcp_xmit_tail_unsent += len;
18932 			mp1->b_cont = mp->b_cont;
18933 			if (tcp->tcp_snd_zcopy_aware &&
18934 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18935 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18936 			freeb(mp);
18937 			mp = mp1;
18938 		} else {
18939 			tcp->tcp_xmit_last->b_cont = mp;
18940 		}
18941 		len += tcp->tcp_unsent;
18942 	}
18943 
18944 	/* Tack on however many more positive length mblks we have */
18945 	if ((mp1 = mp->b_cont) != NULL) {
18946 		do {
18947 			int tlen;
18948 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18949 			    (uintptr_t)INT_MAX);
18950 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18951 			if (tlen <= 0) {
18952 				mp->b_cont = mp1->b_cont;
18953 				freeb(mp1);
18954 			} else {
18955 				len += tlen;
18956 				mp = mp1;
18957 			}
18958 		} while ((mp1 = mp->b_cont) != NULL);
18959 	}
18960 	tcp->tcp_xmit_last = mp;
18961 	tcp->tcp_unsent = len;
18962 
18963 	if (urgent)
18964 		usable = 1;
18965 
18966 data_null:
18967 	snxt = tcp->tcp_snxt;
18968 	xmit_tail = tcp->tcp_xmit_tail;
18969 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18970 
18971 	/*
18972 	 * Note that tcp_mss has been adjusted to take into account the
18973 	 * timestamp option if applicable.  Because SACK options do not
18974 	 * appear in every TCP segments and they are of variable lengths,
18975 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18976 	 * the actual segment length when we need to send a segment which
18977 	 * includes SACK options.
18978 	 */
18979 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18980 		int32_t	opt_len;
18981 
18982 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18983 		    tcp->tcp_num_sack_blk);
18984 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18985 		    2 + TCPOPT_HEADER_LEN;
18986 		mss = tcp->tcp_mss - opt_len;
18987 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18988 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18989 	} else {
18990 		mss = tcp->tcp_mss;
18991 		tcp_hdr_len = tcp->tcp_hdr_len;
18992 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18993 	}
18994 
18995 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18996 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18997 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18998 	}
18999 	if (tcpstate == TCPS_SYN_RCVD) {
19000 		/*
19001 		 * The three-way connection establishment handshake is not
19002 		 * complete yet. We want to queue the data for transmission
19003 		 * after entering ESTABLISHED state (RFC793). A jump to
19004 		 * "done" label effectively leaves data on the queue.
19005 		 */
19006 		goto done;
19007 	} else {
19008 		int usable_r = tcp->tcp_swnd;
19009 
19010 		/*
19011 		 * In the special case when cwnd is zero, which can only
19012 		 * happen if the connection is ECN capable, return now.
19013 		 * New segments is sent using tcp_timer().  The timer
19014 		 * is set in tcp_rput_data().
19015 		 */
19016 		if (tcp->tcp_cwnd == 0) {
19017 			/*
19018 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19019 			 * finished.
19020 			 */
19021 			ASSERT(tcp->tcp_ecn_ok ||
19022 			    tcp->tcp_state < TCPS_ESTABLISHED);
19023 			return;
19024 		}
19025 
19026 		/* NOTE: trouble if xmitting while SYN not acked? */
19027 		usable_r -= snxt;
19028 		usable_r += tcp->tcp_suna;
19029 
19030 		/*
19031 		 * Check if the receiver has shrunk the window.  If
19032 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19033 		 * cannot be set as there is unsent data, so FIN cannot
19034 		 * be sent out.  Otherwise, we need to take into account
19035 		 * of FIN as it consumes an "invisible" sequence number.
19036 		 */
19037 		ASSERT(tcp->tcp_fin_sent == 0);
19038 		if (usable_r < 0) {
19039 			/*
19040 			 * The receiver has shrunk the window and we have sent
19041 			 * -usable_r date beyond the window, re-adjust.
19042 			 *
19043 			 * If TCP window scaling is enabled, there can be
19044 			 * round down error as the advertised receive window
19045 			 * is actually right shifted n bits.  This means that
19046 			 * the lower n bits info is wiped out.  It will look
19047 			 * like the window is shrunk.  Do a check here to
19048 			 * see if the shrunk amount is actually within the
19049 			 * error in window calculation.  If it is, just
19050 			 * return.  Note that this check is inside the
19051 			 * shrunk window check.  This makes sure that even
19052 			 * though tcp_process_shrunk_swnd() is not called,
19053 			 * we will stop further processing.
19054 			 */
19055 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19056 				tcp_process_shrunk_swnd(tcp, -usable_r);
19057 			}
19058 			return;
19059 		}
19060 
19061 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19062 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19063 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19064 
19065 		/* usable = MIN(usable, unsent) */
19066 		if (usable_r > len)
19067 			usable_r = len;
19068 
19069 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19070 		if (usable_r > 0) {
19071 			usable = usable_r;
19072 		} else {
19073 			/* Bypass all other unnecessary processing. */
19074 			goto done;
19075 		}
19076 	}
19077 
19078 	local_time = (mblk_t *)lbolt;
19079 
19080 	/*
19081 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19082 	 * BSD.  This is more in line with the true intent of Nagle.
19083 	 *
19084 	 * The conditions are:
19085 	 * 1. The amount of unsent data (or amount of data which can be
19086 	 *    sent, whichever is smaller) is less than Nagle limit.
19087 	 * 2. The last sent size is also less than Nagle limit.
19088 	 * 3. There is unack'ed data.
19089 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19090 	 *    Nagle algorithm.  This reduces the probability that urgent
19091 	 *    bytes get "merged" together.
19092 	 * 5. The app has not closed the connection.  This eliminates the
19093 	 *    wait time of the receiving side waiting for the last piece of
19094 	 *    (small) data.
19095 	 *
19096 	 * If all are satisified, exit without sending anything.  Note
19097 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19098 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19099 	 * 4095).
19100 	 */
19101 	if (usable < (int)tcp->tcp_naglim &&
19102 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19103 	    snxt != tcp->tcp_suna &&
19104 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19105 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19106 		goto done;
19107 	}
19108 
19109 	if (tcp->tcp_cork) {
19110 		/*
19111 		 * if the tcp->tcp_cork option is set, then we have to force
19112 		 * TCP not to send partial segment (smaller than MSS bytes).
19113 		 * We are calculating the usable now based on full mss and
19114 		 * will save the rest of remaining data for later.
19115 		 */
19116 		if (usable < mss)
19117 			goto done;
19118 		usable = (usable / mss) * mss;
19119 	}
19120 
19121 	/* Update the latest receive window size in TCP header. */
19122 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19123 	    tcp->tcp_tcph->th_win);
19124 
19125 	/*
19126 	 * Determine if it's worthwhile to attempt MDT, based on:
19127 	 *
19128 	 * 1. Simple TCP/IP{v4,v6} (no options).
19129 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19130 	 * 3. If the TCP connection is in ESTABLISHED state.
19131 	 * 4. The TCP is not detached.
19132 	 *
19133 	 * If any of the above conditions have changed during the
19134 	 * connection, stop using MDT and restore the stream head
19135 	 * parameters accordingly.
19136 	 */
19137 	if (tcp->tcp_mdt &&
19138 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19139 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19140 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19141 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19142 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19143 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
19144 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19145 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
19146 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19147 		tcp->tcp_mdt = B_FALSE;
19148 
19149 		/* Anything other than detached is considered pathological */
19150 		if (!TCP_IS_DETACHED(tcp)) {
19151 			TCP_STAT(tcp_mdt_conn_halted1);
19152 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19153 		}
19154 	}
19155 
19156 	/* Use MDT if sendable amount is greater than the threshold */
19157 	if (tcp->tcp_mdt &&
19158 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19159 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19160 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19161 	    (tcp->tcp_valid_bits == 0 ||
19162 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19163 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19164 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19165 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19166 		    local_time, mdt_thres);
19167 	} else {
19168 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19169 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19170 		    local_time, INT_MAX);
19171 	}
19172 
19173 	/* Pretend that all we were trying to send really got sent */
19174 	if (rc < 0 && tail_unsent < 0) {
19175 		do {
19176 			xmit_tail = xmit_tail->b_cont;
19177 			xmit_tail->b_prev = local_time;
19178 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19179 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19180 			tail_unsent += (int)(xmit_tail->b_wptr -
19181 			    xmit_tail->b_rptr);
19182 		} while (tail_unsent < 0);
19183 	}
19184 done:;
19185 	tcp->tcp_xmit_tail = xmit_tail;
19186 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19187 	len = tcp->tcp_snxt - snxt;
19188 	if (len) {
19189 		/*
19190 		 * If new data was sent, need to update the notsack
19191 		 * list, which is, afterall, data blocks that have
19192 		 * not been sack'ed by the receiver.  New data is
19193 		 * not sack'ed.
19194 		 */
19195 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19196 			/* len is a negative value. */
19197 			tcp->tcp_pipe -= len;
19198 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19199 			    tcp->tcp_snxt, snxt,
19200 			    &(tcp->tcp_num_notsack_blk),
19201 			    &(tcp->tcp_cnt_notsack_list));
19202 		}
19203 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19204 		tcp->tcp_rack = tcp->tcp_rnxt;
19205 		tcp->tcp_rack_cnt = 0;
19206 		if ((snxt + len) == tcp->tcp_suna) {
19207 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19208 		}
19209 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19210 		/*
19211 		 * Didn't send anything. Make sure the timer is running
19212 		 * so that we will probe a zero window.
19213 		 */
19214 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19215 	}
19216 	/* Note that len is the amount we just sent but with a negative sign */
19217 	len += tcp->tcp_unsent;
19218 	tcp->tcp_unsent = len;
19219 	if (tcp->tcp_flow_stopped) {
19220 		if (len <= tcp->tcp_xmit_lowater) {
19221 			tcp->tcp_flow_stopped = B_FALSE;
19222 			tcp_clrqfull(tcp);
19223 		}
19224 	} else if (len >= tcp->tcp_xmit_hiwater) {
19225 		tcp->tcp_flow_stopped = B_TRUE;
19226 		tcp_setqfull(tcp);
19227 	}
19228 }
19229 
19230 /*
19231  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19232  * outgoing TCP header with the template header, as well as other
19233  * options such as time-stamp, ECN and/or SACK.
19234  */
19235 static void
19236 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19237 {
19238 	tcph_t *tcp_tmpl, *tcp_h;
19239 	uint32_t *dst, *src;
19240 	int hdrlen;
19241 
19242 	ASSERT(OK_32PTR(rptr));
19243 
19244 	/* Template header */
19245 	tcp_tmpl = tcp->tcp_tcph;
19246 
19247 	/* Header of outgoing packet */
19248 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19249 
19250 	/* dst and src are opaque 32-bit fields, used for copying */
19251 	dst = (uint32_t *)rptr;
19252 	src = (uint32_t *)tcp->tcp_iphc;
19253 	hdrlen = tcp->tcp_hdr_len;
19254 
19255 	/* Fill time-stamp option if needed */
19256 	if (tcp->tcp_snd_ts_ok) {
19257 		U32_TO_BE32((uint32_t)now,
19258 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19259 		U32_TO_BE32(tcp->tcp_ts_recent,
19260 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19261 	} else {
19262 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19263 	}
19264 
19265 	/*
19266 	 * Copy the template header; is this really more efficient than
19267 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19268 	 * but perhaps not for other scenarios.
19269 	 */
19270 	dst[0] = src[0];
19271 	dst[1] = src[1];
19272 	dst[2] = src[2];
19273 	dst[3] = src[3];
19274 	dst[4] = src[4];
19275 	dst[5] = src[5];
19276 	dst[6] = src[6];
19277 	dst[7] = src[7];
19278 	dst[8] = src[8];
19279 	dst[9] = src[9];
19280 	if (hdrlen -= 40) {
19281 		hdrlen >>= 2;
19282 		dst += 10;
19283 		src += 10;
19284 		do {
19285 			*dst++ = *src++;
19286 		} while (--hdrlen);
19287 	}
19288 
19289 	/*
19290 	 * Set the ECN info in the TCP header if it is not a zero
19291 	 * window probe.  Zero window probe is only sent in
19292 	 * tcp_wput_data() and tcp_timer().
19293 	 */
19294 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19295 		SET_ECT(tcp, rptr);
19296 
19297 		if (tcp->tcp_ecn_echo_on)
19298 			tcp_h->th_flags[0] |= TH_ECE;
19299 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19300 			tcp_h->th_flags[0] |= TH_CWR;
19301 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19302 		}
19303 	}
19304 
19305 	/* Fill in SACK options */
19306 	if (num_sack_blk > 0) {
19307 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19308 		sack_blk_t *tmp;
19309 		int32_t	i;
19310 
19311 		wptr[0] = TCPOPT_NOP;
19312 		wptr[1] = TCPOPT_NOP;
19313 		wptr[2] = TCPOPT_SACK;
19314 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19315 		    sizeof (sack_blk_t);
19316 		wptr += TCPOPT_REAL_SACK_LEN;
19317 
19318 		tmp = tcp->tcp_sack_list;
19319 		for (i = 0; i < num_sack_blk; i++) {
19320 			U32_TO_BE32(tmp[i].begin, wptr);
19321 			wptr += sizeof (tcp_seq);
19322 			U32_TO_BE32(tmp[i].end, wptr);
19323 			wptr += sizeof (tcp_seq);
19324 		}
19325 		tcp_h->th_offset_and_rsrvd[0] +=
19326 		    ((num_sack_blk * 2 + 1) << 4);
19327 	}
19328 }
19329 
19330 /*
19331  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19332  * the destination address and SAP attribute, and if necessary, the
19333  * hardware checksum offload attribute to a Multidata message.
19334  */
19335 static int
19336 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19337     const uint32_t start, const uint32_t stuff, const uint32_t end,
19338     const uint32_t flags)
19339 {
19340 	/* Add global destination address & SAP attribute */
19341 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19342 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19343 		    "destination address+SAP\n"));
19344 
19345 		if (dlmp != NULL)
19346 			TCP_STAT(tcp_mdt_allocfail);
19347 		return (-1);
19348 	}
19349 
19350 	/* Add global hwcksum attribute */
19351 	if (hwcksum &&
19352 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19353 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19354 		    "checksum attribute\n"));
19355 
19356 		TCP_STAT(tcp_mdt_allocfail);
19357 		return (-1);
19358 	}
19359 
19360 	return (0);
19361 }
19362 
19363 /*
19364  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19365  * scheme, and returns one the following:
19366  *
19367  * -1 = failed allocation.
19368  *  0 = success; burst count reached, or usable send window is too small,
19369  *      and that we'd rather wait until later before sending again.
19370  */
19371 static int
19372 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19373     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19374     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19375     const int mdt_thres)
19376 {
19377 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19378 	multidata_t	*mmd;
19379 	uint_t		obsegs, obbytes, hdr_frag_sz;
19380 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19381 	int		num_burst_seg, max_pld;
19382 	pdesc_t		*pkt;
19383 	tcp_pdescinfo_t	tcp_pkt_info;
19384 	pdescinfo_t	*pkt_info;
19385 	int		pbuf_idx, pbuf_idx_nxt;
19386 	int		seg_len, len, spill, af;
19387 	boolean_t	add_buffer, zcopy, clusterwide;
19388 	boolean_t	rconfirm = B_FALSE;
19389 	boolean_t	done = B_FALSE;
19390 	uint32_t	cksum;
19391 	uint32_t	hwcksum_flags;
19392 	ire_t		*ire;
19393 	ill_t		*ill;
19394 	ipha_t		*ipha;
19395 	ip6_t		*ip6h;
19396 	ipaddr_t	src, dst;
19397 	ill_zerocopy_capab_t *zc_cap = NULL;
19398 	uint16_t	*up;
19399 	int		err;
19400 
19401 #ifdef	_BIG_ENDIAN
19402 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19403 #else
19404 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19405 #endif
19406 
19407 #define	TCP_CSUM_OFFSET	16
19408 #define	TCP_CSUM_SIZE	2
19409 
19410 #define	PREP_NEW_MULTIDATA() {			\
19411 	mmd = NULL;				\
19412 	md_mp = md_hbuf = NULL;			\
19413 	cur_hdr_off = 0;			\
19414 	max_pld = tcp->tcp_mdt_max_pld;		\
19415 	pbuf_idx = pbuf_idx_nxt = -1;		\
19416 	add_buffer = B_TRUE;			\
19417 	zcopy = B_FALSE;			\
19418 }
19419 
19420 #define	PREP_NEW_PBUF() {			\
19421 	md_pbuf = md_pbuf_nxt = NULL;		\
19422 	pbuf_idx = pbuf_idx_nxt = -1;		\
19423 	cur_pld_off = 0;			\
19424 	first_snxt = *snxt;			\
19425 	ASSERT(*tail_unsent > 0);		\
19426 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19427 }
19428 
19429 	ASSERT(mdt_thres >= mss);
19430 	ASSERT(*usable > 0 && *usable > mdt_thres);
19431 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19432 	ASSERT(!TCP_IS_DETACHED(tcp));
19433 	ASSERT(tcp->tcp_valid_bits == 0 ||
19434 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19435 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19436 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19437 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19438 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19439 	ASSERT(tcp->tcp_connp != NULL);
19440 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
19441 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
19442 
19443 	/*
19444 	 * Note that tcp will only declare at most 2 payload spans per
19445 	 * packet, which is much lower than the maximum allowable number
19446 	 * of packet spans per Multidata.  For this reason, we use the
19447 	 * privately declared and smaller descriptor info structure, in
19448 	 * order to save some stack space.
19449 	 */
19450 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19451 
19452 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19453 	if (af == AF_INET) {
19454 		dst = tcp->tcp_ipha->ipha_dst;
19455 		src = tcp->tcp_ipha->ipha_src;
19456 		ASSERT(!CLASSD(dst));
19457 	}
19458 	ASSERT(af == AF_INET ||
19459 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19460 
19461 	obsegs = obbytes = 0;
19462 	num_burst_seg = tcp->tcp_snd_burst;
19463 	md_mp_head = NULL;
19464 	PREP_NEW_MULTIDATA();
19465 
19466 	/*
19467 	 * Before we go on further, make sure there is an IRE that we can
19468 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19469 	 * in proceeding any further, and we should just hand everything
19470 	 * off to the legacy path.
19471 	 */
19472 	mutex_enter(&tcp->tcp_connp->conn_lock);
19473 	ire = tcp->tcp_connp->conn_ire_cache;
19474 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
19475 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19476 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19477 	    &tcp->tcp_ip6h->ip6_dst))) &&
19478 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19479 		IRE_REFHOLD(ire);
19480 		mutex_exit(&tcp->tcp_connp->conn_lock);
19481 	} else {
19482 		boolean_t cached = B_FALSE;
19483 
19484 		/* force a recheck later on */
19485 		tcp->tcp_ire_ill_check_done = B_FALSE;
19486 
19487 		TCP_DBGSTAT(tcp_ire_null1);
19488 		tcp->tcp_connp->conn_ire_cache = NULL;
19489 		mutex_exit(&tcp->tcp_connp->conn_lock);
19490 
19491 		/* Release the old ire */
19492 		if (ire != NULL)
19493 			IRE_REFRELE_NOTR(ire);
19494 
19495 		ire = (af == AF_INET) ?
19496 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
19497 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19498 		    tcp->tcp_connp->conn_zoneid);
19499 
19500 		if (ire == NULL) {
19501 			TCP_STAT(tcp_ire_null);
19502 			goto legacy_send_no_md;
19503 		}
19504 
19505 		IRE_REFHOLD_NOTR(ire);
19506 		/*
19507 		 * Since we are inside the squeue, there cannot be another
19508 		 * thread in TCP trying to set the conn_ire_cache now. The
19509 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19510 		 * unplumb thread has not yet started cleaning up the conns.
19511 		 * Hence we don't need to grab the conn lock.
19512 		 */
19513 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
19514 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19515 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19516 				tcp->tcp_connp->conn_ire_cache = ire;
19517 				cached = B_TRUE;
19518 			}
19519 			rw_exit(&ire->ire_bucket->irb_lock);
19520 		}
19521 
19522 		/*
19523 		 * We can continue to use the ire but since it was not
19524 		 * cached, we should drop the extra reference.
19525 		 */
19526 		if (!cached)
19527 			IRE_REFRELE_NOTR(ire);
19528 	}
19529 
19530 	ASSERT(ire != NULL);
19531 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19532 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19533 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19534 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19535 	/*
19536 	 * If we do support loopback for MDT (which requires modifications
19537 	 * to the receiving paths), the following assertions should go away,
19538 	 * and we would be sending the Multidata to loopback conn later on.
19539 	 */
19540 	ASSERT(!IRE_IS_LOCAL(ire));
19541 	ASSERT(ire->ire_stq != NULL);
19542 
19543 	ill = ire_to_ill(ire);
19544 	ASSERT(ill != NULL);
19545 	ASSERT((ill->ill_capabilities & ILL_CAPAB_MDT) == 0 ||
19546 	    ill->ill_mdt_capab != NULL);
19547 
19548 	if (!tcp->tcp_ire_ill_check_done) {
19549 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19550 		tcp->tcp_ire_ill_check_done = B_TRUE;
19551 	}
19552 
19553 	/*
19554 	 * If the underlying interface conditions have changed, or if the
19555 	 * new interface does not support MDT, go back to legacy path.
19556 	 */
19557 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19558 		/* don't go through this path anymore for this connection */
19559 		TCP_STAT(tcp_mdt_conn_halted2);
19560 		tcp->tcp_mdt = B_FALSE;
19561 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19562 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
19563 		/* IRE will be released prior to returning */
19564 		goto legacy_send_no_md;
19565 	}
19566 
19567 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19568 		zc_cap = ill->ill_zerocopy_capab;
19569 
19570 	/* go to legacy path if interface doesn't support zerocopy */
19571 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19572 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19573 		/* IRE will be released prior to returning */
19574 		goto legacy_send_no_md;
19575 	}
19576 
19577 	/* does the interface support hardware checksum offload? */
19578 	hwcksum_flags = 0;
19579 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&
19580 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19581 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM)) &&
19582 	    dohwcksum) {
19583 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19584 		    HCKSUM_IPHDRCKSUM)
19585 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19586 
19587 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19588 		    HCKSUM_INET_FULL_V4)
19589 			hwcksum_flags |= HCK_FULLCKSUM;
19590 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19591 		    HCKSUM_INET_PARTIAL)
19592 			hwcksum_flags |= HCK_PARTIALCKSUM;
19593 	}
19594 
19595 	/*
19596 	 * Each header fragment consists of the leading extra space,
19597 	 * followed by the TCP/IP header, and the trailing extra space.
19598 	 * We make sure that each header fragment begins on a 32-bit
19599 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19600 	 * aligned in tcp_mdt_update).
19601 	 */
19602 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19603 	    tcp->tcp_mdt_hdr_tail), 4);
19604 
19605 	/* are we starting from the beginning of data block? */
19606 	if (*tail_unsent == 0) {
19607 		*xmit_tail = (*xmit_tail)->b_cont;
19608 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19609 		*tail_unsent = (int)MBLKL(*xmit_tail);
19610 	}
19611 
19612 	/*
19613 	 * Here we create one or more Multidata messages, each made up of
19614 	 * one header buffer and up to N payload buffers.  This entire
19615 	 * operation is done within two loops:
19616 	 *
19617 	 * The outer loop mostly deals with creating the Multidata message,
19618 	 * as well as the header buffer that gets added to it.  It also
19619 	 * links the Multidata messages together such that all of them can
19620 	 * be sent down to the lower layer in a single putnext call; this
19621 	 * linking behavior depends on the tcp_mdt_chain tunable.
19622 	 *
19623 	 * The inner loop takes an existing Multidata message, and adds
19624 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19625 	 * packetizes those buffers by filling up the corresponding header
19626 	 * buffer fragments with the proper IP and TCP headers, and by
19627 	 * describing the layout of each packet in the packet descriptors
19628 	 * that get added to the Multidata.
19629 	 */
19630 	do {
19631 		/*
19632 		 * If usable send window is too small, or data blocks in
19633 		 * transmit list are smaller than our threshold (i.e. app
19634 		 * performs large writes followed by small ones), we hand
19635 		 * off the control over to the legacy path.  Note that we'll
19636 		 * get back the control once it encounters a large block.
19637 		 */
19638 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19639 		    (*xmit_tail)->b_cont != NULL &&
19640 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19641 			/* send down what we've got so far */
19642 			if (md_mp_head != NULL) {
19643 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19644 				    obsegs, obbytes, &rconfirm);
19645 			}
19646 			/*
19647 			 * Pass control over to tcp_send(), but tell it to
19648 			 * return to us once a large-size transmission is
19649 			 * possible.
19650 			 */
19651 			TCP_STAT(tcp_mdt_legacy_small);
19652 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19653 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19654 			    tail_unsent, xmit_tail, local_time,
19655 			    mdt_thres)) <= 0) {
19656 				/* burst count reached, or alloc failed */
19657 				IRE_REFRELE(ire);
19658 				return (err);
19659 			}
19660 
19661 			/* tcp_send() may have sent everything, so check */
19662 			if (*usable <= 0) {
19663 				IRE_REFRELE(ire);
19664 				return (0);
19665 			}
19666 
19667 			TCP_STAT(tcp_mdt_legacy_ret);
19668 			/*
19669 			 * We may have delivered the Multidata, so make sure
19670 			 * to re-initialize before the next round.
19671 			 */
19672 			md_mp_head = NULL;
19673 			obsegs = obbytes = 0;
19674 			num_burst_seg = tcp->tcp_snd_burst;
19675 			PREP_NEW_MULTIDATA();
19676 
19677 			/* are we starting from the beginning of data block? */
19678 			if (*tail_unsent == 0) {
19679 				*xmit_tail = (*xmit_tail)->b_cont;
19680 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19681 				    (uintptr_t)INT_MAX);
19682 				*tail_unsent = (int)MBLKL(*xmit_tail);
19683 			}
19684 		}
19685 
19686 		/*
19687 		 * max_pld limits the number of mblks in tcp's transmit
19688 		 * queue that can be added to a Multidata message.  Once
19689 		 * this counter reaches zero, no more additional mblks
19690 		 * can be added to it.  What happens afterwards depends
19691 		 * on whether or not we are set to chain the Multidata
19692 		 * messages.  If we are to link them together, reset
19693 		 * max_pld to its original value (tcp_mdt_max_pld) and
19694 		 * prepare to create a new Multidata message which will
19695 		 * get linked to md_mp_head.  Else, leave it alone and
19696 		 * let the inner loop break on its own.
19697 		 */
19698 		if (tcp_mdt_chain && max_pld == 0)
19699 			PREP_NEW_MULTIDATA();
19700 
19701 		/* adding a payload buffer; re-initialize values */
19702 		if (add_buffer)
19703 			PREP_NEW_PBUF();
19704 
19705 		/*
19706 		 * If we don't have a Multidata, either because we just
19707 		 * (re)entered this outer loop, or after we branched off
19708 		 * to tcp_send above, setup the Multidata and header
19709 		 * buffer to be used.
19710 		 */
19711 		if (md_mp == NULL) {
19712 			int md_hbuflen;
19713 			uint32_t start, stuff;
19714 
19715 			/*
19716 			 * Calculate Multidata header buffer size large enough
19717 			 * to hold all of the headers that can possibly be
19718 			 * sent at this moment.  We'd rather over-estimate
19719 			 * the size than running out of space; this is okay
19720 			 * since this buffer is small anyway.
19721 			 */
19722 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19723 
19724 			/*
19725 			 * Start and stuff offset for partial hardware
19726 			 * checksum offload; these are currently for IPv4.
19727 			 * For full checksum offload, they are set to zero.
19728 			 */
19729 			if (af == AF_INET &&
19730 			    (hwcksum_flags & HCK_PARTIALCKSUM)) {
19731 				start = IP_SIMPLE_HDR_LENGTH;
19732 				stuff = IP_SIMPLE_HDR_LENGTH + TCP_CSUM_OFFSET;
19733 			} else {
19734 				start = stuff = 0;
19735 			}
19736 
19737 			/*
19738 			 * Create the header buffer, Multidata, as well as
19739 			 * any necessary attributes (destination address,
19740 			 * SAP and hardware checksum offload) that should
19741 			 * be associated with the Multidata message.
19742 			 */
19743 			ASSERT(cur_hdr_off == 0);
19744 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19745 			    ((md_hbuf->b_wptr += md_hbuflen),
19746 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19747 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19748 			    /* fastpath mblk */
19749 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19750 			    ire->ire_nce->nce_res_mp,
19751 			    /* hardware checksum enabled (IPv4 only) */
19752 			    (af == AF_INET && hwcksum_flags != 0),
19753 			    /* hardware checksum offsets */
19754 			    start, stuff, 0,
19755 			    /* hardware checksum flag */
19756 			    hwcksum_flags) != 0)) {
19757 legacy_send:
19758 				if (md_mp != NULL) {
19759 					/* Unlink message from the chain */
19760 					if (md_mp_head != NULL) {
19761 						err = (intptr_t)rmvb(md_mp_head,
19762 						    md_mp);
19763 						/*
19764 						 * We can't assert that rmvb
19765 						 * did not return -1, since we
19766 						 * may get here before linkb
19767 						 * happens.  We do, however,
19768 						 * check if we just removed the
19769 						 * only element in the list.
19770 						 */
19771 						if (err == 0)
19772 							md_mp_head = NULL;
19773 					}
19774 					/* md_hbuf gets freed automatically */
19775 					TCP_STAT(tcp_mdt_discarded);
19776 					freeb(md_mp);
19777 				} else {
19778 					/* Either allocb or mmd_alloc failed */
19779 					TCP_STAT(tcp_mdt_allocfail);
19780 					if (md_hbuf != NULL)
19781 						freeb(md_hbuf);
19782 				}
19783 
19784 				/* send down what we've got so far */
19785 				if (md_mp_head != NULL) {
19786 					tcp_multisend_data(tcp, ire, ill,
19787 					    md_mp_head, obsegs, obbytes,
19788 					    &rconfirm);
19789 				}
19790 legacy_send_no_md:
19791 				if (ire != NULL)
19792 					IRE_REFRELE(ire);
19793 				/*
19794 				 * Too bad; let the legacy path handle this.
19795 				 * We specify INT_MAX for the threshold, since
19796 				 * we gave up with the Multidata processings
19797 				 * and let the old path have it all.
19798 				 */
19799 				TCP_STAT(tcp_mdt_legacy_all);
19800 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19801 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19802 				    snxt, tail_unsent, xmit_tail, local_time,
19803 				    INT_MAX));
19804 			}
19805 
19806 			/* link to any existing ones, if applicable */
19807 			TCP_STAT(tcp_mdt_allocd);
19808 			if (md_mp_head == NULL) {
19809 				md_mp_head = md_mp;
19810 			} else if (tcp_mdt_chain) {
19811 				TCP_STAT(tcp_mdt_linked);
19812 				linkb(md_mp_head, md_mp);
19813 			}
19814 		}
19815 
19816 		ASSERT(md_mp_head != NULL);
19817 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19818 		ASSERT(md_mp != NULL && mmd != NULL);
19819 		ASSERT(md_hbuf != NULL);
19820 
19821 		/*
19822 		 * Packetize the transmittable portion of the data block;
19823 		 * each data block is essentially added to the Multidata
19824 		 * as a payload buffer.  We also deal with adding more
19825 		 * than one payload buffers, which happens when the remaining
19826 		 * packetized portion of the current payload buffer is less
19827 		 * than MSS, while the next data block in transmit queue
19828 		 * has enough data to make up for one.  This "spillover"
19829 		 * case essentially creates a split-packet, where portions
19830 		 * of the packet's payload fragments may span across two
19831 		 * virtually discontiguous address blocks.
19832 		 */
19833 		seg_len = mss;
19834 		do {
19835 			len = seg_len;
19836 
19837 			ASSERT(len > 0);
19838 			ASSERT(max_pld >= 0);
19839 			ASSERT(!add_buffer || cur_pld_off == 0);
19840 
19841 			/*
19842 			 * First time around for this payload buffer; note
19843 			 * in the case of a spillover, the following has
19844 			 * been done prior to adding the split-packet
19845 			 * descriptor to Multidata, and we don't want to
19846 			 * repeat the process.
19847 			 */
19848 			if (add_buffer) {
19849 				ASSERT(mmd != NULL);
19850 				ASSERT(md_pbuf == NULL);
19851 				ASSERT(md_pbuf_nxt == NULL);
19852 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19853 
19854 				/*
19855 				 * Have we reached the limit?  We'd get to
19856 				 * this case when we're not chaining the
19857 				 * Multidata messages together, and since
19858 				 * we're done, terminate this loop.
19859 				 */
19860 				if (max_pld == 0)
19861 					break; /* done */
19862 
19863 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19864 					TCP_STAT(tcp_mdt_allocfail);
19865 					goto legacy_send; /* out_of_mem */
19866 				}
19867 
19868 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19869 				    zc_cap != NULL) {
19870 					if (!ip_md_zcopy_attr(mmd, NULL,
19871 					    zc_cap->ill_zerocopy_flags)) {
19872 						freeb(md_pbuf);
19873 						TCP_STAT(tcp_mdt_allocfail);
19874 						/* out_of_mem */
19875 						goto legacy_send;
19876 					}
19877 					zcopy = B_TRUE;
19878 				}
19879 
19880 				md_pbuf->b_rptr += base_pld_off;
19881 
19882 				/*
19883 				 * Add a payload buffer to the Multidata; this
19884 				 * operation must not fail, or otherwise our
19885 				 * logic in this routine is broken.  There
19886 				 * is no memory allocation done by the
19887 				 * routine, so any returned failure simply
19888 				 * tells us that we've done something wrong.
19889 				 *
19890 				 * A failure tells us that either we're adding
19891 				 * the same payload buffer more than once, or
19892 				 * we're trying to add more buffers than
19893 				 * allowed (max_pld calculation is wrong).
19894 				 * None of the above cases should happen, and
19895 				 * we panic because either there's horrible
19896 				 * heap corruption, and/or programming mistake.
19897 				 */
19898 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19899 				if (pbuf_idx < 0) {
19900 					cmn_err(CE_PANIC, "tcp_multisend: "
19901 					    "payload buffer logic error "
19902 					    "detected for tcp %p mmd %p "
19903 					    "pbuf %p (%d)\n",
19904 					    (void *)tcp, (void *)mmd,
19905 					    (void *)md_pbuf, pbuf_idx);
19906 				}
19907 
19908 				ASSERT(max_pld > 0);
19909 				--max_pld;
19910 				add_buffer = B_FALSE;
19911 			}
19912 
19913 			ASSERT(md_mp_head != NULL);
19914 			ASSERT(md_pbuf != NULL);
19915 			ASSERT(md_pbuf_nxt == NULL);
19916 			ASSERT(pbuf_idx != -1);
19917 			ASSERT(pbuf_idx_nxt == -1);
19918 			ASSERT(*usable > 0);
19919 
19920 			/*
19921 			 * We spillover to the next payload buffer only
19922 			 * if all of the following is true:
19923 			 *
19924 			 *   1. There is not enough data on the current
19925 			 *	payload buffer to make up `len',
19926 			 *   2. We are allowed to send `len',
19927 			 *   3. The next payload buffer length is large
19928 			 *	enough to accomodate `spill'.
19929 			 */
19930 			if ((spill = len - *tail_unsent) > 0 &&
19931 			    *usable >= len &&
19932 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19933 			    max_pld > 0) {
19934 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19935 				if (md_pbuf_nxt == NULL) {
19936 					TCP_STAT(tcp_mdt_allocfail);
19937 					goto legacy_send; /* out_of_mem */
19938 				}
19939 
19940 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19941 				    zc_cap != NULL) {
19942 					if (!ip_md_zcopy_attr(mmd, NULL,
19943 					    zc_cap->ill_zerocopy_flags)) {
19944 						freeb(md_pbuf_nxt);
19945 						TCP_STAT(tcp_mdt_allocfail);
19946 						/* out_of_mem */
19947 						goto legacy_send;
19948 					}
19949 					zcopy = B_TRUE;
19950 				}
19951 
19952 				/*
19953 				 * See comments above on the first call to
19954 				 * mmd_addpldbuf for explanation on the panic.
19955 				 */
19956 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19957 				if (pbuf_idx_nxt < 0) {
19958 					panic("tcp_multisend: "
19959 					    "next 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_nxt, pbuf_idx_nxt);
19964 				}
19965 
19966 				ASSERT(max_pld > 0);
19967 				--max_pld;
19968 			} else if (spill > 0) {
19969 				/*
19970 				 * If there's a spillover, but the following
19971 				 * xmit_tail couldn't give us enough octets
19972 				 * to reach "len", then stop the current
19973 				 * Multidata creation and let the legacy
19974 				 * tcp_send() path take over.  We don't want
19975 				 * to send the tiny segment as part of this
19976 				 * Multidata for performance reasons; instead,
19977 				 * we let the legacy path deal with grouping
19978 				 * it with the subsequent small mblks.
19979 				 */
19980 				if (*usable >= len &&
19981 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19982 					max_pld = 0;
19983 					break;	/* done */
19984 				}
19985 
19986 				/*
19987 				 * We can't spillover, and we are near
19988 				 * the end of the current payload buffer,
19989 				 * so send what's left.
19990 				 */
19991 				ASSERT(*tail_unsent > 0);
19992 				len = *tail_unsent;
19993 			}
19994 
19995 			/* tail_unsent is negated if there is a spillover */
19996 			*tail_unsent -= len;
19997 			*usable -= len;
19998 			ASSERT(*usable >= 0);
19999 
20000 			if (*usable < mss)
20001 				seg_len = *usable;
20002 			/*
20003 			 * Sender SWS avoidance; see comments in tcp_send();
20004 			 * everything else is the same, except that we only
20005 			 * do this here if there is no more data to be sent
20006 			 * following the current xmit_tail.  We don't check
20007 			 * for 1-byte urgent data because we shouldn't get
20008 			 * here if TCP_URG_VALID is set.
20009 			 */
20010 			if (*usable > 0 && *usable < mss &&
20011 			    ((md_pbuf_nxt == NULL &&
20012 			    (*xmit_tail)->b_cont == NULL) ||
20013 			    (md_pbuf_nxt != NULL &&
20014 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20015 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20016 			    (tcp->tcp_unsent -
20017 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20018 			    !tcp->tcp_zero_win_probe) {
20019 				if ((*snxt + len) == tcp->tcp_snxt &&
20020 				    (*snxt + len) == tcp->tcp_suna) {
20021 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20022 				}
20023 				done = B_TRUE;
20024 			}
20025 
20026 			/*
20027 			 * Prime pump for IP's checksumming on our behalf;
20028 			 * include the adjustment for a source route if any.
20029 			 * Do this only for software/partial hardware checksum
20030 			 * offload, as this field gets zeroed out later for
20031 			 * the full hardware checksum offload case.
20032 			 */
20033 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20034 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20035 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20036 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20037 			}
20038 
20039 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20040 			*snxt += len;
20041 
20042 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20043 			/*
20044 			 * We set the PUSH bit only if TCP has no more buffered
20045 			 * data to be transmitted (or if sender SWS avoidance
20046 			 * takes place), as opposed to setting it for every
20047 			 * last packet in the burst.
20048 			 */
20049 			if (done ||
20050 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20051 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20052 
20053 			/*
20054 			 * Set FIN bit if this is our last segment; snxt
20055 			 * already includes its length, and it will not
20056 			 * be adjusted after this point.
20057 			 */
20058 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20059 			    *snxt == tcp->tcp_fss) {
20060 				if (!tcp->tcp_fin_acked) {
20061 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20062 					BUMP_MIB(&tcp_mib, tcpOutControl);
20063 				}
20064 				if (!tcp->tcp_fin_sent) {
20065 					tcp->tcp_fin_sent = B_TRUE;
20066 					/*
20067 					 * tcp state must be ESTABLISHED
20068 					 * in order for us to get here in
20069 					 * the first place.
20070 					 */
20071 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20072 
20073 					/*
20074 					 * Upon returning from this routine,
20075 					 * tcp_wput_data() will set tcp_snxt
20076 					 * to be equal to snxt + tcp_fin_sent.
20077 					 * This is essentially the same as
20078 					 * setting it to tcp_fss + 1.
20079 					 */
20080 				}
20081 			}
20082 
20083 			tcp->tcp_last_sent_len = (ushort_t)len;
20084 
20085 			len += tcp_hdr_len;
20086 			if (tcp->tcp_ipversion == IPV4_VERSION)
20087 				tcp->tcp_ipha->ipha_length = htons(len);
20088 			else
20089 				tcp->tcp_ip6h->ip6_plen = htons(len -
20090 				    ((char *)&tcp->tcp_ip6h[1] -
20091 				    tcp->tcp_iphc));
20092 
20093 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20094 
20095 			/* setup header fragment */
20096 			PDESC_HDR_ADD(pkt_info,
20097 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20098 			    tcp->tcp_mdt_hdr_head,		/* head room */
20099 			    tcp_hdr_len,			/* len */
20100 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20101 
20102 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20103 			    hdr_frag_sz);
20104 			ASSERT(MBLKIN(md_hbuf,
20105 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20106 			    PDESC_HDRSIZE(pkt_info)));
20107 
20108 			/* setup first payload fragment */
20109 			PDESC_PLD_INIT(pkt_info);
20110 			PDESC_PLD_SPAN_ADD(pkt_info,
20111 			    pbuf_idx,				/* index */
20112 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20113 			    tcp->tcp_last_sent_len);		/* len */
20114 
20115 			/* create a split-packet in case of a spillover */
20116 			if (md_pbuf_nxt != NULL) {
20117 				ASSERT(spill > 0);
20118 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20119 				ASSERT(!add_buffer);
20120 
20121 				md_pbuf = md_pbuf_nxt;
20122 				md_pbuf_nxt = NULL;
20123 				pbuf_idx = pbuf_idx_nxt;
20124 				pbuf_idx_nxt = -1;
20125 				cur_pld_off = spill;
20126 
20127 				/* trim out first payload fragment */
20128 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20129 
20130 				/* setup second payload fragment */
20131 				PDESC_PLD_SPAN_ADD(pkt_info,
20132 				    pbuf_idx,			/* index */
20133 				    md_pbuf->b_rptr,		/* start */
20134 				    spill);			/* len */
20135 
20136 				if ((*xmit_tail)->b_next == NULL) {
20137 					/*
20138 					 * Store the lbolt used for RTT
20139 					 * estimation. We can only record one
20140 					 * timestamp per mblk so we do it when
20141 					 * we reach the end of the payload
20142 					 * buffer.  Also we only take a new
20143 					 * timestamp sample when the previous
20144 					 * timed data from the same mblk has
20145 					 * been ack'ed.
20146 					 */
20147 					(*xmit_tail)->b_prev = local_time;
20148 					(*xmit_tail)->b_next =
20149 					    (mblk_t *)(uintptr_t)first_snxt;
20150 				}
20151 
20152 				first_snxt = *snxt - spill;
20153 
20154 				/*
20155 				 * Advance xmit_tail; usable could be 0 by
20156 				 * the time we got here, but we made sure
20157 				 * above that we would only spillover to
20158 				 * the next data block if usable includes
20159 				 * the spilled-over amount prior to the
20160 				 * subtraction.  Therefore, we are sure
20161 				 * that xmit_tail->b_cont can't be NULL.
20162 				 */
20163 				ASSERT((*xmit_tail)->b_cont != NULL);
20164 				*xmit_tail = (*xmit_tail)->b_cont;
20165 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20166 				    (uintptr_t)INT_MAX);
20167 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20168 			} else {
20169 				cur_pld_off += tcp->tcp_last_sent_len;
20170 			}
20171 
20172 			/*
20173 			 * Fill in the header using the template header, and
20174 			 * add options such as time-stamp, ECN and/or SACK,
20175 			 * as needed.
20176 			 */
20177 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20178 			    (clock_t)local_time, num_sack_blk);
20179 
20180 			/* take care of some IP header businesses */
20181 			if (af == AF_INET) {
20182 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20183 
20184 				ASSERT(OK_32PTR((uchar_t *)ipha));
20185 				ASSERT(PDESC_HDRL(pkt_info) >=
20186 				    IP_SIMPLE_HDR_LENGTH);
20187 				ASSERT(ipha->ipha_version_and_hdr_length ==
20188 				    IP_SIMPLE_HDR_VERSION);
20189 
20190 				/*
20191 				 * Assign ident value for current packet; see
20192 				 * related comments in ip_wput_ire() about the
20193 				 * contract private interface with clustering
20194 				 * group.
20195 				 */
20196 				clusterwide = B_FALSE;
20197 				if (cl_inet_ipident != NULL) {
20198 					ASSERT(cl_inet_isclusterwide != NULL);
20199 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20200 					    AF_INET,
20201 					    (uint8_t *)(uintptr_t)src)) {
20202 						ipha->ipha_ident =
20203 						    (*cl_inet_ipident)
20204 						    (IPPROTO_IP, AF_INET,
20205 						    (uint8_t *)(uintptr_t)src,
20206 						    (uint8_t *)(uintptr_t)dst);
20207 						clusterwide = B_TRUE;
20208 					}
20209 				}
20210 
20211 				if (!clusterwide) {
20212 					ipha->ipha_ident = (uint16_t)
20213 					    atomic_add_32_nv(
20214 						&ire->ire_ident, 1);
20215 				}
20216 #ifndef _BIG_ENDIAN
20217 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20218 				    (ipha->ipha_ident >> 8);
20219 #endif
20220 			} else {
20221 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20222 
20223 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20224 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20225 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20226 				ASSERT(PDESC_HDRL(pkt_info) >=
20227 				    (IPV6_HDR_LEN + TCP_CSUM_OFFSET +
20228 				    TCP_CSUM_SIZE));
20229 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20230 
20231 				if (tcp->tcp_ip_forward_progress) {
20232 					rconfirm = B_TRUE;
20233 					tcp->tcp_ip_forward_progress = B_FALSE;
20234 				}
20235 			}
20236 
20237 			/* at least one payload span, and at most two */
20238 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20239 
20240 			/* add the packet descriptor to Multidata */
20241 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20242 			    KM_NOSLEEP)) == NULL) {
20243 				/*
20244 				 * Any failure other than ENOMEM indicates
20245 				 * that we have passed in invalid pkt_info
20246 				 * or parameters to mmd_addpdesc, which must
20247 				 * not happen.
20248 				 *
20249 				 * EINVAL is a result of failure on boundary
20250 				 * checks against the pkt_info contents.  It
20251 				 * should not happen, and we panic because
20252 				 * either there's horrible heap corruption,
20253 				 * and/or programming mistake.
20254 				 */
20255 				if (err != ENOMEM) {
20256 					cmn_err(CE_PANIC, "tcp_multisend: "
20257 					    "pdesc logic error detected for "
20258 					    "tcp %p mmd %p pinfo %p (%d)\n",
20259 					    (void *)tcp, (void *)mmd,
20260 					    (void *)pkt_info, err);
20261 				}
20262 				TCP_STAT(tcp_mdt_addpdescfail);
20263 				goto legacy_send; /* out_of_mem */
20264 			}
20265 			ASSERT(pkt != NULL);
20266 
20267 			/* calculate IP header and TCP checksums */
20268 			if (af == AF_INET) {
20269 				/* calculate pseudo-header checksum */
20270 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20271 				    (src >> 16) + (src & 0xFFFF);
20272 
20273 				/* offset for TCP header checksum */
20274 				up = IPH_TCPH_CHECKSUMP(ipha,
20275 				    IP_SIMPLE_HDR_LENGTH);
20276 
20277 				if (hwcksum_flags & HCK_FULLCKSUM) {
20278 					/*
20279 					 * Hardware calculates pseudo-header,
20280 					 * header and payload checksums, so
20281 					 * zero out this field.
20282 					 */
20283 					*up = 0;
20284 				} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20285 					uint32_t sum;
20286 
20287 					/* pseudo-header checksumming */
20288 					sum = *up + cksum + IP_TCP_CSUM_COMP;
20289 					sum = (sum & 0xFFFF) + (sum >> 16);
20290 					*up = (sum & 0xFFFF) + (sum >> 16);
20291 				} else {
20292 					/* software checksumming */
20293 					TCP_STAT(tcp_out_sw_cksum);
20294 					*up = IP_MD_CSUM(pkt,
20295 					    IP_SIMPLE_HDR_LENGTH,
20296 					    cksum + IP_TCP_CSUM_COMP);
20297 				}
20298 
20299 				ipha->ipha_fragment_offset_and_flags |=
20300 				    (uint32_t)htons(ire->ire_frag_flag);
20301 
20302 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20303 					ipha->ipha_hdr_checksum = 0;
20304 				} else {
20305 					IP_HDR_CKSUM(ipha, cksum,
20306 					    ((uint32_t *)ipha)[0],
20307 					    ((uint16_t *)ipha)[4]);
20308 				}
20309 			} else {
20310 				up = (uint16_t *)(((uchar_t *)ip6h) +
20311 				    IPV6_HDR_LEN + TCP_CSUM_OFFSET);
20312 
20313 				/*
20314 				 * Software checksumming (hardware checksum
20315 				 * offload for IPv6 will hopefully be
20316 				 * implemented one day).
20317 				 */
20318 				TCP_STAT(tcp_out_sw_cksum);
20319 				*up = IP_MD_CSUM(pkt,
20320 				    IPV6_HDR_LEN - 2 * sizeof (in6_addr_t),
20321 				    htons(IPPROTO_TCP));
20322 			}
20323 
20324 			/* advance header offset */
20325 			cur_hdr_off += hdr_frag_sz;
20326 
20327 			obbytes += tcp->tcp_last_sent_len;
20328 			++obsegs;
20329 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20330 		    *tail_unsent > 0);
20331 
20332 		if ((*xmit_tail)->b_next == NULL) {
20333 			/*
20334 			 * Store the lbolt used for RTT estimation. We can only
20335 			 * record one timestamp per mblk so we do it when we
20336 			 * reach the end of the payload buffer. Also we only
20337 			 * take a new timestamp sample when the previous timed
20338 			 * data from the same mblk has been ack'ed.
20339 			 */
20340 			(*xmit_tail)->b_prev = local_time;
20341 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20342 		}
20343 
20344 		ASSERT(*tail_unsent >= 0);
20345 		if (*tail_unsent > 0) {
20346 			/*
20347 			 * We got here because we broke out of the above
20348 			 * loop due to of one of the following cases:
20349 			 *
20350 			 *   1. len < adjusted MSS (i.e. small),
20351 			 *   2. Sender SWS avoidance,
20352 			 *   3. max_pld is zero.
20353 			 *
20354 			 * We are done for this Multidata, so trim our
20355 			 * last payload buffer (if any) accordingly.
20356 			 */
20357 			if (md_pbuf != NULL)
20358 				md_pbuf->b_wptr -= *tail_unsent;
20359 		} else if (*usable > 0) {
20360 			*xmit_tail = (*xmit_tail)->b_cont;
20361 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20362 			    (uintptr_t)INT_MAX);
20363 			*tail_unsent = (int)MBLKL(*xmit_tail);
20364 			add_buffer = B_TRUE;
20365 		}
20366 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20367 	    (tcp_mdt_chain || max_pld > 0));
20368 
20369 	/* send everything down */
20370 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20371 	    &rconfirm);
20372 
20373 #undef PREP_NEW_MULTIDATA
20374 #undef PREP_NEW_PBUF
20375 #undef IPVER
20376 #undef TCP_CSUM_OFFSET
20377 #undef TCP_CSUM_SIZE
20378 
20379 	IRE_REFRELE(ire);
20380 	return (0);
20381 }
20382 
20383 /*
20384  * A wrapper function for sending one or more Multidata messages down to
20385  * the module below ip; this routine does not release the reference of the
20386  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20387  */
20388 static void
20389 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20390     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20391 {
20392 	uint64_t delta;
20393 	nce_t *nce;
20394 
20395 	ASSERT(ire != NULL && ill != NULL);
20396 	ASSERT(ire->ire_stq != NULL);
20397 	ASSERT(md_mp_head != NULL);
20398 	ASSERT(rconfirm != NULL);
20399 
20400 	/* adjust MIBs and IRE timestamp */
20401 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20402 	tcp->tcp_obsegs += obsegs;
20403 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20404 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20405 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20406 
20407 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20408 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20409 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20410 	} else {
20411 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20412 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20413 	}
20414 
20415 	ire->ire_ob_pkt_count += obsegs;
20416 	if (ire->ire_ipif != NULL)
20417 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20418 	ire->ire_last_used_time = lbolt;
20419 
20420 	/* send it down */
20421 	putnext(ire->ire_stq, md_mp_head);
20422 
20423 	/* we're done for TCP/IPv4 */
20424 	if (tcp->tcp_ipversion == IPV4_VERSION)
20425 		return;
20426 
20427 	nce = ire->ire_nce;
20428 
20429 	ASSERT(nce != NULL);
20430 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20431 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20432 
20433 	/* reachability confirmation? */
20434 	if (*rconfirm) {
20435 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20436 		if (nce->nce_state != ND_REACHABLE) {
20437 			mutex_enter(&nce->nce_lock);
20438 			nce->nce_state = ND_REACHABLE;
20439 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20440 			mutex_exit(&nce->nce_lock);
20441 			(void) untimeout(nce->nce_timeout_id);
20442 			if (ip_debug > 2) {
20443 				/* ip1dbg */
20444 				pr_addr_dbg("tcp_multisend_data: state "
20445 				    "for %s changed to REACHABLE\n",
20446 				    AF_INET6, &ire->ire_addr_v6);
20447 			}
20448 		}
20449 		/* reset transport reachability confirmation */
20450 		*rconfirm = B_FALSE;
20451 	}
20452 
20453 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20454 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20455 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20456 
20457 	if (delta > (uint64_t)ill->ill_reachable_time) {
20458 		mutex_enter(&nce->nce_lock);
20459 		switch (nce->nce_state) {
20460 		case ND_REACHABLE:
20461 		case ND_STALE:
20462 			/*
20463 			 * ND_REACHABLE is identical to ND_STALE in this
20464 			 * specific case. If reachable time has expired for
20465 			 * this neighbor (delta is greater than reachable
20466 			 * time), conceptually, the neighbor cache is no
20467 			 * longer in REACHABLE state, but already in STALE
20468 			 * state.  So the correct transition here is to
20469 			 * ND_DELAY.
20470 			 */
20471 			nce->nce_state = ND_DELAY;
20472 			mutex_exit(&nce->nce_lock);
20473 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20474 			if (ip_debug > 3) {
20475 				/* ip2dbg */
20476 				pr_addr_dbg("tcp_multisend_data: state "
20477 				    "for %s changed to DELAY\n",
20478 				    AF_INET6, &ire->ire_addr_v6);
20479 			}
20480 			break;
20481 		case ND_DELAY:
20482 		case ND_PROBE:
20483 			mutex_exit(&nce->nce_lock);
20484 			/* Timers have already started */
20485 			break;
20486 		case ND_UNREACHABLE:
20487 			/*
20488 			 * ndp timer has detected that this nce is
20489 			 * unreachable and initiated deleting this nce
20490 			 * and all its associated IREs. This is a race
20491 			 * where we found the ire before it was deleted
20492 			 * and have just sent out a packet using this
20493 			 * unreachable nce.
20494 			 */
20495 			mutex_exit(&nce->nce_lock);
20496 			break;
20497 		default:
20498 			ASSERT(0);
20499 		}
20500 	}
20501 }
20502 
20503 /*
20504  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20505  * scheme, and returns one of the following:
20506  *
20507  * -1 = failed allocation.
20508  *  0 = success; burst count reached, or usable send window is too small,
20509  *      and that we'd rather wait until later before sending again.
20510  *  1 = success; we are called from tcp_multisend(), and both usable send
20511  *      window and tail_unsent are greater than the MDT threshold, and thus
20512  *      Multidata Transmit should be used instead.
20513  */
20514 static int
20515 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20516     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20517     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20518     const int mdt_thres)
20519 {
20520 	int num_burst_seg = tcp->tcp_snd_burst;
20521 
20522 	for (;;) {
20523 		struct datab	*db;
20524 		tcph_t		*tcph;
20525 		uint32_t	sum;
20526 		mblk_t		*mp, *mp1;
20527 		uchar_t		*rptr;
20528 		int		len;
20529 
20530 		/*
20531 		 * If we're called by tcp_multisend(), and the amount of
20532 		 * sendable data as well as the size of current xmit_tail
20533 		 * is beyond the MDT threshold, return to the caller and
20534 		 * let the large data transmit be done using MDT.
20535 		 */
20536 		if (*usable > 0 && *usable > mdt_thres &&
20537 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20538 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20539 			ASSERT(tcp->tcp_mdt);
20540 			return (1);	/* success; do large send */
20541 		}
20542 
20543 		if (num_burst_seg-- == 0)
20544 			break;		/* success; burst count reached */
20545 
20546 		len = mss;
20547 		if (len > *usable) {
20548 			len = *usable;
20549 			if (len <= 0) {
20550 				/* Terminate the loop */
20551 				break;	/* success; too small */
20552 			}
20553 			/*
20554 			 * Sender silly-window avoidance.
20555 			 * Ignore this if we are going to send a
20556 			 * zero window probe out.
20557 			 *
20558 			 * TODO: force data into microscopic window?
20559 			 *	==> (!pushed || (unsent > usable))
20560 			 */
20561 			if (len < (tcp->tcp_max_swnd >> 1) &&
20562 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20563 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20564 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20565 				/*
20566 				 * If the retransmit timer is not running
20567 				 * we start it so that we will retransmit
20568 				 * in the case when the the receiver has
20569 				 * decremented the window.
20570 				 */
20571 				if (*snxt == tcp->tcp_snxt &&
20572 				    *snxt == tcp->tcp_suna) {
20573 					/*
20574 					 * We are not supposed to send
20575 					 * anything.  So let's wait a little
20576 					 * bit longer before breaking SWS
20577 					 * avoidance.
20578 					 *
20579 					 * What should the value be?
20580 					 * Suggestion: MAX(init rexmit time,
20581 					 * tcp->tcp_rto)
20582 					 */
20583 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20584 				}
20585 				break;	/* success; too small */
20586 			}
20587 		}
20588 
20589 		tcph = tcp->tcp_tcph;
20590 
20591 		*usable -= len; /* Approximate - can be adjusted later */
20592 		if (*usable > 0)
20593 			tcph->th_flags[0] = TH_ACK;
20594 		else
20595 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20596 
20597 		/*
20598 		 * Prime pump for IP's checksumming on our behalf
20599 		 * Include the adjustment for a source route if any.
20600 		 */
20601 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20602 		sum = (sum >> 16) + (sum & 0xFFFF);
20603 		U16_TO_ABE16(sum, tcph->th_sum);
20604 
20605 		U32_TO_ABE32(*snxt, tcph->th_seq);
20606 
20607 		/*
20608 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20609 		 * set.  For the case when TCP_FSS_VALID is the only valid
20610 		 * bit (normal active close), branch off only when we think
20611 		 * that the FIN flag needs to be set.  Note for this case,
20612 		 * that (snxt + len) may not reflect the actual seg_len,
20613 		 * as len may be further reduced in tcp_xmit_mp().  If len
20614 		 * gets modified, we will end up here again.
20615 		 */
20616 		if (tcp->tcp_valid_bits != 0 &&
20617 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20618 		    ((*snxt + len) == tcp->tcp_fss))) {
20619 			uchar_t		*prev_rptr;
20620 			uint32_t	prev_snxt = tcp->tcp_snxt;
20621 
20622 			if (*tail_unsent == 0) {
20623 				ASSERT((*xmit_tail)->b_cont != NULL);
20624 				*xmit_tail = (*xmit_tail)->b_cont;
20625 				prev_rptr = (*xmit_tail)->b_rptr;
20626 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20627 				    (*xmit_tail)->b_rptr);
20628 			} else {
20629 				prev_rptr = (*xmit_tail)->b_rptr;
20630 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20631 				    *tail_unsent;
20632 			}
20633 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20634 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20635 			/* Restore tcp_snxt so we get amount sent right. */
20636 			tcp->tcp_snxt = prev_snxt;
20637 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20638 				/*
20639 				 * If the previous timestamp is still in use,
20640 				 * don't stomp on it.
20641 				 */
20642 				if ((*xmit_tail)->b_next == NULL) {
20643 					(*xmit_tail)->b_prev = local_time;
20644 					(*xmit_tail)->b_next =
20645 					    (mblk_t *)(uintptr_t)(*snxt);
20646 				}
20647 			} else
20648 				(*xmit_tail)->b_rptr = prev_rptr;
20649 
20650 			if (mp == NULL)
20651 				return (-1);
20652 			mp1 = mp->b_cont;
20653 
20654 			tcp->tcp_last_sent_len = (ushort_t)len;
20655 			while (mp1->b_cont) {
20656 				*xmit_tail = (*xmit_tail)->b_cont;
20657 				(*xmit_tail)->b_prev = local_time;
20658 				(*xmit_tail)->b_next =
20659 				    (mblk_t *)(uintptr_t)(*snxt);
20660 				mp1 = mp1->b_cont;
20661 			}
20662 			*snxt += len;
20663 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20664 			BUMP_LOCAL(tcp->tcp_obsegs);
20665 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20666 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20667 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20668 			tcp_send_data(tcp, q, mp);
20669 			continue;
20670 		}
20671 
20672 		*snxt += len;	/* Adjust later if we don't send all of len */
20673 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20674 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20675 
20676 		if (*tail_unsent) {
20677 			/* Are the bytes above us in flight? */
20678 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20679 			if (rptr != (*xmit_tail)->b_rptr) {
20680 				*tail_unsent -= len;
20681 				tcp->tcp_last_sent_len = (ushort_t)len;
20682 				len += tcp_hdr_len;
20683 				if (tcp->tcp_ipversion == IPV4_VERSION)
20684 					tcp->tcp_ipha->ipha_length = htons(len);
20685 				else
20686 					tcp->tcp_ip6h->ip6_plen =
20687 					    htons(len -
20688 					    ((char *)&tcp->tcp_ip6h[1] -
20689 					    tcp->tcp_iphc));
20690 				mp = dupb(*xmit_tail);
20691 				if (!mp)
20692 					return (-1);	/* out_of_mem */
20693 				mp->b_rptr = rptr;
20694 				/*
20695 				 * If the old timestamp is no longer in use,
20696 				 * sample a new timestamp now.
20697 				 */
20698 				if ((*xmit_tail)->b_next == NULL) {
20699 					(*xmit_tail)->b_prev = local_time;
20700 					(*xmit_tail)->b_next =
20701 					    (mblk_t *)(uintptr_t)(*snxt-len);
20702 				}
20703 				goto must_alloc;
20704 			}
20705 		} else {
20706 			*xmit_tail = (*xmit_tail)->b_cont;
20707 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20708 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20709 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20710 			    (*xmit_tail)->b_rptr);
20711 		}
20712 
20713 		(*xmit_tail)->b_prev = local_time;
20714 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20715 
20716 		*tail_unsent -= len;
20717 		tcp->tcp_last_sent_len = (ushort_t)len;
20718 
20719 		len += tcp_hdr_len;
20720 		if (tcp->tcp_ipversion == IPV4_VERSION)
20721 			tcp->tcp_ipha->ipha_length = htons(len);
20722 		else
20723 			tcp->tcp_ip6h->ip6_plen = htons(len -
20724 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20725 
20726 		mp = dupb(*xmit_tail);
20727 		if (!mp)
20728 			return (-1);	/* out_of_mem */
20729 
20730 		len = tcp_hdr_len;
20731 		/*
20732 		 * There are four reasons to allocate a new hdr mblk:
20733 		 *  1) The bytes above us are in use by another packet
20734 		 *  2) We don't have good alignment
20735 		 *  3) The mblk is being shared
20736 		 *  4) We don't have enough room for a header
20737 		 */
20738 		rptr = mp->b_rptr - len;
20739 		if (!OK_32PTR(rptr) ||
20740 		    ((db = mp->b_datap), db->db_ref != 2) ||
20741 		    rptr < db->db_base) {
20742 			/* NOTE: we assume allocb returns an OK_32PTR */
20743 
20744 		must_alloc:;
20745 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20746 			    tcp_wroff_xtra, BPRI_MED);
20747 			if (!mp1) {
20748 				freemsg(mp);
20749 				return (-1);	/* out_of_mem */
20750 			}
20751 			mp1->b_cont = mp;
20752 			mp = mp1;
20753 			/* Leave room for Link Level header */
20754 			len = tcp_hdr_len;
20755 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20756 			mp->b_wptr = &rptr[len];
20757 		}
20758 
20759 		/*
20760 		 * Fill in the header using the template header, and add
20761 		 * options such as time-stamp, ECN and/or SACK, as needed.
20762 		 */
20763 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20764 
20765 		mp->b_rptr = rptr;
20766 
20767 		if (*tail_unsent) {
20768 			int spill = *tail_unsent;
20769 
20770 			mp1 = mp->b_cont;
20771 			if (!mp1)
20772 				mp1 = mp;
20773 
20774 			/*
20775 			 * If we're a little short, tack on more mblks until
20776 			 * there is no more spillover.
20777 			 */
20778 			while (spill < 0) {
20779 				mblk_t *nmp;
20780 				int nmpsz;
20781 
20782 				nmp = (*xmit_tail)->b_cont;
20783 				nmpsz = MBLKL(nmp);
20784 
20785 				/*
20786 				 * Excess data in mblk; can we split it?
20787 				 * If MDT is enabled for the connection,
20788 				 * keep on splitting as this is a transient
20789 				 * send path.
20790 				 */
20791 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20792 					/*
20793 					 * Don't split if stream head was
20794 					 * told to break up larger writes
20795 					 * into smaller ones.
20796 					 */
20797 					if (tcp->tcp_maxpsz > 0)
20798 						break;
20799 
20800 					/*
20801 					 * Next mblk is less than SMSS/2
20802 					 * rounded up to nearest 64-byte;
20803 					 * let it get sent as part of the
20804 					 * next segment.
20805 					 */
20806 					if (tcp->tcp_localnet &&
20807 					    !tcp->tcp_cork &&
20808 					    (nmpsz < roundup((mss >> 1), 64)))
20809 						break;
20810 				}
20811 
20812 				*xmit_tail = nmp;
20813 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20814 				/* Stash for rtt use later */
20815 				(*xmit_tail)->b_prev = local_time;
20816 				(*xmit_tail)->b_next =
20817 				    (mblk_t *)(uintptr_t)(*snxt - len);
20818 				mp1->b_cont = dupb(*xmit_tail);
20819 				mp1 = mp1->b_cont;
20820 
20821 				spill += nmpsz;
20822 				if (mp1 == NULL) {
20823 					*tail_unsent = spill;
20824 					freemsg(mp);
20825 					return (-1);	/* out_of_mem */
20826 				}
20827 			}
20828 
20829 			/* Trim back any surplus on the last mblk */
20830 			if (spill >= 0) {
20831 				mp1->b_wptr -= spill;
20832 				*tail_unsent = spill;
20833 			} else {
20834 				/*
20835 				 * We did not send everything we could in
20836 				 * order to remain within the b_cont limit.
20837 				 */
20838 				*usable -= spill;
20839 				*snxt += spill;
20840 				tcp->tcp_last_sent_len += spill;
20841 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20842 				/*
20843 				 * Adjust the checksum
20844 				 */
20845 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20846 				sum += spill;
20847 				sum = (sum >> 16) + (sum & 0xFFFF);
20848 				U16_TO_ABE16(sum, tcph->th_sum);
20849 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20850 					sum = ntohs(
20851 					    ((ipha_t *)rptr)->ipha_length) +
20852 					    spill;
20853 					((ipha_t *)rptr)->ipha_length =
20854 					    htons(sum);
20855 				} else {
20856 					sum = ntohs(
20857 					    ((ip6_t *)rptr)->ip6_plen) +
20858 					    spill;
20859 					((ip6_t *)rptr)->ip6_plen =
20860 					    htons(sum);
20861 				}
20862 				*tail_unsent = 0;
20863 			}
20864 		}
20865 		if (tcp->tcp_ip_forward_progress) {
20866 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20867 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20868 			tcp->tcp_ip_forward_progress = B_FALSE;
20869 		}
20870 
20871 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20872 		tcp_send_data(tcp, q, mp);
20873 		BUMP_LOCAL(tcp->tcp_obsegs);
20874 	}
20875 
20876 	return (0);
20877 }
20878 
20879 /* Unlink and return any mblk that looks like it contains a MDT info */
20880 static mblk_t *
20881 tcp_mdt_info_mp(mblk_t *mp)
20882 {
20883 	mblk_t	*prev_mp;
20884 
20885 	for (;;) {
20886 		prev_mp = mp;
20887 		/* no more to process? */
20888 		if ((mp = mp->b_cont) == NULL)
20889 			break;
20890 
20891 		switch (DB_TYPE(mp)) {
20892 		case M_CTL:
20893 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20894 				continue;
20895 			ASSERT(prev_mp != NULL);
20896 			prev_mp->b_cont = mp->b_cont;
20897 			mp->b_cont = NULL;
20898 			return (mp);
20899 		default:
20900 			break;
20901 		}
20902 	}
20903 	return (mp);
20904 }
20905 
20906 /* MDT info update routine, called when IP notifies us about MDT */
20907 static void
20908 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20909 {
20910 	boolean_t prev_state;
20911 
20912 	/*
20913 	 * IP is telling us to abort MDT on this connection?  We know
20914 	 * this because the capability is only turned off when IP
20915 	 * encounters some pathological cases, e.g. link-layer change
20916 	 * where the new driver doesn't support MDT, or in situation
20917 	 * where MDT usage on the link-layer has been switched off.
20918 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20919 	 * if the link-layer doesn't support MDT, and if it does, it
20920 	 * will indicate that the feature is to be turned on.
20921 	 */
20922 	prev_state = tcp->tcp_mdt;
20923 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20924 	if (!tcp->tcp_mdt && !first) {
20925 		TCP_STAT(tcp_mdt_conn_halted3);
20926 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20927 		    (void *)tcp->tcp_connp));
20928 	}
20929 
20930 	/*
20931 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20932 	 * so disable MDT otherwise.  The checks are done here
20933 	 * and in tcp_wput_data().
20934 	 */
20935 	if (tcp->tcp_mdt &&
20936 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20937 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20938 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20939 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20940 		tcp->tcp_mdt = B_FALSE;
20941 
20942 	if (tcp->tcp_mdt) {
20943 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20944 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20945 			    "version (%d), expected version is %d",
20946 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20947 			tcp->tcp_mdt = B_FALSE;
20948 			return;
20949 		}
20950 
20951 		/*
20952 		 * We need the driver to be able to handle at least three
20953 		 * spans per packet in order for tcp MDT to be utilized.
20954 		 * The first is for the header portion, while the rest are
20955 		 * needed to handle a packet that straddles across two
20956 		 * virtually non-contiguous buffers; a typical tcp packet
20957 		 * therefore consists of only two spans.  Note that we take
20958 		 * a zero as "don't care".
20959 		 */
20960 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20961 		    mdt_capab->ill_mdt_span_limit < 3) {
20962 			tcp->tcp_mdt = B_FALSE;
20963 			return;
20964 		}
20965 
20966 		/* a zero means driver wants default value */
20967 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20968 		    tcp_mdt_max_pbufs);
20969 		if (tcp->tcp_mdt_max_pld == 0)
20970 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20971 
20972 		/* ensure 32-bit alignment */
20973 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20974 		    mdt_capab->ill_mdt_hdr_head), 4);
20975 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20976 		    mdt_capab->ill_mdt_hdr_tail), 4);
20977 
20978 		if (!first && !prev_state) {
20979 			TCP_STAT(tcp_mdt_conn_resumed2);
20980 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20981 			    (void *)tcp->tcp_connp));
20982 		}
20983 	}
20984 }
20985 
20986 static void
20987 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20988 {
20989 	conn_t *connp = tcp->tcp_connp;
20990 
20991 	ASSERT(ire != NULL);
20992 
20993 	/*
20994 	 * We may be in the fastpath here, and although we essentially do
20995 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20996 	 * we try to keep things as brief as possible.  After all, these
20997 	 * are only best-effort checks, and we do more thorough ones prior
20998 	 * to calling tcp_multisend().
20999 	 */
21000 	if (ip_multidata_outbound && check_mdt &&
21001 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21002 	    ill != NULL && (ill->ill_capabilities & ILL_CAPAB_MDT) &&
21003 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21004 	    !(ire->ire_flags & RTF_MULTIRT) &&
21005 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
21006 	    CONN_IS_MD_FASTPATH(connp)) {
21007 		/* Remember the result */
21008 		connp->conn_mdt_ok = B_TRUE;
21009 
21010 		ASSERT(ill->ill_mdt_capab != NULL);
21011 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21012 			/*
21013 			 * If MDT has been previously turned off in the past,
21014 			 * and we currently can do MDT (due to IPQoS policy
21015 			 * removal, etc.) then enable it for this interface.
21016 			 */
21017 			ill->ill_mdt_capab->ill_mdt_on = 1;
21018 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
21019 			    "interface %s\n", (void *)connp, ill->ill_name));
21020 		}
21021 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21022 	}
21023 
21024 	/*
21025 	 * The goal is to reduce the number of generated tcp segments by
21026 	 * setting the maxpsz multiplier to 0; this will have an affect on
21027 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21028 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21029 	 * of outbound segments and incoming ACKs, thus allowing for better
21030 	 * network and system performance.  In contrast the legacy behavior
21031 	 * may result in sending less than SMSS size, because the last mblk
21032 	 * for some packets may have more data than needed to make up SMSS,
21033 	 * and the legacy code refused to "split" it.
21034 	 *
21035 	 * We apply the new behavior on following situations:
21036 	 *
21037 	 *   1) Loopback connections,
21038 	 *   2) Connections in which the remote peer is not on local subnet,
21039 	 *   3) Local subnet connections over the bge interface (see below).
21040 	 *
21041 	 * Ideally, we would like this behavior to apply for interfaces other
21042 	 * than bge.  However, doing so would negatively impact drivers which
21043 	 * perform dynamic mapping and unmapping of DMA resources, which are
21044 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21045 	 * packet will be generated by tcp).  The bge driver does not suffer
21046 	 * from this, as it copies the mblks into pre-mapped buffers, and
21047 	 * therefore does not require more I/O resources than before.
21048 	 *
21049 	 * Otherwise, this behavior is present on all network interfaces when
21050 	 * the destination endpoint is non-local, since reducing the number
21051 	 * of packets in general is good for the network.
21052 	 *
21053 	 * TODO We need to remove this hard-coded conditional for bge once
21054 	 *	a better "self-tuning" mechanism, or a way to comprehend
21055 	 *	the driver transmit strategy is devised.  Until the solution
21056 	 *	is found and well understood, we live with this hack.
21057 	 */
21058 	if (!tcp_static_maxpsz &&
21059 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21060 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21061 		/* override the default value */
21062 		tcp->tcp_maxpsz = 0;
21063 
21064 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21065 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21066 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21067 	}
21068 
21069 	/* set the stream head parameters accordingly */
21070 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21071 }
21072 
21073 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21074 static void
21075 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21076 {
21077 	uchar_t	fval = *mp->b_rptr;
21078 	mblk_t	*tail;
21079 	queue_t	*q = tcp->tcp_wq;
21080 
21081 	/* TODO: How should flush interact with urgent data? */
21082 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21083 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21084 		/*
21085 		 * Flush only data that has not yet been put on the wire.  If
21086 		 * we flush data that we have already transmitted, life, as we
21087 		 * know it, may come to an end.
21088 		 */
21089 		tail = tcp->tcp_xmit_tail;
21090 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21091 		tcp->tcp_xmit_tail_unsent = 0;
21092 		tcp->tcp_unsent = 0;
21093 		if (tail->b_wptr != tail->b_rptr)
21094 			tail = tail->b_cont;
21095 		if (tail) {
21096 			mblk_t **excess = &tcp->tcp_xmit_head;
21097 			for (;;) {
21098 				mblk_t *mp1 = *excess;
21099 				if (mp1 == tail)
21100 					break;
21101 				tcp->tcp_xmit_tail = mp1;
21102 				tcp->tcp_xmit_last = mp1;
21103 				excess = &mp1->b_cont;
21104 			}
21105 			*excess = NULL;
21106 			tcp_close_mpp(&tail);
21107 			if (tcp->tcp_snd_zcopy_aware)
21108 				tcp_zcopy_notify(tcp);
21109 		}
21110 		/*
21111 		 * We have no unsent data, so unsent must be less than
21112 		 * tcp_xmit_lowater, so re-enable flow.
21113 		 */
21114 		if (tcp->tcp_flow_stopped) {
21115 			tcp->tcp_flow_stopped = B_FALSE;
21116 			tcp_clrqfull(tcp);
21117 		}
21118 	}
21119 	/*
21120 	 * TODO: you can't just flush these, you have to increase rwnd for one
21121 	 * thing.  For another, how should urgent data interact?
21122 	 */
21123 	if (fval & FLUSHR) {
21124 		*mp->b_rptr = fval & ~FLUSHW;
21125 		/* XXX */
21126 		qreply(q, mp);
21127 		return;
21128 	}
21129 	freemsg(mp);
21130 }
21131 
21132 /*
21133  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21134  * messages.
21135  */
21136 static void
21137 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21138 {
21139 	mblk_t	*mp1;
21140 	STRUCT_HANDLE(strbuf, sb);
21141 	uint16_t port;
21142 	queue_t 	*q = tcp->tcp_wq;
21143 	in6_addr_t	v6addr;
21144 	ipaddr_t	v4addr;
21145 	uint32_t	flowinfo = 0;
21146 	int		addrlen;
21147 
21148 	/* Make sure it is one of ours. */
21149 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21150 	case TI_GETMYNAME:
21151 	case TI_GETPEERNAME:
21152 		break;
21153 	default:
21154 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21155 		return;
21156 	}
21157 	switch (mi_copy_state(q, mp, &mp1)) {
21158 	case -1:
21159 		return;
21160 	case MI_COPY_CASE(MI_COPY_IN, 1):
21161 		break;
21162 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21163 		/* Copy out the strbuf. */
21164 		mi_copyout(q, mp);
21165 		return;
21166 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21167 		/* All done. */
21168 		mi_copy_done(q, mp, 0);
21169 		return;
21170 	default:
21171 		mi_copy_done(q, mp, EPROTO);
21172 		return;
21173 	}
21174 	/* Check alignment of the strbuf */
21175 	if (!OK_32PTR(mp1->b_rptr)) {
21176 		mi_copy_done(q, mp, EINVAL);
21177 		return;
21178 	}
21179 
21180 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21181 	    (void *)mp1->b_rptr);
21182 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21183 
21184 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21185 		mi_copy_done(q, mp, EINVAL);
21186 		return;
21187 	}
21188 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21189 	case TI_GETMYNAME:
21190 		if (tcp->tcp_family == AF_INET) {
21191 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21192 				v4addr = tcp->tcp_ipha->ipha_src;
21193 			} else {
21194 				/* can't return an address in this case */
21195 				v4addr = 0;
21196 			}
21197 		} else {
21198 			/* tcp->tcp_family == AF_INET6 */
21199 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21200 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21201 				    &v6addr);
21202 			} else {
21203 				v6addr = tcp->tcp_ip6h->ip6_src;
21204 			}
21205 		}
21206 		port = tcp->tcp_lport;
21207 		break;
21208 	case TI_GETPEERNAME:
21209 		if (tcp->tcp_family == AF_INET) {
21210 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21211 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21212 				    v4addr);
21213 			} else {
21214 				/* can't return an address in this case */
21215 				v4addr = 0;
21216 			}
21217 		} else {
21218 			/* tcp->tcp_family == AF_INET6) */
21219 			v6addr = tcp->tcp_remote_v6;
21220 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21221 				/*
21222 				 * No flowinfo if tcp->tcp_ipversion is v4.
21223 				 *
21224 				 * flowinfo was already initialized to zero
21225 				 * where it was declared above, so only
21226 				 * set it if ipversion is v6.
21227 				 */
21228 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21229 				    ~IPV6_VERS_AND_FLOW_MASK;
21230 			}
21231 		}
21232 		port = tcp->tcp_fport;
21233 		break;
21234 	default:
21235 		mi_copy_done(q, mp, EPROTO);
21236 		return;
21237 	}
21238 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21239 	if (!mp1)
21240 		return;
21241 
21242 	if (tcp->tcp_family == AF_INET) {
21243 		sin_t *sin;
21244 
21245 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21246 		sin = (sin_t *)mp1->b_rptr;
21247 		mp1->b_wptr = (uchar_t *)&sin[1];
21248 		*sin = sin_null;
21249 		sin->sin_family = AF_INET;
21250 		sin->sin_addr.s_addr = v4addr;
21251 		sin->sin_port = port;
21252 	} else {
21253 		/* tcp->tcp_family == AF_INET6 */
21254 		sin6_t *sin6;
21255 
21256 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21257 		sin6 = (sin6_t *)mp1->b_rptr;
21258 		mp1->b_wptr = (uchar_t *)&sin6[1];
21259 		*sin6 = sin6_null;
21260 		sin6->sin6_family = AF_INET6;
21261 		sin6->sin6_flowinfo = flowinfo;
21262 		sin6->sin6_addr = v6addr;
21263 		sin6->sin6_port = port;
21264 	}
21265 	/* Copy out the address */
21266 	mi_copyout(q, mp);
21267 }
21268 
21269 /*
21270  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21271  * messages.
21272  */
21273 /* ARGSUSED */
21274 static void
21275 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21276 {
21277 	conn_t 	*connp = (conn_t *)arg;
21278 	tcp_t	*tcp = connp->conn_tcp;
21279 	queue_t	*q = tcp->tcp_wq;
21280 	struct iocblk	*iocp;
21281 
21282 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21283 	/*
21284 	 * Try and ASSERT the minimum possible references on the
21285 	 * conn early enough. Since we are executing on write side,
21286 	 * the connection is obviously not detached and that means
21287 	 * there is a ref each for TCP and IP. Since we are behind
21288 	 * the squeue, the minimum references needed are 3. If the
21289 	 * conn is in classifier hash list, there should be an
21290 	 * extra ref for that (we check both the possibilities).
21291 	 */
21292 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21293 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21294 
21295 	iocp = (struct iocblk *)mp->b_rptr;
21296 	switch (iocp->ioc_cmd) {
21297 	case TCP_IOC_DEFAULT_Q:
21298 		/* Wants to be the default wq. */
21299 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
21300 			iocp->ioc_error = EPERM;
21301 			iocp->ioc_count = 0;
21302 			mp->b_datap->db_type = M_IOCACK;
21303 			qreply(q, mp);
21304 			return;
21305 		}
21306 		tcp_def_q_set(tcp, mp);
21307 		return;
21308 	case SIOCPOPSOCKFS:
21309 		/*
21310 		 * sockfs is being I_POP'ed, reset the flag
21311 		 * indicating this
21312 		 */
21313 		tcp->tcp_issocket = B_FALSE;
21314 
21315 		/*
21316 		 * Insert this socket into the acceptor hash.
21317 		 * We might need it for T_CONN_RES message
21318 		 */
21319 #ifdef	_ILP32
21320 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21321 #else
21322 		tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21323 #endif
21324 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21325 		mp->b_datap->db_type = M_IOCACK;
21326 		iocp->ioc_count = 0;
21327 		iocp->ioc_error = 0;
21328 		iocp->ioc_rval = 0;
21329 		qreply(q, mp);
21330 		return;
21331 	}
21332 	CALL_IP_WPUT(connp, q, mp);
21333 }
21334 
21335 /*
21336  * This routine is called by tcp_wput() to handle all TPI requests.
21337  */
21338 /* ARGSUSED */
21339 static void
21340 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21341 {
21342 	conn_t 	*connp = (conn_t *)arg;
21343 	tcp_t	*tcp = connp->conn_tcp;
21344 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21345 	uchar_t *rptr;
21346 	t_scalar_t type;
21347 	int len;
21348 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21349 
21350 	/*
21351 	 * Try and ASSERT the minimum possible references on the
21352 	 * conn early enough. Since we are executing on write side,
21353 	 * the connection is obviously not detached and that means
21354 	 * there is a ref each for TCP and IP. Since we are behind
21355 	 * the squeue, the minimum references needed are 3. If the
21356 	 * conn is in classifier hash list, there should be an
21357 	 * extra ref for that (we check both the possibilities).
21358 	 */
21359 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21360 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21361 
21362 	rptr = mp->b_rptr;
21363 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21364 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21365 		type = ((union T_primitives *)rptr)->type;
21366 		if (type == T_EXDATA_REQ) {
21367 			len = msgdsize(mp->b_cont) - 1;
21368 			if (len < 0) {
21369 				freemsg(mp);
21370 				return;
21371 			}
21372 			/*
21373 			 * Try to force urgent data out on the wire.
21374 			 * Even if we have unsent data this will
21375 			 * at least send the urgent flag.
21376 			 * XXX does not handle more flag correctly.
21377 			 */
21378 			len += tcp->tcp_unsent;
21379 			len += tcp->tcp_snxt;
21380 			tcp->tcp_urg = len;
21381 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21382 
21383 			/* Bypass tcp protocol for fused tcp loopback */
21384 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp))
21385 				return;
21386 		} else if (type != T_DATA_REQ) {
21387 			goto non_urgent_data;
21388 		}
21389 		/* TODO: options, flags, ... from user */
21390 		/* Set length to zero for reclamation below */
21391 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21392 		freeb(mp);
21393 		return;
21394 	} else {
21395 		if (tcp->tcp_debug) {
21396 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21397 			    "tcp_wput_proto, dropping one...");
21398 		}
21399 		freemsg(mp);
21400 		return;
21401 	}
21402 
21403 non_urgent_data:
21404 
21405 	switch ((int)tprim->type) {
21406 	case O_T_BIND_REQ:	/* bind request */
21407 	case T_BIND_REQ:	/* new semantics bind request */
21408 		tcp_bind(tcp, mp);
21409 		break;
21410 	case T_UNBIND_REQ:	/* unbind request */
21411 		tcp_unbind(tcp, mp);
21412 		break;
21413 	case O_T_CONN_RES:	/* old connection response XXX */
21414 	case T_CONN_RES:	/* connection response */
21415 		tcp_accept(tcp, mp);
21416 		break;
21417 	case T_CONN_REQ:	/* connection request */
21418 		tcp_connect(tcp, mp);
21419 		break;
21420 	case T_DISCON_REQ:	/* disconnect request */
21421 		tcp_disconnect(tcp, mp);
21422 		break;
21423 	case T_CAPABILITY_REQ:
21424 		tcp_capability_req(tcp, mp);	/* capability request */
21425 		break;
21426 	case T_INFO_REQ:	/* information request */
21427 		tcp_info_req(tcp, mp);
21428 		break;
21429 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21430 		/* Only IP is allowed to return meaningful value */
21431 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21432 		break;
21433 	case T_OPTMGMT_REQ:
21434 		/*
21435 		 * Note:  no support for snmpcom_req() through new
21436 		 * T_OPTMGMT_REQ. See comments in ip.c
21437 		 */
21438 		/* Only IP is allowed to return meaningful value */
21439 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21440 		break;
21441 
21442 	case T_UNITDATA_REQ:	/* unitdata request */
21443 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21444 		break;
21445 	case T_ORDREL_REQ:	/* orderly release req */
21446 		freemsg(mp);
21447 
21448 		if (tcp->tcp_fused)
21449 			tcp_unfuse(tcp);
21450 
21451 		if (tcp_xmit_end(tcp) != 0) {
21452 			/*
21453 			 * We were crossing FINs and got a reset from
21454 			 * the other side. Just ignore it.
21455 			 */
21456 			if (tcp->tcp_debug) {
21457 				(void) strlog(TCP_MODULE_ID, 0, 1,
21458 				    SL_ERROR|SL_TRACE,
21459 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21460 				    "state %s",
21461 				    tcp_display(tcp, NULL,
21462 				    DISP_ADDR_AND_PORT));
21463 			}
21464 		}
21465 		break;
21466 	case T_ADDR_REQ:
21467 		tcp_addr_req(tcp, mp);
21468 		break;
21469 	default:
21470 		if (tcp->tcp_debug) {
21471 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21472 			    "tcp_wput_proto, bogus TPI msg, type %d",
21473 			    tprim->type);
21474 		}
21475 		/*
21476 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21477 		 * to recover.
21478 		 */
21479 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21480 		break;
21481 	}
21482 }
21483 
21484 /*
21485  * The TCP write service routine should never be called...
21486  */
21487 /* ARGSUSED */
21488 static void
21489 tcp_wsrv(queue_t *q)
21490 {
21491 	TCP_STAT(tcp_wsrv_called);
21492 }
21493 
21494 /* Non overlapping byte exchanger */
21495 static void
21496 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21497 {
21498 	uchar_t	uch;
21499 
21500 	while (len-- > 0) {
21501 		uch = a[len];
21502 		a[len] = b[len];
21503 		b[len] = uch;
21504 	}
21505 }
21506 
21507 /*
21508  * Send out a control packet on the tcp connection specified.  This routine
21509  * is typically called where we need a simple ACK or RST generated.
21510  */
21511 static void
21512 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21513 {
21514 	uchar_t		*rptr;
21515 	tcph_t		*tcph;
21516 	ipha_t		*ipha = NULL;
21517 	ip6_t		*ip6h = NULL;
21518 	uint32_t	sum;
21519 	int		tcp_hdr_len;
21520 	int		tcp_ip_hdr_len;
21521 	mblk_t		*mp;
21522 
21523 	/*
21524 	 * Save sum for use in source route later.
21525 	 */
21526 	ASSERT(tcp != NULL);
21527 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21528 	tcp_hdr_len = tcp->tcp_hdr_len;
21529 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21530 
21531 	/* If a text string is passed in with the request, pass it to strlog. */
21532 	if (str != NULL && tcp->tcp_debug) {
21533 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21534 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21535 		    str, seq, ack, ctl);
21536 	}
21537 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21538 	    BPRI_MED);
21539 	if (mp == NULL) {
21540 		return;
21541 	}
21542 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21543 	mp->b_rptr = rptr;
21544 	mp->b_wptr = &rptr[tcp_hdr_len];
21545 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21546 
21547 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21548 		ipha = (ipha_t *)rptr;
21549 		ipha->ipha_length = htons(tcp_hdr_len);
21550 	} else {
21551 		ip6h = (ip6_t *)rptr;
21552 		ASSERT(tcp != NULL);
21553 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21554 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21555 	}
21556 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21557 	tcph->th_flags[0] = (uint8_t)ctl;
21558 	if (ctl & TH_RST) {
21559 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21560 		BUMP_MIB(&tcp_mib, tcpOutControl);
21561 		/*
21562 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21563 		 */
21564 		if (tcp->tcp_snd_ts_ok &&
21565 		    tcp->tcp_state > TCPS_SYN_SENT) {
21566 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21567 			*(mp->b_wptr) = TCPOPT_EOL;
21568 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21569 				ipha->ipha_length = htons(tcp_hdr_len -
21570 				    TCPOPT_REAL_TS_LEN);
21571 			} else {
21572 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21573 				    TCPOPT_REAL_TS_LEN);
21574 			}
21575 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21576 			sum -= TCPOPT_REAL_TS_LEN;
21577 		}
21578 	}
21579 	if (ctl & TH_ACK) {
21580 		if (tcp->tcp_snd_ts_ok) {
21581 			U32_TO_BE32(lbolt,
21582 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21583 			U32_TO_BE32(tcp->tcp_ts_recent,
21584 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21585 		}
21586 
21587 		/* Update the latest receive window size in TCP header. */
21588 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21589 		    tcph->th_win);
21590 		tcp->tcp_rack = ack;
21591 		tcp->tcp_rack_cnt = 0;
21592 		BUMP_MIB(&tcp_mib, tcpOutAck);
21593 	}
21594 	BUMP_LOCAL(tcp->tcp_obsegs);
21595 	U32_TO_BE32(seq, tcph->th_seq);
21596 	U32_TO_BE32(ack, tcph->th_ack);
21597 	/*
21598 	 * Include the adjustment for a source route if any.
21599 	 */
21600 	sum = (sum >> 16) + (sum & 0xFFFF);
21601 	U16_TO_BE16(sum, tcph->th_sum);
21602 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21603 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21604 }
21605 
21606 /*
21607  * If this routine returns B_TRUE, TCP can generate a RST in response
21608  * to a segment.  If it returns B_FALSE, TCP should not respond.
21609  */
21610 static boolean_t
21611 tcp_send_rst_chk(void)
21612 {
21613 	clock_t	now;
21614 
21615 	/*
21616 	 * TCP needs to protect itself from generating too many RSTs.
21617 	 * This can be a DoS attack by sending us random segments
21618 	 * soliciting RSTs.
21619 	 *
21620 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21621 	 * in each 1 second interval.  In this way, TCP still generate
21622 	 * RSTs in normal cases but when under attack, the impact is
21623 	 * limited.
21624 	 */
21625 	if (tcp_rst_sent_rate_enabled != 0) {
21626 		now = lbolt;
21627 		/* lbolt can wrap around. */
21628 		if ((tcp_last_rst_intrvl > now) ||
21629 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21630 			tcp_last_rst_intrvl = now;
21631 			tcp_rst_cnt = 1;
21632 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21633 			return (B_FALSE);
21634 		}
21635 	}
21636 	return (B_TRUE);
21637 }
21638 
21639 /*
21640  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21641  */
21642 static void
21643 tcp_ip_ire_mark_advice(tcp_t *tcp)
21644 {
21645 	mblk_t *mp;
21646 	ipic_t *ipic;
21647 
21648 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21649 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21650 		    &ipic);
21651 	} else {
21652 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21653 		    &ipic);
21654 	}
21655 	if (mp == NULL)
21656 		return;
21657 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21658 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21659 }
21660 
21661 /*
21662  * Return an IP advice ioctl mblk and set ipic to be the pointer
21663  * to the advice structure.
21664  */
21665 static mblk_t *
21666 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21667 {
21668 	struct iocblk *ioc;
21669 	mblk_t *mp, *mp1;
21670 
21671 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21672 	if (mp == NULL)
21673 		return (NULL);
21674 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21675 	*ipic = (ipic_t *)mp->b_rptr;
21676 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21677 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21678 
21679 	bcopy(addr, *ipic + 1, addr_len);
21680 
21681 	(*ipic)->ipic_addr_length = addr_len;
21682 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21683 
21684 	mp1 = mkiocb(IP_IOCTL);
21685 	if (mp1 == NULL) {
21686 		freemsg(mp);
21687 		return (NULL);
21688 	}
21689 	mp1->b_cont = mp;
21690 	ioc = (struct iocblk *)mp1->b_rptr;
21691 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21692 
21693 	return (mp1);
21694 }
21695 
21696 /*
21697  * Generate a reset based on an inbound packet for which there is no active
21698  * tcp state that we can find.
21699  *
21700  * IPSEC NOTE : Try to send the reply with the same protection as it came
21701  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21702  * the packet will go out at the same level of protection as it came in by
21703  * converting the IPSEC_IN to IPSEC_OUT.
21704  */
21705 static void
21706 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21707     uint32_t ack, int ctl, uint_t ip_hdr_len)
21708 {
21709 	ipha_t		*ipha = NULL;
21710 	ip6_t		*ip6h = NULL;
21711 	ushort_t	len;
21712 	tcph_t		*tcph;
21713 	int		i;
21714 	mblk_t		*ipsec_mp;
21715 	boolean_t	mctl_present;
21716 	ipic_t		*ipic;
21717 	ipaddr_t	v4addr;
21718 	in6_addr_t	v6addr;
21719 	int		addr_len;
21720 	void		*addr;
21721 	queue_t		*q = tcp_g_q;
21722 	tcp_t		*tcp = Q_TO_TCP(q);
21723 
21724 	if (!tcp_send_rst_chk()) {
21725 		tcp_rst_unsent++;
21726 		freemsg(mp);
21727 		return;
21728 	}
21729 
21730 	if (mp->b_datap->db_type == M_CTL) {
21731 		ipsec_mp = mp;
21732 		mp = mp->b_cont;
21733 		mctl_present = B_TRUE;
21734 	} else {
21735 		ipsec_mp = mp;
21736 		mctl_present = B_FALSE;
21737 	}
21738 
21739 	if (str && q && tcp_dbg) {
21740 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21741 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21742 		    "flags 0x%x",
21743 		    str, seq, ack, ctl);
21744 	}
21745 	if (mp->b_datap->db_ref != 1) {
21746 		mblk_t *mp1 = copyb(mp);
21747 		freemsg(mp);
21748 		mp = mp1;
21749 		if (!mp) {
21750 			if (mctl_present)
21751 				freeb(ipsec_mp);
21752 			return;
21753 		} else {
21754 			if (mctl_present) {
21755 				ipsec_mp->b_cont = mp;
21756 			} else {
21757 				ipsec_mp = mp;
21758 			}
21759 		}
21760 	} else if (mp->b_cont) {
21761 		freemsg(mp->b_cont);
21762 		mp->b_cont = NULL;
21763 	}
21764 	/*
21765 	 * We skip reversing source route here.
21766 	 * (for now we replace all IP options with EOL)
21767 	 */
21768 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21769 		ipha = (ipha_t *)mp->b_rptr;
21770 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21771 			mp->b_rptr[i] = IPOPT_EOL;
21772 		/*
21773 		 * Make sure that src address isn't flagrantly invalid.
21774 		 * Not all broadcast address checking for the src address
21775 		 * is possible, since we don't know the netmask of the src
21776 		 * addr.  No check for destination address is done, since
21777 		 * IP will not pass up a packet with a broadcast dest
21778 		 * address to TCP.  Similar checks are done below for IPv6.
21779 		 */
21780 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21781 		    CLASSD(ipha->ipha_src)) {
21782 			freemsg(ipsec_mp);
21783 			BUMP_MIB(&ip_mib, ipInDiscards);
21784 			return;
21785 		}
21786 	} else {
21787 		ip6h = (ip6_t *)mp->b_rptr;
21788 
21789 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21790 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21791 			freemsg(ipsec_mp);
21792 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21793 			return;
21794 		}
21795 
21796 		/* Remove any extension headers assuming partial overlay */
21797 		if (ip_hdr_len > IPV6_HDR_LEN) {
21798 			uint8_t *to;
21799 
21800 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21801 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21802 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21803 			ip_hdr_len = IPV6_HDR_LEN;
21804 			ip6h = (ip6_t *)mp->b_rptr;
21805 			ip6h->ip6_nxt = IPPROTO_TCP;
21806 		}
21807 	}
21808 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21809 	if (tcph->th_flags[0] & TH_RST) {
21810 		freemsg(ipsec_mp);
21811 		return;
21812 	}
21813 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21814 	len = ip_hdr_len + sizeof (tcph_t);
21815 	mp->b_wptr = &mp->b_rptr[len];
21816 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21817 		ipha->ipha_length = htons(len);
21818 		/* Swap addresses */
21819 		v4addr = ipha->ipha_src;
21820 		ipha->ipha_src = ipha->ipha_dst;
21821 		ipha->ipha_dst = v4addr;
21822 		ipha->ipha_ident = 0;
21823 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21824 		addr_len = IP_ADDR_LEN;
21825 		addr = &v4addr;
21826 	} else {
21827 		/* No ip6i_t in this case */
21828 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21829 		/* Swap addresses */
21830 		v6addr = ip6h->ip6_src;
21831 		ip6h->ip6_src = ip6h->ip6_dst;
21832 		ip6h->ip6_dst = v6addr;
21833 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21834 		addr_len = IPV6_ADDR_LEN;
21835 		addr = &v6addr;
21836 	}
21837 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21838 	U32_TO_BE32(ack, tcph->th_ack);
21839 	U32_TO_BE32(seq, tcph->th_seq);
21840 	U16_TO_BE16(0, tcph->th_win);
21841 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21842 	tcph->th_flags[0] = (uint8_t)ctl;
21843 	if (ctl & TH_RST) {
21844 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21845 		BUMP_MIB(&tcp_mib, tcpOutControl);
21846 	}
21847 	if (mctl_present) {
21848 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21849 
21850 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21851 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21852 			return;
21853 		}
21854 	}
21855 	/*
21856 	 * NOTE:  one might consider tracing a TCP packet here, but
21857 	 * this function has no active TCP state nd no tcp structure
21858 	 * which has trace buffer.  If we traced here, we would have
21859 	 * to keep a local trace buffer in tcp_record_trace().
21860 	 */
21861 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21862 
21863 	/*
21864 	 * Tell IP to mark the IRE used for this destination temporary.
21865 	 * This way, we can limit our exposure to DoS attack because IP
21866 	 * creates an IRE for each destination.  If there are too many,
21867 	 * the time to do any routing lookup will be extremely long.  And
21868 	 * the lookup can be in interrupt context.
21869 	 *
21870 	 * Note that in normal circumstances, this marking should not
21871 	 * affect anything.  It would be nice if only 1 message is
21872 	 * needed to inform IP that the IRE created for this RST should
21873 	 * not be added to the cache table.  But there is currently
21874 	 * not such communication mechanism between TCP and IP.  So
21875 	 * the best we can do now is to send the advice ioctl to IP
21876 	 * to mark the IRE temporary.
21877 	 */
21878 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21879 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21880 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21881 	}
21882 }
21883 
21884 /*
21885  * Initiate closedown sequence on an active connection.  (May be called as
21886  * writer.)  Return value zero for OK return, non-zero for error return.
21887  */
21888 static int
21889 tcp_xmit_end(tcp_t *tcp)
21890 {
21891 	ipic_t	*ipic;
21892 	mblk_t	*mp;
21893 
21894 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21895 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21896 		/*
21897 		 * Invalid state, only states TCPS_SYN_RCVD,
21898 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21899 		 */
21900 		return (-1);
21901 	}
21902 
21903 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21904 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21905 	/*
21906 	 * If there is nothing more unsent, send the FIN now.
21907 	 * Otherwise, it will go out with the last segment.
21908 	 */
21909 	if (tcp->tcp_unsent == 0) {
21910 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21911 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21912 
21913 		if (mp) {
21914 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21915 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21916 		} else {
21917 			/*
21918 			 * Couldn't allocate msg.  Pretend we got it out.
21919 			 * Wait for rexmit timeout.
21920 			 */
21921 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21922 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21923 		}
21924 
21925 		/*
21926 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21927 		 * changed.
21928 		 */
21929 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21930 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21931 		}
21932 	} else {
21933 		/*
21934 		 * If tcp->tcp_cork is set, then the data will not get sent,
21935 		 * so we have to check that and unset it first.
21936 		 */
21937 		if (tcp->tcp_cork)
21938 			tcp->tcp_cork = B_FALSE;
21939 		tcp_wput_data(tcp, NULL, B_FALSE);
21940 	}
21941 
21942 	/*
21943 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21944 	 * is 0, don't update the cache.
21945 	 */
21946 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21947 		return (0);
21948 
21949 	/*
21950 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21951 	 * different from the destination.
21952 	 */
21953 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21954 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21955 			return (0);
21956 		}
21957 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21958 		    &ipic);
21959 	} else {
21960 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21961 		    &tcp->tcp_ip6h->ip6_dst))) {
21962 			return (0);
21963 		}
21964 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21965 		    &ipic);
21966 	}
21967 
21968 	/* Record route attributes in the IRE for use by future connections. */
21969 	if (mp == NULL)
21970 		return (0);
21971 
21972 	/*
21973 	 * We do not have a good algorithm to update ssthresh at this time.
21974 	 * So don't do any update.
21975 	 */
21976 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21977 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21978 
21979 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21980 	return (0);
21981 }
21982 
21983 /*
21984  * Generate a "no listener here" RST in response to an "unknown" segment.
21985  * Note that we are reusing the incoming mp to construct the outgoing
21986  * RST.
21987  */
21988 void
21989 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21990 {
21991 	uchar_t		*rptr;
21992 	uint32_t	seg_len;
21993 	tcph_t		*tcph;
21994 	uint32_t	seg_seq;
21995 	uint32_t	seg_ack;
21996 	uint_t		flags;
21997 	mblk_t		*ipsec_mp;
21998 	ipha_t 		*ipha;
21999 	ip6_t 		*ip6h;
22000 	boolean_t	mctl_present = B_FALSE;
22001 	boolean_t	check = B_TRUE;
22002 	boolean_t	policy_present;
22003 
22004 	TCP_STAT(tcp_no_listener);
22005 
22006 	ipsec_mp = mp;
22007 
22008 	if (mp->b_datap->db_type == M_CTL) {
22009 		ipsec_in_t *ii;
22010 
22011 		mctl_present = B_TRUE;
22012 		mp = mp->b_cont;
22013 
22014 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22015 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22016 		if (ii->ipsec_in_dont_check) {
22017 			check = B_FALSE;
22018 			if (!ii->ipsec_in_secure) {
22019 				freeb(ipsec_mp);
22020 				mctl_present = B_FALSE;
22021 				ipsec_mp = mp;
22022 			}
22023 		}
22024 	}
22025 
22026 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22027 		policy_present = ipsec_inbound_v4_policy_present;
22028 		ipha = (ipha_t *)mp->b_rptr;
22029 		ip6h = NULL;
22030 	} else {
22031 		policy_present = ipsec_inbound_v6_policy_present;
22032 		ipha = NULL;
22033 		ip6h = (ip6_t *)mp->b_rptr;
22034 	}
22035 
22036 	if (check && policy_present) {
22037 		/*
22038 		 * The conn_t parameter is NULL because we already know
22039 		 * nobody's home.
22040 		 */
22041 		ipsec_mp = ipsec_check_global_policy(
22042 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
22043 		if (ipsec_mp == NULL)
22044 			return;
22045 	}
22046 
22047 
22048 	rptr = mp->b_rptr;
22049 
22050 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22051 	seg_seq = BE32_TO_U32(tcph->th_seq);
22052 	seg_ack = BE32_TO_U32(tcph->th_ack);
22053 	flags = tcph->th_flags[0];
22054 
22055 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22056 	if (flags & TH_RST) {
22057 		freemsg(ipsec_mp);
22058 	} else if (flags & TH_ACK) {
22059 		tcp_xmit_early_reset("no tcp, reset",
22060 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
22061 	} else {
22062 		if (flags & TH_SYN) {
22063 			seg_len++;
22064 		} else {
22065 			/*
22066 			 * Here we violate the RFC.  Note that a normal
22067 			 * TCP will never send a segment without the ACK
22068 			 * flag, except for RST or SYN segment.  This
22069 			 * segment is neither.  Just drop it on the
22070 			 * floor.
22071 			 */
22072 			freemsg(ipsec_mp);
22073 			tcp_rst_unsent++;
22074 			return;
22075 		}
22076 
22077 		tcp_xmit_early_reset("no tcp, reset/ack",
22078 		    ipsec_mp, 0, seg_seq + seg_len,
22079 		    TH_RST | TH_ACK, ip_hdr_len);
22080 	}
22081 }
22082 
22083 /*
22084  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22085  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22086  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22087  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22088  * otherwise it will dup partial mblks.)
22089  * Otherwise, an appropriate ACK packet will be generated.  This
22090  * routine is not usually called to send new data for the first time.  It
22091  * is mostly called out of the timer for retransmits, and to generate ACKs.
22092  *
22093  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22094  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22095  * of the original mblk chain will be returned in *offset and *end_mp.
22096  */
22097 static mblk_t *
22098 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22099     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22100     boolean_t rexmit)
22101 {
22102 	int	data_length;
22103 	int32_t	off = 0;
22104 	uint_t	flags;
22105 	mblk_t	*mp1;
22106 	mblk_t	*mp2;
22107 	uchar_t	*rptr;
22108 	tcph_t	*tcph;
22109 	int32_t	num_sack_blk = 0;
22110 	int32_t	sack_opt_len = 0;
22111 
22112 	/* Allocate for our maximum TCP header + link-level */
22113 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22114 	    BPRI_MED);
22115 	if (!mp1)
22116 		return (NULL);
22117 	data_length = 0;
22118 
22119 	/*
22120 	 * Note that tcp_mss has been adjusted to take into account the
22121 	 * timestamp option if applicable.  Because SACK options do not
22122 	 * appear in every TCP segments and they are of variable lengths,
22123 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22124 	 * the actual segment length when we need to send a segment which
22125 	 * includes SACK options.
22126 	 */
22127 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22128 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22129 		    tcp->tcp_num_sack_blk);
22130 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22131 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22132 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22133 			max_to_send -= sack_opt_len;
22134 	}
22135 
22136 	if (offset != NULL) {
22137 		off = *offset;
22138 		/* We use offset as an indicator that end_mp is not NULL. */
22139 		*end_mp = NULL;
22140 	}
22141 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22142 		/* This could be faster with cooperation from downstream */
22143 		if (mp2 != mp1 && !sendall &&
22144 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22145 		    max_to_send)
22146 			/*
22147 			 * Don't send the next mblk since the whole mblk
22148 			 * does not fit.
22149 			 */
22150 			break;
22151 		mp2->b_cont = dupb(mp);
22152 		mp2 = mp2->b_cont;
22153 		if (!mp2) {
22154 			freemsg(mp1);
22155 			return (NULL);
22156 		}
22157 		mp2->b_rptr += off;
22158 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22159 		    (uintptr_t)INT_MAX);
22160 
22161 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22162 		if (data_length > max_to_send) {
22163 			mp2->b_wptr -= data_length - max_to_send;
22164 			data_length = max_to_send;
22165 			off = mp2->b_wptr - mp->b_rptr;
22166 			break;
22167 		} else {
22168 			off = 0;
22169 		}
22170 	}
22171 	if (offset != NULL) {
22172 		*offset = off;
22173 		*end_mp = mp;
22174 	}
22175 	if (seg_len != NULL) {
22176 		*seg_len = data_length;
22177 	}
22178 
22179 	/* Update the latest receive window size in TCP header. */
22180 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22181 	    tcp->tcp_tcph->th_win);
22182 
22183 	rptr = mp1->b_rptr + tcp_wroff_xtra;
22184 	mp1->b_rptr = rptr;
22185 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22186 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22187 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22188 	U32_TO_ABE32(seq, tcph->th_seq);
22189 
22190 	/*
22191 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22192 	 * that this function was called from tcp_wput_data. Thus, when called
22193 	 * to retransmit data the setting of the PUSH bit may appear some
22194 	 * what random in that it might get set when it should not. This
22195 	 * should not pose any performance issues.
22196 	 */
22197 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22198 	    tcp->tcp_unsent == data_length)) {
22199 		flags = TH_ACK | TH_PUSH;
22200 	} else {
22201 		flags = TH_ACK;
22202 	}
22203 
22204 	if (tcp->tcp_ecn_ok) {
22205 		if (tcp->tcp_ecn_echo_on)
22206 			flags |= TH_ECE;
22207 
22208 		/*
22209 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22210 		 * There is no TCP flow control for non-data segments, and
22211 		 * only data segment is transmitted reliably.
22212 		 */
22213 		if (data_length > 0 && !rexmit) {
22214 			SET_ECT(tcp, rptr);
22215 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22216 				flags |= TH_CWR;
22217 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22218 			}
22219 		}
22220 	}
22221 
22222 	if (tcp->tcp_valid_bits) {
22223 		uint32_t u1;
22224 
22225 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22226 		    seq == tcp->tcp_iss) {
22227 			uchar_t	*wptr;
22228 
22229 			/*
22230 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22231 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22232 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22233 			 * our SYN is not ack'ed but the app closes this
22234 			 * TCP connection.
22235 			 */
22236 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22237 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22238 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22239 
22240 			/*
22241 			 * Tack on the MSS option.  It is always needed
22242 			 * for both active and passive open.
22243 			 *
22244 			 * MSS option value should be interface MTU - MIN
22245 			 * TCP/IP header according to RFC 793 as it means
22246 			 * the maximum segment size TCP can receive.  But
22247 			 * to get around some broken middle boxes/end hosts
22248 			 * out there, we allow the option value to be the
22249 			 * same as the MSS option size on the peer side.
22250 			 * In this way, the other side will not send
22251 			 * anything larger than they can receive.
22252 			 *
22253 			 * Note that for SYN_SENT state, the ndd param
22254 			 * tcp_use_smss_as_mss_opt has no effect as we
22255 			 * don't know the peer's MSS option value. So
22256 			 * the only case we need to take care of is in
22257 			 * SYN_RCVD state, which is done later.
22258 			 */
22259 			wptr = mp1->b_wptr;
22260 			wptr[0] = TCPOPT_MAXSEG;
22261 			wptr[1] = TCPOPT_MAXSEG_LEN;
22262 			wptr += 2;
22263 			u1 = tcp->tcp_if_mtu -
22264 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22265 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22266 			    TCP_MIN_HEADER_LENGTH;
22267 			U16_TO_BE16(u1, wptr);
22268 			mp1->b_wptr = wptr + 2;
22269 			/* Update the offset to cover the additional word */
22270 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22271 
22272 			/*
22273 			 * Note that the following way of filling in
22274 			 * TCP options are not optimal.  Some NOPs can
22275 			 * be saved.  But there is no need at this time
22276 			 * to optimize it.  When it is needed, we will
22277 			 * do it.
22278 			 */
22279 			switch (tcp->tcp_state) {
22280 			case TCPS_SYN_SENT:
22281 				flags = TH_SYN;
22282 
22283 				if (tcp->tcp_snd_ts_ok) {
22284 					uint32_t llbolt = (uint32_t)lbolt;
22285 
22286 					wptr = mp1->b_wptr;
22287 					wptr[0] = TCPOPT_NOP;
22288 					wptr[1] = TCPOPT_NOP;
22289 					wptr[2] = TCPOPT_TSTAMP;
22290 					wptr[3] = TCPOPT_TSTAMP_LEN;
22291 					wptr += 4;
22292 					U32_TO_BE32(llbolt, wptr);
22293 					wptr += 4;
22294 					ASSERT(tcp->tcp_ts_recent == 0);
22295 					U32_TO_BE32(0L, wptr);
22296 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22297 					tcph->th_offset_and_rsrvd[0] +=
22298 					    (3 << 4);
22299 				}
22300 
22301 				/*
22302 				 * Set up all the bits to tell other side
22303 				 * we are ECN capable.
22304 				 */
22305 				if (tcp->tcp_ecn_ok) {
22306 					flags |= (TH_ECE | TH_CWR);
22307 				}
22308 				break;
22309 			case TCPS_SYN_RCVD:
22310 				flags |= TH_SYN;
22311 
22312 				/*
22313 				 * Reset the MSS option value to be SMSS
22314 				 * We should probably add back the bytes
22315 				 * for timestamp option and IPsec.  We
22316 				 * don't do that as this is a workaround
22317 				 * for broken middle boxes/end hosts, it
22318 				 * is better for us to be more cautious.
22319 				 * They may not take these things into
22320 				 * account in their SMSS calculation.  Thus
22321 				 * the peer's calculated SMSS may be smaller
22322 				 * than what it can be.  This should be OK.
22323 				 */
22324 				if (tcp_use_smss_as_mss_opt) {
22325 					u1 = tcp->tcp_mss;
22326 					U16_TO_BE16(u1, wptr);
22327 				}
22328 
22329 				/*
22330 				 * If the other side is ECN capable, reply
22331 				 * that we are also ECN capable.
22332 				 */
22333 				if (tcp->tcp_ecn_ok)
22334 					flags |= TH_ECE;
22335 				break;
22336 			default:
22337 				/*
22338 				 * The above ASSERT() makes sure that this
22339 				 * must be FIN-WAIT-1 state.  Our SYN has
22340 				 * not been ack'ed so retransmit it.
22341 				 */
22342 				flags |= TH_SYN;
22343 				break;
22344 			}
22345 
22346 			if (tcp->tcp_snd_ws_ok) {
22347 				wptr = mp1->b_wptr;
22348 				wptr[0] =  TCPOPT_NOP;
22349 				wptr[1] =  TCPOPT_WSCALE;
22350 				wptr[2] =  TCPOPT_WS_LEN;
22351 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22352 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22353 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22354 			}
22355 
22356 			if (tcp->tcp_snd_sack_ok) {
22357 				wptr = mp1->b_wptr;
22358 				wptr[0] = TCPOPT_NOP;
22359 				wptr[1] = TCPOPT_NOP;
22360 				wptr[2] = TCPOPT_SACK_PERMITTED;
22361 				wptr[3] = TCPOPT_SACK_OK_LEN;
22362 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22363 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22364 			}
22365 
22366 			/* allocb() of adequate mblk assures space */
22367 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22368 			    (uintptr_t)INT_MAX);
22369 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22370 			/*
22371 			 * Get IP set to checksum on our behalf
22372 			 * Include the adjustment for a source route if any.
22373 			 */
22374 			u1 += tcp->tcp_sum;
22375 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22376 			U16_TO_BE16(u1, tcph->th_sum);
22377 			BUMP_MIB(&tcp_mib, tcpOutControl);
22378 		}
22379 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22380 		    (seq + data_length) == tcp->tcp_fss) {
22381 			if (!tcp->tcp_fin_acked) {
22382 				flags |= TH_FIN;
22383 				BUMP_MIB(&tcp_mib, tcpOutControl);
22384 			}
22385 			if (!tcp->tcp_fin_sent) {
22386 				tcp->tcp_fin_sent = B_TRUE;
22387 				switch (tcp->tcp_state) {
22388 				case TCPS_SYN_RCVD:
22389 				case TCPS_ESTABLISHED:
22390 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22391 					break;
22392 				case TCPS_CLOSE_WAIT:
22393 					tcp->tcp_state = TCPS_LAST_ACK;
22394 					break;
22395 				}
22396 				if (tcp->tcp_suna == tcp->tcp_snxt)
22397 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22398 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22399 			}
22400 		}
22401 		/*
22402 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22403 		 * is smaller than seq, u1 will become a very huge value.
22404 		 * So the comparison will fail.  Also note that tcp_urp
22405 		 * should be positive, see RFC 793 page 17.
22406 		 */
22407 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22408 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22409 		    u1 < (uint32_t)(64 * 1024)) {
22410 			flags |= TH_URG;
22411 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22412 			U32_TO_ABE16(u1, tcph->th_urp);
22413 		}
22414 	}
22415 	tcph->th_flags[0] = (uchar_t)flags;
22416 	tcp->tcp_rack = tcp->tcp_rnxt;
22417 	tcp->tcp_rack_cnt = 0;
22418 
22419 	if (tcp->tcp_snd_ts_ok) {
22420 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22421 			uint32_t llbolt = (uint32_t)lbolt;
22422 
22423 			U32_TO_BE32(llbolt,
22424 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22425 			U32_TO_BE32(tcp->tcp_ts_recent,
22426 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22427 		}
22428 	}
22429 
22430 	if (num_sack_blk > 0) {
22431 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22432 		sack_blk_t *tmp;
22433 		int32_t	i;
22434 
22435 		wptr[0] = TCPOPT_NOP;
22436 		wptr[1] = TCPOPT_NOP;
22437 		wptr[2] = TCPOPT_SACK;
22438 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22439 		    sizeof (sack_blk_t);
22440 		wptr += TCPOPT_REAL_SACK_LEN;
22441 
22442 		tmp = tcp->tcp_sack_list;
22443 		for (i = 0; i < num_sack_blk; i++) {
22444 			U32_TO_BE32(tmp[i].begin, wptr);
22445 			wptr += sizeof (tcp_seq);
22446 			U32_TO_BE32(tmp[i].end, wptr);
22447 			wptr += sizeof (tcp_seq);
22448 		}
22449 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22450 	}
22451 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22452 	data_length += (int)(mp1->b_wptr - rptr);
22453 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22454 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22455 	} else {
22456 		ip6_t *ip6 = (ip6_t *)(rptr +
22457 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22458 		    sizeof (ip6i_t) : 0));
22459 
22460 		ip6->ip6_plen = htons(data_length -
22461 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22462 	}
22463 
22464 	/*
22465 	 * Prime pump for IP
22466 	 * Include the adjustment for a source route if any.
22467 	 */
22468 	data_length -= tcp->tcp_ip_hdr_len;
22469 	data_length += tcp->tcp_sum;
22470 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22471 	U16_TO_ABE16(data_length, tcph->th_sum);
22472 	if (tcp->tcp_ip_forward_progress) {
22473 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22474 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22475 		tcp->tcp_ip_forward_progress = B_FALSE;
22476 	}
22477 	return (mp1);
22478 }
22479 
22480 /* This function handles the push timeout. */
22481 static void
22482 tcp_push_timer(void *arg)
22483 {
22484 	conn_t	*connp = (conn_t *)arg;
22485 	tcp_t *tcp = connp->conn_tcp;
22486 
22487 	TCP_DBGSTAT(tcp_push_timer_cnt);
22488 
22489 	ASSERT(tcp->tcp_listener == NULL);
22490 
22491 	tcp->tcp_push_tid = 0;
22492 	if ((tcp->tcp_rcv_list != NULL) &&
22493 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22494 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22495 }
22496 
22497 /*
22498  * This function handles delayed ACK timeout.
22499  */
22500 static void
22501 tcp_ack_timer(void *arg)
22502 {
22503 	conn_t	*connp = (conn_t *)arg;
22504 	tcp_t *tcp = connp->conn_tcp;
22505 	mblk_t *mp;
22506 
22507 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22508 
22509 	tcp->tcp_ack_tid = 0;
22510 
22511 	if (tcp->tcp_fused)
22512 		return;
22513 
22514 	/*
22515 	 * Do not send ACK if there is no outstanding unack'ed data.
22516 	 */
22517 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22518 		return;
22519 	}
22520 
22521 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22522 		/*
22523 		 * Make sure we don't allow deferred ACKs to result in
22524 		 * timer-based ACKing.  If we have held off an ACK
22525 		 * when there was more than an mss here, and the timer
22526 		 * goes off, we have to worry about the possibility
22527 		 * that the sender isn't doing slow-start, or is out
22528 		 * of step with us for some other reason.  We fall
22529 		 * permanently back in the direction of
22530 		 * ACK-every-other-packet as suggested in RFC 1122.
22531 		 */
22532 		if (tcp->tcp_rack_abs_max > 2)
22533 			tcp->tcp_rack_abs_max--;
22534 		tcp->tcp_rack_cur_max = 2;
22535 	}
22536 	mp = tcp_ack_mp(tcp);
22537 
22538 	if (mp != NULL) {
22539 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22540 		BUMP_LOCAL(tcp->tcp_obsegs);
22541 		BUMP_MIB(&tcp_mib, tcpOutAck);
22542 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22543 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22544 	}
22545 }
22546 
22547 
22548 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22549 static mblk_t *
22550 tcp_ack_mp(tcp_t *tcp)
22551 {
22552 	uint32_t	seq_no;
22553 
22554 	/*
22555 	 * There are a few cases to be considered while setting the sequence no.
22556 	 * Essentially, we can come here while processing an unacceptable pkt
22557 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22558 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22559 	 * If we are here for a zero window probe, stick with suna. In all
22560 	 * other cases, we check if suna + swnd encompasses snxt and set
22561 	 * the sequence number to snxt, if so. If snxt falls outside the
22562 	 * window (the receiver probably shrunk its window), we will go with
22563 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22564 	 * receiver.
22565 	 */
22566 	if (tcp->tcp_zero_win_probe) {
22567 		seq_no = tcp->tcp_suna;
22568 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22569 		ASSERT(tcp->tcp_swnd == 0);
22570 		seq_no = tcp->tcp_snxt;
22571 	} else {
22572 		seq_no = SEQ_GT(tcp->tcp_snxt,
22573 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22574 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22575 	}
22576 
22577 	if (tcp->tcp_valid_bits) {
22578 		/*
22579 		 * For the complex case where we have to send some
22580 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22581 		 */
22582 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22583 		    NULL, B_FALSE));
22584 	} else {
22585 		/* Generate a simple ACK */
22586 		int	data_length;
22587 		uchar_t	*rptr;
22588 		tcph_t	*tcph;
22589 		mblk_t	*mp1;
22590 		int32_t	tcp_hdr_len;
22591 		int32_t	tcp_tcp_hdr_len;
22592 		int32_t	num_sack_blk = 0;
22593 		int32_t sack_opt_len;
22594 
22595 		/*
22596 		 * Allocate space for TCP + IP headers
22597 		 * and link-level header
22598 		 */
22599 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22600 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22601 			    tcp->tcp_num_sack_blk);
22602 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22603 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22604 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22605 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22606 		} else {
22607 			tcp_hdr_len = tcp->tcp_hdr_len;
22608 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22609 		}
22610 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22611 		if (!mp1)
22612 			return (NULL);
22613 
22614 		/* Update the latest receive window size in TCP header. */
22615 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22616 		    tcp->tcp_tcph->th_win);
22617 		/* copy in prototype TCP + IP header */
22618 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22619 		mp1->b_rptr = rptr;
22620 		mp1->b_wptr = rptr + tcp_hdr_len;
22621 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22622 
22623 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22624 
22625 		/* Set the TCP sequence number. */
22626 		U32_TO_ABE32(seq_no, tcph->th_seq);
22627 
22628 		/* Set up the TCP flag field. */
22629 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22630 		if (tcp->tcp_ecn_echo_on)
22631 			tcph->th_flags[0] |= TH_ECE;
22632 
22633 		tcp->tcp_rack = tcp->tcp_rnxt;
22634 		tcp->tcp_rack_cnt = 0;
22635 
22636 		/* fill in timestamp option if in use */
22637 		if (tcp->tcp_snd_ts_ok) {
22638 			uint32_t llbolt = (uint32_t)lbolt;
22639 
22640 			U32_TO_BE32(llbolt,
22641 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22642 			U32_TO_BE32(tcp->tcp_ts_recent,
22643 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22644 		}
22645 
22646 		/* Fill in SACK options */
22647 		if (num_sack_blk > 0) {
22648 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22649 			sack_blk_t *tmp;
22650 			int32_t	i;
22651 
22652 			wptr[0] = TCPOPT_NOP;
22653 			wptr[1] = TCPOPT_NOP;
22654 			wptr[2] = TCPOPT_SACK;
22655 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22656 			    sizeof (sack_blk_t);
22657 			wptr += TCPOPT_REAL_SACK_LEN;
22658 
22659 			tmp = tcp->tcp_sack_list;
22660 			for (i = 0; i < num_sack_blk; i++) {
22661 				U32_TO_BE32(tmp[i].begin, wptr);
22662 				wptr += sizeof (tcp_seq);
22663 				U32_TO_BE32(tmp[i].end, wptr);
22664 				wptr += sizeof (tcp_seq);
22665 			}
22666 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22667 			    << 4);
22668 		}
22669 
22670 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22671 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22672 		} else {
22673 			/* Check for ip6i_t header in sticky hdrs */
22674 			ip6_t *ip6 = (ip6_t *)(rptr +
22675 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22676 			    sizeof (ip6i_t) : 0));
22677 
22678 			ip6->ip6_plen = htons(tcp_hdr_len -
22679 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22680 		}
22681 
22682 		/*
22683 		 * Prime pump for checksum calculation in IP.  Include the
22684 		 * adjustment for a source route if any.
22685 		 */
22686 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22687 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22688 		U16_TO_ABE16(data_length, tcph->th_sum);
22689 
22690 		if (tcp->tcp_ip_forward_progress) {
22691 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22692 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22693 			tcp->tcp_ip_forward_progress = B_FALSE;
22694 		}
22695 		return (mp1);
22696 	}
22697 }
22698 
22699 /*
22700  * To create a temporary tcp structure for inserting into bind hash list.
22701  * The parameter is assumed to be in network byte order, ready for use.
22702  */
22703 /* ARGSUSED */
22704 static tcp_t *
22705 tcp_alloc_temp_tcp(in_port_t port)
22706 {
22707 	conn_t	*connp;
22708 	tcp_t	*tcp;
22709 
22710 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22711 	if (connp == NULL)
22712 		return (NULL);
22713 
22714 	tcp = connp->conn_tcp;
22715 
22716 	/*
22717 	 * Only initialize the necessary info in those structures.  Note
22718 	 * that since INADDR_ANY is all 0, we do not need to set
22719 	 * tcp_bound_source to INADDR_ANY here.
22720 	 */
22721 	tcp->tcp_state = TCPS_BOUND;
22722 	tcp->tcp_lport = port;
22723 	tcp->tcp_exclbind = 1;
22724 	tcp->tcp_reserved_port = 1;
22725 
22726 	/* Just for place holding... */
22727 	tcp->tcp_ipversion = IPV4_VERSION;
22728 
22729 	return (tcp);
22730 }
22731 
22732 /*
22733  * To remove a port range specified by lo_port and hi_port from the
22734  * reserved port ranges.  This is one of the three public functions of
22735  * the reserved port interface.  Note that a port range has to be removed
22736  * as a whole.  Ports in a range cannot be removed individually.
22737  *
22738  * Params:
22739  *	in_port_t lo_port: the beginning port of the reserved port range to
22740  *		be deleted.
22741  *	in_port_t hi_port: the ending port of the reserved port range to
22742  *		be deleted.
22743  *
22744  * Return:
22745  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22746  */
22747 boolean_t
22748 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22749 {
22750 	int	i, j;
22751 	int	size;
22752 	tcp_t	**temp_tcp_array;
22753 	tcp_t	*tcp;
22754 
22755 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22756 
22757 	/* First make sure that the port ranage is indeed reserved. */
22758 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22759 		if (tcp_reserved_port[i].lo_port == lo_port) {
22760 			hi_port = tcp_reserved_port[i].hi_port;
22761 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22762 			break;
22763 		}
22764 	}
22765 	if (i == tcp_reserved_port_array_size) {
22766 		rw_exit(&tcp_reserved_port_lock);
22767 		return (B_FALSE);
22768 	}
22769 
22770 	/*
22771 	 * Remove the range from the array.  This simple loop is possible
22772 	 * because port ranges are inserted in ascending order.
22773 	 */
22774 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22775 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22776 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22777 		tcp_reserved_port[j].temp_tcp_array =
22778 		    tcp_reserved_port[j+1].temp_tcp_array;
22779 	}
22780 
22781 	/* Remove all the temporary tcp structures. */
22782 	size = hi_port - lo_port + 1;
22783 	while (size > 0) {
22784 		tcp = temp_tcp_array[size - 1];
22785 		ASSERT(tcp != NULL);
22786 		tcp_bind_hash_remove(tcp);
22787 		CONN_DEC_REF(tcp->tcp_connp);
22788 		size--;
22789 	}
22790 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22791 	tcp_reserved_port_array_size--;
22792 	rw_exit(&tcp_reserved_port_lock);
22793 	return (B_TRUE);
22794 }
22795 
22796 /*
22797  * Macro to remove temporary tcp structure from the bind hash list.  The
22798  * first parameter is the list of tcp to be removed.  The second parameter
22799  * is the number of tcps in the array.
22800  */
22801 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22802 { \
22803 	while ((num) > 0) { \
22804 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22805 		tf_t *tbf; \
22806 		tcp_t *tcpnext; \
22807 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22808 		mutex_enter(&tbf->tf_lock); \
22809 		tcpnext = tcp->tcp_bind_hash; \
22810 		if (tcpnext) { \
22811 			tcpnext->tcp_ptpbhn = \
22812 				tcp->tcp_ptpbhn; \
22813 		} \
22814 		*tcp->tcp_ptpbhn = tcpnext; \
22815 		mutex_exit(&tbf->tf_lock); \
22816 		kmem_free(tcp, sizeof (tcp_t)); \
22817 		(tcp_array)[(num) - 1] = NULL; \
22818 		(num)--; \
22819 	} \
22820 }
22821 
22822 /*
22823  * The public interface for other modules to call to reserve a port range
22824  * in TCP.  The caller passes in how large a port range it wants.  TCP
22825  * will try to find a range and return it via lo_port and hi_port.  This is
22826  * used by NCA's nca_conn_init.
22827  * NCA can only be used in the global zone so this only affects the global
22828  * zone's ports.
22829  *
22830  * Params:
22831  *	int size: the size of the port range to be reserved.
22832  *	in_port_t *lo_port (referenced): returns the beginning port of the
22833  *		reserved port range added.
22834  *	in_port_t *hi_port (referenced): returns the ending port of the
22835  *		reserved port range added.
22836  *
22837  * Return:
22838  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22839  */
22840 boolean_t
22841 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22842 {
22843 	tcp_t		*tcp;
22844 	tcp_t		*tmp_tcp;
22845 	tcp_t		**temp_tcp_array;
22846 	tf_t		*tbf;
22847 	in_port_t	net_port;
22848 	in_port_t	port;
22849 	int32_t		cur_size;
22850 	int		i, j;
22851 	boolean_t	used;
22852 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22853 	zoneid_t	zoneid = GLOBAL_ZONEID;
22854 
22855 	/* Sanity check. */
22856 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22857 		return (B_FALSE);
22858 	}
22859 
22860 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22861 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22862 		rw_exit(&tcp_reserved_port_lock);
22863 		return (B_FALSE);
22864 	}
22865 
22866 	/*
22867 	 * Find the starting port to try.  Since the port ranges are ordered
22868 	 * in the reserved port array, we can do a simple search here.
22869 	 */
22870 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22871 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22872 	for (i = 0; i < tcp_reserved_port_array_size;
22873 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22874 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22875 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22876 			break;
22877 		}
22878 	}
22879 	/* No available port range. */
22880 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22881 		rw_exit(&tcp_reserved_port_lock);
22882 		return (B_FALSE);
22883 	}
22884 
22885 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22886 	if (temp_tcp_array == NULL) {
22887 		rw_exit(&tcp_reserved_port_lock);
22888 		return (B_FALSE);
22889 	}
22890 
22891 	/* Go thru the port range to see if some ports are already bound. */
22892 	for (port = *lo_port, cur_size = 0;
22893 	    cur_size < size && port <= *hi_port;
22894 	    cur_size++, port++) {
22895 		used = B_FALSE;
22896 		net_port = htons(port);
22897 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22898 		mutex_enter(&tbf->tf_lock);
22899 		for (tcp = tbf->tf_tcp; tcp != NULL;
22900 		    tcp = tcp->tcp_bind_hash) {
22901 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22902 			    net_port == tcp->tcp_lport) {
22903 				/*
22904 				 * A port is already bound.  Search again
22905 				 * starting from port + 1.  Release all
22906 				 * temporary tcps.
22907 				 */
22908 				mutex_exit(&tbf->tf_lock);
22909 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22910 				*lo_port = port + 1;
22911 				cur_size = -1;
22912 				used = B_TRUE;
22913 				break;
22914 			}
22915 		}
22916 		if (!used) {
22917 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22918 				/*
22919 				 * Allocation failure.  Just fail the request.
22920 				 * Need to remove all those temporary tcp
22921 				 * structures.
22922 				 */
22923 				mutex_exit(&tbf->tf_lock);
22924 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22925 				rw_exit(&tcp_reserved_port_lock);
22926 				kmem_free(temp_tcp_array,
22927 				    (hi_port - lo_port + 1) *
22928 				    sizeof (tcp_t *));
22929 				return (B_FALSE);
22930 			}
22931 			temp_tcp_array[cur_size] = tmp_tcp;
22932 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22933 			mutex_exit(&tbf->tf_lock);
22934 		}
22935 	}
22936 
22937 	/*
22938 	 * The current range is not large enough.  We can actually do another
22939 	 * search if this search is done between 2 reserved port ranges.  But
22940 	 * for first release, we just stop here and return saying that no port
22941 	 * range is available.
22942 	 */
22943 	if (cur_size < size) {
22944 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22945 		rw_exit(&tcp_reserved_port_lock);
22946 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22947 		return (B_FALSE);
22948 	}
22949 	*hi_port = port - 1;
22950 
22951 	/*
22952 	 * Insert range into array in ascending order.  Since this function
22953 	 * must not be called often, we choose to use the simplest method.
22954 	 * The above array should not consume excessive stack space as
22955 	 * the size must be very small.  If in future releases, we find
22956 	 * that we should provide more reserved port ranges, this function
22957 	 * has to be modified to be more efficient.
22958 	 */
22959 	if (tcp_reserved_port_array_size == 0) {
22960 		tcp_reserved_port[0].lo_port = *lo_port;
22961 		tcp_reserved_port[0].hi_port = *hi_port;
22962 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22963 	} else {
22964 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22965 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22966 				tmp_ports[j].lo_port = *lo_port;
22967 				tmp_ports[j].hi_port = *hi_port;
22968 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22969 				j++;
22970 			}
22971 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22972 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22973 			tmp_ports[j].temp_tcp_array =
22974 			    tcp_reserved_port[i].temp_tcp_array;
22975 		}
22976 		if (j == i) {
22977 			tmp_ports[j].lo_port = *lo_port;
22978 			tmp_ports[j].hi_port = *hi_port;
22979 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22980 		}
22981 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22982 	}
22983 	tcp_reserved_port_array_size++;
22984 	rw_exit(&tcp_reserved_port_lock);
22985 	return (B_TRUE);
22986 }
22987 
22988 /*
22989  * Check to see if a port is in any reserved port range.
22990  *
22991  * Params:
22992  *	in_port_t port: the port to be verified.
22993  *
22994  * Return:
22995  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22996  */
22997 boolean_t
22998 tcp_reserved_port_check(in_port_t port)
22999 {
23000 	int i;
23001 
23002 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23003 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23004 		if (port >= tcp_reserved_port[i].lo_port ||
23005 		    port <= tcp_reserved_port[i].hi_port) {
23006 			rw_exit(&tcp_reserved_port_lock);
23007 			return (B_TRUE);
23008 		}
23009 	}
23010 	rw_exit(&tcp_reserved_port_lock);
23011 	return (B_FALSE);
23012 }
23013 
23014 /*
23015  * To list all reserved port ranges.  This is the function to handle
23016  * ndd tcp_reserved_port_list.
23017  */
23018 /* ARGSUSED */
23019 static int
23020 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23021 {
23022 	int i;
23023 
23024 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23025 	if (tcp_reserved_port_array_size > 0)
23026 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23027 	else
23028 		(void) mi_mpprintf(mp, "No port is reserved.");
23029 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23030 		(void) mi_mpprintf(mp, "%d-%d",
23031 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
23032 	}
23033 	rw_exit(&tcp_reserved_port_lock);
23034 	return (0);
23035 }
23036 
23037 /*
23038  * Hash list insertion routine for tcp_t structures.
23039  * Inserts entries with the ones bound to a specific IP address first
23040  * followed by those bound to INADDR_ANY.
23041  */
23042 static void
23043 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23044 {
23045 	tcp_t	**tcpp;
23046 	tcp_t	*tcpnext;
23047 
23048 	if (tcp->tcp_ptpbhn != NULL) {
23049 		ASSERT(!caller_holds_lock);
23050 		tcp_bind_hash_remove(tcp);
23051 	}
23052 	tcpp = &tbf->tf_tcp;
23053 	if (!caller_holds_lock) {
23054 		mutex_enter(&tbf->tf_lock);
23055 	} else {
23056 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23057 	}
23058 	tcpnext = tcpp[0];
23059 	if (tcpnext) {
23060 		/*
23061 		 * If the new tcp bound to the INADDR_ANY address
23062 		 * and the first one in the list is not bound to
23063 		 * INADDR_ANY we skip all entries until we find the
23064 		 * first one bound to INADDR_ANY.
23065 		 * This makes sure that applications binding to a
23066 		 * specific address get preference over those binding to
23067 		 * INADDR_ANY.
23068 		 */
23069 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23070 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23071 			while ((tcpnext = tcpp[0]) != NULL &&
23072 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23073 				tcpp = &(tcpnext->tcp_bind_hash);
23074 			if (tcpnext)
23075 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23076 		} else
23077 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23078 	}
23079 	tcp->tcp_bind_hash = tcpnext;
23080 	tcp->tcp_ptpbhn = tcpp;
23081 	tcpp[0] = tcp;
23082 	if (!caller_holds_lock)
23083 		mutex_exit(&tbf->tf_lock);
23084 }
23085 
23086 /*
23087  * Hash list removal routine for tcp_t structures.
23088  */
23089 static void
23090 tcp_bind_hash_remove(tcp_t *tcp)
23091 {
23092 	tcp_t	*tcpnext;
23093 	kmutex_t *lockp;
23094 
23095 	if (tcp->tcp_ptpbhn == NULL)
23096 		return;
23097 
23098 	/*
23099 	 * Extract the lock pointer in case there are concurrent
23100 	 * hash_remove's for this instance.
23101 	 */
23102 	ASSERT(tcp->tcp_lport != 0);
23103 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23104 
23105 	ASSERT(lockp != NULL);
23106 	mutex_enter(lockp);
23107 	if (tcp->tcp_ptpbhn) {
23108 		tcpnext = tcp->tcp_bind_hash;
23109 		if (tcpnext) {
23110 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23111 			tcp->tcp_bind_hash = NULL;
23112 		}
23113 		*tcp->tcp_ptpbhn = tcpnext;
23114 		tcp->tcp_ptpbhn = NULL;
23115 	}
23116 	mutex_exit(lockp);
23117 }
23118 
23119 
23120 /*
23121  * Hash list lookup routine for tcp_t structures.
23122  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23123  */
23124 static tcp_t *
23125 tcp_acceptor_hash_lookup(t_uscalar_t id)
23126 {
23127 	tf_t	*tf;
23128 	tcp_t	*tcp;
23129 
23130 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23131 	mutex_enter(&tf->tf_lock);
23132 	for (tcp = tf->tf_tcp; tcp != NULL;
23133 	    tcp = tcp->tcp_acceptor_hash) {
23134 		if (tcp->tcp_acceptor_id == id) {
23135 			CONN_INC_REF(tcp->tcp_connp);
23136 			mutex_exit(&tf->tf_lock);
23137 			return (tcp);
23138 		}
23139 	}
23140 	mutex_exit(&tf->tf_lock);
23141 	return (NULL);
23142 }
23143 
23144 
23145 /*
23146  * Hash list insertion routine for tcp_t structures.
23147  */
23148 void
23149 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23150 {
23151 	tf_t	*tf;
23152 	tcp_t	**tcpp;
23153 	tcp_t	*tcpnext;
23154 
23155 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23156 
23157 	if (tcp->tcp_ptpahn != NULL)
23158 		tcp_acceptor_hash_remove(tcp);
23159 	tcpp = &tf->tf_tcp;
23160 	mutex_enter(&tf->tf_lock);
23161 	tcpnext = tcpp[0];
23162 	if (tcpnext)
23163 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23164 	tcp->tcp_acceptor_hash = tcpnext;
23165 	tcp->tcp_ptpahn = tcpp;
23166 	tcpp[0] = tcp;
23167 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23168 	mutex_exit(&tf->tf_lock);
23169 }
23170 
23171 /*
23172  * Hash list removal routine for tcp_t structures.
23173  */
23174 static void
23175 tcp_acceptor_hash_remove(tcp_t *tcp)
23176 {
23177 	tcp_t	*tcpnext;
23178 	kmutex_t *lockp;
23179 
23180 	/*
23181 	 * Extract the lock pointer in case there are concurrent
23182 	 * hash_remove's for this instance.
23183 	 */
23184 	lockp = tcp->tcp_acceptor_lockp;
23185 
23186 	if (tcp->tcp_ptpahn == NULL)
23187 		return;
23188 
23189 	ASSERT(lockp != NULL);
23190 	mutex_enter(lockp);
23191 	if (tcp->tcp_ptpahn) {
23192 		tcpnext = tcp->tcp_acceptor_hash;
23193 		if (tcpnext) {
23194 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23195 			tcp->tcp_acceptor_hash = NULL;
23196 		}
23197 		*tcp->tcp_ptpahn = tcpnext;
23198 		tcp->tcp_ptpahn = NULL;
23199 	}
23200 	mutex_exit(lockp);
23201 	tcp->tcp_acceptor_lockp = NULL;
23202 }
23203 
23204 /* ARGSUSED */
23205 static int
23206 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
23207 {
23208 	int error = 0;
23209 	int retval;
23210 	char *end;
23211 
23212 	tcp_hsp_t *hsp;
23213 	tcp_hsp_t *hspprev;
23214 
23215 	ipaddr_t addr = 0;		/* Address we're looking for */
23216 	in6_addr_t v6addr;		/* Address we're looking for */
23217 	uint32_t hash;			/* Hash of that address */
23218 
23219 	/*
23220 	 * If the following variables are still zero after parsing the input
23221 	 * string, the user didn't specify them and we don't change them in
23222 	 * the HSP.
23223 	 */
23224 
23225 	ipaddr_t mask = 0;		/* Subnet mask */
23226 	in6_addr_t v6mask;
23227 	long sendspace = 0;		/* Send buffer size */
23228 	long recvspace = 0;		/* Receive buffer size */
23229 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
23230 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
23231 
23232 	rw_enter(&tcp_hsp_lock, RW_WRITER);
23233 
23234 	/* Parse and validate address */
23235 	if (af == AF_INET) {
23236 		retval = inet_pton(af, value, &addr);
23237 		if (retval == 1)
23238 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
23239 	} else if (af == AF_INET6) {
23240 		retval = inet_pton(af, value, &v6addr);
23241 	} else {
23242 		error = EINVAL;
23243 		goto done;
23244 	}
23245 	if (retval == 0) {
23246 		error = EINVAL;
23247 		goto done;
23248 	}
23249 
23250 	while ((*value) && *value != ' ')
23251 		value++;
23252 
23253 	/* Parse individual keywords, set variables if found */
23254 	while (*value) {
23255 		/* Skip leading blanks */
23256 
23257 		while (*value == ' ' || *value == '\t')
23258 			value++;
23259 
23260 		/* If at end of string, we're done */
23261 
23262 		if (!*value)
23263 			break;
23264 
23265 		/* We have a word, figure out what it is */
23266 
23267 		if (strncmp("mask", value, 4) == 0) {
23268 			value += 4;
23269 			while (*value == ' ' || *value == '\t')
23270 				value++;
23271 			/* Parse subnet mask */
23272 			if (af == AF_INET) {
23273 				retval = inet_pton(af, value, &mask);
23274 				if (retval == 1) {
23275 					V4MASK_TO_V6(mask, v6mask);
23276 				}
23277 			} else if (af == AF_INET6) {
23278 				retval = inet_pton(af, value, &v6mask);
23279 			}
23280 			if (retval != 1) {
23281 				error = EINVAL;
23282 				goto done;
23283 			}
23284 			while ((*value) && *value != ' ')
23285 				value++;
23286 		} else if (strncmp("sendspace", value, 9) == 0) {
23287 			value += 9;
23288 
23289 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23290 			    sendspace < TCP_XMIT_HIWATER ||
23291 			    sendspace >= (1L<<30)) {
23292 				error = EINVAL;
23293 				goto done;
23294 			}
23295 			value = end;
23296 		} else if (strncmp("recvspace", value, 9) == 0) {
23297 			value += 9;
23298 
23299 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23300 			    recvspace < TCP_RECV_HIWATER ||
23301 			    recvspace >= (1L<<30)) {
23302 				error = EINVAL;
23303 				goto done;
23304 			}
23305 			value = end;
23306 		} else if (strncmp("timestamp", value, 9) == 0) {
23307 			value += 9;
23308 
23309 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23310 			    timestamp < 0 || timestamp > 1) {
23311 				error = EINVAL;
23312 				goto done;
23313 			}
23314 
23315 			/*
23316 			 * We increment timestamp so we know it's been set;
23317 			 * this is undone when we put it in the HSP
23318 			 */
23319 			timestamp++;
23320 			value = end;
23321 		} else if (strncmp("delete", value, 6) == 0) {
23322 			value += 6;
23323 			delete = B_TRUE;
23324 		} else {
23325 			error = EINVAL;
23326 			goto done;
23327 		}
23328 	}
23329 
23330 	/* Hash address for lookup */
23331 
23332 	hash = TCP_HSP_HASH(addr);
23333 
23334 	if (delete) {
23335 		/*
23336 		 * Note that deletes don't return an error if the thing
23337 		 * we're trying to delete isn't there.
23338 		 */
23339 		if (tcp_hsp_hash == NULL)
23340 			goto done;
23341 		hsp = tcp_hsp_hash[hash];
23342 
23343 		if (hsp) {
23344 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23345 			    &v6addr)) {
23346 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23347 				mi_free((char *)hsp);
23348 			} else {
23349 				hspprev = hsp;
23350 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23351 					if (IN6_ARE_ADDR_EQUAL(
23352 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23353 						hspprev->tcp_hsp_next =
23354 						    hsp->tcp_hsp_next;
23355 						mi_free((char *)hsp);
23356 						break;
23357 					}
23358 					hspprev = hsp;
23359 				}
23360 			}
23361 		}
23362 	} else {
23363 		/*
23364 		 * We're adding/modifying an HSP.  If we haven't already done
23365 		 * so, allocate the hash table.
23366 		 */
23367 
23368 		if (!tcp_hsp_hash) {
23369 			tcp_hsp_hash = (tcp_hsp_t **)
23370 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23371 			if (!tcp_hsp_hash) {
23372 				error = EINVAL;
23373 				goto done;
23374 			}
23375 		}
23376 
23377 		/* Get head of hash chain */
23378 
23379 		hsp = tcp_hsp_hash[hash];
23380 
23381 		/* Try to find pre-existing hsp on hash chain */
23382 		/* Doesn't handle CIDR prefixes. */
23383 		while (hsp) {
23384 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23385 				break;
23386 			hsp = hsp->tcp_hsp_next;
23387 		}
23388 
23389 		/*
23390 		 * If we didn't, create one with default values and put it
23391 		 * at head of hash chain
23392 		 */
23393 
23394 		if (!hsp) {
23395 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23396 			if (!hsp) {
23397 				error = EINVAL;
23398 				goto done;
23399 			}
23400 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23401 			tcp_hsp_hash[hash] = hsp;
23402 		}
23403 
23404 		/* Set values that the user asked us to change */
23405 
23406 		hsp->tcp_hsp_addr_v6 = v6addr;
23407 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23408 			hsp->tcp_hsp_vers = IPV4_VERSION;
23409 		else
23410 			hsp->tcp_hsp_vers = IPV6_VERSION;
23411 		hsp->tcp_hsp_subnet_v6 = v6mask;
23412 		if (sendspace > 0)
23413 			hsp->tcp_hsp_sendspace = sendspace;
23414 		if (recvspace > 0)
23415 			hsp->tcp_hsp_recvspace = recvspace;
23416 		if (timestamp > 0)
23417 			hsp->tcp_hsp_tstamp = timestamp - 1;
23418 	}
23419 
23420 done:
23421 	rw_exit(&tcp_hsp_lock);
23422 	return (error);
23423 }
23424 
23425 /* Set callback routine passed to nd_load by tcp_param_register. */
23426 /* ARGSUSED */
23427 static int
23428 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23429 {
23430 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23431 }
23432 /* ARGSUSED */
23433 static int
23434 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23435     cred_t *cr)
23436 {
23437 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23438 }
23439 
23440 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23441 /* ARGSUSED */
23442 static int
23443 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23444 {
23445 	tcp_hsp_t *hsp;
23446 	int i;
23447 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23448 
23449 	rw_enter(&tcp_hsp_lock, RW_READER);
23450 	(void) mi_mpprintf(mp,
23451 	    "Hash HSP     " MI_COL_HDRPAD_STR
23452 	    "Address         Subnet Mask     Send       Receive    TStamp");
23453 	if (tcp_hsp_hash) {
23454 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23455 			hsp = tcp_hsp_hash[i];
23456 			while (hsp) {
23457 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23458 					(void) inet_ntop(AF_INET,
23459 					    &hsp->tcp_hsp_addr,
23460 					    addrbuf, sizeof (addrbuf));
23461 					(void) inet_ntop(AF_INET,
23462 					    &hsp->tcp_hsp_subnet,
23463 					    subnetbuf, sizeof (subnetbuf));
23464 				} else {
23465 					(void) inet_ntop(AF_INET6,
23466 					    &hsp->tcp_hsp_addr_v6,
23467 					    addrbuf, sizeof (addrbuf));
23468 					(void) inet_ntop(AF_INET6,
23469 					    &hsp->tcp_hsp_subnet_v6,
23470 					    subnetbuf, sizeof (subnetbuf));
23471 				}
23472 				(void) mi_mpprintf(mp,
23473 				    " %03d " MI_COL_PTRFMT_STR
23474 				    "%s %s %010d %010d      %d",
23475 				    i,
23476 				    (void *)hsp,
23477 				    addrbuf,
23478 				    subnetbuf,
23479 				    hsp->tcp_hsp_sendspace,
23480 				    hsp->tcp_hsp_recvspace,
23481 				    hsp->tcp_hsp_tstamp);
23482 
23483 				hsp = hsp->tcp_hsp_next;
23484 			}
23485 		}
23486 	}
23487 	rw_exit(&tcp_hsp_lock);
23488 	return (0);
23489 }
23490 
23491 
23492 /* Data for fast netmask macro used by tcp_hsp_lookup */
23493 
23494 static ipaddr_t netmasks[] = {
23495 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23496 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23497 };
23498 
23499 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23500 
23501 /*
23502  * XXX This routine should go away and instead we should use the metrics
23503  * associated with the routes to determine the default sndspace and rcvspace.
23504  */
23505 static tcp_hsp_t *
23506 tcp_hsp_lookup(ipaddr_t addr)
23507 {
23508 	tcp_hsp_t *hsp = NULL;
23509 
23510 	/* Quick check without acquiring the lock. */
23511 	if (tcp_hsp_hash == NULL)
23512 		return (NULL);
23513 
23514 	rw_enter(&tcp_hsp_lock, RW_READER);
23515 
23516 	/* This routine finds the best-matching HSP for address addr. */
23517 
23518 	if (tcp_hsp_hash) {
23519 		int i;
23520 		ipaddr_t srchaddr;
23521 		tcp_hsp_t *hsp_net;
23522 
23523 		/* We do three passes: host, network, and subnet. */
23524 
23525 		srchaddr = addr;
23526 
23527 		for (i = 1; i <= 3; i++) {
23528 			/* Look for exact match on srchaddr */
23529 
23530 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23531 			while (hsp) {
23532 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23533 				    hsp->tcp_hsp_addr == srchaddr)
23534 					break;
23535 				hsp = hsp->tcp_hsp_next;
23536 			}
23537 			ASSERT(hsp == NULL ||
23538 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23539 
23540 			/*
23541 			 * If this is the first pass:
23542 			 *   If we found a match, great, return it.
23543 			 *   If not, search for the network on the second pass.
23544 			 */
23545 
23546 			if (i == 1)
23547 				if (hsp)
23548 					break;
23549 				else
23550 				{
23551 					srchaddr = addr & netmask(addr);
23552 					continue;
23553 				}
23554 
23555 			/*
23556 			 * If this is the second pass:
23557 			 *   If we found a match, but there's a subnet mask,
23558 			 *    save the match but try again using the subnet
23559 			 *    mask on the third pass.
23560 			 *   Otherwise, return whatever we found.
23561 			 */
23562 
23563 			if (i == 2) {
23564 				if (hsp && hsp->tcp_hsp_subnet) {
23565 					hsp_net = hsp;
23566 					srchaddr = addr & hsp->tcp_hsp_subnet;
23567 					continue;
23568 				} else {
23569 					break;
23570 				}
23571 			}
23572 
23573 			/*
23574 			 * This must be the third pass.  If we didn't find
23575 			 * anything, return the saved network HSP instead.
23576 			 */
23577 
23578 			if (!hsp)
23579 				hsp = hsp_net;
23580 		}
23581 	}
23582 
23583 	rw_exit(&tcp_hsp_lock);
23584 	return (hsp);
23585 }
23586 
23587 /*
23588  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23589  * match lookup.
23590  */
23591 static tcp_hsp_t *
23592 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23593 {
23594 	tcp_hsp_t *hsp = NULL;
23595 
23596 	/* Quick check without acquiring the lock. */
23597 	if (tcp_hsp_hash == NULL)
23598 		return (NULL);
23599 
23600 	rw_enter(&tcp_hsp_lock, RW_READER);
23601 
23602 	/* This routine finds the best-matching HSP for address addr. */
23603 
23604 	if (tcp_hsp_hash) {
23605 		int i;
23606 		in6_addr_t v6srchaddr;
23607 		tcp_hsp_t *hsp_net;
23608 
23609 		/* We do three passes: host, network, and subnet. */
23610 
23611 		v6srchaddr = *v6addr;
23612 
23613 		for (i = 1; i <= 3; i++) {
23614 			/* Look for exact match on srchaddr */
23615 
23616 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23617 			    V4_PART_OF_V6(v6srchaddr))];
23618 			while (hsp) {
23619 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23620 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23621 				    &v6srchaddr))
23622 					break;
23623 				hsp = hsp->tcp_hsp_next;
23624 			}
23625 
23626 			/*
23627 			 * If this is the first pass:
23628 			 *   If we found a match, great, return it.
23629 			 *   If not, search for the network on the second pass.
23630 			 */
23631 
23632 			if (i == 1)
23633 				if (hsp)
23634 					break;
23635 				else {
23636 					/* Assume a 64 bit mask */
23637 					v6srchaddr.s6_addr32[0] =
23638 					    v6addr->s6_addr32[0];
23639 					v6srchaddr.s6_addr32[1] =
23640 					    v6addr->s6_addr32[1];
23641 					v6srchaddr.s6_addr32[2] = 0;
23642 					v6srchaddr.s6_addr32[3] = 0;
23643 					continue;
23644 				}
23645 
23646 			/*
23647 			 * If this is the second pass:
23648 			 *   If we found a match, but there's a subnet mask,
23649 			 *    save the match but try again using the subnet
23650 			 *    mask on the third pass.
23651 			 *   Otherwise, return whatever we found.
23652 			 */
23653 
23654 			if (i == 2) {
23655 				ASSERT(hsp == NULL ||
23656 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23657 				if (hsp &&
23658 				    !IN6_IS_ADDR_UNSPECIFIED(
23659 				    &hsp->tcp_hsp_subnet_v6)) {
23660 					hsp_net = hsp;
23661 					V6_MASK_COPY(*v6addr,
23662 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23663 					continue;
23664 				} else {
23665 					break;
23666 				}
23667 			}
23668 
23669 			/*
23670 			 * This must be the third pass.  If we didn't find
23671 			 * anything, return the saved network HSP instead.
23672 			 */
23673 
23674 			if (!hsp)
23675 				hsp = hsp_net;
23676 		}
23677 	}
23678 
23679 	rw_exit(&tcp_hsp_lock);
23680 	return (hsp);
23681 }
23682 
23683 /*
23684  * Type three generator adapted from the random() function in 4.4 BSD:
23685  */
23686 
23687 /*
23688  * Copyright (c) 1983, 1993
23689  *	The Regents of the University of California.  All rights reserved.
23690  *
23691  * Redistribution and use in source and binary forms, with or without
23692  * modification, are permitted provided that the following conditions
23693  * are met:
23694  * 1. Redistributions of source code must retain the above copyright
23695  *    notice, this list of conditions and the following disclaimer.
23696  * 2. Redistributions in binary form must reproduce the above copyright
23697  *    notice, this list of conditions and the following disclaimer in the
23698  *    documentation and/or other materials provided with the distribution.
23699  * 3. All advertising materials mentioning features or use of this software
23700  *    must display the following acknowledgement:
23701  *	This product includes software developed by the University of
23702  *	California, Berkeley and its contributors.
23703  * 4. Neither the name of the University nor the names of its contributors
23704  *    may be used to endorse or promote products derived from this software
23705  *    without specific prior written permission.
23706  *
23707  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23708  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23709  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23710  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23711  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23712  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23713  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23714  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23715  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23716  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23717  * SUCH DAMAGE.
23718  */
23719 
23720 /* Type 3 -- x**31 + x**3 + 1 */
23721 #define	DEG_3		31
23722 #define	SEP_3		3
23723 
23724 
23725 /* Protected by tcp_random_lock */
23726 static int tcp_randtbl[DEG_3 + 1];
23727 
23728 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23729 static int *tcp_random_rptr = &tcp_randtbl[1];
23730 
23731 static int *tcp_random_state = &tcp_randtbl[1];
23732 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23733 
23734 kmutex_t tcp_random_lock;
23735 
23736 void
23737 tcp_random_init(void)
23738 {
23739 	int i;
23740 	hrtime_t hrt;
23741 	time_t wallclock;
23742 	uint64_t result;
23743 
23744 	/*
23745 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23746 	 * a longlong, which may contain resolution down to nanoseconds.
23747 	 * The current time will either be a 32-bit or a 64-bit quantity.
23748 	 * XOR the two together in a 64-bit result variable.
23749 	 * Convert the result to a 32-bit value by multiplying the high-order
23750 	 * 32-bits by the low-order 32-bits.
23751 	 */
23752 
23753 	hrt = gethrtime();
23754 	(void) drv_getparm(TIME, &wallclock);
23755 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23756 	mutex_enter(&tcp_random_lock);
23757 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23758 	    (result & 0xffffffff);
23759 
23760 	for (i = 1; i < DEG_3; i++)
23761 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23762 			+ 12345;
23763 	tcp_random_fptr = &tcp_random_state[SEP_3];
23764 	tcp_random_rptr = &tcp_random_state[0];
23765 	mutex_exit(&tcp_random_lock);
23766 	for (i = 0; i < 10 * DEG_3; i++)
23767 		(void) tcp_random();
23768 }
23769 
23770 /*
23771  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23772  * This range is selected to be approximately centered on TCP_ISS / 2,
23773  * and easy to compute. We get this value by generating a 32-bit random
23774  * number, selecting out the high-order 17 bits, and then adding one so
23775  * that we never return zero.
23776  */
23777 int
23778 tcp_random(void)
23779 {
23780 	int i;
23781 
23782 	mutex_enter(&tcp_random_lock);
23783 	*tcp_random_fptr += *tcp_random_rptr;
23784 
23785 	/*
23786 	 * The high-order bits are more random than the low-order bits,
23787 	 * so we select out the high-order 17 bits and add one so that
23788 	 * we never return zero.
23789 	 */
23790 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23791 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23792 		tcp_random_fptr = tcp_random_state;
23793 		++tcp_random_rptr;
23794 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23795 		tcp_random_rptr = tcp_random_state;
23796 
23797 	mutex_exit(&tcp_random_lock);
23798 	return (i);
23799 }
23800 
23801 /*
23802  * XXX This will go away when TPI is extended to send
23803  * info reqs to sockfs/timod .....
23804  * Given a queue, set the max packet size for the write
23805  * side of the queue below stream head.  This value is
23806  * cached on the stream head.
23807  * Returns 1 on success, 0 otherwise.
23808  */
23809 static int
23810 setmaxps(queue_t *q, int maxpsz)
23811 {
23812 	struct stdata	*stp;
23813 	queue_t		*wq;
23814 	stp = STREAM(q);
23815 
23816 	/*
23817 	 * At this point change of a queue parameter is not allowed
23818 	 * when a multiplexor is sitting on top.
23819 	 */
23820 	if (stp->sd_flag & STPLEX)
23821 		return (0);
23822 
23823 	claimstr(stp->sd_wrq);
23824 	wq = stp->sd_wrq->q_next;
23825 	ASSERT(wq != NULL);
23826 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23827 	releasestr(stp->sd_wrq);
23828 	return (1);
23829 }
23830 
23831 static int
23832 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23833     int *t_errorp, int *sys_errorp)
23834 {
23835 	int error;
23836 	int is_absreq_failure;
23837 	t_scalar_t *opt_lenp;
23838 	t_scalar_t opt_offset;
23839 	int prim_type;
23840 	struct T_conn_req *tcreqp;
23841 	struct T_conn_res *tcresp;
23842 	cred_t *cr;
23843 
23844 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23845 
23846 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23847 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23848 	    prim_type == T_CONN_RES);
23849 
23850 	switch (prim_type) {
23851 	case T_CONN_REQ:
23852 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23853 		opt_offset = tcreqp->OPT_offset;
23854 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23855 		break;
23856 	case O_T_CONN_RES:
23857 	case T_CONN_RES:
23858 		tcresp = (struct T_conn_res *)mp->b_rptr;
23859 		opt_offset = tcresp->OPT_offset;
23860 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23861 		break;
23862 	}
23863 
23864 	*t_errorp = 0;
23865 	*sys_errorp = 0;
23866 	*do_disconnectp = 0;
23867 
23868 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23869 	    opt_offset, cr, &tcp_opt_obj,
23870 	    NULL, &is_absreq_failure);
23871 
23872 	switch (error) {
23873 	case  0:		/* no error */
23874 		ASSERT(is_absreq_failure == 0);
23875 		return (0);
23876 	case ENOPROTOOPT:
23877 		*t_errorp = TBADOPT;
23878 		break;
23879 	case EACCES:
23880 		*t_errorp = TACCES;
23881 		break;
23882 	default:
23883 		*t_errorp = TSYSERR; *sys_errorp = error;
23884 		break;
23885 	}
23886 	if (is_absreq_failure != 0) {
23887 		/*
23888 		 * The connection request should get the local ack
23889 		 * T_OK_ACK and then a T_DISCON_IND.
23890 		 */
23891 		*do_disconnectp = 1;
23892 	}
23893 	return (-1);
23894 }
23895 
23896 /*
23897  * Split this function out so that if the secret changes, I'm okay.
23898  *
23899  * Initialize the tcp_iss_cookie and tcp_iss_key.
23900  */
23901 
23902 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23903 
23904 static void
23905 tcp_iss_key_init(uint8_t *phrase, int len)
23906 {
23907 	struct {
23908 		int32_t current_time;
23909 		uint32_t randnum;
23910 		uint16_t pad;
23911 		uint8_t ether[6];
23912 		uint8_t passwd[PASSWD_SIZE];
23913 	} tcp_iss_cookie;
23914 	time_t t;
23915 
23916 	/*
23917 	 * Start with the current absolute time.
23918 	 */
23919 	(void) drv_getparm(TIME, &t);
23920 	tcp_iss_cookie.current_time = t;
23921 
23922 	/*
23923 	 * XXX - Need a more random number per RFC 1750, not this crap.
23924 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23925 	 */
23926 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23927 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23928 
23929 	/*
23930 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23931 	 * as a good template.
23932 	 */
23933 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23934 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23935 
23936 	/*
23937 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23938 	 */
23939 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23940 
23941 	/*
23942 	 * See 4010593 if this section becomes a problem again,
23943 	 * but the local ethernet address is useful here.
23944 	 */
23945 	(void) localetheraddr(NULL,
23946 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23947 
23948 	/*
23949 	 * Hash 'em all together.  The MD5Final is called per-connection.
23950 	 */
23951 	mutex_enter(&tcp_iss_key_lock);
23952 	MD5Init(&tcp_iss_key);
23953 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23954 	    sizeof (tcp_iss_cookie));
23955 	mutex_exit(&tcp_iss_key_lock);
23956 }
23957 
23958 /*
23959  * Set the RFC 1948 pass phrase
23960  */
23961 /* ARGSUSED */
23962 static int
23963 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23964     cred_t *cr)
23965 {
23966 	/*
23967 	 * Basically, value contains a new pass phrase.  Pass it along!
23968 	 */
23969 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23970 	return (0);
23971 }
23972 
23973 /* ARGSUSED */
23974 static int
23975 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23976 {
23977 	bzero(buf, sizeof (tcp_sack_info_t));
23978 	return (0);
23979 }
23980 
23981 /* ARGSUSED */
23982 static int
23983 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23984 {
23985 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23986 	return (0);
23987 }
23988 
23989 void
23990 tcp_ddi_init(void)
23991 {
23992 	int i;
23993 
23994 	/* Initialize locks */
23995 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23996 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23997 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23998 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23999 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24000 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
24001 
24002 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24003 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
24004 		    MUTEX_DEFAULT, NULL);
24005 	}
24006 
24007 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24008 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
24009 		    MUTEX_DEFAULT, NULL);
24010 	}
24011 
24012 	/* TCP's IPsec code calls the packet dropper. */
24013 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
24014 
24015 	if (!tcp_g_nd) {
24016 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
24017 			nd_free(&tcp_g_nd);
24018 		}
24019 	}
24020 
24021 	/*
24022 	 * Note: To really walk the device tree you need the devinfo
24023 	 * pointer to your device which is only available after probe/attach.
24024 	 * The following is safe only because it uses ddi_root_node()
24025 	 */
24026 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24027 	    tcp_opt_obj.odb_opt_arr_cnt);
24028 
24029 	tcp_timercache = kmem_cache_create("tcp_timercache",
24030 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24031 	    NULL, NULL, NULL, NULL, NULL, 0);
24032 
24033 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24034 	    sizeof (tcp_sack_info_t), 0,
24035 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24036 
24037 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24038 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24039 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24040 
24041 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24042 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24043 
24044 	ip_squeue_init(tcp_squeue_add);
24045 
24046 	/* Initialize the random number generator */
24047 	tcp_random_init();
24048 
24049 	/*
24050 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24051 	 * by the boot scripts.
24052 	 *
24053 	 * Use NULL name, as the name is caught by the new lockstats.
24054 	 *
24055 	 * Initialize with some random, non-guessable string, like the global
24056 	 * T_INFO_ACK.
24057 	 */
24058 
24059 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24060 	    sizeof (tcp_g_t_info_ack));
24061 
24062 #if TCP_COUNTERS || TCP_DEBUG_COUNTER
24063 	if ((tcp_kstat = kstat_create("tcp", 0, "tcpstat",
24064 		"net", KSTAT_TYPE_NAMED,
24065 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
24066 		KSTAT_FLAG_VIRTUAL)) != NULL) {
24067 		tcp_kstat->ks_data = &tcp_statistics;
24068 		kstat_install(tcp_kstat);
24069 	}
24070 #endif
24071 	tcp_kstat_init();
24072 }
24073 
24074 void
24075 tcp_ddi_destroy(void)
24076 {
24077 	int i;
24078 
24079 	nd_free(&tcp_g_nd);
24080 
24081 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24082 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
24083 	}
24084 
24085 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24086 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
24087 	}
24088 
24089 	mutex_destroy(&tcp_iss_key_lock);
24090 	rw_destroy(&tcp_hsp_lock);
24091 	mutex_destroy(&tcp_g_q_lock);
24092 	mutex_destroy(&tcp_random_lock);
24093 	mutex_destroy(&tcp_epriv_port_lock);
24094 	rw_destroy(&tcp_reserved_port_lock);
24095 
24096 	ip_drop_unregister(&tcp_dropper);
24097 
24098 	kmem_cache_destroy(tcp_timercache);
24099 	kmem_cache_destroy(tcp_sack_info_cache);
24100 	kmem_cache_destroy(tcp_iphc_cache);
24101 
24102 	tcp_kstat_fini();
24103 }
24104 
24105 /*
24106  * Generate ISS, taking into account NDD changes may happen halfway through.
24107  * (If the iss is not zero, set it.)
24108  */
24109 
24110 static void
24111 tcp_iss_init(tcp_t *tcp)
24112 {
24113 	MD5_CTX context;
24114 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24115 	uint32_t answer[4];
24116 
24117 	tcp_iss_incr_extra += (ISS_INCR >> 1);
24118 	tcp->tcp_iss = tcp_iss_incr_extra;
24119 	switch (tcp_strong_iss) {
24120 	case 2:
24121 		mutex_enter(&tcp_iss_key_lock);
24122 		context = tcp_iss_key;
24123 		mutex_exit(&tcp_iss_key_lock);
24124 		arg.ports = tcp->tcp_ports;
24125 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24126 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24127 			    &arg.src);
24128 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24129 			    &arg.dst);
24130 		} else {
24131 			arg.src = tcp->tcp_ip6h->ip6_src;
24132 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24133 		}
24134 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24135 		MD5Final((uchar_t *)answer, &context);
24136 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24137 		/*
24138 		 * Now that we've hashed into a unique per-connection sequence
24139 		 * space, add a random increment per strong_iss == 1.  So I
24140 		 * guess we'll have to...
24141 		 */
24142 		/* FALLTHRU */
24143 	case 1:
24144 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24145 		break;
24146 	default:
24147 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24148 		break;
24149 	}
24150 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24151 	tcp->tcp_fss = tcp->tcp_iss - 1;
24152 	tcp->tcp_suna = tcp->tcp_iss;
24153 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24154 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24155 	tcp->tcp_csuna = tcp->tcp_snxt;
24156 }
24157 
24158 /*
24159  * Exported routine for extracting active tcp connection status.
24160  *
24161  * This is used by the Solaris Cluster Networking software to
24162  * gather a list of connections that need to be forwarded to
24163  * specific nodes in the cluster when configuration changes occur.
24164  *
24165  * The callback is invoked for each tcp_t structure. Returning
24166  * non-zero from the callback routine terminates the search.
24167  */
24168 int
24169 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
24170 {
24171 	tcp_t *tcp;
24172 	cl_tcp_info_t	cl_tcpi;
24173 	connf_t	*connfp;
24174 	conn_t	*connp;
24175 	int	i;
24176 
24177 	ASSERT(callback != NULL);
24178 
24179 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24180 
24181 		connfp = &ipcl_globalhash_fanout[i];
24182 		connp = NULL;
24183 
24184 		while ((connp = tcp_get_next_conn(connfp, connp))) {
24185 
24186 			tcp = connp->conn_tcp;
24187 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24188 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24189 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24190 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24191 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24192 			/*
24193 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24194 			 * addresses. They are copied implicitly below as
24195 			 * mapped addresses.
24196 			 */
24197 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24198 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24199 				cl_tcpi.cl_tcpi_faddr =
24200 				    tcp->tcp_ipha->ipha_dst;
24201 			} else {
24202 				cl_tcpi.cl_tcpi_faddr_v6 =
24203 				    tcp->tcp_ip6h->ip6_dst;
24204 			}
24205 
24206 			/*
24207 			 * If the callback returns non-zero
24208 			 * we terminate the traversal.
24209 			 */
24210 			if ((*callback)(&cl_tcpi, arg) != 0) {
24211 				CONN_DEC_REF(tcp->tcp_connp);
24212 				return (1);
24213 			}
24214 		}
24215 	}
24216 
24217 	return (0);
24218 }
24219 
24220 /*
24221  * Macros used for accessing the different types of sockaddr
24222  * structures inside a tcp_ioc_abort_conn_t.
24223  */
24224 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24225 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24226 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24227 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24228 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24229 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24230 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24231 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24232 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24233 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24234 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24235 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24236 
24237 /*
24238  * Return the correct error code to mimic the behavior
24239  * of a connection reset.
24240  */
24241 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24242 		switch ((state)) {		\
24243 		case TCPS_SYN_SENT:		\
24244 		case TCPS_SYN_RCVD:		\
24245 			(err) = ECONNREFUSED;	\
24246 			break;			\
24247 		case TCPS_ESTABLISHED:		\
24248 		case TCPS_FIN_WAIT_1:		\
24249 		case TCPS_FIN_WAIT_2:		\
24250 		case TCPS_CLOSE_WAIT:		\
24251 			(err) = ECONNRESET;	\
24252 			break;			\
24253 		case TCPS_CLOSING:		\
24254 		case TCPS_LAST_ACK:		\
24255 		case TCPS_TIME_WAIT:		\
24256 			(err) = 0;		\
24257 			break;			\
24258 		default:			\
24259 			(err) = ENXIO;		\
24260 		}				\
24261 	}
24262 
24263 /*
24264  * Check if a tcp structure matches the info in acp.
24265  */
24266 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24267 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24268 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24269 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24270 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24271 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24272 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24273 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24274 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24275 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24276 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24277 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24278 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24279 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24280 	&(tcp)->tcp_ip_src_v6)) &&				\
24281 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24282 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24283 	&(tcp)->tcp_remote_v6)) &&				\
24284 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24285 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24286 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24287 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24288 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24289 	(acp)->ac_end >= (tcp)->tcp_state))
24290 
24291 #define	TCP_AC_MATCH(acp, tcp)					\
24292 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24293 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24294 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24295 
24296 /*
24297  * Build a message containing a tcp_ioc_abort_conn_t structure
24298  * which is filled in with information from acp and tp.
24299  */
24300 static mblk_t *
24301 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24302 {
24303 	mblk_t *mp;
24304 	tcp_ioc_abort_conn_t *tacp;
24305 
24306 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24307 	if (mp == NULL)
24308 		return (NULL);
24309 
24310 	mp->b_datap->db_type = M_CTL;
24311 
24312 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24313 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24314 		sizeof (uint32_t));
24315 
24316 	tacp->ac_start = acp->ac_start;
24317 	tacp->ac_end = acp->ac_end;
24318 	tacp->ac_zoneid = acp->ac_zoneid;
24319 
24320 	if (acp->ac_local.ss_family == AF_INET) {
24321 		tacp->ac_local.ss_family = AF_INET;
24322 		tacp->ac_remote.ss_family = AF_INET;
24323 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24324 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24325 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24326 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24327 	} else {
24328 		tacp->ac_local.ss_family = AF_INET6;
24329 		tacp->ac_remote.ss_family = AF_INET6;
24330 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24331 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24332 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24333 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24334 	}
24335 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24336 	return (mp);
24337 }
24338 
24339 /*
24340  * Print a tcp_ioc_abort_conn_t structure.
24341  */
24342 static void
24343 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24344 {
24345 	char lbuf[128];
24346 	char rbuf[128];
24347 	sa_family_t af;
24348 	in_port_t lport, rport;
24349 	ushort_t logflags;
24350 
24351 	af = acp->ac_local.ss_family;
24352 
24353 	if (af == AF_INET) {
24354 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24355 				lbuf, 128);
24356 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24357 				rbuf, 128);
24358 		lport = ntohs(TCP_AC_V4LPORT(acp));
24359 		rport = ntohs(TCP_AC_V4RPORT(acp));
24360 	} else {
24361 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24362 				lbuf, 128);
24363 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24364 				rbuf, 128);
24365 		lport = ntohs(TCP_AC_V6LPORT(acp));
24366 		rport = ntohs(TCP_AC_V6RPORT(acp));
24367 	}
24368 
24369 	logflags = SL_TRACE | SL_NOTE;
24370 	/*
24371 	 * Don't print this message to the console if the operation was done
24372 	 * to a non-global zone.
24373 	 */
24374 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24375 		logflags |= SL_CONSOLE;
24376 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags,
24377 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24378 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24379 		acp->ac_start, acp->ac_end);
24380 }
24381 
24382 /*
24383  * Called inside tcp_rput when a message built using
24384  * tcp_ioctl_abort_build_msg is put into a queue.
24385  * Note that when we get here there is no wildcard in acp any more.
24386  */
24387 static void
24388 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24389 {
24390 	tcp_ioc_abort_conn_t *acp;
24391 
24392 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24393 	if (tcp->tcp_state <= acp->ac_end) {
24394 		/*
24395 		 * If we get here, we are already on the correct
24396 		 * squeue. This ioctl follows the following path
24397 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24398 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24399 		 * different squeue)
24400 		 */
24401 		int errcode;
24402 
24403 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24404 		(void) tcp_clean_death(tcp, errcode, 26);
24405 	}
24406 	freemsg(mp);
24407 }
24408 
24409 /*
24410  * Abort all matching connections on a hash chain.
24411  */
24412 static int
24413 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24414     boolean_t exact)
24415 {
24416 	int nmatch, err = 0;
24417 	tcp_t *tcp;
24418 	MBLKP mp, last, listhead = NULL;
24419 	conn_t	*tconnp;
24420 	connf_t	*connfp = &ipcl_conn_fanout[index];
24421 
24422 startover:
24423 	nmatch = 0;
24424 
24425 	mutex_enter(&connfp->connf_lock);
24426 	for (tconnp = connfp->connf_head; tconnp != NULL;
24427 	    tconnp = tconnp->conn_next) {
24428 		tcp = tconnp->conn_tcp;
24429 		if (TCP_AC_MATCH(acp, tcp)) {
24430 			CONN_INC_REF(tcp->tcp_connp);
24431 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24432 			if (mp == NULL) {
24433 				err = ENOMEM;
24434 				CONN_DEC_REF(tcp->tcp_connp);
24435 				break;
24436 			}
24437 			mp->b_prev = (mblk_t *)tcp;
24438 
24439 			if (listhead == NULL) {
24440 				listhead = mp;
24441 				last = mp;
24442 			} else {
24443 				last->b_next = mp;
24444 				last = mp;
24445 			}
24446 			nmatch++;
24447 			if (exact)
24448 				break;
24449 		}
24450 
24451 		/* Avoid holding lock for too long. */
24452 		if (nmatch >= 500)
24453 			break;
24454 	}
24455 	mutex_exit(&connfp->connf_lock);
24456 
24457 	/* Pass mp into the correct tcp */
24458 	while ((mp = listhead) != NULL) {
24459 		listhead = listhead->b_next;
24460 		tcp = (tcp_t *)mp->b_prev;
24461 		mp->b_next = mp->b_prev = NULL;
24462 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24463 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24464 	}
24465 
24466 	*count += nmatch;
24467 	if (nmatch >= 500 && err == 0)
24468 		goto startover;
24469 	return (err);
24470 }
24471 
24472 /*
24473  * Abort all connections that matches the attributes specified in acp.
24474  */
24475 static int
24476 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24477 {
24478 	sa_family_t af;
24479 	uint32_t  ports;
24480 	uint16_t *pports;
24481 	int err = 0, count = 0;
24482 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24483 	int index = -1;
24484 	ushort_t logflags;
24485 
24486 	af = acp->ac_local.ss_family;
24487 
24488 	if (af == AF_INET) {
24489 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24490 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24491 			pports = (uint16_t *)&ports;
24492 			pports[1] = TCP_AC_V4LPORT(acp);
24493 			pports[0] = TCP_AC_V4RPORT(acp);
24494 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24495 		}
24496 	} else {
24497 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24498 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24499 			pports = (uint16_t *)&ports;
24500 			pports[1] = TCP_AC_V6LPORT(acp);
24501 			pports[0] = TCP_AC_V6RPORT(acp);
24502 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24503 		}
24504 	}
24505 
24506 	/*
24507 	 * For cases where remote addr, local port, and remote port are non-
24508 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24509 	 */
24510 	if (index != -1) {
24511 		err = tcp_ioctl_abort_bucket(acp, index,
24512 			    &count, exact);
24513 	} else {
24514 		/*
24515 		 * loop through all entries for wildcard case
24516 		 */
24517 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24518 			err = tcp_ioctl_abort_bucket(acp, index,
24519 			    &count, exact);
24520 			if (err != 0)
24521 				break;
24522 		}
24523 	}
24524 
24525 	logflags = SL_TRACE | SL_NOTE;
24526 	/*
24527 	 * Don't print this message to the console if the operation was done
24528 	 * to a non-global zone.
24529 	 */
24530 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24531 		logflags |= SL_CONSOLE;
24532 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24533 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24534 	if (err == 0 && count == 0)
24535 		err = ENOENT;
24536 	return (err);
24537 }
24538 
24539 /*
24540  * Process the TCP_IOC_ABORT_CONN ioctl request.
24541  */
24542 static void
24543 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24544 {
24545 	int	err;
24546 	IOCP    iocp;
24547 	MBLKP   mp1;
24548 	sa_family_t laf, raf;
24549 	tcp_ioc_abort_conn_t *acp;
24550 	zone_t *zptr;
24551 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24552 
24553 	iocp = (IOCP)mp->b_rptr;
24554 
24555 	if ((mp1 = mp->b_cont) == NULL ||
24556 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24557 		err = EINVAL;
24558 		goto out;
24559 	}
24560 
24561 	/* check permissions */
24562 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24563 		err = EPERM;
24564 		goto out;
24565 	}
24566 
24567 	if (mp1->b_cont != NULL) {
24568 		freemsg(mp1->b_cont);
24569 		mp1->b_cont = NULL;
24570 	}
24571 
24572 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24573 	laf = acp->ac_local.ss_family;
24574 	raf = acp->ac_remote.ss_family;
24575 
24576 	/* check that a zone with the supplied zoneid exists */
24577 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24578 		zptr = zone_find_by_id(zoneid);
24579 		if (zptr != NULL) {
24580 			zone_rele(zptr);
24581 		} else {
24582 			err = EINVAL;
24583 			goto out;
24584 		}
24585 	}
24586 
24587 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24588 	    acp->ac_start > acp->ac_end || laf != raf ||
24589 	    (laf != AF_INET && laf != AF_INET6)) {
24590 		err = EINVAL;
24591 		goto out;
24592 	}
24593 
24594 	tcp_ioctl_abort_dump(acp);
24595 	err = tcp_ioctl_abort(acp);
24596 
24597 out:
24598 	if (mp1 != NULL) {
24599 		freemsg(mp1);
24600 		mp->b_cont = NULL;
24601 	}
24602 
24603 	if (err != 0)
24604 		miocnak(q, mp, 0, err);
24605 	else
24606 		miocack(q, mp, 0, 0);
24607 }
24608 
24609 /*
24610  * tcp_time_wait_processing() handles processing of incoming packets when
24611  * the tcp is in the TIME_WAIT state.
24612  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24613  * on the time wait list.
24614  */
24615 void
24616 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24617     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24618 {
24619 	int32_t		bytes_acked;
24620 	int32_t		gap;
24621 	int32_t		rgap;
24622 	tcp_opt_t	tcpopt;
24623 	uint_t		flags;
24624 	uint32_t	new_swnd = 0;
24625 	conn_t		*connp;
24626 
24627 	BUMP_LOCAL(tcp->tcp_ibsegs);
24628 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24629 
24630 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24631 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24632 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24633 	if (tcp->tcp_snd_ts_ok) {
24634 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24635 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24636 			    tcp->tcp_rnxt, TH_ACK);
24637 			goto done;
24638 		}
24639 	}
24640 	gap = seg_seq - tcp->tcp_rnxt;
24641 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24642 	if (gap < 0) {
24643 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24644 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24645 		    (seg_len > -gap ? -gap : seg_len));
24646 		seg_len += gap;
24647 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24648 			if (flags & TH_RST) {
24649 				goto done;
24650 			}
24651 			if ((flags & TH_FIN) && seg_len == -1) {
24652 				/*
24653 				 * When TCP receives a duplicate FIN in
24654 				 * TIME_WAIT state, restart the 2 MSL timer.
24655 				 * See page 73 in RFC 793. Make sure this TCP
24656 				 * is already on the TIME_WAIT list. If not,
24657 				 * just restart the timer.
24658 				 */
24659 				if (TCP_IS_DETACHED(tcp)) {
24660 					tcp_time_wait_remove(tcp, NULL);
24661 					tcp_time_wait_append(tcp);
24662 					TCP_DBGSTAT(tcp_rput_time_wait);
24663 				} else {
24664 					ASSERT(tcp != NULL);
24665 					TCP_TIMER_RESTART(tcp,
24666 					    tcp_time_wait_interval);
24667 				}
24668 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24669 				    tcp->tcp_rnxt, TH_ACK);
24670 				goto done;
24671 			}
24672 			flags |=  TH_ACK_NEEDED;
24673 			seg_len = 0;
24674 			goto process_ack;
24675 		}
24676 
24677 		/* Fix seg_seq, and chew the gap off the front. */
24678 		seg_seq = tcp->tcp_rnxt;
24679 	}
24680 
24681 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24682 		/*
24683 		 * Make sure that when we accept the connection, pick
24684 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24685 		 * old connection.
24686 		 *
24687 		 * The next ISS generated is equal to tcp_iss_incr_extra
24688 		 * + ISS_INCR/2 + other components depending on the
24689 		 * value of tcp_strong_iss.  We pre-calculate the new
24690 		 * ISS here and compare with tcp_snxt to determine if
24691 		 * we need to make adjustment to tcp_iss_incr_extra.
24692 		 *
24693 		 * The above calculation is ugly and is a
24694 		 * waste of CPU cycles...
24695 		 */
24696 		uint32_t new_iss = tcp_iss_incr_extra;
24697 		int32_t adj;
24698 
24699 		switch (tcp_strong_iss) {
24700 		case 2: {
24701 			/* Add time and MD5 components. */
24702 			uint32_t answer[4];
24703 			struct {
24704 				uint32_t ports;
24705 				in6_addr_t src;
24706 				in6_addr_t dst;
24707 			} arg;
24708 			MD5_CTX context;
24709 
24710 			mutex_enter(&tcp_iss_key_lock);
24711 			context = tcp_iss_key;
24712 			mutex_exit(&tcp_iss_key_lock);
24713 			arg.ports = tcp->tcp_ports;
24714 			/* We use MAPPED addresses in tcp_iss_init */
24715 			arg.src = tcp->tcp_ip_src_v6;
24716 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24717 				IN6_IPADDR_TO_V4MAPPED(
24718 					tcp->tcp_ipha->ipha_dst,
24719 					    &arg.dst);
24720 			} else {
24721 				arg.dst =
24722 				    tcp->tcp_ip6h->ip6_dst;
24723 			}
24724 			MD5Update(&context, (uchar_t *)&arg,
24725 			    sizeof (arg));
24726 			MD5Final((uchar_t *)answer, &context);
24727 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24728 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24729 			break;
24730 		}
24731 		case 1:
24732 			/* Add time component and min random (i.e. 1). */
24733 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24734 			break;
24735 		default:
24736 			/* Add only time component. */
24737 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24738 			break;
24739 		}
24740 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24741 			/*
24742 			 * New ISS not guaranteed to be ISS_INCR/2
24743 			 * ahead of the current tcp_snxt, so add the
24744 			 * difference to tcp_iss_incr_extra.
24745 			 */
24746 			tcp_iss_incr_extra += adj;
24747 		}
24748 		/*
24749 		 * If tcp_clean_death() can not perform the task now,
24750 		 * drop the SYN packet and let the other side re-xmit.
24751 		 * Otherwise pass the SYN packet back in, since the
24752 		 * old tcp state has been cleaned up or freed.
24753 		 */
24754 		if (tcp_clean_death(tcp, 0, 27) == -1)
24755 			goto done;
24756 		/*
24757 		 * We will come back to tcp_rput_data
24758 		 * on the global queue. Packets destined
24759 		 * for the global queue will be checked
24760 		 * with global policy. But the policy for
24761 		 * this packet has already been checked as
24762 		 * this was destined for the detached
24763 		 * connection. We need to bypass policy
24764 		 * check this time by attaching a dummy
24765 		 * ipsec_in with ipsec_in_dont_check set.
24766 		 */
24767 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24768 		    NULL) {
24769 			TCP_STAT(tcp_time_wait_syn_success);
24770 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24771 			return;
24772 		}
24773 		goto done;
24774 	}
24775 
24776 	/*
24777 	 * rgap is the amount of stuff received out of window.  A negative
24778 	 * value is the amount out of window.
24779 	 */
24780 	if (rgap < 0) {
24781 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24782 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24783 		/* Fix seg_len and make sure there is something left. */
24784 		seg_len += rgap;
24785 		if (seg_len <= 0) {
24786 			if (flags & TH_RST) {
24787 				goto done;
24788 			}
24789 			flags |=  TH_ACK_NEEDED;
24790 			seg_len = 0;
24791 			goto process_ack;
24792 		}
24793 	}
24794 	/*
24795 	 * Check whether we can update tcp_ts_recent.  This test is
24796 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24797 	 * Extensions for High Performance: An Update", Internet Draft.
24798 	 */
24799 	if (tcp->tcp_snd_ts_ok &&
24800 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24801 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24802 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24803 		tcp->tcp_last_rcv_lbolt = lbolt64;
24804 	}
24805 
24806 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24807 		/* Always ack out of order packets */
24808 		flags |= TH_ACK_NEEDED;
24809 		seg_len = 0;
24810 	} else if (seg_len > 0) {
24811 		BUMP_MIB(&tcp_mib, tcpInClosed);
24812 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24813 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24814 	}
24815 	if (flags & TH_RST) {
24816 		(void) tcp_clean_death(tcp, 0, 28);
24817 		goto done;
24818 	}
24819 	if (flags & TH_SYN) {
24820 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24821 		    TH_RST|TH_ACK);
24822 		/*
24823 		 * Do not delete the TCP structure if it is in
24824 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24825 		 */
24826 		goto done;
24827 	}
24828 process_ack:
24829 	if (flags & TH_ACK) {
24830 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24831 		if (bytes_acked <= 0) {
24832 			if (bytes_acked == 0 && seg_len == 0 &&
24833 			    new_swnd == tcp->tcp_swnd)
24834 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24835 		} else {
24836 			/* Acks something not sent */
24837 			flags |= TH_ACK_NEEDED;
24838 		}
24839 	}
24840 	if (flags & TH_ACK_NEEDED) {
24841 		/*
24842 		 * Time to send an ack for some reason.
24843 		 */
24844 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24845 		    tcp->tcp_rnxt, TH_ACK);
24846 	}
24847 done:
24848 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24849 		mp->b_datap->db_cksumstart = 0;
24850 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24851 		TCP_STAT(tcp_time_wait_syn_fail);
24852 	}
24853 	freemsg(mp);
24854 }
24855 
24856 /*
24857  * Return zero if the buffers are identical in length and content.
24858  * This is used for comparing extension header buffers.
24859  * Note that an extension header would be declared different
24860  * even if all that changed was the next header value in that header i.e.
24861  * what really changed is the next extension header.
24862  */
24863 static boolean_t
24864 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24865 {
24866 	if (!b_valid)
24867 		blen = 0;
24868 
24869 	if (alen != blen)
24870 		return (B_TRUE);
24871 	if (alen == 0)
24872 		return (B_FALSE);	/* Both zero length */
24873 	return (bcmp(a, b, alen));
24874 }
24875 
24876 /*
24877  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24878  * Return B_FALSE if memory allocation fails - don't change any state!
24879  */
24880 static boolean_t
24881 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24882     void *src, uint_t srclen)
24883 {
24884 	void *dst;
24885 
24886 	if (!src_valid)
24887 		srclen = 0;
24888 
24889 	ASSERT(*dstlenp == 0);
24890 	if (src != NULL && srclen != 0) {
24891 		dst = mi_alloc(srclen, BPRI_MED);
24892 		if (dst == NULL)
24893 			return (B_FALSE);
24894 	} else {
24895 		dst = NULL;
24896 	}
24897 	if (*dstp != NULL) {
24898 		mi_free(*dstp);
24899 		*dstp = NULL;
24900 		*dstlenp = 0;
24901 	}
24902 	*dstp = dst;
24903 	if (dst != NULL)
24904 		*dstlenp = srclen;
24905 	else
24906 		*dstlenp = 0;
24907 	return (B_TRUE);
24908 }
24909 
24910 /*
24911  * Replace what is in *dst, *dstlen with the source.
24912  * Assumes tcp_allocbuf has already been called.
24913  */
24914 static void
24915 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24916     void *src, uint_t srclen)
24917 {
24918 	if (!src_valid)
24919 		srclen = 0;
24920 
24921 	ASSERT(*dstlenp == srclen);
24922 	if (src != NULL && srclen != 0) {
24923 		bcopy(src, *dstp, srclen);
24924 	}
24925 }
24926 
24927 /*
24928  * Allocate a T_SVR4_OPTMGMT_REQ.
24929  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24930  * that tcp_rput_other can drop the acks.
24931  */
24932 static mblk_t *
24933 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24934 {
24935 	mblk_t *mp;
24936 	struct T_optmgmt_req *tor;
24937 	struct opthdr *oh;
24938 	uint_t size;
24939 	char *optptr;
24940 
24941 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24942 	mp = allocb(size, BPRI_MED);
24943 	if (mp == NULL)
24944 		return (NULL);
24945 
24946 	mp->b_wptr += size;
24947 	mp->b_datap->db_type = M_PROTO;
24948 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24949 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24950 	tor->MGMT_flags = T_NEGOTIATE;
24951 	tor->OPT_length = sizeof (*oh) + optlen;
24952 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24953 
24954 	oh = (struct opthdr *)&tor[1];
24955 	oh->level = level;
24956 	oh->name = cmd;
24957 	oh->len = optlen;
24958 	if (optlen != 0) {
24959 		optptr = (char *)&oh[1];
24960 		bcopy(opt, optptr, optlen);
24961 	}
24962 	return (mp);
24963 }
24964 
24965 /*
24966  * TCP Timers Implementation.
24967  */
24968 static timeout_id_t
24969 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24970 {
24971 	mblk_t *mp;
24972 	tcp_timer_t *tcpt;
24973 	tcp_t *tcp = connp->conn_tcp;
24974 
24975 	ASSERT(connp->conn_sqp != NULL);
24976 
24977 	TCP_DBGSTAT(tcp_timeout_calls);
24978 
24979 	if (tcp->tcp_timercache == NULL) {
24980 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24981 	} else {
24982 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24983 		mp = tcp->tcp_timercache;
24984 		tcp->tcp_timercache = mp->b_next;
24985 		mp->b_next = NULL;
24986 		ASSERT(mp->b_wptr == NULL);
24987 	}
24988 
24989 	CONN_INC_REF(connp);
24990 	tcpt = (tcp_timer_t *)mp->b_rptr;
24991 	tcpt->connp = connp;
24992 	tcpt->tcpt_proc = f;
24993 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24994 	return ((timeout_id_t)mp);
24995 }
24996 
24997 static void
24998 tcp_timer_callback(void *arg)
24999 {
25000 	mblk_t *mp = (mblk_t *)arg;
25001 	tcp_timer_t *tcpt;
25002 	conn_t	*connp;
25003 
25004 	tcpt = (tcp_timer_t *)mp->b_rptr;
25005 	connp = tcpt->connp;
25006 	squeue_fill(connp->conn_sqp, mp,
25007 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25008 }
25009 
25010 static void
25011 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25012 {
25013 	tcp_timer_t *tcpt;
25014 	conn_t *connp = (conn_t *)arg;
25015 	tcp_t *tcp = connp->conn_tcp;
25016 
25017 	tcpt = (tcp_timer_t *)mp->b_rptr;
25018 	ASSERT(connp == tcpt->connp);
25019 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25020 
25021 	/*
25022 	 * If the TCP has reached the closed state, don't proceed any
25023 	 * further. This TCP logically does not exist on the system.
25024 	 * tcpt_proc could for example access queues, that have already
25025 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25026 	 */
25027 	if (tcp->tcp_state != TCPS_CLOSED) {
25028 		(*tcpt->tcpt_proc)(connp);
25029 	} else {
25030 		tcp->tcp_timer_tid = 0;
25031 	}
25032 	tcp_timer_free(connp->conn_tcp, mp);
25033 }
25034 
25035 /*
25036  * There is potential race with untimeout and the handler firing at the same
25037  * time. The mblock may be freed by the handler while we are trying to use
25038  * it. But since both should execute on the same squeue, this race should not
25039  * occur.
25040  */
25041 static clock_t
25042 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25043 {
25044 	mblk_t	*mp = (mblk_t *)id;
25045 	tcp_timer_t *tcpt;
25046 	clock_t delta;
25047 
25048 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
25049 
25050 	if (mp == NULL)
25051 		return (-1);
25052 
25053 	tcpt = (tcp_timer_t *)mp->b_rptr;
25054 	ASSERT(tcpt->connp == connp);
25055 
25056 	delta = untimeout(tcpt->tcpt_tid);
25057 
25058 	if (delta >= 0) {
25059 		TCP_DBGSTAT(tcp_timeout_canceled);
25060 		tcp_timer_free(connp->conn_tcp, mp);
25061 		CONN_DEC_REF(connp);
25062 	}
25063 
25064 	return (delta);
25065 }
25066 
25067 /*
25068  * Allocate space for the timer event. The allocation looks like mblk, but it is
25069  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25070  *
25071  * Dealing with failures: If we can't allocate from the timer cache we try
25072  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25073  * points to b_rptr.
25074  * If we can't allocate anything using allocb_tryhard(), we perform a last
25075  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25076  * save the actual allocation size in b_datap.
25077  */
25078 mblk_t *
25079 tcp_timermp_alloc(int kmflags)
25080 {
25081 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25082 	    kmflags & ~KM_PANIC);
25083 
25084 	if (mp != NULL) {
25085 		mp->b_next = mp->b_prev = NULL;
25086 		mp->b_rptr = (uchar_t *)(&mp[1]);
25087 		mp->b_wptr = NULL;
25088 		mp->b_datap = NULL;
25089 		mp->b_queue = NULL;
25090 	} else if (kmflags & KM_PANIC) {
25091 		/*
25092 		 * Failed to allocate memory for the timer. Try allocating from
25093 		 * dblock caches.
25094 		 */
25095 		TCP_STAT(tcp_timermp_allocfail);
25096 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25097 		if (mp == NULL) {
25098 			size_t size = 0;
25099 			/*
25100 			 * Memory is really low. Try tryhard allocation.
25101 			 */
25102 			TCP_STAT(tcp_timermp_allocdblfail);
25103 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25104 			    sizeof (tcp_timer_t), &size, kmflags);
25105 			mp->b_rptr = (uchar_t *)(&mp[1]);
25106 			mp->b_next = mp->b_prev = NULL;
25107 			mp->b_wptr = (uchar_t *)-1;
25108 			mp->b_datap = (dblk_t *)size;
25109 			mp->b_queue = NULL;
25110 		}
25111 		ASSERT(mp->b_wptr != NULL);
25112 	}
25113 	TCP_DBGSTAT(tcp_timermp_alloced);
25114 
25115 	return (mp);
25116 }
25117 
25118 /*
25119  * Free per-tcp timer cache.
25120  * It can only contain entries from tcp_timercache.
25121  */
25122 void
25123 tcp_timermp_free(tcp_t *tcp)
25124 {
25125 	mblk_t *mp;
25126 
25127 	while ((mp = tcp->tcp_timercache) != NULL) {
25128 		ASSERT(mp->b_wptr == NULL);
25129 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25130 		kmem_cache_free(tcp_timercache, mp);
25131 	}
25132 }
25133 
25134 /*
25135  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25136  * events there already (currently at most two events are cached).
25137  * If the event is not allocated from the timer cache, free it right away.
25138  */
25139 static void
25140 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25141 {
25142 	mblk_t *mp1 = tcp->tcp_timercache;
25143 
25144 	if (mp->b_wptr != NULL) {
25145 		/*
25146 		 * This allocation is not from a timer cache, free it right
25147 		 * away.
25148 		 */
25149 		if (mp->b_wptr != (uchar_t *)-1)
25150 			freeb(mp);
25151 		else
25152 			kmem_free(mp, (size_t)mp->b_datap);
25153 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25154 		/* Cache this timer block for future allocations */
25155 		mp->b_rptr = (uchar_t *)(&mp[1]);
25156 		mp->b_next = mp1;
25157 		tcp->tcp_timercache = mp;
25158 	} else {
25159 		kmem_cache_free(tcp_timercache, mp);
25160 		TCP_DBGSTAT(tcp_timermp_freed);
25161 	}
25162 }
25163 
25164 /*
25165  * End of TCP Timers implementation.
25166  */
25167 
25168 static void
25169 tcp_setqfull(tcp_t *tcp)
25170 {
25171 	queue_t *q = tcp->tcp_wq;
25172 
25173 	if (!(q->q_flag & QFULL)) {
25174 		TCP_STAT(tcp_flwctl_on);
25175 		mutex_enter(QLOCK(q));
25176 		q->q_flag |= QFULL;
25177 		mutex_exit(QLOCK(q));
25178 	}
25179 }
25180 
25181 static void
25182 tcp_clrqfull(tcp_t *tcp)
25183 {
25184 	queue_t *q = tcp->tcp_wq;
25185 
25186 	if (q->q_flag & QFULL) {
25187 		mutex_enter(QLOCK(q));
25188 		q->q_flag &= ~QFULL;
25189 		mutex_exit(QLOCK(q));
25190 		if (q->q_flag & QWANTW)
25191 			qbackenable(q, 0);
25192 	}
25193 }
25194 
25195 /*
25196  * TCP Kstats implementation
25197  */
25198 static void
25199 tcp_kstat_init(void)
25200 {
25201 	tcp_named_kstat_t template = {
25202 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25203 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25204 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25205 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25206 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25207 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25208 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25209 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25210 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25211 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
25212 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
25213 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25214 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25215 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25216 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25217 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25218 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25219 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25220 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25221 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25222 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25223 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25224 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25225 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25226 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25227 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25228 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25229 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25230 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25231 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25232 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25233 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25234 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25235 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25236 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25237 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25238 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25239 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25240 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25241 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25242 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25243 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25244 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25245 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25246 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25247 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25248 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25249 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25250 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25251 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25252 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25253 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25254 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25255 	};
25256 
25257 	tcp_mibkp = kstat_create("tcp", 0, "tcp", "mib2", KSTAT_TYPE_NAMED,
25258 	    NUM_OF_FIELDS(tcp_named_kstat_t), 0);
25259 
25260 	if (tcp_mibkp == NULL)
25261 		return;
25262 
25263 	template.rtoAlgorithm.value.ui32 = 4;
25264 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
25265 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
25266 	template.maxConn.value.i32 = -1;
25267 
25268 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
25269 
25270 	tcp_mibkp->ks_update = tcp_kstat_update;
25271 
25272 	kstat_install(tcp_mibkp);
25273 }
25274 
25275 static void
25276 tcp_kstat_fini(void)
25277 {
25278 
25279 	if (tcp_mibkp != NULL) {
25280 		kstat_delete(tcp_mibkp);
25281 		tcp_mibkp = NULL;
25282 	}
25283 }
25284 
25285 static int
25286 tcp_kstat_update(kstat_t *kp, int rw)
25287 {
25288 	tcp_named_kstat_t	*tcpkp;
25289 	tcp_t			*tcp;
25290 	connf_t			*connfp;
25291 	conn_t			*connp;
25292 	int 			i;
25293 
25294 	if (!kp || !kp->ks_data)
25295 		return (EIO);
25296 
25297 	if (rw == KSTAT_WRITE)
25298 		return (EACCES);
25299 
25300 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25301 
25302 	tcpkp->currEstab.value.ui32 = 0;
25303 
25304 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25305 		connfp = &ipcl_globalhash_fanout[i];
25306 		connp = NULL;
25307 		while ((connp = tcp_get_next_conn(connfp, connp))) {
25308 			tcp = connp->conn_tcp;
25309 			switch (tcp_snmp_state(tcp)) {
25310 			case MIB2_TCP_established:
25311 			case MIB2_TCP_closeWait:
25312 				tcpkp->currEstab.value.ui32++;
25313 				break;
25314 			}
25315 		}
25316 	}
25317 
25318 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25319 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25320 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25321 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25322 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
25323 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
25324 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25325 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25326 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25327 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25328 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25329 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25330 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25331 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25332 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25333 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25334 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25335 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25336 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25337 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25338 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25339 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25340 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25341 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25342 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25343 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25344 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25345 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25346 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25347 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25348 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25349 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25350 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25351 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25352 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25353 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25354 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25355 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25356 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25357 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25358 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25359 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25360 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25361 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25362 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25363 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25364 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25365 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25366 
25367 	return (0);
25368 }
25369 
25370 void
25371 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25372 {
25373 	uint16_t	hdr_len;
25374 	ipha_t		*ipha;
25375 	uint8_t		*nexthdrp;
25376 	tcph_t		*tcph;
25377 
25378 	/* Already has an eager */
25379 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25380 		TCP_STAT(tcp_reinput_syn);
25381 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25382 		    connp, SQTAG_TCP_REINPUT_EAGER);
25383 		return;
25384 	}
25385 
25386 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25387 	case IPV4_VERSION:
25388 		ipha = (ipha_t *)mp->b_rptr;
25389 		hdr_len = IPH_HDR_LENGTH(ipha);
25390 		break;
25391 	case IPV6_VERSION:
25392 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25393 		    &hdr_len, &nexthdrp)) {
25394 			CONN_DEC_REF(connp);
25395 			freemsg(mp);
25396 			return;
25397 		}
25398 		break;
25399 	}
25400 
25401 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25402 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25403 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25404 		mp->b_datap->db_cksumstart = (intptr_t)sqp;
25405 	}
25406 
25407 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25408 	    SQTAG_TCP_REINPUT);
25409 }
25410 
25411 static squeue_func_t
25412 tcp_squeue_switch(int val)
25413 {
25414 	squeue_func_t rval = squeue_fill;
25415 
25416 	switch (val) {
25417 	case 1:
25418 		rval = squeue_enter_nodrain;
25419 		break;
25420 	case 2:
25421 		rval = squeue_enter;
25422 		break;
25423 	default:
25424 		break;
25425 	}
25426 	return (rval);
25427 }
25428 
25429 static void
25430 tcp_squeue_add(squeue_t *sqp)
25431 {
25432 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25433 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25434 
25435 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25436 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25437 	    sqp, TCP_TIME_WAIT_DELAY);
25438 }
25439