xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision cc6c5292fa8a241fe50604cf6a918edfbf7cd7d2)
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_HOPLIMIT:
10224 			if (ipp->ipp_fields & IPPF_HOPLIMIT)
10225 				*i1 = ipp->ipp_hoplimit;
10226 			else
10227 				*i1 = -1; /* Not set */
10228 			break;	/* goto sizeof (int) option return */
10229 		case IPV6_TCLASS:
10230 			if (ipp->ipp_fields & IPPF_TCLASS)
10231 				*i1 = ipp->ipp_tclass;
10232 			else
10233 				*i1 = IPV6_FLOW_TCLASS(
10234 				    IPV6_DEFAULT_VERS_AND_FLOW);
10235 			break;	/* goto sizeof (int) option return */
10236 		case IPV6_NEXTHOP: {
10237 			sin6_t *sin6 = (sin6_t *)ptr;
10238 
10239 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10240 				return (0);
10241 			*sin6 = sin6_null;
10242 			sin6->sin6_family = AF_INET6;
10243 			sin6->sin6_addr = ipp->ipp_nexthop;
10244 			return (sizeof (sin6_t));
10245 		}
10246 		case IPV6_HOPOPTS:
10247 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10248 				return (0);
10249 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
10250 			return (ipp->ipp_hopoptslen);
10251 		case IPV6_RTHDRDSTOPTS:
10252 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10253 				return (0);
10254 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10255 			return (ipp->ipp_rtdstoptslen);
10256 		case IPV6_RTHDR:
10257 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10258 				return (0);
10259 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10260 			return (ipp->ipp_rthdrlen);
10261 		case IPV6_DSTOPTS:
10262 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10263 				return (0);
10264 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10265 			return (ipp->ipp_dstoptslen);
10266 		case IPV6_SRC_PREFERENCES:
10267 			return (ip6_get_src_preferences(connp,
10268 			    (uint32_t *)ptr));
10269 		case IPV6_PATHMTU: {
10270 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10271 
10272 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10273 				return (-1);
10274 
10275 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10276 				connp->conn_fport, mtuinfo));
10277 		}
10278 		default:
10279 			return (-1);
10280 		}
10281 		break;
10282 	default:
10283 		return (-1);
10284 	}
10285 	return (sizeof (int));
10286 }
10287 
10288 /*
10289  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10290  * Parameters are assumed to be verified by the caller.
10291  */
10292 /* ARGSUSED */
10293 int
10294 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10295     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10296     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10297 {
10298 	tcp_t	*tcp = Q_TO_TCP(q);
10299 	int	*i1 = (int *)invalp;
10300 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10301 	boolean_t checkonly;
10302 	int	reterr;
10303 
10304 	switch (optset_context) {
10305 	case SETFN_OPTCOM_CHECKONLY:
10306 		checkonly = B_TRUE;
10307 		/*
10308 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10309 		 * inlen != 0 implies value supplied and
10310 		 * 	we have to "pretend" to set it.
10311 		 * inlen == 0 implies that there is no
10312 		 * 	value part in T_CHECK request and just validation
10313 		 * done elsewhere should be enough, we just return here.
10314 		 */
10315 		if (inlen == 0) {
10316 			*outlenp = 0;
10317 			return (0);
10318 		}
10319 		break;
10320 	case SETFN_OPTCOM_NEGOTIATE:
10321 		checkonly = B_FALSE;
10322 		break;
10323 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10324 	case SETFN_CONN_NEGOTIATE:
10325 		checkonly = B_FALSE;
10326 		/*
10327 		 * Negotiating local and "association-related" options
10328 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10329 		 * primitives is allowed by XTI, but we choose
10330 		 * to not implement this style negotiation for Internet
10331 		 * protocols (We interpret it is a must for OSI world but
10332 		 * optional for Internet protocols) for all options.
10333 		 * [ Will do only for the few options that enable test
10334 		 * suites that our XTI implementation of this feature
10335 		 * works for transports that do allow it ]
10336 		 */
10337 		if (!tcp_allow_connopt_set(level, name)) {
10338 			*outlenp = 0;
10339 			return (EINVAL);
10340 		}
10341 		break;
10342 	default:
10343 		/*
10344 		 * We should never get here
10345 		 */
10346 		*outlenp = 0;
10347 		return (EINVAL);
10348 	}
10349 
10350 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10351 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10352 
10353 	/*
10354 	 * For TCP, we should have no ancillary data sent down
10355 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10356 	 * has to be zero.
10357 	 */
10358 	ASSERT(thisdg_attrs == NULL);
10359 
10360 	/*
10361 	 * For fixed length options, no sanity check
10362 	 * of passed in length is done. It is assumed *_optcom_req()
10363 	 * routines do the right thing.
10364 	 */
10365 
10366 	switch (level) {
10367 	case SOL_SOCKET:
10368 		switch (name) {
10369 		case SO_LINGER: {
10370 			struct linger *lgr = (struct linger *)invalp;
10371 
10372 			if (!checkonly) {
10373 				if (lgr->l_onoff) {
10374 					tcp->tcp_linger = 1;
10375 					tcp->tcp_lingertime = lgr->l_linger;
10376 				} else {
10377 					tcp->tcp_linger = 0;
10378 					tcp->tcp_lingertime = 0;
10379 				}
10380 				/* struct copy */
10381 				*(struct linger *)outvalp = *lgr;
10382 			} else {
10383 				if (!lgr->l_onoff) {
10384 				    ((struct linger *)outvalp)->l_onoff = 0;
10385 				    ((struct linger *)outvalp)->l_linger = 0;
10386 				} else {
10387 				    /* struct copy */
10388 				    *(struct linger *)outvalp = *lgr;
10389 				}
10390 			}
10391 			*outlenp = sizeof (struct linger);
10392 			return (0);
10393 		}
10394 		case SO_DEBUG:
10395 			if (!checkonly)
10396 				tcp->tcp_debug = onoff;
10397 			break;
10398 		case SO_KEEPALIVE:
10399 			if (checkonly) {
10400 				/* T_CHECK case */
10401 				break;
10402 			}
10403 
10404 			if (!onoff) {
10405 				if (tcp->tcp_ka_enabled) {
10406 					if (tcp->tcp_ka_tid != 0) {
10407 						(void) TCP_TIMER_CANCEL(tcp,
10408 						    tcp->tcp_ka_tid);
10409 						tcp->tcp_ka_tid = 0;
10410 					}
10411 					tcp->tcp_ka_enabled = 0;
10412 				}
10413 				break;
10414 			}
10415 			if (!tcp->tcp_ka_enabled) {
10416 				/* Crank up the keepalive timer */
10417 				tcp->tcp_ka_last_intrvl = 0;
10418 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10419 				    tcp_keepalive_killer,
10420 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10421 				tcp->tcp_ka_enabled = 1;
10422 			}
10423 			break;
10424 		case SO_DONTROUTE:
10425 			/*
10426 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
10427 			 * only of interest to IP.  We track them here only so
10428 			 * that we can report their current value.
10429 			 */
10430 			if (!checkonly) {
10431 				tcp->tcp_dontroute = onoff;
10432 				tcp->tcp_connp->conn_dontroute = onoff;
10433 			}
10434 			break;
10435 		case SO_USELOOPBACK:
10436 			if (!checkonly) {
10437 				tcp->tcp_useloopback = onoff;
10438 				tcp->tcp_connp->conn_loopback = onoff;
10439 			}
10440 			break;
10441 		case SO_BROADCAST:
10442 			if (!checkonly) {
10443 				tcp->tcp_broadcast = onoff;
10444 				tcp->tcp_connp->conn_broadcast = onoff;
10445 			}
10446 			break;
10447 		case SO_REUSEADDR:
10448 			if (!checkonly) {
10449 				tcp->tcp_reuseaddr = onoff;
10450 				tcp->tcp_connp->conn_reuseaddr = onoff;
10451 			}
10452 			break;
10453 		case SO_OOBINLINE:
10454 			if (!checkonly)
10455 				tcp->tcp_oobinline = onoff;
10456 			break;
10457 		case SO_DGRAM_ERRIND:
10458 			if (!checkonly)
10459 				tcp->tcp_dgram_errind = onoff;
10460 			break;
10461 		case SO_SNDBUF:
10462 			if (*i1 > tcp_max_buf) {
10463 				*outlenp = 0;
10464 				return (ENOBUFS);
10465 			}
10466 			if (!checkonly) {
10467 				tcp->tcp_xmit_hiwater = *i1;
10468 				if (tcp_snd_lowat_fraction != 0)
10469 					tcp->tcp_xmit_lowater =
10470 					    tcp->tcp_xmit_hiwater /
10471 					    tcp_snd_lowat_fraction;
10472 				(void) tcp_maxpsz_set(tcp, B_TRUE);
10473 				/*
10474 				 * If we are flow-controlled, recheck the
10475 				 * condition. There are apps that increase
10476 				 * SO_SNDBUF size when flow-controlled
10477 				 * (EWOULDBLOCK), and expect the flow control
10478 				 * condition to be lifted right away.
10479 				 */
10480 				if (tcp->tcp_flow_stopped &&
10481 				    tcp->tcp_unsent < tcp->tcp_xmit_hiwater) {
10482 					tcp->tcp_flow_stopped = B_FALSE;
10483 					tcp_clrqfull(tcp);
10484 				}
10485 			}
10486 			break;
10487 		case SO_RCVBUF:
10488 			if (*i1 > tcp_max_buf) {
10489 				*outlenp = 0;
10490 				return (ENOBUFS);
10491 			}
10492 			/* Silently ignore zero */
10493 			if (!checkonly && *i1 != 0) {
10494 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10495 				(void) tcp_rwnd_set(tcp, *i1);
10496 			}
10497 			/*
10498 			 * XXX should we return the rwnd here
10499 			 * and tcp_opt_get ?
10500 			 */
10501 			break;
10502 		case SO_SND_COPYAVOID:
10503 			if (!checkonly) {
10504 				/* we only allow enable at most once for now */
10505 				if (tcp->tcp_loopback ||
10506 				    (!tcp->tcp_snd_zcopy_aware &&
10507 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10508 					*outlenp = 0;
10509 					return (EOPNOTSUPP);
10510 				}
10511 				tcp->tcp_snd_zcopy_aware = 1;
10512 			}
10513 			break;
10514 		default:
10515 			*outlenp = 0;
10516 			return (EINVAL);
10517 		}
10518 		break;
10519 	case IPPROTO_TCP:
10520 		switch (name) {
10521 		case TCP_NODELAY:
10522 			if (!checkonly)
10523 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10524 			break;
10525 		case TCP_NOTIFY_THRESHOLD:
10526 			if (!checkonly)
10527 				tcp->tcp_first_timer_threshold = *i1;
10528 			break;
10529 		case TCP_ABORT_THRESHOLD:
10530 			if (!checkonly)
10531 				tcp->tcp_second_timer_threshold = *i1;
10532 			break;
10533 		case TCP_CONN_NOTIFY_THRESHOLD:
10534 			if (!checkonly)
10535 				tcp->tcp_first_ctimer_threshold = *i1;
10536 			break;
10537 		case TCP_CONN_ABORT_THRESHOLD:
10538 			if (!checkonly)
10539 				tcp->tcp_second_ctimer_threshold = *i1;
10540 			break;
10541 		case TCP_RECVDSTADDR:
10542 			if (tcp->tcp_state > TCPS_LISTEN)
10543 				return (EOPNOTSUPP);
10544 			if (!checkonly)
10545 				tcp->tcp_recvdstaddr = onoff;
10546 			break;
10547 		case TCP_ANONPRIVBIND:
10548 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10549 				*outlenp = 0;
10550 				return (reterr);
10551 			}
10552 			if (!checkonly) {
10553 				tcp->tcp_anon_priv_bind = onoff;
10554 			}
10555 			break;
10556 		case TCP_EXCLBIND:
10557 			if (!checkonly)
10558 				tcp->tcp_exclbind = onoff;
10559 			break;	/* goto sizeof (int) option return */
10560 		case TCP_INIT_CWND: {
10561 			uint32_t init_cwnd = *((uint32_t *)invalp);
10562 
10563 			if (checkonly)
10564 				break;
10565 
10566 			/*
10567 			 * Only allow socket with network configuration
10568 			 * privilege to set the initial cwnd to be larger
10569 			 * than allowed by RFC 3390.
10570 			 */
10571 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10572 				tcp->tcp_init_cwnd = init_cwnd;
10573 				break;
10574 			}
10575 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10576 				*outlenp = 0;
10577 				return (reterr);
10578 			}
10579 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10580 				*outlenp = 0;
10581 				return (EINVAL);
10582 			}
10583 			tcp->tcp_init_cwnd = init_cwnd;
10584 			break;
10585 		}
10586 		case TCP_KEEPALIVE_THRESHOLD:
10587 			if (checkonly)
10588 				break;
10589 
10590 			if (*i1 < tcp_keepalive_interval_low ||
10591 			    *i1 > tcp_keepalive_interval_high) {
10592 				*outlenp = 0;
10593 				return (EINVAL);
10594 			}
10595 			if (*i1 != tcp->tcp_ka_interval) {
10596 				tcp->tcp_ka_interval = *i1;
10597 				/*
10598 				 * Check if we need to restart the
10599 				 * keepalive timer.
10600 				 */
10601 				if (tcp->tcp_ka_tid != 0) {
10602 					ASSERT(tcp->tcp_ka_enabled);
10603 					(void) TCP_TIMER_CANCEL(tcp,
10604 					    tcp->tcp_ka_tid);
10605 					tcp->tcp_ka_last_intrvl = 0;
10606 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10607 					    tcp_keepalive_killer,
10608 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10609 				}
10610 			}
10611 			break;
10612 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10613 			if (!checkonly) {
10614 				if (*i1 < tcp_keepalive_abort_interval_low ||
10615 				    *i1 > tcp_keepalive_abort_interval_high) {
10616 					*outlenp = 0;
10617 					return (EINVAL);
10618 				}
10619 				tcp->tcp_ka_abort_thres = *i1;
10620 			}
10621 			break;
10622 		case TCP_CORK:
10623 			if (!checkonly) {
10624 				/*
10625 				 * if tcp->tcp_cork was set and is now
10626 				 * being unset, we have to make sure that
10627 				 * the remaining data gets sent out. Also
10628 				 * unset tcp->tcp_cork so that tcp_wput_data()
10629 				 * can send data even if it is less than mss
10630 				 */
10631 				if (tcp->tcp_cork && onoff == 0 &&
10632 				    tcp->tcp_unsent > 0) {
10633 					tcp->tcp_cork = B_FALSE;
10634 					tcp_wput_data(tcp, NULL, B_FALSE);
10635 				}
10636 				tcp->tcp_cork = onoff;
10637 			}
10638 			break;
10639 		default:
10640 			*outlenp = 0;
10641 			return (EINVAL);
10642 		}
10643 		break;
10644 	case IPPROTO_IP:
10645 		if (tcp->tcp_family != AF_INET) {
10646 			*outlenp = 0;
10647 			return (ENOPROTOOPT);
10648 		}
10649 		switch (name) {
10650 		case IP_OPTIONS:
10651 		case T_IP_OPTIONS:
10652 			reterr = tcp_opt_set_header(tcp, checkonly,
10653 			    invalp, inlen);
10654 			if (reterr) {
10655 				*outlenp = 0;
10656 				return (reterr);
10657 			}
10658 			/* OK return - copy input buffer into output buffer */
10659 			if (invalp != outvalp) {
10660 				/* don't trust bcopy for identical src/dst */
10661 				bcopy(invalp, outvalp, inlen);
10662 			}
10663 			*outlenp = inlen;
10664 			return (0);
10665 		case IP_TOS:
10666 		case T_IP_TOS:
10667 			if (!checkonly) {
10668 				tcp->tcp_ipha->ipha_type_of_service =
10669 				    (uchar_t)*i1;
10670 				tcp->tcp_tos = (uchar_t)*i1;
10671 			}
10672 			break;
10673 		case IP_TTL:
10674 			if (!checkonly) {
10675 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10676 				tcp->tcp_ttl = (uchar_t)*i1;
10677 			}
10678 			break;
10679 		case IP_BOUND_IF:
10680 			/* Handled at the IP level */
10681 			return (-EINVAL);
10682 		case IP_SEC_OPT:
10683 			/*
10684 			 * We should not allow policy setting after
10685 			 * we start listening for connections.
10686 			 */
10687 			if (tcp->tcp_state == TCPS_LISTEN) {
10688 				return (EINVAL);
10689 			} else {
10690 				/* Handled at the IP level */
10691 				return (-EINVAL);
10692 			}
10693 		default:
10694 			*outlenp = 0;
10695 			return (EINVAL);
10696 		}
10697 		break;
10698 	case IPPROTO_IPV6: {
10699 		ip6_pkt_t		*ipp;
10700 
10701 		/*
10702 		 * IPPROTO_IPV6 options are only supported for sockets
10703 		 * that are using IPv6 on the wire.
10704 		 */
10705 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10706 			*outlenp = 0;
10707 			return (ENOPROTOOPT);
10708 		}
10709 		/*
10710 		 * Only sticky options; no ancillary data
10711 		 */
10712 		ASSERT(thisdg_attrs == NULL);
10713 		ipp = &tcp->tcp_sticky_ipp;
10714 
10715 		switch (name) {
10716 		case IPV6_UNICAST_HOPS:
10717 			/* -1 means use default */
10718 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10719 				*outlenp = 0;
10720 				return (EINVAL);
10721 			}
10722 			if (!checkonly) {
10723 				if (*i1 == -1) {
10724 					tcp->tcp_ip6h->ip6_hops =
10725 					    ipp->ipp_hoplimit =
10726 					    (uint8_t)tcp_ipv6_hoplimit;
10727 					ipp->ipp_fields &= ~IPPF_HOPLIMIT;
10728 					/* Pass modified value to IP. */
10729 					*i1 = tcp->tcp_ip6h->ip6_hops;
10730 				} else {
10731 					tcp->tcp_ip6h->ip6_hops =
10732 					    ipp->ipp_hoplimit = (uint8_t)*i1;
10733 					ipp->ipp_fields |= IPPF_HOPLIMIT;
10734 				}
10735 			}
10736 			break;
10737 		case IPV6_BOUND_IF:
10738 			if (!checkonly) {
10739 				int error = 0;
10740 
10741 				tcp->tcp_bound_if = *i1;
10742 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10743 				    B_TRUE, checkonly, level, name, mblk);
10744 				if (error != 0) {
10745 					*outlenp = 0;
10746 					return (error);
10747 				}
10748 			}
10749 			break;
10750 		/*
10751 		 * Set boolean switches for ancillary data delivery
10752 		 */
10753 		case IPV6_RECVPKTINFO:
10754 			if (!checkonly) {
10755 				if (onoff)
10756 					tcp->tcp_ipv6_recvancillary |=
10757 					    TCP_IPV6_RECVPKTINFO;
10758 				else
10759 					tcp->tcp_ipv6_recvancillary &=
10760 					    ~TCP_IPV6_RECVPKTINFO;
10761 				/* Force it to be sent up with the next msg */
10762 				tcp->tcp_recvifindex = 0;
10763 			}
10764 			break;
10765 		case IPV6_RECVTCLASS:
10766 			if (!checkonly) {
10767 				if (onoff)
10768 					tcp->tcp_ipv6_recvancillary |=
10769 					    TCP_IPV6_RECVTCLASS;
10770 				else
10771 					tcp->tcp_ipv6_recvancillary &=
10772 					    ~TCP_IPV6_RECVTCLASS;
10773 			}
10774 			break;
10775 		case IPV6_RECVHOPLIMIT:
10776 			if (!checkonly) {
10777 				if (onoff)
10778 					tcp->tcp_ipv6_recvancillary |=
10779 					    TCP_IPV6_RECVHOPLIMIT;
10780 				else
10781 					tcp->tcp_ipv6_recvancillary &=
10782 					    ~TCP_IPV6_RECVHOPLIMIT;
10783 				/* Force it to be sent up with the next msg */
10784 				tcp->tcp_recvhops = 0xffffffffU;
10785 			}
10786 			break;
10787 		case IPV6_RECVHOPOPTS:
10788 			if (!checkonly) {
10789 				if (onoff)
10790 					tcp->tcp_ipv6_recvancillary |=
10791 					    TCP_IPV6_RECVHOPOPTS;
10792 				else
10793 					tcp->tcp_ipv6_recvancillary &=
10794 					    ~TCP_IPV6_RECVHOPOPTS;
10795 			}
10796 			break;
10797 		case IPV6_RECVDSTOPTS:
10798 			if (!checkonly) {
10799 				if (onoff)
10800 					tcp->tcp_ipv6_recvancillary |=
10801 					    TCP_IPV6_RECVDSTOPTS;
10802 				else
10803 					tcp->tcp_ipv6_recvancillary &=
10804 					    ~TCP_IPV6_RECVDSTOPTS;
10805 			}
10806 			break;
10807 		case _OLD_IPV6_RECVDSTOPTS:
10808 			if (!checkonly) {
10809 				if (onoff)
10810 					tcp->tcp_ipv6_recvancillary |=
10811 					    TCP_OLD_IPV6_RECVDSTOPTS;
10812 				else
10813 					tcp->tcp_ipv6_recvancillary &=
10814 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10815 			}
10816 			break;
10817 		case IPV6_RECVRTHDR:
10818 			if (!checkonly) {
10819 				if (onoff)
10820 					tcp->tcp_ipv6_recvancillary |=
10821 					    TCP_IPV6_RECVRTHDR;
10822 				else
10823 					tcp->tcp_ipv6_recvancillary &=
10824 					    ~TCP_IPV6_RECVRTHDR;
10825 			}
10826 			break;
10827 		case IPV6_RECVRTHDRDSTOPTS:
10828 			if (!checkonly) {
10829 				if (onoff)
10830 					tcp->tcp_ipv6_recvancillary |=
10831 					    TCP_IPV6_RECVRTDSTOPTS;
10832 				else
10833 					tcp->tcp_ipv6_recvancillary &=
10834 					    ~TCP_IPV6_RECVRTDSTOPTS;
10835 			}
10836 			break;
10837 		case IPV6_PKTINFO:
10838 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10839 				return (EINVAL);
10840 			if (checkonly)
10841 				break;
10842 
10843 			if (inlen == 0) {
10844 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10845 			} else {
10846 				struct in6_pktinfo *pkti;
10847 
10848 				pkti = (struct in6_pktinfo *)invalp;
10849 				/*
10850 				 * RFC 3542 states that ipi6_addr must be
10851 				 * the unspecified address when setting the
10852 				 * IPV6_PKTINFO sticky socket option on a
10853 				 * TCP socket.
10854 				 */
10855 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10856 					return (EINVAL);
10857 				/*
10858 				 * ip6_set_pktinfo() validates the source
10859 				 * address and interface index.
10860 				 */
10861 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10862 				    pkti, mblk);
10863 				if (reterr != 0)
10864 					return (reterr);
10865 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10866 				ipp->ipp_addr = pkti->ipi6_addr;
10867 				if (ipp->ipp_ifindex != 0)
10868 					ipp->ipp_fields |= IPPF_IFINDEX;
10869 				else
10870 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10871 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10872 					ipp->ipp_fields |= IPPF_ADDR;
10873 				else
10874 					ipp->ipp_fields &= ~IPPF_ADDR;
10875 			}
10876 			reterr = tcp_build_hdrs(q, tcp);
10877 			if (reterr != 0)
10878 				return (reterr);
10879 			break;
10880 		case IPV6_HOPLIMIT:
10881 			if (inlen != 0 && inlen != sizeof (int))
10882 				return (EINVAL);
10883 			if (checkonly)
10884 				break;
10885 
10886 			if (inlen == 0) {
10887 				ipp->ipp_fields &= ~IPPF_HOPLIMIT;
10888 				tcp->tcp_ip6_hops =
10889 				    (uint8_t)tcp_ipv6_hoplimit;
10890 			} else {
10891 				if (*i1 > 255 || *i1 < -1)
10892 					return (EINVAL);
10893 				if (*i1 == -1) {
10894 					ipp->ipp_hoplimit = tcp_ipv6_hoplimit;
10895 					*i1 = tcp_ipv6_hoplimit;
10896 				} else {
10897 					ipp->ipp_hoplimit = *i1;
10898 				}
10899 				ipp->ipp_fields |= IPPF_HOPLIMIT;
10900 				tcp->tcp_ip6_hops =
10901 				    ipp->ipp_hoplimit;
10902 			}
10903 			reterr = tcp_build_hdrs(q, tcp);
10904 			if (reterr != 0)
10905 				return (reterr);
10906 			break;
10907 		case IPV6_TCLASS:
10908 			if (inlen != 0 && inlen != sizeof (int))
10909 				return (EINVAL);
10910 			if (checkonly)
10911 				break;
10912 
10913 			if (inlen == 0) {
10914 				ipp->ipp_fields &= ~IPPF_TCLASS;
10915 			} else {
10916 				if (*i1 > 255 || *i1 < -1)
10917 					return (EINVAL);
10918 				if (*i1 == -1) {
10919 					ipp->ipp_tclass = 0;
10920 					*i1 = 0;
10921 				} else {
10922 					ipp->ipp_tclass = *i1;
10923 				}
10924 				ipp->ipp_fields |= IPPF_TCLASS;
10925 			}
10926 			reterr = tcp_build_hdrs(q, tcp);
10927 			if (reterr != 0)
10928 				return (reterr);
10929 			break;
10930 		case IPV6_NEXTHOP:
10931 			/*
10932 			 * IP will verify that the nexthop is reachable
10933 			 * and fail for sticky options.
10934 			 */
10935 			if (inlen != 0 && inlen != sizeof (sin6_t))
10936 				return (EINVAL);
10937 			if (checkonly)
10938 				break;
10939 
10940 			if (inlen == 0) {
10941 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10942 			} else {
10943 				sin6_t *sin6 = (sin6_t *)invalp;
10944 
10945 				if (sin6->sin6_family != AF_INET6)
10946 					return (EAFNOSUPPORT);
10947 				if (IN6_IS_ADDR_V4MAPPED(
10948 				    &sin6->sin6_addr))
10949 					return (EADDRNOTAVAIL);
10950 				ipp->ipp_nexthop = sin6->sin6_addr;
10951 				if (!IN6_IS_ADDR_UNSPECIFIED(
10952 				    &ipp->ipp_nexthop))
10953 					ipp->ipp_fields |= IPPF_NEXTHOP;
10954 				else
10955 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10956 			}
10957 			reterr = tcp_build_hdrs(q, tcp);
10958 			if (reterr != 0)
10959 				return (reterr);
10960 			break;
10961 		case IPV6_HOPOPTS: {
10962 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10963 			/*
10964 			 * Sanity checks - minimum size, size a multiple of
10965 			 * eight bytes, and matching size passed in.
10966 			 */
10967 			if (inlen != 0 &&
10968 			    inlen != (8 * (hopts->ip6h_len + 1)))
10969 				return (EINVAL);
10970 
10971 			if (checkonly)
10972 				break;
10973 
10974 			if (inlen == 0) {
10975 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10976 					kmem_free(ipp->ipp_hopopts,
10977 					    ipp->ipp_hopoptslen);
10978 					ipp->ipp_hopopts = NULL;
10979 					ipp->ipp_hopoptslen = 0;
10980 				}
10981 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10982 			} else {
10983 				reterr = tcp_pkt_set(invalp, inlen,
10984 				    (uchar_t **)&ipp->ipp_hopopts,
10985 				    &ipp->ipp_hopoptslen);
10986 				if (reterr != 0)
10987 					return (reterr);
10988 				ipp->ipp_fields |= IPPF_HOPOPTS;
10989 			}
10990 			reterr = tcp_build_hdrs(q, tcp);
10991 			if (reterr != 0)
10992 				return (reterr);
10993 			break;
10994 		}
10995 		case IPV6_RTHDRDSTOPTS: {
10996 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10997 
10998 			/*
10999 			 * Sanity checks - minimum size, size a multiple of
11000 			 * eight bytes, and matching size passed in.
11001 			 */
11002 			if (inlen != 0 &&
11003 			    inlen != (8 * (dopts->ip6d_len + 1)))
11004 				return (EINVAL);
11005 
11006 			if (checkonly)
11007 				break;
11008 
11009 			if (inlen == 0) {
11010 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
11011 					kmem_free(ipp->ipp_rtdstopts,
11012 					    ipp->ipp_rtdstoptslen);
11013 					ipp->ipp_rtdstopts = NULL;
11014 					ipp->ipp_rtdstoptslen = 0;
11015 				}
11016 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
11017 			} else {
11018 				reterr = tcp_pkt_set(invalp, inlen,
11019 				    (uchar_t **)&ipp->ipp_rtdstopts,
11020 				    &ipp->ipp_rtdstoptslen);
11021 				if (reterr != 0)
11022 					return (reterr);
11023 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
11024 			}
11025 			reterr = tcp_build_hdrs(q, tcp);
11026 			if (reterr != 0)
11027 				return (reterr);
11028 			break;
11029 		}
11030 		case IPV6_DSTOPTS: {
11031 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11032 
11033 			/*
11034 			 * Sanity checks - minimum size, size a multiple of
11035 			 * eight bytes, and matching size passed in.
11036 			 */
11037 			if (inlen != 0 &&
11038 			    inlen != (8 * (dopts->ip6d_len + 1)))
11039 				return (EINVAL);
11040 
11041 			if (checkonly)
11042 				break;
11043 
11044 			if (inlen == 0) {
11045 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
11046 					kmem_free(ipp->ipp_dstopts,
11047 					    ipp->ipp_dstoptslen);
11048 					ipp->ipp_dstopts = NULL;
11049 					ipp->ipp_dstoptslen = 0;
11050 				}
11051 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11052 			} else {
11053 				reterr = tcp_pkt_set(invalp, inlen,
11054 				    (uchar_t **)&ipp->ipp_dstopts,
11055 				    &ipp->ipp_dstoptslen);
11056 				if (reterr != 0)
11057 					return (reterr);
11058 				ipp->ipp_fields |= IPPF_DSTOPTS;
11059 			}
11060 			reterr = tcp_build_hdrs(q, tcp);
11061 			if (reterr != 0)
11062 				return (reterr);
11063 			break;
11064 		}
11065 		case IPV6_RTHDR: {
11066 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11067 
11068 			/*
11069 			 * Sanity checks - minimum size, size a multiple of
11070 			 * eight bytes, and matching size passed in.
11071 			 */
11072 			if (inlen != 0 &&
11073 			    inlen != (8 * (rt->ip6r_len + 1)))
11074 				return (EINVAL);
11075 
11076 			if (checkonly)
11077 				break;
11078 
11079 			if (inlen == 0) {
11080 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
11081 					kmem_free(ipp->ipp_rthdr,
11082 					    ipp->ipp_rthdrlen);
11083 					ipp->ipp_rthdr = NULL;
11084 					ipp->ipp_rthdrlen = 0;
11085 				}
11086 				ipp->ipp_fields &= ~IPPF_RTHDR;
11087 			} else {
11088 				reterr = tcp_pkt_set(invalp, inlen,
11089 				    (uchar_t **)&ipp->ipp_rthdr,
11090 				    &ipp->ipp_rthdrlen);
11091 				if (reterr != 0)
11092 					return (reterr);
11093 				ipp->ipp_fields |= IPPF_RTHDR;
11094 			}
11095 			reterr = tcp_build_hdrs(q, tcp);
11096 			if (reterr != 0)
11097 				return (reterr);
11098 			break;
11099 		}
11100 		case IPV6_V6ONLY:
11101 			if (!checkonly)
11102 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11103 			break;
11104 		case IPV6_USE_MIN_MTU:
11105 			if (inlen != sizeof (int))
11106 				return (EINVAL);
11107 
11108 			if (*i1 < -1 || *i1 > 1)
11109 				return (EINVAL);
11110 
11111 			if (checkonly)
11112 				break;
11113 
11114 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11115 			ipp->ipp_use_min_mtu = *i1;
11116 			break;
11117 		case IPV6_BOUND_PIF:
11118 			/* Handled at the IP level */
11119 			return (-EINVAL);
11120 		case IPV6_SEC_OPT:
11121 			/*
11122 			 * We should not allow policy setting after
11123 			 * we start listening for connections.
11124 			 */
11125 			if (tcp->tcp_state == TCPS_LISTEN) {
11126 				return (EINVAL);
11127 			} else {
11128 				/* Handled at the IP level */
11129 				return (-EINVAL);
11130 			}
11131 		case IPV6_SRC_PREFERENCES:
11132 			if (inlen != sizeof (uint32_t))
11133 				return (EINVAL);
11134 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11135 			    *(uint32_t *)invalp);
11136 			if (reterr != 0) {
11137 				*outlenp = 0;
11138 				return (reterr);
11139 			}
11140 			break;
11141 		default:
11142 			*outlenp = 0;
11143 			return (EINVAL);
11144 		}
11145 		break;
11146 	}		/* end IPPROTO_IPV6 */
11147 	default:
11148 		*outlenp = 0;
11149 		return (EINVAL);
11150 	}
11151 	/*
11152 	 * Common case of OK return with outval same as inval
11153 	 */
11154 	if (invalp != outvalp) {
11155 		/* don't trust bcopy for identical src/dst */
11156 		(void) bcopy(invalp, outvalp, inlen);
11157 	}
11158 	*outlenp = inlen;
11159 	return (0);
11160 }
11161 
11162 /*
11163  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11164  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11165  * headers, and the maximum size tcp header (to avoid reallocation
11166  * on the fly for additional tcp options).
11167  * Returns failure if can't allocate memory.
11168  */
11169 static int
11170 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11171 {
11172 	char	*hdrs;
11173 	uint_t	hdrs_len;
11174 	ip6i_t	*ip6i;
11175 	char	buf[TCP_MAX_HDR_LENGTH];
11176 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11177 	in6_addr_t src, dst;
11178 	uint8_t hops;
11179 
11180 	/*
11181 	 * save the existing tcp header and source/dest IP addresses
11182 	 */
11183 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11184 	src = tcp->tcp_ip6h->ip6_src;
11185 	dst = tcp->tcp_ip6h->ip6_dst;
11186 	hops = tcp->tcp_ip6h->ip6_hops;
11187 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11188 	ASSERT(hdrs_len != 0);
11189 	if (hdrs_len > tcp->tcp_iphc_len) {
11190 		/* Need to reallocate */
11191 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11192 		if (hdrs == NULL)
11193 			return (ENOMEM);
11194 		if (tcp->tcp_iphc != NULL) {
11195 			if (tcp->tcp_hdr_grown) {
11196 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11197 			} else {
11198 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11199 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11200 			}
11201 			tcp->tcp_iphc_len = 0;
11202 		}
11203 		ASSERT(tcp->tcp_iphc_len == 0);
11204 		tcp->tcp_iphc = hdrs;
11205 		tcp->tcp_iphc_len = hdrs_len;
11206 		tcp->tcp_hdr_grown = B_TRUE;
11207 	}
11208 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11209 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11210 
11211 	/* Set header fields not in ipp */
11212 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11213 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11214 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11215 	} else {
11216 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11217 	}
11218 	/*
11219 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11220 	 *
11221 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11222 	 */
11223 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11224 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11225 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11226 
11227 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11228 
11229 	tcp->tcp_ip6h->ip6_src = src;
11230 	tcp->tcp_ip6h->ip6_dst = dst;
11231 
11232 	/*
11233 	 * If the hop limit was not set by ip_build_hdrs_v6(), restore
11234 	 * the saved value.
11235 	 */
11236 	if (!(ipp->ipp_fields & IPPF_HOPLIMIT))
11237 		tcp->tcp_ip6h->ip6_hops = hops;
11238 
11239 	/*
11240 	 * Set the IPv6 header payload length.
11241 	 * If there's an ip6i_t included, don't count it in the length.
11242 	 */
11243 	tcp->tcp_ip6h->ip6_plen = tcp->tcp_hdr_len - IPV6_HDR_LEN;
11244 	if (ipp->ipp_fields & IPPF_HAS_IP6I)
11245 		tcp->tcp_ip6h->ip6_plen -= sizeof (ip6i_t);
11246 	/*
11247 	 * If we're setting extension headers after a connection
11248 	 * has been established, and if we have a routing header
11249 	 * among the extension headers, call ip_massage_options_v6 to
11250 	 * manipulate the routing header/ip6_dst set the checksum
11251 	 * difference in the tcp header template.
11252 	 * (This happens in tcp_connect_ipv6 if the routing header
11253 	 * is set prior to the connect.)
11254 	 * Set the tcp_sum to zero first in case we've cleared a
11255 	 * routing header or don't have one at all.
11256 	 */
11257 	tcp->tcp_sum = 0;
11258 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11259 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11260 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11261 		    (uint8_t *)tcp->tcp_tcph);
11262 		if (rth != NULL) {
11263 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11264 			    rth);
11265 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11266 			    (tcp->tcp_sum >> 16));
11267 		}
11268 	}
11269 
11270 	/* Try to get everything in a single mblk */
11271 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
11272 	return (0);
11273 }
11274 
11275 /*
11276  * Set optbuf and optlen for the option.
11277  * Allocate memory (if not already present).
11278  * Otherwise just point optbuf and optlen at invalp and inlen.
11279  * Returns failure if memory can not be allocated.
11280  */
11281 static int
11282 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
11283 {
11284 	uchar_t *optbuf;
11285 
11286 	if (inlen == *optlenp) {
11287 		/* Unchanged length - no need to realocate */
11288 		bcopy(invalp, *optbufp, inlen);
11289 		return (0);
11290 	}
11291 	if (inlen != 0) {
11292 		/* Allocate new buffer before free */
11293 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
11294 		if (optbuf == NULL)
11295 			return (ENOMEM);
11296 	} else {
11297 		optbuf = NULL;
11298 	}
11299 	/* Free old buffer */
11300 	if (*optlenp != 0)
11301 		kmem_free(*optbufp, *optlenp);
11302 
11303 	bcopy(invalp, optbuf, inlen);
11304 	*optbufp = optbuf;
11305 	*optlenp = inlen;
11306 	return (0);
11307 }
11308 
11309 
11310 /*
11311  * Use the outgoing IP header to create an IP_OPTIONS option the way
11312  * it was passed down from the application.
11313  */
11314 static int
11315 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
11316 {
11317 	ipoptp_t	opts;
11318 	uchar_t		*opt;
11319 	uint8_t		optval;
11320 	uint8_t		optlen;
11321 	uint32_t	len = 0;
11322 	uchar_t	*buf1 = buf;
11323 
11324 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
11325 	len += IP_ADDR_LEN;
11326 	bzero(buf1, IP_ADDR_LEN);
11327 
11328 	for (optval = ipoptp_first(&opts, ipha);
11329 	    optval != IPOPT_EOL;
11330 	    optval = ipoptp_next(&opts)) {
11331 		opt = opts.ipoptp_cur;
11332 		optlen = opts.ipoptp_len;
11333 		switch (optval) {
11334 			int	off;
11335 		case IPOPT_SSRR:
11336 		case IPOPT_LSRR:
11337 
11338 			/*
11339 			 * Insert ipha_dst as the first entry in the source
11340 			 * route and move down the entries on step.
11341 			 * The last entry gets placed at buf1.
11342 			 */
11343 			buf[IPOPT_OPTVAL] = optval;
11344 			buf[IPOPT_OLEN] = optlen;
11345 			buf[IPOPT_OFFSET] = optlen;
11346 
11347 			off = optlen - IP_ADDR_LEN;
11348 			if (off < 0) {
11349 				/* No entries in source route */
11350 				break;
11351 			}
11352 			/* Last entry in source route */
11353 			bcopy(opt + off, buf1, IP_ADDR_LEN);
11354 			off -= IP_ADDR_LEN;
11355 
11356 			while (off > 0) {
11357 				bcopy(opt + off,
11358 				    buf + off + IP_ADDR_LEN,
11359 				    IP_ADDR_LEN);
11360 				off -= IP_ADDR_LEN;
11361 			}
11362 			/* ipha_dst into first slot */
11363 			bcopy(&ipha->ipha_dst,
11364 			    buf + off + IP_ADDR_LEN,
11365 			    IP_ADDR_LEN);
11366 			buf += optlen;
11367 			len += optlen;
11368 			break;
11369 		default:
11370 			bcopy(opt, buf, optlen);
11371 			buf += optlen;
11372 			len += optlen;
11373 			break;
11374 		}
11375 	}
11376 done:
11377 	/* Pad the resulting options */
11378 	while (len & 0x3) {
11379 		*buf++ = IPOPT_EOL;
11380 		len++;
11381 	}
11382 	return (len);
11383 }
11384 
11385 /*
11386  * Transfer any source route option from ipha to buf/dst in reversed form.
11387  */
11388 static int
11389 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11390 {
11391 	ipoptp_t	opts;
11392 	uchar_t		*opt;
11393 	uint8_t		optval;
11394 	uint8_t		optlen;
11395 	uint32_t	len = 0;
11396 
11397 	for (optval = ipoptp_first(&opts, ipha);
11398 	    optval != IPOPT_EOL;
11399 	    optval = ipoptp_next(&opts)) {
11400 		opt = opts.ipoptp_cur;
11401 		optlen = opts.ipoptp_len;
11402 		switch (optval) {
11403 			int	off1, off2;
11404 		case IPOPT_SSRR:
11405 		case IPOPT_LSRR:
11406 
11407 			/* Reverse source route */
11408 			/*
11409 			 * First entry should be the next to last one in the
11410 			 * current source route (the last entry is our
11411 			 * address.)
11412 			 * The last entry should be the final destination.
11413 			 */
11414 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11415 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11416 			off1 = IPOPT_MINOFF_SR - 1;
11417 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11418 			if (off2 < 0) {
11419 				/* No entries in source route */
11420 				break;
11421 			}
11422 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11423 			/*
11424 			 * Note: use src since ipha has not had its src
11425 			 * and dst reversed (it is in the state it was
11426 			 * received.
11427 			 */
11428 			bcopy(&ipha->ipha_src, buf + off2,
11429 			    IP_ADDR_LEN);
11430 			off2 -= IP_ADDR_LEN;
11431 
11432 			while (off2 > 0) {
11433 				bcopy(opt + off2, buf + off1,
11434 				    IP_ADDR_LEN);
11435 				off1 += IP_ADDR_LEN;
11436 				off2 -= IP_ADDR_LEN;
11437 			}
11438 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11439 			buf += optlen;
11440 			len += optlen;
11441 			break;
11442 		}
11443 	}
11444 done:
11445 	/* Pad the resulting options */
11446 	while (len & 0x3) {
11447 		*buf++ = IPOPT_EOL;
11448 		len++;
11449 	}
11450 	return (len);
11451 }
11452 
11453 
11454 /*
11455  * Extract and revert a source route from ipha (if any)
11456  * and then update the relevant fields in both tcp_t and the standard header.
11457  */
11458 static void
11459 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11460 {
11461 	char	buf[TCP_MAX_HDR_LENGTH];
11462 	uint_t	tcph_len;
11463 	int	len;
11464 
11465 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11466 	len = IPH_HDR_LENGTH(ipha);
11467 	if (len == IP_SIMPLE_HDR_LENGTH)
11468 		/* Nothing to do */
11469 		return;
11470 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11471 	    (len & 0x3))
11472 		return;
11473 
11474 	tcph_len = tcp->tcp_tcp_hdr_len;
11475 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11476 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11477 		(tcp->tcp_ipha->ipha_dst & 0xffff);
11478 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11479 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11480 	len += IP_SIMPLE_HDR_LENGTH;
11481 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11482 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11483 	if ((int)tcp->tcp_sum < 0)
11484 		tcp->tcp_sum--;
11485 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11486 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11487 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11488 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11489 	tcp->tcp_ip_hdr_len = len;
11490 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11491 	    (IP_VERSION << 4) | (len >> 2);
11492 	len += tcph_len;
11493 	tcp->tcp_hdr_len = len;
11494 }
11495 
11496 /*
11497  * Copy the standard header into its new location,
11498  * lay in the new options and then update the relevant
11499  * fields in both tcp_t and the standard header.
11500  */
11501 static int
11502 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11503 {
11504 	uint_t	tcph_len;
11505 	char	*ip_optp;
11506 	tcph_t	*new_tcph;
11507 
11508 	if (checkonly) {
11509 		/*
11510 		 * do not really set, just pretend to - T_CHECK
11511 		 */
11512 		if (len != 0) {
11513 			/*
11514 			 * there is value supplied, validate it as if
11515 			 * for a real set operation.
11516 			 */
11517 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11518 				return (EINVAL);
11519 		}
11520 		return (0);
11521 	}
11522 
11523 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11524 		return (EINVAL);
11525 
11526 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11527 	tcph_len = tcp->tcp_tcp_hdr_len;
11528 	new_tcph = (tcph_t *)(ip_optp + len);
11529 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
11530 	tcp->tcp_tcph = new_tcph;
11531 	bcopy(ptr, ip_optp, len);
11532 
11533 	len += IP_SIMPLE_HDR_LENGTH;
11534 
11535 	tcp->tcp_ip_hdr_len = len;
11536 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11537 		(IP_VERSION << 4) | (len >> 2);
11538 	len += tcph_len;
11539 	tcp->tcp_hdr_len = len;
11540 	if (!TCP_IS_DETACHED(tcp)) {
11541 		/* Always allocate room for all options. */
11542 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11543 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
11544 	}
11545 	return (0);
11546 }
11547 
11548 /* Get callback routine passed to nd_load by tcp_param_register */
11549 /* ARGSUSED */
11550 static int
11551 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11552 {
11553 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11554 
11555 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11556 	return (0);
11557 }
11558 
11559 /*
11560  * Walk through the param array specified registering each element with the
11561  * named dispatch handler.
11562  */
11563 static boolean_t
11564 tcp_param_register(tcpparam_t *tcppa, int cnt)
11565 {
11566 	for (; cnt-- > 0; tcppa++) {
11567 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11568 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
11569 			    tcp_param_get, tcp_param_set,
11570 			    (caddr_t)tcppa)) {
11571 				nd_free(&tcp_g_nd);
11572 				return (B_FALSE);
11573 			}
11574 		}
11575 	}
11576 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
11577 	    tcp_param_get, tcp_param_set_aligned,
11578 	    (caddr_t)&tcp_wroff_xtra_param)) {
11579 		nd_free(&tcp_g_nd);
11580 		return (B_FALSE);
11581 	}
11582 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
11583 	    tcp_param_get, tcp_param_set_aligned,
11584 	    (caddr_t)&tcp_mdt_head_param)) {
11585 		nd_free(&tcp_g_nd);
11586 		return (B_FALSE);
11587 	}
11588 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11589 	    tcp_param_get, tcp_param_set_aligned,
11590 	    (caddr_t)&tcp_mdt_tail_param)) {
11591 		nd_free(&tcp_g_nd);
11592 		return (B_FALSE);
11593 	}
11594 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11595 	    tcp_param_get, tcp_param_set,
11596 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11597 		nd_free(&tcp_g_nd);
11598 		return (B_FALSE);
11599 	}
11600 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11601 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11602 		nd_free(&tcp_g_nd);
11603 		return (B_FALSE);
11604 	}
11605 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11606 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11607 		nd_free(&tcp_g_nd);
11608 		return (B_FALSE);
11609 	}
11610 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11611 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11612 		nd_free(&tcp_g_nd);
11613 		return (B_FALSE);
11614 	}
11615 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11616 	    NULL)) {
11617 		nd_free(&tcp_g_nd);
11618 		return (B_FALSE);
11619 	}
11620 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11621 	    NULL, NULL)) {
11622 		nd_free(&tcp_g_nd);
11623 		return (B_FALSE);
11624 	}
11625 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11626 	    NULL, NULL)) {
11627 		nd_free(&tcp_g_nd);
11628 		return (B_FALSE);
11629 	}
11630 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11631 	    NULL, NULL)) {
11632 		nd_free(&tcp_g_nd);
11633 		return (B_FALSE);
11634 	}
11635 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11636 	    NULL, NULL)) {
11637 		nd_free(&tcp_g_nd);
11638 		return (B_FALSE);
11639 	}
11640 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11641 	    tcp_host_param_set, NULL)) {
11642 		nd_free(&tcp_g_nd);
11643 		return (B_FALSE);
11644 	}
11645 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11646 	    tcp_host_param_set_ipv6, NULL)) {
11647 		nd_free(&tcp_g_nd);
11648 		return (B_FALSE);
11649 	}
11650 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11651 	    NULL)) {
11652 		nd_free(&tcp_g_nd);
11653 		return (B_FALSE);
11654 	}
11655 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11656 	    tcp_reserved_port_list, NULL, NULL)) {
11657 		nd_free(&tcp_g_nd);
11658 		return (B_FALSE);
11659 	}
11660 	/*
11661 	 * Dummy ndd variables - only to convey obsolescence information
11662 	 * through printing of their name (no get or set routines)
11663 	 * XXX Remove in future releases ?
11664 	 */
11665 	if (!nd_load(&tcp_g_nd,
11666 	    "tcp_close_wait_interval(obsoleted - "
11667 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11668 		nd_free(&tcp_g_nd);
11669 		return (B_FALSE);
11670 	}
11671 	return (B_TRUE);
11672 }
11673 
11674 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11675 /* ARGSUSED */
11676 static int
11677 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11678     cred_t *cr)
11679 {
11680 	long new_value;
11681 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11682 
11683 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11684 	    new_value < tcppa->tcp_param_min ||
11685 	    new_value > tcppa->tcp_param_max) {
11686 		return (EINVAL);
11687 	}
11688 	/*
11689 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11690 	 * round it up.  For future 64 bit requirement, we actually make it
11691 	 * a multiple of 8.
11692 	 */
11693 	if (new_value & 0x7) {
11694 		new_value = (new_value & ~0x7) + 0x8;
11695 	}
11696 	tcppa->tcp_param_val = new_value;
11697 	return (0);
11698 }
11699 
11700 /* Set callback routine passed to nd_load by tcp_param_register */
11701 /* ARGSUSED */
11702 static int
11703 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11704 {
11705 	long	new_value;
11706 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11707 
11708 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11709 	    new_value < tcppa->tcp_param_min ||
11710 	    new_value > tcppa->tcp_param_max) {
11711 		return (EINVAL);
11712 	}
11713 	tcppa->tcp_param_val = new_value;
11714 	return (0);
11715 }
11716 
11717 /*
11718  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11719  * is filled, return as much as we can.  The message passed in may be
11720  * multi-part, chained using b_cont.  "start" is the starting sequence
11721  * number for this piece.
11722  */
11723 static mblk_t *
11724 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11725 {
11726 	uint32_t	end;
11727 	mblk_t		*mp1;
11728 	mblk_t		*mp2;
11729 	mblk_t		*next_mp;
11730 	uint32_t	u1;
11731 
11732 	/* Walk through all the new pieces. */
11733 	do {
11734 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11735 		    (uintptr_t)INT_MAX);
11736 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11737 		next_mp = mp->b_cont;
11738 		if (start == end) {
11739 			/* Empty.  Blast it. */
11740 			freeb(mp);
11741 			continue;
11742 		}
11743 		mp->b_cont = NULL;
11744 		TCP_REASS_SET_SEQ(mp, start);
11745 		TCP_REASS_SET_END(mp, end);
11746 		mp1 = tcp->tcp_reass_tail;
11747 		if (!mp1) {
11748 			tcp->tcp_reass_tail = mp;
11749 			tcp->tcp_reass_head = mp;
11750 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11751 			UPDATE_MIB(&tcp_mib,
11752 			    tcpInDataUnorderBytes, end - start);
11753 			continue;
11754 		}
11755 		/* New stuff completely beyond tail? */
11756 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11757 			/* Link it on end. */
11758 			mp1->b_cont = mp;
11759 			tcp->tcp_reass_tail = mp;
11760 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11761 			UPDATE_MIB(&tcp_mib,
11762 			    tcpInDataUnorderBytes, end - start);
11763 			continue;
11764 		}
11765 		mp1 = tcp->tcp_reass_head;
11766 		u1 = TCP_REASS_SEQ(mp1);
11767 		/* New stuff at the front? */
11768 		if (SEQ_LT(start, u1)) {
11769 			/* Yes... Check for overlap. */
11770 			mp->b_cont = mp1;
11771 			tcp->tcp_reass_head = mp;
11772 			tcp_reass_elim_overlap(tcp, mp);
11773 			continue;
11774 		}
11775 		/*
11776 		 * The new piece fits somewhere between the head and tail.
11777 		 * We find our slot, where mp1 precedes us and mp2 trails.
11778 		 */
11779 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11780 			u1 = TCP_REASS_SEQ(mp2);
11781 			if (SEQ_LEQ(start, u1))
11782 				break;
11783 		}
11784 		/* Link ourselves in */
11785 		mp->b_cont = mp2;
11786 		mp1->b_cont = mp;
11787 
11788 		/* Trim overlap with following mblk(s) first */
11789 		tcp_reass_elim_overlap(tcp, mp);
11790 
11791 		/* Trim overlap with preceding mblk */
11792 		tcp_reass_elim_overlap(tcp, mp1);
11793 
11794 	} while (start = end, mp = next_mp);
11795 	mp1 = tcp->tcp_reass_head;
11796 	/* Anything ready to go? */
11797 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11798 		return (NULL);
11799 	/* Eat what we can off the queue */
11800 	for (;;) {
11801 		mp = mp1->b_cont;
11802 		end = TCP_REASS_END(mp1);
11803 		TCP_REASS_SET_SEQ(mp1, 0);
11804 		TCP_REASS_SET_END(mp1, 0);
11805 		if (!mp) {
11806 			tcp->tcp_reass_tail = NULL;
11807 			break;
11808 		}
11809 		if (end != TCP_REASS_SEQ(mp)) {
11810 			mp1->b_cont = NULL;
11811 			break;
11812 		}
11813 		mp1 = mp;
11814 	}
11815 	mp1 = tcp->tcp_reass_head;
11816 	tcp->tcp_reass_head = mp;
11817 	return (mp1);
11818 }
11819 
11820 /* Eliminate any overlap that mp may have over later mblks */
11821 static void
11822 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11823 {
11824 	uint32_t	end;
11825 	mblk_t		*mp1;
11826 	uint32_t	u1;
11827 
11828 	end = TCP_REASS_END(mp);
11829 	while ((mp1 = mp->b_cont) != NULL) {
11830 		u1 = TCP_REASS_SEQ(mp1);
11831 		if (!SEQ_GT(end, u1))
11832 			break;
11833 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11834 			mp->b_wptr -= end - u1;
11835 			TCP_REASS_SET_END(mp, u1);
11836 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11837 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11838 			break;
11839 		}
11840 		mp->b_cont = mp1->b_cont;
11841 		TCP_REASS_SET_SEQ(mp1, 0);
11842 		TCP_REASS_SET_END(mp1, 0);
11843 		freeb(mp1);
11844 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11845 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11846 	}
11847 	if (!mp1)
11848 		tcp->tcp_reass_tail = mp;
11849 }
11850 
11851 /*
11852  * Send up all messages queued on tcp_rcv_list.
11853  */
11854 static uint_t
11855 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11856 {
11857 	mblk_t *mp;
11858 	uint_t ret = 0;
11859 	uint_t thwin;
11860 #ifdef DEBUG
11861 	uint_t cnt = 0;
11862 #endif
11863 	/* Can't drain on an eager connection */
11864 	if (tcp->tcp_listener != NULL)
11865 		return (ret);
11866 
11867 	/*
11868 	 * Handle two cases here: we are currently fused or we were
11869 	 * previously fused and have some urgent data to be delivered
11870 	 * upstream.  The latter happens because we either ran out of
11871 	 * memory or were detached and therefore sending the SIGURG was
11872 	 * deferred until this point.  In either case we pass control
11873 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11874 	 * some work.
11875 	 */
11876 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11877 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11878 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11879 		    &tcp->tcp_fused_sigurg_mp))
11880 			return (ret);
11881 	}
11882 
11883 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11884 		tcp->tcp_rcv_list = mp->b_next;
11885 		mp->b_next = NULL;
11886 #ifdef DEBUG
11887 		cnt += msgdsize(mp);
11888 #endif
11889 		putnext(q, mp);
11890 	}
11891 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11892 	tcp->tcp_rcv_last_head = NULL;
11893 	tcp->tcp_rcv_last_tail = NULL;
11894 	tcp->tcp_rcv_cnt = 0;
11895 
11896 	/* Learn the latest rwnd information that we sent to the other side. */
11897 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11898 	    << tcp->tcp_rcv_ws;
11899 	/* This is peer's calculated send window (our receive window). */
11900 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11901 	/*
11902 	 * Increase the receive window to max.  But we need to do receiver
11903 	 * SWS avoidance.  This means that we need to check the increase of
11904 	 * of receive window is at least 1 MSS.
11905 	 */
11906 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11907 		/*
11908 		 * If the window that the other side knows is less than max
11909 		 * deferred acks segments, send an update immediately.
11910 		 */
11911 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11912 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11913 			ret = TH_ACK_NEEDED;
11914 		}
11915 		tcp->tcp_rwnd = q->q_hiwat;
11916 	}
11917 	/* No need for the push timer now. */
11918 	if (tcp->tcp_push_tid != 0) {
11919 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11920 		tcp->tcp_push_tid = 0;
11921 	}
11922 	return (ret);
11923 }
11924 
11925 /*
11926  * Queue data on tcp_rcv_list which is a b_next chain.
11927  * tcp_rcv_last_head/tail is the last element of this chain.
11928  * Each element of the chain is a b_cont chain.
11929  *
11930  * M_DATA messages are added to the current element.
11931  * Other messages are added as new (b_next) elements.
11932  */
11933 static void
11934 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11935 {
11936 	ASSERT(seg_len == msgdsize(mp));
11937 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11938 
11939 	if (tcp->tcp_rcv_list == NULL) {
11940 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11941 		tcp->tcp_rcv_list = mp;
11942 		tcp->tcp_rcv_last_head = mp;
11943 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11944 		tcp->tcp_rcv_last_tail->b_cont = mp;
11945 	} else {
11946 		tcp->tcp_rcv_last_head->b_next = mp;
11947 		tcp->tcp_rcv_last_head = mp;
11948 	}
11949 
11950 	while (mp->b_cont)
11951 		mp = mp->b_cont;
11952 
11953 	tcp->tcp_rcv_last_tail = mp;
11954 	tcp->tcp_rcv_cnt += seg_len;
11955 	tcp->tcp_rwnd -= seg_len;
11956 }
11957 
11958 /*
11959  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11960  *
11961  * This is the default entry function into TCP on the read side. TCP is
11962  * always entered via squeue i.e. using squeue's for mutual exclusion.
11963  * When classifier does a lookup to find the tcp, it also puts a reference
11964  * on the conn structure associated so the tcp is guaranteed to exist
11965  * when we come here. We still need to check the state because it might
11966  * as well has been closed. The squeue processing function i.e. squeue_enter,
11967  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11968  * CONN_DEC_REF.
11969  *
11970  * Apart from the default entry point, IP also sends packets directly to
11971  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11972  * connections.
11973  */
11974 void
11975 tcp_input(void *arg, mblk_t *mp, void *arg2)
11976 {
11977 	conn_t	*connp = (conn_t *)arg;
11978 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11979 
11980 	/* arg2 is the sqp */
11981 	ASSERT(arg2 != NULL);
11982 	ASSERT(mp != NULL);
11983 
11984 	/*
11985 	 * Don't accept any input on a closed tcp as this TCP logically does
11986 	 * not exist on the system. Don't proceed further with this TCP.
11987 	 * For eg. this packet could trigger another close of this tcp
11988 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11989 	 * tcp_clean_death / tcp_closei_local must be called at most once
11990 	 * on a TCP. In this case we need to refeed the packet into the
11991 	 * classifier and figure out where the packet should go. Need to
11992 	 * preserve the recv_ill somehow. Until we figure that out, for
11993 	 * now just drop the packet if we can't classify the packet.
11994 	 */
11995 	if (tcp->tcp_state == TCPS_CLOSED ||
11996 	    tcp->tcp_state == TCPS_BOUND) {
11997 		conn_t	*new_connp;
11998 
11999 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12000 		if (new_connp != NULL) {
12001 			tcp_reinput(new_connp, mp, arg2);
12002 			return;
12003 		}
12004 		/* We failed to classify. For now just drop the packet */
12005 		freemsg(mp);
12006 		return;
12007 	}
12008 
12009 	if (DB_TYPE(mp) == M_DATA)
12010 		tcp_rput_data(connp, mp, arg2);
12011 	else
12012 		tcp_rput_common(tcp, mp);
12013 }
12014 
12015 /*
12016  * The read side put procedure.
12017  * The packets passed up by ip are assume to be aligned according to
12018  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12019  */
12020 static void
12021 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12022 {
12023 	/*
12024 	 * tcp_rput_data() does not expect M_CTL except for the case
12025 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12026 	 * type. Need to make sure that any other M_CTLs don't make
12027 	 * it to tcp_rput_data since it is not expecting any and doesn't
12028 	 * check for it.
12029 	 */
12030 	if (DB_TYPE(mp) == M_CTL) {
12031 		switch (*(uint32_t *)(mp->b_rptr)) {
12032 		case TCP_IOC_ABORT_CONN:
12033 			/*
12034 			 * Handle connection abort request.
12035 			 */
12036 			tcp_ioctl_abort_handler(tcp, mp);
12037 			return;
12038 		case IPSEC_IN:
12039 			/*
12040 			 * Only secure icmp arrive in TCP and they
12041 			 * don't go through data path.
12042 			 */
12043 			tcp_icmp_error(tcp, mp);
12044 			return;
12045 		case IN_PKTINFO:
12046 			/*
12047 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12048 			 * sockets that are receiving IPv4 traffic. tcp
12049 			 */
12050 			ASSERT(tcp->tcp_family == AF_INET6);
12051 			ASSERT(tcp->tcp_ipv6_recvancillary &
12052 			    TCP_IPV6_RECVPKTINFO);
12053 			tcp_rput_data(tcp->tcp_connp, mp,
12054 			    tcp->tcp_connp->conn_sqp);
12055 			return;
12056 		case MDT_IOC_INFO_UPDATE:
12057 			/*
12058 			 * Handle Multidata information update; the
12059 			 * following routine will free the message.
12060 			 */
12061 			if (tcp->tcp_connp->conn_mdt_ok) {
12062 				tcp_mdt_update(tcp,
12063 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12064 				    B_FALSE);
12065 			}
12066 			freemsg(mp);
12067 			return;
12068 		default:
12069 			break;
12070 		}
12071 	}
12072 
12073 	/* No point processing the message if tcp is already closed */
12074 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12075 		freemsg(mp);
12076 		return;
12077 	}
12078 
12079 	tcp_rput_other(tcp, mp);
12080 }
12081 
12082 
12083 /* The minimum of smoothed mean deviation in RTO calculation. */
12084 #define	TCP_SD_MIN	400
12085 
12086 /*
12087  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12088  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12089  * are the same as those in Appendix A.2 of that paper.
12090  *
12091  * m = new measurement
12092  * sa = smoothed RTT average (8 * average estimates).
12093  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12094  */
12095 static void
12096 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12097 {
12098 	long m = TICK_TO_MSEC(rtt);
12099 	clock_t sa = tcp->tcp_rtt_sa;
12100 	clock_t sv = tcp->tcp_rtt_sd;
12101 	clock_t rto;
12102 
12103 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
12104 	tcp->tcp_rtt_update++;
12105 
12106 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12107 	if (sa != 0) {
12108 		/*
12109 		 * Update average estimator:
12110 		 *	new rtt = 7/8 old rtt + 1/8 Error
12111 		 */
12112 
12113 		/* m is now Error in estimate. */
12114 		m -= sa >> 3;
12115 		if ((sa += m) <= 0) {
12116 			/*
12117 			 * Don't allow the smoothed average to be negative.
12118 			 * We use 0 to denote reinitialization of the
12119 			 * variables.
12120 			 */
12121 			sa = 1;
12122 		}
12123 
12124 		/*
12125 		 * Update deviation estimator:
12126 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12127 		 */
12128 		if (m < 0)
12129 			m = -m;
12130 		m -= sv >> 2;
12131 		sv += m;
12132 	} else {
12133 		/*
12134 		 * This follows BSD's implementation.  So the reinitialized
12135 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12136 		 * link is bandwidth dominated, doubling the window size
12137 		 * during slow start means doubling the RTT.  We want to be
12138 		 * more conservative when we reinitialize our estimates.  3
12139 		 * is just a convenient number.
12140 		 */
12141 		sa = m << 3;
12142 		sv = m << 1;
12143 	}
12144 	if (sv < TCP_SD_MIN) {
12145 		/*
12146 		 * We do not know that if sa captures the delay ACK
12147 		 * effect as in a long train of segments, a receiver
12148 		 * does not delay its ACKs.  So set the minimum of sv
12149 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12150 		 * of BSD DATO.  That means the minimum of mean
12151 		 * deviation is 100 ms.
12152 		 *
12153 		 */
12154 		sv = TCP_SD_MIN;
12155 	}
12156 	tcp->tcp_rtt_sa = sa;
12157 	tcp->tcp_rtt_sd = sv;
12158 	/*
12159 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12160 	 *
12161 	 * Add tcp_rexmit_interval extra in case of extreme environment
12162 	 * where the algorithm fails to work.  The default value of
12163 	 * tcp_rexmit_interval_extra should be 0.
12164 	 *
12165 	 * As we use a finer grained clock than BSD and update
12166 	 * RTO for every ACKs, add in another .25 of RTT to the
12167 	 * deviation of RTO to accomodate burstiness of 1/4 of
12168 	 * window size.
12169 	 */
12170 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
12171 
12172 	if (rto > tcp_rexmit_interval_max) {
12173 		tcp->tcp_rto = tcp_rexmit_interval_max;
12174 	} else if (rto < tcp_rexmit_interval_min) {
12175 		tcp->tcp_rto = tcp_rexmit_interval_min;
12176 	} else {
12177 		tcp->tcp_rto = rto;
12178 	}
12179 
12180 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12181 	tcp->tcp_timer_backoff = 0;
12182 }
12183 
12184 /*
12185  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12186  * send queue which starts at the given seq. no.
12187  *
12188  * Parameters:
12189  *	tcp_t *tcp: the tcp instance pointer.
12190  *	uint32_t seq: the starting seq. no of the requested segment.
12191  *	int32_t *off: after the execution, *off will be the offset to
12192  *		the returned mblk which points to the requested seq no.
12193  *		It is the caller's responsibility to send in a non-null off.
12194  *
12195  * Return:
12196  *	A mblk_t pointer pointing to the requested segment in send queue.
12197  */
12198 static mblk_t *
12199 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12200 {
12201 	int32_t	cnt;
12202 	mblk_t	*mp;
12203 
12204 	/* Defensive coding.  Make sure we don't send incorrect data. */
12205 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12206 		return (NULL);
12207 
12208 	cnt = seq - tcp->tcp_suna;
12209 	mp = tcp->tcp_xmit_head;
12210 	while (cnt > 0 && mp != NULL) {
12211 		cnt -= mp->b_wptr - mp->b_rptr;
12212 		if (cnt < 0) {
12213 			cnt += mp->b_wptr - mp->b_rptr;
12214 			break;
12215 		}
12216 		mp = mp->b_cont;
12217 	}
12218 	ASSERT(mp != NULL);
12219 	*off = cnt;
12220 	return (mp);
12221 }
12222 
12223 /*
12224  * This function handles all retransmissions if SACK is enabled for this
12225  * connection.  First it calculates how many segments can be retransmitted
12226  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12227  * segments.  A segment is eligible if sack_cnt for that segment is greater
12228  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12229  * all eligible segments, it checks to see if TCP can send some new segments
12230  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12231  *
12232  * Parameters:
12233  *	tcp_t *tcp: the tcp structure of the connection.
12234  *	uint_t *flags: in return, appropriate value will be set for
12235  *	tcp_rput_data().
12236  */
12237 static void
12238 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12239 {
12240 	notsack_blk_t	*notsack_blk;
12241 	int32_t		usable_swnd;
12242 	int32_t		mss;
12243 	uint32_t	seg_len;
12244 	mblk_t		*xmit_mp;
12245 
12246 	ASSERT(tcp->tcp_sack_info != NULL);
12247 	ASSERT(tcp->tcp_notsack_list != NULL);
12248 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12249 
12250 	/* Defensive coding in case there is a bug... */
12251 	if (tcp->tcp_notsack_list == NULL) {
12252 		return;
12253 	}
12254 	notsack_blk = tcp->tcp_notsack_list;
12255 	mss = tcp->tcp_mss;
12256 
12257 	/*
12258 	 * Limit the num of outstanding data in the network to be
12259 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12260 	 */
12261 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12262 
12263 	/* At least retransmit 1 MSS of data. */
12264 	if (usable_swnd <= 0) {
12265 		usable_swnd = mss;
12266 	}
12267 
12268 	/* Make sure no new RTT samples will be taken. */
12269 	tcp->tcp_csuna = tcp->tcp_snxt;
12270 
12271 	notsack_blk = tcp->tcp_notsack_list;
12272 	while (usable_swnd > 0) {
12273 		mblk_t		*snxt_mp, *tmp_mp;
12274 		tcp_seq		begin = tcp->tcp_sack_snxt;
12275 		tcp_seq		end;
12276 		int32_t		off;
12277 
12278 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12279 			if (SEQ_GT(notsack_blk->end, begin) &&
12280 			    (notsack_blk->sack_cnt >=
12281 			    tcp_dupack_fast_retransmit)) {
12282 				end = notsack_blk->end;
12283 				if (SEQ_LT(begin, notsack_blk->begin)) {
12284 					begin = notsack_blk->begin;
12285 				}
12286 				break;
12287 			}
12288 		}
12289 		/*
12290 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12291 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12292 		 * set to tcp_cwnd_ssthresh.
12293 		 */
12294 		if (notsack_blk == NULL) {
12295 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12296 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12297 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12298 				ASSERT(tcp->tcp_cwnd > 0);
12299 				return;
12300 			} else {
12301 				usable_swnd = usable_swnd / mss;
12302 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12303 				    MAX(usable_swnd * mss, mss);
12304 				*flags |= TH_XMIT_NEEDED;
12305 				return;
12306 			}
12307 		}
12308 
12309 		/*
12310 		 * Note that we may send more than usable_swnd allows here
12311 		 * because of round off, but no more than 1 MSS of data.
12312 		 */
12313 		seg_len = end - begin;
12314 		if (seg_len > mss)
12315 			seg_len = mss;
12316 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12317 		ASSERT(snxt_mp != NULL);
12318 		/* This should not happen.  Defensive coding again... */
12319 		if (snxt_mp == NULL) {
12320 			return;
12321 		}
12322 
12323 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12324 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12325 		if (xmit_mp == NULL)
12326 			return;
12327 
12328 		usable_swnd -= seg_len;
12329 		tcp->tcp_pipe += seg_len;
12330 		tcp->tcp_sack_snxt = begin + seg_len;
12331 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
12332 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12333 
12334 		/*
12335 		 * Update the send timestamp to avoid false retransmission.
12336 		 */
12337 		snxt_mp->b_prev = (mblk_t *)lbolt;
12338 
12339 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
12340 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
12341 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
12342 		/*
12343 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12344 		 * This happens when new data sent during fast recovery is
12345 		 * also lost.  If TCP retransmits those new data, it needs
12346 		 * to extend SACK recover phase to avoid starting another
12347 		 * fast retransmit/recovery unnecessarily.
12348 		 */
12349 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12350 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12351 		}
12352 	}
12353 }
12354 
12355 /*
12356  * This function handles policy checking at TCP level for non-hard_bound/
12357  * detached connections.
12358  */
12359 static boolean_t
12360 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12361     boolean_t secure, boolean_t mctl_present)
12362 {
12363 	ipsec_latch_t *ipl = NULL;
12364 	ipsec_action_t *act = NULL;
12365 	mblk_t *data_mp;
12366 	ipsec_in_t *ii;
12367 	const char *reason;
12368 	kstat_named_t *counter;
12369 
12370 	ASSERT(mctl_present || !secure);
12371 
12372 	ASSERT((ipha == NULL && ip6h != NULL) ||
12373 	    (ip6h == NULL && ipha != NULL));
12374 
12375 	/*
12376 	 * We don't necessarily have an ipsec_in_act action to verify
12377 	 * policy because of assymetrical policy where we have only
12378 	 * outbound policy and no inbound policy (possible with global
12379 	 * policy).
12380 	 */
12381 	if (!secure) {
12382 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12383 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12384 			return (B_TRUE);
12385 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
12386 		    "tcp_check_policy", ipha, ip6h, secure);
12387 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12388 		    &ipdrops_tcp_clear, &tcp_dropper);
12389 		return (B_FALSE);
12390 	}
12391 
12392 	/*
12393 	 * We have a secure packet.
12394 	 */
12395 	if (act == NULL) {
12396 		ipsec_log_policy_failure(tcp->tcp_wq,
12397 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
12398 		    secure);
12399 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12400 		    &ipdrops_tcp_secure, &tcp_dropper);
12401 		return (B_FALSE);
12402 	}
12403 
12404 	/*
12405 	 * XXX This whole routine is currently incorrect.  ipl should
12406 	 * be set to the latch pointer, but is currently not set, so
12407 	 * we initialize it to NULL to avoid picking up random garbage.
12408 	 */
12409 	if (ipl == NULL)
12410 		return (B_TRUE);
12411 
12412 	data_mp = first_mp->b_cont;
12413 
12414 	ii = (ipsec_in_t *)first_mp->b_rptr;
12415 
12416 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12417 	    &counter)) {
12418 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
12419 		return (B_TRUE);
12420 	}
12421 	(void) strlog(TCP_MODULE_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12422 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12423 	    reason);
12424 	BUMP_MIB(&ip_mib, ipsecInFailed);
12425 
12426 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
12427 	return (B_FALSE);
12428 }
12429 
12430 /*
12431  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12432  * retransmission after a timeout.
12433  *
12434  * To limit the number of duplicate segments, we limit the number of segment
12435  * to be sent in one time to tcp_snd_burst, the burst variable.
12436  */
12437 static void
12438 tcp_ss_rexmit(tcp_t *tcp)
12439 {
12440 	uint32_t	snxt;
12441 	uint32_t	smax;
12442 	int32_t		win;
12443 	int32_t		mss;
12444 	int32_t		off;
12445 	int32_t		burst = tcp->tcp_snd_burst;
12446 	mblk_t		*snxt_mp;
12447 
12448 	/*
12449 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12450 	 * all unack'ed segments.
12451 	 */
12452 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12453 		smax = tcp->tcp_rexmit_max;
12454 		snxt = tcp->tcp_rexmit_nxt;
12455 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12456 			snxt = tcp->tcp_suna;
12457 		}
12458 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12459 		win -= snxt - tcp->tcp_suna;
12460 		mss = tcp->tcp_mss;
12461 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12462 
12463 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12464 		    (burst > 0) && (snxt_mp != NULL)) {
12465 			mblk_t	*xmit_mp;
12466 			mblk_t	*old_snxt_mp = snxt_mp;
12467 			uint32_t cnt = mss;
12468 
12469 			if (win < cnt) {
12470 				cnt = win;
12471 			}
12472 			if (SEQ_GT(snxt + cnt, smax)) {
12473 				cnt = smax - snxt;
12474 			}
12475 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12476 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12477 			if (xmit_mp == NULL)
12478 				return;
12479 
12480 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12481 
12482 			snxt += cnt;
12483 			win -= cnt;
12484 			/*
12485 			 * Update the send timestamp to avoid false
12486 			 * retransmission.
12487 			 */
12488 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12489 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
12490 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
12491 
12492 			tcp->tcp_rexmit_nxt = snxt;
12493 			burst--;
12494 		}
12495 		/*
12496 		 * If we have transmitted all we have at the time
12497 		 * we started the retranmission, we can leave
12498 		 * the rest of the job to tcp_wput_data().  But we
12499 		 * need to check the send window first.  If the
12500 		 * win is not 0, go on with tcp_wput_data().
12501 		 */
12502 		if (SEQ_LT(snxt, smax) || win == 0) {
12503 			return;
12504 		}
12505 	}
12506 	/* Only call tcp_wput_data() if there is data to be sent. */
12507 	if (tcp->tcp_unsent) {
12508 		tcp_wput_data(tcp, NULL, B_FALSE);
12509 	}
12510 }
12511 
12512 /*
12513  * Process all TCP option in SYN segment.  Note that this function should
12514  * be called after tcp_adapt_ire() is called so that the necessary info
12515  * from IRE is already set in the tcp structure.
12516  *
12517  * This function sets up the correct tcp_mss value according to the
12518  * MSS option value and our header size.  It also sets up the window scale
12519  * and timestamp values, and initialize SACK info blocks.  But it does not
12520  * change receive window size after setting the tcp_mss value.  The caller
12521  * should do the appropriate change.
12522  */
12523 void
12524 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12525 {
12526 	int options;
12527 	tcp_opt_t tcpopt;
12528 	uint32_t mss_max;
12529 	char *tmp_tcph;
12530 
12531 	tcpopt.tcp = NULL;
12532 	options = tcp_parse_options(tcph, &tcpopt);
12533 
12534 	/*
12535 	 * Process MSS option.  Note that MSS option value does not account
12536 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12537 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12538 	 * IPv6.
12539 	 */
12540 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12541 		if (tcp->tcp_ipversion == IPV4_VERSION)
12542 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
12543 		else
12544 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
12545 	} else {
12546 		if (tcp->tcp_ipversion == IPV4_VERSION)
12547 			mss_max = tcp_mss_max_ipv4;
12548 		else
12549 			mss_max = tcp_mss_max_ipv6;
12550 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
12551 			tcpopt.tcp_opt_mss = tcp_mss_min;
12552 		else if (tcpopt.tcp_opt_mss > mss_max)
12553 			tcpopt.tcp_opt_mss = mss_max;
12554 	}
12555 
12556 	/* Process Window Scale option. */
12557 	if (options & TCP_OPT_WSCALE_PRESENT) {
12558 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12559 		tcp->tcp_snd_ws_ok = B_TRUE;
12560 	} else {
12561 		tcp->tcp_snd_ws = B_FALSE;
12562 		tcp->tcp_snd_ws_ok = B_FALSE;
12563 		tcp->tcp_rcv_ws = B_FALSE;
12564 	}
12565 
12566 	/* Process Timestamp option. */
12567 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12568 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12569 		tmp_tcph = (char *)tcp->tcp_tcph;
12570 
12571 		tcp->tcp_snd_ts_ok = B_TRUE;
12572 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12573 		tcp->tcp_last_rcv_lbolt = lbolt64;
12574 		ASSERT(OK_32PTR(tmp_tcph));
12575 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12576 
12577 		/* Fill in our template header with basic timestamp option. */
12578 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12579 		tmp_tcph[0] = TCPOPT_NOP;
12580 		tmp_tcph[1] = TCPOPT_NOP;
12581 		tmp_tcph[2] = TCPOPT_TSTAMP;
12582 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12583 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12584 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12585 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12586 	} else {
12587 		tcp->tcp_snd_ts_ok = B_FALSE;
12588 	}
12589 
12590 	/*
12591 	 * Process SACK options.  If SACK is enabled for this connection,
12592 	 * then allocate the SACK info structure.  Note the following ways
12593 	 * when tcp_snd_sack_ok is set to true.
12594 	 *
12595 	 * For active connection: in tcp_adapt_ire() called in
12596 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12597 	 * is checked.
12598 	 *
12599 	 * For passive connection: in tcp_adapt_ire() called in
12600 	 * tcp_accept_comm().
12601 	 *
12602 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12603 	 * That check makes sure that if we did not send a SACK OK option,
12604 	 * we will not enable SACK for this connection even though the other
12605 	 * side sends us SACK OK option.  For active connection, the SACK
12606 	 * info structure has already been allocated.  So we need to free
12607 	 * it if SACK is disabled.
12608 	 */
12609 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12610 	    (tcp->tcp_snd_sack_ok ||
12611 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12612 		/* This should be true only in the passive case. */
12613 		if (tcp->tcp_sack_info == NULL) {
12614 			ASSERT(TCP_IS_DETACHED(tcp));
12615 			tcp->tcp_sack_info =
12616 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12617 		}
12618 		if (tcp->tcp_sack_info == NULL) {
12619 			tcp->tcp_snd_sack_ok = B_FALSE;
12620 		} else {
12621 			tcp->tcp_snd_sack_ok = B_TRUE;
12622 			if (tcp->tcp_snd_ts_ok) {
12623 				tcp->tcp_max_sack_blk = 3;
12624 			} else {
12625 				tcp->tcp_max_sack_blk = 4;
12626 			}
12627 		}
12628 	} else {
12629 		/*
12630 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12631 		 * no SACK info will be used for this
12632 		 * connection.  This assumes that SACK usage
12633 		 * permission is negotiated.  This may need
12634 		 * to be changed once this is clarified.
12635 		 */
12636 		if (tcp->tcp_sack_info != NULL) {
12637 			ASSERT(tcp->tcp_notsack_list == NULL);
12638 			kmem_cache_free(tcp_sack_info_cache,
12639 			    tcp->tcp_sack_info);
12640 			tcp->tcp_sack_info = NULL;
12641 		}
12642 		tcp->tcp_snd_sack_ok = B_FALSE;
12643 	}
12644 
12645 	/*
12646 	 * Now we know the exact TCP/IP header length, subtract
12647 	 * that from tcp_mss to get our side's MSS.
12648 	 */
12649 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12650 	/*
12651 	 * Here we assume that the other side's header size will be equal to
12652 	 * our header size.  We calculate the real MSS accordingly.  Need to
12653 	 * take into additional stuffs IPsec puts in.
12654 	 *
12655 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12656 	 */
12657 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12658 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12659 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12660 
12661 	/*
12662 	 * Set MSS to the smaller one of both ends of the connection.
12663 	 * We should not have called tcp_mss_set() before, but our
12664 	 * side of the MSS should have been set to a proper value
12665 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12666 	 * STREAM head parameters properly.
12667 	 *
12668 	 * If we have a larger-than-16-bit window but the other side
12669 	 * didn't want to do window scale, tcp_rwnd_set() will take
12670 	 * care of that.
12671 	 */
12672 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12673 }
12674 
12675 /*
12676  * Sends the T_CONN_IND to the listener. The caller calls this
12677  * functions via squeue to get inside the listener's perimeter
12678  * once the 3 way hand shake is done a T_CONN_IND needs to be
12679  * sent. As an optimization, the caller can call this directly
12680  * if listener's perimeter is same as eager's.
12681  */
12682 /* ARGSUSED */
12683 void
12684 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12685 {
12686 	conn_t			*lconnp = (conn_t *)arg;
12687 	tcp_t			*listener = lconnp->conn_tcp;
12688 	tcp_t			*tcp;
12689 	struct T_conn_ind	*conn_ind;
12690 	ipaddr_t 		*addr_cache;
12691 	boolean_t		need_send_conn_ind = B_FALSE;
12692 
12693 	/* retrieve the eager */
12694 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12695 	ASSERT(conn_ind->OPT_offset != 0 &&
12696 	    conn_ind->OPT_length == sizeof (intptr_t));
12697 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12698 		conn_ind->OPT_length);
12699 
12700 	/*
12701 	 * TLI/XTI applications will get confused by
12702 	 * sending eager as an option since it violates
12703 	 * the option semantics. So remove the eager as
12704 	 * option since TLI/XTI app doesn't need it anyway.
12705 	 */
12706 	if (!TCP_IS_SOCKET(listener)) {
12707 		conn_ind->OPT_length = 0;
12708 		conn_ind->OPT_offset = 0;
12709 	}
12710 	if (listener->tcp_state == TCPS_CLOSED ||
12711 	    TCP_IS_DETACHED(listener)) {
12712 		/*
12713 		 * If listener has closed, it would have caused a
12714 		 * a cleanup/blowoff to happen for the eager. We
12715 		 * just need to return.
12716 		 */
12717 		freemsg(mp);
12718 		return;
12719 	}
12720 
12721 
12722 	/*
12723 	 * if the conn_req_q is full defer passing up the
12724 	 * T_CONN_IND until space is availabe after t_accept()
12725 	 * processing
12726 	 */
12727 	mutex_enter(&listener->tcp_eager_lock);
12728 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12729 		tcp_t *tail;
12730 
12731 		/*
12732 		 * The eager already has an extra ref put in tcp_rput_data
12733 		 * so that it stays till accept comes back even though it
12734 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12735 		 */
12736 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12737 		listener->tcp_conn_req_cnt_q0--;
12738 		listener->tcp_conn_req_cnt_q++;
12739 
12740 		/* Move from SYN_RCVD to ESTABLISHED list  */
12741 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12742 		    tcp->tcp_eager_prev_q0;
12743 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12744 		    tcp->tcp_eager_next_q0;
12745 		tcp->tcp_eager_prev_q0 = NULL;
12746 		tcp->tcp_eager_next_q0 = NULL;
12747 
12748 		/*
12749 		 * Insert at end of the queue because sockfs
12750 		 * sends down T_CONN_RES in chronological
12751 		 * order. Leaving the older conn indications
12752 		 * at front of the queue helps reducing search
12753 		 * time.
12754 		 */
12755 		tail = listener->tcp_eager_last_q;
12756 		if (tail != NULL)
12757 			tail->tcp_eager_next_q = tcp;
12758 		else
12759 			listener->tcp_eager_next_q = tcp;
12760 		listener->tcp_eager_last_q = tcp;
12761 		tcp->tcp_eager_next_q = NULL;
12762 		/*
12763 		 * Delay sending up the T_conn_ind until we are
12764 		 * done with the eager. Once we have have sent up
12765 		 * the T_conn_ind, the accept can potentially complete
12766 		 * any time and release the refhold we have on the eager.
12767 		 */
12768 		need_send_conn_ind = B_TRUE;
12769 	} else {
12770 		/*
12771 		 * Defer connection on q0 and set deferred
12772 		 * connection bit true
12773 		 */
12774 		tcp->tcp_conn_def_q0 = B_TRUE;
12775 
12776 		/* take tcp out of q0 ... */
12777 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12778 		    tcp->tcp_eager_next_q0;
12779 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12780 		    tcp->tcp_eager_prev_q0;
12781 
12782 		/* ... and place it at the end of q0 */
12783 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12784 		tcp->tcp_eager_next_q0 = listener;
12785 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12786 		listener->tcp_eager_prev_q0 = tcp;
12787 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12788 	}
12789 
12790 	/* we have timed out before */
12791 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12792 		tcp->tcp_syn_rcvd_timeout = 0;
12793 		listener->tcp_syn_rcvd_timeout--;
12794 		if (listener->tcp_syn_defense &&
12795 		    listener->tcp_syn_rcvd_timeout <=
12796 		    (tcp_conn_req_max_q0 >> 5) &&
12797 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12798 			listener->tcp_last_rcv_lbolt)) {
12799 			/*
12800 			 * Turn off the defense mode if we
12801 			 * believe the SYN attack is over.
12802 			 */
12803 			listener->tcp_syn_defense = B_FALSE;
12804 			if (listener->tcp_ip_addr_cache) {
12805 				kmem_free((void *)listener->tcp_ip_addr_cache,
12806 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12807 				listener->tcp_ip_addr_cache = NULL;
12808 			}
12809 		}
12810 	}
12811 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12812 	if (addr_cache != NULL) {
12813 		/*
12814 		 * We have finished a 3-way handshake with this
12815 		 * remote host. This proves the IP addr is good.
12816 		 * Cache it!
12817 		 */
12818 		addr_cache[IP_ADDR_CACHE_HASH(
12819 			tcp->tcp_remote)] = tcp->tcp_remote;
12820 	}
12821 	mutex_exit(&listener->tcp_eager_lock);
12822 	if (need_send_conn_ind)
12823 		putnext(listener->tcp_rq, mp);
12824 }
12825 
12826 mblk_t *
12827 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12828     uint_t *ifindexp, ip6_pkt_t *ippp)
12829 {
12830 	in_pktinfo_t	*pinfo;
12831 	ip6_t		*ip6h;
12832 	uchar_t		*rptr;
12833 	mblk_t		*first_mp = mp;
12834 	boolean_t	mctl_present = B_FALSE;
12835 	uint_t 		ifindex = 0;
12836 	ip6_pkt_t	ipp;
12837 	uint_t		ipvers;
12838 	uint_t		ip_hdr_len;
12839 
12840 	rptr = mp->b_rptr;
12841 	ASSERT(OK_32PTR(rptr));
12842 	ASSERT(tcp != NULL);
12843 	ipp.ipp_fields = 0;
12844 
12845 	switch DB_TYPE(mp) {
12846 	case M_CTL:
12847 		mp = mp->b_cont;
12848 		if (mp == NULL) {
12849 			freemsg(first_mp);
12850 			return (NULL);
12851 		}
12852 		if (DB_TYPE(mp) != M_DATA) {
12853 			freemsg(first_mp);
12854 			return (NULL);
12855 		}
12856 		mctl_present = B_TRUE;
12857 		break;
12858 	case M_DATA:
12859 		break;
12860 	default:
12861 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12862 		freemsg(mp);
12863 		return (NULL);
12864 	}
12865 	ipvers = IPH_HDR_VERSION(rptr);
12866 	if (ipvers == IPV4_VERSION) {
12867 		if (tcp == NULL) {
12868 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12869 			goto done;
12870 		}
12871 
12872 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12873 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12874 
12875 		/*
12876 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12877 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12878 		 */
12879 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12880 		    mctl_present) {
12881 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12882 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12883 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12884 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12885 				ipp.ipp_fields |= IPPF_IFINDEX;
12886 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12887 				ifindex = pinfo->in_pkt_ifindex;
12888 			}
12889 			freeb(first_mp);
12890 			mctl_present = B_FALSE;
12891 		}
12892 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12893 	} else {
12894 		ip6h = (ip6_t *)rptr;
12895 
12896 		ASSERT(ipvers == IPV6_VERSION);
12897 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12898 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12899 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12900 
12901 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12902 			uint8_t	nexthdrp;
12903 
12904 			/* Look for ifindex information */
12905 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12906 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12907 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12908 					BUMP_MIB(&ip_mib, tcpInErrs);
12909 					freemsg(first_mp);
12910 					return (NULL);
12911 				}
12912 
12913 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12914 					ASSERT(ip6i->ip6i_ifindex != 0);
12915 					ipp.ipp_fields |= IPPF_IFINDEX;
12916 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12917 					ifindex = ip6i->ip6i_ifindex;
12918 				}
12919 				rptr = (uchar_t *)&ip6i[1];
12920 				mp->b_rptr = rptr;
12921 				if (rptr == mp->b_wptr) {
12922 					mblk_t *mp1;
12923 					mp1 = mp->b_cont;
12924 					freeb(mp);
12925 					mp = mp1;
12926 					rptr = mp->b_rptr;
12927 				}
12928 				if (MBLKL(mp) < IPV6_HDR_LEN +
12929 				    sizeof (tcph_t)) {
12930 					BUMP_MIB(&ip_mib, tcpInErrs);
12931 					freemsg(first_mp);
12932 					return (NULL);
12933 				}
12934 				ip6h = (ip6_t *)rptr;
12935 			}
12936 
12937 			/*
12938 			 * Find any potentially interesting extension headers
12939 			 * as well as the length of the IPv6 + extension
12940 			 * headers.
12941 			 */
12942 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12943 			/* Verify if this is a TCP packet */
12944 			if (nexthdrp != IPPROTO_TCP) {
12945 				BUMP_MIB(&ip_mib, tcpInErrs);
12946 				freemsg(first_mp);
12947 				return (NULL);
12948 			}
12949 		} else {
12950 			ip_hdr_len = IPV6_HDR_LEN;
12951 		}
12952 	}
12953 
12954 done:
12955 	if (ipversp != NULL)
12956 		*ipversp = ipvers;
12957 	if (ip_hdr_lenp != NULL)
12958 		*ip_hdr_lenp = ip_hdr_len;
12959 	if (ippp != NULL)
12960 		*ippp = ipp;
12961 	if (ifindexp != NULL)
12962 		*ifindexp = ifindex;
12963 	if (mctl_present) {
12964 		freeb(first_mp);
12965 	}
12966 	return (mp);
12967 }
12968 
12969 /*
12970  * Handle M_DATA messages from IP. Its called directly from IP via
12971  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12972  * in this path.
12973  *
12974  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12975  * v4 and v6), we are called through tcp_input() and a M_CTL can
12976  * be present for options but tcp_find_pktinfo() deals with it. We
12977  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12978  *
12979  * The first argument is always the connp/tcp to which the mp belongs.
12980  * There are no exceptions to this rule. The caller has already put
12981  * a reference on this connp/tcp and once tcp_rput_data() returns,
12982  * the squeue will do the refrele.
12983  *
12984  * The TH_SYN for the listener directly go to tcp_conn_request via
12985  * squeue.
12986  *
12987  * sqp: NULL = recursive, sqp != NULL means called from squeue
12988  */
12989 void
12990 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12991 {
12992 	int32_t		bytes_acked;
12993 	int32_t		gap;
12994 	mblk_t		*mp1;
12995 	uint_t		flags;
12996 	uint32_t	new_swnd = 0;
12997 	uchar_t		*iphdr;
12998 	uchar_t		*rptr;
12999 	int32_t		rgap;
13000 	uint32_t	seg_ack;
13001 	int		seg_len;
13002 	uint_t		ip_hdr_len;
13003 	uint32_t	seg_seq;
13004 	tcph_t		*tcph;
13005 	int		urp;
13006 	tcp_opt_t	tcpopt;
13007 	uint_t		ipvers;
13008 	ip6_pkt_t	ipp;
13009 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13010 	uint32_t	cwnd;
13011 	uint32_t	add;
13012 	int		npkt;
13013 	int		mss;
13014 	conn_t		*connp = (conn_t *)arg;
13015 	squeue_t	*sqp = (squeue_t *)arg2;
13016 	tcp_t		*tcp = connp->conn_tcp;
13017 
13018 	/*
13019 	 * RST from fused tcp loopback peer should trigger an unfuse.
13020 	 */
13021 	if (tcp->tcp_fused) {
13022 		TCP_STAT(tcp_fusion_aborted);
13023 		tcp_unfuse(tcp);
13024 	}
13025 
13026 	iphdr = mp->b_rptr;
13027 	rptr = mp->b_rptr;
13028 	ASSERT(OK_32PTR(rptr));
13029 
13030 	/*
13031 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13032 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13033 	 * necessary information.
13034 	 */
13035 	if (IPCL_IS_TCP4(connp)) {
13036 		ipvers = IPV4_VERSION;
13037 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13038 	} else {
13039 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13040 		    NULL, &ipp);
13041 		if (mp == NULL) {
13042 			TCP_STAT(tcp_rput_v6_error);
13043 			return;
13044 		}
13045 		iphdr = mp->b_rptr;
13046 		rptr = mp->b_rptr;
13047 	}
13048 	ASSERT(DB_TYPE(mp) == M_DATA);
13049 
13050 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13051 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13052 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13053 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13054 	seg_len = (int)(mp->b_wptr - rptr) -
13055 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13056 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13057 		do {
13058 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13059 			    (uintptr_t)INT_MAX);
13060 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13061 		} while ((mp1 = mp1->b_cont) != NULL &&
13062 		    mp1->b_datap->db_type == M_DATA);
13063 	}
13064 
13065 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13066 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13067 		    seg_len, tcph);
13068 		return;
13069 	}
13070 
13071 	if (sqp != NULL) {
13072 		/*
13073 		 * This is the correct place to update tcp_last_recv_time. Note
13074 		 * that it is also updated for tcp structure that belongs to
13075 		 * global and listener queues which do not really need updating.
13076 		 * But that should not cause any harm.  And it is updated for
13077 		 * all kinds of incoming segments, not only for data segments.
13078 		 */
13079 		tcp->tcp_last_recv_time = lbolt;
13080 	}
13081 
13082 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13083 
13084 	BUMP_LOCAL(tcp->tcp_ibsegs);
13085 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
13086 
13087 	if ((flags & TH_URG) && sqp != NULL) {
13088 		/*
13089 		 * TCP can't handle urgent pointers that arrive before
13090 		 * the connection has been accept()ed since it can't
13091 		 * buffer OOB data.  Discard segment if this happens.
13092 		 *
13093 		 * Nor can it reassemble urgent pointers, so discard
13094 		 * if it's not the next segment expected.
13095 		 *
13096 		 * Otherwise, collapse chain into one mblk (discard if
13097 		 * that fails).  This makes sure the headers, retransmitted
13098 		 * data, and new data all are in the same mblk.
13099 		 */
13100 		ASSERT(mp != NULL);
13101 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
13102 			freemsg(mp);
13103 			return;
13104 		}
13105 		/* Update pointers into message */
13106 		iphdr = rptr = mp->b_rptr;
13107 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13108 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13109 			/*
13110 			 * Since we can't handle any data with this urgent
13111 			 * pointer that is out of sequence, we expunge
13112 			 * the data.  This allows us to still register
13113 			 * the urgent mark and generate the M_PCSIG,
13114 			 * which we can do.
13115 			 */
13116 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13117 			seg_len = 0;
13118 		}
13119 	}
13120 
13121 	switch (tcp->tcp_state) {
13122 	case TCPS_SYN_SENT:
13123 		if (flags & TH_ACK) {
13124 			/*
13125 			 * Note that our stack cannot send data before a
13126 			 * connection is established, therefore the
13127 			 * following check is valid.  Otherwise, it has
13128 			 * to be changed.
13129 			 */
13130 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13131 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13132 				freemsg(mp);
13133 				if (flags & TH_RST)
13134 					return;
13135 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13136 				    tcp, seg_ack, 0, TH_RST);
13137 				return;
13138 			}
13139 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13140 		}
13141 		if (flags & TH_RST) {
13142 			freemsg(mp);
13143 			if (flags & TH_ACK)
13144 				(void) tcp_clean_death(tcp,
13145 				    ECONNREFUSED, 13);
13146 			return;
13147 		}
13148 		if (!(flags & TH_SYN)) {
13149 			freemsg(mp);
13150 			return;
13151 		}
13152 
13153 		/* Process all TCP options. */
13154 		tcp_process_options(tcp, tcph);
13155 		/*
13156 		 * The following changes our rwnd to be a multiple of the
13157 		 * MIN(peer MSS, our MSS) for performance reason.
13158 		 */
13159 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13160 		    tcp->tcp_mss));
13161 
13162 		/* Is the other end ECN capable? */
13163 		if (tcp->tcp_ecn_ok) {
13164 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13165 				tcp->tcp_ecn_ok = B_FALSE;
13166 			}
13167 		}
13168 		/*
13169 		 * Clear ECN flags because it may interfere with later
13170 		 * processing.
13171 		 */
13172 		flags &= ~(TH_ECE|TH_CWR);
13173 
13174 		tcp->tcp_irs = seg_seq;
13175 		tcp->tcp_rack = seg_seq;
13176 		tcp->tcp_rnxt = seg_seq + 1;
13177 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13178 		if (!TCP_IS_DETACHED(tcp)) {
13179 			/* Allocate room for SACK options if needed. */
13180 			if (tcp->tcp_snd_sack_ok) {
13181 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13182 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13183 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13184 			} else {
13185 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13186 				    tcp->tcp_hdr_len +
13187 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
13188 			}
13189 		}
13190 		if (flags & TH_ACK) {
13191 			/*
13192 			 * If we can't get the confirmation upstream, pretend
13193 			 * we didn't even see this one.
13194 			 *
13195 			 * XXX: how can we pretend we didn't see it if we
13196 			 * have updated rnxt et. al.
13197 			 *
13198 			 * For loopback we defer sending up the T_CONN_CON
13199 			 * until after some checks below.
13200 			 */
13201 			mp1 = NULL;
13202 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13203 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13204 				freemsg(mp);
13205 				return;
13206 			}
13207 			/* SYN was acked - making progress */
13208 			if (tcp->tcp_ipversion == IPV6_VERSION)
13209 				tcp->tcp_ip_forward_progress = B_TRUE;
13210 
13211 			/* One for the SYN */
13212 			tcp->tcp_suna = tcp->tcp_iss + 1;
13213 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13214 			tcp->tcp_state = TCPS_ESTABLISHED;
13215 
13216 			/*
13217 			 * If SYN was retransmitted, need to reset all
13218 			 * retransmission info.  This is because this
13219 			 * segment will be treated as a dup ACK.
13220 			 */
13221 			if (tcp->tcp_rexmit) {
13222 				tcp->tcp_rexmit = B_FALSE;
13223 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13224 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13225 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13226 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13227 				tcp->tcp_ms_we_have_waited = 0;
13228 
13229 				/*
13230 				 * Set tcp_cwnd back to 1 MSS, per
13231 				 * recommendation from
13232 				 * draft-floyd-incr-init-win-01.txt,
13233 				 * Increasing TCP's Initial Window.
13234 				 */
13235 				tcp->tcp_cwnd = tcp->tcp_mss;
13236 			}
13237 
13238 			tcp->tcp_swl1 = seg_seq;
13239 			tcp->tcp_swl2 = seg_ack;
13240 
13241 			new_swnd = BE16_TO_U16(tcph->th_win);
13242 			tcp->tcp_swnd = new_swnd;
13243 			if (new_swnd > tcp->tcp_max_swnd)
13244 				tcp->tcp_max_swnd = new_swnd;
13245 
13246 			/*
13247 			 * Always send the three-way handshake ack immediately
13248 			 * in order to make the connection complete as soon as
13249 			 * possible on the accepting host.
13250 			 */
13251 			flags |= TH_ACK_NEEDED;
13252 
13253 			/*
13254 			 * Special case for loopback.  At this point we have
13255 			 * received SYN-ACK from the remote endpoint.  In
13256 			 * order to ensure that both endpoints reach the
13257 			 * fused state prior to any data exchange, the final
13258 			 * ACK needs to be sent before we indicate T_CONN_CON
13259 			 * to the module upstream.
13260 			 */
13261 			if (tcp->tcp_loopback) {
13262 				mblk_t *ack_mp;
13263 
13264 				ASSERT(!tcp->tcp_unfusable);
13265 				ASSERT(mp1 != NULL);
13266 				/*
13267 				 * For loopback, we always get a pure SYN-ACK
13268 				 * and only need to send back the final ACK
13269 				 * with no data (this is because the other
13270 				 * tcp is ours and we don't do T/TCP).  This
13271 				 * final ACK triggers the passive side to
13272 				 * perform fusion in ESTABLISHED state.
13273 				 */
13274 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13275 					if (tcp->tcp_ack_tid != 0) {
13276 						(void) TCP_TIMER_CANCEL(tcp,
13277 						    tcp->tcp_ack_tid);
13278 						tcp->tcp_ack_tid = 0;
13279 					}
13280 					TCP_RECORD_TRACE(tcp, ack_mp,
13281 					    TCP_TRACE_SEND_PKT);
13282 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13283 					BUMP_LOCAL(tcp->tcp_obsegs);
13284 					BUMP_MIB(&tcp_mib, tcpOutAck);
13285 
13286 					/* Send up T_CONN_CON */
13287 					putnext(tcp->tcp_rq, mp1);
13288 
13289 					freemsg(mp);
13290 					return;
13291 				}
13292 				/*
13293 				 * Forget fusion; we need to handle more
13294 				 * complex cases below.  Send the deferred
13295 				 * T_CONN_CON message upstream and proceed
13296 				 * as usual.  Mark this tcp as not capable
13297 				 * of fusion.
13298 				 */
13299 				TCP_STAT(tcp_fusion_unfusable);
13300 				tcp->tcp_unfusable = B_TRUE;
13301 				putnext(tcp->tcp_rq, mp1);
13302 			}
13303 
13304 			/*
13305 			 * Check to see if there is data to be sent.  If
13306 			 * yes, set the transmit flag.  Then check to see
13307 			 * if received data processing needs to be done.
13308 			 * If not, go straight to xmit_check.  This short
13309 			 * cut is OK as we don't support T/TCP.
13310 			 */
13311 			if (tcp->tcp_unsent)
13312 				flags |= TH_XMIT_NEEDED;
13313 
13314 			if (seg_len == 0 && !(flags & TH_URG)) {
13315 				freemsg(mp);
13316 				goto xmit_check;
13317 			}
13318 
13319 			flags &= ~TH_SYN;
13320 			seg_seq++;
13321 			break;
13322 		}
13323 		tcp->tcp_state = TCPS_SYN_RCVD;
13324 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13325 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13326 		if (mp1) {
13327 			mblk_setcred(mp1, tcp->tcp_cred);
13328 			DB_CPID(mp1) = tcp->tcp_cpid;
13329 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
13330 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13331 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13332 		}
13333 		freemsg(mp);
13334 		return;
13335 	case TCPS_SYN_RCVD:
13336 		if (flags & TH_ACK) {
13337 			/*
13338 			 * In this state, a SYN|ACK packet is either bogus
13339 			 * because the other side must be ACKing our SYN which
13340 			 * indicates it has seen the ACK for their SYN and
13341 			 * shouldn't retransmit it or we're crossing SYNs
13342 			 * on active open.
13343 			 */
13344 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13345 				freemsg(mp);
13346 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13347 				    tcp, seg_ack, 0, TH_RST);
13348 				return;
13349 			}
13350 			/*
13351 			 * NOTE: RFC 793 pg. 72 says this should be
13352 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13353 			 * but that would mean we have an ack that ignored
13354 			 * our SYN.
13355 			 */
13356 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13357 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13358 				freemsg(mp);
13359 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13360 				    tcp, seg_ack, 0, TH_RST);
13361 				return;
13362 			}
13363 		}
13364 		break;
13365 	case TCPS_LISTEN:
13366 		/*
13367 		 * Only a TLI listener can come through this path when a
13368 		 * acceptor is going back to be a listener and a packet
13369 		 * for the acceptor hits the classifier. For a socket
13370 		 * listener, this can never happen because a listener
13371 		 * can never accept connection on itself and hence a
13372 		 * socket acceptor can not go back to being a listener.
13373 		 */
13374 		ASSERT(!TCP_IS_SOCKET(tcp));
13375 		/*FALLTHRU*/
13376 	case TCPS_CLOSED:
13377 	case TCPS_BOUND: {
13378 		conn_t	*new_connp;
13379 
13380 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
13381 		if (new_connp != NULL) {
13382 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13383 			return;
13384 		}
13385 		/* We failed to classify. For now just drop the packet */
13386 		freemsg(mp);
13387 		return;
13388 	}
13389 	case TCPS_IDLE:
13390 		/*
13391 		 * Handle the case where the tcp_clean_death() has happened
13392 		 * on a connection (application hasn't closed yet) but a packet
13393 		 * was already queued on squeue before tcp_clean_death()
13394 		 * was processed. Calling tcp_clean_death() twice on same
13395 		 * connection can result in weird behaviour.
13396 		 */
13397 		freemsg(mp);
13398 		return;
13399 	default:
13400 		break;
13401 	}
13402 
13403 	/*
13404 	 * Already on the correct queue/perimeter.
13405 	 * If this is a detached connection and not an eager
13406 	 * connection hanging off a listener then new data
13407 	 * (past the FIN) will cause a reset.
13408 	 * We do a special check here where it
13409 	 * is out of the main line, rather than check
13410 	 * if we are detached every time we see new
13411 	 * data down below.
13412 	 */
13413 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13414 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13415 		BUMP_MIB(&tcp_mib, tcpInClosed);
13416 		TCP_RECORD_TRACE(tcp,
13417 		    mp, TCP_TRACE_RECV_PKT);
13418 		freemsg(mp);
13419 		tcp_xmit_ctl("new data when detached", tcp,
13420 		    tcp->tcp_snxt, 0, TH_RST);
13421 		(void) tcp_clean_death(tcp, EPROTO, 12);
13422 		return;
13423 	}
13424 
13425 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13426 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13427 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13428 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13429 	mss = tcp->tcp_mss;
13430 
13431 	if (tcp->tcp_snd_ts_ok) {
13432 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13433 			/*
13434 			 * This segment is not acceptable.
13435 			 * Drop it and send back an ACK.
13436 			 */
13437 			freemsg(mp);
13438 			flags |= TH_ACK_NEEDED;
13439 			goto ack_check;
13440 		}
13441 	} else if (tcp->tcp_snd_sack_ok) {
13442 		ASSERT(tcp->tcp_sack_info != NULL);
13443 		tcpopt.tcp = tcp;
13444 		/*
13445 		 * SACK info in already updated in tcp_parse_options.  Ignore
13446 		 * all other TCP options...
13447 		 */
13448 		(void) tcp_parse_options(tcph, &tcpopt);
13449 	}
13450 try_again:;
13451 	gap = seg_seq - tcp->tcp_rnxt;
13452 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13453 	/*
13454 	 * gap is the amount of sequence space between what we expect to see
13455 	 * and what we got for seg_seq.  A positive value for gap means
13456 	 * something got lost.  A negative value means we got some old stuff.
13457 	 */
13458 	if (gap < 0) {
13459 		/* Old stuff present.  Is the SYN in there? */
13460 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13461 		    (seg_len != 0)) {
13462 			flags &= ~TH_SYN;
13463 			seg_seq++;
13464 			urp--;
13465 			/* Recompute the gaps after noting the SYN. */
13466 			goto try_again;
13467 		}
13468 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
13469 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
13470 		    (seg_len > -gap ? -gap : seg_len));
13471 		/* Remove the old stuff from seg_len. */
13472 		seg_len += gap;
13473 		/*
13474 		 * Anything left?
13475 		 * Make sure to check for unack'd FIN when rest of data
13476 		 * has been previously ack'd.
13477 		 */
13478 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13479 			/*
13480 			 * Resets are only valid if they lie within our offered
13481 			 * window.  If the RST bit is set, we just ignore this
13482 			 * segment.
13483 			 */
13484 			if (flags & TH_RST) {
13485 				freemsg(mp);
13486 				return;
13487 			}
13488 
13489 			/*
13490 			 * The arriving of dup data packets indicate that we
13491 			 * may have postponed an ack for too long, or the other
13492 			 * side's RTT estimate is out of shape. Start acking
13493 			 * more often.
13494 			 */
13495 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13496 			    tcp->tcp_rack_cnt >= 1 &&
13497 			    tcp->tcp_rack_abs_max > 2) {
13498 				tcp->tcp_rack_abs_max--;
13499 			}
13500 			tcp->tcp_rack_cur_max = 1;
13501 
13502 			/*
13503 			 * This segment is "unacceptable".  None of its
13504 			 * sequence space lies within our advertized window.
13505 			 *
13506 			 * Adjust seg_len to the original value for tracing.
13507 			 */
13508 			seg_len -= gap;
13509 			if (tcp->tcp_debug) {
13510 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13511 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13512 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13513 				    "seg_len %d, rnxt %u, snxt %u, %s",
13514 				    gap, rgap, flags, seg_seq, seg_ack,
13515 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13516 				    tcp_display(tcp, NULL,
13517 				    DISP_ADDR_AND_PORT));
13518 			}
13519 
13520 			/*
13521 			 * Arrange to send an ACK in response to the
13522 			 * unacceptable segment per RFC 793 page 69. There
13523 			 * is only one small difference between ours and the
13524 			 * acceptability test in the RFC - we accept ACK-only
13525 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13526 			 * will be generated.
13527 			 *
13528 			 * Note that we have to ACK an ACK-only packet at least
13529 			 * for stacks that send 0-length keep-alives with
13530 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13531 			 * section 4.2.3.6. As long as we don't ever generate
13532 			 * an unacceptable packet in response to an incoming
13533 			 * packet that is unacceptable, it should not cause
13534 			 * "ACK wars".
13535 			 */
13536 			flags |=  TH_ACK_NEEDED;
13537 
13538 			/*
13539 			 * Continue processing this segment in order to use the
13540 			 * ACK information it contains, but skip all other
13541 			 * sequence-number processing.	Processing the ACK
13542 			 * information is necessary in order to
13543 			 * re-synchronize connections that may have lost
13544 			 * synchronization.
13545 			 *
13546 			 * We clear seg_len and flag fields related to
13547 			 * sequence number processing as they are not
13548 			 * to be trusted for an unacceptable segment.
13549 			 */
13550 			seg_len = 0;
13551 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13552 			goto process_ack;
13553 		}
13554 
13555 		/* Fix seg_seq, and chew the gap off the front. */
13556 		seg_seq = tcp->tcp_rnxt;
13557 		urp += gap;
13558 		do {
13559 			mblk_t	*mp2;
13560 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13561 			    (uintptr_t)UINT_MAX);
13562 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13563 			if (gap > 0) {
13564 				mp->b_rptr = mp->b_wptr - gap;
13565 				break;
13566 			}
13567 			mp2 = mp;
13568 			mp = mp->b_cont;
13569 			freeb(mp2);
13570 		} while (gap < 0);
13571 		/*
13572 		 * If the urgent data has already been acknowledged, we
13573 		 * should ignore TH_URG below
13574 		 */
13575 		if (urp < 0)
13576 			flags &= ~TH_URG;
13577 	}
13578 	/*
13579 	 * rgap is the amount of stuff received out of window.  A negative
13580 	 * value is the amount out of window.
13581 	 */
13582 	if (rgap < 0) {
13583 		mblk_t	*mp2;
13584 
13585 		if (tcp->tcp_rwnd == 0) {
13586 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13587 		} else {
13588 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13589 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13590 		}
13591 
13592 		/*
13593 		 * seg_len does not include the FIN, so if more than
13594 		 * just the FIN is out of window, we act like we don't
13595 		 * see it.  (If just the FIN is out of window, rgap
13596 		 * will be zero and we will go ahead and acknowledge
13597 		 * the FIN.)
13598 		 */
13599 		flags &= ~TH_FIN;
13600 
13601 		/* Fix seg_len and make sure there is something left. */
13602 		seg_len += rgap;
13603 		if (seg_len <= 0) {
13604 			/*
13605 			 * Resets are only valid if they lie within our offered
13606 			 * window.  If the RST bit is set, we just ignore this
13607 			 * segment.
13608 			 */
13609 			if (flags & TH_RST) {
13610 				freemsg(mp);
13611 				return;
13612 			}
13613 
13614 			/* Per RFC 793, we need to send back an ACK. */
13615 			flags |= TH_ACK_NEEDED;
13616 
13617 			/*
13618 			 * Send SIGURG as soon as possible i.e. even
13619 			 * if the TH_URG was delivered in a window probe
13620 			 * packet (which will be unacceptable).
13621 			 *
13622 			 * We generate a signal if none has been generated
13623 			 * for this connection or if this is a new urgent
13624 			 * byte. Also send a zero-length "unmarked" message
13625 			 * to inform SIOCATMARK that this is not the mark.
13626 			 *
13627 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13628 			 * is sent up. This plus the check for old data
13629 			 * (gap >= 0) handles the wraparound of the sequence
13630 			 * number space without having to always track the
13631 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13632 			 * this max in its rcv_up variable).
13633 			 *
13634 			 * This prevents duplicate SIGURGS due to a "late"
13635 			 * zero-window probe when the T_EXDATA_IND has already
13636 			 * been sent up.
13637 			 */
13638 			if ((flags & TH_URG) &&
13639 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13640 			    tcp->tcp_urp_last))) {
13641 				mp1 = allocb(0, BPRI_MED);
13642 				if (mp1 == NULL) {
13643 					freemsg(mp);
13644 					return;
13645 				}
13646 				if (!TCP_IS_DETACHED(tcp) &&
13647 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13648 				    SIGURG)) {
13649 					/* Try again on the rexmit. */
13650 					freemsg(mp1);
13651 					freemsg(mp);
13652 					return;
13653 				}
13654 				/*
13655 				 * If the next byte would be the mark
13656 				 * then mark with MARKNEXT else mark
13657 				 * with NOTMARKNEXT.
13658 				 */
13659 				if (gap == 0 && urp == 0)
13660 					mp1->b_flag |= MSGMARKNEXT;
13661 				else
13662 					mp1->b_flag |= MSGNOTMARKNEXT;
13663 				freemsg(tcp->tcp_urp_mark_mp);
13664 				tcp->tcp_urp_mark_mp = mp1;
13665 				flags |= TH_SEND_URP_MARK;
13666 				tcp->tcp_urp_last_valid = B_TRUE;
13667 				tcp->tcp_urp_last = urp + seg_seq;
13668 			}
13669 			/*
13670 			 * If this is a zero window probe, continue to
13671 			 * process the ACK part.  But we need to set seg_len
13672 			 * to 0 to avoid data processing.  Otherwise just
13673 			 * drop the segment and send back an ACK.
13674 			 */
13675 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13676 				flags &= ~(TH_SYN | TH_URG);
13677 				seg_len = 0;
13678 				goto process_ack;
13679 			} else {
13680 				freemsg(mp);
13681 				goto ack_check;
13682 			}
13683 		}
13684 		/* Pitch out of window stuff off the end. */
13685 		rgap = seg_len;
13686 		mp2 = mp;
13687 		do {
13688 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13689 			    (uintptr_t)INT_MAX);
13690 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13691 			if (rgap < 0) {
13692 				mp2->b_wptr += rgap;
13693 				if ((mp1 = mp2->b_cont) != NULL) {
13694 					mp2->b_cont = NULL;
13695 					freemsg(mp1);
13696 				}
13697 				break;
13698 			}
13699 		} while ((mp2 = mp2->b_cont) != NULL);
13700 	}
13701 ok:;
13702 	/*
13703 	 * TCP should check ECN info for segments inside the window only.
13704 	 * Therefore the check should be done here.
13705 	 */
13706 	if (tcp->tcp_ecn_ok) {
13707 		if (flags & TH_CWR) {
13708 			tcp->tcp_ecn_echo_on = B_FALSE;
13709 		}
13710 		/*
13711 		 * Note that both ECN_CE and CWR can be set in the
13712 		 * same segment.  In this case, we once again turn
13713 		 * on ECN_ECHO.
13714 		 */
13715 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13716 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13717 
13718 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13719 				tcp->tcp_ecn_echo_on = B_TRUE;
13720 			}
13721 		} else {
13722 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13723 
13724 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13725 			    htonl(IPH_ECN_CE << 20)) {
13726 				tcp->tcp_ecn_echo_on = B_TRUE;
13727 			}
13728 		}
13729 	}
13730 
13731 	/*
13732 	 * Check whether we can update tcp_ts_recent.  This test is
13733 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13734 	 * Extensions for High Performance: An Update", Internet Draft.
13735 	 */
13736 	if (tcp->tcp_snd_ts_ok &&
13737 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13738 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13739 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13740 		tcp->tcp_last_rcv_lbolt = lbolt64;
13741 	}
13742 
13743 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13744 		/*
13745 		 * FIN in an out of order segment.  We record this in
13746 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13747 		 * Clear the FIN so that any check on FIN flag will fail.
13748 		 * Remember that FIN also counts in the sequence number
13749 		 * space.  So we need to ack out of order FIN only segments.
13750 		 */
13751 		if (flags & TH_FIN) {
13752 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13753 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13754 			flags &= ~TH_FIN;
13755 			flags |= TH_ACK_NEEDED;
13756 		}
13757 		if (seg_len > 0) {
13758 			/* Fill in the SACK blk list. */
13759 			if (tcp->tcp_snd_sack_ok) {
13760 				ASSERT(tcp->tcp_sack_info != NULL);
13761 				tcp_sack_insert(tcp->tcp_sack_list,
13762 				    seg_seq, seg_seq + seg_len,
13763 				    &(tcp->tcp_num_sack_blk));
13764 			}
13765 
13766 			/*
13767 			 * Attempt reassembly and see if we have something
13768 			 * ready to go.
13769 			 */
13770 			mp = tcp_reass(tcp, mp, seg_seq);
13771 			/* Always ack out of order packets */
13772 			flags |= TH_ACK_NEEDED | TH_PUSH;
13773 			if (mp) {
13774 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13775 				    (uintptr_t)INT_MAX);
13776 				seg_len = mp->b_cont ? msgdsize(mp) :
13777 					(int)(mp->b_wptr - mp->b_rptr);
13778 				seg_seq = tcp->tcp_rnxt;
13779 				/*
13780 				 * A gap is filled and the seq num and len
13781 				 * of the gap match that of a previously
13782 				 * received FIN, put the FIN flag back in.
13783 				 */
13784 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13785 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13786 					flags |= TH_FIN;
13787 					tcp->tcp_valid_bits &=
13788 					    ~TCP_OFO_FIN_VALID;
13789 				}
13790 			} else {
13791 				/*
13792 				 * Keep going even with NULL mp.
13793 				 * There may be a useful ACK or something else
13794 				 * we don't want to miss.
13795 				 *
13796 				 * But TCP should not perform fast retransmit
13797 				 * because of the ack number.  TCP uses
13798 				 * seg_len == 0 to determine if it is a pure
13799 				 * ACK.  And this is not a pure ACK.
13800 				 */
13801 				seg_len = 0;
13802 				ofo_seg = B_TRUE;
13803 			}
13804 		}
13805 	} else if (seg_len > 0) {
13806 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13807 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13808 		/*
13809 		 * If an out of order FIN was received before, and the seq
13810 		 * num and len of the new segment match that of the FIN,
13811 		 * put the FIN flag back in.
13812 		 */
13813 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13814 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13815 			flags |= TH_FIN;
13816 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13817 		}
13818 	}
13819 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13820 	if (flags & TH_RST) {
13821 		freemsg(mp);
13822 		switch (tcp->tcp_state) {
13823 		case TCPS_SYN_RCVD:
13824 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13825 			break;
13826 		case TCPS_ESTABLISHED:
13827 		case TCPS_FIN_WAIT_1:
13828 		case TCPS_FIN_WAIT_2:
13829 		case TCPS_CLOSE_WAIT:
13830 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13831 			break;
13832 		case TCPS_CLOSING:
13833 		case TCPS_LAST_ACK:
13834 			(void) tcp_clean_death(tcp, 0, 16);
13835 			break;
13836 		default:
13837 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13838 			(void) tcp_clean_death(tcp, ENXIO, 17);
13839 			break;
13840 		}
13841 		return;
13842 	}
13843 	if (flags & TH_SYN) {
13844 		/*
13845 		 * See RFC 793, Page 71
13846 		 *
13847 		 * The seq number must be in the window as it should
13848 		 * be "fixed" above.  If it is outside window, it should
13849 		 * be already rejected.  Note that we allow seg_seq to be
13850 		 * rnxt + rwnd because we want to accept 0 window probe.
13851 		 */
13852 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13853 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13854 		freemsg(mp);
13855 		/*
13856 		 * If the ACK flag is not set, just use our snxt as the
13857 		 * seq number of the RST segment.
13858 		 */
13859 		if (!(flags & TH_ACK)) {
13860 			seg_ack = tcp->tcp_snxt;
13861 		}
13862 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13863 		    TH_RST|TH_ACK);
13864 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13865 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13866 		return;
13867 	}
13868 	/*
13869 	 * urp could be -1 when the urp field in the packet is 0
13870 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13871 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13872 	 */
13873 	if (flags & TH_URG && urp >= 0) {
13874 		if (!tcp->tcp_urp_last_valid ||
13875 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13876 			/*
13877 			 * If we haven't generated the signal yet for this
13878 			 * urgent pointer value, do it now.  Also, send up a
13879 			 * zero-length M_DATA indicating whether or not this is
13880 			 * the mark. The latter is not needed when a
13881 			 * T_EXDATA_IND is sent up. However, if there are
13882 			 * allocation failures this code relies on the sender
13883 			 * retransmitting and the socket code for determining
13884 			 * the mark should not block waiting for the peer to
13885 			 * transmit. Thus, for simplicity we always send up the
13886 			 * mark indication.
13887 			 */
13888 			mp1 = allocb(0, BPRI_MED);
13889 			if (mp1 == NULL) {
13890 				freemsg(mp);
13891 				return;
13892 			}
13893 			if (!TCP_IS_DETACHED(tcp) &&
13894 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13895 				/* Try again on the rexmit. */
13896 				freemsg(mp1);
13897 				freemsg(mp);
13898 				return;
13899 			}
13900 			/*
13901 			 * Mark with NOTMARKNEXT for now.
13902 			 * The code below will change this to MARKNEXT
13903 			 * if we are at the mark.
13904 			 *
13905 			 * If there are allocation failures (e.g. in dupmsg
13906 			 * below) the next time tcp_rput_data sees the urgent
13907 			 * segment it will send up the MSG*MARKNEXT message.
13908 			 */
13909 			mp1->b_flag |= MSGNOTMARKNEXT;
13910 			freemsg(tcp->tcp_urp_mark_mp);
13911 			tcp->tcp_urp_mark_mp = mp1;
13912 			flags |= TH_SEND_URP_MARK;
13913 #ifdef DEBUG
13914 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
13915 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13916 			    "last %x, %s",
13917 			    seg_seq, urp, tcp->tcp_urp_last,
13918 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13919 #endif /* DEBUG */
13920 			tcp->tcp_urp_last_valid = B_TRUE;
13921 			tcp->tcp_urp_last = urp + seg_seq;
13922 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13923 			/*
13924 			 * An allocation failure prevented the previous
13925 			 * tcp_rput_data from sending up the allocated
13926 			 * MSG*MARKNEXT message - send it up this time
13927 			 * around.
13928 			 */
13929 			flags |= TH_SEND_URP_MARK;
13930 		}
13931 
13932 		/*
13933 		 * If the urgent byte is in this segment, make sure that it is
13934 		 * all by itself.  This makes it much easier to deal with the
13935 		 * possibility of an allocation failure on the T_exdata_ind.
13936 		 * Note that seg_len is the number of bytes in the segment, and
13937 		 * urp is the offset into the segment of the urgent byte.
13938 		 * urp < seg_len means that the urgent byte is in this segment.
13939 		 */
13940 		if (urp < seg_len) {
13941 			if (seg_len != 1) {
13942 				uint32_t  tmp_rnxt;
13943 				/*
13944 				 * Break it up and feed it back in.
13945 				 * Re-attach the IP header.
13946 				 */
13947 				mp->b_rptr = iphdr;
13948 				if (urp > 0) {
13949 					/*
13950 					 * There is stuff before the urgent
13951 					 * byte.
13952 					 */
13953 					mp1 = dupmsg(mp);
13954 					if (!mp1) {
13955 						/*
13956 						 * Trim from urgent byte on.
13957 						 * The rest will come back.
13958 						 */
13959 						(void) adjmsg(mp,
13960 						    urp - seg_len);
13961 						tcp_rput_data(connp,
13962 						    mp, NULL);
13963 						return;
13964 					}
13965 					(void) adjmsg(mp1, urp - seg_len);
13966 					/* Feed this piece back in. */
13967 					tmp_rnxt = tcp->tcp_rnxt;
13968 					tcp_rput_data(connp, mp1, NULL);
13969 					/*
13970 					 * If the data passed back in was not
13971 					 * processed (ie: bad ACK) sending
13972 					 * the remainder back in will cause a
13973 					 * loop. In this case, drop the
13974 					 * packet and let the sender try
13975 					 * sending a good packet.
13976 					 */
13977 					if (tmp_rnxt == tcp->tcp_rnxt) {
13978 						freemsg(mp);
13979 						return;
13980 					}
13981 				}
13982 				if (urp != seg_len - 1) {
13983 					uint32_t  tmp_rnxt;
13984 					/*
13985 					 * There is stuff after the urgent
13986 					 * byte.
13987 					 */
13988 					mp1 = dupmsg(mp);
13989 					if (!mp1) {
13990 						/*
13991 						 * Trim everything beyond the
13992 						 * urgent byte.  The rest will
13993 						 * come back.
13994 						 */
13995 						(void) adjmsg(mp,
13996 						    urp + 1 - seg_len);
13997 						tcp_rput_data(connp,
13998 						    mp, NULL);
13999 						return;
14000 					}
14001 					(void) adjmsg(mp1, urp + 1 - seg_len);
14002 					tmp_rnxt = tcp->tcp_rnxt;
14003 					tcp_rput_data(connp, mp1, NULL);
14004 					/*
14005 					 * If the data passed back in was not
14006 					 * processed (ie: bad ACK) sending
14007 					 * the remainder back in will cause a
14008 					 * loop. In this case, drop the
14009 					 * packet and let the sender try
14010 					 * sending a good packet.
14011 					 */
14012 					if (tmp_rnxt == tcp->tcp_rnxt) {
14013 						freemsg(mp);
14014 						return;
14015 					}
14016 				}
14017 				tcp_rput_data(connp, mp, NULL);
14018 				return;
14019 			}
14020 			/*
14021 			 * This segment contains only the urgent byte.  We
14022 			 * have to allocate the T_exdata_ind, if we can.
14023 			 */
14024 			if (!tcp->tcp_urp_mp) {
14025 				struct T_exdata_ind *tei;
14026 				mp1 = allocb(sizeof (struct T_exdata_ind),
14027 				    BPRI_MED);
14028 				if (!mp1) {
14029 					/*
14030 					 * Sigh... It'll be back.
14031 					 * Generate any MSG*MARK message now.
14032 					 */
14033 					freemsg(mp);
14034 					seg_len = 0;
14035 					if (flags & TH_SEND_URP_MARK) {
14036 
14037 
14038 						ASSERT(tcp->tcp_urp_mark_mp);
14039 						tcp->tcp_urp_mark_mp->b_flag &=
14040 							~MSGNOTMARKNEXT;
14041 						tcp->tcp_urp_mark_mp->b_flag |=
14042 							MSGMARKNEXT;
14043 					}
14044 					goto ack_check;
14045 				}
14046 				mp1->b_datap->db_type = M_PROTO;
14047 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14048 				tei->PRIM_type = T_EXDATA_IND;
14049 				tei->MORE_flag = 0;
14050 				mp1->b_wptr = (uchar_t *)&tei[1];
14051 				tcp->tcp_urp_mp = mp1;
14052 #ifdef DEBUG
14053 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14054 				    "tcp_rput: allocated exdata_ind %s",
14055 				    tcp_display(tcp, NULL,
14056 				    DISP_PORT_ONLY));
14057 #endif /* DEBUG */
14058 				/*
14059 				 * There is no need to send a separate MSG*MARK
14060 				 * message since the T_EXDATA_IND will be sent
14061 				 * now.
14062 				 */
14063 				flags &= ~TH_SEND_URP_MARK;
14064 				freemsg(tcp->tcp_urp_mark_mp);
14065 				tcp->tcp_urp_mark_mp = NULL;
14066 			}
14067 			/*
14068 			 * Now we are all set.  On the next putnext upstream,
14069 			 * tcp_urp_mp will be non-NULL and will get prepended
14070 			 * to what has to be this piece containing the urgent
14071 			 * byte.  If for any reason we abort this segment below,
14072 			 * if it comes back, we will have this ready, or it
14073 			 * will get blown off in close.
14074 			 */
14075 		} else if (urp == seg_len) {
14076 			/*
14077 			 * The urgent byte is the next byte after this sequence
14078 			 * number. If there is data it is marked with
14079 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14080 			 * since it is not needed. Otherwise, if the code
14081 			 * above just allocated a zero-length tcp_urp_mark_mp
14082 			 * message, that message is tagged with MSGMARKNEXT.
14083 			 * Sending up these MSGMARKNEXT messages makes
14084 			 * SIOCATMARK work correctly even though
14085 			 * the T_EXDATA_IND will not be sent up until the
14086 			 * urgent byte arrives.
14087 			 */
14088 			if (seg_len != 0) {
14089 				flags |= TH_MARKNEXT_NEEDED;
14090 				freemsg(tcp->tcp_urp_mark_mp);
14091 				tcp->tcp_urp_mark_mp = NULL;
14092 				flags &= ~TH_SEND_URP_MARK;
14093 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14094 				flags |= TH_SEND_URP_MARK;
14095 				tcp->tcp_urp_mark_mp->b_flag &=
14096 					~MSGNOTMARKNEXT;
14097 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14098 			}
14099 #ifdef DEBUG
14100 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14101 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14102 			    seg_len, flags,
14103 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14104 #endif /* DEBUG */
14105 		} else {
14106 			/* Data left until we hit mark */
14107 #ifdef DEBUG
14108 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
14109 			    "tcp_rput: URP %d bytes left, %s",
14110 			    urp - seg_len, tcp_display(tcp, NULL,
14111 			    DISP_PORT_ONLY));
14112 #endif /* DEBUG */
14113 		}
14114 	}
14115 
14116 process_ack:
14117 	if (!(flags & TH_ACK)) {
14118 		freemsg(mp);
14119 		goto xmit_check;
14120 	}
14121 	}
14122 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14123 
14124 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14125 		tcp->tcp_ip_forward_progress = B_TRUE;
14126 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14127 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
14128 			/* 3-way handshake complete - pass up the T_CONN_IND */
14129 			tcp_t	*listener = tcp->tcp_listener;
14130 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14131 
14132 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14133 			/*
14134 			 * We are here means eager is fine but it can
14135 			 * get a TH_RST at any point between now and till
14136 			 * accept completes and disappear. We need to
14137 			 * ensure that reference to eager is valid after
14138 			 * we get out of eager's perimeter. So we do
14139 			 * an extra refhold.
14140 			 */
14141 			CONN_INC_REF(connp);
14142 
14143 			/*
14144 			 * The listener also exists because of the refhold
14145 			 * done in tcp_conn_request. Its possible that it
14146 			 * might have closed. We will check that once we
14147 			 * get inside listeners context.
14148 			 */
14149 			CONN_INC_REF(listener->tcp_connp);
14150 			if (listener->tcp_connp->conn_sqp ==
14151 			    connp->conn_sqp) {
14152 				tcp_send_conn_ind(listener->tcp_connp, mp,
14153 				    listener->tcp_connp->conn_sqp);
14154 				CONN_DEC_REF(listener->tcp_connp);
14155 			} else if (!tcp->tcp_loopback) {
14156 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14157 				    tcp_send_conn_ind,
14158 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14159 			} else {
14160 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14161 				    tcp_send_conn_ind, listener->tcp_connp,
14162 				    SQTAG_TCP_CONN_IND);
14163 			}
14164 		}
14165 
14166 		if (tcp->tcp_active_open) {
14167 			/*
14168 			 * We are seeing the final ack in the three way
14169 			 * hand shake of a active open'ed connection
14170 			 * so we must send up a T_CONN_CON
14171 			 */
14172 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14173 				freemsg(mp);
14174 				return;
14175 			}
14176 			/*
14177 			 * Don't fuse the loopback endpoints for
14178 			 * simultaneous active opens.
14179 			 */
14180 			if (tcp->tcp_loopback) {
14181 				TCP_STAT(tcp_fusion_unfusable);
14182 				tcp->tcp_unfusable = B_TRUE;
14183 			}
14184 		}
14185 
14186 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14187 		bytes_acked--;
14188 		/* SYN was acked - making progress */
14189 		if (tcp->tcp_ipversion == IPV6_VERSION)
14190 			tcp->tcp_ip_forward_progress = B_TRUE;
14191 
14192 		/*
14193 		 * If SYN was retransmitted, need to reset all
14194 		 * retransmission info as this segment will be
14195 		 * treated as a dup ACK.
14196 		 */
14197 		if (tcp->tcp_rexmit) {
14198 			tcp->tcp_rexmit = B_FALSE;
14199 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14200 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14201 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14202 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14203 			tcp->tcp_ms_we_have_waited = 0;
14204 			tcp->tcp_cwnd = mss;
14205 		}
14206 
14207 		/*
14208 		 * We set the send window to zero here.
14209 		 * This is needed if there is data to be
14210 		 * processed already on the queue.
14211 		 * Later (at swnd_update label), the
14212 		 * "new_swnd > tcp_swnd" condition is satisfied
14213 		 * the XMIT_NEEDED flag is set in the current
14214 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14215 		 * called if there is already data on queue in
14216 		 * this state.
14217 		 */
14218 		tcp->tcp_swnd = 0;
14219 
14220 		if (new_swnd > tcp->tcp_max_swnd)
14221 			tcp->tcp_max_swnd = new_swnd;
14222 		tcp->tcp_swl1 = seg_seq;
14223 		tcp->tcp_swl2 = seg_ack;
14224 		tcp->tcp_state = TCPS_ESTABLISHED;
14225 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14226 
14227 		/* Fuse when both sides are in ESTABLISHED state */
14228 		if (tcp->tcp_loopback && do_tcp_fusion)
14229 			tcp_fuse(tcp, iphdr, tcph);
14230 
14231 	}
14232 	/* This code follows 4.4BSD-Lite2 mostly. */
14233 	if (bytes_acked < 0)
14234 		goto est;
14235 
14236 	/*
14237 	 * If TCP is ECN capable and the congestion experience bit is
14238 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14239 	 * done once per window (or more loosely, per RTT).
14240 	 */
14241 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14242 		tcp->tcp_cwr = B_FALSE;
14243 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14244 		if (!tcp->tcp_cwr) {
14245 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14246 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14247 			tcp->tcp_cwnd = npkt * mss;
14248 			/*
14249 			 * If the cwnd is 0, use the timer to clock out
14250 			 * new segments.  This is required by the ECN spec.
14251 			 */
14252 			if (npkt == 0) {
14253 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14254 				/*
14255 				 * This makes sure that when the ACK comes
14256 				 * back, we will increase tcp_cwnd by 1 MSS.
14257 				 */
14258 				tcp->tcp_cwnd_cnt = 0;
14259 			}
14260 			tcp->tcp_cwr = B_TRUE;
14261 			/*
14262 			 * This marks the end of the current window of in
14263 			 * flight data.  That is why we don't use
14264 			 * tcp_suna + tcp_swnd.  Only data in flight can
14265 			 * provide ECN info.
14266 			 */
14267 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14268 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14269 		}
14270 	}
14271 
14272 	mp1 = tcp->tcp_xmit_head;
14273 	if (bytes_acked == 0) {
14274 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14275 			int dupack_cnt;
14276 
14277 			BUMP_MIB(&tcp_mib, tcpInDupAck);
14278 			/*
14279 			 * Fast retransmit.  When we have seen exactly three
14280 			 * identical ACKs while we have unacked data
14281 			 * outstanding we take it as a hint that our peer
14282 			 * dropped something.
14283 			 *
14284 			 * If TCP is retransmitting, don't do fast retransmit.
14285 			 */
14286 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14287 			    ! tcp->tcp_rexmit) {
14288 				/* Do Limited Transmit */
14289 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14290 				    tcp_dupack_fast_retransmit) {
14291 					/*
14292 					 * RFC 3042
14293 					 *
14294 					 * What we need to do is temporarily
14295 					 * increase tcp_cwnd so that new
14296 					 * data can be sent if it is allowed
14297 					 * by the receive window (tcp_rwnd).
14298 					 * tcp_wput_data() will take care of
14299 					 * the rest.
14300 					 *
14301 					 * If the connection is SACK capable,
14302 					 * only do limited xmit when there
14303 					 * is SACK info.
14304 					 *
14305 					 * Note how tcp_cwnd is incremented.
14306 					 * The first dup ACK will increase
14307 					 * it by 1 MSS.  The second dup ACK
14308 					 * will increase it by 2 MSS.  This
14309 					 * means that only 1 new segment will
14310 					 * be sent for each dup ACK.
14311 					 */
14312 					if (tcp->tcp_unsent > 0 &&
14313 					    (!tcp->tcp_snd_sack_ok ||
14314 					    (tcp->tcp_snd_sack_ok &&
14315 					    tcp->tcp_notsack_list != NULL))) {
14316 						tcp->tcp_cwnd += mss <<
14317 						    (tcp->tcp_dupack_cnt - 1);
14318 						flags |= TH_LIMIT_XMIT;
14319 					}
14320 				} else if (dupack_cnt ==
14321 				    tcp_dupack_fast_retransmit) {
14322 
14323 				/*
14324 				 * If we have reduced tcp_ssthresh
14325 				 * because of ECN, do not reduce it again
14326 				 * unless it is already one window of data
14327 				 * away.  After one window of data, tcp_cwr
14328 				 * should then be cleared.  Note that
14329 				 * for non ECN capable connection, tcp_cwr
14330 				 * should always be false.
14331 				 *
14332 				 * Adjust cwnd since the duplicate
14333 				 * ack indicates that a packet was
14334 				 * dropped (due to congestion.)
14335 				 */
14336 				if (!tcp->tcp_cwr) {
14337 					npkt = ((tcp->tcp_snxt -
14338 					    tcp->tcp_suna) >> 1) / mss;
14339 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14340 					    mss;
14341 					tcp->tcp_cwnd = (npkt +
14342 					    tcp->tcp_dupack_cnt) * mss;
14343 				}
14344 				if (tcp->tcp_ecn_ok) {
14345 					tcp->tcp_cwr = B_TRUE;
14346 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14347 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14348 				}
14349 
14350 				/*
14351 				 * We do Hoe's algorithm.  Refer to her
14352 				 * paper "Improving the Start-up Behavior
14353 				 * of a Congestion Control Scheme for TCP,"
14354 				 * appeared in SIGCOMM'96.
14355 				 *
14356 				 * Save highest seq no we have sent so far.
14357 				 * Be careful about the invisible FIN byte.
14358 				 */
14359 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14360 				    (tcp->tcp_unsent == 0)) {
14361 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14362 				} else {
14363 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14364 				}
14365 
14366 				/*
14367 				 * Do not allow bursty traffic during.
14368 				 * fast recovery.  Refer to Fall and Floyd's
14369 				 * paper "Simulation-based Comparisons of
14370 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14371 				 * This is a best current practise.
14372 				 */
14373 				tcp->tcp_snd_burst = TCP_CWND_SS;
14374 
14375 				/*
14376 				 * For SACK:
14377 				 * Calculate tcp_pipe, which is the
14378 				 * estimated number of bytes in
14379 				 * network.
14380 				 *
14381 				 * tcp_fack is the highest sack'ed seq num
14382 				 * TCP has received.
14383 				 *
14384 				 * tcp_pipe is explained in the above quoted
14385 				 * Fall and Floyd's paper.  tcp_fack is
14386 				 * explained in Mathis and Mahdavi's
14387 				 * "Forward Acknowledgment: Refining TCP
14388 				 * Congestion Control" in SIGCOMM '96.
14389 				 */
14390 				if (tcp->tcp_snd_sack_ok) {
14391 					ASSERT(tcp->tcp_sack_info != NULL);
14392 					if (tcp->tcp_notsack_list != NULL) {
14393 						tcp->tcp_pipe = tcp->tcp_snxt -
14394 						    tcp->tcp_fack;
14395 						tcp->tcp_sack_snxt = seg_ack;
14396 						flags |= TH_NEED_SACK_REXMIT;
14397 					} else {
14398 						/*
14399 						 * Always initialize tcp_pipe
14400 						 * even though we don't have
14401 						 * any SACK info.  If later
14402 						 * we get SACK info and
14403 						 * tcp_pipe is not initialized,
14404 						 * funny things will happen.
14405 						 */
14406 						tcp->tcp_pipe =
14407 						    tcp->tcp_cwnd_ssthresh;
14408 					}
14409 				} else {
14410 					flags |= TH_REXMIT_NEEDED;
14411 				} /* tcp_snd_sack_ok */
14412 
14413 				} else {
14414 					/*
14415 					 * Here we perform congestion
14416 					 * avoidance, but NOT slow start.
14417 					 * This is known as the Fast
14418 					 * Recovery Algorithm.
14419 					 */
14420 					if (tcp->tcp_snd_sack_ok &&
14421 					    tcp->tcp_notsack_list != NULL) {
14422 						flags |= TH_NEED_SACK_REXMIT;
14423 						tcp->tcp_pipe -= mss;
14424 						if (tcp->tcp_pipe < 0)
14425 							tcp->tcp_pipe = 0;
14426 					} else {
14427 					/*
14428 					 * We know that one more packet has
14429 					 * left the pipe thus we can update
14430 					 * cwnd.
14431 					 */
14432 					cwnd = tcp->tcp_cwnd + mss;
14433 					if (cwnd > tcp->tcp_cwnd_max)
14434 						cwnd = tcp->tcp_cwnd_max;
14435 					tcp->tcp_cwnd = cwnd;
14436 					if (tcp->tcp_unsent > 0)
14437 						flags |= TH_XMIT_NEEDED;
14438 					}
14439 				}
14440 			}
14441 		} else if (tcp->tcp_zero_win_probe) {
14442 			/*
14443 			 * If the window has opened, need to arrange
14444 			 * to send additional data.
14445 			 */
14446 			if (new_swnd != 0) {
14447 				/* tcp_suna != tcp_snxt */
14448 				/* Packet contains a window update */
14449 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
14450 				tcp->tcp_zero_win_probe = 0;
14451 				tcp->tcp_timer_backoff = 0;
14452 				tcp->tcp_ms_we_have_waited = 0;
14453 
14454 				/*
14455 				 * Transmit starting with tcp_suna since
14456 				 * the one byte probe is not ack'ed.
14457 				 * If TCP has sent more than one identical
14458 				 * probe, tcp_rexmit will be set.  That means
14459 				 * tcp_ss_rexmit() will send out the one
14460 				 * byte along with new data.  Otherwise,
14461 				 * fake the retransmission.
14462 				 */
14463 				flags |= TH_XMIT_NEEDED;
14464 				if (!tcp->tcp_rexmit) {
14465 					tcp->tcp_rexmit = B_TRUE;
14466 					tcp->tcp_dupack_cnt = 0;
14467 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14468 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14469 				}
14470 			}
14471 		}
14472 		goto swnd_update;
14473 	}
14474 
14475 	/*
14476 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14477 	 * If the ACK value acks something that we have not yet sent, it might
14478 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14479 	 * other side.
14480 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14481 	 * state is handled above, so we can always just drop the segment and
14482 	 * send an ACK here.
14483 	 *
14484 	 * Should we send ACKs in response to ACK only segments?
14485 	 */
14486 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14487 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
14488 		/* drop the received segment */
14489 		freemsg(mp);
14490 
14491 		/*
14492 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14493 		 * greater than 0, check if the number of such
14494 		 * bogus ACks is greater than that count.  If yes,
14495 		 * don't send back any ACK.  This prevents TCP from
14496 		 * getting into an ACK storm if somehow an attacker
14497 		 * successfully spoofs an acceptable segment to our
14498 		 * peer.
14499 		 */
14500 		if (tcp_drop_ack_unsent_cnt > 0 &&
14501 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14502 			TCP_STAT(tcp_in_ack_unsent_drop);
14503 			return;
14504 		}
14505 		mp = tcp_ack_mp(tcp);
14506 		if (mp != NULL) {
14507 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
14508 			BUMP_LOCAL(tcp->tcp_obsegs);
14509 			BUMP_MIB(&tcp_mib, tcpOutAck);
14510 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14511 		}
14512 		return;
14513 	}
14514 
14515 	/*
14516 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14517 	 * blocks that are covered by this ACK.
14518 	 */
14519 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14520 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14521 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14522 	}
14523 
14524 	/*
14525 	 * If we got an ACK after fast retransmit, check to see
14526 	 * if it is a partial ACK.  If it is not and the congestion
14527 	 * window was inflated to account for the other side's
14528 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14529 	 */
14530 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
14531 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14532 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14533 			tcp->tcp_dupack_cnt = 0;
14534 			/*
14535 			 * Restore the orig tcp_cwnd_ssthresh after
14536 			 * fast retransmit phase.
14537 			 */
14538 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14539 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14540 			}
14541 			tcp->tcp_rexmit_max = seg_ack;
14542 			tcp->tcp_cwnd_cnt = 0;
14543 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14544 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14545 
14546 			/*
14547 			 * Remove all notsack info to avoid confusion with
14548 			 * the next fast retrasnmit/recovery phase.
14549 			 */
14550 			if (tcp->tcp_snd_sack_ok &&
14551 			    tcp->tcp_notsack_list != NULL) {
14552 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14553 			}
14554 		} else {
14555 			if (tcp->tcp_snd_sack_ok &&
14556 			    tcp->tcp_notsack_list != NULL) {
14557 				flags |= TH_NEED_SACK_REXMIT;
14558 				tcp->tcp_pipe -= mss;
14559 				if (tcp->tcp_pipe < 0)
14560 					tcp->tcp_pipe = 0;
14561 			} else {
14562 				/*
14563 				 * Hoe's algorithm:
14564 				 *
14565 				 * Retransmit the unack'ed segment and
14566 				 * restart fast recovery.  Note that we
14567 				 * need to scale back tcp_cwnd to the
14568 				 * original value when we started fast
14569 				 * recovery.  This is to prevent overly
14570 				 * aggressive behaviour in sending new
14571 				 * segments.
14572 				 */
14573 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14574 					tcp_dupack_fast_retransmit * mss;
14575 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14576 				flags |= TH_REXMIT_NEEDED;
14577 			}
14578 		}
14579 	} else {
14580 		tcp->tcp_dupack_cnt = 0;
14581 		if (tcp->tcp_rexmit) {
14582 			/*
14583 			 * TCP is retranmitting.  If the ACK ack's all
14584 			 * outstanding data, update tcp_rexmit_max and
14585 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14586 			 * to the correct value.
14587 			 *
14588 			 * Note that SEQ_LEQ() is used.  This is to avoid
14589 			 * unnecessary fast retransmit caused by dup ACKs
14590 			 * received when TCP does slow start retransmission
14591 			 * after a time out.  During this phase, TCP may
14592 			 * send out segments which are already received.
14593 			 * This causes dup ACKs to be sent back.
14594 			 */
14595 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14596 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14597 					tcp->tcp_rexmit_nxt = seg_ack;
14598 				}
14599 				if (seg_ack != tcp->tcp_rexmit_max) {
14600 					flags |= TH_XMIT_NEEDED;
14601 				}
14602 			} else {
14603 				tcp->tcp_rexmit = B_FALSE;
14604 				tcp->tcp_xmit_zc_clean = B_FALSE;
14605 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14606 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14607 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14608 			}
14609 			tcp->tcp_ms_we_have_waited = 0;
14610 		}
14611 	}
14612 
14613 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14614 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14615 	tcp->tcp_suna = seg_ack;
14616 	if (tcp->tcp_zero_win_probe != 0) {
14617 		tcp->tcp_zero_win_probe = 0;
14618 		tcp->tcp_timer_backoff = 0;
14619 	}
14620 
14621 	/*
14622 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14623 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14624 	 * will not reach here.
14625 	 */
14626 	if (mp1 == NULL) {
14627 		goto fin_acked;
14628 	}
14629 
14630 	/*
14631 	 * Update the congestion window.
14632 	 *
14633 	 * If TCP is not ECN capable or TCP is ECN capable but the
14634 	 * congestion experience bit is not set, increase the tcp_cwnd as
14635 	 * usual.
14636 	 */
14637 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14638 		cwnd = tcp->tcp_cwnd;
14639 		add = mss;
14640 
14641 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14642 			/*
14643 			 * This is to prevent an increase of less than 1 MSS of
14644 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14645 			 * may send out tinygrams in order to preserve mblk
14646 			 * boundaries.
14647 			 *
14648 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14649 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14650 			 * increased by 1 MSS for every RTTs.
14651 			 */
14652 			if (tcp->tcp_cwnd_cnt <= 0) {
14653 				tcp->tcp_cwnd_cnt = cwnd + add;
14654 			} else {
14655 				tcp->tcp_cwnd_cnt -= add;
14656 				add = 0;
14657 			}
14658 		}
14659 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14660 	}
14661 
14662 	/* See if the latest urgent data has been acknowledged */
14663 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14664 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14665 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14666 
14667 	/* Can we update the RTT estimates? */
14668 	if (tcp->tcp_snd_ts_ok) {
14669 		/* Ignore zero timestamp echo-reply. */
14670 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14671 			tcp_set_rto(tcp, (int32_t)lbolt -
14672 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14673 		}
14674 
14675 		/* If needed, restart the timer. */
14676 		if (tcp->tcp_set_timer == 1) {
14677 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14678 			tcp->tcp_set_timer = 0;
14679 		}
14680 		/*
14681 		 * Update tcp_csuna in case the other side stops sending
14682 		 * us timestamps.
14683 		 */
14684 		tcp->tcp_csuna = tcp->tcp_snxt;
14685 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14686 		/*
14687 		 * An ACK sequence we haven't seen before, so get the RTT
14688 		 * and update the RTO. But first check if the timestamp is
14689 		 * valid to use.
14690 		 */
14691 		if ((mp1->b_next != NULL) &&
14692 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14693 			tcp_set_rto(tcp, (int32_t)lbolt -
14694 			    (int32_t)(intptr_t)mp1->b_prev);
14695 		else
14696 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14697 
14698 		/* Remeber the last sequence to be ACKed */
14699 		tcp->tcp_csuna = seg_ack;
14700 		if (tcp->tcp_set_timer == 1) {
14701 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14702 			tcp->tcp_set_timer = 0;
14703 		}
14704 	} else {
14705 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14706 	}
14707 
14708 	/* Eat acknowledged bytes off the xmit queue. */
14709 	for (;;) {
14710 		mblk_t	*mp2;
14711 		uchar_t	*wptr;
14712 
14713 		wptr = mp1->b_wptr;
14714 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14715 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14716 		if (bytes_acked < 0) {
14717 			mp1->b_rptr = wptr + bytes_acked;
14718 			/*
14719 			 * Set a new timestamp if all the bytes timed by the
14720 			 * old timestamp have been ack'ed.
14721 			 */
14722 			if (SEQ_GT(seg_ack,
14723 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14724 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14725 				mp1->b_next = NULL;
14726 			}
14727 			break;
14728 		}
14729 		mp1->b_next = NULL;
14730 		mp1->b_prev = NULL;
14731 		mp2 = mp1;
14732 		mp1 = mp1->b_cont;
14733 
14734 		/*
14735 		 * This notification is required for some zero-copy
14736 		 * clients to maintain a copy semantic. After the data
14737 		 * is ack'ed, client is safe to modify or reuse the buffer.
14738 		 */
14739 		if (tcp->tcp_snd_zcopy_aware &&
14740 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14741 			tcp_zcopy_notify(tcp);
14742 		freeb(mp2);
14743 		if (bytes_acked == 0) {
14744 			if (mp1 == NULL) {
14745 				/* Everything is ack'ed, clear the tail. */
14746 				tcp->tcp_xmit_tail = NULL;
14747 				/*
14748 				 * Cancel the timer unless we are still
14749 				 * waiting for an ACK for the FIN packet.
14750 				 */
14751 				if (tcp->tcp_timer_tid != 0 &&
14752 				    tcp->tcp_snxt == tcp->tcp_suna) {
14753 					(void) TCP_TIMER_CANCEL(tcp,
14754 					    tcp->tcp_timer_tid);
14755 					tcp->tcp_timer_tid = 0;
14756 				}
14757 				goto pre_swnd_update;
14758 			}
14759 			if (mp2 != tcp->tcp_xmit_tail)
14760 				break;
14761 			tcp->tcp_xmit_tail = mp1;
14762 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14763 			    (uintptr_t)INT_MAX);
14764 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14765 			    mp1->b_rptr);
14766 			break;
14767 		}
14768 		if (mp1 == NULL) {
14769 			/*
14770 			 * More was acked but there is nothing more
14771 			 * outstanding.  This means that the FIN was
14772 			 * just acked or that we're talking to a clown.
14773 			 */
14774 fin_acked:
14775 			ASSERT(tcp->tcp_fin_sent);
14776 			tcp->tcp_xmit_tail = NULL;
14777 			if (tcp->tcp_fin_sent) {
14778 				/* FIN was acked - making progress */
14779 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14780 				    !tcp->tcp_fin_acked)
14781 					tcp->tcp_ip_forward_progress = B_TRUE;
14782 				tcp->tcp_fin_acked = B_TRUE;
14783 				if (tcp->tcp_linger_tid != 0 &&
14784 				    TCP_TIMER_CANCEL(tcp,
14785 					tcp->tcp_linger_tid) >= 0) {
14786 					tcp_stop_lingering(tcp);
14787 				}
14788 			} else {
14789 				/*
14790 				 * We should never get here because
14791 				 * we have already checked that the
14792 				 * number of bytes ack'ed should be
14793 				 * smaller than or equal to what we
14794 				 * have sent so far (it is the
14795 				 * acceptability check of the ACK).
14796 				 * We can only get here if the send
14797 				 * queue is corrupted.
14798 				 *
14799 				 * Terminate the connection and
14800 				 * panic the system.  It is better
14801 				 * for us to panic instead of
14802 				 * continuing to avoid other disaster.
14803 				 */
14804 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14805 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14806 				panic("Memory corruption "
14807 				    "detected for connection %s.",
14808 				    tcp_display(tcp, NULL,
14809 					DISP_ADDR_AND_PORT));
14810 				/*NOTREACHED*/
14811 			}
14812 			goto pre_swnd_update;
14813 		}
14814 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14815 	}
14816 	if (tcp->tcp_unsent) {
14817 		flags |= TH_XMIT_NEEDED;
14818 	}
14819 pre_swnd_update:
14820 	tcp->tcp_xmit_head = mp1;
14821 swnd_update:
14822 	/*
14823 	 * The following check is different from most other implementations.
14824 	 * For bi-directional transfer, when segments are dropped, the
14825 	 * "normal" check will not accept a window update in those
14826 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14827 	 * segments which are outside receiver's window.  As TCP accepts
14828 	 * the ack in those retransmitted segments, if the window update in
14829 	 * the same segment is not accepted, TCP will incorrectly calculates
14830 	 * that it can send more segments.  This can create a deadlock
14831 	 * with the receiver if its window becomes zero.
14832 	 */
14833 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14834 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14835 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14836 		/*
14837 		 * The criteria for update is:
14838 		 *
14839 		 * 1. the segment acknowledges some data.  Or
14840 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14841 		 * 3. the segment is not old and the advertised window is
14842 		 * larger than the previous advertised window.
14843 		 */
14844 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14845 			flags |= TH_XMIT_NEEDED;
14846 		tcp->tcp_swnd = new_swnd;
14847 		if (new_swnd > tcp->tcp_max_swnd)
14848 			tcp->tcp_max_swnd = new_swnd;
14849 		tcp->tcp_swl1 = seg_seq;
14850 		tcp->tcp_swl2 = seg_ack;
14851 	}
14852 est:
14853 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14854 		switch (tcp->tcp_state) {
14855 		case TCPS_FIN_WAIT_1:
14856 			if (tcp->tcp_fin_acked) {
14857 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14858 				/*
14859 				 * We implement the non-standard BSD/SunOS
14860 				 * FIN_WAIT_2 flushing algorithm.
14861 				 * If there is no user attached to this
14862 				 * TCP endpoint, then this TCP struct
14863 				 * could hang around forever in FIN_WAIT_2
14864 				 * state if the peer forgets to send us
14865 				 * a FIN.  To prevent this, we wait only
14866 				 * 2*MSL (a convenient time value) for
14867 				 * the FIN to arrive.  If it doesn't show up,
14868 				 * we flush the TCP endpoint.  This algorithm,
14869 				 * though a violation of RFC-793, has worked
14870 				 * for over 10 years in BSD systems.
14871 				 * Note: SunOS 4.x waits 675 seconds before
14872 				 * flushing the FIN_WAIT_2 connection.
14873 				 */
14874 				TCP_TIMER_RESTART(tcp,
14875 				    tcp_fin_wait_2_flush_interval);
14876 			}
14877 			break;
14878 		case TCPS_FIN_WAIT_2:
14879 			break;	/* Shutdown hook? */
14880 		case TCPS_LAST_ACK:
14881 			freemsg(mp);
14882 			if (tcp->tcp_fin_acked) {
14883 				(void) tcp_clean_death(tcp, 0, 19);
14884 				return;
14885 			}
14886 			goto xmit_check;
14887 		case TCPS_CLOSING:
14888 			if (tcp->tcp_fin_acked) {
14889 				tcp->tcp_state = TCPS_TIME_WAIT;
14890 				if (!TCP_IS_DETACHED(tcp)) {
14891 					TCP_TIMER_RESTART(tcp,
14892 					    tcp_time_wait_interval);
14893 				} else {
14894 					tcp_time_wait_append(tcp);
14895 					TCP_DBGSTAT(tcp_rput_time_wait);
14896 				}
14897 			}
14898 			/*FALLTHRU*/
14899 		case TCPS_CLOSE_WAIT:
14900 			freemsg(mp);
14901 			goto xmit_check;
14902 		default:
14903 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14904 			break;
14905 		}
14906 	}
14907 	if (flags & TH_FIN) {
14908 		/* Make sure we ack the fin */
14909 		flags |= TH_ACK_NEEDED;
14910 		if (!tcp->tcp_fin_rcvd) {
14911 			tcp->tcp_fin_rcvd = B_TRUE;
14912 			tcp->tcp_rnxt++;
14913 			tcph = tcp->tcp_tcph;
14914 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14915 
14916 			/*
14917 			 * Generate the ordrel_ind at the end unless we
14918 			 * are an eager guy.
14919 			 * In the eager case tcp_rsrv will do this when run
14920 			 * after tcp_accept is done.
14921 			 */
14922 			if (tcp->tcp_listener == NULL &&
14923 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14924 				flags |= TH_ORDREL_NEEDED;
14925 			switch (tcp->tcp_state) {
14926 			case TCPS_SYN_RCVD:
14927 			case TCPS_ESTABLISHED:
14928 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14929 				/* Keepalive? */
14930 				break;
14931 			case TCPS_FIN_WAIT_1:
14932 				if (!tcp->tcp_fin_acked) {
14933 					tcp->tcp_state = TCPS_CLOSING;
14934 					break;
14935 				}
14936 				/* FALLTHRU */
14937 			case TCPS_FIN_WAIT_2:
14938 				tcp->tcp_state = TCPS_TIME_WAIT;
14939 				if (!TCP_IS_DETACHED(tcp)) {
14940 					TCP_TIMER_RESTART(tcp,
14941 					    tcp_time_wait_interval);
14942 				} else {
14943 					tcp_time_wait_append(tcp);
14944 					TCP_DBGSTAT(tcp_rput_time_wait);
14945 				}
14946 				if (seg_len) {
14947 					/*
14948 					 * implies data piggybacked on FIN.
14949 					 * break to handle data.
14950 					 */
14951 					break;
14952 				}
14953 				freemsg(mp);
14954 				goto ack_check;
14955 			}
14956 		}
14957 	}
14958 	if (mp == NULL)
14959 		goto xmit_check;
14960 	if (seg_len == 0) {
14961 		freemsg(mp);
14962 		goto xmit_check;
14963 	}
14964 	if (mp->b_rptr == mp->b_wptr) {
14965 		/*
14966 		 * The header has been consumed, so we remove the
14967 		 * zero-length mblk here.
14968 		 */
14969 		mp1 = mp;
14970 		mp = mp->b_cont;
14971 		freeb(mp1);
14972 	}
14973 	tcph = tcp->tcp_tcph;
14974 	tcp->tcp_rack_cnt++;
14975 	{
14976 		uint32_t cur_max;
14977 
14978 		cur_max = tcp->tcp_rack_cur_max;
14979 		if (tcp->tcp_rack_cnt >= cur_max) {
14980 			/*
14981 			 * We have more unacked data than we should - send
14982 			 * an ACK now.
14983 			 */
14984 			flags |= TH_ACK_NEEDED;
14985 			cur_max++;
14986 			if (cur_max > tcp->tcp_rack_abs_max)
14987 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14988 			else
14989 				tcp->tcp_rack_cur_max = cur_max;
14990 		} else if (TCP_IS_DETACHED(tcp)) {
14991 			/* We don't have an ACK timer for detached TCP. */
14992 			flags |= TH_ACK_NEEDED;
14993 		} else if (seg_len < mss) {
14994 			/*
14995 			 * If we get a segment that is less than an mss, and we
14996 			 * already have unacknowledged data, and the amount
14997 			 * unacknowledged is not a multiple of mss, then we
14998 			 * better generate an ACK now.  Otherwise, this may be
14999 			 * the tail piece of a transaction, and we would rather
15000 			 * wait for the response.
15001 			 */
15002 			uint32_t udif;
15003 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15004 			    (uintptr_t)INT_MAX);
15005 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15006 			if (udif && (udif % mss))
15007 				flags |= TH_ACK_NEEDED;
15008 			else
15009 				flags |= TH_ACK_TIMER_NEEDED;
15010 		} else {
15011 			/* Start delayed ack timer */
15012 			flags |= TH_ACK_TIMER_NEEDED;
15013 		}
15014 	}
15015 	tcp->tcp_rnxt += seg_len;
15016 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15017 
15018 	/* Update SACK list */
15019 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15020 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15021 		    &(tcp->tcp_num_sack_blk));
15022 	}
15023 
15024 	if (tcp->tcp_urp_mp) {
15025 		tcp->tcp_urp_mp->b_cont = mp;
15026 		mp = tcp->tcp_urp_mp;
15027 		tcp->tcp_urp_mp = NULL;
15028 		/* Ready for a new signal. */
15029 		tcp->tcp_urp_last_valid = B_FALSE;
15030 #ifdef DEBUG
15031 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15032 		    "tcp_rput: sending exdata_ind %s",
15033 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15034 #endif /* DEBUG */
15035 	}
15036 
15037 	/*
15038 	 * Check for ancillary data changes compared to last segment.
15039 	 */
15040 	if (tcp->tcp_ipv6_recvancillary != 0) {
15041 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15042 		if (mp == NULL)
15043 			return;
15044 	}
15045 
15046 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15047 		/*
15048 		 * Side queue inbound data until the accept happens.
15049 		 * tcp_accept/tcp_rput drains this when the accept happens.
15050 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15051 		 * T_EXDATA_IND) it is queued on b_next.
15052 		 * XXX Make urgent data use this. Requires:
15053 		 *	Removing tcp_listener check for TH_URG
15054 		 *	Making M_PCPROTO and MARK messages skip the eager case
15055 		 */
15056 		tcp_rcv_enqueue(tcp, mp, seg_len);
15057 	} else {
15058 		if (mp->b_datap->db_type != M_DATA ||
15059 		    (flags & TH_MARKNEXT_NEEDED)) {
15060 			if (tcp->tcp_rcv_list != NULL) {
15061 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15062 			}
15063 			ASSERT(tcp->tcp_rcv_list == NULL ||
15064 			    tcp->tcp_fused_sigurg);
15065 			if (flags & TH_MARKNEXT_NEEDED) {
15066 #ifdef DEBUG
15067 				(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15068 				    "tcp_rput: sending MSGMARKNEXT %s",
15069 				    tcp_display(tcp, NULL,
15070 				    DISP_PORT_ONLY));
15071 #endif /* DEBUG */
15072 				mp->b_flag |= MSGMARKNEXT;
15073 				flags &= ~TH_MARKNEXT_NEEDED;
15074 			}
15075 			putnext(tcp->tcp_rq, mp);
15076 			if (!canputnext(tcp->tcp_rq))
15077 				tcp->tcp_rwnd -= seg_len;
15078 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
15079 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
15080 		    (sqp != NULL)) {
15081 			if (tcp->tcp_rcv_list != NULL) {
15082 				/*
15083 				 * Enqueue the new segment first and then
15084 				 * call tcp_rcv_drain() to send all data
15085 				 * up.  The other way to do this is to
15086 				 * send all queued data up and then call
15087 				 * putnext() to send the new segment up.
15088 				 * This way can remove the else part later
15089 				 * on.
15090 				 *
15091 				 * We don't this to avoid one more call to
15092 				 * canputnext() as tcp_rcv_drain() needs to
15093 				 * call canputnext().
15094 				 */
15095 				tcp_rcv_enqueue(tcp, mp, seg_len);
15096 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15097 			} else {
15098 				putnext(tcp->tcp_rq, mp);
15099 				if (!canputnext(tcp->tcp_rq))
15100 					tcp->tcp_rwnd -= seg_len;
15101 			}
15102 		} else {
15103 			/*
15104 			 * Enqueue all packets when processing an mblk
15105 			 * from the co queue and also enqueue normal packets.
15106 			 */
15107 			tcp_rcv_enqueue(tcp, mp, seg_len);
15108 		}
15109 		/*
15110 		 * Make sure the timer is running if we have data waiting
15111 		 * for a push bit. This provides resiliency against
15112 		 * implementations that do not correctly generate push bits.
15113 		 */
15114 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
15115 		    tcp->tcp_push_tid == 0) {
15116 			/*
15117 			 * The connection may be closed at this point, so don't
15118 			 * do anything for a detached tcp.
15119 			 */
15120 			if (!TCP_IS_DETACHED(tcp))
15121 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15122 				    tcp_push_timer,
15123 				    MSEC_TO_TICK(tcp_push_timer_interval));
15124 		}
15125 	}
15126 xmit_check:
15127 	/* Is there anything left to do? */
15128 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15129 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15130 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15131 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15132 		goto done;
15133 
15134 	/* Any transmit work to do and a non-zero window? */
15135 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15136 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15137 		if (flags & TH_REXMIT_NEEDED) {
15138 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15139 
15140 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
15141 			if (snd_size > mss)
15142 				snd_size = mss;
15143 			if (snd_size > tcp->tcp_swnd)
15144 				snd_size = tcp->tcp_swnd;
15145 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15146 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15147 			    B_TRUE);
15148 
15149 			if (mp1 != NULL) {
15150 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15151 				tcp->tcp_csuna = tcp->tcp_snxt;
15152 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
15153 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
15154 				TCP_RECORD_TRACE(tcp, mp1,
15155 				    TCP_TRACE_SEND_PKT);
15156 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15157 			}
15158 		}
15159 		if (flags & TH_NEED_SACK_REXMIT) {
15160 			tcp_sack_rxmit(tcp, &flags);
15161 		}
15162 		/*
15163 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15164 		 * out new segment.  Note that tcp_rexmit should not be
15165 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15166 		 */
15167 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15168 			if (!tcp->tcp_rexmit) {
15169 				tcp_wput_data(tcp, NULL, B_FALSE);
15170 			} else {
15171 				tcp_ss_rexmit(tcp);
15172 			}
15173 		}
15174 		/*
15175 		 * Adjust tcp_cwnd back to normal value after sending
15176 		 * new data segments.
15177 		 */
15178 		if (flags & TH_LIMIT_XMIT) {
15179 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15180 			/*
15181 			 * This will restart the timer.  Restarting the
15182 			 * timer is used to avoid a timeout before the
15183 			 * limited transmitted segment's ACK gets back.
15184 			 */
15185 			if (tcp->tcp_xmit_head != NULL)
15186 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15187 		}
15188 
15189 		/* Anything more to do? */
15190 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15191 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15192 			goto done;
15193 	}
15194 ack_check:
15195 	if (flags & TH_SEND_URP_MARK) {
15196 		ASSERT(tcp->tcp_urp_mark_mp);
15197 		/*
15198 		 * Send up any queued data and then send the mark message
15199 		 */
15200 		if (tcp->tcp_rcv_list != NULL) {
15201 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15202 		}
15203 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15204 
15205 		mp1 = tcp->tcp_urp_mark_mp;
15206 		tcp->tcp_urp_mark_mp = NULL;
15207 #ifdef DEBUG
15208 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
15209 		    "tcp_rput: sending zero-length %s %s",
15210 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15211 		    "MSGNOTMARKNEXT"),
15212 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15213 #endif /* DEBUG */
15214 		putnext(tcp->tcp_rq, mp1);
15215 		flags &= ~TH_SEND_URP_MARK;
15216 	}
15217 	if (flags & TH_ACK_NEEDED) {
15218 		/*
15219 		 * Time to send an ack for some reason.
15220 		 */
15221 		mp1 = tcp_ack_mp(tcp);
15222 
15223 		if (mp1 != NULL) {
15224 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
15225 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15226 			BUMP_LOCAL(tcp->tcp_obsegs);
15227 			BUMP_MIB(&tcp_mib, tcpOutAck);
15228 		}
15229 		if (tcp->tcp_ack_tid != 0) {
15230 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15231 			tcp->tcp_ack_tid = 0;
15232 		}
15233 	}
15234 	if (flags & TH_ACK_TIMER_NEEDED) {
15235 		/*
15236 		 * Arrange for deferred ACK or push wait timeout.
15237 		 * Start timer if it is not already running.
15238 		 */
15239 		if (tcp->tcp_ack_tid == 0) {
15240 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15241 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15242 			    (clock_t)tcp_local_dack_interval :
15243 			    (clock_t)tcp_deferred_ack_interval));
15244 		}
15245 	}
15246 	if (flags & TH_ORDREL_NEEDED) {
15247 		/*
15248 		 * Send up the ordrel_ind unless we are an eager guy.
15249 		 * In the eager case tcp_rsrv will do this when run
15250 		 * after tcp_accept is done.
15251 		 */
15252 		ASSERT(tcp->tcp_listener == NULL);
15253 		if (tcp->tcp_rcv_list != NULL) {
15254 			/*
15255 			 * Push any mblk(s) enqueued from co processing.
15256 			 */
15257 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15258 		}
15259 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15260 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15261 			tcp->tcp_ordrel_done = B_TRUE;
15262 			putnext(tcp->tcp_rq, mp1);
15263 			if (tcp->tcp_deferred_clean_death) {
15264 				/*
15265 				 * tcp_clean_death was deferred
15266 				 * for T_ORDREL_IND - do it now
15267 				 */
15268 				(void) tcp_clean_death(tcp,
15269 				    tcp->tcp_client_errno, 20);
15270 				tcp->tcp_deferred_clean_death =	B_FALSE;
15271 			}
15272 		} else {
15273 			/*
15274 			 * Run the orderly release in the
15275 			 * service routine.
15276 			 */
15277 			qenable(tcp->tcp_rq);
15278 			/*
15279 			 * Caveat(XXX): The machine may be so
15280 			 * overloaded that tcp_rsrv() is not scheduled
15281 			 * until after the endpoint has transitioned
15282 			 * to TCPS_TIME_WAIT
15283 			 * and tcp_time_wait_interval expires. Then
15284 			 * tcp_timer() will blow away state in tcp_t
15285 			 * and T_ORDREL_IND will never be delivered
15286 			 * upstream. Unlikely but potentially
15287 			 * a problem.
15288 			 */
15289 		}
15290 	}
15291 done:
15292 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15293 }
15294 
15295 /*
15296  * This function does PAWS protection check. Returns B_TRUE if the
15297  * segment passes the PAWS test, else returns B_FALSE.
15298  */
15299 boolean_t
15300 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15301 {
15302 	uint8_t	flags;
15303 	int	options;
15304 	uint8_t *up;
15305 
15306 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15307 	/*
15308 	 * If timestamp option is aligned nicely, get values inline,
15309 	 * otherwise call general routine to parse.  Only do that
15310 	 * if timestamp is the only option.
15311 	 */
15312 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15313 	    TCPOPT_REAL_TS_LEN &&
15314 	    OK_32PTR((up = ((uint8_t *)tcph) +
15315 	    TCP_MIN_HEADER_LENGTH)) &&
15316 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15317 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15318 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15319 
15320 		options = TCP_OPT_TSTAMP_PRESENT;
15321 	} else {
15322 		if (tcp->tcp_snd_sack_ok) {
15323 			tcpoptp->tcp = tcp;
15324 		} else {
15325 			tcpoptp->tcp = NULL;
15326 		}
15327 		options = tcp_parse_options(tcph, tcpoptp);
15328 	}
15329 
15330 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15331 		/*
15332 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15333 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15334 		 */
15335 		if ((flags & TH_RST) == 0 &&
15336 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15337 		    tcp->tcp_ts_recent)) {
15338 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15339 			    PAWS_TIMEOUT)) {
15340 				/* This segment is not acceptable. */
15341 				return (B_FALSE);
15342 			} else {
15343 				/*
15344 				 * Connection has been idle for
15345 				 * too long.  Reset the timestamp
15346 				 * and assume the segment is valid.
15347 				 */
15348 				tcp->tcp_ts_recent =
15349 				    tcpoptp->tcp_opt_ts_val;
15350 			}
15351 		}
15352 	} else {
15353 		/*
15354 		 * If we don't get a timestamp on every packet, we
15355 		 * figure we can't really trust 'em, so we stop sending
15356 		 * and parsing them.
15357 		 */
15358 		tcp->tcp_snd_ts_ok = B_FALSE;
15359 
15360 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15361 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15362 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15363 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
15364 		if (tcp->tcp_snd_sack_ok) {
15365 			ASSERT(tcp->tcp_sack_info != NULL);
15366 			tcp->tcp_max_sack_blk = 4;
15367 		}
15368 	}
15369 	return (B_TRUE);
15370 }
15371 
15372 /*
15373  * Attach ancillary data to a received TCP segments for the
15374  * ancillary pieces requested by the application that are
15375  * different than they were in the previous data segment.
15376  *
15377  * Save the "current" values once memory allocation is ok so that
15378  * when memory allocation fails we can just wait for the next data segment.
15379  */
15380 static mblk_t *
15381 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15382 {
15383 	struct T_optdata_ind *todi;
15384 	int optlen;
15385 	uchar_t *optptr;
15386 	struct T_opthdr *toh;
15387 	uint_t addflag;	/* Which pieces to add */
15388 	mblk_t *mp1;
15389 
15390 	optlen = 0;
15391 	addflag = 0;
15392 	/* If app asked for pktinfo and the index has changed ... */
15393 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15394 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15395 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15396 		optlen += sizeof (struct T_opthdr) +
15397 		    sizeof (struct in6_pktinfo);
15398 		addflag |= TCP_IPV6_RECVPKTINFO;
15399 	}
15400 	/* If app asked for hoplimit and it has changed ... */
15401 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15402 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15403 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15404 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15405 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15406 	}
15407 	/* If app asked for tclass and it has changed ... */
15408 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15409 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15410 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15411 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15412 		addflag |= TCP_IPV6_RECVTCLASS;
15413 	}
15414 	/* If app asked for hopbyhop headers and it has changed ... */
15415 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15416 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15417 		(ipp->ipp_fields & IPPF_HOPOPTS),
15418 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15419 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
15420 		addflag |= TCP_IPV6_RECVHOPOPTS;
15421 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
15422 		    &tcp->tcp_hopoptslen,
15423 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15424 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15425 			return (mp);
15426 	}
15427 	/* If app asked for dst headers before routing headers ... */
15428 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15429 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15430 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
15431 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15432 		optlen += sizeof (struct T_opthdr) +
15433 		    ipp->ipp_rtdstoptslen;
15434 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15435 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
15436 		    &tcp->tcp_rtdstoptslen,
15437 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15438 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15439 			return (mp);
15440 	}
15441 	/* If app asked for routing headers and it has changed ... */
15442 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15443 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15444 		(ipp->ipp_fields & IPPF_RTHDR),
15445 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15446 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15447 		addflag |= TCP_IPV6_RECVRTHDR;
15448 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
15449 		    &tcp->tcp_rthdrlen,
15450 		    (ipp->ipp_fields & IPPF_RTHDR),
15451 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15452 			return (mp);
15453 	}
15454 	/* If app asked for dest headers and it has changed ... */
15455 	if ((tcp->tcp_ipv6_recvancillary &
15456 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15457 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15458 		(ipp->ipp_fields & IPPF_DSTOPTS),
15459 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15460 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15461 		addflag |= TCP_IPV6_RECVDSTOPTS;
15462 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
15463 		    &tcp->tcp_dstoptslen,
15464 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15465 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15466 			return (mp);
15467 	}
15468 
15469 	if (optlen == 0) {
15470 		/* Nothing to add */
15471 		return (mp);
15472 	}
15473 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15474 	if (mp1 == NULL) {
15475 		/*
15476 		 * Defer sending ancillary data until the next TCP segment
15477 		 * arrives.
15478 		 */
15479 		return (mp);
15480 	}
15481 	mp1->b_cont = mp;
15482 	mp = mp1;
15483 	mp->b_wptr += sizeof (*todi) + optlen;
15484 	mp->b_datap->db_type = M_PROTO;
15485 	todi = (struct T_optdata_ind *)mp->b_rptr;
15486 	todi->PRIM_type = T_OPTDATA_IND;
15487 	todi->DATA_flag = 1;	/* MORE data */
15488 	todi->OPT_length = optlen;
15489 	todi->OPT_offset = sizeof (*todi);
15490 	optptr = (uchar_t *)&todi[1];
15491 	/*
15492 	 * If app asked for pktinfo and the index has changed ...
15493 	 * Note that the local address never changes for the connection.
15494 	 */
15495 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15496 		struct in6_pktinfo *pkti;
15497 
15498 		toh = (struct T_opthdr *)optptr;
15499 		toh->level = IPPROTO_IPV6;
15500 		toh->name = IPV6_PKTINFO;
15501 		toh->len = sizeof (*toh) + sizeof (*pkti);
15502 		toh->status = 0;
15503 		optptr += sizeof (*toh);
15504 		pkti = (struct in6_pktinfo *)optptr;
15505 		if (tcp->tcp_ipversion == IPV6_VERSION)
15506 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15507 		else
15508 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15509 			    &pkti->ipi6_addr);
15510 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15511 		optptr += sizeof (*pkti);
15512 		ASSERT(OK_32PTR(optptr));
15513 		/* Save as "last" value */
15514 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15515 	}
15516 	/* If app asked for hoplimit and it has changed ... */
15517 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15518 		toh = (struct T_opthdr *)optptr;
15519 		toh->level = IPPROTO_IPV6;
15520 		toh->name = IPV6_HOPLIMIT;
15521 		toh->len = sizeof (*toh) + sizeof (uint_t);
15522 		toh->status = 0;
15523 		optptr += sizeof (*toh);
15524 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15525 		optptr += sizeof (uint_t);
15526 		ASSERT(OK_32PTR(optptr));
15527 		/* Save as "last" value */
15528 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15529 	}
15530 	/* If app asked for tclass and it has changed ... */
15531 	if (addflag & TCP_IPV6_RECVTCLASS) {
15532 		toh = (struct T_opthdr *)optptr;
15533 		toh->level = IPPROTO_IPV6;
15534 		toh->name = IPV6_TCLASS;
15535 		toh->len = sizeof (*toh) + sizeof (uint_t);
15536 		toh->status = 0;
15537 		optptr += sizeof (*toh);
15538 		*(uint_t *)optptr = ipp->ipp_tclass;
15539 		optptr += sizeof (uint_t);
15540 		ASSERT(OK_32PTR(optptr));
15541 		/* Save as "last" value */
15542 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15543 	}
15544 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15545 		toh = (struct T_opthdr *)optptr;
15546 		toh->level = IPPROTO_IPV6;
15547 		toh->name = IPV6_HOPOPTS;
15548 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
15549 		toh->status = 0;
15550 		optptr += sizeof (*toh);
15551 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
15552 		optptr += ipp->ipp_hopoptslen;
15553 		ASSERT(OK_32PTR(optptr));
15554 		/* Save as last value */
15555 		tcp_savebuf((void **)&tcp->tcp_hopopts,
15556 		    &tcp->tcp_hopoptslen,
15557 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15558 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15559 	}
15560 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15561 		toh = (struct T_opthdr *)optptr;
15562 		toh->level = IPPROTO_IPV6;
15563 		toh->name = IPV6_RTHDRDSTOPTS;
15564 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15565 		toh->status = 0;
15566 		optptr += sizeof (*toh);
15567 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15568 		optptr += ipp->ipp_rtdstoptslen;
15569 		ASSERT(OK_32PTR(optptr));
15570 		/* Save as last value */
15571 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
15572 		    &tcp->tcp_rtdstoptslen,
15573 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15574 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15575 	}
15576 	if (addflag & TCP_IPV6_RECVRTHDR) {
15577 		toh = (struct T_opthdr *)optptr;
15578 		toh->level = IPPROTO_IPV6;
15579 		toh->name = IPV6_RTHDR;
15580 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15581 		toh->status = 0;
15582 		optptr += sizeof (*toh);
15583 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15584 		optptr += ipp->ipp_rthdrlen;
15585 		ASSERT(OK_32PTR(optptr));
15586 		/* Save as last value */
15587 		tcp_savebuf((void **)&tcp->tcp_rthdr,
15588 		    &tcp->tcp_rthdrlen,
15589 		    (ipp->ipp_fields & IPPF_RTHDR),
15590 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15591 	}
15592 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15593 		toh = (struct T_opthdr *)optptr;
15594 		toh->level = IPPROTO_IPV6;
15595 		toh->name = IPV6_DSTOPTS;
15596 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15597 		toh->status = 0;
15598 		optptr += sizeof (*toh);
15599 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15600 		optptr += ipp->ipp_dstoptslen;
15601 		ASSERT(OK_32PTR(optptr));
15602 		/* Save as last value */
15603 		tcp_savebuf((void **)&tcp->tcp_dstopts,
15604 		    &tcp->tcp_dstoptslen,
15605 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15606 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15607 	}
15608 	ASSERT(optptr == mp->b_wptr);
15609 	return (mp);
15610 }
15611 
15612 
15613 /*
15614  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15615  * or a "bad" IRE detected by tcp_adapt_ire.
15616  * We can't tell if the failure was due to the laddr or the faddr
15617  * thus we clear out all addresses and ports.
15618  */
15619 static void
15620 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15621 {
15622 	queue_t	*q = tcp->tcp_rq;
15623 	tcph_t	*tcph;
15624 	struct T_error_ack *tea;
15625 	conn_t	*connp = tcp->tcp_connp;
15626 
15627 
15628 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15629 
15630 	if (mp->b_cont) {
15631 		freemsg(mp->b_cont);
15632 		mp->b_cont = NULL;
15633 	}
15634 	tea = (struct T_error_ack *)mp->b_rptr;
15635 	switch (tea->PRIM_type) {
15636 	case T_BIND_ACK:
15637 		/*
15638 		 * Need to unbind with classifier since we were just told that
15639 		 * our bind succeeded.
15640 		 */
15641 		tcp->tcp_hard_bound = B_FALSE;
15642 		tcp->tcp_hard_binding = B_FALSE;
15643 
15644 		ipcl_hash_remove(connp);
15645 		/* Reuse the mblk if possible */
15646 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15647 			sizeof (*tea));
15648 		mp->b_rptr = mp->b_datap->db_base;
15649 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15650 		tea = (struct T_error_ack *)mp->b_rptr;
15651 		tea->PRIM_type = T_ERROR_ACK;
15652 		tea->TLI_error = TSYSERR;
15653 		tea->UNIX_error = error;
15654 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15655 			tea->ERROR_prim = T_CONN_REQ;
15656 		} else {
15657 			tea->ERROR_prim = O_T_BIND_REQ;
15658 		}
15659 		break;
15660 
15661 	case T_ERROR_ACK:
15662 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15663 			tea->ERROR_prim = T_CONN_REQ;
15664 		break;
15665 	default:
15666 		panic("tcp_bind_failed: unexpected TPI type");
15667 		/*NOTREACHED*/
15668 	}
15669 
15670 	tcp->tcp_state = TCPS_IDLE;
15671 	if (tcp->tcp_ipversion == IPV4_VERSION)
15672 		tcp->tcp_ipha->ipha_src = 0;
15673 	else
15674 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15675 	/*
15676 	 * Copy of the src addr. in tcp_t is needed since
15677 	 * the lookup funcs. can only look at tcp_t
15678 	 */
15679 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15680 
15681 	tcph = tcp->tcp_tcph;
15682 	tcph->th_lport[0] = 0;
15683 	tcph->th_lport[1] = 0;
15684 	tcp_bind_hash_remove(tcp);
15685 	bzero(&connp->u_port, sizeof (connp->u_port));
15686 	/* blow away saved option results if any */
15687 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15688 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15689 
15690 	conn_delete_ire(tcp->tcp_connp, NULL);
15691 	putnext(q, mp);
15692 }
15693 
15694 /*
15695  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15696  * messages.
15697  */
15698 void
15699 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15700 {
15701 	mblk_t	*mp1;
15702 	uchar_t	*rptr = mp->b_rptr;
15703 	queue_t	*q = tcp->tcp_rq;
15704 	struct T_error_ack *tea;
15705 	uint32_t mss;
15706 	mblk_t *syn_mp;
15707 	mblk_t *mdti;
15708 	int	retval;
15709 	mblk_t *ire_mp;
15710 
15711 	switch (mp->b_datap->db_type) {
15712 	case M_PROTO:
15713 	case M_PCPROTO:
15714 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15715 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15716 			break;
15717 		tea = (struct T_error_ack *)rptr;
15718 		switch (tea->PRIM_type) {
15719 		case T_BIND_ACK:
15720 			/*
15721 			 * Adapt Multidata information, if any.  The
15722 			 * following tcp_mdt_update routine will free
15723 			 * the message.
15724 			 */
15725 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15726 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15727 				    b_rptr)->mdt_capab, B_TRUE);
15728 				freemsg(mdti);
15729 			}
15730 
15731 			/* Get the IRE, if we had requested for it */
15732 			ire_mp = tcp_ire_mp(mp);
15733 
15734 			if (tcp->tcp_hard_binding) {
15735 				tcp->tcp_hard_binding = B_FALSE;
15736 				tcp->tcp_hard_bound = B_TRUE;
15737 				CL_INET_CONNECT(tcp);
15738 			} else {
15739 				if (ire_mp != NULL)
15740 					freeb(ire_mp);
15741 				goto after_syn_sent;
15742 			}
15743 
15744 			retval = tcp_adapt_ire(tcp, ire_mp);
15745 			if (ire_mp != NULL)
15746 				freeb(ire_mp);
15747 			if (retval == 0) {
15748 				tcp_bind_failed(tcp, mp,
15749 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15750 				    ENETUNREACH : EADDRNOTAVAIL));
15751 				return;
15752 			}
15753 			/*
15754 			 * Don't let an endpoint connect to itself.
15755 			 * Also checked in tcp_connect() but that
15756 			 * check can't handle the case when the
15757 			 * local IP address is INADDR_ANY.
15758 			 */
15759 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15760 				if ((tcp->tcp_ipha->ipha_dst ==
15761 				    tcp->tcp_ipha->ipha_src) &&
15762 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15763 				    tcp->tcp_tcph->th_fport))) {
15764 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15765 					return;
15766 				}
15767 			} else {
15768 				if (IN6_ARE_ADDR_EQUAL(
15769 				    &tcp->tcp_ip6h->ip6_dst,
15770 				    &tcp->tcp_ip6h->ip6_src) &&
15771 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15772 				    tcp->tcp_tcph->th_fport))) {
15773 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15774 					return;
15775 				}
15776 			}
15777 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15778 			/*
15779 			 * This should not be possible!  Just for
15780 			 * defensive coding...
15781 			 */
15782 			if (tcp->tcp_state != TCPS_SYN_SENT)
15783 				goto after_syn_sent;
15784 
15785 			ASSERT(q == tcp->tcp_rq);
15786 			/*
15787 			 * tcp_adapt_ire() does not adjust
15788 			 * for TCP/IP header length.
15789 			 */
15790 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15791 
15792 			/*
15793 			 * Just make sure our rwnd is at
15794 			 * least tcp_recv_hiwat_mss * MSS
15795 			 * large, and round up to the nearest
15796 			 * MSS.
15797 			 *
15798 			 * We do the round up here because
15799 			 * we need to get the interface
15800 			 * MTU first before we can do the
15801 			 * round up.
15802 			 */
15803 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15804 			    tcp_recv_hiwat_minmss * mss);
15805 			q->q_hiwat = tcp->tcp_rwnd;
15806 			tcp_set_ws_value(tcp);
15807 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15808 			    tcp->tcp_tcph->th_win);
15809 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15810 				tcp->tcp_snd_ws_ok = B_TRUE;
15811 
15812 			/*
15813 			 * Set tcp_snd_ts_ok to true
15814 			 * so that tcp_xmit_mp will
15815 			 * include the timestamp
15816 			 * option in the SYN segment.
15817 			 */
15818 			if (tcp_tstamp_always ||
15819 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15820 				tcp->tcp_snd_ts_ok = B_TRUE;
15821 			}
15822 
15823 			/*
15824 			 * tcp_snd_sack_ok can be set in
15825 			 * tcp_adapt_ire() if the sack metric
15826 			 * is set.  So check it here also.
15827 			 */
15828 			if (tcp_sack_permitted == 2 ||
15829 			    tcp->tcp_snd_sack_ok) {
15830 				if (tcp->tcp_sack_info == NULL) {
15831 					tcp->tcp_sack_info =
15832 					kmem_cache_alloc(tcp_sack_info_cache,
15833 					    KM_SLEEP);
15834 				}
15835 				tcp->tcp_snd_sack_ok = B_TRUE;
15836 			}
15837 
15838 			/*
15839 			 * Should we use ECN?  Note that the current
15840 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15841 			 * is 1.  The reason for doing this is that there
15842 			 * are equipments out there that will drop ECN
15843 			 * enabled IP packets.  Setting it to 1 avoids
15844 			 * compatibility problems.
15845 			 */
15846 			if (tcp_ecn_permitted == 2)
15847 				tcp->tcp_ecn_ok = B_TRUE;
15848 
15849 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15850 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15851 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15852 			if (syn_mp) {
15853 				cred_t *cr;
15854 				pid_t pid;
15855 
15856 				/*
15857 				 * Obtain the credential from the
15858 				 * thread calling connect(); the credential
15859 				 * lives on in the second mblk which
15860 				 * originated from T_CONN_REQ and is echoed
15861 				 * with the T_BIND_ACK from ip.  If none
15862 				 * can be found, default to the creator
15863 				 * of the socket.
15864 				 */
15865 				if (mp->b_cont == NULL ||
15866 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15867 					cr = tcp->tcp_cred;
15868 					pid = tcp->tcp_cpid;
15869 				} else {
15870 					pid = DB_CPID(mp->b_cont);
15871 				}
15872 
15873 				TCP_RECORD_TRACE(tcp, syn_mp,
15874 				    TCP_TRACE_SEND_PKT);
15875 				mblk_setcred(syn_mp, cr);
15876 				DB_CPID(syn_mp) = pid;
15877 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15878 			}
15879 		after_syn_sent:
15880 			/*
15881 			 * A trailer mblk indicates a waiting client upstream.
15882 			 * We complete here the processing begun in
15883 			 * either tcp_bind() or tcp_connect() by passing
15884 			 * upstream the reply message they supplied.
15885 			 */
15886 			mp1 = mp;
15887 			mp = mp->b_cont;
15888 			freeb(mp1);
15889 			if (mp)
15890 				break;
15891 			return;
15892 		case T_ERROR_ACK:
15893 			if (tcp->tcp_debug) {
15894 				(void) strlog(TCP_MODULE_ID, 0, 1,
15895 				    SL_TRACE|SL_ERROR,
15896 				    "tcp_rput_other: case T_ERROR_ACK, "
15897 				    "ERROR_prim == %d",
15898 				    tea->ERROR_prim);
15899 			}
15900 			switch (tea->ERROR_prim) {
15901 			case O_T_BIND_REQ:
15902 			case T_BIND_REQ:
15903 				tcp_bind_failed(tcp, mp,
15904 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15905 				    ENETUNREACH : EADDRNOTAVAIL));
15906 				return;
15907 			case T_UNBIND_REQ:
15908 				tcp->tcp_hard_binding = B_FALSE;
15909 				tcp->tcp_hard_bound = B_FALSE;
15910 				if (mp->b_cont) {
15911 					freemsg(mp->b_cont);
15912 					mp->b_cont = NULL;
15913 				}
15914 				if (tcp->tcp_unbind_pending)
15915 					tcp->tcp_unbind_pending = 0;
15916 				else {
15917 					/* From tcp_ip_unbind() - free */
15918 					freemsg(mp);
15919 					return;
15920 				}
15921 				break;
15922 			case T_SVR4_OPTMGMT_REQ:
15923 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15924 					/* T_OPTMGMT_REQ generated by TCP */
15925 					printf("T_SVR4_OPTMGMT_REQ failed "
15926 					    "%d/%d - dropped (cnt %d)\n",
15927 					    tea->TLI_error, tea->UNIX_error,
15928 					    tcp->tcp_drop_opt_ack_cnt);
15929 					freemsg(mp);
15930 					tcp->tcp_drop_opt_ack_cnt--;
15931 					return;
15932 				}
15933 				break;
15934 			}
15935 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15936 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15937 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15938 				    "- dropped (cnt %d)\n",
15939 				    tea->TLI_error, tea->UNIX_error,
15940 				    tcp->tcp_drop_opt_ack_cnt);
15941 				freemsg(mp);
15942 				tcp->tcp_drop_opt_ack_cnt--;
15943 				return;
15944 			}
15945 			break;
15946 		case T_OPTMGMT_ACK:
15947 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15948 				/* T_OPTMGMT_REQ generated by TCP */
15949 				freemsg(mp);
15950 				tcp->tcp_drop_opt_ack_cnt--;
15951 				return;
15952 			}
15953 			break;
15954 		default:
15955 			break;
15956 		}
15957 		break;
15958 	case M_CTL:
15959 		/*
15960 		 * ICMP messages.
15961 		 */
15962 		tcp_icmp_error(tcp, mp);
15963 		return;
15964 	case M_FLUSH:
15965 		if (*rptr & FLUSHR)
15966 			flushq(q, FLUSHDATA);
15967 		break;
15968 	default:
15969 		break;
15970 	}
15971 	/*
15972 	 * Make sure we set this bit before sending the ACK for
15973 	 * bind. Otherwise accept could possibly run and free
15974 	 * this tcp struct.
15975 	 */
15976 	putnext(q, mp);
15977 }
15978 
15979 /*
15980  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15981  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15982  * tcp_rsrv() try again.
15983  */
15984 static void
15985 tcp_ordrel_kick(void *arg)
15986 {
15987 	conn_t 	*connp = (conn_t *)arg;
15988 	tcp_t	*tcp = connp->conn_tcp;
15989 
15990 	tcp->tcp_ordrelid = 0;
15991 	tcp->tcp_timeout = B_FALSE;
15992 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15993 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15994 		qenable(tcp->tcp_rq);
15995 	}
15996 }
15997 
15998 /* ARGSUSED */
15999 static void
16000 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16001 {
16002 	conn_t	*connp = (conn_t *)arg;
16003 	tcp_t	*tcp = connp->conn_tcp;
16004 	queue_t	*q = tcp->tcp_rq;
16005 	uint_t	thwin;
16006 
16007 	freeb(mp);
16008 
16009 	TCP_STAT(tcp_rsrv_calls);
16010 
16011 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16012 		return;
16013 	}
16014 
16015 	if (tcp->tcp_fused) {
16016 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16017 
16018 		ASSERT(tcp->tcp_fused);
16019 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16020 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16021 		ASSERT(!TCP_IS_DETACHED(tcp));
16022 		ASSERT(tcp->tcp_connp->conn_sqp ==
16023 		    peer_tcp->tcp_connp->conn_sqp);
16024 
16025 		if (tcp->tcp_rcv_list != NULL)
16026 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16027 
16028 		tcp_clrqfull(peer_tcp);
16029 		peer_tcp->tcp_flow_stopped = B_FALSE;
16030 		TCP_STAT(tcp_fusion_backenabled);
16031 		return;
16032 	}
16033 
16034 	if (canputnext(q)) {
16035 		tcp->tcp_rwnd = q->q_hiwat;
16036 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16037 		    << tcp->tcp_rcv_ws;
16038 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16039 		/*
16040 		 * Send back a window update immediately if TCP is above
16041 		 * ESTABLISHED state and the increase of the rcv window
16042 		 * that the other side knows is at least 1 MSS after flow
16043 		 * control is lifted.
16044 		 */
16045 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16046 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16047 			tcp_xmit_ctl(NULL, tcp,
16048 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16049 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16050 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
16051 		}
16052 	}
16053 	/* Handle a failure to allocate a T_ORDREL_IND here */
16054 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16055 		ASSERT(tcp->tcp_listener == NULL);
16056 		if (tcp->tcp_rcv_list != NULL) {
16057 			(void) tcp_rcv_drain(q, tcp);
16058 		}
16059 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
16060 		mp = mi_tpi_ordrel_ind();
16061 		if (mp) {
16062 			tcp->tcp_ordrel_done = B_TRUE;
16063 			putnext(q, mp);
16064 			if (tcp->tcp_deferred_clean_death) {
16065 				/*
16066 				 * tcp_clean_death was deferred for
16067 				 * T_ORDREL_IND - do it now
16068 				 */
16069 				tcp->tcp_deferred_clean_death = B_FALSE;
16070 				(void) tcp_clean_death(tcp,
16071 				    tcp->tcp_client_errno, 22);
16072 			}
16073 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16074 			/*
16075 			 * If there isn't already a timer running
16076 			 * start one.  Use a 4 second
16077 			 * timer as a fallback since it can't fail.
16078 			 */
16079 			tcp->tcp_timeout = B_TRUE;
16080 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16081 			    MSEC_TO_TICK(4000));
16082 		}
16083 	}
16084 }
16085 
16086 /*
16087  * The read side service routine is called mostly when we get back-enabled as a
16088  * result of flow control relief.  Since we don't actually queue anything in
16089  * TCP, we have no data to send out of here.  What we do is clear the receive
16090  * window, and send out a window update.
16091  * This routine is also called to drive an orderly release message upstream
16092  * if the attempt in tcp_rput failed.
16093  */
16094 static void
16095 tcp_rsrv(queue_t *q)
16096 {
16097 	conn_t *connp = Q_TO_CONN(q);
16098 	tcp_t	*tcp = connp->conn_tcp;
16099 	mblk_t	*mp;
16100 
16101 	/* No code does a putq on the read side */
16102 	ASSERT(q->q_first == NULL);
16103 
16104 	/* Nothing to do for the default queue */
16105 	if (q == tcp_g_q) {
16106 		return;
16107 	}
16108 
16109 	mp = allocb(0, BPRI_HI);
16110 	if (mp == NULL) {
16111 		/*
16112 		 * We are under memory pressure. Return for now and we
16113 		 * we will be called again later.
16114 		 */
16115 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16116 			/*
16117 			 * If there isn't already a timer running
16118 			 * start one.  Use a 4 second
16119 			 * timer as a fallback since it can't fail.
16120 			 */
16121 			tcp->tcp_timeout = B_TRUE;
16122 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16123 			    MSEC_TO_TICK(4000));
16124 		}
16125 		return;
16126 	}
16127 	CONN_INC_REF(connp);
16128 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16129 	    SQTAG_TCP_RSRV);
16130 }
16131 
16132 /*
16133  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16134  * We do not allow the receive window to shrink.  After setting rwnd,
16135  * set the flow control hiwat of the stream.
16136  *
16137  * This function is called in 2 cases:
16138  *
16139  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16140  *    connection (passive open) and in tcp_rput_data() for active connect.
16141  *    This is called after tcp_mss_set() when the desired MSS value is known.
16142  *    This makes sure that our window size is a mutiple of the other side's
16143  *    MSS.
16144  * 2) Handling SO_RCVBUF option.
16145  *
16146  * It is ASSUMED that the requested size is a multiple of the current MSS.
16147  *
16148  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16149  * user requests so.
16150  */
16151 static int
16152 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16153 {
16154 	uint32_t	mss = tcp->tcp_mss;
16155 	uint32_t	old_max_rwnd;
16156 	uint32_t	max_transmittable_rwnd;
16157 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16158 
16159 	if (tcp_detached)
16160 		old_max_rwnd = tcp->tcp_rwnd;
16161 	else
16162 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16163 
16164 	/*
16165 	 * Insist on a receive window that is at least
16166 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16167 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16168 	 * and delayed acknowledgement.
16169 	 */
16170 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
16171 
16172 	/*
16173 	 * If window size info has already been exchanged, TCP should not
16174 	 * shrink the window.  Shrinking window is doable if done carefully.
16175 	 * We may add that support later.  But so far there is not a real
16176 	 * need to do that.
16177 	 */
16178 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16179 		/* MSS may have changed, do a round up again. */
16180 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16181 	}
16182 
16183 	/*
16184 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16185 	 * can be applied even before the window scale option is decided.
16186 	 */
16187 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16188 	if (rwnd > max_transmittable_rwnd) {
16189 		rwnd = max_transmittable_rwnd -
16190 		    (max_transmittable_rwnd % mss);
16191 		if (rwnd < mss)
16192 			rwnd = max_transmittable_rwnd;
16193 		/*
16194 		 * If we're over the limit we may have to back down tcp_rwnd.
16195 		 * The increment below won't work for us. So we set all three
16196 		 * here and the increment below will have no effect.
16197 		 */
16198 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16199 	}
16200 	if (tcp->tcp_localnet) {
16201 		tcp->tcp_rack_abs_max =
16202 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
16203 	} else {
16204 		/*
16205 		 * For a remote host on a different subnet (through a router),
16206 		 * we ack every other packet to be conforming to RFC1122.
16207 		 * tcp_deferred_acks_max is default to 2.
16208 		 */
16209 		tcp->tcp_rack_abs_max =
16210 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
16211 	}
16212 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16213 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16214 	else
16215 		tcp->tcp_rack_cur_max = 0;
16216 	/*
16217 	 * Increment the current rwnd by the amount the maximum grew (we
16218 	 * can not overwrite it since we might be in the middle of a
16219 	 * connection.)
16220 	 */
16221 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16222 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16223 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16224 		tcp->tcp_cwnd_max = rwnd;
16225 
16226 	if (tcp_detached)
16227 		return (rwnd);
16228 	/*
16229 	 * We set the maximum receive window into rq->q_hiwat.
16230 	 * This is not actually used for flow control.
16231 	 */
16232 	tcp->tcp_rq->q_hiwat = rwnd;
16233 	/*
16234 	 * Set the Stream head high water mark. This doesn't have to be
16235 	 * here, since we are simply using default values, but we would
16236 	 * prefer to choose these values algorithmically, with a likely
16237 	 * relationship to rwnd.  For fused loopback tcp, we double the
16238 	 * amount of buffer in order to simulate the normal tcp case.
16239 	 */
16240 	if (tcp->tcp_fused) {
16241 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd << 1,
16242 		    tcp_sth_rcv_hiwat));
16243 	} else {
16244 		(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd,
16245 		    tcp_sth_rcv_hiwat));
16246 	}
16247 	return (rwnd);
16248 }
16249 
16250 /*
16251  * Return SNMP stuff in buffer in mpdata.
16252  */
16253 static int
16254 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16255 {
16256 	mblk_t			*mpdata;
16257 	mblk_t			*mp_conn_ctl = NULL;
16258 	mblk_t			*mp_conn_data;
16259 	mblk_t			*mp6_conn_ctl = NULL;
16260 	mblk_t			*mp6_conn_data;
16261 	mblk_t			*mp_conn_tail = NULL;
16262 	mblk_t			*mp6_conn_tail = NULL;
16263 	struct opthdr		*optp;
16264 	mib2_tcpConnEntry_t	tce;
16265 	mib2_tcp6ConnEntry_t	tce6;
16266 	connf_t			*connfp;
16267 	conn_t			*connp;
16268 	int			i;
16269 	boolean_t 		ispriv;
16270 	zoneid_t 		zoneid;
16271 
16272 	if (mpctl == NULL ||
16273 	    (mpdata = mpctl->b_cont) == NULL ||
16274 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16275 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
16276 		if (mp_conn_ctl != NULL)
16277 			freemsg(mp_conn_ctl);
16278 		if (mp6_conn_ctl != NULL)
16279 			freemsg(mp6_conn_ctl);
16280 		return (0);
16281 	}
16282 
16283 	/* build table of connections -- need count in fixed part */
16284 	mp_conn_data = mp_conn_ctl->b_cont;
16285 	mp6_conn_data = mp6_conn_ctl->b_cont;
16286 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
16287 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
16288 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
16289 	SET_MIB(tcp_mib.tcpMaxConn, -1);
16290 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
16291 
16292 	ispriv =
16293 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16294 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16295 
16296 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16297 
16298 		connfp = &ipcl_globalhash_fanout[i];
16299 
16300 		connp = NULL;
16301 
16302 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16303 			tcp_t *tcp;
16304 
16305 			if (connp->conn_zoneid != zoneid)
16306 				continue;	/* not in this zone */
16307 
16308 			tcp = connp->conn_tcp;
16309 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
16310 			tcp->tcp_ibsegs = 0;
16311 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
16312 			tcp->tcp_obsegs = 0;
16313 
16314 			tce6.tcp6ConnState = tce.tcpConnState =
16315 			    tcp_snmp_state(tcp);
16316 			if (tce.tcpConnState == MIB2_TCP_established ||
16317 			    tce.tcpConnState == MIB2_TCP_closeWait)
16318 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
16319 
16320 			/* Create a message to report on IPv6 entries */
16321 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16322 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16323 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16324 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16325 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16326 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16327 			/* Don't want just anybody seeing these... */
16328 			if (ispriv) {
16329 				tce6.tcp6ConnEntryInfo.ce_snxt =
16330 				    tcp->tcp_snxt;
16331 				tce6.tcp6ConnEntryInfo.ce_suna =
16332 				    tcp->tcp_suna;
16333 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16334 				    tcp->tcp_rnxt;
16335 				tce6.tcp6ConnEntryInfo.ce_rack =
16336 				    tcp->tcp_rack;
16337 			} else {
16338 				/*
16339 				 * Netstat, unfortunately, uses this to
16340 				 * get send/receive queue sizes.  How to fix?
16341 				 * Why not compute the difference only?
16342 				 */
16343 				tce6.tcp6ConnEntryInfo.ce_snxt =
16344 				    tcp->tcp_snxt - tcp->tcp_suna;
16345 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16346 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16347 				    tcp->tcp_rnxt - tcp->tcp_rack;
16348 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16349 			}
16350 
16351 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16352 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16353 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16354 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16355 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16356 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
16357 			    (char *)&tce6, sizeof (tce6));
16358 			}
16359 			/*
16360 			 * Create an IPv4 table entry for IPv4 entries and also
16361 			 * for IPv6 entries which are bound to in6addr_any
16362 			 * but don't have IPV6_V6ONLY set.
16363 			 * (i.e. anything an IPv4 peer could connect to)
16364 			 */
16365 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16366 			    (tcp->tcp_state <= TCPS_LISTEN &&
16367 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16368 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16369 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16370 					tce.tcpConnRemAddress = INADDR_ANY;
16371 					tce.tcpConnLocalAddress = INADDR_ANY;
16372 				} else {
16373 					tce.tcpConnRemAddress =
16374 					    tcp->tcp_remote;
16375 					tce.tcpConnLocalAddress =
16376 					    tcp->tcp_ip_src;
16377 				}
16378 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16379 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16380 				/* Don't want just anybody seeing these... */
16381 				if (ispriv) {
16382 					tce.tcpConnEntryInfo.ce_snxt =
16383 					    tcp->tcp_snxt;
16384 					tce.tcpConnEntryInfo.ce_suna =
16385 					    tcp->tcp_suna;
16386 					tce.tcpConnEntryInfo.ce_rnxt =
16387 					    tcp->tcp_rnxt;
16388 					tce.tcpConnEntryInfo.ce_rack =
16389 					    tcp->tcp_rack;
16390 				} else {
16391 					/*
16392 					 * Netstat, unfortunately, uses this to
16393 					 * get send/receive queue sizes.  How
16394 					 * to fix?
16395 					 * Why not compute the difference only?
16396 					 */
16397 					tce.tcpConnEntryInfo.ce_snxt =
16398 					    tcp->tcp_snxt - tcp->tcp_suna;
16399 					tce.tcpConnEntryInfo.ce_suna = 0;
16400 					tce.tcpConnEntryInfo.ce_rnxt =
16401 					    tcp->tcp_rnxt - tcp->tcp_rack;
16402 					tce.tcpConnEntryInfo.ce_rack = 0;
16403 				}
16404 
16405 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16406 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16407 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16408 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16409 				tce.tcpConnEntryInfo.ce_state =
16410 				    tcp->tcp_state;
16411 				(void) snmp_append_data2(mp_conn_data,
16412 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16413 			}
16414 		}
16415 	}
16416 
16417 	/* fixed length structure for IPv4 and IPv6 counters */
16418 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16419 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
16420 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16421 	optp->level = MIB2_TCP;
16422 	optp->name = 0;
16423 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
16424 	optp->len = msgdsize(mpdata);
16425 	qreply(q, mpctl);
16426 
16427 	/* table of connections... */
16428 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16429 	    sizeof (struct T_optmgmt_ack)];
16430 	optp->level = MIB2_TCP;
16431 	optp->name = MIB2_TCP_CONN;
16432 	optp->len = msgdsize(mp_conn_data);
16433 	qreply(q, mp_conn_ctl);
16434 
16435 	/* table of IPv6 connections... */
16436 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16437 	    sizeof (struct T_optmgmt_ack)];
16438 	optp->level = MIB2_TCP6;
16439 	optp->name = MIB2_TCP6_CONN;
16440 	optp->len = msgdsize(mp6_conn_data);
16441 	qreply(q, mp6_conn_ctl);
16442 	return (1);
16443 }
16444 
16445 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16446 /* ARGSUSED */
16447 static int
16448 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16449 {
16450 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16451 
16452 	switch (level) {
16453 	case MIB2_TCP:
16454 		switch (name) {
16455 		case 13:
16456 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16457 				return (0);
16458 			/* TODO: delete entry defined by tce */
16459 			return (1);
16460 		default:
16461 			return (0);
16462 		}
16463 	default:
16464 		return (1);
16465 	}
16466 }
16467 
16468 /* Translate TCP state to MIB2 TCP state. */
16469 static int
16470 tcp_snmp_state(tcp_t *tcp)
16471 {
16472 	if (tcp == NULL)
16473 		return (0);
16474 
16475 	switch (tcp->tcp_state) {
16476 	case TCPS_CLOSED:
16477 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16478 	case TCPS_BOUND:
16479 		return (MIB2_TCP_closed);
16480 	case TCPS_LISTEN:
16481 		return (MIB2_TCP_listen);
16482 	case TCPS_SYN_SENT:
16483 		return (MIB2_TCP_synSent);
16484 	case TCPS_SYN_RCVD:
16485 		return (MIB2_TCP_synReceived);
16486 	case TCPS_ESTABLISHED:
16487 		return (MIB2_TCP_established);
16488 	case TCPS_CLOSE_WAIT:
16489 		return (MIB2_TCP_closeWait);
16490 	case TCPS_FIN_WAIT_1:
16491 		return (MIB2_TCP_finWait1);
16492 	case TCPS_CLOSING:
16493 		return (MIB2_TCP_closing);
16494 	case TCPS_LAST_ACK:
16495 		return (MIB2_TCP_lastAck);
16496 	case TCPS_FIN_WAIT_2:
16497 		return (MIB2_TCP_finWait2);
16498 	case TCPS_TIME_WAIT:
16499 		return (MIB2_TCP_timeWait);
16500 	default:
16501 		return (0);
16502 	}
16503 }
16504 
16505 static char tcp_report_header[] =
16506 	"TCP     " MI_COL_HDRPAD_STR
16507 	"zone dest            snxt     suna     "
16508 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16509 	"recent   [lport,fport] state";
16510 
16511 /*
16512  * TCP status report triggered via the Named Dispatch mechanism.
16513  */
16514 /* ARGSUSED */
16515 static void
16516 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16517     cred_t *cr)
16518 {
16519 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16520 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16521 	char cflag;
16522 	in6_addr_t	v6dst;
16523 	char buf[80];
16524 	uint_t print_len, buf_len;
16525 
16526 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16527 	if (buf_len <= 0)
16528 		return;
16529 
16530 	if (hashval >= 0)
16531 		(void) sprintf(hash, "%03d ", hashval);
16532 	else
16533 		hash[0] = '\0';
16534 
16535 	/*
16536 	 * Note that we use the remote address in the tcp_b  structure.
16537 	 * This means that it will print out the real destination address,
16538 	 * not the next hop's address if source routing is used.  This
16539 	 * avoid the confusion on the output because user may not
16540 	 * know that source routing is used for a connection.
16541 	 */
16542 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16543 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16544 	} else {
16545 		v6dst = tcp->tcp_remote_v6;
16546 	}
16547 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16548 	/*
16549 	 * the ispriv checks are so that normal users cannot determine
16550 	 * sequence number information using NDD.
16551 	 */
16552 
16553 	if (TCP_IS_DETACHED(tcp))
16554 		cflag = '*';
16555 	else
16556 		cflag = ' ';
16557 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16558 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16559 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16560 	    hash,
16561 	    (void *)tcp,
16562 	    tcp->tcp_connp->conn_zoneid,
16563 	    addrbuf,
16564 	    (ispriv) ? tcp->tcp_snxt : 0,
16565 	    (ispriv) ? tcp->tcp_suna : 0,
16566 	    tcp->tcp_swnd,
16567 	    (ispriv) ? tcp->tcp_rnxt : 0,
16568 	    (ispriv) ? tcp->tcp_rack : 0,
16569 	    tcp->tcp_rwnd,
16570 	    tcp->tcp_rto,
16571 	    tcp->tcp_mss,
16572 	    tcp->tcp_snd_ws_ok,
16573 	    tcp->tcp_snd_ws,
16574 	    tcp->tcp_rcv_ws,
16575 	    tcp->tcp_snd_ts_ok,
16576 	    tcp->tcp_ts_recent,
16577 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16578 	if (print_len < buf_len) {
16579 		((mblk_t *)mp)->b_wptr += print_len;
16580 	} else {
16581 		((mblk_t *)mp)->b_wptr += buf_len;
16582 	}
16583 }
16584 
16585 /*
16586  * TCP status report (for listeners only) triggered via the Named Dispatch
16587  * mechanism.
16588  */
16589 /* ARGSUSED */
16590 static void
16591 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16592 {
16593 	char addrbuf[INET6_ADDRSTRLEN];
16594 	in6_addr_t	v6dst;
16595 	uint_t print_len, buf_len;
16596 
16597 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16598 	if (buf_len <= 0)
16599 		return;
16600 
16601 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16602 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16603 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16604 	} else {
16605 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16606 		    addrbuf, sizeof (addrbuf));
16607 	}
16608 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16609 	    "%03d "
16610 	    MI_COL_PTRFMT_STR
16611 	    "%d %s %05u %08u %d/%d/%d%c\n",
16612 	    hashval, (void *)tcp,
16613 	    tcp->tcp_connp->conn_zoneid,
16614 	    addrbuf,
16615 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16616 	    tcp->tcp_conn_req_seqnum,
16617 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16618 	    tcp->tcp_conn_req_max,
16619 	    tcp->tcp_syn_defense ? '*' : ' ');
16620 	if (print_len < buf_len) {
16621 		((mblk_t *)mp)->b_wptr += print_len;
16622 	} else {
16623 		((mblk_t *)mp)->b_wptr += buf_len;
16624 	}
16625 }
16626 
16627 /* TCP status report triggered via the Named Dispatch mechanism. */
16628 /* ARGSUSED */
16629 static int
16630 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16631 {
16632 	tcp_t	*tcp;
16633 	int	i;
16634 	conn_t	*connp;
16635 	connf_t	*connfp;
16636 	zoneid_t zoneid;
16637 
16638 	/*
16639 	 * Because of the ndd constraint, at most we can have 64K buffer
16640 	 * to put in all TCP info.  So to be more efficient, just
16641 	 * allocate a 64K buffer here, assuming we need that large buffer.
16642 	 * This may be a problem as any user can read tcp_status.  Therefore
16643 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16644 	 * This should be OK as normal users should not do this too often.
16645 	 */
16646 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16647 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16648 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16649 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16650 			return (0);
16651 		}
16652 	}
16653 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16654 		/* The following may work even if we cannot get a large buf. */
16655 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16656 		return (0);
16657 	}
16658 
16659 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16660 
16661 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16662 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16663 
16664 		connfp = &ipcl_globalhash_fanout[i];
16665 
16666 		connp = NULL;
16667 
16668 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16669 			tcp = connp->conn_tcp;
16670 			if (zoneid != GLOBAL_ZONEID &&
16671 			    zoneid != connp->conn_zoneid)
16672 				continue;
16673 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16674 			    cr);
16675 		}
16676 
16677 	}
16678 
16679 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16680 	return (0);
16681 }
16682 
16683 /* TCP status report triggered via the Named Dispatch mechanism. */
16684 /* ARGSUSED */
16685 static int
16686 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16687 {
16688 	tf_t	*tbf;
16689 	tcp_t	*tcp;
16690 	int	i;
16691 	zoneid_t zoneid;
16692 
16693 	/* Refer to comments in tcp_status_report(). */
16694 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16695 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16696 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16697 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16698 			return (0);
16699 		}
16700 	}
16701 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16702 		/* The following may work even if we cannot get a large buf. */
16703 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16704 		return (0);
16705 	}
16706 
16707 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16708 
16709 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16710 
16711 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16712 		tbf = &tcp_bind_fanout[i];
16713 		mutex_enter(&tbf->tf_lock);
16714 		for (tcp = tbf->tf_tcp; tcp != NULL;
16715 		    tcp = tcp->tcp_bind_hash) {
16716 			if (zoneid != GLOBAL_ZONEID &&
16717 			    zoneid != tcp->tcp_connp->conn_zoneid)
16718 				continue;
16719 			CONN_INC_REF(tcp->tcp_connp);
16720 			tcp_report_item(mp->b_cont, tcp, i,
16721 			    Q_TO_TCP(q), cr);
16722 			CONN_DEC_REF(tcp->tcp_connp);
16723 		}
16724 		mutex_exit(&tbf->tf_lock);
16725 	}
16726 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16727 	return (0);
16728 }
16729 
16730 /* TCP status report triggered via the Named Dispatch mechanism. */
16731 /* ARGSUSED */
16732 static int
16733 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16734 {
16735 	connf_t	*connfp;
16736 	conn_t	*connp;
16737 	tcp_t	*tcp;
16738 	int	i;
16739 	zoneid_t zoneid;
16740 
16741 	/* Refer to comments in tcp_status_report(). */
16742 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16743 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16744 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16745 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16746 			return (0);
16747 		}
16748 	}
16749 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16750 		/* The following may work even if we cannot get a large buf. */
16751 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16752 		return (0);
16753 	}
16754 
16755 	(void) mi_mpprintf(mp,
16756 	    "    TCP    " MI_COL_HDRPAD_STR
16757 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16758 
16759 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16760 
16761 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16762 		connfp =  &ipcl_bind_fanout[i];
16763 		connp = NULL;
16764 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16765 			tcp = connp->conn_tcp;
16766 			if (zoneid != GLOBAL_ZONEID &&
16767 			    zoneid != connp->conn_zoneid)
16768 				continue;
16769 			tcp_report_listener(mp->b_cont, tcp, i);
16770 		}
16771 	}
16772 
16773 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16774 	return (0);
16775 }
16776 
16777 /* TCP status report triggered via the Named Dispatch mechanism. */
16778 /* ARGSUSED */
16779 static int
16780 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16781 {
16782 	connf_t	*connfp;
16783 	conn_t	*connp;
16784 	tcp_t	*tcp;
16785 	int	i;
16786 	zoneid_t zoneid;
16787 
16788 	/* Refer to comments in tcp_status_report(). */
16789 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16790 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16791 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16792 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16793 			return (0);
16794 		}
16795 	}
16796 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16797 		/* The following may work even if we cannot get a large buf. */
16798 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16799 		return (0);
16800 	}
16801 
16802 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16803 	    ipcl_conn_fanout_size);
16804 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16805 
16806 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16807 
16808 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16809 		connfp =  &ipcl_conn_fanout[i];
16810 		connp = NULL;
16811 		while ((connp = tcp_get_next_conn(connfp, connp))) {
16812 			tcp = connp->conn_tcp;
16813 			if (zoneid != GLOBAL_ZONEID &&
16814 			    zoneid != connp->conn_zoneid)
16815 				continue;
16816 			tcp_report_item(mp->b_cont, tcp, i,
16817 			    Q_TO_TCP(q), cr);
16818 		}
16819 	}
16820 
16821 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16822 	return (0);
16823 }
16824 
16825 /* TCP status report triggered via the Named Dispatch mechanism. */
16826 /* ARGSUSED */
16827 static int
16828 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16829 {
16830 	tf_t	*tf;
16831 	tcp_t	*tcp;
16832 	int	i;
16833 	zoneid_t zoneid;
16834 
16835 	/* Refer to comments in tcp_status_report(). */
16836 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16837 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16838 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16839 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16840 			return (0);
16841 		}
16842 	}
16843 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16844 		/* The following may work even if we cannot get a large buf. */
16845 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16846 		return (0);
16847 	}
16848 
16849 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16850 
16851 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16852 
16853 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16854 		tf = &tcp_acceptor_fanout[i];
16855 		mutex_enter(&tf->tf_lock);
16856 		for (tcp = tf->tf_tcp; tcp != NULL;
16857 		    tcp = tcp->tcp_acceptor_hash) {
16858 			if (zoneid != GLOBAL_ZONEID &&
16859 			    zoneid != tcp->tcp_connp->conn_zoneid)
16860 				continue;
16861 			tcp_report_item(mp->b_cont, tcp, i,
16862 			    Q_TO_TCP(q), cr);
16863 		}
16864 		mutex_exit(&tf->tf_lock);
16865 	}
16866 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16867 	return (0);
16868 }
16869 
16870 /*
16871  * tcp_timer is the timer service routine.  It handles the retransmission,
16872  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16873  * from the state of the tcp instance what kind of action needs to be done
16874  * at the time it is called.
16875  */
16876 static void
16877 tcp_timer(void *arg)
16878 {
16879 	mblk_t		*mp;
16880 	clock_t		first_threshold;
16881 	clock_t		second_threshold;
16882 	clock_t		ms;
16883 	uint32_t	mss;
16884 	conn_t		*connp = (conn_t *)arg;
16885 	tcp_t		*tcp = connp->conn_tcp;
16886 
16887 	tcp->tcp_timer_tid = 0;
16888 
16889 	if (tcp->tcp_fused)
16890 		return;
16891 
16892 	first_threshold =  tcp->tcp_first_timer_threshold;
16893 	second_threshold = tcp->tcp_second_timer_threshold;
16894 	switch (tcp->tcp_state) {
16895 	case TCPS_IDLE:
16896 	case TCPS_BOUND:
16897 	case TCPS_LISTEN:
16898 		return;
16899 	case TCPS_SYN_RCVD: {
16900 		tcp_t	*listener = tcp->tcp_listener;
16901 
16902 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16903 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16904 			/* it's our first timeout */
16905 			tcp->tcp_syn_rcvd_timeout = 1;
16906 			mutex_enter(&listener->tcp_eager_lock);
16907 			listener->tcp_syn_rcvd_timeout++;
16908 			if (!listener->tcp_syn_defense &&
16909 			    (listener->tcp_syn_rcvd_timeout >
16910 			    (tcp_conn_req_max_q0 >> 2)) &&
16911 			    (tcp_conn_req_max_q0 > 200)) {
16912 				/* We may be under attack. Put on a defense. */
16913 				listener->tcp_syn_defense = B_TRUE;
16914 				cmn_err(CE_WARN, "High TCP connect timeout "
16915 				    "rate! System (port %d) may be under a "
16916 				    "SYN flood attack!",
16917 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16918 
16919 				listener->tcp_ip_addr_cache = kmem_zalloc(
16920 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16921 				    KM_NOSLEEP);
16922 			}
16923 			mutex_exit(&listener->tcp_eager_lock);
16924 		}
16925 	}
16926 		/* FALLTHRU */
16927 	case TCPS_SYN_SENT:
16928 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16929 		second_threshold = tcp->tcp_second_ctimer_threshold;
16930 		break;
16931 	case TCPS_ESTABLISHED:
16932 	case TCPS_FIN_WAIT_1:
16933 	case TCPS_CLOSING:
16934 	case TCPS_CLOSE_WAIT:
16935 	case TCPS_LAST_ACK:
16936 		/* If we have data to rexmit */
16937 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16938 			clock_t	time_to_wait;
16939 
16940 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16941 			if (!tcp->tcp_xmit_head)
16942 				break;
16943 			time_to_wait = lbolt -
16944 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16945 			time_to_wait = tcp->tcp_rto -
16946 			    TICK_TO_MSEC(time_to_wait);
16947 			/*
16948 			 * If the timer fires too early, 1 clock tick earlier,
16949 			 * restart the timer.
16950 			 */
16951 			if (time_to_wait > msec_per_tick) {
16952 				TCP_STAT(tcp_timer_fire_early);
16953 				TCP_TIMER_RESTART(tcp, time_to_wait);
16954 				return;
16955 			}
16956 			/*
16957 			 * When we probe zero windows, we force the swnd open.
16958 			 * If our peer acks with a closed window swnd will be
16959 			 * set to zero by tcp_rput(). As long as we are
16960 			 * receiving acks tcp_rput will
16961 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16962 			 * first and second interval actions.  NOTE: the timer
16963 			 * interval is allowed to continue its exponential
16964 			 * backoff.
16965 			 */
16966 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16967 				if (tcp->tcp_debug) {
16968 					(void) strlog(TCP_MODULE_ID, 0, 1,
16969 					    SL_TRACE, "tcp_timer: zero win");
16970 				}
16971 			} else {
16972 				/*
16973 				 * After retransmission, we need to do
16974 				 * slow start.  Set the ssthresh to one
16975 				 * half of current effective window and
16976 				 * cwnd to one MSS.  Also reset
16977 				 * tcp_cwnd_cnt.
16978 				 *
16979 				 * Note that if tcp_ssthresh is reduced because
16980 				 * of ECN, do not reduce it again unless it is
16981 				 * already one window of data away (tcp_cwr
16982 				 * should then be cleared) or this is a
16983 				 * timeout for a retransmitted segment.
16984 				 */
16985 				uint32_t npkt;
16986 
16987 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16988 					npkt = ((tcp->tcp_timer_backoff ?
16989 					    tcp->tcp_cwnd_ssthresh :
16990 					    tcp->tcp_snxt -
16991 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16992 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16993 					    tcp->tcp_mss;
16994 				}
16995 				tcp->tcp_cwnd = tcp->tcp_mss;
16996 				tcp->tcp_cwnd_cnt = 0;
16997 				if (tcp->tcp_ecn_ok) {
16998 					tcp->tcp_cwr = B_TRUE;
16999 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17000 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17001 				}
17002 			}
17003 			break;
17004 		}
17005 		/*
17006 		 * We have something to send yet we cannot send.  The
17007 		 * reason can be:
17008 		 *
17009 		 * 1. Zero send window: we need to do zero window probe.
17010 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17011 		 * segments.
17012 		 * 3. SWS avoidance: receiver may have shrunk window,
17013 		 * reset our knowledge.
17014 		 *
17015 		 * Note that condition 2 can happen with either 1 or
17016 		 * 3.  But 1 and 3 are exclusive.
17017 		 */
17018 		if (tcp->tcp_unsent != 0) {
17019 			if (tcp->tcp_cwnd == 0) {
17020 				/*
17021 				 * Set tcp_cwnd to 1 MSS so that a
17022 				 * new segment can be sent out.  We
17023 				 * are "clocking out" new data when
17024 				 * the network is really congested.
17025 				 */
17026 				ASSERT(tcp->tcp_ecn_ok);
17027 				tcp->tcp_cwnd = tcp->tcp_mss;
17028 			}
17029 			if (tcp->tcp_swnd == 0) {
17030 				/* Extend window for zero window probe */
17031 				tcp->tcp_swnd++;
17032 				tcp->tcp_zero_win_probe = B_TRUE;
17033 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
17034 			} else {
17035 				/*
17036 				 * Handle timeout from sender SWS avoidance.
17037 				 * Reset our knowledge of the max send window
17038 				 * since the receiver might have reduced its
17039 				 * receive buffer.  Avoid setting tcp_max_swnd
17040 				 * to one since that will essentially disable
17041 				 * the SWS checks.
17042 				 *
17043 				 * Note that since we don't have a SWS
17044 				 * state variable, if the timeout is set
17045 				 * for ECN but not for SWS, this
17046 				 * code will also be executed.  This is
17047 				 * fine as tcp_max_swnd is updated
17048 				 * constantly and it will not affect
17049 				 * anything.
17050 				 */
17051 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17052 			}
17053 			tcp_wput_data(tcp, NULL, B_FALSE);
17054 			return;
17055 		}
17056 		/* Is there a FIN that needs to be to re retransmitted? */
17057 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17058 		    !tcp->tcp_fin_acked)
17059 			break;
17060 		/* Nothing to do, return without restarting timer. */
17061 		TCP_STAT(tcp_timer_fire_miss);
17062 		return;
17063 	case TCPS_FIN_WAIT_2:
17064 		/*
17065 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17066 		 * We waited some time for for peer's FIN, but it hasn't
17067 		 * arrived.  We flush the connection now to avoid
17068 		 * case where the peer has rebooted.
17069 		 */
17070 		if (TCP_IS_DETACHED(tcp)) {
17071 			(void) tcp_clean_death(tcp, 0, 23);
17072 		} else {
17073 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
17074 		}
17075 		return;
17076 	case TCPS_TIME_WAIT:
17077 		(void) tcp_clean_death(tcp, 0, 24);
17078 		return;
17079 	default:
17080 		if (tcp->tcp_debug) {
17081 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE|SL_ERROR,
17082 			    "tcp_timer: strange state (%d) %s",
17083 			    tcp->tcp_state, tcp_display(tcp, NULL,
17084 			    DISP_PORT_ONLY));
17085 		}
17086 		return;
17087 	}
17088 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17089 		/*
17090 		 * For zero window probe, we need to send indefinitely,
17091 		 * unless we have not heard from the other side for some
17092 		 * time...
17093 		 */
17094 		if ((tcp->tcp_zero_win_probe == 0) ||
17095 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17096 		    second_threshold)) {
17097 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
17098 			/*
17099 			 * If TCP is in SYN_RCVD state, send back a
17100 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17101 			 * should be zero in TCPS_SYN_RCVD state.
17102 			 */
17103 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17104 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17105 				    "in SYN_RCVD",
17106 				    tcp, tcp->tcp_snxt,
17107 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17108 			}
17109 			(void) tcp_clean_death(tcp,
17110 			    tcp->tcp_client_errno ?
17111 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17112 			return;
17113 		} else {
17114 			/*
17115 			 * Set tcp_ms_we_have_waited to second_threshold
17116 			 * so that in next timeout, we will do the above
17117 			 * check (lbolt - tcp_last_recv_time).  This is
17118 			 * also to avoid overflow.
17119 			 *
17120 			 * We don't need to decrement tcp_timer_backoff
17121 			 * to avoid overflow because it will be decremented
17122 			 * later if new timeout value is greater than
17123 			 * tcp_rexmit_interval_max.  In the case when
17124 			 * tcp_rexmit_interval_max is greater than
17125 			 * second_threshold, it means that we will wait
17126 			 * longer than second_threshold to send the next
17127 			 * window probe.
17128 			 */
17129 			tcp->tcp_ms_we_have_waited = second_threshold;
17130 		}
17131 	} else if (ms > first_threshold) {
17132 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17133 		    tcp->tcp_xmit_head != NULL) {
17134 			tcp->tcp_xmit_head =
17135 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17136 		}
17137 		/*
17138 		 * We have been retransmitting for too long...  The RTT
17139 		 * we calculated is probably incorrect.  Reinitialize it.
17140 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17141 		 * tcp_rtt_update so that we won't accidentally cache a
17142 		 * bad value.  But only do this if this is not a zero
17143 		 * window probe.
17144 		 */
17145 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17146 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17147 			    (tcp->tcp_rtt_sa >> 5);
17148 			tcp->tcp_rtt_sa = 0;
17149 			tcp_ip_notify(tcp);
17150 			tcp->tcp_rtt_update = 0;
17151 		}
17152 	}
17153 	tcp->tcp_timer_backoff++;
17154 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17155 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17156 	    tcp_rexmit_interval_min) {
17157 		/*
17158 		 * This means the original RTO is tcp_rexmit_interval_min.
17159 		 * So we will use tcp_rexmit_interval_min as the RTO value
17160 		 * and do the backoff.
17161 		 */
17162 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
17163 	} else {
17164 		ms <<= tcp->tcp_timer_backoff;
17165 	}
17166 	if (ms > tcp_rexmit_interval_max) {
17167 		ms = tcp_rexmit_interval_max;
17168 		/*
17169 		 * ms is at max, decrement tcp_timer_backoff to avoid
17170 		 * overflow.
17171 		 */
17172 		tcp->tcp_timer_backoff--;
17173 	}
17174 	tcp->tcp_ms_we_have_waited += ms;
17175 	if (tcp->tcp_zero_win_probe == 0) {
17176 		tcp->tcp_rto = ms;
17177 	}
17178 	TCP_TIMER_RESTART(tcp, ms);
17179 	/*
17180 	 * This is after a timeout and tcp_rto is backed off.  Set
17181 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17182 	 * restart the timer with a correct value.
17183 	 */
17184 	tcp->tcp_set_timer = 1;
17185 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17186 	if (mss > tcp->tcp_mss)
17187 		mss = tcp->tcp_mss;
17188 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17189 		mss = tcp->tcp_swnd;
17190 
17191 	if ((mp = tcp->tcp_xmit_head) != NULL)
17192 		mp->b_prev = (mblk_t *)lbolt;
17193 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17194 	    B_TRUE);
17195 
17196 	/*
17197 	 * When slow start after retransmission begins, start with
17198 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17199 	 * start phase.  tcp_snd_burst controls how many segments
17200 	 * can be sent because of an ack.
17201 	 */
17202 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17203 	tcp->tcp_snd_burst = TCP_CWND_SS;
17204 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17205 	    (tcp->tcp_unsent == 0)) {
17206 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17207 	} else {
17208 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17209 	}
17210 	tcp->tcp_rexmit = B_TRUE;
17211 	tcp->tcp_dupack_cnt = 0;
17212 
17213 	/*
17214 	 * Remove all rexmit SACK blk to start from fresh.
17215 	 */
17216 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17217 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17218 		tcp->tcp_num_notsack_blk = 0;
17219 		tcp->tcp_cnt_notsack_list = 0;
17220 	}
17221 	if (mp == NULL) {
17222 		return;
17223 	}
17224 	/* Attach credentials to retransmitted initial SYNs. */
17225 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17226 		mblk_setcred(mp, tcp->tcp_cred);
17227 		DB_CPID(mp) = tcp->tcp_cpid;
17228 	}
17229 
17230 	tcp->tcp_csuna = tcp->tcp_snxt;
17231 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
17232 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
17233 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
17234 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17235 
17236 }
17237 
17238 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17239 static void
17240 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17241 {
17242 	conn_t	*connp;
17243 
17244 	switch (tcp->tcp_state) {
17245 	case TCPS_BOUND:
17246 	case TCPS_LISTEN:
17247 		break;
17248 	default:
17249 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17250 		return;
17251 	}
17252 
17253 	/*
17254 	 * Need to clean up all the eagers since after the unbind, segments
17255 	 * will no longer be delivered to this listener stream.
17256 	 */
17257 	mutex_enter(&tcp->tcp_eager_lock);
17258 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17259 		tcp_eager_cleanup(tcp, 0);
17260 	}
17261 	mutex_exit(&tcp->tcp_eager_lock);
17262 
17263 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17264 		tcp->tcp_ipha->ipha_src = 0;
17265 	} else {
17266 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17267 	}
17268 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17269 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17270 	tcp_bind_hash_remove(tcp);
17271 	tcp->tcp_state = TCPS_IDLE;
17272 	tcp->tcp_mdt = B_FALSE;
17273 	/* Send M_FLUSH according to TPI */
17274 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17275 	connp = tcp->tcp_connp;
17276 	connp->conn_mdt_ok = B_FALSE;
17277 	ipcl_hash_remove(connp);
17278 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17279 	mp = mi_tpi_ok_ack_alloc(mp);
17280 	putnext(tcp->tcp_rq, mp);
17281 }
17282 
17283 /*
17284  * Don't let port fall into the privileged range.
17285  * Since the extra privileged ports can be arbitrary we also
17286  * ensure that we exclude those from consideration.
17287  * tcp_g_epriv_ports is not sorted thus we loop over it until
17288  * there are no changes.
17289  *
17290  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17291  * but instead the code relies on:
17292  * - the fact that the address of the array and its size never changes
17293  * - the atomic assignment of the elements of the array
17294  */
17295 static in_port_t
17296 tcp_update_next_port(in_port_t port, boolean_t random)
17297 {
17298 	int i;
17299 
17300 	if (random && tcp_random_anon_port != 0) {
17301 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17302 		    sizeof (in_port_t));
17303 		/*
17304 		 * Unless changed by a sys admin, the smallest anon port
17305 		 * is 32768 and the largest anon port is 65535.  It is
17306 		 * very likely (50%) for the random port to be smaller
17307 		 * than the smallest anon port.  When that happens,
17308 		 * add port % (anon port range) to the smallest anon
17309 		 * port to get the random port.  It should fall into the
17310 		 * valid anon port range.
17311 		 */
17312 		if (port < tcp_smallest_anon_port) {
17313 			port = tcp_smallest_anon_port +
17314 			    port % (tcp_largest_anon_port -
17315 				tcp_smallest_anon_port);
17316 		}
17317 	}
17318 
17319 retry:
17320 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
17321 		port = (in_port_t)tcp_smallest_anon_port;
17322 
17323 	if (port < tcp_smallest_nonpriv_port)
17324 		port = (in_port_t)tcp_smallest_nonpriv_port;
17325 
17326 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
17327 		if (port == tcp_g_epriv_ports[i]) {
17328 			port++;
17329 			/*
17330 			 * Make sure whether the port is in the
17331 			 * valid range.
17332 			 *
17333 			 * XXX Note that if tcp_g_epriv_ports contains
17334 			 * all the anonymous ports this will be an
17335 			 * infinite loop.
17336 			 */
17337 			goto retry;
17338 		}
17339 	}
17340 	return (port);
17341 }
17342 
17343 /*
17344  * Return the next anonymous port in the priviledged port range for
17345  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17346  * downwards.  This is the same behavior as documented in the userland
17347  * library call rresvport(3N).
17348  */
17349 static in_port_t
17350 tcp_get_next_priv_port(void)
17351 {
17352 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17353 
17354 	if (next_priv_port < tcp_min_anonpriv_port) {
17355 		next_priv_port = IPPORT_RESERVED - 1;
17356 	}
17357 	return (next_priv_port--);
17358 }
17359 
17360 /* The write side r/w procedure. */
17361 
17362 #if CCS_STATS
17363 struct {
17364 	struct {
17365 		int64_t count, bytes;
17366 	} tot, hit;
17367 } wrw_stats;
17368 #endif
17369 
17370 /*
17371  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17372  * messages.
17373  */
17374 /* ARGSUSED */
17375 static void
17376 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17377 {
17378 	conn_t	*connp = (conn_t *)arg;
17379 	tcp_t	*tcp = connp->conn_tcp;
17380 	queue_t	*q = tcp->tcp_wq;
17381 
17382 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17383 	/*
17384 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17385 	 * Once the close starts, streamhead and sockfs will not let any data
17386 	 * packets come down (close ensures that there are no threads using the
17387 	 * queue and no new threads will come down) but since qprocsoff()
17388 	 * hasn't happened yet, a M_FLUSH or some non data message might
17389 	 * get reflected back (in response to our own FLUSHRW) and get
17390 	 * processed after tcp_close() is done. The conn would still be valid
17391 	 * because a ref would have added but we need to check the state
17392 	 * before actually processing the packet.
17393 	 */
17394 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17395 		freemsg(mp);
17396 		return;
17397 	}
17398 
17399 	switch (DB_TYPE(mp)) {
17400 	case M_IOCDATA:
17401 		tcp_wput_iocdata(tcp, mp);
17402 		break;
17403 	case M_FLUSH:
17404 		tcp_wput_flush(tcp, mp);
17405 		break;
17406 	default:
17407 		CALL_IP_WPUT(connp, q, mp);
17408 		break;
17409 	}
17410 }
17411 
17412 /*
17413  * Write side put procedure for TCP module instance.
17414  * TCP as a module is only used for MIB browsers that push TCP over IP or
17415  * ARP. The only supported primitives are T_SVR4_OPTMGMT_REQ and
17416  * T_OPTMGMT_REQ. M_FLUSH messages are only passed downstream; we don't flush
17417  * our queues as we never enqueue messages there. All ioctls are NAKed and
17418  * everything else is freed.
17419  */
17420 static void
17421 tcp_wput_mod(queue_t *q, mblk_t *mp)
17422 {
17423 	switch (DB_TYPE(mp)) {
17424 	case M_PROTO:
17425 	case M_PCPROTO:
17426 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
17427 		    ((((union T_primitives *)mp->b_rptr)->type ==
17428 			T_SVR4_OPTMGMT_REQ) ||
17429 		    (((union T_primitives *)mp->b_rptr)->type ==
17430 			T_OPTMGMT_REQ))) {
17431 			/*
17432 			 * This is the only TPI primitive supported. Its
17433 			 * handling does not require tcp_t, but it does require
17434 			 * conn_t to check permissions.
17435 			 */
17436 			cred_t	*cr = DB_CREDDEF(mp, Q_TO_CONN(q)->conn_cred);
17437 			if (!snmpcom_req(q, mp, tcp_snmp_set,
17438 			    tcp_snmp_get, cr)) {
17439 				freemsg(mp);
17440 				return;
17441 			}
17442 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
17443 		    != NULL)
17444 			qreply(q, mp);
17445 		break;
17446 	case M_FLUSH:
17447 		putnext(q, mp);
17448 		break;
17449 	case M_IOCTL:
17450 		miocnak(q, mp, 0, ENOTSUP);
17451 		break;
17452 	default:
17453 		freemsg(mp);
17454 		break;
17455 	}
17456 }
17457 
17458 /*
17459  * The TCP fast path write put procedure.
17460  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17461  */
17462 /* ARGSUSED */
17463 static void
17464 tcp_output(void *arg, mblk_t *mp, void *arg2)
17465 {
17466 	int		len;
17467 	int		hdrlen;
17468 	int		plen;
17469 	mblk_t		*mp1;
17470 	uchar_t		*rptr;
17471 	uint32_t	snxt;
17472 	tcph_t		*tcph;
17473 	struct datab	*db;
17474 	uint32_t	suna;
17475 	uint32_t	mss;
17476 	ipaddr_t	*dst;
17477 	ipaddr_t	*src;
17478 	uint32_t	sum;
17479 	int		usable;
17480 	conn_t		*connp = (conn_t *)arg;
17481 	tcp_t		*tcp = connp->conn_tcp;
17482 
17483 	/*
17484 	 * Try and ASSERT the minimum possible references on the
17485 	 * conn early enough. Since we are executing on write side,
17486 	 * the connection is obviously not detached and that means
17487 	 * there is a ref each for TCP and IP. Since we are behind
17488 	 * the squeue, the minimum references needed are 3. If the
17489 	 * conn is in classifier hash list, there should be an
17490 	 * extra ref for that (we check both the possibilities).
17491 	 */
17492 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17493 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17494 
17495 	/* Bypass tcp protocol for fused tcp loopback */
17496 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp))
17497 		return;
17498 
17499 	mss = tcp->tcp_mss;
17500 	if (tcp->tcp_xmit_zc_clean)
17501 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17502 
17503 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17504 	len = (int)(mp->b_wptr - mp->b_rptr);
17505 
17506 	/*
17507 	 * Criteria for fast path:
17508 	 *
17509 	 *   1. no unsent data
17510 	 *   2. single mblk in request
17511 	 *   3. connection established
17512 	 *   4. data in mblk
17513 	 *   5. len <= mss
17514 	 *   6. no tcp_valid bits
17515 	 */
17516 	if ((tcp->tcp_unsent != 0) ||
17517 	    (tcp->tcp_cork) ||
17518 	    (mp->b_cont != NULL) ||
17519 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17520 	    (len == 0) ||
17521 	    (len > mss) ||
17522 	    (tcp->tcp_valid_bits != 0)) {
17523 		tcp_wput_data(tcp, mp, B_FALSE);
17524 		return;
17525 	}
17526 
17527 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17528 	ASSERT(tcp->tcp_fin_sent == 0);
17529 
17530 	/* queue new packet onto retransmission queue */
17531 	if (tcp->tcp_xmit_head == NULL) {
17532 		tcp->tcp_xmit_head = mp;
17533 	} else {
17534 		tcp->tcp_xmit_last->b_cont = mp;
17535 	}
17536 	tcp->tcp_xmit_last = mp;
17537 	tcp->tcp_xmit_tail = mp;
17538 
17539 	/* find out how much we can send */
17540 	/* BEGIN CSTYLED */
17541 	/*
17542 	 *    un-acked           usable
17543 	 *  |--------------|-----------------|
17544 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17545 	 */
17546 	/* END CSTYLED */
17547 
17548 	/* start sending from tcp_snxt */
17549 	snxt = tcp->tcp_snxt;
17550 
17551 	/*
17552 	 * Check to see if this connection has been idled for some
17553 	 * time and no ACK is expected.  If it is, we need to slow
17554 	 * start again to get back the connection's "self-clock" as
17555 	 * described in VJ's paper.
17556 	 *
17557 	 * Refer to the comment in tcp_mss_set() for the calculation
17558 	 * of tcp_cwnd after idle.
17559 	 */
17560 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17561 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17562 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17563 	}
17564 
17565 	usable = tcp->tcp_swnd;		/* tcp window size */
17566 	if (usable > tcp->tcp_cwnd)
17567 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17568 	usable -= snxt;		/* subtract stuff already sent */
17569 	suna = tcp->tcp_suna;
17570 	usable += suna;
17571 	/* usable can be < 0 if the congestion window is smaller */
17572 	if (len > usable) {
17573 		/* Can't send complete M_DATA in one shot */
17574 		goto slow;
17575 	}
17576 
17577 	/*
17578 	 * determine if anything to send (Nagle).
17579 	 *
17580 	 *   1. len < tcp_mss (i.e. small)
17581 	 *   2. unacknowledged data present
17582 	 *   3. len < nagle limit
17583 	 *   4. last packet sent < nagle limit (previous packet sent)
17584 	 */
17585 	if ((len < mss) && (snxt != suna) &&
17586 	    (len < (int)tcp->tcp_naglim) &&
17587 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17588 		/*
17589 		 * This was the first unsent packet and normally
17590 		 * mss < xmit_hiwater so there is no need to worry
17591 		 * about flow control. The next packet will go
17592 		 * through the flow control check in tcp_wput_data().
17593 		 */
17594 		/* leftover work from above */
17595 		tcp->tcp_unsent = len;
17596 		tcp->tcp_xmit_tail_unsent = len;
17597 
17598 		return;
17599 	}
17600 
17601 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17602 
17603 	if (snxt == suna) {
17604 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17605 	}
17606 
17607 	/* we have always sent something */
17608 	tcp->tcp_rack_cnt = 0;
17609 
17610 	tcp->tcp_snxt = snxt + len;
17611 	tcp->tcp_rack = tcp->tcp_rnxt;
17612 
17613 	if ((mp1 = dupb(mp)) == 0)
17614 		goto no_memory;
17615 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17616 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17617 
17618 	/* adjust tcp header information */
17619 	tcph = tcp->tcp_tcph;
17620 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17621 
17622 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17623 	sum = (sum >> 16) + (sum & 0xFFFF);
17624 	U16_TO_ABE16(sum, tcph->th_sum);
17625 
17626 	U32_TO_ABE32(snxt, tcph->th_seq);
17627 
17628 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17629 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17630 	BUMP_LOCAL(tcp->tcp_obsegs);
17631 
17632 	/* Update the latest receive window size in TCP header. */
17633 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17634 	    tcph->th_win);
17635 
17636 	tcp->tcp_last_sent_len = (ushort_t)len;
17637 
17638 	plen = len + tcp->tcp_hdr_len;
17639 
17640 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17641 		tcp->tcp_ipha->ipha_length = htons(plen);
17642 	} else {
17643 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17644 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17645 	}
17646 
17647 	/* see if we need to allocate a mblk for the headers */
17648 	hdrlen = tcp->tcp_hdr_len;
17649 	rptr = mp1->b_rptr - hdrlen;
17650 	db = mp1->b_datap;
17651 	if ((db->db_ref != 2) || rptr < db->db_base ||
17652 	    (!OK_32PTR(rptr))) {
17653 		/* NOTE: we assume allocb returns an OK_32PTR */
17654 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17655 		    tcp_wroff_xtra, BPRI_MED);
17656 		if (!mp) {
17657 			freemsg(mp1);
17658 			goto no_memory;
17659 		}
17660 		mp->b_cont = mp1;
17661 		mp1 = mp;
17662 		/* Leave room for Link Level header */
17663 		/* hdrlen = tcp->tcp_hdr_len; */
17664 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17665 		mp1->b_wptr = &rptr[hdrlen];
17666 	}
17667 	mp1->b_rptr = rptr;
17668 
17669 	/* Fill in the timestamp option. */
17670 	if (tcp->tcp_snd_ts_ok) {
17671 		U32_TO_BE32((uint32_t)lbolt,
17672 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17673 		U32_TO_BE32(tcp->tcp_ts_recent,
17674 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17675 	} else {
17676 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17677 	}
17678 
17679 	/* copy header into outgoing packet */
17680 	dst = (ipaddr_t *)rptr;
17681 	src = (ipaddr_t *)tcp->tcp_iphc;
17682 	dst[0] = src[0];
17683 	dst[1] = src[1];
17684 	dst[2] = src[2];
17685 	dst[3] = src[3];
17686 	dst[4] = src[4];
17687 	dst[5] = src[5];
17688 	dst[6] = src[6];
17689 	dst[7] = src[7];
17690 	dst[8] = src[8];
17691 	dst[9] = src[9];
17692 	if (hdrlen -= 40) {
17693 		hdrlen >>= 2;
17694 		dst += 10;
17695 		src += 10;
17696 		do {
17697 			*dst++ = *src++;
17698 		} while (--hdrlen);
17699 	}
17700 
17701 	/*
17702 	 * Set the ECN info in the TCP header.  Note that this
17703 	 * is not the template header.
17704 	 */
17705 	if (tcp->tcp_ecn_ok) {
17706 		SET_ECT(tcp, rptr);
17707 
17708 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17709 		if (tcp->tcp_ecn_echo_on)
17710 			tcph->th_flags[0] |= TH_ECE;
17711 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17712 			tcph->th_flags[0] |= TH_CWR;
17713 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17714 		}
17715 	}
17716 
17717 	if (tcp->tcp_ip_forward_progress) {
17718 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17719 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17720 		tcp->tcp_ip_forward_progress = B_FALSE;
17721 	}
17722 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17723 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17724 	return;
17725 
17726 	/*
17727 	 * If we ran out of memory, we pretend to have sent the packet
17728 	 * and that it was lost on the wire.
17729 	 */
17730 no_memory:
17731 	return;
17732 
17733 slow:
17734 	/* leftover work from above */
17735 	tcp->tcp_unsent = len;
17736 	tcp->tcp_xmit_tail_unsent = len;
17737 	tcp_wput_data(tcp, NULL, B_FALSE);
17738 }
17739 
17740 /*
17741  * The function called through squeue to get behind eager's perimeter to
17742  * finish the accept processing.
17743  */
17744 /* ARGSUSED */
17745 void
17746 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17747 {
17748 	conn_t			*connp = (conn_t *)arg;
17749 	tcp_t			*tcp = connp->conn_tcp;
17750 	queue_t			*q = tcp->tcp_rq;
17751 	mblk_t			*mp1;
17752 	mblk_t			*stropt_mp = mp;
17753 	struct  stroptions	*stropt;
17754 	uint_t			thwin;
17755 
17756 	/*
17757 	 * Drop the eager's ref on the listener, that was placed when
17758 	 * this eager began life in tcp_conn_request.
17759 	 */
17760 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17761 
17762 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17763 		/*
17764 		 * Someone blewoff the eager before we could finish
17765 		 * the accept.
17766 		 *
17767 		 * The only reason eager exists it because we put in
17768 		 * a ref on it when conn ind went up. We need to send
17769 		 * a disconnect indication up while the last reference
17770 		 * on the eager will be dropped by the squeue when we
17771 		 * return.
17772 		 */
17773 		ASSERT(tcp->tcp_listener == NULL);
17774 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17775 			struct	T_discon_ind	*tdi;
17776 
17777 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17778 			/*
17779 			 * Let us reuse the incoming mblk to avoid memory
17780 			 * allocation failure problems. We know that the
17781 			 * size of the incoming mblk i.e. stroptions is greater
17782 			 * than sizeof T_discon_ind. So the reallocb below
17783 			 * can't fail.
17784 			 */
17785 			freemsg(mp->b_cont);
17786 			mp->b_cont = NULL;
17787 			ASSERT(DB_REF(mp) == 1);
17788 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17789 			    B_FALSE);
17790 			ASSERT(mp != NULL);
17791 			DB_TYPE(mp) = M_PROTO;
17792 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17793 			tdi = (struct T_discon_ind *)mp->b_rptr;
17794 			if (tcp->tcp_issocket) {
17795 				tdi->DISCON_reason = ECONNREFUSED;
17796 				tdi->SEQ_number = 0;
17797 			} else {
17798 				tdi->DISCON_reason = ENOPROTOOPT;
17799 				tdi->SEQ_number =
17800 				    tcp->tcp_conn_req_seqnum;
17801 			}
17802 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17803 			putnext(q, mp);
17804 		} else {
17805 			freemsg(mp);
17806 		}
17807 		if (tcp->tcp_hard_binding) {
17808 			tcp->tcp_hard_binding = B_FALSE;
17809 			tcp->tcp_hard_bound = B_TRUE;
17810 		}
17811 		tcp->tcp_detached = B_FALSE;
17812 		return;
17813 	}
17814 
17815 	mp1 = stropt_mp->b_cont;
17816 	stropt_mp->b_cont = NULL;
17817 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17818 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17819 
17820 	while (mp1 != NULL) {
17821 		mp = mp1;
17822 		mp1 = mp1->b_cont;
17823 		mp->b_cont = NULL;
17824 		tcp->tcp_drop_opt_ack_cnt++;
17825 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17826 	}
17827 	mp = NULL;
17828 
17829 	/*
17830 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17831 	 * properly.  This is the first time we know of the acceptor'
17832 	 * queue.  So we do it here.
17833 	 */
17834 	if (tcp->tcp_rcv_list == NULL) {
17835 		/*
17836 		 * Recv queue is empty, tcp_rwnd should not have changed.
17837 		 * That means it should be equal to the listener's tcp_rwnd.
17838 		 */
17839 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17840 	} else {
17841 #ifdef DEBUG
17842 		uint_t cnt = 0;
17843 
17844 		mp1 = tcp->tcp_rcv_list;
17845 		while ((mp = mp1) != NULL) {
17846 			mp1 = mp->b_next;
17847 			cnt += msgdsize(mp);
17848 		}
17849 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17850 #endif
17851 		/* There is some data, add them back to get the max. */
17852 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17853 	}
17854 
17855 	stropt->so_flags = SO_HIWAT;
17856 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17857 
17858 	stropt->so_flags |= SO_MAXBLK;
17859 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17860 
17861 	/*
17862 	 * This is the first time we run on the correct
17863 	 * queue after tcp_accept. So fix all the q parameters
17864 	 * here.
17865 	 */
17866 	/* Allocate room for SACK options if needed. */
17867 	stropt->so_flags |= SO_WROFF;
17868 	if (tcp->tcp_fused) {
17869 		size_t sth_hiwat;
17870 
17871 		ASSERT(tcp->tcp_loopback);
17872 		/*
17873 		 * For fused tcp loopback, set the stream head's write
17874 		 * offset value to zero since we won't be needing any room
17875 		 * for TCP/IP headers.  This would also improve performance
17876 		 * since it would reduce the amount of work done by kmem.
17877 		 * Non-fused tcp loopback case is handled separately below.
17878 		 */
17879 		stropt->so_wroff = 0;
17880 
17881 		/*
17882 		 * Override q_hiwat and set it to be twice that of the
17883 		 * previous value; this is to simulate non-fusion case.
17884 		 */
17885 		sth_hiwat = q->q_hiwat << 1;
17886 		if (sth_hiwat > tcp_max_buf)
17887 			sth_hiwat = tcp_max_buf;
17888 
17889 		stropt->so_hiwat = MAX(sth_hiwat, tcp_sth_rcv_hiwat);
17890 	} else if (tcp->tcp_snd_sack_ok) {
17891 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17892 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17893 	} else {
17894 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17895 		    tcp_wroff_xtra);
17896 	}
17897 
17898 	/*
17899 	 * If loopback, set COPYCACHED option to make sure NOT to use
17900 	 * non-temporal access.
17901 	 */
17902 	if (tcp->tcp_loopback) {
17903 		stropt->so_flags |= SO_COPYOPT;
17904 		stropt->so_copyopt = COPYCACHED;
17905 	}
17906 
17907 	/* Send the options up */
17908 	putnext(q, stropt_mp);
17909 
17910 	/*
17911 	 * Pass up any data and/or a fin that has been received.
17912 	 *
17913 	 * Adjust receive window in case it had decreased
17914 	 * (because there is data <=> tcp_rcv_list != NULL)
17915 	 * while the connection was detached. Note that
17916 	 * in case the eager was flow-controlled, w/o this
17917 	 * code, the rwnd may never open up again!
17918 	 */
17919 	if (tcp->tcp_rcv_list != NULL) {
17920 		/* We drain directly in case of fused tcp loopback */
17921 		if (!tcp->tcp_fused && canputnext(q)) {
17922 			tcp->tcp_rwnd = q->q_hiwat;
17923 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17924 			    << tcp->tcp_rcv_ws;
17925 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17926 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17927 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17928 				tcp_xmit_ctl(NULL,
17929 				    tcp, (tcp->tcp_swnd == 0) ?
17930 				    tcp->tcp_suna : tcp->tcp_snxt,
17931 				    tcp->tcp_rnxt, TH_ACK);
17932 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17933 			}
17934 
17935 		}
17936 		(void) tcp_rcv_drain(q, tcp);
17937 
17938 		/*
17939 		 * For fused tcp loopback, back-enable peer endpoint
17940 		 * if it's currently flow-controlled.
17941 		 */
17942 		if (tcp->tcp_fused &&
17943 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17944 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17945 
17946 			ASSERT(peer_tcp != NULL);
17947 			ASSERT(peer_tcp->tcp_fused);
17948 
17949 			tcp_clrqfull(peer_tcp);
17950 			peer_tcp->tcp_flow_stopped = B_FALSE;
17951 			TCP_STAT(tcp_fusion_backenabled);
17952 		}
17953 	}
17954 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17955 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17956 		mp = mi_tpi_ordrel_ind();
17957 		if (mp) {
17958 			tcp->tcp_ordrel_done = B_TRUE;
17959 			putnext(q, mp);
17960 			if (tcp->tcp_deferred_clean_death) {
17961 				/*
17962 				 * tcp_clean_death was deferred
17963 				 * for T_ORDREL_IND - do it now
17964 				 */
17965 				(void) tcp_clean_death(
17966 					tcp,
17967 					    tcp->tcp_client_errno, 21);
17968 				tcp->tcp_deferred_clean_death =
17969 				    B_FALSE;
17970 			}
17971 		} else {
17972 			/*
17973 			 * Run the orderly release in the
17974 			 * service routine.
17975 			 */
17976 			qenable(q);
17977 		}
17978 	}
17979 	if (tcp->tcp_hard_binding) {
17980 		tcp->tcp_hard_binding = B_FALSE;
17981 		tcp->tcp_hard_bound = B_TRUE;
17982 	}
17983 	tcp->tcp_detached = B_FALSE;
17984 
17985 	if (tcp->tcp_ka_enabled) {
17986 		tcp->tcp_ka_last_intrvl = 0;
17987 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17988 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17989 	}
17990 
17991 	/*
17992 	 * At this point, eager is fully established and will
17993 	 * have the following references -
17994 	 *
17995 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17996 	 * 1 reference for the squeue which will be dropped by the squeue as
17997 	 *	soon as this function returns.
17998 	 * There will be 1 additonal reference for being in classifier
17999 	 *	hash list provided something bad hasn't happened.
18000 	 */
18001 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18002 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18003 }
18004 
18005 /*
18006  * The function called through squeue to get behind listener's perimeter to
18007  * send a deffered conn_ind.
18008  */
18009 /* ARGSUSED */
18010 void
18011 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18012 {
18013 	conn_t	*connp = (conn_t *)arg;
18014 	tcp_t *listener = connp->conn_tcp;
18015 
18016 	if (listener->tcp_state == TCPS_CLOSED ||
18017 	    TCP_IS_DETACHED(listener)) {
18018 		/*
18019 		 * If listener has closed, it would have caused a
18020 		 * a cleanup/blowoff to happen for the eager.
18021 		 */
18022 		tcp_t *tcp;
18023 		struct T_conn_ind	*conn_ind;
18024 
18025 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18026 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18027 		    conn_ind->OPT_length);
18028 		/*
18029 		 * We need to drop the ref on eager that was put
18030 		 * tcp_rput_data() before trying to send the conn_ind
18031 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18032 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18033 		 * listener is closed so we drop the ref.
18034 		 */
18035 		CONN_DEC_REF(tcp->tcp_connp);
18036 		freemsg(mp);
18037 		return;
18038 	}
18039 	putnext(listener->tcp_rq, mp);
18040 }
18041 
18042 
18043 /*
18044  * This is the STREAMS entry point for T_CONN_RES coming down on
18045  * Acceptor STREAM when  sockfs listener does accept processing.
18046  * Read the block comment on top pf tcp_conn_request().
18047  */
18048 void
18049 tcp_wput_accept(queue_t *q, mblk_t *mp)
18050 {
18051 	queue_t *rq = RD(q);
18052 	struct T_conn_res *conn_res;
18053 	tcp_t *eager;
18054 	tcp_t *listener;
18055 	struct T_ok_ack *ok;
18056 	t_scalar_t PRIM_type;
18057 	mblk_t *opt_mp;
18058 	conn_t *econnp;
18059 
18060 	ASSERT(DB_TYPE(mp) == M_PROTO);
18061 
18062 	conn_res = (struct T_conn_res *)mp->b_rptr;
18063 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18064 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18065 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18066 		if (mp != NULL)
18067 			putnext(rq, mp);
18068 		return;
18069 	}
18070 	switch (conn_res->PRIM_type) {
18071 	case O_T_CONN_RES:
18072 	case T_CONN_RES:
18073 		/*
18074 		 * We pass up an err ack if allocb fails. This will
18075 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18076 		 * tcp_eager_blowoff to be called. sockfs will then call
18077 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18078 		 * we need to do the allocb up here because we have to
18079 		 * make sure rq->q_qinfo->qi_qclose still points to the
18080 		 * correct function (tcpclose_accept) in case allocb
18081 		 * fails.
18082 		 */
18083 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18084 		if (opt_mp == NULL) {
18085 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18086 			if (mp != NULL)
18087 				putnext(rq, mp);
18088 			return;
18089 		}
18090 
18091 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18092 		    &eager, conn_res->OPT_length);
18093 		PRIM_type = conn_res->PRIM_type;
18094 		mp->b_datap->db_type = M_PCPROTO;
18095 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18096 		ok = (struct T_ok_ack *)mp->b_rptr;
18097 		ok->PRIM_type = T_OK_ACK;
18098 		ok->CORRECT_prim = PRIM_type;
18099 		econnp = eager->tcp_connp;
18100 		econnp->conn_dev = (dev_t)q->q_ptr;
18101 		eager->tcp_rq = rq;
18102 		eager->tcp_wq = q;
18103 		rq->q_ptr = econnp;
18104 		rq->q_qinfo = &tcp_rinit;
18105 		q->q_ptr = econnp;
18106 		q->q_qinfo = &tcp_winit;
18107 		listener = eager->tcp_listener;
18108 		eager->tcp_issocket = B_TRUE;
18109 		eager->tcp_cred = econnp->conn_cred =
18110 		    listener->tcp_connp->conn_cred;
18111 		crhold(econnp->conn_cred);
18112 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18113 
18114 		/* Put the ref for IP */
18115 		CONN_INC_REF(econnp);
18116 
18117 		/*
18118 		 * We should have minimum of 3 references on the conn
18119 		 * at this point. One each for TCP and IP and one for
18120 		 * the T_conn_ind that was sent up when the 3-way handshake
18121 		 * completed. In the normal case we would also have another
18122 		 * reference (making a total of 4) for the conn being in the
18123 		 * classifier hash list. However the eager could have received
18124 		 * an RST subsequently and tcp_closei_local could have removed
18125 		 * the eager from the classifier hash list, hence we can't
18126 		 * assert that reference.
18127 		 */
18128 		ASSERT(econnp->conn_ref >= 3);
18129 
18130 		/*
18131 		 * Send the new local address also up to sockfs. There
18132 		 * should already be enough space in the mp that came
18133 		 * down from soaccept().
18134 		 */
18135 		if (eager->tcp_family == AF_INET) {
18136 			sin_t *sin;
18137 
18138 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18139 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18140 			sin = (sin_t *)mp->b_wptr;
18141 			mp->b_wptr += sizeof (sin_t);
18142 			sin->sin_family = AF_INET;
18143 			sin->sin_port = eager->tcp_lport;
18144 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18145 		} else {
18146 			sin6_t *sin6;
18147 
18148 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18149 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18150 			sin6 = (sin6_t *)mp->b_wptr;
18151 			mp->b_wptr += sizeof (sin6_t);
18152 			sin6->sin6_family = AF_INET6;
18153 			sin6->sin6_port = eager->tcp_lport;
18154 			if (eager->tcp_ipversion == IPV4_VERSION) {
18155 				sin6->sin6_flowinfo = 0;
18156 				IN6_IPADDR_TO_V4MAPPED(
18157 					eager->tcp_ipha->ipha_src,
18158 					    &sin6->sin6_addr);
18159 			} else {
18160 				ASSERT(eager->tcp_ip6h != NULL);
18161 				sin6->sin6_flowinfo =
18162 				    eager->tcp_ip6h->ip6_vcf &
18163 				    ~IPV6_VERS_AND_FLOW_MASK;
18164 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18165 			}
18166 			sin6->sin6_scope_id = 0;
18167 			sin6->__sin6_src_id = 0;
18168 		}
18169 
18170 		putnext(rq, mp);
18171 
18172 		opt_mp->b_datap->db_type = M_SETOPTS;
18173 		opt_mp->b_wptr += sizeof (struct stroptions);
18174 
18175 		/*
18176 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18177 		 * from listener to acceptor. The message is chained on the
18178 		 * bind_mp which tcp_rput_other will send down to IP.
18179 		 */
18180 		if (listener->tcp_bound_if != 0) {
18181 			/* allocate optmgmt req */
18182 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18183 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18184 			    sizeof (int));
18185 			if (mp != NULL)
18186 				linkb(opt_mp, mp);
18187 		}
18188 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18189 			uint_t on = 1;
18190 
18191 			/* allocate optmgmt req */
18192 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18193 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18194 			if (mp != NULL)
18195 				linkb(opt_mp, mp);
18196 		}
18197 
18198 
18199 		mutex_enter(&listener->tcp_eager_lock);
18200 
18201 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18202 
18203 			tcp_t *tail;
18204 			tcp_t *tcp;
18205 			mblk_t *mp1;
18206 
18207 			tcp = listener->tcp_eager_prev_q0;
18208 			/*
18209 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18210 			 * deferred T_conn_ind queue. We need to get to the head
18211 			 * of the queue in order to send up T_conn_ind the same
18212 			 * order as how the 3WHS is completed.
18213 			 */
18214 			while (tcp != listener) {
18215 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
18216 					break;
18217 				else
18218 					tcp = tcp->tcp_eager_prev_q0;
18219 			}
18220 			ASSERT(tcp != listener);
18221 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18222 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18223 			/* Move from q0 to q */
18224 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18225 			listener->tcp_conn_req_cnt_q0--;
18226 			listener->tcp_conn_req_cnt_q++;
18227 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18228 			    tcp->tcp_eager_prev_q0;
18229 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18230 			    tcp->tcp_eager_next_q0;
18231 			tcp->tcp_eager_prev_q0 = NULL;
18232 			tcp->tcp_eager_next_q0 = NULL;
18233 			tcp->tcp_conn_def_q0 = B_FALSE;
18234 
18235 			/*
18236 			 * Insert at end of the queue because sockfs sends
18237 			 * down T_CONN_RES in chronological order. Leaving
18238 			 * the older conn indications at front of the queue
18239 			 * helps reducing search time.
18240 			 */
18241 			tail = listener->tcp_eager_last_q;
18242 			if (tail != NULL) {
18243 				tail->tcp_eager_next_q = tcp;
18244 			} else {
18245 				listener->tcp_eager_next_q = tcp;
18246 			}
18247 			listener->tcp_eager_last_q = tcp;
18248 			tcp->tcp_eager_next_q = NULL;
18249 
18250 			/* Need to get inside the listener perimeter */
18251 			CONN_INC_REF(listener->tcp_connp);
18252 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18253 			    tcp_send_pending, listener->tcp_connp,
18254 			    SQTAG_TCP_SEND_PENDING);
18255 		}
18256 		tcp_eager_unlink(eager);
18257 		mutex_exit(&listener->tcp_eager_lock);
18258 
18259 		/*
18260 		 * At this point, the eager is detached from the listener
18261 		 * but we still have an extra refs on eager (apart from the
18262 		 * usual tcp references). The ref was placed in tcp_rput_data
18263 		 * before sending the conn_ind in tcp_send_conn_ind.
18264 		 * The ref will be dropped in tcp_accept_finish().
18265 		 */
18266 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18267 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18268 		return;
18269 	default:
18270 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18271 		if (mp != NULL)
18272 			putnext(rq, mp);
18273 		return;
18274 	}
18275 }
18276 
18277 static void
18278 tcp_wput(queue_t *q, mblk_t *mp)
18279 {
18280 	conn_t	*connp = Q_TO_CONN(q);
18281 	tcp_t	*tcp;
18282 	void (*output_proc)();
18283 	t_scalar_t type;
18284 	uchar_t *rptr;
18285 	struct iocblk	*iocp;
18286 
18287 	ASSERT(connp->conn_ref >= 2);
18288 
18289 	switch (DB_TYPE(mp)) {
18290 	case M_DATA:
18291 		CONN_INC_REF(connp);
18292 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18293 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18294 		return;
18295 	case M_PROTO:
18296 	case M_PCPROTO:
18297 		/*
18298 		 * if it is a snmp message, don't get behind the squeue
18299 		 */
18300 		tcp = connp->conn_tcp;
18301 		rptr = mp->b_rptr;
18302 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18303 			type = ((union T_primitives *)rptr)->type;
18304 		} else {
18305 			if (tcp->tcp_debug) {
18306 				(void) strlog(TCP_MODULE_ID, 0, 1,
18307 				    SL_ERROR|SL_TRACE,
18308 				    "tcp_wput_proto, dropping one...");
18309 			}
18310 			freemsg(mp);
18311 			return;
18312 		}
18313 		if (type == T_SVR4_OPTMGMT_REQ) {
18314 			cred_t	*cr = DB_CREDDEF(mp,
18315 			    tcp->tcp_cred);
18316 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
18317 			    cr)) {
18318 				/*
18319 				 * This was a SNMP request
18320 				 */
18321 				return;
18322 			} else {
18323 				output_proc = tcp_wput_proto;
18324 			}
18325 		} else {
18326 			output_proc = tcp_wput_proto;
18327 		}
18328 		break;
18329 	case M_IOCTL:
18330 		/*
18331 		 * Most ioctls can be processed right away without going via
18332 		 * squeues - process them right here. Those that do require
18333 		 * squeue (currently TCP_IOC_DEFAULT_Q and SIOCPOPSOCKFS)
18334 		 * are processed by tcp_wput_ioctl().
18335 		 */
18336 		iocp = (struct iocblk *)mp->b_rptr;
18337 		tcp = connp->conn_tcp;
18338 
18339 		switch (iocp->ioc_cmd) {
18340 		case TCP_IOC_ABORT_CONN:
18341 			tcp_ioctl_abort_conn(q, mp);
18342 			return;
18343 		case TI_GETPEERNAME:
18344 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
18345 				iocp->ioc_error = ENOTCONN;
18346 				iocp->ioc_count = 0;
18347 				mp->b_datap->db_type = M_IOCACK;
18348 				qreply(q, mp);
18349 				return;
18350 			}
18351 			/* FALLTHRU */
18352 		case TI_GETMYNAME:
18353 			mi_copyin(q, mp, NULL,
18354 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18355 			return;
18356 		case ND_SET:
18357 			/* nd_getset does the necessary checks */
18358 		case ND_GET:
18359 			if (!nd_getset(q, tcp_g_nd, mp)) {
18360 				CALL_IP_WPUT(connp, q, mp);
18361 				return;
18362 			}
18363 			qreply(q, mp);
18364 			return;
18365 		case TCP_IOC_DEFAULT_Q:
18366 			/*
18367 			 * Wants to be the default wq. Check the credentials
18368 			 * first, the rest is executed via squeue.
18369 			 */
18370 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
18371 				iocp->ioc_error = EPERM;
18372 				iocp->ioc_count = 0;
18373 				mp->b_datap->db_type = M_IOCACK;
18374 				qreply(q, mp);
18375 				return;
18376 			}
18377 			output_proc = tcp_wput_ioctl;
18378 			break;
18379 		default:
18380 			output_proc = tcp_wput_ioctl;
18381 			break;
18382 		}
18383 		break;
18384 	default:
18385 		output_proc = tcp_wput_nondata;
18386 		break;
18387 	}
18388 
18389 	CONN_INC_REF(connp);
18390 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18391 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18392 }
18393 
18394 /*
18395  * Initial STREAMS write side put() procedure for sockets. It tries to
18396  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18397  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18398  * are handled by tcp_wput() as usual.
18399  *
18400  * All further messages will also be handled by tcp_wput() because we cannot
18401  * be sure that the above short cut is safe later.
18402  */
18403 static void
18404 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18405 {
18406 	conn_t			*connp = Q_TO_CONN(wq);
18407 	tcp_t			*tcp = connp->conn_tcp;
18408 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18409 
18410 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18411 	wq->q_qinfo = &tcp_winit;
18412 
18413 	ASSERT(IS_TCP_CONN(connp));
18414 	ASSERT(TCP_IS_SOCKET(tcp));
18415 
18416 	if (DB_TYPE(mp) == M_PCPROTO &&
18417 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18418 	    car->PRIM_type == T_CAPABILITY_REQ) {
18419 		tcp_capability_req(tcp, mp);
18420 		return;
18421 	}
18422 
18423 	tcp_wput(wq, mp);
18424 }
18425 
18426 static boolean_t
18427 tcp_zcopy_check(tcp_t *tcp)
18428 {
18429 	conn_t	*connp = tcp->tcp_connp;
18430 	ire_t	*ire;
18431 	boolean_t	zc_enabled = B_FALSE;
18432 
18433 	if (do_tcpzcopy == 2)
18434 		zc_enabled = B_TRUE;
18435 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18436 	    IPCL_IS_CONNECTED(connp) &&
18437 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18438 	    connp->conn_dontroute == 0 &&
18439 	    connp->conn_xmit_if_ill == NULL &&
18440 	    connp->conn_nofailover_ill == NULL &&
18441 	    do_tcpzcopy == 1) {
18442 		/*
18443 		 * the checks above  closely resemble the fast path checks
18444 		 * in tcp_send_data().
18445 		 */
18446 		mutex_enter(&connp->conn_lock);
18447 		ire = connp->conn_ire_cache;
18448 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18449 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18450 			IRE_REFHOLD(ire);
18451 			if (ire->ire_stq != NULL) {
18452 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18453 
18454 				zc_enabled = ill && (ill->ill_capabilities &
18455 				    ILL_CAPAB_ZEROCOPY) &&
18456 				    (ill->ill_zerocopy_capab->
18457 				    ill_zerocopy_flags != 0);
18458 			}
18459 			IRE_REFRELE(ire);
18460 		}
18461 		mutex_exit(&connp->conn_lock);
18462 	}
18463 	tcp->tcp_snd_zcopy_on = zc_enabled;
18464 	if (!TCP_IS_DETACHED(tcp)) {
18465 		if (zc_enabled) {
18466 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18467 			TCP_STAT(tcp_zcopy_on);
18468 		} else {
18469 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18470 			TCP_STAT(tcp_zcopy_off);
18471 		}
18472 	}
18473 	return (zc_enabled);
18474 }
18475 
18476 static mblk_t *
18477 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18478 {
18479 	if (do_tcpzcopy == 2)
18480 		return (bp);
18481 	else if (tcp->tcp_snd_zcopy_on) {
18482 		tcp->tcp_snd_zcopy_on = B_FALSE;
18483 		if (!TCP_IS_DETACHED(tcp)) {
18484 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18485 			TCP_STAT(tcp_zcopy_disable);
18486 		}
18487 	}
18488 	return (tcp_zcopy_backoff(tcp, bp, 0));
18489 }
18490 
18491 /*
18492  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18493  * the original desballoca'ed segmapped mblk.
18494  */
18495 static mblk_t *
18496 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18497 {
18498 	mblk_t *head, *tail, *nbp;
18499 	if (IS_VMLOANED_MBLK(bp)) {
18500 		TCP_STAT(tcp_zcopy_backoff);
18501 		if ((head = copyb(bp)) == NULL) {
18502 			/* fail to backoff; leave it for the next backoff */
18503 			tcp->tcp_xmit_zc_clean = B_FALSE;
18504 			return (bp);
18505 		}
18506 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18507 			if (fix_xmitlist)
18508 				tcp_zcopy_notify(tcp);
18509 			else
18510 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18511 		}
18512 		nbp = bp->b_cont;
18513 		if (fix_xmitlist) {
18514 			head->b_prev = bp->b_prev;
18515 			head->b_next = bp->b_next;
18516 			if (tcp->tcp_xmit_tail == bp)
18517 				tcp->tcp_xmit_tail = head;
18518 		}
18519 		bp->b_next = NULL;
18520 		bp->b_prev = NULL;
18521 		freeb(bp);
18522 	} else {
18523 		head = bp;
18524 		nbp = bp->b_cont;
18525 	}
18526 	tail = head;
18527 	while (nbp) {
18528 		if (IS_VMLOANED_MBLK(nbp)) {
18529 			TCP_STAT(tcp_zcopy_backoff);
18530 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18531 				tcp->tcp_xmit_zc_clean = B_FALSE;
18532 				tail->b_cont = nbp;
18533 				return (head);
18534 			}
18535 			tail = tail->b_cont;
18536 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18537 				if (fix_xmitlist)
18538 					tcp_zcopy_notify(tcp);
18539 				else
18540 					tail->b_datap->db_struioflag |=
18541 					    STRUIO_ZCNOTIFY;
18542 			}
18543 			bp = nbp;
18544 			nbp = nbp->b_cont;
18545 			if (fix_xmitlist) {
18546 				tail->b_prev = bp->b_prev;
18547 				tail->b_next = bp->b_next;
18548 				if (tcp->tcp_xmit_tail == bp)
18549 					tcp->tcp_xmit_tail = tail;
18550 			}
18551 			bp->b_next = NULL;
18552 			bp->b_prev = NULL;
18553 			freeb(bp);
18554 		} else {
18555 			tail->b_cont = nbp;
18556 			tail = nbp;
18557 			nbp = nbp->b_cont;
18558 		}
18559 	}
18560 	if (fix_xmitlist) {
18561 		tcp->tcp_xmit_last = tail;
18562 		tcp->tcp_xmit_zc_clean = B_TRUE;
18563 	}
18564 	return (head);
18565 }
18566 
18567 static void
18568 tcp_zcopy_notify(tcp_t *tcp)
18569 {
18570 	struct stdata	*stp;
18571 
18572 	if (tcp->tcp_detached)
18573 		return;
18574 	stp = STREAM(tcp->tcp_rq);
18575 	mutex_enter(&stp->sd_lock);
18576 	stp->sd_flag |= STZCNOTIFY;
18577 	cv_broadcast(&stp->sd_zcopy_wait);
18578 	mutex_exit(&stp->sd_lock);
18579 }
18580 
18581 
18582 static void
18583 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18584 {
18585 	ipha_t		*ipha;
18586 	ipaddr_t	src;
18587 	ipaddr_t	dst;
18588 	uint32_t	cksum;
18589 	ire_t		*ire;
18590 	uint16_t	*up;
18591 	ill_t		*ill;
18592 	conn_t		*connp = tcp->tcp_connp;
18593 	uint32_t	hcksum_txflags = 0;
18594 	mblk_t		*ire_fp_mp;
18595 	uint_t		ire_fp_mp_len;
18596 	ill_poll_capab_t *ill_poll;
18597 
18598 	ASSERT(DB_TYPE(mp) == M_DATA);
18599 
18600 	ipha = (ipha_t *)mp->b_rptr;
18601 	src = ipha->ipha_src;
18602 	dst = ipha->ipha_dst;
18603 
18604 	/*
18605 	 * Drop off slow path for IPv6 and also if options are present.
18606 	 */
18607 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18608 	    !IPCL_IS_CONNECTED(connp) ||
18609 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18610 	    connp->conn_dontroute ||
18611 	    connp->conn_xmit_if_ill != NULL ||
18612 	    connp->conn_nofailover_ill != NULL ||
18613 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18614 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18615 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18616 		if (tcp->tcp_snd_zcopy_aware)
18617 			mp = tcp_zcopy_disable(tcp, mp);
18618 		TCP_STAT(tcp_ip_send);
18619 		CALL_IP_WPUT(connp, q, mp);
18620 		return;
18621 	}
18622 
18623 	mutex_enter(&connp->conn_lock);
18624 	ire = connp->conn_ire_cache;
18625 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18626 	if (ire != NULL && ire->ire_addr == dst &&
18627 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18628 		IRE_REFHOLD(ire);
18629 		mutex_exit(&connp->conn_lock);
18630 	} else {
18631 		boolean_t cached = B_FALSE;
18632 
18633 		/* force a recheck later on */
18634 		tcp->tcp_ire_ill_check_done = B_FALSE;
18635 
18636 		TCP_DBGSTAT(tcp_ire_null1);
18637 		connp->conn_ire_cache = NULL;
18638 		mutex_exit(&connp->conn_lock);
18639 		if (ire != NULL)
18640 			IRE_REFRELE_NOTR(ire);
18641 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
18642 		if (ire == NULL) {
18643 			if (tcp->tcp_snd_zcopy_aware)
18644 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18645 			TCP_STAT(tcp_ire_null);
18646 			CALL_IP_WPUT(connp, q, mp);
18647 			return;
18648 		}
18649 		IRE_REFHOLD_NOTR(ire);
18650 		/*
18651 		 * Since we are inside the squeue, there cannot be another
18652 		 * thread in TCP trying to set the conn_ire_cache now.  The
18653 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18654 		 * unplumb thread has not yet started cleaning up the conns.
18655 		 * Hence we don't need to grab the conn lock.
18656 		 */
18657 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18658 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18659 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18660 				connp->conn_ire_cache = ire;
18661 				cached = B_TRUE;
18662 			}
18663 			rw_exit(&ire->ire_bucket->irb_lock);
18664 		}
18665 
18666 		/*
18667 		 * We can continue to use the ire but since it was
18668 		 * not cached, we should drop the extra reference.
18669 		 */
18670 		if (!cached)
18671 			IRE_REFRELE_NOTR(ire);
18672 	}
18673 
18674 	if (ire->ire_flags & RTF_MULTIRT ||
18675 	    ire->ire_stq == NULL ||
18676 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18677 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18678 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18679 		if (tcp->tcp_snd_zcopy_aware)
18680 			mp = tcp_zcopy_disable(tcp, mp);
18681 		TCP_STAT(tcp_ip_ire_send);
18682 		IRE_REFRELE(ire);
18683 		CALL_IP_WPUT(connp, q, mp);
18684 		return;
18685 	}
18686 
18687 	ill = ire_to_ill(ire);
18688 	if (connp->conn_outgoing_ill != NULL) {
18689 		ill_t *conn_outgoing_ill = NULL;
18690 		/*
18691 		 * Choose a good ill in the group to send the packets on.
18692 		 */
18693 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18694 		ill = ire_to_ill(ire);
18695 	}
18696 	ASSERT(ill != NULL);
18697 
18698 	if (!tcp->tcp_ire_ill_check_done) {
18699 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18700 		tcp->tcp_ire_ill_check_done = B_TRUE;
18701 	}
18702 
18703 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18704 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18705 #ifndef _BIG_ENDIAN
18706 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18707 #endif
18708 
18709 	/*
18710 	 * Check to see if we need to re-enable MDT for this connection
18711 	 * because it was previously disabled due to changes in the ill;
18712 	 * note that by doing it here, this re-enabling only applies when
18713 	 * the packet is not dispatched through CALL_IP_WPUT().
18714 	 *
18715 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18716 	 * case, since that's how we ended up here.  For IPv6, we do the
18717 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18718 	 */
18719 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18720 		/*
18721 		 * Restore MDT for this connection, so that next time around
18722 		 * it is eligible to go through tcp_multisend() path again.
18723 		 */
18724 		TCP_STAT(tcp_mdt_conn_resumed1);
18725 		tcp->tcp_mdt = B_TRUE;
18726 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18727 		    "interface %s\n", (void *)connp, ill->ill_name));
18728 	}
18729 
18730 	if (tcp->tcp_snd_zcopy_aware) {
18731 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18732 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18733 			mp = tcp_zcopy_disable(tcp, mp);
18734 		/*
18735 		 * we shouldn't need to reset ipha as the mp containing
18736 		 * ipha should never be a zero-copy mp.
18737 		 */
18738 	}
18739 
18740 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) && dohwcksum) {
18741 		ASSERT(ill->ill_hcksum_capab != NULL);
18742 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18743 	}
18744 
18745 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18746 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18747 
18748 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18749 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18750 
18751 	/*
18752 	 * Underlying interface supports hardware checksum offload for
18753 	 * the tcp payload, along with M_DATA fast path; leave the payload
18754 	 * checksum for the hardware to calculate.
18755 	 *
18756 	 * N.B: We only need to set up checksum info on the first mblk.
18757 	 */
18758 	if (hcksum_txflags & HCKSUM_INET_FULL_V4) {
18759 		/*
18760 		 * Hardware calculates pseudo-header, header and payload
18761 		 * checksums, so clear checksum field in TCP header.
18762 		 */
18763 		*up = 0;
18764 		mp->b_datap->db_struioun.cksum.flags |= HCK_FULLCKSUM;
18765 	} else if (hcksum_txflags & HCKSUM_INET_PARTIAL) {
18766 		uint32_t sum;
18767 		/*
18768 		 * Partial checksum offload has been enabled.  Fill the
18769 		 * checksum field in the TCP header with the pseudo-header
18770 		 * checksum value.
18771 		 */
18772 		sum = *up + cksum + IP_TCP_CSUM_COMP;
18773 		sum = (sum & 0xFFFF) + (sum >> 16);
18774 		*up = (sum & 0xFFFF) + (sum >> 16);
18775 		mp->b_datap->db_cksumstart = IP_SIMPLE_HDR_LENGTH;
18776 		mp->b_datap->db_cksumstuff = IP_SIMPLE_HDR_LENGTH + 16;
18777 		mp->b_datap->db_cksumend = ntohs(ipha->ipha_length);
18778 		mp->b_datap->db_struioun.cksum.flags |= HCK_PARTIALCKSUM;
18779 	} else {
18780 		/* software checksumming */
18781 		TCP_STAT(tcp_out_sw_cksum);
18782 		*up = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH,
18783 		    cksum + IP_TCP_CSUM_COMP);
18784 		mp->b_datap->db_struioun.cksum.flags = 0;
18785 	}
18786 
18787 	ipha->ipha_fragment_offset_and_flags |=
18788 	    (uint32_t)htons(ire->ire_frag_flag);
18789 
18790 	/*
18791 	 * Hardware supports IP header checksum offload; clear contents
18792 	 * of IP header checksum field.  Otherwise we calculate it.
18793 	 */
18794 	if (hcksum_txflags & HCKSUM_IPHDRCKSUM) {
18795 		ipha->ipha_hdr_checksum = 0;
18796 		mp->b_datap->db_struioun.cksum.flags |= HCK_IPV4_HDRCKSUM;
18797 	} else {
18798 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18799 		    ((uint16_t *)ipha)[4]);
18800 	}
18801 
18802 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18803 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18804 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18805 
18806 	UPDATE_OB_PKT_COUNT(ire);
18807 	ire->ire_last_used_time = lbolt;
18808 	BUMP_MIB(&ip_mib, ipOutRequests);
18809 
18810 	if (ill->ill_capabilities & ILL_CAPAB_POLL) {
18811 		ill_poll = ill->ill_poll_capab;
18812 		ASSERT(ill_poll != NULL);
18813 		ASSERT(ill_poll->ill_tx != NULL);
18814 		ASSERT(ill_poll->ill_tx_handle != NULL);
18815 
18816 		ill_poll->ill_tx(ill_poll->ill_tx_handle, mp);
18817 	} else {
18818 		putnext(ire->ire_stq, mp);
18819 	}
18820 	IRE_REFRELE(ire);
18821 }
18822 
18823 /*
18824  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18825  * if the receiver shrinks the window, i.e. moves the right window to the
18826  * left, the we should not send new data, but should retransmit normally the
18827  * old unacked data between suna and suna + swnd. We might has sent data
18828  * that is now outside the new window, pretend that we didn't send  it.
18829  */
18830 static void
18831 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18832 {
18833 	uint32_t	snxt = tcp->tcp_snxt;
18834 	mblk_t		*xmit_tail;
18835 	int32_t		offset;
18836 
18837 	ASSERT(shrunk_count > 0);
18838 
18839 	/* Pretend we didn't send the data outside the window */
18840 	snxt -= shrunk_count;
18841 
18842 	/* Get the mblk and the offset in it per the shrunk window */
18843 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18844 
18845 	ASSERT(xmit_tail != NULL);
18846 
18847 	/* Reset all the values per the now shrunk window */
18848 	tcp->tcp_snxt = snxt;
18849 	tcp->tcp_xmit_tail = xmit_tail;
18850 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18851 	    offset;
18852 	tcp->tcp_unsent += shrunk_count;
18853 
18854 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18855 		/*
18856 		 * Make sure the timer is running so that we will probe a zero
18857 		 * window.
18858 		 */
18859 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18860 }
18861 
18862 
18863 /*
18864  * The TCP normal data output path.
18865  * NOTE: the logic of the fast path is duplicated from this function.
18866  */
18867 static void
18868 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18869 {
18870 	int		len;
18871 	mblk_t		*local_time;
18872 	mblk_t		*mp1;
18873 	uint32_t	snxt;
18874 	int		tail_unsent;
18875 	int		tcpstate;
18876 	int		usable = 0;
18877 	mblk_t		*xmit_tail;
18878 	queue_t		*q = tcp->tcp_wq;
18879 	int32_t		mss;
18880 	int32_t		num_sack_blk = 0;
18881 	int32_t		tcp_hdr_len;
18882 	int32_t		tcp_tcp_hdr_len;
18883 	int		mdt_thres;
18884 	int		rc;
18885 
18886 	tcpstate = tcp->tcp_state;
18887 	if (mp == NULL) {
18888 		/*
18889 		 * tcp_wput_data() with NULL mp should only be called when
18890 		 * there is unsent data.
18891 		 */
18892 		ASSERT(tcp->tcp_unsent > 0);
18893 		/* Really tacky... but we need this for detached closes. */
18894 		len = tcp->tcp_unsent;
18895 		goto data_null;
18896 	}
18897 
18898 #if CCS_STATS
18899 	wrw_stats.tot.count++;
18900 	wrw_stats.tot.bytes += msgdsize(mp);
18901 #endif
18902 	ASSERT(mp->b_datap->db_type == M_DATA);
18903 	/*
18904 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18905 	 * or before a connection attempt has begun.
18906 	 */
18907 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18908 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18909 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18910 #ifdef DEBUG
18911 			cmn_err(CE_WARN,
18912 			    "tcp_wput_data: data after ordrel, %s",
18913 			    tcp_display(tcp, NULL,
18914 			    DISP_ADDR_AND_PORT));
18915 #else
18916 			if (tcp->tcp_debug) {
18917 				(void) strlog(TCP_MODULE_ID, 0, 1,
18918 				    SL_TRACE|SL_ERROR,
18919 				    "tcp_wput_data: data after ordrel, %s\n",
18920 				    tcp_display(tcp, NULL,
18921 				    DISP_ADDR_AND_PORT));
18922 			}
18923 #endif /* DEBUG */
18924 		}
18925 		if (tcp->tcp_snd_zcopy_aware &&
18926 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18927 			tcp_zcopy_notify(tcp);
18928 		freemsg(mp);
18929 		return;
18930 	}
18931 
18932 	/* Strip empties */
18933 	for (;;) {
18934 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18935 		    (uintptr_t)INT_MAX);
18936 		len = (int)(mp->b_wptr - mp->b_rptr);
18937 		if (len > 0)
18938 			break;
18939 		mp1 = mp;
18940 		mp = mp->b_cont;
18941 		freeb(mp1);
18942 		if (!mp) {
18943 			return;
18944 		}
18945 	}
18946 
18947 	/* If we are the first on the list ... */
18948 	if (tcp->tcp_xmit_head == NULL) {
18949 		tcp->tcp_xmit_head = mp;
18950 		tcp->tcp_xmit_tail = mp;
18951 		tcp->tcp_xmit_tail_unsent = len;
18952 	} else {
18953 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18954 		struct datab *dp;
18955 
18956 		mp1 = tcp->tcp_xmit_last;
18957 		if (len < tcp_tx_pull_len &&
18958 		    (dp = mp1->b_datap)->db_ref == 1 &&
18959 		    dp->db_lim - mp1->b_wptr >= len) {
18960 			ASSERT(len > 0);
18961 			ASSERT(!mp1->b_cont);
18962 			if (len == 1) {
18963 				*mp1->b_wptr++ = *mp->b_rptr;
18964 			} else {
18965 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18966 				mp1->b_wptr += len;
18967 			}
18968 			if (mp1 == tcp->tcp_xmit_tail)
18969 				tcp->tcp_xmit_tail_unsent += len;
18970 			mp1->b_cont = mp->b_cont;
18971 			if (tcp->tcp_snd_zcopy_aware &&
18972 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18973 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18974 			freeb(mp);
18975 			mp = mp1;
18976 		} else {
18977 			tcp->tcp_xmit_last->b_cont = mp;
18978 		}
18979 		len += tcp->tcp_unsent;
18980 	}
18981 
18982 	/* Tack on however many more positive length mblks we have */
18983 	if ((mp1 = mp->b_cont) != NULL) {
18984 		do {
18985 			int tlen;
18986 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18987 			    (uintptr_t)INT_MAX);
18988 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18989 			if (tlen <= 0) {
18990 				mp->b_cont = mp1->b_cont;
18991 				freeb(mp1);
18992 			} else {
18993 				len += tlen;
18994 				mp = mp1;
18995 			}
18996 		} while ((mp1 = mp->b_cont) != NULL);
18997 	}
18998 	tcp->tcp_xmit_last = mp;
18999 	tcp->tcp_unsent = len;
19000 
19001 	if (urgent)
19002 		usable = 1;
19003 
19004 data_null:
19005 	snxt = tcp->tcp_snxt;
19006 	xmit_tail = tcp->tcp_xmit_tail;
19007 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19008 
19009 	/*
19010 	 * Note that tcp_mss has been adjusted to take into account the
19011 	 * timestamp option if applicable.  Because SACK options do not
19012 	 * appear in every TCP segments and they are of variable lengths,
19013 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19014 	 * the actual segment length when we need to send a segment which
19015 	 * includes SACK options.
19016 	 */
19017 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19018 		int32_t	opt_len;
19019 
19020 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19021 		    tcp->tcp_num_sack_blk);
19022 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19023 		    2 + TCPOPT_HEADER_LEN;
19024 		mss = tcp->tcp_mss - opt_len;
19025 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19026 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19027 	} else {
19028 		mss = tcp->tcp_mss;
19029 		tcp_hdr_len = tcp->tcp_hdr_len;
19030 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19031 	}
19032 
19033 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19034 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19035 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
19036 	}
19037 	if (tcpstate == TCPS_SYN_RCVD) {
19038 		/*
19039 		 * The three-way connection establishment handshake is not
19040 		 * complete yet. We want to queue the data for transmission
19041 		 * after entering ESTABLISHED state (RFC793). A jump to
19042 		 * "done" label effectively leaves data on the queue.
19043 		 */
19044 		goto done;
19045 	} else {
19046 		int usable_r = tcp->tcp_swnd;
19047 
19048 		/*
19049 		 * In the special case when cwnd is zero, which can only
19050 		 * happen if the connection is ECN capable, return now.
19051 		 * New segments is sent using tcp_timer().  The timer
19052 		 * is set in tcp_rput_data().
19053 		 */
19054 		if (tcp->tcp_cwnd == 0) {
19055 			/*
19056 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19057 			 * finished.
19058 			 */
19059 			ASSERT(tcp->tcp_ecn_ok ||
19060 			    tcp->tcp_state < TCPS_ESTABLISHED);
19061 			return;
19062 		}
19063 
19064 		/* NOTE: trouble if xmitting while SYN not acked? */
19065 		usable_r -= snxt;
19066 		usable_r += tcp->tcp_suna;
19067 
19068 		/*
19069 		 * Check if the receiver has shrunk the window.  If
19070 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19071 		 * cannot be set as there is unsent data, so FIN cannot
19072 		 * be sent out.  Otherwise, we need to take into account
19073 		 * of FIN as it consumes an "invisible" sequence number.
19074 		 */
19075 		ASSERT(tcp->tcp_fin_sent == 0);
19076 		if (usable_r < 0) {
19077 			/*
19078 			 * The receiver has shrunk the window and we have sent
19079 			 * -usable_r date beyond the window, re-adjust.
19080 			 *
19081 			 * If TCP window scaling is enabled, there can be
19082 			 * round down error as the advertised receive window
19083 			 * is actually right shifted n bits.  This means that
19084 			 * the lower n bits info is wiped out.  It will look
19085 			 * like the window is shrunk.  Do a check here to
19086 			 * see if the shrunk amount is actually within the
19087 			 * error in window calculation.  If it is, just
19088 			 * return.  Note that this check is inside the
19089 			 * shrunk window check.  This makes sure that even
19090 			 * though tcp_process_shrunk_swnd() is not called,
19091 			 * we will stop further processing.
19092 			 */
19093 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19094 				tcp_process_shrunk_swnd(tcp, -usable_r);
19095 			}
19096 			return;
19097 		}
19098 
19099 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19100 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19101 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19102 
19103 		/* usable = MIN(usable, unsent) */
19104 		if (usable_r > len)
19105 			usable_r = len;
19106 
19107 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19108 		if (usable_r > 0) {
19109 			usable = usable_r;
19110 		} else {
19111 			/* Bypass all other unnecessary processing. */
19112 			goto done;
19113 		}
19114 	}
19115 
19116 	local_time = (mblk_t *)lbolt;
19117 
19118 	/*
19119 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19120 	 * BSD.  This is more in line with the true intent of Nagle.
19121 	 *
19122 	 * The conditions are:
19123 	 * 1. The amount of unsent data (or amount of data which can be
19124 	 *    sent, whichever is smaller) is less than Nagle limit.
19125 	 * 2. The last sent size is also less than Nagle limit.
19126 	 * 3. There is unack'ed data.
19127 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19128 	 *    Nagle algorithm.  This reduces the probability that urgent
19129 	 *    bytes get "merged" together.
19130 	 * 5. The app has not closed the connection.  This eliminates the
19131 	 *    wait time of the receiving side waiting for the last piece of
19132 	 *    (small) data.
19133 	 *
19134 	 * If all are satisified, exit without sending anything.  Note
19135 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19136 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19137 	 * 4095).
19138 	 */
19139 	if (usable < (int)tcp->tcp_naglim &&
19140 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19141 	    snxt != tcp->tcp_suna &&
19142 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19143 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19144 		goto done;
19145 	}
19146 
19147 	if (tcp->tcp_cork) {
19148 		/*
19149 		 * if the tcp->tcp_cork option is set, then we have to force
19150 		 * TCP not to send partial segment (smaller than MSS bytes).
19151 		 * We are calculating the usable now based on full mss and
19152 		 * will save the rest of remaining data for later.
19153 		 */
19154 		if (usable < mss)
19155 			goto done;
19156 		usable = (usable / mss) * mss;
19157 	}
19158 
19159 	/* Update the latest receive window size in TCP header. */
19160 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19161 	    tcp->tcp_tcph->th_win);
19162 
19163 	/*
19164 	 * Determine if it's worthwhile to attempt MDT, based on:
19165 	 *
19166 	 * 1. Simple TCP/IP{v4,v6} (no options).
19167 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19168 	 * 3. If the TCP connection is in ESTABLISHED state.
19169 	 * 4. The TCP is not detached.
19170 	 *
19171 	 * If any of the above conditions have changed during the
19172 	 * connection, stop using MDT and restore the stream head
19173 	 * parameters accordingly.
19174 	 */
19175 	if (tcp->tcp_mdt &&
19176 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19177 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19178 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19179 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19180 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19181 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
19182 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19183 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
19184 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19185 		tcp->tcp_mdt = B_FALSE;
19186 
19187 		/* Anything other than detached is considered pathological */
19188 		if (!TCP_IS_DETACHED(tcp)) {
19189 			TCP_STAT(tcp_mdt_conn_halted1);
19190 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19191 		}
19192 	}
19193 
19194 	/* Use MDT if sendable amount is greater than the threshold */
19195 	if (tcp->tcp_mdt &&
19196 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19197 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19198 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19199 	    (tcp->tcp_valid_bits == 0 ||
19200 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19201 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19202 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19203 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19204 		    local_time, mdt_thres);
19205 	} else {
19206 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19207 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19208 		    local_time, INT_MAX);
19209 	}
19210 
19211 	/* Pretend that all we were trying to send really got sent */
19212 	if (rc < 0 && tail_unsent < 0) {
19213 		do {
19214 			xmit_tail = xmit_tail->b_cont;
19215 			xmit_tail->b_prev = local_time;
19216 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19217 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19218 			tail_unsent += (int)(xmit_tail->b_wptr -
19219 			    xmit_tail->b_rptr);
19220 		} while (tail_unsent < 0);
19221 	}
19222 done:;
19223 	tcp->tcp_xmit_tail = xmit_tail;
19224 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19225 	len = tcp->tcp_snxt - snxt;
19226 	if (len) {
19227 		/*
19228 		 * If new data was sent, need to update the notsack
19229 		 * list, which is, afterall, data blocks that have
19230 		 * not been sack'ed by the receiver.  New data is
19231 		 * not sack'ed.
19232 		 */
19233 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19234 			/* len is a negative value. */
19235 			tcp->tcp_pipe -= len;
19236 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19237 			    tcp->tcp_snxt, snxt,
19238 			    &(tcp->tcp_num_notsack_blk),
19239 			    &(tcp->tcp_cnt_notsack_list));
19240 		}
19241 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19242 		tcp->tcp_rack = tcp->tcp_rnxt;
19243 		tcp->tcp_rack_cnt = 0;
19244 		if ((snxt + len) == tcp->tcp_suna) {
19245 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19246 		}
19247 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19248 		/*
19249 		 * Didn't send anything. Make sure the timer is running
19250 		 * so that we will probe a zero window.
19251 		 */
19252 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19253 	}
19254 	/* Note that len is the amount we just sent but with a negative sign */
19255 	len += tcp->tcp_unsent;
19256 	tcp->tcp_unsent = len;
19257 	if (tcp->tcp_flow_stopped) {
19258 		if (len <= tcp->tcp_xmit_lowater) {
19259 			tcp->tcp_flow_stopped = B_FALSE;
19260 			tcp_clrqfull(tcp);
19261 		}
19262 	} else if (len >= tcp->tcp_xmit_hiwater) {
19263 		tcp->tcp_flow_stopped = B_TRUE;
19264 		tcp_setqfull(tcp);
19265 	}
19266 }
19267 
19268 /*
19269  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19270  * outgoing TCP header with the template header, as well as other
19271  * options such as time-stamp, ECN and/or SACK.
19272  */
19273 static void
19274 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19275 {
19276 	tcph_t *tcp_tmpl, *tcp_h;
19277 	uint32_t *dst, *src;
19278 	int hdrlen;
19279 
19280 	ASSERT(OK_32PTR(rptr));
19281 
19282 	/* Template header */
19283 	tcp_tmpl = tcp->tcp_tcph;
19284 
19285 	/* Header of outgoing packet */
19286 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19287 
19288 	/* dst and src are opaque 32-bit fields, used for copying */
19289 	dst = (uint32_t *)rptr;
19290 	src = (uint32_t *)tcp->tcp_iphc;
19291 	hdrlen = tcp->tcp_hdr_len;
19292 
19293 	/* Fill time-stamp option if needed */
19294 	if (tcp->tcp_snd_ts_ok) {
19295 		U32_TO_BE32((uint32_t)now,
19296 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19297 		U32_TO_BE32(tcp->tcp_ts_recent,
19298 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19299 	} else {
19300 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19301 	}
19302 
19303 	/*
19304 	 * Copy the template header; is this really more efficient than
19305 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19306 	 * but perhaps not for other scenarios.
19307 	 */
19308 	dst[0] = src[0];
19309 	dst[1] = src[1];
19310 	dst[2] = src[2];
19311 	dst[3] = src[3];
19312 	dst[4] = src[4];
19313 	dst[5] = src[5];
19314 	dst[6] = src[6];
19315 	dst[7] = src[7];
19316 	dst[8] = src[8];
19317 	dst[9] = src[9];
19318 	if (hdrlen -= 40) {
19319 		hdrlen >>= 2;
19320 		dst += 10;
19321 		src += 10;
19322 		do {
19323 			*dst++ = *src++;
19324 		} while (--hdrlen);
19325 	}
19326 
19327 	/*
19328 	 * Set the ECN info in the TCP header if it is not a zero
19329 	 * window probe.  Zero window probe is only sent in
19330 	 * tcp_wput_data() and tcp_timer().
19331 	 */
19332 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19333 		SET_ECT(tcp, rptr);
19334 
19335 		if (tcp->tcp_ecn_echo_on)
19336 			tcp_h->th_flags[0] |= TH_ECE;
19337 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19338 			tcp_h->th_flags[0] |= TH_CWR;
19339 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19340 		}
19341 	}
19342 
19343 	/* Fill in SACK options */
19344 	if (num_sack_blk > 0) {
19345 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19346 		sack_blk_t *tmp;
19347 		int32_t	i;
19348 
19349 		wptr[0] = TCPOPT_NOP;
19350 		wptr[1] = TCPOPT_NOP;
19351 		wptr[2] = TCPOPT_SACK;
19352 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19353 		    sizeof (sack_blk_t);
19354 		wptr += TCPOPT_REAL_SACK_LEN;
19355 
19356 		tmp = tcp->tcp_sack_list;
19357 		for (i = 0; i < num_sack_blk; i++) {
19358 			U32_TO_BE32(tmp[i].begin, wptr);
19359 			wptr += sizeof (tcp_seq);
19360 			U32_TO_BE32(tmp[i].end, wptr);
19361 			wptr += sizeof (tcp_seq);
19362 		}
19363 		tcp_h->th_offset_and_rsrvd[0] +=
19364 		    ((num_sack_blk * 2 + 1) << 4);
19365 	}
19366 }
19367 
19368 /*
19369  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19370  * the destination address and SAP attribute, and if necessary, the
19371  * hardware checksum offload attribute to a Multidata message.
19372  */
19373 static int
19374 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19375     const uint32_t start, const uint32_t stuff, const uint32_t end,
19376     const uint32_t flags)
19377 {
19378 	/* Add global destination address & SAP attribute */
19379 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
19380 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
19381 		    "destination address+SAP\n"));
19382 
19383 		if (dlmp != NULL)
19384 			TCP_STAT(tcp_mdt_allocfail);
19385 		return (-1);
19386 	}
19387 
19388 	/* Add global hwcksum attribute */
19389 	if (hwcksum &&
19390 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
19391 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
19392 		    "checksum attribute\n"));
19393 
19394 		TCP_STAT(tcp_mdt_allocfail);
19395 		return (-1);
19396 	}
19397 
19398 	return (0);
19399 }
19400 
19401 /*
19402  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
19403  * scheme, and returns one the following:
19404  *
19405  * -1 = failed allocation.
19406  *  0 = success; burst count reached, or usable send window is too small,
19407  *      and that we'd rather wait until later before sending again.
19408  */
19409 static int
19410 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19411     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19412     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19413     const int mdt_thres)
19414 {
19415 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
19416 	multidata_t	*mmd;
19417 	uint_t		obsegs, obbytes, hdr_frag_sz;
19418 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
19419 	int		num_burst_seg, max_pld;
19420 	pdesc_t		*pkt;
19421 	tcp_pdescinfo_t	tcp_pkt_info;
19422 	pdescinfo_t	*pkt_info;
19423 	int		pbuf_idx, pbuf_idx_nxt;
19424 	int		seg_len, len, spill, af;
19425 	boolean_t	add_buffer, zcopy, clusterwide;
19426 	boolean_t	rconfirm = B_FALSE;
19427 	boolean_t	done = B_FALSE;
19428 	uint32_t	cksum;
19429 	uint32_t	hwcksum_flags;
19430 	ire_t		*ire;
19431 	ill_t		*ill;
19432 	ipha_t		*ipha;
19433 	ip6_t		*ip6h;
19434 	ipaddr_t	src, dst;
19435 	ill_zerocopy_capab_t *zc_cap = NULL;
19436 	uint16_t	*up;
19437 	int		err;
19438 
19439 #ifdef	_BIG_ENDIAN
19440 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19441 #else
19442 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19443 #endif
19444 
19445 #define	TCP_CSUM_OFFSET	16
19446 #define	TCP_CSUM_SIZE	2
19447 
19448 #define	PREP_NEW_MULTIDATA() {			\
19449 	mmd = NULL;				\
19450 	md_mp = md_hbuf = NULL;			\
19451 	cur_hdr_off = 0;			\
19452 	max_pld = tcp->tcp_mdt_max_pld;		\
19453 	pbuf_idx = pbuf_idx_nxt = -1;		\
19454 	add_buffer = B_TRUE;			\
19455 	zcopy = B_FALSE;			\
19456 }
19457 
19458 #define	PREP_NEW_PBUF() {			\
19459 	md_pbuf = md_pbuf_nxt = NULL;		\
19460 	pbuf_idx = pbuf_idx_nxt = -1;		\
19461 	cur_pld_off = 0;			\
19462 	first_snxt = *snxt;			\
19463 	ASSERT(*tail_unsent > 0);		\
19464 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19465 }
19466 
19467 	ASSERT(mdt_thres >= mss);
19468 	ASSERT(*usable > 0 && *usable > mdt_thres);
19469 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19470 	ASSERT(!TCP_IS_DETACHED(tcp));
19471 	ASSERT(tcp->tcp_valid_bits == 0 ||
19472 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19473 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19474 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19475 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19476 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19477 	ASSERT(tcp->tcp_connp != NULL);
19478 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
19479 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
19480 
19481 	/*
19482 	 * Note that tcp will only declare at most 2 payload spans per
19483 	 * packet, which is much lower than the maximum allowable number
19484 	 * of packet spans per Multidata.  For this reason, we use the
19485 	 * privately declared and smaller descriptor info structure, in
19486 	 * order to save some stack space.
19487 	 */
19488 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19489 
19490 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19491 	if (af == AF_INET) {
19492 		dst = tcp->tcp_ipha->ipha_dst;
19493 		src = tcp->tcp_ipha->ipha_src;
19494 		ASSERT(!CLASSD(dst));
19495 	}
19496 	ASSERT(af == AF_INET ||
19497 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19498 
19499 	obsegs = obbytes = 0;
19500 	num_burst_seg = tcp->tcp_snd_burst;
19501 	md_mp_head = NULL;
19502 	PREP_NEW_MULTIDATA();
19503 
19504 	/*
19505 	 * Before we go on further, make sure there is an IRE that we can
19506 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19507 	 * in proceeding any further, and we should just hand everything
19508 	 * off to the legacy path.
19509 	 */
19510 	mutex_enter(&tcp->tcp_connp->conn_lock);
19511 	ire = tcp->tcp_connp->conn_ire_cache;
19512 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
19513 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19514 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19515 	    &tcp->tcp_ip6h->ip6_dst))) &&
19516 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19517 		IRE_REFHOLD(ire);
19518 		mutex_exit(&tcp->tcp_connp->conn_lock);
19519 	} else {
19520 		boolean_t cached = B_FALSE;
19521 
19522 		/* force a recheck later on */
19523 		tcp->tcp_ire_ill_check_done = B_FALSE;
19524 
19525 		TCP_DBGSTAT(tcp_ire_null1);
19526 		tcp->tcp_connp->conn_ire_cache = NULL;
19527 		mutex_exit(&tcp->tcp_connp->conn_lock);
19528 
19529 		/* Release the old ire */
19530 		if (ire != NULL)
19531 			IRE_REFRELE_NOTR(ire);
19532 
19533 		ire = (af == AF_INET) ?
19534 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
19535 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19536 		    tcp->tcp_connp->conn_zoneid);
19537 
19538 		if (ire == NULL) {
19539 			TCP_STAT(tcp_ire_null);
19540 			goto legacy_send_no_md;
19541 		}
19542 
19543 		IRE_REFHOLD_NOTR(ire);
19544 		/*
19545 		 * Since we are inside the squeue, there cannot be another
19546 		 * thread in TCP trying to set the conn_ire_cache now. The
19547 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19548 		 * unplumb thread has not yet started cleaning up the conns.
19549 		 * Hence we don't need to grab the conn lock.
19550 		 */
19551 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
19552 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19553 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19554 				tcp->tcp_connp->conn_ire_cache = ire;
19555 				cached = B_TRUE;
19556 			}
19557 			rw_exit(&ire->ire_bucket->irb_lock);
19558 		}
19559 
19560 		/*
19561 		 * We can continue to use the ire but since it was not
19562 		 * cached, we should drop the extra reference.
19563 		 */
19564 		if (!cached)
19565 			IRE_REFRELE_NOTR(ire);
19566 	}
19567 
19568 	ASSERT(ire != NULL);
19569 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19570 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19571 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19572 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19573 	/*
19574 	 * If we do support loopback for MDT (which requires modifications
19575 	 * to the receiving paths), the following assertions should go away,
19576 	 * and we would be sending the Multidata to loopback conn later on.
19577 	 */
19578 	ASSERT(!IRE_IS_LOCAL(ire));
19579 	ASSERT(ire->ire_stq != NULL);
19580 
19581 	ill = ire_to_ill(ire);
19582 	ASSERT(ill != NULL);
19583 	ASSERT((ill->ill_capabilities & ILL_CAPAB_MDT) == 0 ||
19584 	    ill->ill_mdt_capab != NULL);
19585 
19586 	if (!tcp->tcp_ire_ill_check_done) {
19587 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19588 		tcp->tcp_ire_ill_check_done = B_TRUE;
19589 	}
19590 
19591 	/*
19592 	 * If the underlying interface conditions have changed, or if the
19593 	 * new interface does not support MDT, go back to legacy path.
19594 	 */
19595 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19596 		/* don't go through this path anymore for this connection */
19597 		TCP_STAT(tcp_mdt_conn_halted2);
19598 		tcp->tcp_mdt = B_FALSE;
19599 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19600 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
19601 		/* IRE will be released prior to returning */
19602 		goto legacy_send_no_md;
19603 	}
19604 
19605 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19606 		zc_cap = ill->ill_zerocopy_capab;
19607 
19608 	/* go to legacy path if interface doesn't support zerocopy */
19609 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19610 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19611 		/* IRE will be released prior to returning */
19612 		goto legacy_send_no_md;
19613 	}
19614 
19615 	/* does the interface support hardware checksum offload? */
19616 	hwcksum_flags = 0;
19617 	if ((ill->ill_capabilities & ILL_CAPAB_HCKSUM) &&
19618 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19619 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_PARTIAL | HCKSUM_IPHDRCKSUM)) &&
19620 	    dohwcksum) {
19621 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19622 		    HCKSUM_IPHDRCKSUM)
19623 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19624 
19625 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19626 		    HCKSUM_INET_FULL_V4)
19627 			hwcksum_flags |= HCK_FULLCKSUM;
19628 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19629 		    HCKSUM_INET_PARTIAL)
19630 			hwcksum_flags |= HCK_PARTIALCKSUM;
19631 	}
19632 
19633 	/*
19634 	 * Each header fragment consists of the leading extra space,
19635 	 * followed by the TCP/IP header, and the trailing extra space.
19636 	 * We make sure that each header fragment begins on a 32-bit
19637 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19638 	 * aligned in tcp_mdt_update).
19639 	 */
19640 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19641 	    tcp->tcp_mdt_hdr_tail), 4);
19642 
19643 	/* are we starting from the beginning of data block? */
19644 	if (*tail_unsent == 0) {
19645 		*xmit_tail = (*xmit_tail)->b_cont;
19646 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19647 		*tail_unsent = (int)MBLKL(*xmit_tail);
19648 	}
19649 
19650 	/*
19651 	 * Here we create one or more Multidata messages, each made up of
19652 	 * one header buffer and up to N payload buffers.  This entire
19653 	 * operation is done within two loops:
19654 	 *
19655 	 * The outer loop mostly deals with creating the Multidata message,
19656 	 * as well as the header buffer that gets added to it.  It also
19657 	 * links the Multidata messages together such that all of them can
19658 	 * be sent down to the lower layer in a single putnext call; this
19659 	 * linking behavior depends on the tcp_mdt_chain tunable.
19660 	 *
19661 	 * The inner loop takes an existing Multidata message, and adds
19662 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19663 	 * packetizes those buffers by filling up the corresponding header
19664 	 * buffer fragments with the proper IP and TCP headers, and by
19665 	 * describing the layout of each packet in the packet descriptors
19666 	 * that get added to the Multidata.
19667 	 */
19668 	do {
19669 		/*
19670 		 * If usable send window is too small, or data blocks in
19671 		 * transmit list are smaller than our threshold (i.e. app
19672 		 * performs large writes followed by small ones), we hand
19673 		 * off the control over to the legacy path.  Note that we'll
19674 		 * get back the control once it encounters a large block.
19675 		 */
19676 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19677 		    (*xmit_tail)->b_cont != NULL &&
19678 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19679 			/* send down what we've got so far */
19680 			if (md_mp_head != NULL) {
19681 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19682 				    obsegs, obbytes, &rconfirm);
19683 			}
19684 			/*
19685 			 * Pass control over to tcp_send(), but tell it to
19686 			 * return to us once a large-size transmission is
19687 			 * possible.
19688 			 */
19689 			TCP_STAT(tcp_mdt_legacy_small);
19690 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19691 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19692 			    tail_unsent, xmit_tail, local_time,
19693 			    mdt_thres)) <= 0) {
19694 				/* burst count reached, or alloc failed */
19695 				IRE_REFRELE(ire);
19696 				return (err);
19697 			}
19698 
19699 			/* tcp_send() may have sent everything, so check */
19700 			if (*usable <= 0) {
19701 				IRE_REFRELE(ire);
19702 				return (0);
19703 			}
19704 
19705 			TCP_STAT(tcp_mdt_legacy_ret);
19706 			/*
19707 			 * We may have delivered the Multidata, so make sure
19708 			 * to re-initialize before the next round.
19709 			 */
19710 			md_mp_head = NULL;
19711 			obsegs = obbytes = 0;
19712 			num_burst_seg = tcp->tcp_snd_burst;
19713 			PREP_NEW_MULTIDATA();
19714 
19715 			/* are we starting from the beginning of data block? */
19716 			if (*tail_unsent == 0) {
19717 				*xmit_tail = (*xmit_tail)->b_cont;
19718 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19719 				    (uintptr_t)INT_MAX);
19720 				*tail_unsent = (int)MBLKL(*xmit_tail);
19721 			}
19722 		}
19723 
19724 		/*
19725 		 * max_pld limits the number of mblks in tcp's transmit
19726 		 * queue that can be added to a Multidata message.  Once
19727 		 * this counter reaches zero, no more additional mblks
19728 		 * can be added to it.  What happens afterwards depends
19729 		 * on whether or not we are set to chain the Multidata
19730 		 * messages.  If we are to link them together, reset
19731 		 * max_pld to its original value (tcp_mdt_max_pld) and
19732 		 * prepare to create a new Multidata message which will
19733 		 * get linked to md_mp_head.  Else, leave it alone and
19734 		 * let the inner loop break on its own.
19735 		 */
19736 		if (tcp_mdt_chain && max_pld == 0)
19737 			PREP_NEW_MULTIDATA();
19738 
19739 		/* adding a payload buffer; re-initialize values */
19740 		if (add_buffer)
19741 			PREP_NEW_PBUF();
19742 
19743 		/*
19744 		 * If we don't have a Multidata, either because we just
19745 		 * (re)entered this outer loop, or after we branched off
19746 		 * to tcp_send above, setup the Multidata and header
19747 		 * buffer to be used.
19748 		 */
19749 		if (md_mp == NULL) {
19750 			int md_hbuflen;
19751 			uint32_t start, stuff;
19752 
19753 			/*
19754 			 * Calculate Multidata header buffer size large enough
19755 			 * to hold all of the headers that can possibly be
19756 			 * sent at this moment.  We'd rather over-estimate
19757 			 * the size than running out of space; this is okay
19758 			 * since this buffer is small anyway.
19759 			 */
19760 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19761 
19762 			/*
19763 			 * Start and stuff offset for partial hardware
19764 			 * checksum offload; these are currently for IPv4.
19765 			 * For full checksum offload, they are set to zero.
19766 			 */
19767 			if (af == AF_INET &&
19768 			    (hwcksum_flags & HCK_PARTIALCKSUM)) {
19769 				start = IP_SIMPLE_HDR_LENGTH;
19770 				stuff = IP_SIMPLE_HDR_LENGTH + TCP_CSUM_OFFSET;
19771 			} else {
19772 				start = stuff = 0;
19773 			}
19774 
19775 			/*
19776 			 * Create the header buffer, Multidata, as well as
19777 			 * any necessary attributes (destination address,
19778 			 * SAP and hardware checksum offload) that should
19779 			 * be associated with the Multidata message.
19780 			 */
19781 			ASSERT(cur_hdr_off == 0);
19782 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19783 			    ((md_hbuf->b_wptr += md_hbuflen),
19784 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19785 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19786 			    /* fastpath mblk */
19787 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19788 			    ire->ire_nce->nce_res_mp,
19789 			    /* hardware checksum enabled (IPv4 only) */
19790 			    (af == AF_INET && hwcksum_flags != 0),
19791 			    /* hardware checksum offsets */
19792 			    start, stuff, 0,
19793 			    /* hardware checksum flag */
19794 			    hwcksum_flags) != 0)) {
19795 legacy_send:
19796 				if (md_mp != NULL) {
19797 					/* Unlink message from the chain */
19798 					if (md_mp_head != NULL) {
19799 						err = (intptr_t)rmvb(md_mp_head,
19800 						    md_mp);
19801 						/*
19802 						 * We can't assert that rmvb
19803 						 * did not return -1, since we
19804 						 * may get here before linkb
19805 						 * happens.  We do, however,
19806 						 * check if we just removed the
19807 						 * only element in the list.
19808 						 */
19809 						if (err == 0)
19810 							md_mp_head = NULL;
19811 					}
19812 					/* md_hbuf gets freed automatically */
19813 					TCP_STAT(tcp_mdt_discarded);
19814 					freeb(md_mp);
19815 				} else {
19816 					/* Either allocb or mmd_alloc failed */
19817 					TCP_STAT(tcp_mdt_allocfail);
19818 					if (md_hbuf != NULL)
19819 						freeb(md_hbuf);
19820 				}
19821 
19822 				/* send down what we've got so far */
19823 				if (md_mp_head != NULL) {
19824 					tcp_multisend_data(tcp, ire, ill,
19825 					    md_mp_head, obsegs, obbytes,
19826 					    &rconfirm);
19827 				}
19828 legacy_send_no_md:
19829 				if (ire != NULL)
19830 					IRE_REFRELE(ire);
19831 				/*
19832 				 * Too bad; let the legacy path handle this.
19833 				 * We specify INT_MAX for the threshold, since
19834 				 * we gave up with the Multidata processings
19835 				 * and let the old path have it all.
19836 				 */
19837 				TCP_STAT(tcp_mdt_legacy_all);
19838 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19839 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19840 				    snxt, tail_unsent, xmit_tail, local_time,
19841 				    INT_MAX));
19842 			}
19843 
19844 			/* link to any existing ones, if applicable */
19845 			TCP_STAT(tcp_mdt_allocd);
19846 			if (md_mp_head == NULL) {
19847 				md_mp_head = md_mp;
19848 			} else if (tcp_mdt_chain) {
19849 				TCP_STAT(tcp_mdt_linked);
19850 				linkb(md_mp_head, md_mp);
19851 			}
19852 		}
19853 
19854 		ASSERT(md_mp_head != NULL);
19855 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19856 		ASSERT(md_mp != NULL && mmd != NULL);
19857 		ASSERT(md_hbuf != NULL);
19858 
19859 		/*
19860 		 * Packetize the transmittable portion of the data block;
19861 		 * each data block is essentially added to the Multidata
19862 		 * as a payload buffer.  We also deal with adding more
19863 		 * than one payload buffers, which happens when the remaining
19864 		 * packetized portion of the current payload buffer is less
19865 		 * than MSS, while the next data block in transmit queue
19866 		 * has enough data to make up for one.  This "spillover"
19867 		 * case essentially creates a split-packet, where portions
19868 		 * of the packet's payload fragments may span across two
19869 		 * virtually discontiguous address blocks.
19870 		 */
19871 		seg_len = mss;
19872 		do {
19873 			len = seg_len;
19874 
19875 			ASSERT(len > 0);
19876 			ASSERT(max_pld >= 0);
19877 			ASSERT(!add_buffer || cur_pld_off == 0);
19878 
19879 			/*
19880 			 * First time around for this payload buffer; note
19881 			 * in the case of a spillover, the following has
19882 			 * been done prior to adding the split-packet
19883 			 * descriptor to Multidata, and we don't want to
19884 			 * repeat the process.
19885 			 */
19886 			if (add_buffer) {
19887 				ASSERT(mmd != NULL);
19888 				ASSERT(md_pbuf == NULL);
19889 				ASSERT(md_pbuf_nxt == NULL);
19890 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19891 
19892 				/*
19893 				 * Have we reached the limit?  We'd get to
19894 				 * this case when we're not chaining the
19895 				 * Multidata messages together, and since
19896 				 * we're done, terminate this loop.
19897 				 */
19898 				if (max_pld == 0)
19899 					break; /* done */
19900 
19901 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19902 					TCP_STAT(tcp_mdt_allocfail);
19903 					goto legacy_send; /* out_of_mem */
19904 				}
19905 
19906 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19907 				    zc_cap != NULL) {
19908 					if (!ip_md_zcopy_attr(mmd, NULL,
19909 					    zc_cap->ill_zerocopy_flags)) {
19910 						freeb(md_pbuf);
19911 						TCP_STAT(tcp_mdt_allocfail);
19912 						/* out_of_mem */
19913 						goto legacy_send;
19914 					}
19915 					zcopy = B_TRUE;
19916 				}
19917 
19918 				md_pbuf->b_rptr += base_pld_off;
19919 
19920 				/*
19921 				 * Add a payload buffer to the Multidata; this
19922 				 * operation must not fail, or otherwise our
19923 				 * logic in this routine is broken.  There
19924 				 * is no memory allocation done by the
19925 				 * routine, so any returned failure simply
19926 				 * tells us that we've done something wrong.
19927 				 *
19928 				 * A failure tells us that either we're adding
19929 				 * the same payload buffer more than once, or
19930 				 * we're trying to add more buffers than
19931 				 * allowed (max_pld calculation is wrong).
19932 				 * None of the above cases should happen, and
19933 				 * we panic because either there's horrible
19934 				 * heap corruption, and/or programming mistake.
19935 				 */
19936 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19937 				if (pbuf_idx < 0) {
19938 					cmn_err(CE_PANIC, "tcp_multisend: "
19939 					    "payload buffer logic error "
19940 					    "detected for tcp %p mmd %p "
19941 					    "pbuf %p (%d)\n",
19942 					    (void *)tcp, (void *)mmd,
19943 					    (void *)md_pbuf, pbuf_idx);
19944 				}
19945 
19946 				ASSERT(max_pld > 0);
19947 				--max_pld;
19948 				add_buffer = B_FALSE;
19949 			}
19950 
19951 			ASSERT(md_mp_head != NULL);
19952 			ASSERT(md_pbuf != NULL);
19953 			ASSERT(md_pbuf_nxt == NULL);
19954 			ASSERT(pbuf_idx != -1);
19955 			ASSERT(pbuf_idx_nxt == -1);
19956 			ASSERT(*usable > 0);
19957 
19958 			/*
19959 			 * We spillover to the next payload buffer only
19960 			 * if all of the following is true:
19961 			 *
19962 			 *   1. There is not enough data on the current
19963 			 *	payload buffer to make up `len',
19964 			 *   2. We are allowed to send `len',
19965 			 *   3. The next payload buffer length is large
19966 			 *	enough to accomodate `spill'.
19967 			 */
19968 			if ((spill = len - *tail_unsent) > 0 &&
19969 			    *usable >= len &&
19970 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19971 			    max_pld > 0) {
19972 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19973 				if (md_pbuf_nxt == NULL) {
19974 					TCP_STAT(tcp_mdt_allocfail);
19975 					goto legacy_send; /* out_of_mem */
19976 				}
19977 
19978 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19979 				    zc_cap != NULL) {
19980 					if (!ip_md_zcopy_attr(mmd, NULL,
19981 					    zc_cap->ill_zerocopy_flags)) {
19982 						freeb(md_pbuf_nxt);
19983 						TCP_STAT(tcp_mdt_allocfail);
19984 						/* out_of_mem */
19985 						goto legacy_send;
19986 					}
19987 					zcopy = B_TRUE;
19988 				}
19989 
19990 				/*
19991 				 * See comments above on the first call to
19992 				 * mmd_addpldbuf for explanation on the panic.
19993 				 */
19994 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19995 				if (pbuf_idx_nxt < 0) {
19996 					panic("tcp_multisend: "
19997 					    "next payload buffer logic error "
19998 					    "detected for tcp %p mmd %p "
19999 					    "pbuf %p (%d)\n",
20000 					    (void *)tcp, (void *)mmd,
20001 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20002 				}
20003 
20004 				ASSERT(max_pld > 0);
20005 				--max_pld;
20006 			} else if (spill > 0) {
20007 				/*
20008 				 * If there's a spillover, but the following
20009 				 * xmit_tail couldn't give us enough octets
20010 				 * to reach "len", then stop the current
20011 				 * Multidata creation and let the legacy
20012 				 * tcp_send() path take over.  We don't want
20013 				 * to send the tiny segment as part of this
20014 				 * Multidata for performance reasons; instead,
20015 				 * we let the legacy path deal with grouping
20016 				 * it with the subsequent small mblks.
20017 				 */
20018 				if (*usable >= len &&
20019 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20020 					max_pld = 0;
20021 					break;	/* done */
20022 				}
20023 
20024 				/*
20025 				 * We can't spillover, and we are near
20026 				 * the end of the current payload buffer,
20027 				 * so send what's left.
20028 				 */
20029 				ASSERT(*tail_unsent > 0);
20030 				len = *tail_unsent;
20031 			}
20032 
20033 			/* tail_unsent is negated if there is a spillover */
20034 			*tail_unsent -= len;
20035 			*usable -= len;
20036 			ASSERT(*usable >= 0);
20037 
20038 			if (*usable < mss)
20039 				seg_len = *usable;
20040 			/*
20041 			 * Sender SWS avoidance; see comments in tcp_send();
20042 			 * everything else is the same, except that we only
20043 			 * do this here if there is no more data to be sent
20044 			 * following the current xmit_tail.  We don't check
20045 			 * for 1-byte urgent data because we shouldn't get
20046 			 * here if TCP_URG_VALID is set.
20047 			 */
20048 			if (*usable > 0 && *usable < mss &&
20049 			    ((md_pbuf_nxt == NULL &&
20050 			    (*xmit_tail)->b_cont == NULL) ||
20051 			    (md_pbuf_nxt != NULL &&
20052 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20053 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20054 			    (tcp->tcp_unsent -
20055 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20056 			    !tcp->tcp_zero_win_probe) {
20057 				if ((*snxt + len) == tcp->tcp_snxt &&
20058 				    (*snxt + len) == tcp->tcp_suna) {
20059 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20060 				}
20061 				done = B_TRUE;
20062 			}
20063 
20064 			/*
20065 			 * Prime pump for IP's checksumming on our behalf;
20066 			 * include the adjustment for a source route if any.
20067 			 * Do this only for software/partial hardware checksum
20068 			 * offload, as this field gets zeroed out later for
20069 			 * the full hardware checksum offload case.
20070 			 */
20071 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20072 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20073 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20074 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20075 			}
20076 
20077 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20078 			*snxt += len;
20079 
20080 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20081 			/*
20082 			 * We set the PUSH bit only if TCP has no more buffered
20083 			 * data to be transmitted (or if sender SWS avoidance
20084 			 * takes place), as opposed to setting it for every
20085 			 * last packet in the burst.
20086 			 */
20087 			if (done ||
20088 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20089 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20090 
20091 			/*
20092 			 * Set FIN bit if this is our last segment; snxt
20093 			 * already includes its length, and it will not
20094 			 * be adjusted after this point.
20095 			 */
20096 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20097 			    *snxt == tcp->tcp_fss) {
20098 				if (!tcp->tcp_fin_acked) {
20099 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20100 					BUMP_MIB(&tcp_mib, tcpOutControl);
20101 				}
20102 				if (!tcp->tcp_fin_sent) {
20103 					tcp->tcp_fin_sent = B_TRUE;
20104 					/*
20105 					 * tcp state must be ESTABLISHED
20106 					 * in order for us to get here in
20107 					 * the first place.
20108 					 */
20109 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20110 
20111 					/*
20112 					 * Upon returning from this routine,
20113 					 * tcp_wput_data() will set tcp_snxt
20114 					 * to be equal to snxt + tcp_fin_sent.
20115 					 * This is essentially the same as
20116 					 * setting it to tcp_fss + 1.
20117 					 */
20118 				}
20119 			}
20120 
20121 			tcp->tcp_last_sent_len = (ushort_t)len;
20122 
20123 			len += tcp_hdr_len;
20124 			if (tcp->tcp_ipversion == IPV4_VERSION)
20125 				tcp->tcp_ipha->ipha_length = htons(len);
20126 			else
20127 				tcp->tcp_ip6h->ip6_plen = htons(len -
20128 				    ((char *)&tcp->tcp_ip6h[1] -
20129 				    tcp->tcp_iphc));
20130 
20131 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20132 
20133 			/* setup header fragment */
20134 			PDESC_HDR_ADD(pkt_info,
20135 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20136 			    tcp->tcp_mdt_hdr_head,		/* head room */
20137 			    tcp_hdr_len,			/* len */
20138 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20139 
20140 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20141 			    hdr_frag_sz);
20142 			ASSERT(MBLKIN(md_hbuf,
20143 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20144 			    PDESC_HDRSIZE(pkt_info)));
20145 
20146 			/* setup first payload fragment */
20147 			PDESC_PLD_INIT(pkt_info);
20148 			PDESC_PLD_SPAN_ADD(pkt_info,
20149 			    pbuf_idx,				/* index */
20150 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20151 			    tcp->tcp_last_sent_len);		/* len */
20152 
20153 			/* create a split-packet in case of a spillover */
20154 			if (md_pbuf_nxt != NULL) {
20155 				ASSERT(spill > 0);
20156 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20157 				ASSERT(!add_buffer);
20158 
20159 				md_pbuf = md_pbuf_nxt;
20160 				md_pbuf_nxt = NULL;
20161 				pbuf_idx = pbuf_idx_nxt;
20162 				pbuf_idx_nxt = -1;
20163 				cur_pld_off = spill;
20164 
20165 				/* trim out first payload fragment */
20166 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20167 
20168 				/* setup second payload fragment */
20169 				PDESC_PLD_SPAN_ADD(pkt_info,
20170 				    pbuf_idx,			/* index */
20171 				    md_pbuf->b_rptr,		/* start */
20172 				    spill);			/* len */
20173 
20174 				if ((*xmit_tail)->b_next == NULL) {
20175 					/*
20176 					 * Store the lbolt used for RTT
20177 					 * estimation. We can only record one
20178 					 * timestamp per mblk so we do it when
20179 					 * we reach the end of the payload
20180 					 * buffer.  Also we only take a new
20181 					 * timestamp sample when the previous
20182 					 * timed data from the same mblk has
20183 					 * been ack'ed.
20184 					 */
20185 					(*xmit_tail)->b_prev = local_time;
20186 					(*xmit_tail)->b_next =
20187 					    (mblk_t *)(uintptr_t)first_snxt;
20188 				}
20189 
20190 				first_snxt = *snxt - spill;
20191 
20192 				/*
20193 				 * Advance xmit_tail; usable could be 0 by
20194 				 * the time we got here, but we made sure
20195 				 * above that we would only spillover to
20196 				 * the next data block if usable includes
20197 				 * the spilled-over amount prior to the
20198 				 * subtraction.  Therefore, we are sure
20199 				 * that xmit_tail->b_cont can't be NULL.
20200 				 */
20201 				ASSERT((*xmit_tail)->b_cont != NULL);
20202 				*xmit_tail = (*xmit_tail)->b_cont;
20203 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20204 				    (uintptr_t)INT_MAX);
20205 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20206 			} else {
20207 				cur_pld_off += tcp->tcp_last_sent_len;
20208 			}
20209 
20210 			/*
20211 			 * Fill in the header using the template header, and
20212 			 * add options such as time-stamp, ECN and/or SACK,
20213 			 * as needed.
20214 			 */
20215 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20216 			    (clock_t)local_time, num_sack_blk);
20217 
20218 			/* take care of some IP header businesses */
20219 			if (af == AF_INET) {
20220 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20221 
20222 				ASSERT(OK_32PTR((uchar_t *)ipha));
20223 				ASSERT(PDESC_HDRL(pkt_info) >=
20224 				    IP_SIMPLE_HDR_LENGTH);
20225 				ASSERT(ipha->ipha_version_and_hdr_length ==
20226 				    IP_SIMPLE_HDR_VERSION);
20227 
20228 				/*
20229 				 * Assign ident value for current packet; see
20230 				 * related comments in ip_wput_ire() about the
20231 				 * contract private interface with clustering
20232 				 * group.
20233 				 */
20234 				clusterwide = B_FALSE;
20235 				if (cl_inet_ipident != NULL) {
20236 					ASSERT(cl_inet_isclusterwide != NULL);
20237 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20238 					    AF_INET,
20239 					    (uint8_t *)(uintptr_t)src)) {
20240 						ipha->ipha_ident =
20241 						    (*cl_inet_ipident)
20242 						    (IPPROTO_IP, AF_INET,
20243 						    (uint8_t *)(uintptr_t)src,
20244 						    (uint8_t *)(uintptr_t)dst);
20245 						clusterwide = B_TRUE;
20246 					}
20247 				}
20248 
20249 				if (!clusterwide) {
20250 					ipha->ipha_ident = (uint16_t)
20251 					    atomic_add_32_nv(
20252 						&ire->ire_ident, 1);
20253 				}
20254 #ifndef _BIG_ENDIAN
20255 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20256 				    (ipha->ipha_ident >> 8);
20257 #endif
20258 			} else {
20259 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20260 
20261 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20262 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20263 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20264 				ASSERT(PDESC_HDRL(pkt_info) >=
20265 				    (IPV6_HDR_LEN + TCP_CSUM_OFFSET +
20266 				    TCP_CSUM_SIZE));
20267 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20268 
20269 				if (tcp->tcp_ip_forward_progress) {
20270 					rconfirm = B_TRUE;
20271 					tcp->tcp_ip_forward_progress = B_FALSE;
20272 				}
20273 			}
20274 
20275 			/* at least one payload span, and at most two */
20276 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20277 
20278 			/* add the packet descriptor to Multidata */
20279 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20280 			    KM_NOSLEEP)) == NULL) {
20281 				/*
20282 				 * Any failure other than ENOMEM indicates
20283 				 * that we have passed in invalid pkt_info
20284 				 * or parameters to mmd_addpdesc, which must
20285 				 * not happen.
20286 				 *
20287 				 * EINVAL is a result of failure on boundary
20288 				 * checks against the pkt_info contents.  It
20289 				 * should not happen, and we panic because
20290 				 * either there's horrible heap corruption,
20291 				 * and/or programming mistake.
20292 				 */
20293 				if (err != ENOMEM) {
20294 					cmn_err(CE_PANIC, "tcp_multisend: "
20295 					    "pdesc logic error detected for "
20296 					    "tcp %p mmd %p pinfo %p (%d)\n",
20297 					    (void *)tcp, (void *)mmd,
20298 					    (void *)pkt_info, err);
20299 				}
20300 				TCP_STAT(tcp_mdt_addpdescfail);
20301 				goto legacy_send; /* out_of_mem */
20302 			}
20303 			ASSERT(pkt != NULL);
20304 
20305 			/* calculate IP header and TCP checksums */
20306 			if (af == AF_INET) {
20307 				/* calculate pseudo-header checksum */
20308 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20309 				    (src >> 16) + (src & 0xFFFF);
20310 
20311 				/* offset for TCP header checksum */
20312 				up = IPH_TCPH_CHECKSUMP(ipha,
20313 				    IP_SIMPLE_HDR_LENGTH);
20314 
20315 				if (hwcksum_flags & HCK_FULLCKSUM) {
20316 					/*
20317 					 * Hardware calculates pseudo-header,
20318 					 * header and payload checksums, so
20319 					 * zero out this field.
20320 					 */
20321 					*up = 0;
20322 				} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20323 					uint32_t sum;
20324 
20325 					/* pseudo-header checksumming */
20326 					sum = *up + cksum + IP_TCP_CSUM_COMP;
20327 					sum = (sum & 0xFFFF) + (sum >> 16);
20328 					*up = (sum & 0xFFFF) + (sum >> 16);
20329 				} else {
20330 					/* software checksumming */
20331 					TCP_STAT(tcp_out_sw_cksum);
20332 					*up = IP_MD_CSUM(pkt,
20333 					    IP_SIMPLE_HDR_LENGTH,
20334 					    cksum + IP_TCP_CSUM_COMP);
20335 				}
20336 
20337 				ipha->ipha_fragment_offset_and_flags |=
20338 				    (uint32_t)htons(ire->ire_frag_flag);
20339 
20340 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20341 					ipha->ipha_hdr_checksum = 0;
20342 				} else {
20343 					IP_HDR_CKSUM(ipha, cksum,
20344 					    ((uint32_t *)ipha)[0],
20345 					    ((uint16_t *)ipha)[4]);
20346 				}
20347 			} else {
20348 				up = (uint16_t *)(((uchar_t *)ip6h) +
20349 				    IPV6_HDR_LEN + TCP_CSUM_OFFSET);
20350 
20351 				/*
20352 				 * Software checksumming (hardware checksum
20353 				 * offload for IPv6 will hopefully be
20354 				 * implemented one day).
20355 				 */
20356 				TCP_STAT(tcp_out_sw_cksum);
20357 				*up = IP_MD_CSUM(pkt,
20358 				    IPV6_HDR_LEN - 2 * sizeof (in6_addr_t),
20359 				    htons(IPPROTO_TCP));
20360 			}
20361 
20362 			/* advance header offset */
20363 			cur_hdr_off += hdr_frag_sz;
20364 
20365 			obbytes += tcp->tcp_last_sent_len;
20366 			++obsegs;
20367 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
20368 		    *tail_unsent > 0);
20369 
20370 		if ((*xmit_tail)->b_next == NULL) {
20371 			/*
20372 			 * Store the lbolt used for RTT estimation. We can only
20373 			 * record one timestamp per mblk so we do it when we
20374 			 * reach the end of the payload buffer. Also we only
20375 			 * take a new timestamp sample when the previous timed
20376 			 * data from the same mblk has been ack'ed.
20377 			 */
20378 			(*xmit_tail)->b_prev = local_time;
20379 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
20380 		}
20381 
20382 		ASSERT(*tail_unsent >= 0);
20383 		if (*tail_unsent > 0) {
20384 			/*
20385 			 * We got here because we broke out of the above
20386 			 * loop due to of one of the following cases:
20387 			 *
20388 			 *   1. len < adjusted MSS (i.e. small),
20389 			 *   2. Sender SWS avoidance,
20390 			 *   3. max_pld is zero.
20391 			 *
20392 			 * We are done for this Multidata, so trim our
20393 			 * last payload buffer (if any) accordingly.
20394 			 */
20395 			if (md_pbuf != NULL)
20396 				md_pbuf->b_wptr -= *tail_unsent;
20397 		} else if (*usable > 0) {
20398 			*xmit_tail = (*xmit_tail)->b_cont;
20399 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20400 			    (uintptr_t)INT_MAX);
20401 			*tail_unsent = (int)MBLKL(*xmit_tail);
20402 			add_buffer = B_TRUE;
20403 		}
20404 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
20405 	    (tcp_mdt_chain || max_pld > 0));
20406 
20407 	/* send everything down */
20408 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
20409 	    &rconfirm);
20410 
20411 #undef PREP_NEW_MULTIDATA
20412 #undef PREP_NEW_PBUF
20413 #undef IPVER
20414 #undef TCP_CSUM_OFFSET
20415 #undef TCP_CSUM_SIZE
20416 
20417 	IRE_REFRELE(ire);
20418 	return (0);
20419 }
20420 
20421 /*
20422  * A wrapper function for sending one or more Multidata messages down to
20423  * the module below ip; this routine does not release the reference of the
20424  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20425  */
20426 static void
20427 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20428     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20429 {
20430 	uint64_t delta;
20431 	nce_t *nce;
20432 
20433 	ASSERT(ire != NULL && ill != NULL);
20434 	ASSERT(ire->ire_stq != NULL);
20435 	ASSERT(md_mp_head != NULL);
20436 	ASSERT(rconfirm != NULL);
20437 
20438 	/* adjust MIBs and IRE timestamp */
20439 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20440 	tcp->tcp_obsegs += obsegs;
20441 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20442 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20443 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20444 
20445 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20446 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20447 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20448 	} else {
20449 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20450 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20451 	}
20452 
20453 	ire->ire_ob_pkt_count += obsegs;
20454 	if (ire->ire_ipif != NULL)
20455 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20456 	ire->ire_last_used_time = lbolt;
20457 
20458 	/* send it down */
20459 	putnext(ire->ire_stq, md_mp_head);
20460 
20461 	/* we're done for TCP/IPv4 */
20462 	if (tcp->tcp_ipversion == IPV4_VERSION)
20463 		return;
20464 
20465 	nce = ire->ire_nce;
20466 
20467 	ASSERT(nce != NULL);
20468 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20469 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20470 
20471 	/* reachability confirmation? */
20472 	if (*rconfirm) {
20473 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20474 		if (nce->nce_state != ND_REACHABLE) {
20475 			mutex_enter(&nce->nce_lock);
20476 			nce->nce_state = ND_REACHABLE;
20477 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20478 			mutex_exit(&nce->nce_lock);
20479 			(void) untimeout(nce->nce_timeout_id);
20480 			if (ip_debug > 2) {
20481 				/* ip1dbg */
20482 				pr_addr_dbg("tcp_multisend_data: state "
20483 				    "for %s changed to REACHABLE\n",
20484 				    AF_INET6, &ire->ire_addr_v6);
20485 			}
20486 		}
20487 		/* reset transport reachability confirmation */
20488 		*rconfirm = B_FALSE;
20489 	}
20490 
20491 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20492 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20493 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20494 
20495 	if (delta > (uint64_t)ill->ill_reachable_time) {
20496 		mutex_enter(&nce->nce_lock);
20497 		switch (nce->nce_state) {
20498 		case ND_REACHABLE:
20499 		case ND_STALE:
20500 			/*
20501 			 * ND_REACHABLE is identical to ND_STALE in this
20502 			 * specific case. If reachable time has expired for
20503 			 * this neighbor (delta is greater than reachable
20504 			 * time), conceptually, the neighbor cache is no
20505 			 * longer in REACHABLE state, but already in STALE
20506 			 * state.  So the correct transition here is to
20507 			 * ND_DELAY.
20508 			 */
20509 			nce->nce_state = ND_DELAY;
20510 			mutex_exit(&nce->nce_lock);
20511 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20512 			if (ip_debug > 3) {
20513 				/* ip2dbg */
20514 				pr_addr_dbg("tcp_multisend_data: state "
20515 				    "for %s changed to DELAY\n",
20516 				    AF_INET6, &ire->ire_addr_v6);
20517 			}
20518 			break;
20519 		case ND_DELAY:
20520 		case ND_PROBE:
20521 			mutex_exit(&nce->nce_lock);
20522 			/* Timers have already started */
20523 			break;
20524 		case ND_UNREACHABLE:
20525 			/*
20526 			 * ndp timer has detected that this nce is
20527 			 * unreachable and initiated deleting this nce
20528 			 * and all its associated IREs. This is a race
20529 			 * where we found the ire before it was deleted
20530 			 * and have just sent out a packet using this
20531 			 * unreachable nce.
20532 			 */
20533 			mutex_exit(&nce->nce_lock);
20534 			break;
20535 		default:
20536 			ASSERT(0);
20537 		}
20538 	}
20539 }
20540 
20541 /*
20542  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20543  * scheme, and returns one of the following:
20544  *
20545  * -1 = failed allocation.
20546  *  0 = success; burst count reached, or usable send window is too small,
20547  *      and that we'd rather wait until later before sending again.
20548  *  1 = success; we are called from tcp_multisend(), and both usable send
20549  *      window and tail_unsent are greater than the MDT threshold, and thus
20550  *      Multidata Transmit should be used instead.
20551  */
20552 static int
20553 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20554     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20555     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20556     const int mdt_thres)
20557 {
20558 	int num_burst_seg = tcp->tcp_snd_burst;
20559 
20560 	for (;;) {
20561 		struct datab	*db;
20562 		tcph_t		*tcph;
20563 		uint32_t	sum;
20564 		mblk_t		*mp, *mp1;
20565 		uchar_t		*rptr;
20566 		int		len;
20567 
20568 		/*
20569 		 * If we're called by tcp_multisend(), and the amount of
20570 		 * sendable data as well as the size of current xmit_tail
20571 		 * is beyond the MDT threshold, return to the caller and
20572 		 * let the large data transmit be done using MDT.
20573 		 */
20574 		if (*usable > 0 && *usable > mdt_thres &&
20575 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20576 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20577 			ASSERT(tcp->tcp_mdt);
20578 			return (1);	/* success; do large send */
20579 		}
20580 
20581 		if (num_burst_seg-- == 0)
20582 			break;		/* success; burst count reached */
20583 
20584 		len = mss;
20585 		if (len > *usable) {
20586 			len = *usable;
20587 			if (len <= 0) {
20588 				/* Terminate the loop */
20589 				break;	/* success; too small */
20590 			}
20591 			/*
20592 			 * Sender silly-window avoidance.
20593 			 * Ignore this if we are going to send a
20594 			 * zero window probe out.
20595 			 *
20596 			 * TODO: force data into microscopic window?
20597 			 *	==> (!pushed || (unsent > usable))
20598 			 */
20599 			if (len < (tcp->tcp_max_swnd >> 1) &&
20600 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20601 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20602 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20603 				/*
20604 				 * If the retransmit timer is not running
20605 				 * we start it so that we will retransmit
20606 				 * in the case when the the receiver has
20607 				 * decremented the window.
20608 				 */
20609 				if (*snxt == tcp->tcp_snxt &&
20610 				    *snxt == tcp->tcp_suna) {
20611 					/*
20612 					 * We are not supposed to send
20613 					 * anything.  So let's wait a little
20614 					 * bit longer before breaking SWS
20615 					 * avoidance.
20616 					 *
20617 					 * What should the value be?
20618 					 * Suggestion: MAX(init rexmit time,
20619 					 * tcp->tcp_rto)
20620 					 */
20621 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20622 				}
20623 				break;	/* success; too small */
20624 			}
20625 		}
20626 
20627 		tcph = tcp->tcp_tcph;
20628 
20629 		*usable -= len; /* Approximate - can be adjusted later */
20630 		if (*usable > 0)
20631 			tcph->th_flags[0] = TH_ACK;
20632 		else
20633 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20634 
20635 		/*
20636 		 * Prime pump for IP's checksumming on our behalf
20637 		 * Include the adjustment for a source route if any.
20638 		 */
20639 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20640 		sum = (sum >> 16) + (sum & 0xFFFF);
20641 		U16_TO_ABE16(sum, tcph->th_sum);
20642 
20643 		U32_TO_ABE32(*snxt, tcph->th_seq);
20644 
20645 		/*
20646 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20647 		 * set.  For the case when TCP_FSS_VALID is the only valid
20648 		 * bit (normal active close), branch off only when we think
20649 		 * that the FIN flag needs to be set.  Note for this case,
20650 		 * that (snxt + len) may not reflect the actual seg_len,
20651 		 * as len may be further reduced in tcp_xmit_mp().  If len
20652 		 * gets modified, we will end up here again.
20653 		 */
20654 		if (tcp->tcp_valid_bits != 0 &&
20655 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20656 		    ((*snxt + len) == tcp->tcp_fss))) {
20657 			uchar_t		*prev_rptr;
20658 			uint32_t	prev_snxt = tcp->tcp_snxt;
20659 
20660 			if (*tail_unsent == 0) {
20661 				ASSERT((*xmit_tail)->b_cont != NULL);
20662 				*xmit_tail = (*xmit_tail)->b_cont;
20663 				prev_rptr = (*xmit_tail)->b_rptr;
20664 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20665 				    (*xmit_tail)->b_rptr);
20666 			} else {
20667 				prev_rptr = (*xmit_tail)->b_rptr;
20668 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20669 				    *tail_unsent;
20670 			}
20671 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20672 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20673 			/* Restore tcp_snxt so we get amount sent right. */
20674 			tcp->tcp_snxt = prev_snxt;
20675 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20676 				/*
20677 				 * If the previous timestamp is still in use,
20678 				 * don't stomp on it.
20679 				 */
20680 				if ((*xmit_tail)->b_next == NULL) {
20681 					(*xmit_tail)->b_prev = local_time;
20682 					(*xmit_tail)->b_next =
20683 					    (mblk_t *)(uintptr_t)(*snxt);
20684 				}
20685 			} else
20686 				(*xmit_tail)->b_rptr = prev_rptr;
20687 
20688 			if (mp == NULL)
20689 				return (-1);
20690 			mp1 = mp->b_cont;
20691 
20692 			tcp->tcp_last_sent_len = (ushort_t)len;
20693 			while (mp1->b_cont) {
20694 				*xmit_tail = (*xmit_tail)->b_cont;
20695 				(*xmit_tail)->b_prev = local_time;
20696 				(*xmit_tail)->b_next =
20697 				    (mblk_t *)(uintptr_t)(*snxt);
20698 				mp1 = mp1->b_cont;
20699 			}
20700 			*snxt += len;
20701 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20702 			BUMP_LOCAL(tcp->tcp_obsegs);
20703 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20704 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20705 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20706 			tcp_send_data(tcp, q, mp);
20707 			continue;
20708 		}
20709 
20710 		*snxt += len;	/* Adjust later if we don't send all of len */
20711 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20712 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20713 
20714 		if (*tail_unsent) {
20715 			/* Are the bytes above us in flight? */
20716 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20717 			if (rptr != (*xmit_tail)->b_rptr) {
20718 				*tail_unsent -= len;
20719 				tcp->tcp_last_sent_len = (ushort_t)len;
20720 				len += tcp_hdr_len;
20721 				if (tcp->tcp_ipversion == IPV4_VERSION)
20722 					tcp->tcp_ipha->ipha_length = htons(len);
20723 				else
20724 					tcp->tcp_ip6h->ip6_plen =
20725 					    htons(len -
20726 					    ((char *)&tcp->tcp_ip6h[1] -
20727 					    tcp->tcp_iphc));
20728 				mp = dupb(*xmit_tail);
20729 				if (!mp)
20730 					return (-1);	/* out_of_mem */
20731 				mp->b_rptr = rptr;
20732 				/*
20733 				 * If the old timestamp is no longer in use,
20734 				 * sample a new timestamp now.
20735 				 */
20736 				if ((*xmit_tail)->b_next == NULL) {
20737 					(*xmit_tail)->b_prev = local_time;
20738 					(*xmit_tail)->b_next =
20739 					    (mblk_t *)(uintptr_t)(*snxt-len);
20740 				}
20741 				goto must_alloc;
20742 			}
20743 		} else {
20744 			*xmit_tail = (*xmit_tail)->b_cont;
20745 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20746 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20747 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20748 			    (*xmit_tail)->b_rptr);
20749 		}
20750 
20751 		(*xmit_tail)->b_prev = local_time;
20752 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20753 
20754 		*tail_unsent -= len;
20755 		tcp->tcp_last_sent_len = (ushort_t)len;
20756 
20757 		len += tcp_hdr_len;
20758 		if (tcp->tcp_ipversion == IPV4_VERSION)
20759 			tcp->tcp_ipha->ipha_length = htons(len);
20760 		else
20761 			tcp->tcp_ip6h->ip6_plen = htons(len -
20762 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20763 
20764 		mp = dupb(*xmit_tail);
20765 		if (!mp)
20766 			return (-1);	/* out_of_mem */
20767 
20768 		len = tcp_hdr_len;
20769 		/*
20770 		 * There are four reasons to allocate a new hdr mblk:
20771 		 *  1) The bytes above us are in use by another packet
20772 		 *  2) We don't have good alignment
20773 		 *  3) The mblk is being shared
20774 		 *  4) We don't have enough room for a header
20775 		 */
20776 		rptr = mp->b_rptr - len;
20777 		if (!OK_32PTR(rptr) ||
20778 		    ((db = mp->b_datap), db->db_ref != 2) ||
20779 		    rptr < db->db_base) {
20780 			/* NOTE: we assume allocb returns an OK_32PTR */
20781 
20782 		must_alloc:;
20783 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20784 			    tcp_wroff_xtra, BPRI_MED);
20785 			if (!mp1) {
20786 				freemsg(mp);
20787 				return (-1);	/* out_of_mem */
20788 			}
20789 			mp1->b_cont = mp;
20790 			mp = mp1;
20791 			/* Leave room for Link Level header */
20792 			len = tcp_hdr_len;
20793 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20794 			mp->b_wptr = &rptr[len];
20795 		}
20796 
20797 		/*
20798 		 * Fill in the header using the template header, and add
20799 		 * options such as time-stamp, ECN and/or SACK, as needed.
20800 		 */
20801 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20802 
20803 		mp->b_rptr = rptr;
20804 
20805 		if (*tail_unsent) {
20806 			int spill = *tail_unsent;
20807 
20808 			mp1 = mp->b_cont;
20809 			if (!mp1)
20810 				mp1 = mp;
20811 
20812 			/*
20813 			 * If we're a little short, tack on more mblks until
20814 			 * there is no more spillover.
20815 			 */
20816 			while (spill < 0) {
20817 				mblk_t *nmp;
20818 				int nmpsz;
20819 
20820 				nmp = (*xmit_tail)->b_cont;
20821 				nmpsz = MBLKL(nmp);
20822 
20823 				/*
20824 				 * Excess data in mblk; can we split it?
20825 				 * If MDT is enabled for the connection,
20826 				 * keep on splitting as this is a transient
20827 				 * send path.
20828 				 */
20829 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20830 					/*
20831 					 * Don't split if stream head was
20832 					 * told to break up larger writes
20833 					 * into smaller ones.
20834 					 */
20835 					if (tcp->tcp_maxpsz > 0)
20836 						break;
20837 
20838 					/*
20839 					 * Next mblk is less than SMSS/2
20840 					 * rounded up to nearest 64-byte;
20841 					 * let it get sent as part of the
20842 					 * next segment.
20843 					 */
20844 					if (tcp->tcp_localnet &&
20845 					    !tcp->tcp_cork &&
20846 					    (nmpsz < roundup((mss >> 1), 64)))
20847 						break;
20848 				}
20849 
20850 				*xmit_tail = nmp;
20851 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20852 				/* Stash for rtt use later */
20853 				(*xmit_tail)->b_prev = local_time;
20854 				(*xmit_tail)->b_next =
20855 				    (mblk_t *)(uintptr_t)(*snxt - len);
20856 				mp1->b_cont = dupb(*xmit_tail);
20857 				mp1 = mp1->b_cont;
20858 
20859 				spill += nmpsz;
20860 				if (mp1 == NULL) {
20861 					*tail_unsent = spill;
20862 					freemsg(mp);
20863 					return (-1);	/* out_of_mem */
20864 				}
20865 			}
20866 
20867 			/* Trim back any surplus on the last mblk */
20868 			if (spill >= 0) {
20869 				mp1->b_wptr -= spill;
20870 				*tail_unsent = spill;
20871 			} else {
20872 				/*
20873 				 * We did not send everything we could in
20874 				 * order to remain within the b_cont limit.
20875 				 */
20876 				*usable -= spill;
20877 				*snxt += spill;
20878 				tcp->tcp_last_sent_len += spill;
20879 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20880 				/*
20881 				 * Adjust the checksum
20882 				 */
20883 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20884 				sum += spill;
20885 				sum = (sum >> 16) + (sum & 0xFFFF);
20886 				U16_TO_ABE16(sum, tcph->th_sum);
20887 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20888 					sum = ntohs(
20889 					    ((ipha_t *)rptr)->ipha_length) +
20890 					    spill;
20891 					((ipha_t *)rptr)->ipha_length =
20892 					    htons(sum);
20893 				} else {
20894 					sum = ntohs(
20895 					    ((ip6_t *)rptr)->ip6_plen) +
20896 					    spill;
20897 					((ip6_t *)rptr)->ip6_plen =
20898 					    htons(sum);
20899 				}
20900 				*tail_unsent = 0;
20901 			}
20902 		}
20903 		if (tcp->tcp_ip_forward_progress) {
20904 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20905 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20906 			tcp->tcp_ip_forward_progress = B_FALSE;
20907 		}
20908 
20909 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20910 		tcp_send_data(tcp, q, mp);
20911 		BUMP_LOCAL(tcp->tcp_obsegs);
20912 	}
20913 
20914 	return (0);
20915 }
20916 
20917 /* Unlink and return any mblk that looks like it contains a MDT info */
20918 static mblk_t *
20919 tcp_mdt_info_mp(mblk_t *mp)
20920 {
20921 	mblk_t	*prev_mp;
20922 
20923 	for (;;) {
20924 		prev_mp = mp;
20925 		/* no more to process? */
20926 		if ((mp = mp->b_cont) == NULL)
20927 			break;
20928 
20929 		switch (DB_TYPE(mp)) {
20930 		case M_CTL:
20931 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20932 				continue;
20933 			ASSERT(prev_mp != NULL);
20934 			prev_mp->b_cont = mp->b_cont;
20935 			mp->b_cont = NULL;
20936 			return (mp);
20937 		default:
20938 			break;
20939 		}
20940 	}
20941 	return (mp);
20942 }
20943 
20944 /* MDT info update routine, called when IP notifies us about MDT */
20945 static void
20946 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20947 {
20948 	boolean_t prev_state;
20949 
20950 	/*
20951 	 * IP is telling us to abort MDT on this connection?  We know
20952 	 * this because the capability is only turned off when IP
20953 	 * encounters some pathological cases, e.g. link-layer change
20954 	 * where the new driver doesn't support MDT, or in situation
20955 	 * where MDT usage on the link-layer has been switched off.
20956 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20957 	 * if the link-layer doesn't support MDT, and if it does, it
20958 	 * will indicate that the feature is to be turned on.
20959 	 */
20960 	prev_state = tcp->tcp_mdt;
20961 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20962 	if (!tcp->tcp_mdt && !first) {
20963 		TCP_STAT(tcp_mdt_conn_halted3);
20964 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20965 		    (void *)tcp->tcp_connp));
20966 	}
20967 
20968 	/*
20969 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20970 	 * so disable MDT otherwise.  The checks are done here
20971 	 * and in tcp_wput_data().
20972 	 */
20973 	if (tcp->tcp_mdt &&
20974 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20975 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20976 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20977 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20978 		tcp->tcp_mdt = B_FALSE;
20979 
20980 	if (tcp->tcp_mdt) {
20981 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20982 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20983 			    "version (%d), expected version is %d",
20984 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20985 			tcp->tcp_mdt = B_FALSE;
20986 			return;
20987 		}
20988 
20989 		/*
20990 		 * We need the driver to be able to handle at least three
20991 		 * spans per packet in order for tcp MDT to be utilized.
20992 		 * The first is for the header portion, while the rest are
20993 		 * needed to handle a packet that straddles across two
20994 		 * virtually non-contiguous buffers; a typical tcp packet
20995 		 * therefore consists of only two spans.  Note that we take
20996 		 * a zero as "don't care".
20997 		 */
20998 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20999 		    mdt_capab->ill_mdt_span_limit < 3) {
21000 			tcp->tcp_mdt = B_FALSE;
21001 			return;
21002 		}
21003 
21004 		/* a zero means driver wants default value */
21005 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21006 		    tcp_mdt_max_pbufs);
21007 		if (tcp->tcp_mdt_max_pld == 0)
21008 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
21009 
21010 		/* ensure 32-bit alignment */
21011 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
21012 		    mdt_capab->ill_mdt_hdr_head), 4);
21013 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
21014 		    mdt_capab->ill_mdt_hdr_tail), 4);
21015 
21016 		if (!first && !prev_state) {
21017 			TCP_STAT(tcp_mdt_conn_resumed2);
21018 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
21019 			    (void *)tcp->tcp_connp));
21020 		}
21021 	}
21022 }
21023 
21024 static void
21025 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
21026 {
21027 	conn_t *connp = tcp->tcp_connp;
21028 
21029 	ASSERT(ire != NULL);
21030 
21031 	/*
21032 	 * We may be in the fastpath here, and although we essentially do
21033 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
21034 	 * we try to keep things as brief as possible.  After all, these
21035 	 * are only best-effort checks, and we do more thorough ones prior
21036 	 * to calling tcp_multisend().
21037 	 */
21038 	if (ip_multidata_outbound && check_mdt &&
21039 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
21040 	    ill != NULL && (ill->ill_capabilities & ILL_CAPAB_MDT) &&
21041 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
21042 	    !(ire->ire_flags & RTF_MULTIRT) &&
21043 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
21044 	    CONN_IS_MD_FASTPATH(connp)) {
21045 		/* Remember the result */
21046 		connp->conn_mdt_ok = B_TRUE;
21047 
21048 		ASSERT(ill->ill_mdt_capab != NULL);
21049 		if (!ill->ill_mdt_capab->ill_mdt_on) {
21050 			/*
21051 			 * If MDT has been previously turned off in the past,
21052 			 * and we currently can do MDT (due to IPQoS policy
21053 			 * removal, etc.) then enable it for this interface.
21054 			 */
21055 			ill->ill_mdt_capab->ill_mdt_on = 1;
21056 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
21057 			    "interface %s\n", (void *)connp, ill->ill_name));
21058 		}
21059 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
21060 	}
21061 
21062 	/*
21063 	 * The goal is to reduce the number of generated tcp segments by
21064 	 * setting the maxpsz multiplier to 0; this will have an affect on
21065 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
21066 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
21067 	 * of outbound segments and incoming ACKs, thus allowing for better
21068 	 * network and system performance.  In contrast the legacy behavior
21069 	 * may result in sending less than SMSS size, because the last mblk
21070 	 * for some packets may have more data than needed to make up SMSS,
21071 	 * and the legacy code refused to "split" it.
21072 	 *
21073 	 * We apply the new behavior on following situations:
21074 	 *
21075 	 *   1) Loopback connections,
21076 	 *   2) Connections in which the remote peer is not on local subnet,
21077 	 *   3) Local subnet connections over the bge interface (see below).
21078 	 *
21079 	 * Ideally, we would like this behavior to apply for interfaces other
21080 	 * than bge.  However, doing so would negatively impact drivers which
21081 	 * perform dynamic mapping and unmapping of DMA resources, which are
21082 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
21083 	 * packet will be generated by tcp).  The bge driver does not suffer
21084 	 * from this, as it copies the mblks into pre-mapped buffers, and
21085 	 * therefore does not require more I/O resources than before.
21086 	 *
21087 	 * Otherwise, this behavior is present on all network interfaces when
21088 	 * the destination endpoint is non-local, since reducing the number
21089 	 * of packets in general is good for the network.
21090 	 *
21091 	 * TODO We need to remove this hard-coded conditional for bge once
21092 	 *	a better "self-tuning" mechanism, or a way to comprehend
21093 	 *	the driver transmit strategy is devised.  Until the solution
21094 	 *	is found and well understood, we live with this hack.
21095 	 */
21096 	if (!tcp_static_maxpsz &&
21097 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
21098 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
21099 		/* override the default value */
21100 		tcp->tcp_maxpsz = 0;
21101 
21102 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
21103 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
21104 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
21105 	}
21106 
21107 	/* set the stream head parameters accordingly */
21108 	(void) tcp_maxpsz_set(tcp, B_TRUE);
21109 }
21110 
21111 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
21112 static void
21113 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
21114 {
21115 	uchar_t	fval = *mp->b_rptr;
21116 	mblk_t	*tail;
21117 	queue_t	*q = tcp->tcp_wq;
21118 
21119 	/* TODO: How should flush interact with urgent data? */
21120 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
21121 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
21122 		/*
21123 		 * Flush only data that has not yet been put on the wire.  If
21124 		 * we flush data that we have already transmitted, life, as we
21125 		 * know it, may come to an end.
21126 		 */
21127 		tail = tcp->tcp_xmit_tail;
21128 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
21129 		tcp->tcp_xmit_tail_unsent = 0;
21130 		tcp->tcp_unsent = 0;
21131 		if (tail->b_wptr != tail->b_rptr)
21132 			tail = tail->b_cont;
21133 		if (tail) {
21134 			mblk_t **excess = &tcp->tcp_xmit_head;
21135 			for (;;) {
21136 				mblk_t *mp1 = *excess;
21137 				if (mp1 == tail)
21138 					break;
21139 				tcp->tcp_xmit_tail = mp1;
21140 				tcp->tcp_xmit_last = mp1;
21141 				excess = &mp1->b_cont;
21142 			}
21143 			*excess = NULL;
21144 			tcp_close_mpp(&tail);
21145 			if (tcp->tcp_snd_zcopy_aware)
21146 				tcp_zcopy_notify(tcp);
21147 		}
21148 		/*
21149 		 * We have no unsent data, so unsent must be less than
21150 		 * tcp_xmit_lowater, so re-enable flow.
21151 		 */
21152 		if (tcp->tcp_flow_stopped) {
21153 			tcp->tcp_flow_stopped = B_FALSE;
21154 			tcp_clrqfull(tcp);
21155 		}
21156 	}
21157 	/*
21158 	 * TODO: you can't just flush these, you have to increase rwnd for one
21159 	 * thing.  For another, how should urgent data interact?
21160 	 */
21161 	if (fval & FLUSHR) {
21162 		*mp->b_rptr = fval & ~FLUSHW;
21163 		/* XXX */
21164 		qreply(q, mp);
21165 		return;
21166 	}
21167 	freemsg(mp);
21168 }
21169 
21170 /*
21171  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
21172  * messages.
21173  */
21174 static void
21175 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
21176 {
21177 	mblk_t	*mp1;
21178 	STRUCT_HANDLE(strbuf, sb);
21179 	uint16_t port;
21180 	queue_t 	*q = tcp->tcp_wq;
21181 	in6_addr_t	v6addr;
21182 	ipaddr_t	v4addr;
21183 	uint32_t	flowinfo = 0;
21184 	int		addrlen;
21185 
21186 	/* Make sure it is one of ours. */
21187 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21188 	case TI_GETMYNAME:
21189 	case TI_GETPEERNAME:
21190 		break;
21191 	default:
21192 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21193 		return;
21194 	}
21195 	switch (mi_copy_state(q, mp, &mp1)) {
21196 	case -1:
21197 		return;
21198 	case MI_COPY_CASE(MI_COPY_IN, 1):
21199 		break;
21200 	case MI_COPY_CASE(MI_COPY_OUT, 1):
21201 		/* Copy out the strbuf. */
21202 		mi_copyout(q, mp);
21203 		return;
21204 	case MI_COPY_CASE(MI_COPY_OUT, 2):
21205 		/* All done. */
21206 		mi_copy_done(q, mp, 0);
21207 		return;
21208 	default:
21209 		mi_copy_done(q, mp, EPROTO);
21210 		return;
21211 	}
21212 	/* Check alignment of the strbuf */
21213 	if (!OK_32PTR(mp1->b_rptr)) {
21214 		mi_copy_done(q, mp, EINVAL);
21215 		return;
21216 	}
21217 
21218 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
21219 	    (void *)mp1->b_rptr);
21220 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
21221 
21222 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
21223 		mi_copy_done(q, mp, EINVAL);
21224 		return;
21225 	}
21226 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
21227 	case TI_GETMYNAME:
21228 		if (tcp->tcp_family == AF_INET) {
21229 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21230 				v4addr = tcp->tcp_ipha->ipha_src;
21231 			} else {
21232 				/* can't return an address in this case */
21233 				v4addr = 0;
21234 			}
21235 		} else {
21236 			/* tcp->tcp_family == AF_INET6 */
21237 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21238 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
21239 				    &v6addr);
21240 			} else {
21241 				v6addr = tcp->tcp_ip6h->ip6_src;
21242 			}
21243 		}
21244 		port = tcp->tcp_lport;
21245 		break;
21246 	case TI_GETPEERNAME:
21247 		if (tcp->tcp_family == AF_INET) {
21248 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21249 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
21250 				    v4addr);
21251 			} else {
21252 				/* can't return an address in this case */
21253 				v4addr = 0;
21254 			}
21255 		} else {
21256 			/* tcp->tcp_family == AF_INET6) */
21257 			v6addr = tcp->tcp_remote_v6;
21258 			if (tcp->tcp_ipversion == IPV6_VERSION) {
21259 				/*
21260 				 * No flowinfo if tcp->tcp_ipversion is v4.
21261 				 *
21262 				 * flowinfo was already initialized to zero
21263 				 * where it was declared above, so only
21264 				 * set it if ipversion is v6.
21265 				 */
21266 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
21267 				    ~IPV6_VERS_AND_FLOW_MASK;
21268 			}
21269 		}
21270 		port = tcp->tcp_fport;
21271 		break;
21272 	default:
21273 		mi_copy_done(q, mp, EPROTO);
21274 		return;
21275 	}
21276 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
21277 	if (!mp1)
21278 		return;
21279 
21280 	if (tcp->tcp_family == AF_INET) {
21281 		sin_t *sin;
21282 
21283 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
21284 		sin = (sin_t *)mp1->b_rptr;
21285 		mp1->b_wptr = (uchar_t *)&sin[1];
21286 		*sin = sin_null;
21287 		sin->sin_family = AF_INET;
21288 		sin->sin_addr.s_addr = v4addr;
21289 		sin->sin_port = port;
21290 	} else {
21291 		/* tcp->tcp_family == AF_INET6 */
21292 		sin6_t *sin6;
21293 
21294 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
21295 		sin6 = (sin6_t *)mp1->b_rptr;
21296 		mp1->b_wptr = (uchar_t *)&sin6[1];
21297 		*sin6 = sin6_null;
21298 		sin6->sin6_family = AF_INET6;
21299 		sin6->sin6_flowinfo = flowinfo;
21300 		sin6->sin6_addr = v6addr;
21301 		sin6->sin6_port = port;
21302 	}
21303 	/* Copy out the address */
21304 	mi_copyout(q, mp);
21305 }
21306 
21307 /*
21308  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
21309  * messages.
21310  */
21311 /* ARGSUSED */
21312 static void
21313 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
21314 {
21315 	conn_t 	*connp = (conn_t *)arg;
21316 	tcp_t	*tcp = connp->conn_tcp;
21317 	queue_t	*q = tcp->tcp_wq;
21318 	struct iocblk	*iocp;
21319 
21320 	ASSERT(DB_TYPE(mp) == M_IOCTL);
21321 	/*
21322 	 * Try and ASSERT the minimum possible references on the
21323 	 * conn early enough. Since we are executing on write side,
21324 	 * the connection is obviously not detached and that means
21325 	 * there is a ref each for TCP and IP. Since we are behind
21326 	 * the squeue, the minimum references needed are 3. If the
21327 	 * conn is in classifier hash list, there should be an
21328 	 * extra ref for that (we check both the possibilities).
21329 	 */
21330 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21331 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21332 
21333 	iocp = (struct iocblk *)mp->b_rptr;
21334 	switch (iocp->ioc_cmd) {
21335 	case TCP_IOC_DEFAULT_Q:
21336 		/* Wants to be the default wq. */
21337 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
21338 			iocp->ioc_error = EPERM;
21339 			iocp->ioc_count = 0;
21340 			mp->b_datap->db_type = M_IOCACK;
21341 			qreply(q, mp);
21342 			return;
21343 		}
21344 		tcp_def_q_set(tcp, mp);
21345 		return;
21346 	case SIOCPOPSOCKFS:
21347 		/*
21348 		 * sockfs is being I_POP'ed, reset the flag
21349 		 * indicating this
21350 		 */
21351 		tcp->tcp_issocket = B_FALSE;
21352 
21353 		/*
21354 		 * Insert this socket into the acceptor hash.
21355 		 * We might need it for T_CONN_RES message
21356 		 */
21357 #ifdef	_ILP32
21358 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
21359 #else
21360 		tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
21361 #endif
21362 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
21363 		mp->b_datap->db_type = M_IOCACK;
21364 		iocp->ioc_count = 0;
21365 		iocp->ioc_error = 0;
21366 		iocp->ioc_rval = 0;
21367 		qreply(q, mp);
21368 		return;
21369 	}
21370 	CALL_IP_WPUT(connp, q, mp);
21371 }
21372 
21373 /*
21374  * This routine is called by tcp_wput() to handle all TPI requests.
21375  */
21376 /* ARGSUSED */
21377 static void
21378 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
21379 {
21380 	conn_t 	*connp = (conn_t *)arg;
21381 	tcp_t	*tcp = connp->conn_tcp;
21382 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
21383 	uchar_t *rptr;
21384 	t_scalar_t type;
21385 	int len;
21386 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
21387 
21388 	/*
21389 	 * Try and ASSERT the minimum possible references on the
21390 	 * conn early enough. Since we are executing on write side,
21391 	 * the connection is obviously not detached and that means
21392 	 * there is a ref each for TCP and IP. Since we are behind
21393 	 * the squeue, the minimum references needed are 3. If the
21394 	 * conn is in classifier hash list, there should be an
21395 	 * extra ref for that (we check both the possibilities).
21396 	 */
21397 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
21398 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21399 
21400 	rptr = mp->b_rptr;
21401 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21402 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21403 		type = ((union T_primitives *)rptr)->type;
21404 		if (type == T_EXDATA_REQ) {
21405 			len = msgdsize(mp->b_cont) - 1;
21406 			if (len < 0) {
21407 				freemsg(mp);
21408 				return;
21409 			}
21410 			/*
21411 			 * Try to force urgent data out on the wire.
21412 			 * Even if we have unsent data this will
21413 			 * at least send the urgent flag.
21414 			 * XXX does not handle more flag correctly.
21415 			 */
21416 			len += tcp->tcp_unsent;
21417 			len += tcp->tcp_snxt;
21418 			tcp->tcp_urg = len;
21419 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21420 
21421 			/* Bypass tcp protocol for fused tcp loopback */
21422 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp))
21423 				return;
21424 		} else if (type != T_DATA_REQ) {
21425 			goto non_urgent_data;
21426 		}
21427 		/* TODO: options, flags, ... from user */
21428 		/* Set length to zero for reclamation below */
21429 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21430 		freeb(mp);
21431 		return;
21432 	} else {
21433 		if (tcp->tcp_debug) {
21434 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21435 			    "tcp_wput_proto, dropping one...");
21436 		}
21437 		freemsg(mp);
21438 		return;
21439 	}
21440 
21441 non_urgent_data:
21442 
21443 	switch ((int)tprim->type) {
21444 	case O_T_BIND_REQ:	/* bind request */
21445 	case T_BIND_REQ:	/* new semantics bind request */
21446 		tcp_bind(tcp, mp);
21447 		break;
21448 	case T_UNBIND_REQ:	/* unbind request */
21449 		tcp_unbind(tcp, mp);
21450 		break;
21451 	case O_T_CONN_RES:	/* old connection response XXX */
21452 	case T_CONN_RES:	/* connection response */
21453 		tcp_accept(tcp, mp);
21454 		break;
21455 	case T_CONN_REQ:	/* connection request */
21456 		tcp_connect(tcp, mp);
21457 		break;
21458 	case T_DISCON_REQ:	/* disconnect request */
21459 		tcp_disconnect(tcp, mp);
21460 		break;
21461 	case T_CAPABILITY_REQ:
21462 		tcp_capability_req(tcp, mp);	/* capability request */
21463 		break;
21464 	case T_INFO_REQ:	/* information request */
21465 		tcp_info_req(tcp, mp);
21466 		break;
21467 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21468 		/* Only IP is allowed to return meaningful value */
21469 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21470 		break;
21471 	case T_OPTMGMT_REQ:
21472 		/*
21473 		 * Note:  no support for snmpcom_req() through new
21474 		 * T_OPTMGMT_REQ. See comments in ip.c
21475 		 */
21476 		/* Only IP is allowed to return meaningful value */
21477 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21478 		break;
21479 
21480 	case T_UNITDATA_REQ:	/* unitdata request */
21481 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21482 		break;
21483 	case T_ORDREL_REQ:	/* orderly release req */
21484 		freemsg(mp);
21485 
21486 		if (tcp->tcp_fused)
21487 			tcp_unfuse(tcp);
21488 
21489 		if (tcp_xmit_end(tcp) != 0) {
21490 			/*
21491 			 * We were crossing FINs and got a reset from
21492 			 * the other side. Just ignore it.
21493 			 */
21494 			if (tcp->tcp_debug) {
21495 				(void) strlog(TCP_MODULE_ID, 0, 1,
21496 				    SL_ERROR|SL_TRACE,
21497 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21498 				    "state %s",
21499 				    tcp_display(tcp, NULL,
21500 				    DISP_ADDR_AND_PORT));
21501 			}
21502 		}
21503 		break;
21504 	case T_ADDR_REQ:
21505 		tcp_addr_req(tcp, mp);
21506 		break;
21507 	default:
21508 		if (tcp->tcp_debug) {
21509 			(void) strlog(TCP_MODULE_ID, 0, 1, SL_ERROR|SL_TRACE,
21510 			    "tcp_wput_proto, bogus TPI msg, type %d",
21511 			    tprim->type);
21512 		}
21513 		/*
21514 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21515 		 * to recover.
21516 		 */
21517 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21518 		break;
21519 	}
21520 }
21521 
21522 /*
21523  * The TCP write service routine should never be called...
21524  */
21525 /* ARGSUSED */
21526 static void
21527 tcp_wsrv(queue_t *q)
21528 {
21529 	TCP_STAT(tcp_wsrv_called);
21530 }
21531 
21532 /* Non overlapping byte exchanger */
21533 static void
21534 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21535 {
21536 	uchar_t	uch;
21537 
21538 	while (len-- > 0) {
21539 		uch = a[len];
21540 		a[len] = b[len];
21541 		b[len] = uch;
21542 	}
21543 }
21544 
21545 /*
21546  * Send out a control packet on the tcp connection specified.  This routine
21547  * is typically called where we need a simple ACK or RST generated.
21548  */
21549 static void
21550 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21551 {
21552 	uchar_t		*rptr;
21553 	tcph_t		*tcph;
21554 	ipha_t		*ipha = NULL;
21555 	ip6_t		*ip6h = NULL;
21556 	uint32_t	sum;
21557 	int		tcp_hdr_len;
21558 	int		tcp_ip_hdr_len;
21559 	mblk_t		*mp;
21560 
21561 	/*
21562 	 * Save sum for use in source route later.
21563 	 */
21564 	ASSERT(tcp != NULL);
21565 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21566 	tcp_hdr_len = tcp->tcp_hdr_len;
21567 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21568 
21569 	/* If a text string is passed in with the request, pass it to strlog. */
21570 	if (str != NULL && tcp->tcp_debug) {
21571 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21572 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21573 		    str, seq, ack, ctl);
21574 	}
21575 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21576 	    BPRI_MED);
21577 	if (mp == NULL) {
21578 		return;
21579 	}
21580 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21581 	mp->b_rptr = rptr;
21582 	mp->b_wptr = &rptr[tcp_hdr_len];
21583 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21584 
21585 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21586 		ipha = (ipha_t *)rptr;
21587 		ipha->ipha_length = htons(tcp_hdr_len);
21588 	} else {
21589 		ip6h = (ip6_t *)rptr;
21590 		ASSERT(tcp != NULL);
21591 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21592 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21593 	}
21594 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21595 	tcph->th_flags[0] = (uint8_t)ctl;
21596 	if (ctl & TH_RST) {
21597 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21598 		BUMP_MIB(&tcp_mib, tcpOutControl);
21599 		/*
21600 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21601 		 */
21602 		if (tcp->tcp_snd_ts_ok &&
21603 		    tcp->tcp_state > TCPS_SYN_SENT) {
21604 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21605 			*(mp->b_wptr) = TCPOPT_EOL;
21606 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21607 				ipha->ipha_length = htons(tcp_hdr_len -
21608 				    TCPOPT_REAL_TS_LEN);
21609 			} else {
21610 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21611 				    TCPOPT_REAL_TS_LEN);
21612 			}
21613 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21614 			sum -= TCPOPT_REAL_TS_LEN;
21615 		}
21616 	}
21617 	if (ctl & TH_ACK) {
21618 		if (tcp->tcp_snd_ts_ok) {
21619 			U32_TO_BE32(lbolt,
21620 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21621 			U32_TO_BE32(tcp->tcp_ts_recent,
21622 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21623 		}
21624 
21625 		/* Update the latest receive window size in TCP header. */
21626 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21627 		    tcph->th_win);
21628 		tcp->tcp_rack = ack;
21629 		tcp->tcp_rack_cnt = 0;
21630 		BUMP_MIB(&tcp_mib, tcpOutAck);
21631 	}
21632 	BUMP_LOCAL(tcp->tcp_obsegs);
21633 	U32_TO_BE32(seq, tcph->th_seq);
21634 	U32_TO_BE32(ack, tcph->th_ack);
21635 	/*
21636 	 * Include the adjustment for a source route if any.
21637 	 */
21638 	sum = (sum >> 16) + (sum & 0xFFFF);
21639 	U16_TO_BE16(sum, tcph->th_sum);
21640 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21641 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21642 }
21643 
21644 /*
21645  * If this routine returns B_TRUE, TCP can generate a RST in response
21646  * to a segment.  If it returns B_FALSE, TCP should not respond.
21647  */
21648 static boolean_t
21649 tcp_send_rst_chk(void)
21650 {
21651 	clock_t	now;
21652 
21653 	/*
21654 	 * TCP needs to protect itself from generating too many RSTs.
21655 	 * This can be a DoS attack by sending us random segments
21656 	 * soliciting RSTs.
21657 	 *
21658 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21659 	 * in each 1 second interval.  In this way, TCP still generate
21660 	 * RSTs in normal cases but when under attack, the impact is
21661 	 * limited.
21662 	 */
21663 	if (tcp_rst_sent_rate_enabled != 0) {
21664 		now = lbolt;
21665 		/* lbolt can wrap around. */
21666 		if ((tcp_last_rst_intrvl > now) ||
21667 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21668 			tcp_last_rst_intrvl = now;
21669 			tcp_rst_cnt = 1;
21670 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21671 			return (B_FALSE);
21672 		}
21673 	}
21674 	return (B_TRUE);
21675 }
21676 
21677 /*
21678  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21679  */
21680 static void
21681 tcp_ip_ire_mark_advice(tcp_t *tcp)
21682 {
21683 	mblk_t *mp;
21684 	ipic_t *ipic;
21685 
21686 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21687 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21688 		    &ipic);
21689 	} else {
21690 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21691 		    &ipic);
21692 	}
21693 	if (mp == NULL)
21694 		return;
21695 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21696 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21697 }
21698 
21699 /*
21700  * Return an IP advice ioctl mblk and set ipic to be the pointer
21701  * to the advice structure.
21702  */
21703 static mblk_t *
21704 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21705 {
21706 	struct iocblk *ioc;
21707 	mblk_t *mp, *mp1;
21708 
21709 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21710 	if (mp == NULL)
21711 		return (NULL);
21712 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21713 	*ipic = (ipic_t *)mp->b_rptr;
21714 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21715 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21716 
21717 	bcopy(addr, *ipic + 1, addr_len);
21718 
21719 	(*ipic)->ipic_addr_length = addr_len;
21720 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21721 
21722 	mp1 = mkiocb(IP_IOCTL);
21723 	if (mp1 == NULL) {
21724 		freemsg(mp);
21725 		return (NULL);
21726 	}
21727 	mp1->b_cont = mp;
21728 	ioc = (struct iocblk *)mp1->b_rptr;
21729 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21730 
21731 	return (mp1);
21732 }
21733 
21734 /*
21735  * Generate a reset based on an inbound packet for which there is no active
21736  * tcp state that we can find.
21737  *
21738  * IPSEC NOTE : Try to send the reply with the same protection as it came
21739  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21740  * the packet will go out at the same level of protection as it came in by
21741  * converting the IPSEC_IN to IPSEC_OUT.
21742  */
21743 static void
21744 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21745     uint32_t ack, int ctl, uint_t ip_hdr_len)
21746 {
21747 	ipha_t		*ipha = NULL;
21748 	ip6_t		*ip6h = NULL;
21749 	ushort_t	len;
21750 	tcph_t		*tcph;
21751 	int		i;
21752 	mblk_t		*ipsec_mp;
21753 	boolean_t	mctl_present;
21754 	ipic_t		*ipic;
21755 	ipaddr_t	v4addr;
21756 	in6_addr_t	v6addr;
21757 	int		addr_len;
21758 	void		*addr;
21759 	queue_t		*q = tcp_g_q;
21760 	tcp_t		*tcp = Q_TO_TCP(q);
21761 
21762 	if (!tcp_send_rst_chk()) {
21763 		tcp_rst_unsent++;
21764 		freemsg(mp);
21765 		return;
21766 	}
21767 
21768 	if (mp->b_datap->db_type == M_CTL) {
21769 		ipsec_mp = mp;
21770 		mp = mp->b_cont;
21771 		mctl_present = B_TRUE;
21772 	} else {
21773 		ipsec_mp = mp;
21774 		mctl_present = B_FALSE;
21775 	}
21776 
21777 	if (str && q && tcp_dbg) {
21778 		(void) strlog(TCP_MODULE_ID, 0, 1, SL_TRACE,
21779 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21780 		    "flags 0x%x",
21781 		    str, seq, ack, ctl);
21782 	}
21783 	if (mp->b_datap->db_ref != 1) {
21784 		mblk_t *mp1 = copyb(mp);
21785 		freemsg(mp);
21786 		mp = mp1;
21787 		if (!mp) {
21788 			if (mctl_present)
21789 				freeb(ipsec_mp);
21790 			return;
21791 		} else {
21792 			if (mctl_present) {
21793 				ipsec_mp->b_cont = mp;
21794 			} else {
21795 				ipsec_mp = mp;
21796 			}
21797 		}
21798 	} else if (mp->b_cont) {
21799 		freemsg(mp->b_cont);
21800 		mp->b_cont = NULL;
21801 	}
21802 	/*
21803 	 * We skip reversing source route here.
21804 	 * (for now we replace all IP options with EOL)
21805 	 */
21806 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21807 		ipha = (ipha_t *)mp->b_rptr;
21808 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21809 			mp->b_rptr[i] = IPOPT_EOL;
21810 		/*
21811 		 * Make sure that src address isn't flagrantly invalid.
21812 		 * Not all broadcast address checking for the src address
21813 		 * is possible, since we don't know the netmask of the src
21814 		 * addr.  No check for destination address is done, since
21815 		 * IP will not pass up a packet with a broadcast dest
21816 		 * address to TCP.  Similar checks are done below for IPv6.
21817 		 */
21818 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21819 		    CLASSD(ipha->ipha_src)) {
21820 			freemsg(ipsec_mp);
21821 			BUMP_MIB(&ip_mib, ipInDiscards);
21822 			return;
21823 		}
21824 	} else {
21825 		ip6h = (ip6_t *)mp->b_rptr;
21826 
21827 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21828 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21829 			freemsg(ipsec_mp);
21830 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21831 			return;
21832 		}
21833 
21834 		/* Remove any extension headers assuming partial overlay */
21835 		if (ip_hdr_len > IPV6_HDR_LEN) {
21836 			uint8_t *to;
21837 
21838 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21839 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21840 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21841 			ip_hdr_len = IPV6_HDR_LEN;
21842 			ip6h = (ip6_t *)mp->b_rptr;
21843 			ip6h->ip6_nxt = IPPROTO_TCP;
21844 		}
21845 	}
21846 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21847 	if (tcph->th_flags[0] & TH_RST) {
21848 		freemsg(ipsec_mp);
21849 		return;
21850 	}
21851 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21852 	len = ip_hdr_len + sizeof (tcph_t);
21853 	mp->b_wptr = &mp->b_rptr[len];
21854 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21855 		ipha->ipha_length = htons(len);
21856 		/* Swap addresses */
21857 		v4addr = ipha->ipha_src;
21858 		ipha->ipha_src = ipha->ipha_dst;
21859 		ipha->ipha_dst = v4addr;
21860 		ipha->ipha_ident = 0;
21861 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21862 		addr_len = IP_ADDR_LEN;
21863 		addr = &v4addr;
21864 	} else {
21865 		/* No ip6i_t in this case */
21866 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21867 		/* Swap addresses */
21868 		v6addr = ip6h->ip6_src;
21869 		ip6h->ip6_src = ip6h->ip6_dst;
21870 		ip6h->ip6_dst = v6addr;
21871 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21872 		addr_len = IPV6_ADDR_LEN;
21873 		addr = &v6addr;
21874 	}
21875 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21876 	U32_TO_BE32(ack, tcph->th_ack);
21877 	U32_TO_BE32(seq, tcph->th_seq);
21878 	U16_TO_BE16(0, tcph->th_win);
21879 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21880 	tcph->th_flags[0] = (uint8_t)ctl;
21881 	if (ctl & TH_RST) {
21882 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21883 		BUMP_MIB(&tcp_mib, tcpOutControl);
21884 	}
21885 	if (mctl_present) {
21886 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21887 
21888 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21889 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21890 			return;
21891 		}
21892 	}
21893 	/*
21894 	 * NOTE:  one might consider tracing a TCP packet here, but
21895 	 * this function has no active TCP state nd no tcp structure
21896 	 * which has trace buffer.  If we traced here, we would have
21897 	 * to keep a local trace buffer in tcp_record_trace().
21898 	 */
21899 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21900 
21901 	/*
21902 	 * Tell IP to mark the IRE used for this destination temporary.
21903 	 * This way, we can limit our exposure to DoS attack because IP
21904 	 * creates an IRE for each destination.  If there are too many,
21905 	 * the time to do any routing lookup will be extremely long.  And
21906 	 * the lookup can be in interrupt context.
21907 	 *
21908 	 * Note that in normal circumstances, this marking should not
21909 	 * affect anything.  It would be nice if only 1 message is
21910 	 * needed to inform IP that the IRE created for this RST should
21911 	 * not be added to the cache table.  But there is currently
21912 	 * not such communication mechanism between TCP and IP.  So
21913 	 * the best we can do now is to send the advice ioctl to IP
21914 	 * to mark the IRE temporary.
21915 	 */
21916 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21917 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21918 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21919 	}
21920 }
21921 
21922 /*
21923  * Initiate closedown sequence on an active connection.  (May be called as
21924  * writer.)  Return value zero for OK return, non-zero for error return.
21925  */
21926 static int
21927 tcp_xmit_end(tcp_t *tcp)
21928 {
21929 	ipic_t	*ipic;
21930 	mblk_t	*mp;
21931 
21932 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21933 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21934 		/*
21935 		 * Invalid state, only states TCPS_SYN_RCVD,
21936 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21937 		 */
21938 		return (-1);
21939 	}
21940 
21941 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21942 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21943 	/*
21944 	 * If there is nothing more unsent, send the FIN now.
21945 	 * Otherwise, it will go out with the last segment.
21946 	 */
21947 	if (tcp->tcp_unsent == 0) {
21948 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21949 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21950 
21951 		if (mp) {
21952 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21953 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21954 		} else {
21955 			/*
21956 			 * Couldn't allocate msg.  Pretend we got it out.
21957 			 * Wait for rexmit timeout.
21958 			 */
21959 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21960 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21961 		}
21962 
21963 		/*
21964 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21965 		 * changed.
21966 		 */
21967 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21968 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21969 		}
21970 	} else {
21971 		/*
21972 		 * If tcp->tcp_cork is set, then the data will not get sent,
21973 		 * so we have to check that and unset it first.
21974 		 */
21975 		if (tcp->tcp_cork)
21976 			tcp->tcp_cork = B_FALSE;
21977 		tcp_wput_data(tcp, NULL, B_FALSE);
21978 	}
21979 
21980 	/*
21981 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21982 	 * is 0, don't update the cache.
21983 	 */
21984 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21985 		return (0);
21986 
21987 	/*
21988 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21989 	 * different from the destination.
21990 	 */
21991 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21992 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21993 			return (0);
21994 		}
21995 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21996 		    &ipic);
21997 	} else {
21998 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21999 		    &tcp->tcp_ip6h->ip6_dst))) {
22000 			return (0);
22001 		}
22002 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22003 		    &ipic);
22004 	}
22005 
22006 	/* Record route attributes in the IRE for use by future connections. */
22007 	if (mp == NULL)
22008 		return (0);
22009 
22010 	/*
22011 	 * We do not have a good algorithm to update ssthresh at this time.
22012 	 * So don't do any update.
22013 	 */
22014 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
22015 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
22016 
22017 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22018 	return (0);
22019 }
22020 
22021 /*
22022  * Generate a "no listener here" RST in response to an "unknown" segment.
22023  * Note that we are reusing the incoming mp to construct the outgoing
22024  * RST.
22025  */
22026 void
22027 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
22028 {
22029 	uchar_t		*rptr;
22030 	uint32_t	seg_len;
22031 	tcph_t		*tcph;
22032 	uint32_t	seg_seq;
22033 	uint32_t	seg_ack;
22034 	uint_t		flags;
22035 	mblk_t		*ipsec_mp;
22036 	ipha_t 		*ipha;
22037 	ip6_t 		*ip6h;
22038 	boolean_t	mctl_present = B_FALSE;
22039 	boolean_t	check = B_TRUE;
22040 	boolean_t	policy_present;
22041 
22042 	TCP_STAT(tcp_no_listener);
22043 
22044 	ipsec_mp = mp;
22045 
22046 	if (mp->b_datap->db_type == M_CTL) {
22047 		ipsec_in_t *ii;
22048 
22049 		mctl_present = B_TRUE;
22050 		mp = mp->b_cont;
22051 
22052 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22053 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22054 		if (ii->ipsec_in_dont_check) {
22055 			check = B_FALSE;
22056 			if (!ii->ipsec_in_secure) {
22057 				freeb(ipsec_mp);
22058 				mctl_present = B_FALSE;
22059 				ipsec_mp = mp;
22060 			}
22061 		}
22062 	}
22063 
22064 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22065 		policy_present = ipsec_inbound_v4_policy_present;
22066 		ipha = (ipha_t *)mp->b_rptr;
22067 		ip6h = NULL;
22068 	} else {
22069 		policy_present = ipsec_inbound_v6_policy_present;
22070 		ipha = NULL;
22071 		ip6h = (ip6_t *)mp->b_rptr;
22072 	}
22073 
22074 	if (check && policy_present) {
22075 		/*
22076 		 * The conn_t parameter is NULL because we already know
22077 		 * nobody's home.
22078 		 */
22079 		ipsec_mp = ipsec_check_global_policy(
22080 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
22081 		if (ipsec_mp == NULL)
22082 			return;
22083 	}
22084 
22085 
22086 	rptr = mp->b_rptr;
22087 
22088 	tcph = (tcph_t *)&rptr[ip_hdr_len];
22089 	seg_seq = BE32_TO_U32(tcph->th_seq);
22090 	seg_ack = BE32_TO_U32(tcph->th_ack);
22091 	flags = tcph->th_flags[0];
22092 
22093 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
22094 	if (flags & TH_RST) {
22095 		freemsg(ipsec_mp);
22096 	} else if (flags & TH_ACK) {
22097 		tcp_xmit_early_reset("no tcp, reset",
22098 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
22099 	} else {
22100 		if (flags & TH_SYN) {
22101 			seg_len++;
22102 		} else {
22103 			/*
22104 			 * Here we violate the RFC.  Note that a normal
22105 			 * TCP will never send a segment without the ACK
22106 			 * flag, except for RST or SYN segment.  This
22107 			 * segment is neither.  Just drop it on the
22108 			 * floor.
22109 			 */
22110 			freemsg(ipsec_mp);
22111 			tcp_rst_unsent++;
22112 			return;
22113 		}
22114 
22115 		tcp_xmit_early_reset("no tcp, reset/ack",
22116 		    ipsec_mp, 0, seg_seq + seg_len,
22117 		    TH_RST | TH_ACK, ip_hdr_len);
22118 	}
22119 }
22120 
22121 /*
22122  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
22123  * ip and tcp header ready to pass down to IP.  If the mp passed in is
22124  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
22125  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
22126  * otherwise it will dup partial mblks.)
22127  * Otherwise, an appropriate ACK packet will be generated.  This
22128  * routine is not usually called to send new data for the first time.  It
22129  * is mostly called out of the timer for retransmits, and to generate ACKs.
22130  *
22131  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
22132  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
22133  * of the original mblk chain will be returned in *offset and *end_mp.
22134  */
22135 static mblk_t *
22136 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
22137     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
22138     boolean_t rexmit)
22139 {
22140 	int	data_length;
22141 	int32_t	off = 0;
22142 	uint_t	flags;
22143 	mblk_t	*mp1;
22144 	mblk_t	*mp2;
22145 	uchar_t	*rptr;
22146 	tcph_t	*tcph;
22147 	int32_t	num_sack_blk = 0;
22148 	int32_t	sack_opt_len = 0;
22149 
22150 	/* Allocate for our maximum TCP header + link-level */
22151 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
22152 	    BPRI_MED);
22153 	if (!mp1)
22154 		return (NULL);
22155 	data_length = 0;
22156 
22157 	/*
22158 	 * Note that tcp_mss has been adjusted to take into account the
22159 	 * timestamp option if applicable.  Because SACK options do not
22160 	 * appear in every TCP segments and they are of variable lengths,
22161 	 * they cannot be included in tcp_mss.  Thus we need to calculate
22162 	 * the actual segment length when we need to send a segment which
22163 	 * includes SACK options.
22164 	 */
22165 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22166 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22167 		    tcp->tcp_num_sack_blk);
22168 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22169 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22170 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
22171 			max_to_send -= sack_opt_len;
22172 	}
22173 
22174 	if (offset != NULL) {
22175 		off = *offset;
22176 		/* We use offset as an indicator that end_mp is not NULL. */
22177 		*end_mp = NULL;
22178 	}
22179 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
22180 		/* This could be faster with cooperation from downstream */
22181 		if (mp2 != mp1 && !sendall &&
22182 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
22183 		    max_to_send)
22184 			/*
22185 			 * Don't send the next mblk since the whole mblk
22186 			 * does not fit.
22187 			 */
22188 			break;
22189 		mp2->b_cont = dupb(mp);
22190 		mp2 = mp2->b_cont;
22191 		if (!mp2) {
22192 			freemsg(mp1);
22193 			return (NULL);
22194 		}
22195 		mp2->b_rptr += off;
22196 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
22197 		    (uintptr_t)INT_MAX);
22198 
22199 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
22200 		if (data_length > max_to_send) {
22201 			mp2->b_wptr -= data_length - max_to_send;
22202 			data_length = max_to_send;
22203 			off = mp2->b_wptr - mp->b_rptr;
22204 			break;
22205 		} else {
22206 			off = 0;
22207 		}
22208 	}
22209 	if (offset != NULL) {
22210 		*offset = off;
22211 		*end_mp = mp;
22212 	}
22213 	if (seg_len != NULL) {
22214 		*seg_len = data_length;
22215 	}
22216 
22217 	/* Update the latest receive window size in TCP header. */
22218 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22219 	    tcp->tcp_tcph->th_win);
22220 
22221 	rptr = mp1->b_rptr + tcp_wroff_xtra;
22222 	mp1->b_rptr = rptr;
22223 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
22224 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22225 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22226 	U32_TO_ABE32(seq, tcph->th_seq);
22227 
22228 	/*
22229 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
22230 	 * that this function was called from tcp_wput_data. Thus, when called
22231 	 * to retransmit data the setting of the PUSH bit may appear some
22232 	 * what random in that it might get set when it should not. This
22233 	 * should not pose any performance issues.
22234 	 */
22235 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
22236 	    tcp->tcp_unsent == data_length)) {
22237 		flags = TH_ACK | TH_PUSH;
22238 	} else {
22239 		flags = TH_ACK;
22240 	}
22241 
22242 	if (tcp->tcp_ecn_ok) {
22243 		if (tcp->tcp_ecn_echo_on)
22244 			flags |= TH_ECE;
22245 
22246 		/*
22247 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
22248 		 * There is no TCP flow control for non-data segments, and
22249 		 * only data segment is transmitted reliably.
22250 		 */
22251 		if (data_length > 0 && !rexmit) {
22252 			SET_ECT(tcp, rptr);
22253 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
22254 				flags |= TH_CWR;
22255 				tcp->tcp_ecn_cwr_sent = B_TRUE;
22256 			}
22257 		}
22258 	}
22259 
22260 	if (tcp->tcp_valid_bits) {
22261 		uint32_t u1;
22262 
22263 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
22264 		    seq == tcp->tcp_iss) {
22265 			uchar_t	*wptr;
22266 
22267 			/*
22268 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
22269 			 * TCP can only be in SYN-SENT, SYN-RCVD or
22270 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
22271 			 * our SYN is not ack'ed but the app closes this
22272 			 * TCP connection.
22273 			 */
22274 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
22275 			    tcp->tcp_state == TCPS_SYN_RCVD ||
22276 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
22277 
22278 			/*
22279 			 * Tack on the MSS option.  It is always needed
22280 			 * for both active and passive open.
22281 			 *
22282 			 * MSS option value should be interface MTU - MIN
22283 			 * TCP/IP header according to RFC 793 as it means
22284 			 * the maximum segment size TCP can receive.  But
22285 			 * to get around some broken middle boxes/end hosts
22286 			 * out there, we allow the option value to be the
22287 			 * same as the MSS option size on the peer side.
22288 			 * In this way, the other side will not send
22289 			 * anything larger than they can receive.
22290 			 *
22291 			 * Note that for SYN_SENT state, the ndd param
22292 			 * tcp_use_smss_as_mss_opt has no effect as we
22293 			 * don't know the peer's MSS option value. So
22294 			 * the only case we need to take care of is in
22295 			 * SYN_RCVD state, which is done later.
22296 			 */
22297 			wptr = mp1->b_wptr;
22298 			wptr[0] = TCPOPT_MAXSEG;
22299 			wptr[1] = TCPOPT_MAXSEG_LEN;
22300 			wptr += 2;
22301 			u1 = tcp->tcp_if_mtu -
22302 			    (tcp->tcp_ipversion == IPV4_VERSION ?
22303 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
22304 			    TCP_MIN_HEADER_LENGTH;
22305 			U16_TO_BE16(u1, wptr);
22306 			mp1->b_wptr = wptr + 2;
22307 			/* Update the offset to cover the additional word */
22308 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
22309 
22310 			/*
22311 			 * Note that the following way of filling in
22312 			 * TCP options are not optimal.  Some NOPs can
22313 			 * be saved.  But there is no need at this time
22314 			 * to optimize it.  When it is needed, we will
22315 			 * do it.
22316 			 */
22317 			switch (tcp->tcp_state) {
22318 			case TCPS_SYN_SENT:
22319 				flags = TH_SYN;
22320 
22321 				if (tcp->tcp_snd_ts_ok) {
22322 					uint32_t llbolt = (uint32_t)lbolt;
22323 
22324 					wptr = mp1->b_wptr;
22325 					wptr[0] = TCPOPT_NOP;
22326 					wptr[1] = TCPOPT_NOP;
22327 					wptr[2] = TCPOPT_TSTAMP;
22328 					wptr[3] = TCPOPT_TSTAMP_LEN;
22329 					wptr += 4;
22330 					U32_TO_BE32(llbolt, wptr);
22331 					wptr += 4;
22332 					ASSERT(tcp->tcp_ts_recent == 0);
22333 					U32_TO_BE32(0L, wptr);
22334 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22335 					tcph->th_offset_and_rsrvd[0] +=
22336 					    (3 << 4);
22337 				}
22338 
22339 				/*
22340 				 * Set up all the bits to tell other side
22341 				 * we are ECN capable.
22342 				 */
22343 				if (tcp->tcp_ecn_ok) {
22344 					flags |= (TH_ECE | TH_CWR);
22345 				}
22346 				break;
22347 			case TCPS_SYN_RCVD:
22348 				flags |= TH_SYN;
22349 
22350 				/*
22351 				 * Reset the MSS option value to be SMSS
22352 				 * We should probably add back the bytes
22353 				 * for timestamp option and IPsec.  We
22354 				 * don't do that as this is a workaround
22355 				 * for broken middle boxes/end hosts, it
22356 				 * is better for us to be more cautious.
22357 				 * They may not take these things into
22358 				 * account in their SMSS calculation.  Thus
22359 				 * the peer's calculated SMSS may be smaller
22360 				 * than what it can be.  This should be OK.
22361 				 */
22362 				if (tcp_use_smss_as_mss_opt) {
22363 					u1 = tcp->tcp_mss;
22364 					U16_TO_BE16(u1, wptr);
22365 				}
22366 
22367 				/*
22368 				 * If the other side is ECN capable, reply
22369 				 * that we are also ECN capable.
22370 				 */
22371 				if (tcp->tcp_ecn_ok)
22372 					flags |= TH_ECE;
22373 				break;
22374 			default:
22375 				/*
22376 				 * The above ASSERT() makes sure that this
22377 				 * must be FIN-WAIT-1 state.  Our SYN has
22378 				 * not been ack'ed so retransmit it.
22379 				 */
22380 				flags |= TH_SYN;
22381 				break;
22382 			}
22383 
22384 			if (tcp->tcp_snd_ws_ok) {
22385 				wptr = mp1->b_wptr;
22386 				wptr[0] =  TCPOPT_NOP;
22387 				wptr[1] =  TCPOPT_WSCALE;
22388 				wptr[2] =  TCPOPT_WS_LEN;
22389 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22390 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22391 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22392 			}
22393 
22394 			if (tcp->tcp_snd_sack_ok) {
22395 				wptr = mp1->b_wptr;
22396 				wptr[0] = TCPOPT_NOP;
22397 				wptr[1] = TCPOPT_NOP;
22398 				wptr[2] = TCPOPT_SACK_PERMITTED;
22399 				wptr[3] = TCPOPT_SACK_OK_LEN;
22400 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22401 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22402 			}
22403 
22404 			/* allocb() of adequate mblk assures space */
22405 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22406 			    (uintptr_t)INT_MAX);
22407 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22408 			/*
22409 			 * Get IP set to checksum on our behalf
22410 			 * Include the adjustment for a source route if any.
22411 			 */
22412 			u1 += tcp->tcp_sum;
22413 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22414 			U16_TO_BE16(u1, tcph->th_sum);
22415 			BUMP_MIB(&tcp_mib, tcpOutControl);
22416 		}
22417 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22418 		    (seq + data_length) == tcp->tcp_fss) {
22419 			if (!tcp->tcp_fin_acked) {
22420 				flags |= TH_FIN;
22421 				BUMP_MIB(&tcp_mib, tcpOutControl);
22422 			}
22423 			if (!tcp->tcp_fin_sent) {
22424 				tcp->tcp_fin_sent = B_TRUE;
22425 				switch (tcp->tcp_state) {
22426 				case TCPS_SYN_RCVD:
22427 				case TCPS_ESTABLISHED:
22428 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22429 					break;
22430 				case TCPS_CLOSE_WAIT:
22431 					tcp->tcp_state = TCPS_LAST_ACK;
22432 					break;
22433 				}
22434 				if (tcp->tcp_suna == tcp->tcp_snxt)
22435 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22436 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22437 			}
22438 		}
22439 		/*
22440 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22441 		 * is smaller than seq, u1 will become a very huge value.
22442 		 * So the comparison will fail.  Also note that tcp_urp
22443 		 * should be positive, see RFC 793 page 17.
22444 		 */
22445 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22446 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22447 		    u1 < (uint32_t)(64 * 1024)) {
22448 			flags |= TH_URG;
22449 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22450 			U32_TO_ABE16(u1, tcph->th_urp);
22451 		}
22452 	}
22453 	tcph->th_flags[0] = (uchar_t)flags;
22454 	tcp->tcp_rack = tcp->tcp_rnxt;
22455 	tcp->tcp_rack_cnt = 0;
22456 
22457 	if (tcp->tcp_snd_ts_ok) {
22458 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22459 			uint32_t llbolt = (uint32_t)lbolt;
22460 
22461 			U32_TO_BE32(llbolt,
22462 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22463 			U32_TO_BE32(tcp->tcp_ts_recent,
22464 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22465 		}
22466 	}
22467 
22468 	if (num_sack_blk > 0) {
22469 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22470 		sack_blk_t *tmp;
22471 		int32_t	i;
22472 
22473 		wptr[0] = TCPOPT_NOP;
22474 		wptr[1] = TCPOPT_NOP;
22475 		wptr[2] = TCPOPT_SACK;
22476 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22477 		    sizeof (sack_blk_t);
22478 		wptr += TCPOPT_REAL_SACK_LEN;
22479 
22480 		tmp = tcp->tcp_sack_list;
22481 		for (i = 0; i < num_sack_blk; i++) {
22482 			U32_TO_BE32(tmp[i].begin, wptr);
22483 			wptr += sizeof (tcp_seq);
22484 			U32_TO_BE32(tmp[i].end, wptr);
22485 			wptr += sizeof (tcp_seq);
22486 		}
22487 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22488 	}
22489 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22490 	data_length += (int)(mp1->b_wptr - rptr);
22491 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22492 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22493 	} else {
22494 		ip6_t *ip6 = (ip6_t *)(rptr +
22495 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22496 		    sizeof (ip6i_t) : 0));
22497 
22498 		ip6->ip6_plen = htons(data_length -
22499 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22500 	}
22501 
22502 	/*
22503 	 * Prime pump for IP
22504 	 * Include the adjustment for a source route if any.
22505 	 */
22506 	data_length -= tcp->tcp_ip_hdr_len;
22507 	data_length += tcp->tcp_sum;
22508 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22509 	U16_TO_ABE16(data_length, tcph->th_sum);
22510 	if (tcp->tcp_ip_forward_progress) {
22511 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22512 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22513 		tcp->tcp_ip_forward_progress = B_FALSE;
22514 	}
22515 	return (mp1);
22516 }
22517 
22518 /* This function handles the push timeout. */
22519 static void
22520 tcp_push_timer(void *arg)
22521 {
22522 	conn_t	*connp = (conn_t *)arg;
22523 	tcp_t *tcp = connp->conn_tcp;
22524 
22525 	TCP_DBGSTAT(tcp_push_timer_cnt);
22526 
22527 	ASSERT(tcp->tcp_listener == NULL);
22528 
22529 	tcp->tcp_push_tid = 0;
22530 	if ((tcp->tcp_rcv_list != NULL) &&
22531 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22532 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22533 }
22534 
22535 /*
22536  * This function handles delayed ACK timeout.
22537  */
22538 static void
22539 tcp_ack_timer(void *arg)
22540 {
22541 	conn_t	*connp = (conn_t *)arg;
22542 	tcp_t *tcp = connp->conn_tcp;
22543 	mblk_t *mp;
22544 
22545 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22546 
22547 	tcp->tcp_ack_tid = 0;
22548 
22549 	if (tcp->tcp_fused)
22550 		return;
22551 
22552 	/*
22553 	 * Do not send ACK if there is no outstanding unack'ed data.
22554 	 */
22555 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22556 		return;
22557 	}
22558 
22559 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22560 		/*
22561 		 * Make sure we don't allow deferred ACKs to result in
22562 		 * timer-based ACKing.  If we have held off an ACK
22563 		 * when there was more than an mss here, and the timer
22564 		 * goes off, we have to worry about the possibility
22565 		 * that the sender isn't doing slow-start, or is out
22566 		 * of step with us for some other reason.  We fall
22567 		 * permanently back in the direction of
22568 		 * ACK-every-other-packet as suggested in RFC 1122.
22569 		 */
22570 		if (tcp->tcp_rack_abs_max > 2)
22571 			tcp->tcp_rack_abs_max--;
22572 		tcp->tcp_rack_cur_max = 2;
22573 	}
22574 	mp = tcp_ack_mp(tcp);
22575 
22576 	if (mp != NULL) {
22577 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22578 		BUMP_LOCAL(tcp->tcp_obsegs);
22579 		BUMP_MIB(&tcp_mib, tcpOutAck);
22580 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22581 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22582 	}
22583 }
22584 
22585 
22586 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22587 static mblk_t *
22588 tcp_ack_mp(tcp_t *tcp)
22589 {
22590 	uint32_t	seq_no;
22591 
22592 	/*
22593 	 * There are a few cases to be considered while setting the sequence no.
22594 	 * Essentially, we can come here while processing an unacceptable pkt
22595 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22596 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22597 	 * If we are here for a zero window probe, stick with suna. In all
22598 	 * other cases, we check if suna + swnd encompasses snxt and set
22599 	 * the sequence number to snxt, if so. If snxt falls outside the
22600 	 * window (the receiver probably shrunk its window), we will go with
22601 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22602 	 * receiver.
22603 	 */
22604 	if (tcp->tcp_zero_win_probe) {
22605 		seq_no = tcp->tcp_suna;
22606 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22607 		ASSERT(tcp->tcp_swnd == 0);
22608 		seq_no = tcp->tcp_snxt;
22609 	} else {
22610 		seq_no = SEQ_GT(tcp->tcp_snxt,
22611 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22612 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22613 	}
22614 
22615 	if (tcp->tcp_valid_bits) {
22616 		/*
22617 		 * For the complex case where we have to send some
22618 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22619 		 */
22620 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22621 		    NULL, B_FALSE));
22622 	} else {
22623 		/* Generate a simple ACK */
22624 		int	data_length;
22625 		uchar_t	*rptr;
22626 		tcph_t	*tcph;
22627 		mblk_t	*mp1;
22628 		int32_t	tcp_hdr_len;
22629 		int32_t	tcp_tcp_hdr_len;
22630 		int32_t	num_sack_blk = 0;
22631 		int32_t sack_opt_len;
22632 
22633 		/*
22634 		 * Allocate space for TCP + IP headers
22635 		 * and link-level header
22636 		 */
22637 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22638 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22639 			    tcp->tcp_num_sack_blk);
22640 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22641 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22642 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22643 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22644 		} else {
22645 			tcp_hdr_len = tcp->tcp_hdr_len;
22646 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22647 		}
22648 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22649 		if (!mp1)
22650 			return (NULL);
22651 
22652 		/* Update the latest receive window size in TCP header. */
22653 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22654 		    tcp->tcp_tcph->th_win);
22655 		/* copy in prototype TCP + IP header */
22656 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22657 		mp1->b_rptr = rptr;
22658 		mp1->b_wptr = rptr + tcp_hdr_len;
22659 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22660 
22661 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22662 
22663 		/* Set the TCP sequence number. */
22664 		U32_TO_ABE32(seq_no, tcph->th_seq);
22665 
22666 		/* Set up the TCP flag field. */
22667 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22668 		if (tcp->tcp_ecn_echo_on)
22669 			tcph->th_flags[0] |= TH_ECE;
22670 
22671 		tcp->tcp_rack = tcp->tcp_rnxt;
22672 		tcp->tcp_rack_cnt = 0;
22673 
22674 		/* fill in timestamp option if in use */
22675 		if (tcp->tcp_snd_ts_ok) {
22676 			uint32_t llbolt = (uint32_t)lbolt;
22677 
22678 			U32_TO_BE32(llbolt,
22679 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22680 			U32_TO_BE32(tcp->tcp_ts_recent,
22681 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22682 		}
22683 
22684 		/* Fill in SACK options */
22685 		if (num_sack_blk > 0) {
22686 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22687 			sack_blk_t *tmp;
22688 			int32_t	i;
22689 
22690 			wptr[0] = TCPOPT_NOP;
22691 			wptr[1] = TCPOPT_NOP;
22692 			wptr[2] = TCPOPT_SACK;
22693 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22694 			    sizeof (sack_blk_t);
22695 			wptr += TCPOPT_REAL_SACK_LEN;
22696 
22697 			tmp = tcp->tcp_sack_list;
22698 			for (i = 0; i < num_sack_blk; i++) {
22699 				U32_TO_BE32(tmp[i].begin, wptr);
22700 				wptr += sizeof (tcp_seq);
22701 				U32_TO_BE32(tmp[i].end, wptr);
22702 				wptr += sizeof (tcp_seq);
22703 			}
22704 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22705 			    << 4);
22706 		}
22707 
22708 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22709 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22710 		} else {
22711 			/* Check for ip6i_t header in sticky hdrs */
22712 			ip6_t *ip6 = (ip6_t *)(rptr +
22713 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22714 			    sizeof (ip6i_t) : 0));
22715 
22716 			ip6->ip6_plen = htons(tcp_hdr_len -
22717 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22718 		}
22719 
22720 		/*
22721 		 * Prime pump for checksum calculation in IP.  Include the
22722 		 * adjustment for a source route if any.
22723 		 */
22724 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22725 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22726 		U16_TO_ABE16(data_length, tcph->th_sum);
22727 
22728 		if (tcp->tcp_ip_forward_progress) {
22729 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22730 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22731 			tcp->tcp_ip_forward_progress = B_FALSE;
22732 		}
22733 		return (mp1);
22734 	}
22735 }
22736 
22737 /*
22738  * To create a temporary tcp structure for inserting into bind hash list.
22739  * The parameter is assumed to be in network byte order, ready for use.
22740  */
22741 /* ARGSUSED */
22742 static tcp_t *
22743 tcp_alloc_temp_tcp(in_port_t port)
22744 {
22745 	conn_t	*connp;
22746 	tcp_t	*tcp;
22747 
22748 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22749 	if (connp == NULL)
22750 		return (NULL);
22751 
22752 	tcp = connp->conn_tcp;
22753 
22754 	/*
22755 	 * Only initialize the necessary info in those structures.  Note
22756 	 * that since INADDR_ANY is all 0, we do not need to set
22757 	 * tcp_bound_source to INADDR_ANY here.
22758 	 */
22759 	tcp->tcp_state = TCPS_BOUND;
22760 	tcp->tcp_lport = port;
22761 	tcp->tcp_exclbind = 1;
22762 	tcp->tcp_reserved_port = 1;
22763 
22764 	/* Just for place holding... */
22765 	tcp->tcp_ipversion = IPV4_VERSION;
22766 
22767 	return (tcp);
22768 }
22769 
22770 /*
22771  * To remove a port range specified by lo_port and hi_port from the
22772  * reserved port ranges.  This is one of the three public functions of
22773  * the reserved port interface.  Note that a port range has to be removed
22774  * as a whole.  Ports in a range cannot be removed individually.
22775  *
22776  * Params:
22777  *	in_port_t lo_port: the beginning port of the reserved port range to
22778  *		be deleted.
22779  *	in_port_t hi_port: the ending port of the reserved port range to
22780  *		be deleted.
22781  *
22782  * Return:
22783  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22784  */
22785 boolean_t
22786 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22787 {
22788 	int	i, j;
22789 	int	size;
22790 	tcp_t	**temp_tcp_array;
22791 	tcp_t	*tcp;
22792 
22793 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22794 
22795 	/* First make sure that the port ranage is indeed reserved. */
22796 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22797 		if (tcp_reserved_port[i].lo_port == lo_port) {
22798 			hi_port = tcp_reserved_port[i].hi_port;
22799 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22800 			break;
22801 		}
22802 	}
22803 	if (i == tcp_reserved_port_array_size) {
22804 		rw_exit(&tcp_reserved_port_lock);
22805 		return (B_FALSE);
22806 	}
22807 
22808 	/*
22809 	 * Remove the range from the array.  This simple loop is possible
22810 	 * because port ranges are inserted in ascending order.
22811 	 */
22812 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22813 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22814 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22815 		tcp_reserved_port[j].temp_tcp_array =
22816 		    tcp_reserved_port[j+1].temp_tcp_array;
22817 	}
22818 
22819 	/* Remove all the temporary tcp structures. */
22820 	size = hi_port - lo_port + 1;
22821 	while (size > 0) {
22822 		tcp = temp_tcp_array[size - 1];
22823 		ASSERT(tcp != NULL);
22824 		tcp_bind_hash_remove(tcp);
22825 		CONN_DEC_REF(tcp->tcp_connp);
22826 		size--;
22827 	}
22828 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22829 	tcp_reserved_port_array_size--;
22830 	rw_exit(&tcp_reserved_port_lock);
22831 	return (B_TRUE);
22832 }
22833 
22834 /*
22835  * Macro to remove temporary tcp structure from the bind hash list.  The
22836  * first parameter is the list of tcp to be removed.  The second parameter
22837  * is the number of tcps in the array.
22838  */
22839 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22840 { \
22841 	while ((num) > 0) { \
22842 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22843 		tf_t *tbf; \
22844 		tcp_t *tcpnext; \
22845 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22846 		mutex_enter(&tbf->tf_lock); \
22847 		tcpnext = tcp->tcp_bind_hash; \
22848 		if (tcpnext) { \
22849 			tcpnext->tcp_ptpbhn = \
22850 				tcp->tcp_ptpbhn; \
22851 		} \
22852 		*tcp->tcp_ptpbhn = tcpnext; \
22853 		mutex_exit(&tbf->tf_lock); \
22854 		kmem_free(tcp, sizeof (tcp_t)); \
22855 		(tcp_array)[(num) - 1] = NULL; \
22856 		(num)--; \
22857 	} \
22858 }
22859 
22860 /*
22861  * The public interface for other modules to call to reserve a port range
22862  * in TCP.  The caller passes in how large a port range it wants.  TCP
22863  * will try to find a range and return it via lo_port and hi_port.  This is
22864  * used by NCA's nca_conn_init.
22865  * NCA can only be used in the global zone so this only affects the global
22866  * zone's ports.
22867  *
22868  * Params:
22869  *	int size: the size of the port range to be reserved.
22870  *	in_port_t *lo_port (referenced): returns the beginning port of the
22871  *		reserved port range added.
22872  *	in_port_t *hi_port (referenced): returns the ending port of the
22873  *		reserved port range added.
22874  *
22875  * Return:
22876  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22877  */
22878 boolean_t
22879 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22880 {
22881 	tcp_t		*tcp;
22882 	tcp_t		*tmp_tcp;
22883 	tcp_t		**temp_tcp_array;
22884 	tf_t		*tbf;
22885 	in_port_t	net_port;
22886 	in_port_t	port;
22887 	int32_t		cur_size;
22888 	int		i, j;
22889 	boolean_t	used;
22890 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22891 	zoneid_t	zoneid = GLOBAL_ZONEID;
22892 
22893 	/* Sanity check. */
22894 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22895 		return (B_FALSE);
22896 	}
22897 
22898 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22899 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22900 		rw_exit(&tcp_reserved_port_lock);
22901 		return (B_FALSE);
22902 	}
22903 
22904 	/*
22905 	 * Find the starting port to try.  Since the port ranges are ordered
22906 	 * in the reserved port array, we can do a simple search here.
22907 	 */
22908 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22909 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22910 	for (i = 0; i < tcp_reserved_port_array_size;
22911 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22912 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22913 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22914 			break;
22915 		}
22916 	}
22917 	/* No available port range. */
22918 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22919 		rw_exit(&tcp_reserved_port_lock);
22920 		return (B_FALSE);
22921 	}
22922 
22923 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22924 	if (temp_tcp_array == NULL) {
22925 		rw_exit(&tcp_reserved_port_lock);
22926 		return (B_FALSE);
22927 	}
22928 
22929 	/* Go thru the port range to see if some ports are already bound. */
22930 	for (port = *lo_port, cur_size = 0;
22931 	    cur_size < size && port <= *hi_port;
22932 	    cur_size++, port++) {
22933 		used = B_FALSE;
22934 		net_port = htons(port);
22935 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22936 		mutex_enter(&tbf->tf_lock);
22937 		for (tcp = tbf->tf_tcp; tcp != NULL;
22938 		    tcp = tcp->tcp_bind_hash) {
22939 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22940 			    net_port == tcp->tcp_lport) {
22941 				/*
22942 				 * A port is already bound.  Search again
22943 				 * starting from port + 1.  Release all
22944 				 * temporary tcps.
22945 				 */
22946 				mutex_exit(&tbf->tf_lock);
22947 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22948 				*lo_port = port + 1;
22949 				cur_size = -1;
22950 				used = B_TRUE;
22951 				break;
22952 			}
22953 		}
22954 		if (!used) {
22955 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22956 				/*
22957 				 * Allocation failure.  Just fail the request.
22958 				 * Need to remove all those temporary tcp
22959 				 * structures.
22960 				 */
22961 				mutex_exit(&tbf->tf_lock);
22962 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22963 				rw_exit(&tcp_reserved_port_lock);
22964 				kmem_free(temp_tcp_array,
22965 				    (hi_port - lo_port + 1) *
22966 				    sizeof (tcp_t *));
22967 				return (B_FALSE);
22968 			}
22969 			temp_tcp_array[cur_size] = tmp_tcp;
22970 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22971 			mutex_exit(&tbf->tf_lock);
22972 		}
22973 	}
22974 
22975 	/*
22976 	 * The current range is not large enough.  We can actually do another
22977 	 * search if this search is done between 2 reserved port ranges.  But
22978 	 * for first release, we just stop here and return saying that no port
22979 	 * range is available.
22980 	 */
22981 	if (cur_size < size) {
22982 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22983 		rw_exit(&tcp_reserved_port_lock);
22984 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22985 		return (B_FALSE);
22986 	}
22987 	*hi_port = port - 1;
22988 
22989 	/*
22990 	 * Insert range into array in ascending order.  Since this function
22991 	 * must not be called often, we choose to use the simplest method.
22992 	 * The above array should not consume excessive stack space as
22993 	 * the size must be very small.  If in future releases, we find
22994 	 * that we should provide more reserved port ranges, this function
22995 	 * has to be modified to be more efficient.
22996 	 */
22997 	if (tcp_reserved_port_array_size == 0) {
22998 		tcp_reserved_port[0].lo_port = *lo_port;
22999 		tcp_reserved_port[0].hi_port = *hi_port;
23000 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
23001 	} else {
23002 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
23003 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
23004 				tmp_ports[j].lo_port = *lo_port;
23005 				tmp_ports[j].hi_port = *hi_port;
23006 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
23007 				j++;
23008 			}
23009 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
23010 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
23011 			tmp_ports[j].temp_tcp_array =
23012 			    tcp_reserved_port[i].temp_tcp_array;
23013 		}
23014 		if (j == i) {
23015 			tmp_ports[j].lo_port = *lo_port;
23016 			tmp_ports[j].hi_port = *hi_port;
23017 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
23018 		}
23019 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
23020 	}
23021 	tcp_reserved_port_array_size++;
23022 	rw_exit(&tcp_reserved_port_lock);
23023 	return (B_TRUE);
23024 }
23025 
23026 /*
23027  * Check to see if a port is in any reserved port range.
23028  *
23029  * Params:
23030  *	in_port_t port: the port to be verified.
23031  *
23032  * Return:
23033  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
23034  */
23035 boolean_t
23036 tcp_reserved_port_check(in_port_t port)
23037 {
23038 	int i;
23039 
23040 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23041 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23042 		if (port >= tcp_reserved_port[i].lo_port ||
23043 		    port <= tcp_reserved_port[i].hi_port) {
23044 			rw_exit(&tcp_reserved_port_lock);
23045 			return (B_TRUE);
23046 		}
23047 	}
23048 	rw_exit(&tcp_reserved_port_lock);
23049 	return (B_FALSE);
23050 }
23051 
23052 /*
23053  * To list all reserved port ranges.  This is the function to handle
23054  * ndd tcp_reserved_port_list.
23055  */
23056 /* ARGSUSED */
23057 static int
23058 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23059 {
23060 	int i;
23061 
23062 	rw_enter(&tcp_reserved_port_lock, RW_READER);
23063 	if (tcp_reserved_port_array_size > 0)
23064 		(void) mi_mpprintf(mp, "The following ports are reserved:");
23065 	else
23066 		(void) mi_mpprintf(mp, "No port is reserved.");
23067 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
23068 		(void) mi_mpprintf(mp, "%d-%d",
23069 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
23070 	}
23071 	rw_exit(&tcp_reserved_port_lock);
23072 	return (0);
23073 }
23074 
23075 /*
23076  * Hash list insertion routine for tcp_t structures.
23077  * Inserts entries with the ones bound to a specific IP address first
23078  * followed by those bound to INADDR_ANY.
23079  */
23080 static void
23081 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23082 {
23083 	tcp_t	**tcpp;
23084 	tcp_t	*tcpnext;
23085 
23086 	if (tcp->tcp_ptpbhn != NULL) {
23087 		ASSERT(!caller_holds_lock);
23088 		tcp_bind_hash_remove(tcp);
23089 	}
23090 	tcpp = &tbf->tf_tcp;
23091 	if (!caller_holds_lock) {
23092 		mutex_enter(&tbf->tf_lock);
23093 	} else {
23094 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23095 	}
23096 	tcpnext = tcpp[0];
23097 	if (tcpnext) {
23098 		/*
23099 		 * If the new tcp bound to the INADDR_ANY address
23100 		 * and the first one in the list is not bound to
23101 		 * INADDR_ANY we skip all entries until we find the
23102 		 * first one bound to INADDR_ANY.
23103 		 * This makes sure that applications binding to a
23104 		 * specific address get preference over those binding to
23105 		 * INADDR_ANY.
23106 		 */
23107 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23108 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23109 			while ((tcpnext = tcpp[0]) != NULL &&
23110 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23111 				tcpp = &(tcpnext->tcp_bind_hash);
23112 			if (tcpnext)
23113 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23114 		} else
23115 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
23116 	}
23117 	tcp->tcp_bind_hash = tcpnext;
23118 	tcp->tcp_ptpbhn = tcpp;
23119 	tcpp[0] = tcp;
23120 	if (!caller_holds_lock)
23121 		mutex_exit(&tbf->tf_lock);
23122 }
23123 
23124 /*
23125  * Hash list removal routine for tcp_t structures.
23126  */
23127 static void
23128 tcp_bind_hash_remove(tcp_t *tcp)
23129 {
23130 	tcp_t	*tcpnext;
23131 	kmutex_t *lockp;
23132 
23133 	if (tcp->tcp_ptpbhn == NULL)
23134 		return;
23135 
23136 	/*
23137 	 * Extract the lock pointer in case there are concurrent
23138 	 * hash_remove's for this instance.
23139 	 */
23140 	ASSERT(tcp->tcp_lport != 0);
23141 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23142 
23143 	ASSERT(lockp != NULL);
23144 	mutex_enter(lockp);
23145 	if (tcp->tcp_ptpbhn) {
23146 		tcpnext = tcp->tcp_bind_hash;
23147 		if (tcpnext) {
23148 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23149 			tcp->tcp_bind_hash = NULL;
23150 		}
23151 		*tcp->tcp_ptpbhn = tcpnext;
23152 		tcp->tcp_ptpbhn = NULL;
23153 	}
23154 	mutex_exit(lockp);
23155 }
23156 
23157 
23158 /*
23159  * Hash list lookup routine for tcp_t structures.
23160  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
23161  */
23162 static tcp_t *
23163 tcp_acceptor_hash_lookup(t_uscalar_t id)
23164 {
23165 	tf_t	*tf;
23166 	tcp_t	*tcp;
23167 
23168 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23169 	mutex_enter(&tf->tf_lock);
23170 	for (tcp = tf->tf_tcp; tcp != NULL;
23171 	    tcp = tcp->tcp_acceptor_hash) {
23172 		if (tcp->tcp_acceptor_id == id) {
23173 			CONN_INC_REF(tcp->tcp_connp);
23174 			mutex_exit(&tf->tf_lock);
23175 			return (tcp);
23176 		}
23177 	}
23178 	mutex_exit(&tf->tf_lock);
23179 	return (NULL);
23180 }
23181 
23182 
23183 /*
23184  * Hash list insertion routine for tcp_t structures.
23185  */
23186 void
23187 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
23188 {
23189 	tf_t	*tf;
23190 	tcp_t	**tcpp;
23191 	tcp_t	*tcpnext;
23192 
23193 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
23194 
23195 	if (tcp->tcp_ptpahn != NULL)
23196 		tcp_acceptor_hash_remove(tcp);
23197 	tcpp = &tf->tf_tcp;
23198 	mutex_enter(&tf->tf_lock);
23199 	tcpnext = tcpp[0];
23200 	if (tcpnext)
23201 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
23202 	tcp->tcp_acceptor_hash = tcpnext;
23203 	tcp->tcp_ptpahn = tcpp;
23204 	tcpp[0] = tcp;
23205 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
23206 	mutex_exit(&tf->tf_lock);
23207 }
23208 
23209 /*
23210  * Hash list removal routine for tcp_t structures.
23211  */
23212 static void
23213 tcp_acceptor_hash_remove(tcp_t *tcp)
23214 {
23215 	tcp_t	*tcpnext;
23216 	kmutex_t *lockp;
23217 
23218 	/*
23219 	 * Extract the lock pointer in case there are concurrent
23220 	 * hash_remove's for this instance.
23221 	 */
23222 	lockp = tcp->tcp_acceptor_lockp;
23223 
23224 	if (tcp->tcp_ptpahn == NULL)
23225 		return;
23226 
23227 	ASSERT(lockp != NULL);
23228 	mutex_enter(lockp);
23229 	if (tcp->tcp_ptpahn) {
23230 		tcpnext = tcp->tcp_acceptor_hash;
23231 		if (tcpnext) {
23232 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
23233 			tcp->tcp_acceptor_hash = NULL;
23234 		}
23235 		*tcp->tcp_ptpahn = tcpnext;
23236 		tcp->tcp_ptpahn = NULL;
23237 	}
23238 	mutex_exit(lockp);
23239 	tcp->tcp_acceptor_lockp = NULL;
23240 }
23241 
23242 /* ARGSUSED */
23243 static int
23244 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
23245 {
23246 	int error = 0;
23247 	int retval;
23248 	char *end;
23249 
23250 	tcp_hsp_t *hsp;
23251 	tcp_hsp_t *hspprev;
23252 
23253 	ipaddr_t addr = 0;		/* Address we're looking for */
23254 	in6_addr_t v6addr;		/* Address we're looking for */
23255 	uint32_t hash;			/* Hash of that address */
23256 
23257 	/*
23258 	 * If the following variables are still zero after parsing the input
23259 	 * string, the user didn't specify them and we don't change them in
23260 	 * the HSP.
23261 	 */
23262 
23263 	ipaddr_t mask = 0;		/* Subnet mask */
23264 	in6_addr_t v6mask;
23265 	long sendspace = 0;		/* Send buffer size */
23266 	long recvspace = 0;		/* Receive buffer size */
23267 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
23268 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
23269 
23270 	rw_enter(&tcp_hsp_lock, RW_WRITER);
23271 
23272 	/* Parse and validate address */
23273 	if (af == AF_INET) {
23274 		retval = inet_pton(af, value, &addr);
23275 		if (retval == 1)
23276 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
23277 	} else if (af == AF_INET6) {
23278 		retval = inet_pton(af, value, &v6addr);
23279 	} else {
23280 		error = EINVAL;
23281 		goto done;
23282 	}
23283 	if (retval == 0) {
23284 		error = EINVAL;
23285 		goto done;
23286 	}
23287 
23288 	while ((*value) && *value != ' ')
23289 		value++;
23290 
23291 	/* Parse individual keywords, set variables if found */
23292 	while (*value) {
23293 		/* Skip leading blanks */
23294 
23295 		while (*value == ' ' || *value == '\t')
23296 			value++;
23297 
23298 		/* If at end of string, we're done */
23299 
23300 		if (!*value)
23301 			break;
23302 
23303 		/* We have a word, figure out what it is */
23304 
23305 		if (strncmp("mask", value, 4) == 0) {
23306 			value += 4;
23307 			while (*value == ' ' || *value == '\t')
23308 				value++;
23309 			/* Parse subnet mask */
23310 			if (af == AF_INET) {
23311 				retval = inet_pton(af, value, &mask);
23312 				if (retval == 1) {
23313 					V4MASK_TO_V6(mask, v6mask);
23314 				}
23315 			} else if (af == AF_INET6) {
23316 				retval = inet_pton(af, value, &v6mask);
23317 			}
23318 			if (retval != 1) {
23319 				error = EINVAL;
23320 				goto done;
23321 			}
23322 			while ((*value) && *value != ' ')
23323 				value++;
23324 		} else if (strncmp("sendspace", value, 9) == 0) {
23325 			value += 9;
23326 
23327 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23328 			    sendspace < TCP_XMIT_HIWATER ||
23329 			    sendspace >= (1L<<30)) {
23330 				error = EINVAL;
23331 				goto done;
23332 			}
23333 			value = end;
23334 		} else if (strncmp("recvspace", value, 9) == 0) {
23335 			value += 9;
23336 
23337 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23338 			    recvspace < TCP_RECV_HIWATER ||
23339 			    recvspace >= (1L<<30)) {
23340 				error = EINVAL;
23341 				goto done;
23342 			}
23343 			value = end;
23344 		} else if (strncmp("timestamp", value, 9) == 0) {
23345 			value += 9;
23346 
23347 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23348 			    timestamp < 0 || timestamp > 1) {
23349 				error = EINVAL;
23350 				goto done;
23351 			}
23352 
23353 			/*
23354 			 * We increment timestamp so we know it's been set;
23355 			 * this is undone when we put it in the HSP
23356 			 */
23357 			timestamp++;
23358 			value = end;
23359 		} else if (strncmp("delete", value, 6) == 0) {
23360 			value += 6;
23361 			delete = B_TRUE;
23362 		} else {
23363 			error = EINVAL;
23364 			goto done;
23365 		}
23366 	}
23367 
23368 	/* Hash address for lookup */
23369 
23370 	hash = TCP_HSP_HASH(addr);
23371 
23372 	if (delete) {
23373 		/*
23374 		 * Note that deletes don't return an error if the thing
23375 		 * we're trying to delete isn't there.
23376 		 */
23377 		if (tcp_hsp_hash == NULL)
23378 			goto done;
23379 		hsp = tcp_hsp_hash[hash];
23380 
23381 		if (hsp) {
23382 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23383 			    &v6addr)) {
23384 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23385 				mi_free((char *)hsp);
23386 			} else {
23387 				hspprev = hsp;
23388 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23389 					if (IN6_ARE_ADDR_EQUAL(
23390 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23391 						hspprev->tcp_hsp_next =
23392 						    hsp->tcp_hsp_next;
23393 						mi_free((char *)hsp);
23394 						break;
23395 					}
23396 					hspprev = hsp;
23397 				}
23398 			}
23399 		}
23400 	} else {
23401 		/*
23402 		 * We're adding/modifying an HSP.  If we haven't already done
23403 		 * so, allocate the hash table.
23404 		 */
23405 
23406 		if (!tcp_hsp_hash) {
23407 			tcp_hsp_hash = (tcp_hsp_t **)
23408 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23409 			if (!tcp_hsp_hash) {
23410 				error = EINVAL;
23411 				goto done;
23412 			}
23413 		}
23414 
23415 		/* Get head of hash chain */
23416 
23417 		hsp = tcp_hsp_hash[hash];
23418 
23419 		/* Try to find pre-existing hsp on hash chain */
23420 		/* Doesn't handle CIDR prefixes. */
23421 		while (hsp) {
23422 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23423 				break;
23424 			hsp = hsp->tcp_hsp_next;
23425 		}
23426 
23427 		/*
23428 		 * If we didn't, create one with default values and put it
23429 		 * at head of hash chain
23430 		 */
23431 
23432 		if (!hsp) {
23433 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23434 			if (!hsp) {
23435 				error = EINVAL;
23436 				goto done;
23437 			}
23438 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23439 			tcp_hsp_hash[hash] = hsp;
23440 		}
23441 
23442 		/* Set values that the user asked us to change */
23443 
23444 		hsp->tcp_hsp_addr_v6 = v6addr;
23445 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23446 			hsp->tcp_hsp_vers = IPV4_VERSION;
23447 		else
23448 			hsp->tcp_hsp_vers = IPV6_VERSION;
23449 		hsp->tcp_hsp_subnet_v6 = v6mask;
23450 		if (sendspace > 0)
23451 			hsp->tcp_hsp_sendspace = sendspace;
23452 		if (recvspace > 0)
23453 			hsp->tcp_hsp_recvspace = recvspace;
23454 		if (timestamp > 0)
23455 			hsp->tcp_hsp_tstamp = timestamp - 1;
23456 	}
23457 
23458 done:
23459 	rw_exit(&tcp_hsp_lock);
23460 	return (error);
23461 }
23462 
23463 /* Set callback routine passed to nd_load by tcp_param_register. */
23464 /* ARGSUSED */
23465 static int
23466 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23467 {
23468 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23469 }
23470 /* ARGSUSED */
23471 static int
23472 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23473     cred_t *cr)
23474 {
23475 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23476 }
23477 
23478 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23479 /* ARGSUSED */
23480 static int
23481 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23482 {
23483 	tcp_hsp_t *hsp;
23484 	int i;
23485 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23486 
23487 	rw_enter(&tcp_hsp_lock, RW_READER);
23488 	(void) mi_mpprintf(mp,
23489 	    "Hash HSP     " MI_COL_HDRPAD_STR
23490 	    "Address         Subnet Mask     Send       Receive    TStamp");
23491 	if (tcp_hsp_hash) {
23492 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23493 			hsp = tcp_hsp_hash[i];
23494 			while (hsp) {
23495 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23496 					(void) inet_ntop(AF_INET,
23497 					    &hsp->tcp_hsp_addr,
23498 					    addrbuf, sizeof (addrbuf));
23499 					(void) inet_ntop(AF_INET,
23500 					    &hsp->tcp_hsp_subnet,
23501 					    subnetbuf, sizeof (subnetbuf));
23502 				} else {
23503 					(void) inet_ntop(AF_INET6,
23504 					    &hsp->tcp_hsp_addr_v6,
23505 					    addrbuf, sizeof (addrbuf));
23506 					(void) inet_ntop(AF_INET6,
23507 					    &hsp->tcp_hsp_subnet_v6,
23508 					    subnetbuf, sizeof (subnetbuf));
23509 				}
23510 				(void) mi_mpprintf(mp,
23511 				    " %03d " MI_COL_PTRFMT_STR
23512 				    "%s %s %010d %010d      %d",
23513 				    i,
23514 				    (void *)hsp,
23515 				    addrbuf,
23516 				    subnetbuf,
23517 				    hsp->tcp_hsp_sendspace,
23518 				    hsp->tcp_hsp_recvspace,
23519 				    hsp->tcp_hsp_tstamp);
23520 
23521 				hsp = hsp->tcp_hsp_next;
23522 			}
23523 		}
23524 	}
23525 	rw_exit(&tcp_hsp_lock);
23526 	return (0);
23527 }
23528 
23529 
23530 /* Data for fast netmask macro used by tcp_hsp_lookup */
23531 
23532 static ipaddr_t netmasks[] = {
23533 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23534 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23535 };
23536 
23537 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23538 
23539 /*
23540  * XXX This routine should go away and instead we should use the metrics
23541  * associated with the routes to determine the default sndspace and rcvspace.
23542  */
23543 static tcp_hsp_t *
23544 tcp_hsp_lookup(ipaddr_t addr)
23545 {
23546 	tcp_hsp_t *hsp = NULL;
23547 
23548 	/* Quick check without acquiring the lock. */
23549 	if (tcp_hsp_hash == NULL)
23550 		return (NULL);
23551 
23552 	rw_enter(&tcp_hsp_lock, RW_READER);
23553 
23554 	/* This routine finds the best-matching HSP for address addr. */
23555 
23556 	if (tcp_hsp_hash) {
23557 		int i;
23558 		ipaddr_t srchaddr;
23559 		tcp_hsp_t *hsp_net;
23560 
23561 		/* We do three passes: host, network, and subnet. */
23562 
23563 		srchaddr = addr;
23564 
23565 		for (i = 1; i <= 3; i++) {
23566 			/* Look for exact match on srchaddr */
23567 
23568 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23569 			while (hsp) {
23570 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23571 				    hsp->tcp_hsp_addr == srchaddr)
23572 					break;
23573 				hsp = hsp->tcp_hsp_next;
23574 			}
23575 			ASSERT(hsp == NULL ||
23576 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23577 
23578 			/*
23579 			 * If this is the first pass:
23580 			 *   If we found a match, great, return it.
23581 			 *   If not, search for the network on the second pass.
23582 			 */
23583 
23584 			if (i == 1)
23585 				if (hsp)
23586 					break;
23587 				else
23588 				{
23589 					srchaddr = addr & netmask(addr);
23590 					continue;
23591 				}
23592 
23593 			/*
23594 			 * If this is the second pass:
23595 			 *   If we found a match, but there's a subnet mask,
23596 			 *    save the match but try again using the subnet
23597 			 *    mask on the third pass.
23598 			 *   Otherwise, return whatever we found.
23599 			 */
23600 
23601 			if (i == 2) {
23602 				if (hsp && hsp->tcp_hsp_subnet) {
23603 					hsp_net = hsp;
23604 					srchaddr = addr & hsp->tcp_hsp_subnet;
23605 					continue;
23606 				} else {
23607 					break;
23608 				}
23609 			}
23610 
23611 			/*
23612 			 * This must be the third pass.  If we didn't find
23613 			 * anything, return the saved network HSP instead.
23614 			 */
23615 
23616 			if (!hsp)
23617 				hsp = hsp_net;
23618 		}
23619 	}
23620 
23621 	rw_exit(&tcp_hsp_lock);
23622 	return (hsp);
23623 }
23624 
23625 /*
23626  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23627  * match lookup.
23628  */
23629 static tcp_hsp_t *
23630 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23631 {
23632 	tcp_hsp_t *hsp = NULL;
23633 
23634 	/* Quick check without acquiring the lock. */
23635 	if (tcp_hsp_hash == NULL)
23636 		return (NULL);
23637 
23638 	rw_enter(&tcp_hsp_lock, RW_READER);
23639 
23640 	/* This routine finds the best-matching HSP for address addr. */
23641 
23642 	if (tcp_hsp_hash) {
23643 		int i;
23644 		in6_addr_t v6srchaddr;
23645 		tcp_hsp_t *hsp_net;
23646 
23647 		/* We do three passes: host, network, and subnet. */
23648 
23649 		v6srchaddr = *v6addr;
23650 
23651 		for (i = 1; i <= 3; i++) {
23652 			/* Look for exact match on srchaddr */
23653 
23654 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23655 			    V4_PART_OF_V6(v6srchaddr))];
23656 			while (hsp) {
23657 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23658 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23659 				    &v6srchaddr))
23660 					break;
23661 				hsp = hsp->tcp_hsp_next;
23662 			}
23663 
23664 			/*
23665 			 * If this is the first pass:
23666 			 *   If we found a match, great, return it.
23667 			 *   If not, search for the network on the second pass.
23668 			 */
23669 
23670 			if (i == 1)
23671 				if (hsp)
23672 					break;
23673 				else {
23674 					/* Assume a 64 bit mask */
23675 					v6srchaddr.s6_addr32[0] =
23676 					    v6addr->s6_addr32[0];
23677 					v6srchaddr.s6_addr32[1] =
23678 					    v6addr->s6_addr32[1];
23679 					v6srchaddr.s6_addr32[2] = 0;
23680 					v6srchaddr.s6_addr32[3] = 0;
23681 					continue;
23682 				}
23683 
23684 			/*
23685 			 * If this is the second pass:
23686 			 *   If we found a match, but there's a subnet mask,
23687 			 *    save the match but try again using the subnet
23688 			 *    mask on the third pass.
23689 			 *   Otherwise, return whatever we found.
23690 			 */
23691 
23692 			if (i == 2) {
23693 				ASSERT(hsp == NULL ||
23694 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23695 				if (hsp &&
23696 				    !IN6_IS_ADDR_UNSPECIFIED(
23697 				    &hsp->tcp_hsp_subnet_v6)) {
23698 					hsp_net = hsp;
23699 					V6_MASK_COPY(*v6addr,
23700 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23701 					continue;
23702 				} else {
23703 					break;
23704 				}
23705 			}
23706 
23707 			/*
23708 			 * This must be the third pass.  If we didn't find
23709 			 * anything, return the saved network HSP instead.
23710 			 */
23711 
23712 			if (!hsp)
23713 				hsp = hsp_net;
23714 		}
23715 	}
23716 
23717 	rw_exit(&tcp_hsp_lock);
23718 	return (hsp);
23719 }
23720 
23721 /*
23722  * Type three generator adapted from the random() function in 4.4 BSD:
23723  */
23724 
23725 /*
23726  * Copyright (c) 1983, 1993
23727  *	The Regents of the University of California.  All rights reserved.
23728  *
23729  * Redistribution and use in source and binary forms, with or without
23730  * modification, are permitted provided that the following conditions
23731  * are met:
23732  * 1. Redistributions of source code must retain the above copyright
23733  *    notice, this list of conditions and the following disclaimer.
23734  * 2. Redistributions in binary form must reproduce the above copyright
23735  *    notice, this list of conditions and the following disclaimer in the
23736  *    documentation and/or other materials provided with the distribution.
23737  * 3. All advertising materials mentioning features or use of this software
23738  *    must display the following acknowledgement:
23739  *	This product includes software developed by the University of
23740  *	California, Berkeley and its contributors.
23741  * 4. Neither the name of the University nor the names of its contributors
23742  *    may be used to endorse or promote products derived from this software
23743  *    without specific prior written permission.
23744  *
23745  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23746  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23747  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23748  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23749  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23750  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23751  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23752  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23753  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23754  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23755  * SUCH DAMAGE.
23756  */
23757 
23758 /* Type 3 -- x**31 + x**3 + 1 */
23759 #define	DEG_3		31
23760 #define	SEP_3		3
23761 
23762 
23763 /* Protected by tcp_random_lock */
23764 static int tcp_randtbl[DEG_3 + 1];
23765 
23766 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23767 static int *tcp_random_rptr = &tcp_randtbl[1];
23768 
23769 static int *tcp_random_state = &tcp_randtbl[1];
23770 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23771 
23772 kmutex_t tcp_random_lock;
23773 
23774 void
23775 tcp_random_init(void)
23776 {
23777 	int i;
23778 	hrtime_t hrt;
23779 	time_t wallclock;
23780 	uint64_t result;
23781 
23782 	/*
23783 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23784 	 * a longlong, which may contain resolution down to nanoseconds.
23785 	 * The current time will either be a 32-bit or a 64-bit quantity.
23786 	 * XOR the two together in a 64-bit result variable.
23787 	 * Convert the result to a 32-bit value by multiplying the high-order
23788 	 * 32-bits by the low-order 32-bits.
23789 	 */
23790 
23791 	hrt = gethrtime();
23792 	(void) drv_getparm(TIME, &wallclock);
23793 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23794 	mutex_enter(&tcp_random_lock);
23795 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23796 	    (result & 0xffffffff);
23797 
23798 	for (i = 1; i < DEG_3; i++)
23799 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23800 			+ 12345;
23801 	tcp_random_fptr = &tcp_random_state[SEP_3];
23802 	tcp_random_rptr = &tcp_random_state[0];
23803 	mutex_exit(&tcp_random_lock);
23804 	for (i = 0; i < 10 * DEG_3; i++)
23805 		(void) tcp_random();
23806 }
23807 
23808 /*
23809  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23810  * This range is selected to be approximately centered on TCP_ISS / 2,
23811  * and easy to compute. We get this value by generating a 32-bit random
23812  * number, selecting out the high-order 17 bits, and then adding one so
23813  * that we never return zero.
23814  */
23815 int
23816 tcp_random(void)
23817 {
23818 	int i;
23819 
23820 	mutex_enter(&tcp_random_lock);
23821 	*tcp_random_fptr += *tcp_random_rptr;
23822 
23823 	/*
23824 	 * The high-order bits are more random than the low-order bits,
23825 	 * so we select out the high-order 17 bits and add one so that
23826 	 * we never return zero.
23827 	 */
23828 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23829 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23830 		tcp_random_fptr = tcp_random_state;
23831 		++tcp_random_rptr;
23832 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23833 		tcp_random_rptr = tcp_random_state;
23834 
23835 	mutex_exit(&tcp_random_lock);
23836 	return (i);
23837 }
23838 
23839 /*
23840  * XXX This will go away when TPI is extended to send
23841  * info reqs to sockfs/timod .....
23842  * Given a queue, set the max packet size for the write
23843  * side of the queue below stream head.  This value is
23844  * cached on the stream head.
23845  * Returns 1 on success, 0 otherwise.
23846  */
23847 static int
23848 setmaxps(queue_t *q, int maxpsz)
23849 {
23850 	struct stdata	*stp;
23851 	queue_t		*wq;
23852 	stp = STREAM(q);
23853 
23854 	/*
23855 	 * At this point change of a queue parameter is not allowed
23856 	 * when a multiplexor is sitting on top.
23857 	 */
23858 	if (stp->sd_flag & STPLEX)
23859 		return (0);
23860 
23861 	claimstr(stp->sd_wrq);
23862 	wq = stp->sd_wrq->q_next;
23863 	ASSERT(wq != NULL);
23864 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23865 	releasestr(stp->sd_wrq);
23866 	return (1);
23867 }
23868 
23869 static int
23870 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23871     int *t_errorp, int *sys_errorp)
23872 {
23873 	int error;
23874 	int is_absreq_failure;
23875 	t_scalar_t *opt_lenp;
23876 	t_scalar_t opt_offset;
23877 	int prim_type;
23878 	struct T_conn_req *tcreqp;
23879 	struct T_conn_res *tcresp;
23880 	cred_t *cr;
23881 
23882 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23883 
23884 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23885 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23886 	    prim_type == T_CONN_RES);
23887 
23888 	switch (prim_type) {
23889 	case T_CONN_REQ:
23890 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23891 		opt_offset = tcreqp->OPT_offset;
23892 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23893 		break;
23894 	case O_T_CONN_RES:
23895 	case T_CONN_RES:
23896 		tcresp = (struct T_conn_res *)mp->b_rptr;
23897 		opt_offset = tcresp->OPT_offset;
23898 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23899 		break;
23900 	}
23901 
23902 	*t_errorp = 0;
23903 	*sys_errorp = 0;
23904 	*do_disconnectp = 0;
23905 
23906 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23907 	    opt_offset, cr, &tcp_opt_obj,
23908 	    NULL, &is_absreq_failure);
23909 
23910 	switch (error) {
23911 	case  0:		/* no error */
23912 		ASSERT(is_absreq_failure == 0);
23913 		return (0);
23914 	case ENOPROTOOPT:
23915 		*t_errorp = TBADOPT;
23916 		break;
23917 	case EACCES:
23918 		*t_errorp = TACCES;
23919 		break;
23920 	default:
23921 		*t_errorp = TSYSERR; *sys_errorp = error;
23922 		break;
23923 	}
23924 	if (is_absreq_failure != 0) {
23925 		/*
23926 		 * The connection request should get the local ack
23927 		 * T_OK_ACK and then a T_DISCON_IND.
23928 		 */
23929 		*do_disconnectp = 1;
23930 	}
23931 	return (-1);
23932 }
23933 
23934 /*
23935  * Split this function out so that if the secret changes, I'm okay.
23936  *
23937  * Initialize the tcp_iss_cookie and tcp_iss_key.
23938  */
23939 
23940 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23941 
23942 static void
23943 tcp_iss_key_init(uint8_t *phrase, int len)
23944 {
23945 	struct {
23946 		int32_t current_time;
23947 		uint32_t randnum;
23948 		uint16_t pad;
23949 		uint8_t ether[6];
23950 		uint8_t passwd[PASSWD_SIZE];
23951 	} tcp_iss_cookie;
23952 	time_t t;
23953 
23954 	/*
23955 	 * Start with the current absolute time.
23956 	 */
23957 	(void) drv_getparm(TIME, &t);
23958 	tcp_iss_cookie.current_time = t;
23959 
23960 	/*
23961 	 * XXX - Need a more random number per RFC 1750, not this crap.
23962 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23963 	 */
23964 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23965 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23966 
23967 	/*
23968 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23969 	 * as a good template.
23970 	 */
23971 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23972 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23973 
23974 	/*
23975 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23976 	 */
23977 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23978 
23979 	/*
23980 	 * See 4010593 if this section becomes a problem again,
23981 	 * but the local ethernet address is useful here.
23982 	 */
23983 	(void) localetheraddr(NULL,
23984 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23985 
23986 	/*
23987 	 * Hash 'em all together.  The MD5Final is called per-connection.
23988 	 */
23989 	mutex_enter(&tcp_iss_key_lock);
23990 	MD5Init(&tcp_iss_key);
23991 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23992 	    sizeof (tcp_iss_cookie));
23993 	mutex_exit(&tcp_iss_key_lock);
23994 }
23995 
23996 /*
23997  * Set the RFC 1948 pass phrase
23998  */
23999 /* ARGSUSED */
24000 static int
24001 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24002     cred_t *cr)
24003 {
24004 	/*
24005 	 * Basically, value contains a new pass phrase.  Pass it along!
24006 	 */
24007 	tcp_iss_key_init((uint8_t *)value, strlen(value));
24008 	return (0);
24009 }
24010 
24011 /* ARGSUSED */
24012 static int
24013 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24014 {
24015 	bzero(buf, sizeof (tcp_sack_info_t));
24016 	return (0);
24017 }
24018 
24019 /* ARGSUSED */
24020 static int
24021 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24022 {
24023 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24024 	return (0);
24025 }
24026 
24027 void
24028 tcp_ddi_init(void)
24029 {
24030 	int i;
24031 
24032 	/* Initialize locks */
24033 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
24034 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24035 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24036 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24037 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24038 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
24039 
24040 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24041 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
24042 		    MUTEX_DEFAULT, NULL);
24043 	}
24044 
24045 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24046 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
24047 		    MUTEX_DEFAULT, NULL);
24048 	}
24049 
24050 	/* TCP's IPsec code calls the packet dropper. */
24051 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
24052 
24053 	if (!tcp_g_nd) {
24054 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
24055 			nd_free(&tcp_g_nd);
24056 		}
24057 	}
24058 
24059 	/*
24060 	 * Note: To really walk the device tree you need the devinfo
24061 	 * pointer to your device which is only available after probe/attach.
24062 	 * The following is safe only because it uses ddi_root_node()
24063 	 */
24064 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24065 	    tcp_opt_obj.odb_opt_arr_cnt);
24066 
24067 	tcp_timercache = kmem_cache_create("tcp_timercache",
24068 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24069 	    NULL, NULL, NULL, NULL, NULL, 0);
24070 
24071 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24072 	    sizeof (tcp_sack_info_t), 0,
24073 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24074 
24075 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24076 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24077 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24078 
24079 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24080 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24081 
24082 	ip_squeue_init(tcp_squeue_add);
24083 
24084 	/* Initialize the random number generator */
24085 	tcp_random_init();
24086 
24087 	/*
24088 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24089 	 * by the boot scripts.
24090 	 *
24091 	 * Use NULL name, as the name is caught by the new lockstats.
24092 	 *
24093 	 * Initialize with some random, non-guessable string, like the global
24094 	 * T_INFO_ACK.
24095 	 */
24096 
24097 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24098 	    sizeof (tcp_g_t_info_ack));
24099 
24100 #if TCP_COUNTERS || TCP_DEBUG_COUNTER
24101 	if ((tcp_kstat = kstat_create("tcp", 0, "tcpstat",
24102 		"net", KSTAT_TYPE_NAMED,
24103 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
24104 		KSTAT_FLAG_VIRTUAL)) != NULL) {
24105 		tcp_kstat->ks_data = &tcp_statistics;
24106 		kstat_install(tcp_kstat);
24107 	}
24108 #endif
24109 	tcp_kstat_init();
24110 }
24111 
24112 void
24113 tcp_ddi_destroy(void)
24114 {
24115 	int i;
24116 
24117 	nd_free(&tcp_g_nd);
24118 
24119 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
24120 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
24121 	}
24122 
24123 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
24124 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
24125 	}
24126 
24127 	mutex_destroy(&tcp_iss_key_lock);
24128 	rw_destroy(&tcp_hsp_lock);
24129 	mutex_destroy(&tcp_g_q_lock);
24130 	mutex_destroy(&tcp_random_lock);
24131 	mutex_destroy(&tcp_epriv_port_lock);
24132 	rw_destroy(&tcp_reserved_port_lock);
24133 
24134 	ip_drop_unregister(&tcp_dropper);
24135 
24136 	kmem_cache_destroy(tcp_timercache);
24137 	kmem_cache_destroy(tcp_sack_info_cache);
24138 	kmem_cache_destroy(tcp_iphc_cache);
24139 
24140 	tcp_kstat_fini();
24141 }
24142 
24143 /*
24144  * Generate ISS, taking into account NDD changes may happen halfway through.
24145  * (If the iss is not zero, set it.)
24146  */
24147 
24148 static void
24149 tcp_iss_init(tcp_t *tcp)
24150 {
24151 	MD5_CTX context;
24152 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
24153 	uint32_t answer[4];
24154 
24155 	tcp_iss_incr_extra += (ISS_INCR >> 1);
24156 	tcp->tcp_iss = tcp_iss_incr_extra;
24157 	switch (tcp_strong_iss) {
24158 	case 2:
24159 		mutex_enter(&tcp_iss_key_lock);
24160 		context = tcp_iss_key;
24161 		mutex_exit(&tcp_iss_key_lock);
24162 		arg.ports = tcp->tcp_ports;
24163 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24164 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
24165 			    &arg.src);
24166 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
24167 			    &arg.dst);
24168 		} else {
24169 			arg.src = tcp->tcp_ip6h->ip6_src;
24170 			arg.dst = tcp->tcp_ip6h->ip6_dst;
24171 		}
24172 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
24173 		MD5Final((uchar_t *)answer, &context);
24174 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
24175 		/*
24176 		 * Now that we've hashed into a unique per-connection sequence
24177 		 * space, add a random increment per strong_iss == 1.  So I
24178 		 * guess we'll have to...
24179 		 */
24180 		/* FALLTHRU */
24181 	case 1:
24182 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
24183 		break;
24184 	default:
24185 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24186 		break;
24187 	}
24188 	tcp->tcp_valid_bits = TCP_ISS_VALID;
24189 	tcp->tcp_fss = tcp->tcp_iss - 1;
24190 	tcp->tcp_suna = tcp->tcp_iss;
24191 	tcp->tcp_snxt = tcp->tcp_iss + 1;
24192 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
24193 	tcp->tcp_csuna = tcp->tcp_snxt;
24194 }
24195 
24196 /*
24197  * Exported routine for extracting active tcp connection status.
24198  *
24199  * This is used by the Solaris Cluster Networking software to
24200  * gather a list of connections that need to be forwarded to
24201  * specific nodes in the cluster when configuration changes occur.
24202  *
24203  * The callback is invoked for each tcp_t structure. Returning
24204  * non-zero from the callback routine terminates the search.
24205  */
24206 int
24207 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
24208 {
24209 	tcp_t *tcp;
24210 	cl_tcp_info_t	cl_tcpi;
24211 	connf_t	*connfp;
24212 	conn_t	*connp;
24213 	int	i;
24214 
24215 	ASSERT(callback != NULL);
24216 
24217 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24218 
24219 		connfp = &ipcl_globalhash_fanout[i];
24220 		connp = NULL;
24221 
24222 		while ((connp = tcp_get_next_conn(connfp, connp))) {
24223 
24224 			tcp = connp->conn_tcp;
24225 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
24226 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
24227 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
24228 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
24229 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
24230 			/*
24231 			 * The macros tcp_laddr and tcp_faddr give the IPv4
24232 			 * addresses. They are copied implicitly below as
24233 			 * mapped addresses.
24234 			 */
24235 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
24236 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24237 				cl_tcpi.cl_tcpi_faddr =
24238 				    tcp->tcp_ipha->ipha_dst;
24239 			} else {
24240 				cl_tcpi.cl_tcpi_faddr_v6 =
24241 				    tcp->tcp_ip6h->ip6_dst;
24242 			}
24243 
24244 			/*
24245 			 * If the callback returns non-zero
24246 			 * we terminate the traversal.
24247 			 */
24248 			if ((*callback)(&cl_tcpi, arg) != 0) {
24249 				CONN_DEC_REF(tcp->tcp_connp);
24250 				return (1);
24251 			}
24252 		}
24253 	}
24254 
24255 	return (0);
24256 }
24257 
24258 /*
24259  * Macros used for accessing the different types of sockaddr
24260  * structures inside a tcp_ioc_abort_conn_t.
24261  */
24262 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
24263 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
24264 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
24265 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
24266 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
24267 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
24268 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
24269 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
24270 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
24271 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
24272 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
24273 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
24274 
24275 /*
24276  * Return the correct error code to mimic the behavior
24277  * of a connection reset.
24278  */
24279 #define	TCP_AC_GET_ERRCODE(state, err) {	\
24280 		switch ((state)) {		\
24281 		case TCPS_SYN_SENT:		\
24282 		case TCPS_SYN_RCVD:		\
24283 			(err) = ECONNREFUSED;	\
24284 			break;			\
24285 		case TCPS_ESTABLISHED:		\
24286 		case TCPS_FIN_WAIT_1:		\
24287 		case TCPS_FIN_WAIT_2:		\
24288 		case TCPS_CLOSE_WAIT:		\
24289 			(err) = ECONNRESET;	\
24290 			break;			\
24291 		case TCPS_CLOSING:		\
24292 		case TCPS_LAST_ACK:		\
24293 		case TCPS_TIME_WAIT:		\
24294 			(err) = 0;		\
24295 			break;			\
24296 		default:			\
24297 			(err) = ENXIO;		\
24298 		}				\
24299 	}
24300 
24301 /*
24302  * Check if a tcp structure matches the info in acp.
24303  */
24304 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
24305 	(((acp)->ac_local.ss_family == AF_INET) ?		\
24306 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
24307 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
24308 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
24309 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
24310 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
24311 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
24312 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
24313 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
24314 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24315 	(acp)->ac_end >= (tcp)->tcp_state) :		\
24316 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
24317 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
24318 	&(tcp)->tcp_ip_src_v6)) &&				\
24319 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
24320 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
24321 	&(tcp)->tcp_remote_v6)) &&				\
24322 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24323 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24324 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24325 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24326 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24327 	(acp)->ac_end >= (tcp)->tcp_state))
24328 
24329 #define	TCP_AC_MATCH(acp, tcp)					\
24330 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24331 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24332 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24333 
24334 /*
24335  * Build a message containing a tcp_ioc_abort_conn_t structure
24336  * which is filled in with information from acp and tp.
24337  */
24338 static mblk_t *
24339 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24340 {
24341 	mblk_t *mp;
24342 	tcp_ioc_abort_conn_t *tacp;
24343 
24344 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24345 	if (mp == NULL)
24346 		return (NULL);
24347 
24348 	mp->b_datap->db_type = M_CTL;
24349 
24350 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24351 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24352 		sizeof (uint32_t));
24353 
24354 	tacp->ac_start = acp->ac_start;
24355 	tacp->ac_end = acp->ac_end;
24356 	tacp->ac_zoneid = acp->ac_zoneid;
24357 
24358 	if (acp->ac_local.ss_family == AF_INET) {
24359 		tacp->ac_local.ss_family = AF_INET;
24360 		tacp->ac_remote.ss_family = AF_INET;
24361 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24362 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24363 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24364 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24365 	} else {
24366 		tacp->ac_local.ss_family = AF_INET6;
24367 		tacp->ac_remote.ss_family = AF_INET6;
24368 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24369 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24370 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24371 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24372 	}
24373 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24374 	return (mp);
24375 }
24376 
24377 /*
24378  * Print a tcp_ioc_abort_conn_t structure.
24379  */
24380 static void
24381 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24382 {
24383 	char lbuf[128];
24384 	char rbuf[128];
24385 	sa_family_t af;
24386 	in_port_t lport, rport;
24387 	ushort_t logflags;
24388 
24389 	af = acp->ac_local.ss_family;
24390 
24391 	if (af == AF_INET) {
24392 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24393 				lbuf, 128);
24394 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24395 				rbuf, 128);
24396 		lport = ntohs(TCP_AC_V4LPORT(acp));
24397 		rport = ntohs(TCP_AC_V4RPORT(acp));
24398 	} else {
24399 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24400 				lbuf, 128);
24401 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24402 				rbuf, 128);
24403 		lport = ntohs(TCP_AC_V6LPORT(acp));
24404 		rport = ntohs(TCP_AC_V6RPORT(acp));
24405 	}
24406 
24407 	logflags = SL_TRACE | SL_NOTE;
24408 	/*
24409 	 * Don't print this message to the console if the operation was done
24410 	 * to a non-global zone.
24411 	 */
24412 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24413 		logflags |= SL_CONSOLE;
24414 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags,
24415 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24416 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24417 		acp->ac_start, acp->ac_end);
24418 }
24419 
24420 /*
24421  * Called inside tcp_rput when a message built using
24422  * tcp_ioctl_abort_build_msg is put into a queue.
24423  * Note that when we get here there is no wildcard in acp any more.
24424  */
24425 static void
24426 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24427 {
24428 	tcp_ioc_abort_conn_t *acp;
24429 
24430 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24431 	if (tcp->tcp_state <= acp->ac_end) {
24432 		/*
24433 		 * If we get here, we are already on the correct
24434 		 * squeue. This ioctl follows the following path
24435 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24436 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24437 		 * different squeue)
24438 		 */
24439 		int errcode;
24440 
24441 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24442 		(void) tcp_clean_death(tcp, errcode, 26);
24443 	}
24444 	freemsg(mp);
24445 }
24446 
24447 /*
24448  * Abort all matching connections on a hash chain.
24449  */
24450 static int
24451 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24452     boolean_t exact)
24453 {
24454 	int nmatch, err = 0;
24455 	tcp_t *tcp;
24456 	MBLKP mp, last, listhead = NULL;
24457 	conn_t	*tconnp;
24458 	connf_t	*connfp = &ipcl_conn_fanout[index];
24459 
24460 startover:
24461 	nmatch = 0;
24462 
24463 	mutex_enter(&connfp->connf_lock);
24464 	for (tconnp = connfp->connf_head; tconnp != NULL;
24465 	    tconnp = tconnp->conn_next) {
24466 		tcp = tconnp->conn_tcp;
24467 		if (TCP_AC_MATCH(acp, tcp)) {
24468 			CONN_INC_REF(tcp->tcp_connp);
24469 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24470 			if (mp == NULL) {
24471 				err = ENOMEM;
24472 				CONN_DEC_REF(tcp->tcp_connp);
24473 				break;
24474 			}
24475 			mp->b_prev = (mblk_t *)tcp;
24476 
24477 			if (listhead == NULL) {
24478 				listhead = mp;
24479 				last = mp;
24480 			} else {
24481 				last->b_next = mp;
24482 				last = mp;
24483 			}
24484 			nmatch++;
24485 			if (exact)
24486 				break;
24487 		}
24488 
24489 		/* Avoid holding lock for too long. */
24490 		if (nmatch >= 500)
24491 			break;
24492 	}
24493 	mutex_exit(&connfp->connf_lock);
24494 
24495 	/* Pass mp into the correct tcp */
24496 	while ((mp = listhead) != NULL) {
24497 		listhead = listhead->b_next;
24498 		tcp = (tcp_t *)mp->b_prev;
24499 		mp->b_next = mp->b_prev = NULL;
24500 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24501 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24502 	}
24503 
24504 	*count += nmatch;
24505 	if (nmatch >= 500 && err == 0)
24506 		goto startover;
24507 	return (err);
24508 }
24509 
24510 /*
24511  * Abort all connections that matches the attributes specified in acp.
24512  */
24513 static int
24514 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24515 {
24516 	sa_family_t af;
24517 	uint32_t  ports;
24518 	uint16_t *pports;
24519 	int err = 0, count = 0;
24520 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24521 	int index = -1;
24522 	ushort_t logflags;
24523 
24524 	af = acp->ac_local.ss_family;
24525 
24526 	if (af == AF_INET) {
24527 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24528 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24529 			pports = (uint16_t *)&ports;
24530 			pports[1] = TCP_AC_V4LPORT(acp);
24531 			pports[0] = TCP_AC_V4RPORT(acp);
24532 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24533 		}
24534 	} else {
24535 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24536 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24537 			pports = (uint16_t *)&ports;
24538 			pports[1] = TCP_AC_V6LPORT(acp);
24539 			pports[0] = TCP_AC_V6RPORT(acp);
24540 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24541 		}
24542 	}
24543 
24544 	/*
24545 	 * For cases where remote addr, local port, and remote port are non-
24546 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24547 	 */
24548 	if (index != -1) {
24549 		err = tcp_ioctl_abort_bucket(acp, index,
24550 			    &count, exact);
24551 	} else {
24552 		/*
24553 		 * loop through all entries for wildcard case
24554 		 */
24555 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24556 			err = tcp_ioctl_abort_bucket(acp, index,
24557 			    &count, exact);
24558 			if (err != 0)
24559 				break;
24560 		}
24561 	}
24562 
24563 	logflags = SL_TRACE | SL_NOTE;
24564 	/*
24565 	 * Don't print this message to the console if the operation was done
24566 	 * to a non-global zone.
24567 	 */
24568 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24569 		logflags |= SL_CONSOLE;
24570 	(void) strlog(TCP_MODULE_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24571 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24572 	if (err == 0 && count == 0)
24573 		err = ENOENT;
24574 	return (err);
24575 }
24576 
24577 /*
24578  * Process the TCP_IOC_ABORT_CONN ioctl request.
24579  */
24580 static void
24581 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24582 {
24583 	int	err;
24584 	IOCP    iocp;
24585 	MBLKP   mp1;
24586 	sa_family_t laf, raf;
24587 	tcp_ioc_abort_conn_t *acp;
24588 	zone_t *zptr;
24589 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24590 
24591 	iocp = (IOCP)mp->b_rptr;
24592 
24593 	if ((mp1 = mp->b_cont) == NULL ||
24594 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24595 		err = EINVAL;
24596 		goto out;
24597 	}
24598 
24599 	/* check permissions */
24600 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24601 		err = EPERM;
24602 		goto out;
24603 	}
24604 
24605 	if (mp1->b_cont != NULL) {
24606 		freemsg(mp1->b_cont);
24607 		mp1->b_cont = NULL;
24608 	}
24609 
24610 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24611 	laf = acp->ac_local.ss_family;
24612 	raf = acp->ac_remote.ss_family;
24613 
24614 	/* check that a zone with the supplied zoneid exists */
24615 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24616 		zptr = zone_find_by_id(zoneid);
24617 		if (zptr != NULL) {
24618 			zone_rele(zptr);
24619 		} else {
24620 			err = EINVAL;
24621 			goto out;
24622 		}
24623 	}
24624 
24625 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24626 	    acp->ac_start > acp->ac_end || laf != raf ||
24627 	    (laf != AF_INET && laf != AF_INET6)) {
24628 		err = EINVAL;
24629 		goto out;
24630 	}
24631 
24632 	tcp_ioctl_abort_dump(acp);
24633 	err = tcp_ioctl_abort(acp);
24634 
24635 out:
24636 	if (mp1 != NULL) {
24637 		freemsg(mp1);
24638 		mp->b_cont = NULL;
24639 	}
24640 
24641 	if (err != 0)
24642 		miocnak(q, mp, 0, err);
24643 	else
24644 		miocack(q, mp, 0, 0);
24645 }
24646 
24647 /*
24648  * tcp_time_wait_processing() handles processing of incoming packets when
24649  * the tcp is in the TIME_WAIT state.
24650  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24651  * on the time wait list.
24652  */
24653 void
24654 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24655     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24656 {
24657 	int32_t		bytes_acked;
24658 	int32_t		gap;
24659 	int32_t		rgap;
24660 	tcp_opt_t	tcpopt;
24661 	uint_t		flags;
24662 	uint32_t	new_swnd = 0;
24663 	conn_t		*connp;
24664 
24665 	BUMP_LOCAL(tcp->tcp_ibsegs);
24666 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24667 
24668 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24669 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24670 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24671 	if (tcp->tcp_snd_ts_ok) {
24672 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24673 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24674 			    tcp->tcp_rnxt, TH_ACK);
24675 			goto done;
24676 		}
24677 	}
24678 	gap = seg_seq - tcp->tcp_rnxt;
24679 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24680 	if (gap < 0) {
24681 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24682 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24683 		    (seg_len > -gap ? -gap : seg_len));
24684 		seg_len += gap;
24685 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24686 			if (flags & TH_RST) {
24687 				goto done;
24688 			}
24689 			if ((flags & TH_FIN) && seg_len == -1) {
24690 				/*
24691 				 * When TCP receives a duplicate FIN in
24692 				 * TIME_WAIT state, restart the 2 MSL timer.
24693 				 * See page 73 in RFC 793. Make sure this TCP
24694 				 * is already on the TIME_WAIT list. If not,
24695 				 * just restart the timer.
24696 				 */
24697 				if (TCP_IS_DETACHED(tcp)) {
24698 					tcp_time_wait_remove(tcp, NULL);
24699 					tcp_time_wait_append(tcp);
24700 					TCP_DBGSTAT(tcp_rput_time_wait);
24701 				} else {
24702 					ASSERT(tcp != NULL);
24703 					TCP_TIMER_RESTART(tcp,
24704 					    tcp_time_wait_interval);
24705 				}
24706 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24707 				    tcp->tcp_rnxt, TH_ACK);
24708 				goto done;
24709 			}
24710 			flags |=  TH_ACK_NEEDED;
24711 			seg_len = 0;
24712 			goto process_ack;
24713 		}
24714 
24715 		/* Fix seg_seq, and chew the gap off the front. */
24716 		seg_seq = tcp->tcp_rnxt;
24717 	}
24718 
24719 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24720 		/*
24721 		 * Make sure that when we accept the connection, pick
24722 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24723 		 * old connection.
24724 		 *
24725 		 * The next ISS generated is equal to tcp_iss_incr_extra
24726 		 * + ISS_INCR/2 + other components depending on the
24727 		 * value of tcp_strong_iss.  We pre-calculate the new
24728 		 * ISS here and compare with tcp_snxt to determine if
24729 		 * we need to make adjustment to tcp_iss_incr_extra.
24730 		 *
24731 		 * The above calculation is ugly and is a
24732 		 * waste of CPU cycles...
24733 		 */
24734 		uint32_t new_iss = tcp_iss_incr_extra;
24735 		int32_t adj;
24736 
24737 		switch (tcp_strong_iss) {
24738 		case 2: {
24739 			/* Add time and MD5 components. */
24740 			uint32_t answer[4];
24741 			struct {
24742 				uint32_t ports;
24743 				in6_addr_t src;
24744 				in6_addr_t dst;
24745 			} arg;
24746 			MD5_CTX context;
24747 
24748 			mutex_enter(&tcp_iss_key_lock);
24749 			context = tcp_iss_key;
24750 			mutex_exit(&tcp_iss_key_lock);
24751 			arg.ports = tcp->tcp_ports;
24752 			/* We use MAPPED addresses in tcp_iss_init */
24753 			arg.src = tcp->tcp_ip_src_v6;
24754 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24755 				IN6_IPADDR_TO_V4MAPPED(
24756 					tcp->tcp_ipha->ipha_dst,
24757 					    &arg.dst);
24758 			} else {
24759 				arg.dst =
24760 				    tcp->tcp_ip6h->ip6_dst;
24761 			}
24762 			MD5Update(&context, (uchar_t *)&arg,
24763 			    sizeof (arg));
24764 			MD5Final((uchar_t *)answer, &context);
24765 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24766 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24767 			break;
24768 		}
24769 		case 1:
24770 			/* Add time component and min random (i.e. 1). */
24771 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24772 			break;
24773 		default:
24774 			/* Add only time component. */
24775 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24776 			break;
24777 		}
24778 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24779 			/*
24780 			 * New ISS not guaranteed to be ISS_INCR/2
24781 			 * ahead of the current tcp_snxt, so add the
24782 			 * difference to tcp_iss_incr_extra.
24783 			 */
24784 			tcp_iss_incr_extra += adj;
24785 		}
24786 		/*
24787 		 * If tcp_clean_death() can not perform the task now,
24788 		 * drop the SYN packet and let the other side re-xmit.
24789 		 * Otherwise pass the SYN packet back in, since the
24790 		 * old tcp state has been cleaned up or freed.
24791 		 */
24792 		if (tcp_clean_death(tcp, 0, 27) == -1)
24793 			goto done;
24794 		/*
24795 		 * We will come back to tcp_rput_data
24796 		 * on the global queue. Packets destined
24797 		 * for the global queue will be checked
24798 		 * with global policy. But the policy for
24799 		 * this packet has already been checked as
24800 		 * this was destined for the detached
24801 		 * connection. We need to bypass policy
24802 		 * check this time by attaching a dummy
24803 		 * ipsec_in with ipsec_in_dont_check set.
24804 		 */
24805 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24806 		    NULL) {
24807 			TCP_STAT(tcp_time_wait_syn_success);
24808 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24809 			return;
24810 		}
24811 		goto done;
24812 	}
24813 
24814 	/*
24815 	 * rgap is the amount of stuff received out of window.  A negative
24816 	 * value is the amount out of window.
24817 	 */
24818 	if (rgap < 0) {
24819 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24820 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24821 		/* Fix seg_len and make sure there is something left. */
24822 		seg_len += rgap;
24823 		if (seg_len <= 0) {
24824 			if (flags & TH_RST) {
24825 				goto done;
24826 			}
24827 			flags |=  TH_ACK_NEEDED;
24828 			seg_len = 0;
24829 			goto process_ack;
24830 		}
24831 	}
24832 	/*
24833 	 * Check whether we can update tcp_ts_recent.  This test is
24834 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24835 	 * Extensions for High Performance: An Update", Internet Draft.
24836 	 */
24837 	if (tcp->tcp_snd_ts_ok &&
24838 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24839 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24840 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24841 		tcp->tcp_last_rcv_lbolt = lbolt64;
24842 	}
24843 
24844 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24845 		/* Always ack out of order packets */
24846 		flags |= TH_ACK_NEEDED;
24847 		seg_len = 0;
24848 	} else if (seg_len > 0) {
24849 		BUMP_MIB(&tcp_mib, tcpInClosed);
24850 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24851 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24852 	}
24853 	if (flags & TH_RST) {
24854 		(void) tcp_clean_death(tcp, 0, 28);
24855 		goto done;
24856 	}
24857 	if (flags & TH_SYN) {
24858 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24859 		    TH_RST|TH_ACK);
24860 		/*
24861 		 * Do not delete the TCP structure if it is in
24862 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24863 		 */
24864 		goto done;
24865 	}
24866 process_ack:
24867 	if (flags & TH_ACK) {
24868 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24869 		if (bytes_acked <= 0) {
24870 			if (bytes_acked == 0 && seg_len == 0 &&
24871 			    new_swnd == tcp->tcp_swnd)
24872 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24873 		} else {
24874 			/* Acks something not sent */
24875 			flags |= TH_ACK_NEEDED;
24876 		}
24877 	}
24878 	if (flags & TH_ACK_NEEDED) {
24879 		/*
24880 		 * Time to send an ack for some reason.
24881 		 */
24882 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24883 		    tcp->tcp_rnxt, TH_ACK);
24884 	}
24885 done:
24886 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24887 		mp->b_datap->db_cksumstart = 0;
24888 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24889 		TCP_STAT(tcp_time_wait_syn_fail);
24890 	}
24891 	freemsg(mp);
24892 }
24893 
24894 /*
24895  * Return zero if the buffers are identical in length and content.
24896  * This is used for comparing extension header buffers.
24897  * Note that an extension header would be declared different
24898  * even if all that changed was the next header value in that header i.e.
24899  * what really changed is the next extension header.
24900  */
24901 static boolean_t
24902 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24903 {
24904 	if (!b_valid)
24905 		blen = 0;
24906 
24907 	if (alen != blen)
24908 		return (B_TRUE);
24909 	if (alen == 0)
24910 		return (B_FALSE);	/* Both zero length */
24911 	return (bcmp(a, b, alen));
24912 }
24913 
24914 /*
24915  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24916  * Return B_FALSE if memory allocation fails - don't change any state!
24917  */
24918 static boolean_t
24919 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24920     void *src, uint_t srclen)
24921 {
24922 	void *dst;
24923 
24924 	if (!src_valid)
24925 		srclen = 0;
24926 
24927 	ASSERT(*dstlenp == 0);
24928 	if (src != NULL && srclen != 0) {
24929 		dst = mi_alloc(srclen, BPRI_MED);
24930 		if (dst == NULL)
24931 			return (B_FALSE);
24932 	} else {
24933 		dst = NULL;
24934 	}
24935 	if (*dstp != NULL) {
24936 		mi_free(*dstp);
24937 		*dstp = NULL;
24938 		*dstlenp = 0;
24939 	}
24940 	*dstp = dst;
24941 	if (dst != NULL)
24942 		*dstlenp = srclen;
24943 	else
24944 		*dstlenp = 0;
24945 	return (B_TRUE);
24946 }
24947 
24948 /*
24949  * Replace what is in *dst, *dstlen with the source.
24950  * Assumes tcp_allocbuf has already been called.
24951  */
24952 static void
24953 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24954     void *src, uint_t srclen)
24955 {
24956 	if (!src_valid)
24957 		srclen = 0;
24958 
24959 	ASSERT(*dstlenp == srclen);
24960 	if (src != NULL && srclen != 0) {
24961 		bcopy(src, *dstp, srclen);
24962 	}
24963 }
24964 
24965 /*
24966  * Allocate a T_SVR4_OPTMGMT_REQ.
24967  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24968  * that tcp_rput_other can drop the acks.
24969  */
24970 static mblk_t *
24971 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24972 {
24973 	mblk_t *mp;
24974 	struct T_optmgmt_req *tor;
24975 	struct opthdr *oh;
24976 	uint_t size;
24977 	char *optptr;
24978 
24979 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24980 	mp = allocb(size, BPRI_MED);
24981 	if (mp == NULL)
24982 		return (NULL);
24983 
24984 	mp->b_wptr += size;
24985 	mp->b_datap->db_type = M_PROTO;
24986 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24987 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24988 	tor->MGMT_flags = T_NEGOTIATE;
24989 	tor->OPT_length = sizeof (*oh) + optlen;
24990 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24991 
24992 	oh = (struct opthdr *)&tor[1];
24993 	oh->level = level;
24994 	oh->name = cmd;
24995 	oh->len = optlen;
24996 	if (optlen != 0) {
24997 		optptr = (char *)&oh[1];
24998 		bcopy(opt, optptr, optlen);
24999 	}
25000 	return (mp);
25001 }
25002 
25003 /*
25004  * TCP Timers Implementation.
25005  */
25006 static timeout_id_t
25007 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25008 {
25009 	mblk_t *mp;
25010 	tcp_timer_t *tcpt;
25011 	tcp_t *tcp = connp->conn_tcp;
25012 
25013 	ASSERT(connp->conn_sqp != NULL);
25014 
25015 	TCP_DBGSTAT(tcp_timeout_calls);
25016 
25017 	if (tcp->tcp_timercache == NULL) {
25018 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25019 	} else {
25020 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
25021 		mp = tcp->tcp_timercache;
25022 		tcp->tcp_timercache = mp->b_next;
25023 		mp->b_next = NULL;
25024 		ASSERT(mp->b_wptr == NULL);
25025 	}
25026 
25027 	CONN_INC_REF(connp);
25028 	tcpt = (tcp_timer_t *)mp->b_rptr;
25029 	tcpt->connp = connp;
25030 	tcpt->tcpt_proc = f;
25031 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
25032 	return ((timeout_id_t)mp);
25033 }
25034 
25035 static void
25036 tcp_timer_callback(void *arg)
25037 {
25038 	mblk_t *mp = (mblk_t *)arg;
25039 	tcp_timer_t *tcpt;
25040 	conn_t	*connp;
25041 
25042 	tcpt = (tcp_timer_t *)mp->b_rptr;
25043 	connp = tcpt->connp;
25044 	squeue_fill(connp->conn_sqp, mp,
25045 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25046 }
25047 
25048 static void
25049 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25050 {
25051 	tcp_timer_t *tcpt;
25052 	conn_t *connp = (conn_t *)arg;
25053 	tcp_t *tcp = connp->conn_tcp;
25054 
25055 	tcpt = (tcp_timer_t *)mp->b_rptr;
25056 	ASSERT(connp == tcpt->connp);
25057 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25058 
25059 	/*
25060 	 * If the TCP has reached the closed state, don't proceed any
25061 	 * further. This TCP logically does not exist on the system.
25062 	 * tcpt_proc could for example access queues, that have already
25063 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25064 	 */
25065 	if (tcp->tcp_state != TCPS_CLOSED) {
25066 		(*tcpt->tcpt_proc)(connp);
25067 	} else {
25068 		tcp->tcp_timer_tid = 0;
25069 	}
25070 	tcp_timer_free(connp->conn_tcp, mp);
25071 }
25072 
25073 /*
25074  * There is potential race with untimeout and the handler firing at the same
25075  * time. The mblock may be freed by the handler while we are trying to use
25076  * it. But since both should execute on the same squeue, this race should not
25077  * occur.
25078  */
25079 static clock_t
25080 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25081 {
25082 	mblk_t	*mp = (mblk_t *)id;
25083 	tcp_timer_t *tcpt;
25084 	clock_t delta;
25085 
25086 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
25087 
25088 	if (mp == NULL)
25089 		return (-1);
25090 
25091 	tcpt = (tcp_timer_t *)mp->b_rptr;
25092 	ASSERT(tcpt->connp == connp);
25093 
25094 	delta = untimeout(tcpt->tcpt_tid);
25095 
25096 	if (delta >= 0) {
25097 		TCP_DBGSTAT(tcp_timeout_canceled);
25098 		tcp_timer_free(connp->conn_tcp, mp);
25099 		CONN_DEC_REF(connp);
25100 	}
25101 
25102 	return (delta);
25103 }
25104 
25105 /*
25106  * Allocate space for the timer event. The allocation looks like mblk, but it is
25107  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25108  *
25109  * Dealing with failures: If we can't allocate from the timer cache we try
25110  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25111  * points to b_rptr.
25112  * If we can't allocate anything using allocb_tryhard(), we perform a last
25113  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25114  * save the actual allocation size in b_datap.
25115  */
25116 mblk_t *
25117 tcp_timermp_alloc(int kmflags)
25118 {
25119 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25120 	    kmflags & ~KM_PANIC);
25121 
25122 	if (mp != NULL) {
25123 		mp->b_next = mp->b_prev = NULL;
25124 		mp->b_rptr = (uchar_t *)(&mp[1]);
25125 		mp->b_wptr = NULL;
25126 		mp->b_datap = NULL;
25127 		mp->b_queue = NULL;
25128 	} else if (kmflags & KM_PANIC) {
25129 		/*
25130 		 * Failed to allocate memory for the timer. Try allocating from
25131 		 * dblock caches.
25132 		 */
25133 		TCP_STAT(tcp_timermp_allocfail);
25134 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25135 		if (mp == NULL) {
25136 			size_t size = 0;
25137 			/*
25138 			 * Memory is really low. Try tryhard allocation.
25139 			 */
25140 			TCP_STAT(tcp_timermp_allocdblfail);
25141 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25142 			    sizeof (tcp_timer_t), &size, kmflags);
25143 			mp->b_rptr = (uchar_t *)(&mp[1]);
25144 			mp->b_next = mp->b_prev = NULL;
25145 			mp->b_wptr = (uchar_t *)-1;
25146 			mp->b_datap = (dblk_t *)size;
25147 			mp->b_queue = NULL;
25148 		}
25149 		ASSERT(mp->b_wptr != NULL);
25150 	}
25151 	TCP_DBGSTAT(tcp_timermp_alloced);
25152 
25153 	return (mp);
25154 }
25155 
25156 /*
25157  * Free per-tcp timer cache.
25158  * It can only contain entries from tcp_timercache.
25159  */
25160 void
25161 tcp_timermp_free(tcp_t *tcp)
25162 {
25163 	mblk_t *mp;
25164 
25165 	while ((mp = tcp->tcp_timercache) != NULL) {
25166 		ASSERT(mp->b_wptr == NULL);
25167 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25168 		kmem_cache_free(tcp_timercache, mp);
25169 	}
25170 }
25171 
25172 /*
25173  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25174  * events there already (currently at most two events are cached).
25175  * If the event is not allocated from the timer cache, free it right away.
25176  */
25177 static void
25178 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25179 {
25180 	mblk_t *mp1 = tcp->tcp_timercache;
25181 
25182 	if (mp->b_wptr != NULL) {
25183 		/*
25184 		 * This allocation is not from a timer cache, free it right
25185 		 * away.
25186 		 */
25187 		if (mp->b_wptr != (uchar_t *)-1)
25188 			freeb(mp);
25189 		else
25190 			kmem_free(mp, (size_t)mp->b_datap);
25191 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25192 		/* Cache this timer block for future allocations */
25193 		mp->b_rptr = (uchar_t *)(&mp[1]);
25194 		mp->b_next = mp1;
25195 		tcp->tcp_timercache = mp;
25196 	} else {
25197 		kmem_cache_free(tcp_timercache, mp);
25198 		TCP_DBGSTAT(tcp_timermp_freed);
25199 	}
25200 }
25201 
25202 /*
25203  * End of TCP Timers implementation.
25204  */
25205 
25206 static void
25207 tcp_setqfull(tcp_t *tcp)
25208 {
25209 	queue_t *q = tcp->tcp_wq;
25210 
25211 	if (!(q->q_flag & QFULL)) {
25212 		TCP_STAT(tcp_flwctl_on);
25213 		mutex_enter(QLOCK(q));
25214 		q->q_flag |= QFULL;
25215 		mutex_exit(QLOCK(q));
25216 	}
25217 }
25218 
25219 static void
25220 tcp_clrqfull(tcp_t *tcp)
25221 {
25222 	queue_t *q = tcp->tcp_wq;
25223 
25224 	if (q->q_flag & QFULL) {
25225 		mutex_enter(QLOCK(q));
25226 		q->q_flag &= ~QFULL;
25227 		mutex_exit(QLOCK(q));
25228 		if (q->q_flag & QWANTW)
25229 			qbackenable(q, 0);
25230 	}
25231 }
25232 
25233 /*
25234  * TCP Kstats implementation
25235  */
25236 static void
25237 tcp_kstat_init(void)
25238 {
25239 	tcp_named_kstat_t template = {
25240 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
25241 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
25242 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
25243 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
25244 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
25245 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
25246 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
25247 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
25248 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
25249 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
25250 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
25251 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
25252 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
25253 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
25254 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
25255 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
25256 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
25257 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
25258 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
25259 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
25260 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
25261 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
25262 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
25263 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
25264 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
25265 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
25266 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
25267 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
25268 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
25269 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
25270 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
25271 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
25272 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
25273 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
25274 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
25275 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
25276 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
25277 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
25278 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
25279 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
25280 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
25281 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
25282 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
25283 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
25284 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
25285 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
25286 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
25287 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
25288 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
25289 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
25290 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
25291 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
25292 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
25293 	};
25294 
25295 	tcp_mibkp = kstat_create("tcp", 0, "tcp", "mib2", KSTAT_TYPE_NAMED,
25296 	    NUM_OF_FIELDS(tcp_named_kstat_t), 0);
25297 
25298 	if (tcp_mibkp == NULL)
25299 		return;
25300 
25301 	template.rtoAlgorithm.value.ui32 = 4;
25302 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
25303 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
25304 	template.maxConn.value.i32 = -1;
25305 
25306 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
25307 
25308 	tcp_mibkp->ks_update = tcp_kstat_update;
25309 
25310 	kstat_install(tcp_mibkp);
25311 }
25312 
25313 static void
25314 tcp_kstat_fini(void)
25315 {
25316 
25317 	if (tcp_mibkp != NULL) {
25318 		kstat_delete(tcp_mibkp);
25319 		tcp_mibkp = NULL;
25320 	}
25321 }
25322 
25323 static int
25324 tcp_kstat_update(kstat_t *kp, int rw)
25325 {
25326 	tcp_named_kstat_t	*tcpkp;
25327 	tcp_t			*tcp;
25328 	connf_t			*connfp;
25329 	conn_t			*connp;
25330 	int 			i;
25331 
25332 	if (!kp || !kp->ks_data)
25333 		return (EIO);
25334 
25335 	if (rw == KSTAT_WRITE)
25336 		return (EACCES);
25337 
25338 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
25339 
25340 	tcpkp->currEstab.value.ui32 = 0;
25341 
25342 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25343 		connfp = &ipcl_globalhash_fanout[i];
25344 		connp = NULL;
25345 		while ((connp = tcp_get_next_conn(connfp, connp))) {
25346 			tcp = connp->conn_tcp;
25347 			switch (tcp_snmp_state(tcp)) {
25348 			case MIB2_TCP_established:
25349 			case MIB2_TCP_closeWait:
25350 				tcpkp->currEstab.value.ui32++;
25351 				break;
25352 			}
25353 		}
25354 	}
25355 
25356 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
25357 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
25358 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
25359 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
25360 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
25361 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
25362 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
25363 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
25364 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
25365 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
25366 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
25367 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
25368 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
25369 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
25370 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
25371 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
25372 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
25373 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
25374 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25375 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25376 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25377 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25378 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25379 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25380 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25381 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25382 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25383 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25384 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25385 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25386 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25387 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25388 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25389 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25390 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25391 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25392 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25393 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25394 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25395 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25396 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25397 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25398 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25399 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25400 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25401 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25402 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25403 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25404 
25405 	return (0);
25406 }
25407 
25408 void
25409 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25410 {
25411 	uint16_t	hdr_len;
25412 	ipha_t		*ipha;
25413 	uint8_t		*nexthdrp;
25414 	tcph_t		*tcph;
25415 
25416 	/* Already has an eager */
25417 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25418 		TCP_STAT(tcp_reinput_syn);
25419 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25420 		    connp, SQTAG_TCP_REINPUT_EAGER);
25421 		return;
25422 	}
25423 
25424 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25425 	case IPV4_VERSION:
25426 		ipha = (ipha_t *)mp->b_rptr;
25427 		hdr_len = IPH_HDR_LENGTH(ipha);
25428 		break;
25429 	case IPV6_VERSION:
25430 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25431 		    &hdr_len, &nexthdrp)) {
25432 			CONN_DEC_REF(connp);
25433 			freemsg(mp);
25434 			return;
25435 		}
25436 		break;
25437 	}
25438 
25439 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25440 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25441 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25442 		mp->b_datap->db_cksumstart = (intptr_t)sqp;
25443 	}
25444 
25445 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25446 	    SQTAG_TCP_REINPUT);
25447 }
25448 
25449 static squeue_func_t
25450 tcp_squeue_switch(int val)
25451 {
25452 	squeue_func_t rval = squeue_fill;
25453 
25454 	switch (val) {
25455 	case 1:
25456 		rval = squeue_enter_nodrain;
25457 		break;
25458 	case 2:
25459 		rval = squeue_enter;
25460 		break;
25461 	default:
25462 		break;
25463 	}
25464 	return (rval);
25465 }
25466 
25467 static void
25468 tcp_squeue_add(squeue_t *sqp)
25469 {
25470 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25471 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25472 
25473 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25474 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25475 	    sqp, TCP_TIME_WAIT_DELAY);
25476 }
25477