xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision 00d0963faf2e861a4aef6b1bf28f99a5b2b20755)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 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/priv.h>
58 #include <sys/zone.h>
59 
60 #include <sys/errno.h>
61 #include <sys/signal.h>
62 #include <sys/socket.h>
63 #include <sys/sockio.h>
64 #include <sys/isa_defs.h>
65 #include <sys/md5.h>
66 #include <sys/random.h>
67 #include <netinet/in.h>
68 #include <netinet/tcp.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 #include <inet/ipsec_impl.h>
74 
75 #include <inet/common.h>
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip_ndp.h>
80 #include <inet/mi.h>
81 #include <inet/mib2.h>
82 #include <inet/nd.h>
83 #include <inet/optcom.h>
84 #include <inet/snmpcom.h>
85 #include <inet/kstatcom.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <net/pfkeyv2.h>
89 #include <inet/ipsec_info.h>
90 #include <inet/ipdrop.h>
91 #include <inet/tcp_trace.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_if.h>
96 #include <inet/ipp_common.h>
97 #include <sys/squeue.h>
98 #include <inet/kssl/ksslapi.h>
99 #include <sys/tsol/label.h>
100 #include <sys/tsol/tnet.h>
101 #include <sys/sdt.h>
102 #include <rpc/pmap_prot.h>
103 
104 /*
105  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
106  *
107  * (Read the detailed design doc in PSARC case directory)
108  *
109  * The entire tcp state is contained in tcp_t and conn_t structure
110  * which are allocated in tandem using ipcl_conn_create() and passing
111  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
112  * the references on the tcp_t. The tcp_t structure is never compressed
113  * and packets always land on the correct TCP perimeter from the time
114  * eager is created till the time tcp_t dies (as such the old mentat
115  * TCP global queue is not used for detached state and no IPSEC checking
116  * is required). The global queue is still allocated to send out resets
117  * for connection which have no listeners and IP directly calls
118  * tcp_xmit_listeners_reset() which does any policy check.
119  *
120  * Protection and Synchronisation mechanism:
121  *
122  * The tcp data structure does not use any kind of lock for protecting
123  * its state but instead uses 'squeues' for mutual exclusion from various
124  * read and write side threads. To access a tcp member, the thread should
125  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
126  * squeue_fill). Since the squeues allow a direct function call, caller
127  * can pass any tcp function having prototype of edesc_t as argument
128  * (different from traditional STREAMs model where packets come in only
129  * designated entry points). The list of functions that can be directly
130  * called via squeue are listed before the usual function prototype.
131  *
132  * Referencing:
133  *
134  * TCP is MT-Hot and we use a reference based scheme to make sure that the
135  * tcp structure doesn't disappear when its needed. When the application
136  * creates an outgoing connection or accepts an incoming connection, we
137  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
138  * The IP reference is just a symbolic reference since ip_tcpclose()
139  * looks at tcp structure after tcp_close_output() returns which could
140  * have dropped the last TCP reference. So as long as the connection is
141  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
142  * conn_t. The classifier puts its own reference when the connection is
143  * inserted in listen or connected hash. Anytime a thread needs to enter
144  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
145  * on write side or by doing a classify on read side and then puts a
146  * reference on the conn before doing squeue_enter/tryenter/fill. For
147  * read side, the classifier itself puts the reference under fanout lock
148  * to make sure that tcp can't disappear before it gets processed. The
149  * squeue will drop this reference automatically so the called function
150  * doesn't have to do a DEC_REF.
151  *
152  * Opening a new connection:
153  *
154  * The outgoing connection open is pretty simple. ip_tcpopen() does the
155  * work in creating the conn/tcp structure and initializing it. The
156  * squeue assignment is done based on the CPU the application
157  * is running on. So for outbound connections, processing is always done
158  * on application CPU which might be different from the incoming CPU
159  * being interrupted by the NIC. An optimal way would be to figure out
160  * the NIC <-> CPU binding at listen time, and assign the outgoing
161  * connection to the squeue attached to the CPU that will be interrupted
162  * for incoming packets (we know the NIC based on the bind IP address).
163  * This might seem like a problem if more data is going out but the
164  * fact is that in most cases the transmit is ACK driven transmit where
165  * the outgoing data normally sits on TCP's xmit queue waiting to be
166  * transmitted.
167  *
168  * Accepting a connection:
169  *
170  * This is a more interesting case because of various races involved in
171  * establishing a eager in its own perimeter. Read the meta comment on
172  * top of tcp_conn_request(). But briefly, the squeue is picked by
173  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
174  *
175  * Closing a connection:
176  *
177  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
178  * via squeue to do the close and mark the tcp as detached if the connection
179  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
180  * reference but tcp_close() drop IP's reference always. So if tcp was
181  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
182  * and 1 because it is in classifier's connected hash. This is the condition
183  * we use to determine that its OK to clean up the tcp outside of squeue
184  * when time wait expires (check the ref under fanout and conn_lock and
185  * if it is 2, remove it from fanout hash and kill it).
186  *
187  * Although close just drops the necessary references and marks the
188  * tcp_detached state, tcp_close needs to know the tcp_detached has been
189  * set (under squeue) before letting the STREAM go away (because a
190  * inbound packet might attempt to go up the STREAM while the close
191  * has happened and tcp_detached is not set). So a special lock and
192  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
193  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
194  * tcp_detached.
195  *
196  * Special provisions and fast paths:
197  *
198  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
199  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
200  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
201  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
202  * check to send packets directly to tcp_rput_data via squeue. Everyone
203  * else comes through tcp_input() on the read side.
204  *
205  * We also make special provisions for sockfs by marking tcp_issocket
206  * whenever we have only sockfs on top of TCP. This allows us to skip
207  * putting the tcp in acceptor hash since a sockfs listener can never
208  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
209  * since eager has already been allocated and the accept now happens
210  * on acceptor STREAM. There is a big blob of comment on top of
211  * tcp_conn_request explaining the new accept. When socket is POP'd,
212  * sockfs sends us an ioctl to mark the fact and we go back to old
213  * behaviour. Once tcp_issocket is unset, its never set for the
214  * life of that connection.
215  *
216  * IPsec notes :
217  *
218  * Since a packet is always executed on the correct TCP perimeter
219  * all IPsec processing is defered to IP including checking new
220  * connections and setting IPSEC policies for new connection. The
221  * only exception is tcp_xmit_listeners_reset() which is called
222  * directly from IP and needs to policy check to see if TH_RST
223  * can be sent out.
224  */
225 
226 extern major_t TCP6_MAJ;
227 
228 /*
229  * Values for squeue switch:
230  * 1: squeue_enter_nodrain
231  * 2: squeue_enter
232  * 3: squeue_fill
233  */
234 int tcp_squeue_close = 2;
235 int tcp_squeue_wput = 2;
236 
237 squeue_func_t tcp_squeue_close_proc;
238 squeue_func_t tcp_squeue_wput_proc;
239 
240 /*
241  * This controls how tiny a write must be before we try to copy it
242  * into the the mblk on the tail of the transmit queue.  Not much
243  * speedup is observed for values larger than sixteen.  Zero will
244  * disable the optimisation.
245  */
246 int tcp_tx_pull_len = 16;
247 
248 /*
249  * TCP Statistics.
250  *
251  * How TCP statistics work.
252  *
253  * There are two types of statistics invoked by two macros.
254  *
255  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
256  * supposed to be used in non MT-hot paths of the code.
257  *
258  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
259  * supposed to be used for DEBUG purposes and may be used on a hot path.
260  *
261  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
262  * (use "kstat tcp" to get them).
263  *
264  * There is also additional debugging facility that marks tcp_clean_death()
265  * instances and saves them in tcp_t structure. It is triggered by
266  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
267  * tcp_clean_death() calls that counts the number of times each tag was hit. It
268  * is triggered by TCP_CLD_COUNTERS define.
269  *
270  * How to add new counters.
271  *
272  * 1) Add a field in the tcp_stat structure describing your counter.
273  * 2) Add a line in tcp_statistics with the name of the counter.
274  *
275  *    IMPORTANT!! - make sure that both are in sync !!
276  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
277  *
278  * Please avoid using private counters which are not kstat-exported.
279  *
280  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
281  * in tcp_t structure.
282  *
283  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
284  */
285 
286 #ifndef TCP_DEBUG_COUNTER
287 #ifdef DEBUG
288 #define	TCP_DEBUG_COUNTER 1
289 #else
290 #define	TCP_DEBUG_COUNTER 0
291 #endif
292 #endif
293 
294 #define	TCP_CLD_COUNTERS 0
295 
296 #define	TCP_TAG_CLEAN_DEATH 1
297 #define	TCP_MAX_CLEAN_DEATH_TAG 32
298 
299 #ifdef lint
300 static int _lint_dummy_;
301 #endif
302 
303 #if TCP_CLD_COUNTERS
304 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
305 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
306 #elif defined(lint)
307 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
308 #else
309 #define	TCP_CLD_STAT(x)
310 #endif
311 
312 #if TCP_DEBUG_COUNTER
313 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
314 #elif defined(lint)
315 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
316 #else
317 #define	TCP_DBGSTAT(x)
318 #endif
319 
320 tcp_stat_t tcp_statistics = {
321 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
322 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
323 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
324 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
325 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
326 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
327 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
328 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
329 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
330 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
331 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
332 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
333 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
334 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
335 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
336 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
337 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
338 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
339 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
340 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
341 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
342 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
343 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
344 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
345 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
346 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
347 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
348 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
349 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
350 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
351 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
352 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
353 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
354 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
355 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
356 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
358 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
359 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
360 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
361 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
362 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
363 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
364 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
365 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
366 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
367 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
368 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
369 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
370 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
371 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
372 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
373 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
374 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
375 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
376 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
377 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
378 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
379 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
380 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
381 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
382 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
394 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
395 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
396 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
397 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
398 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
403 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
404 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
405 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
406 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
407 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
408 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
409 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
410 };
411 
412 static kstat_t *tcp_kstat;
413 
414 /*
415  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
416  * tcp write side.
417  */
418 #define	CALL_IP_WPUT(connp, q, mp) {					\
419 	ASSERT(((q)->q_flag & QREADR) == 0);				\
420 	TCP_DBGSTAT(tcp_ip_output);					\
421 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
422 }
423 
424 /* Macros for timestamp comparisons */
425 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
426 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
427 
428 /*
429  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
430  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
431  * by adding three components: a time component which grows by 1 every 4096
432  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
433  * a per-connection component which grows by 125000 for every new connection;
434  * and an "extra" component that grows by a random amount centered
435  * approximately on 64000.  This causes the the ISS generator to cycle every
436  * 4.89 hours if no TCP connections are made, and faster if connections are
437  * made.
438  *
439  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
440  * components: a time component which grows by 250000 every second; and
441  * a per-connection component which grows by 125000 for every new connections.
442  *
443  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
444  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
445  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
446  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
447  * password.
448  */
449 #define	ISS_INCR	250000
450 #define	ISS_NSEC_SHT	12
451 
452 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
453 static kmutex_t tcp_iss_key_lock;
454 static MD5_CTX tcp_iss_key;
455 static sin_t	sin_null;	/* Zero address for quick clears */
456 static sin6_t	sin6_null;	/* Zero address for quick clears */
457 
458 /* Packet dropper for TCP IPsec policy drops. */
459 static ipdropper_t tcp_dropper;
460 
461 /*
462  * This implementation follows the 4.3BSD interpretation of the urgent
463  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
464  * incompatible changes in protocols like telnet and rlogin.
465  */
466 #define	TCP_OLD_URP_INTERPRETATION	1
467 
468 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
469 	(TCP_IS_DETACHED(tcp) && \
470 	    (!(tcp)->tcp_hard_binding))
471 
472 /*
473  * TCP reassembly macros.  We hide starting and ending sequence numbers in
474  * b_next and b_prev of messages on the reassembly queue.  The messages are
475  * chained using b_cont.  These macros are used in tcp_reass() so we don't
476  * have to see the ugly casts and assignments.
477  */
478 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
479 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
480 					(mblk_t *)(uintptr_t)(u))
481 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
482 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
483 					(mblk_t *)(uintptr_t)(u))
484 
485 /*
486  * Implementation of TCP Timers.
487  * =============================
488  *
489  * INTERFACE:
490  *
491  * There are two basic functions dealing with tcp timers:
492  *
493  *	timeout_id_t	tcp_timeout(connp, func, time)
494  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
495  *	TCP_TIMER_RESTART(tcp, intvl)
496  *
497  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
498  * after 'time' ticks passed. The function called by timeout() must adhere to
499  * the same restrictions as a driver soft interrupt handler - it must not sleep
500  * or call other functions that might sleep. The value returned is the opaque
501  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
502  * cancel the request. The call to tcp_timeout() may fail in which case it
503  * returns zero. This is different from the timeout(9F) function which never
504  * fails.
505  *
506  * The call-back function 'func' always receives 'connp' as its single
507  * argument. It is always executed in the squeue corresponding to the tcp
508  * structure. The tcp structure is guaranteed to be present at the time the
509  * call-back is called.
510  *
511  * NOTE: The call-back function 'func' is never called if tcp is in
512  * 	the TCPS_CLOSED state.
513  *
514  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
515  * request. locks acquired by the call-back routine should not be held across
516  * the call to tcp_timeout_cancel() or a deadlock may result.
517  *
518  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
519  * Otherwise, it returns an integer value greater than or equal to 0. In
520  * particular, if the call-back function is already placed on the squeue, it can
521  * not be canceled.
522  *
523  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
524  * 	within squeue context corresponding to the tcp instance. Since the
525  *	call-back is also called via the same squeue, there are no race
526  *	conditions described in untimeout(9F) manual page since all calls are
527  *	strictly serialized.
528  *
529  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
530  *	stored in tcp_timer_tid and starts a new one using
531  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
532  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
533  *	field.
534  *
535  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
536  *	call-back may still be called, so it is possible tcp_timer() will be
537  *	called several times. This should not be a problem since tcp_timer()
538  *	should always check the tcp instance state.
539  *
540  *
541  * IMPLEMENTATION:
542  *
543  * TCP timers are implemented using three-stage process. The call to
544  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
545  * when the timer expires. The tcp_timer_callback() arranges the call of the
546  * tcp_timer_handler() function via squeue corresponding to the tcp
547  * instance. The tcp_timer_handler() calls actual requested timeout call-back
548  * and passes tcp instance as an argument to it. Information is passed between
549  * stages using the tcp_timer_t structure which contains the connp pointer, the
550  * tcp call-back to call and the timeout id returned by the timeout(9F).
551  *
552  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
553  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
554  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
555  * returns the pointer to this mblk.
556  *
557  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
558  * looks like a normal mblk without actual dblk attached to it.
559  *
560  * To optimize performance each tcp instance holds a small cache of timer
561  * mblocks. In the current implementation it caches up to two timer mblocks per
562  * tcp instance. The cache is preserved over tcp frees and is only freed when
563  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
564  * timer processing happens on a corresponding squeue, the cache manipulation
565  * does not require any locks. Experiments show that majority of timer mblocks
566  * allocations are satisfied from the tcp cache and do not involve kmem calls.
567  *
568  * The tcp_timeout() places a refhold on the connp instance which guarantees
569  * that it will be present at the time the call-back function fires. The
570  * tcp_timer_handler() drops the reference after calling the call-back, so the
571  * call-back function does not need to manipulate the references explicitly.
572  */
573 
574 typedef struct tcp_timer_s {
575 	conn_t	*connp;
576 	void 	(*tcpt_proc)(void *);
577 	timeout_id_t   tcpt_tid;
578 } tcp_timer_t;
579 
580 static kmem_cache_t *tcp_timercache;
581 kmem_cache_t	*tcp_sack_info_cache;
582 kmem_cache_t	*tcp_iphc_cache;
583 
584 /*
585  * For scalability, we must not run a timer for every TCP connection
586  * in TIME_WAIT state.  To see why, consider (for time wait interval of
587  * 4 minutes):
588  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
589  *
590  * This list is ordered by time, so you need only delete from the head
591  * until you get to entries which aren't old enough to delete yet.
592  * The list consists of only the detached TIME_WAIT connections.
593  *
594  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
595  * becomes detached TIME_WAIT (either by changing the state and already
596  * being detached or the other way around). This means that the TIME_WAIT
597  * state can be extended (up to doubled) if the connection doesn't become
598  * detached for a long time.
599  *
600  * The list manipulations (including tcp_time_wait_next/prev)
601  * are protected by the tcp_time_wait_lock. The content of the
602  * detached TIME_WAIT connections is protected by the normal perimeters.
603  */
604 
605 typedef struct tcp_squeue_priv_s {
606 	kmutex_t	tcp_time_wait_lock;
607 				/* Protects the next 3 globals */
608 	timeout_id_t	tcp_time_wait_tid;
609 	tcp_t		*tcp_time_wait_head;
610 	tcp_t		*tcp_time_wait_tail;
611 	tcp_t		*tcp_free_list;
612 	uint_t		tcp_free_list_cnt;
613 } tcp_squeue_priv_t;
614 
615 /*
616  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
617  * Running it every 5 seconds seems to give the best results.
618  */
619 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
620 
621 /*
622  * To prevent memory hog, limit the number of entries in tcp_free_list
623  * to 1% of available memory / number of cpus
624  */
625 uint_t tcp_free_list_max_cnt = 0;
626 
627 #define	TCP_XMIT_LOWATER	4096
628 #define	TCP_XMIT_HIWATER	49152
629 #define	TCP_RECV_LOWATER	2048
630 #define	TCP_RECV_HIWATER	49152
631 
632 /*
633  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
634  */
635 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
636 
637 #define	TIDUSZ	4096	/* transport interface data unit size */
638 
639 /*
640  * Bind hash list size and has function.  It has to be a power of 2 for
641  * hashing.
642  */
643 #define	TCP_BIND_FANOUT_SIZE	512
644 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
645 /*
646  * Size of listen and acceptor hash list.  It has to be a power of 2 for
647  * hashing.
648  */
649 #define	TCP_FANOUT_SIZE		256
650 
651 #ifdef	_ILP32
652 #define	TCP_ACCEPTOR_HASH(accid)					\
653 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
654 #else
655 #define	TCP_ACCEPTOR_HASH(accid)					\
656 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
657 #endif	/* _ILP32 */
658 
659 #define	IP_ADDR_CACHE_SIZE	2048
660 #define	IP_ADDR_CACHE_HASH(faddr)					\
661 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
662 
663 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
664 #define	TCP_HSP_HASH_SIZE 256
665 
666 #define	TCP_HSP_HASH(addr)					\
667 	(((addr>>24) ^ (addr >>16) ^			\
668 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
669 
670 /*
671  * TCP options struct returned from tcp_parse_options.
672  */
673 typedef struct tcp_opt_s {
674 	uint32_t	tcp_opt_mss;
675 	uint32_t	tcp_opt_wscale;
676 	uint32_t	tcp_opt_ts_val;
677 	uint32_t	tcp_opt_ts_ecr;
678 	tcp_t		*tcp;
679 } tcp_opt_t;
680 
681 /*
682  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
683  */
684 
685 #ifdef _BIG_ENDIAN
686 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
687 	(TCPOPT_TSTAMP << 8) | 10)
688 #else
689 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
690 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
691 #endif
692 
693 /*
694  * Flags returned from tcp_parse_options.
695  */
696 #define	TCP_OPT_MSS_PRESENT	1
697 #define	TCP_OPT_WSCALE_PRESENT	2
698 #define	TCP_OPT_TSTAMP_PRESENT	4
699 #define	TCP_OPT_SACK_OK_PRESENT	8
700 #define	TCP_OPT_SACK_PRESENT	16
701 
702 /* TCP option length */
703 #define	TCPOPT_NOP_LEN		1
704 #define	TCPOPT_MAXSEG_LEN	4
705 #define	TCPOPT_WS_LEN		3
706 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
707 #define	TCPOPT_TSTAMP_LEN	10
708 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
709 #define	TCPOPT_SACK_OK_LEN	2
710 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
711 #define	TCPOPT_REAL_SACK_LEN	4
712 #define	TCPOPT_MAX_SACK_LEN	36
713 #define	TCPOPT_HEADER_LEN	2
714 
715 /* TCP cwnd burst factor. */
716 #define	TCP_CWND_INFINITE	65535
717 #define	TCP_CWND_SS		3
718 #define	TCP_CWND_NORMAL		5
719 
720 /* Maximum TCP initial cwin (start/restart). */
721 #define	TCP_MAX_INIT_CWND	8
722 
723 /*
724  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
725  * either tcp_slow_start_initial or tcp_slow_start_after idle
726  * depending on the caller.  If the upper layer has not used the
727  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
728  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
729  * If the upper layer has changed set the tcp_init_cwnd, just use
730  * it to calculate the tcp_cwnd.
731  */
732 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
733 {									\
734 	if ((tcp)->tcp_init_cwnd == 0) {				\
735 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
736 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
737 	} else {							\
738 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
739 	}								\
740 	tcp->tcp_cwnd_cnt = 0;						\
741 }
742 
743 /* TCP Timer control structure */
744 typedef struct tcpt_s {
745 	pfv_t	tcpt_pfv;	/* The routine we are to call */
746 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
747 } tcpt_t;
748 
749 /* Host Specific Parameter structure */
750 typedef struct tcp_hsp {
751 	struct tcp_hsp	*tcp_hsp_next;
752 	in6_addr_t	tcp_hsp_addr_v6;
753 	in6_addr_t	tcp_hsp_subnet_v6;
754 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
755 	int32_t		tcp_hsp_sendspace;
756 	int32_t		tcp_hsp_recvspace;
757 	int32_t		tcp_hsp_tstamp;
758 } tcp_hsp_t;
759 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
760 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
761 
762 /*
763  * Functions called directly via squeue having a prototype of edesc_t.
764  */
765 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
766 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
767 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
768 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
769 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
770 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
771 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
772 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
773 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
774 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
775 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
776 
777 
778 /* Prototype for TCP functions */
779 static void	tcp_random_init(void);
780 int		tcp_random(void);
781 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
783 		    tcp_t *eager);
784 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
785 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
786     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
787     boolean_t user_specified);
788 static void	tcp_closei_local(tcp_t *tcp);
789 static void	tcp_close_detached(tcp_t *tcp);
790 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
791 			mblk_t *idmp, mblk_t **defermp);
792 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
793 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
794 		    in_port_t dstport, uint_t srcid);
795 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
796 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
797 		    uint32_t scope_id);
798 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
799 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
800 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
801 static char	*tcp_display(tcp_t *tcp, char *, char);
802 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
803 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
804 static void	tcp_eager_unlink(tcp_t *tcp);
805 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
806 		    int unixerr);
807 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
808 		    int tlierr, int unixerr);
809 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
810 		    cred_t *cr);
811 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
812 		    char *value, caddr_t cp, cred_t *cr);
813 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
814 		    char *value, caddr_t cp, cred_t *cr);
815 static int	tcp_tpistate(tcp_t *tcp);
816 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
817     int caller_holds_lock);
818 static void	tcp_bind_hash_remove(tcp_t *tcp);
819 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
820 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
821 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
822 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
823 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
824 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
825 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
826 static int	tcp_header_init_ipv4(tcp_t *tcp);
827 static int	tcp_header_init_ipv6(tcp_t *tcp);
828 int		tcp_init(tcp_t *tcp, queue_t *q);
829 static int	tcp_init_values(tcp_t *tcp);
830 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
831 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
832 		    t_scalar_t addr_length);
833 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
834 static void	tcp_ip_notify(tcp_t *tcp);
835 static mblk_t	*tcp_ire_mp(mblk_t *mp);
836 static void	tcp_iss_init(tcp_t *tcp);
837 static void	tcp_keepalive_killer(void *arg);
838 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
839 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
840 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
841 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
842 static boolean_t tcp_allow_connopt_set(int level, int name);
843 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
844 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
845 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
846 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
847 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
848 		    mblk_t *mblk);
849 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
850 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
851 		    uchar_t *ptr, uint_t len);
852 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
853 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
854 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
855 		    caddr_t cp, cred_t *cr);
856 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
857 		    caddr_t cp, cred_t *cr);
858 static void	tcp_iss_key_init(uint8_t *phrase, int len);
859 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
860 		    caddr_t cp, cred_t *cr);
861 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
862 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
863 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
864 static void	tcp_reinit(tcp_t *tcp);
865 static void	tcp_reinit_values(tcp_t *tcp);
866 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
867 		    tcp_t *thisstream, cred_t *cr);
868 
869 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
870 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
871 static boolean_t tcp_send_rst_chk(void);
872 static void	tcp_ss_rexmit(tcp_t *tcp);
873 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
874 static void	tcp_process_options(tcp_t *, tcph_t *);
875 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
876 static void	tcp_rsrv(queue_t *q);
877 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
878 static int	tcp_snmp_state(tcp_t *tcp);
879 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
880 		    cred_t *cr);
881 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
882 		    cred_t *cr);
883 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
884 		    cred_t *cr);
885 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
886 		    cred_t *cr);
887 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
888 		    cred_t *cr);
889 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
890 		    caddr_t cp, cred_t *cr);
891 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
892 		    caddr_t cp, cred_t *cr);
893 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
894 		    cred_t *cr);
895 static void	tcp_timer(void *arg);
896 static void	tcp_timer_callback(void *);
897 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
898     boolean_t random);
899 static in_port_t tcp_get_next_priv_port(const tcp_t *);
900 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
901 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
902 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
903 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
904 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
905 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
906 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
907 		    const int num_sack_blk, int *usable, uint_t *snxt,
908 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
909 		    const int mdt_thres);
910 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
911 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
912 		    const int num_sack_blk, int *usable, uint_t *snxt,
913 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
914 		    const int mdt_thres);
915 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
916 		    int num_sack_blk);
917 static void	tcp_wsrv(queue_t *q);
918 static int	tcp_xmit_end(tcp_t *tcp);
919 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
920 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
921 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
922 static void	tcp_ack_timer(void *arg);
923 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
924 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
925 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
926 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
927 		    uint32_t ack, int ctl);
928 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
929 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
930 static int	setmaxps(queue_t *q, int maxpsz);
931 static void	tcp_set_rto(tcp_t *, time_t);
932 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
933 		    boolean_t, boolean_t);
934 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
935 		    boolean_t ipsec_mctl);
936 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
937 		    char *opt, int optlen);
938 static int	tcp_build_hdrs(queue_t *, tcp_t *);
939 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
940 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
941 		    tcph_t *tcph);
942 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
943 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
944 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
945 boolean_t	tcp_reserved_port_check(in_port_t);
946 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
947 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
948 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
949 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
950 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
951 		    const boolean_t, const uint32_t, const uint32_t,
952 		    const uint32_t, const uint32_t);
953 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
954 		    const uint_t, const uint_t, boolean_t *);
955 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
956 extern mblk_t	*tcp_timermp_alloc(int);
957 extern void	tcp_timermp_free(tcp_t *);
958 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
959 static void	tcp_stop_lingering(tcp_t *tcp);
960 static void	tcp_close_linger_timeout(void *arg);
961 void		tcp_ddi_init(void);
962 void		tcp_ddi_destroy(void);
963 static void	tcp_kstat_init(void);
964 static void	tcp_kstat_fini(void);
965 static int	tcp_kstat_update(kstat_t *kp, int rw);
966 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
967 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
968 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
969 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
970 			tcph_t *tcph, mblk_t *idmp);
971 static squeue_func_t tcp_squeue_switch(int);
972 
973 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
974 static int	tcp_close(queue_t *, int);
975 static int	tcpclose_accept(queue_t *);
976 static int	tcp_modclose(queue_t *);
977 static void	tcp_wput_mod(queue_t *, mblk_t *);
978 
979 static void	tcp_squeue_add(squeue_t *);
980 static boolean_t tcp_zcopy_check(tcp_t *);
981 static void	tcp_zcopy_notify(tcp_t *);
982 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
983 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
984 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
985 
986 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
987 
988 /*
989  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
990  *
991  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
992  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
993  * (defined in tcp.h) needs to be filled in and passed into the kernel
994  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
995  * structure contains the four-tuple of a TCP connection and a range of TCP
996  * states (specified by ac_start and ac_end). The use of wildcard addresses
997  * and ports is allowed. Connections with a matching four tuple and a state
998  * within the specified range will be aborted. The valid states for the
999  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1000  * inclusive.
1001  *
1002  * An application which has its connection aborted by this ioctl will receive
1003  * an error that is dependent on the connection state at the time of the abort.
1004  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1005  * though a RST packet has been received.  If the connection state is equal to
1006  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1007  * and all resources associated with the connection will be freed.
1008  */
1009 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1010 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1011 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1012 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1013 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1014 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1015     boolean_t);
1016 
1017 static struct module_info tcp_rinfo =  {
1018 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1019 };
1020 
1021 static struct module_info tcp_winfo =  {
1022 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1023 };
1024 
1025 /*
1026  * Entry points for TCP as a module. It only allows SNMP requests
1027  * to pass through.
1028  */
1029 struct qinit tcp_mod_rinit = {
1030 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1031 };
1032 
1033 struct qinit tcp_mod_winit = {
1034 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1035 	&tcp_rinfo
1036 };
1037 
1038 /*
1039  * Entry points for TCP as a device. The normal case which supports
1040  * the TCP functionality.
1041  */
1042 struct qinit tcp_rinit = {
1043 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1044 };
1045 
1046 struct qinit tcp_winit = {
1047 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1048 };
1049 
1050 /* Initial entry point for TCP in socket mode. */
1051 struct qinit tcp_sock_winit = {
1052 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1053 };
1054 
1055 /*
1056  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1057  * an accept. Avoid allocating data structures since eager has already
1058  * been created.
1059  */
1060 struct qinit tcp_acceptor_rinit = {
1061 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1062 };
1063 
1064 struct qinit tcp_acceptor_winit = {
1065 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1066 };
1067 
1068 /*
1069  * Entry points for TCP loopback (read side only)
1070  */
1071 struct qinit tcp_loopback_rinit = {
1072 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1073 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1074 };
1075 
1076 struct streamtab tcpinfo = {
1077 	&tcp_rinit, &tcp_winit
1078 };
1079 
1080 extern squeue_func_t tcp_squeue_wput_proc;
1081 extern squeue_func_t tcp_squeue_timer_proc;
1082 
1083 /* Protected by tcp_g_q_lock */
1084 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1085 kmutex_t tcp_g_q_lock;
1086 
1087 /* Protected by tcp_hsp_lock */
1088 /*
1089  * XXX The host param mechanism should go away and instead we should use
1090  * the metrics associated with the routes to determine the default sndspace
1091  * and rcvspace.
1092  */
1093 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1094 krwlock_t tcp_hsp_lock;
1095 
1096 /*
1097  * Extra privileged ports. In host byte order.
1098  * Protected by tcp_epriv_port_lock.
1099  */
1100 #define	TCP_NUM_EPRIV_PORTS	64
1101 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1102 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1103 kmutex_t tcp_epriv_port_lock;
1104 
1105 /*
1106  * The smallest anonymous port in the privileged port range which TCP
1107  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1108  */
1109 static in_port_t tcp_min_anonpriv_port = 512;
1110 
1111 /* Only modified during _init and _fini thus no locking is needed. */
1112 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1113 
1114 /* Hint not protected by any lock */
1115 static uint_t	tcp_next_port_to_try;
1116 
1117 
1118 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1119 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1120 
1121 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1122 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1123 
1124 /*
1125  * TCP has a private interface for other kernel modules to reserve a
1126  * port range for them to use.  Once reserved, TCP will not use any ports
1127  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1128  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1129  * has to be verified.
1130  *
1131  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1132  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1133  * range is [port a, port b] inclusive.  And each port range is between
1134  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1135  *
1136  * Note that the default anonymous port range starts from 32768.  There is
1137  * no port "collision" between that and the reserved port range.  If there
1138  * is port collision (because the default smallest anonymous port is lowered
1139  * or some apps specifically bind to ports in the reserved port range), the
1140  * system may not be able to reserve a port range even there are enough
1141  * unbound ports as a reserved port range contains consecutive ports .
1142  */
1143 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1144 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1145 #define	TCP_SMALLEST_RESERVED_PORT		10240
1146 #define	TCP_LARGEST_RESERVED_PORT		20480
1147 
1148 /* Structure to represent those reserved port ranges. */
1149 typedef struct tcp_rport_s {
1150 	in_port_t	lo_port;
1151 	in_port_t	hi_port;
1152 	tcp_t		**temp_tcp_array;
1153 } tcp_rport_t;
1154 
1155 /* The reserved port array. */
1156 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1157 
1158 /* Locks to protect the tcp_reserved_ports array. */
1159 static krwlock_t tcp_reserved_port_lock;
1160 
1161 /* The number of ranges in the array. */
1162 uint32_t tcp_reserved_port_array_size = 0;
1163 
1164 /*
1165  * MIB-2 stuff for SNMP
1166  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1167  */
1168 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1169 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1170 
1171 boolean_t tcp_icmp_source_quench = B_FALSE;
1172 /*
1173  * Following assumes TPI alignment requirements stay along 32 bit
1174  * boundaries
1175  */
1176 #define	ROUNDUP32(x) \
1177 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1178 
1179 /* Template for response to info request. */
1180 static struct T_info_ack tcp_g_t_info_ack = {
1181 	T_INFO_ACK,		/* PRIM_type */
1182 	0,			/* TSDU_size */
1183 	T_INFINITE,		/* ETSDU_size */
1184 	T_INVALID,		/* CDATA_size */
1185 	T_INVALID,		/* DDATA_size */
1186 	sizeof (sin_t),		/* ADDR_size */
1187 	0,			/* OPT_size - not initialized here */
1188 	TIDUSZ,			/* TIDU_size */
1189 	T_COTS_ORD,		/* SERV_type */
1190 	TCPS_IDLE,		/* CURRENT_state */
1191 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1192 };
1193 
1194 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1195 	T_INFO_ACK,		/* PRIM_type */
1196 	0,			/* TSDU_size */
1197 	T_INFINITE,		/* ETSDU_size */
1198 	T_INVALID,		/* CDATA_size */
1199 	T_INVALID,		/* DDATA_size */
1200 	sizeof (sin6_t),	/* ADDR_size */
1201 	0,			/* OPT_size - not initialized here */
1202 	TIDUSZ,		/* TIDU_size */
1203 	T_COTS_ORD,		/* SERV_type */
1204 	TCPS_IDLE,		/* CURRENT_state */
1205 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1206 };
1207 
1208 #define	MS	1L
1209 #define	SECONDS	(1000 * MS)
1210 #define	MINUTES	(60 * SECONDS)
1211 #define	HOURS	(60 * MINUTES)
1212 #define	DAYS	(24 * HOURS)
1213 
1214 #define	PARAM_MAX (~(uint32_t)0)
1215 
1216 /* Max size IP datagram is 64k - 1 */
1217 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1218 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1219 /* Max of the above */
1220 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1221 
1222 /* Largest TCP port number */
1223 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1224 
1225 /*
1226  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1227  * layer header.  It has to be a multiple of 4.
1228  */
1229 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1230 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1231 
1232 /*
1233  * All of these are alterable, within the min/max values given, at run time.
1234  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1235  * per the TCP spec.
1236  */
1237 /* BEGIN CSTYLED */
1238 tcpparam_t	tcp_param_arr[] = {
1239  /*min		max		value		name */
1240  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1241  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1242  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1243  { 1,		1024,		1,		"tcp_conn_req_min" },
1244  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1245  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1246  { 0,		10,		0,		"tcp_debug" },
1247  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1248  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1249  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1250  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1251  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1252  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1253  { 1,		255,		64,		"tcp_ipv4_ttl"},
1254  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1255  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1256  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1257  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1258  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1259  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1260  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1261  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1262  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1263  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1264  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1265  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1266  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1267  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1268  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1269  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1270  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1271  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1272  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1273  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1274  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1275  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1276  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1277  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1278 /*
1279  * Question:  What default value should I set for tcp_strong_iss?
1280  */
1281  { 0,		2,		1,		"tcp_strong_iss"},
1282  { 0,		65536,		20,		"tcp_rtt_updates"},
1283  { 0,		1,		1,		"tcp_wscale_always"},
1284  { 0,		1,		0,		"tcp_tstamp_always"},
1285  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1286  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1287  { 0,		16,		2,		"tcp_deferred_acks_max"},
1288  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1289  { 1,		4,		4,		"tcp_slow_start_initial"},
1290  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1291  { 0,		2,		2,		"tcp_sack_permitted"},
1292  { 0,		1,		0,		"tcp_trace"},
1293  { 0,		1,		1,		"tcp_compression_enabled"},
1294  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1295  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1296  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1297  { 0,		1,		0,		"tcp_rev_src_routes"},
1298  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1299  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1300  { 0,		16,		8,		"tcp_local_dacks_max"},
1301  { 0,		2,		1,		"tcp_ecn_permitted"},
1302  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1303  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1304  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1305  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1306  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1307 };
1308 /* END CSTYLED */
1309 
1310 /*
1311  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1312  * each header fragment in the header buffer.  Each parameter value has
1313  * to be a multiple of 4 (32-bit aligned).
1314  */
1315 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1316 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1317 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1318 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1319 
1320 /*
1321  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1322  * the maximum number of payload buffers associated per Multidata.
1323  */
1324 static tcpparam_t tcp_mdt_max_pbufs_param =
1325 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1326 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1327 
1328 /* Round up the value to the nearest mss. */
1329 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1330 
1331 /*
1332  * Set ECN capable transport (ECT) code point in IP header.
1333  *
1334  * Note that there are 2 ECT code points '01' and '10', which are called
1335  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1336  * point ECT(0) for TCP as described in RFC 2481.
1337  */
1338 #define	SET_ECT(tcp, iph) \
1339 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1340 		/* We need to clear the code point first. */ \
1341 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1342 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1343 	} else { \
1344 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1345 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1346 	}
1347 
1348 /*
1349  * The format argument to pass to tcp_display().
1350  * DISP_PORT_ONLY means that the returned string has only port info.
1351  * DISP_ADDR_AND_PORT means that the returned string also contains the
1352  * remote and local IP address.
1353  */
1354 #define	DISP_PORT_ONLY		1
1355 #define	DISP_ADDR_AND_PORT	2
1356 
1357 /*
1358  * This controls the rate some ndd info report functions can be used
1359  * by non-privileged users.  It stores the last time such info is
1360  * requested.  When those report functions are called again, this
1361  * is checked with the current time and compare with the ndd param
1362  * tcp_ndd_get_info_interval.
1363  */
1364 static clock_t tcp_last_ndd_get_info_time = 0;
1365 #define	NDD_TOO_QUICK_MSG \
1366 	"ndd get info rate too high for non-privileged users, try again " \
1367 	"later.\n"
1368 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1369 
1370 #define	IS_VMLOANED_MBLK(mp) \
1371 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1372 
1373 /*
1374  * These two variables control the rate for TCP to generate RSTs in
1375  * response to segments not belonging to any connections.  We limit
1376  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1377  * each 1 second interval.  This is to protect TCP against DoS attack.
1378  */
1379 static clock_t tcp_last_rst_intrvl;
1380 static uint32_t tcp_rst_cnt;
1381 
1382 /* The number of RST not sent because of the rate limit. */
1383 static uint32_t tcp_rst_unsent;
1384 
1385 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1386 boolean_t tcp_mdt_chain = B_TRUE;
1387 
1388 /*
1389  * MDT threshold in the form of effective send MSS multiplier; we take
1390  * the MDT path if the amount of unsent data exceeds the threshold value
1391  * (default threshold is 1*SMSS).
1392  */
1393 uint_t tcp_mdt_smss_threshold = 1;
1394 
1395 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1396 
1397 /*
1398  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1399  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1400  * determined dynamically during tcp_adapt_ire(), which is the default.
1401  */
1402 boolean_t tcp_static_maxpsz = B_FALSE;
1403 
1404 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1405 uint32_t tcp_random_anon_port = 1;
1406 
1407 /*
1408  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1409  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1410  * data, TCP will not respond with an ACK.  RFC 793 requires that
1411  * TCP responds with an ACK for such a bogus ACK.  By not following
1412  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1413  * an attacker successfully spoofs an acceptable segment to our
1414  * peer; or when our peer is "confused."
1415  */
1416 uint32_t tcp_drop_ack_unsent_cnt = 10;
1417 
1418 /*
1419  * Hook functions to enable cluster networking
1420  * On non-clustered systems these vectors must always be NULL.
1421  */
1422 
1423 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1424 			    uint8_t *laddrp, in_port_t lport) = NULL;
1425 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1426 			    uint8_t *laddrp, in_port_t lport) = NULL;
1427 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1428 			    uint8_t *laddrp, in_port_t lport,
1429 			    uint8_t *faddrp, in_port_t fport) = NULL;
1430 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1431 			    uint8_t *laddrp, in_port_t lport,
1432 			    uint8_t *faddrp, in_port_t fport) = NULL;
1433 
1434 /*
1435  * The following are defined in ip.c
1436  */
1437 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1438 				uint8_t *laddrp);
1439 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1440 				uint8_t *laddrp, uint8_t *faddrp);
1441 
1442 #define	CL_INET_CONNECT(tcp)		{			\
1443 	if (cl_inet_connect != NULL) {				\
1444 		/*						\
1445 		 * Running in cluster mode - register active connection	\
1446 		 * information						\
1447 		 */							\
1448 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1449 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1450 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1451 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1452 				    (in_port_t)(tcp)->tcp_lport,	\
1453 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1454 				    (in_port_t)(tcp)->tcp_fport);	\
1455 			}						\
1456 		} else {						\
1457 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1458 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1459 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1460 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1461 				    (in_port_t)(tcp)->tcp_lport,	\
1462 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1463 				    (in_port_t)(tcp)->tcp_fport);	\
1464 			}						\
1465 		}							\
1466 	}								\
1467 }
1468 
1469 #define	CL_INET_DISCONNECT(tcp)	{				\
1470 	if (cl_inet_disconnect != NULL) {				\
1471 		/*							\
1472 		 * Running in cluster mode - deregister active		\
1473 		 * connection information				\
1474 		 */							\
1475 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1476 			if ((tcp)->tcp_ip_src != 0) {			\
1477 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1478 				    AF_INET,				\
1479 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1480 				    (in_port_t)(tcp)->tcp_lport,	\
1481 				    (uint8_t *)				\
1482 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1483 				    (in_port_t)(tcp)->tcp_fport);	\
1484 			}						\
1485 		} else {						\
1486 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1487 			    &(tcp)->tcp_ip_src_v6)) {			\
1488 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1489 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1490 				    (in_port_t)(tcp)->tcp_lport,	\
1491 				    (uint8_t *)				\
1492 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1493 				    (in_port_t)(tcp)->tcp_fport);	\
1494 			}						\
1495 		}							\
1496 	}								\
1497 }
1498 
1499 /*
1500  * Cluster networking hook for traversing current connection list.
1501  * This routine is used to extract the current list of live connections
1502  * which must continue to to be dispatched to this node.
1503  */
1504 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1505 
1506 /*
1507  * Figure out the value of window scale opton.  Note that the rwnd is
1508  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1509  * We cannot find the scale value and then do a round up of tcp_rwnd
1510  * because the scale value may not be correct after that.
1511  *
1512  * Set the compiler flag to make this function inline.
1513  */
1514 static void
1515 tcp_set_ws_value(tcp_t *tcp)
1516 {
1517 	int i;
1518 	uint32_t rwnd = tcp->tcp_rwnd;
1519 
1520 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1521 	    i++, rwnd >>= 1)
1522 		;
1523 	tcp->tcp_rcv_ws = i;
1524 }
1525 
1526 /*
1527  * Remove a connection from the list of detached TIME_WAIT connections.
1528  */
1529 static void
1530 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1531 {
1532 	boolean_t	locked = B_FALSE;
1533 
1534 	if (tcp_time_wait == NULL) {
1535 		tcp_time_wait = *((tcp_squeue_priv_t **)
1536 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1537 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1538 		locked = B_TRUE;
1539 	}
1540 
1541 	if (tcp->tcp_time_wait_expire == 0) {
1542 		ASSERT(tcp->tcp_time_wait_next == NULL);
1543 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1544 		if (locked)
1545 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1546 		return;
1547 	}
1548 	ASSERT(TCP_IS_DETACHED(tcp));
1549 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1550 
1551 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1552 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1553 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1554 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1555 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1556 			    NULL;
1557 		} else {
1558 			tcp_time_wait->tcp_time_wait_tail = NULL;
1559 		}
1560 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1561 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1562 		ASSERT(tcp->tcp_time_wait_next == NULL);
1563 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1564 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1565 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1566 	} else {
1567 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1568 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1569 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1570 		    tcp->tcp_time_wait_next;
1571 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1572 		    tcp->tcp_time_wait_prev;
1573 	}
1574 	tcp->tcp_time_wait_next = NULL;
1575 	tcp->tcp_time_wait_prev = NULL;
1576 	tcp->tcp_time_wait_expire = 0;
1577 
1578 	if (locked)
1579 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1580 }
1581 
1582 /*
1583  * Add a connection to the list of detached TIME_WAIT connections
1584  * and set its time to expire.
1585  */
1586 static void
1587 tcp_time_wait_append(tcp_t *tcp)
1588 {
1589 	tcp_squeue_priv_t *tcp_time_wait =
1590 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1591 		SQPRIVATE_TCP));
1592 
1593 	tcp_timers_stop(tcp);
1594 
1595 	/* Freed above */
1596 	ASSERT(tcp->tcp_timer_tid == 0);
1597 	ASSERT(tcp->tcp_ack_tid == 0);
1598 
1599 	/* must have happened at the time of detaching the tcp */
1600 	ASSERT(tcp->tcp_ptpahn == NULL);
1601 	ASSERT(tcp->tcp_flow_stopped == 0);
1602 	ASSERT(tcp->tcp_time_wait_next == NULL);
1603 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1604 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1605 	ASSERT(tcp->tcp_listener == NULL);
1606 
1607 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1608 	/*
1609 	 * The value computed below in tcp->tcp_time_wait_expire may
1610 	 * appear negative or wrap around. That is ok since our
1611 	 * interest is only in the difference between the current lbolt
1612 	 * value and tcp->tcp_time_wait_expire. But the value should not
1613 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1614 	 * The corresponding comparison in tcp_time_wait_collector() uses
1615 	 * modular arithmetic.
1616 	 */
1617 	tcp->tcp_time_wait_expire +=
1618 	    drv_usectohz(tcp_time_wait_interval * 1000);
1619 	if (tcp->tcp_time_wait_expire == 0)
1620 		tcp->tcp_time_wait_expire = 1;
1621 
1622 	ASSERT(TCP_IS_DETACHED(tcp));
1623 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1624 	ASSERT(tcp->tcp_time_wait_next == NULL);
1625 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1626 	TCP_DBGSTAT(tcp_time_wait);
1627 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1628 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1629 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1630 		tcp_time_wait->tcp_time_wait_head = tcp;
1631 	} else {
1632 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1633 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1634 		    TCPS_TIME_WAIT);
1635 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1636 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1637 	}
1638 	tcp_time_wait->tcp_time_wait_tail = tcp;
1639 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1640 }
1641 
1642 /* ARGSUSED */
1643 void
1644 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1645 {
1646 	conn_t	*connp = (conn_t *)arg;
1647 	tcp_t	*tcp = connp->conn_tcp;
1648 
1649 	ASSERT(tcp != NULL);
1650 	if (tcp->tcp_state == TCPS_CLOSED) {
1651 		return;
1652 	}
1653 
1654 	ASSERT((tcp->tcp_family == AF_INET &&
1655 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1656 	    (tcp->tcp_family == AF_INET6 &&
1657 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1658 	    tcp->tcp_ipversion == IPV6_VERSION)));
1659 	ASSERT(!tcp->tcp_listener);
1660 
1661 	TCP_STAT(tcp_time_wait_reap);
1662 	ASSERT(TCP_IS_DETACHED(tcp));
1663 
1664 	/*
1665 	 * Because they have no upstream client to rebind or tcp_close()
1666 	 * them later, we axe the connection here and now.
1667 	 */
1668 	tcp_close_detached(tcp);
1669 }
1670 
1671 void
1672 tcp_cleanup(tcp_t *tcp)
1673 {
1674 	mblk_t		*mp;
1675 	char		*tcp_iphc;
1676 	int		tcp_iphc_len;
1677 	int		tcp_hdr_grown;
1678 	tcp_sack_info_t	*tcp_sack_info;
1679 	conn_t		*connp = tcp->tcp_connp;
1680 
1681 	tcp_bind_hash_remove(tcp);
1682 	tcp_free(tcp);
1683 
1684 	/* Release any SSL context */
1685 	if (tcp->tcp_kssl_ent != NULL) {
1686 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1687 		tcp->tcp_kssl_ent = NULL;
1688 	}
1689 
1690 	if (tcp->tcp_kssl_ctx != NULL) {
1691 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1692 		tcp->tcp_kssl_ctx = NULL;
1693 	}
1694 	tcp->tcp_kssl_pending = B_FALSE;
1695 
1696 	conn_delete_ire(connp, NULL);
1697 	if (connp->conn_flags & IPCL_TCPCONN) {
1698 		if (connp->conn_latch != NULL)
1699 			IPLATCH_REFRELE(connp->conn_latch);
1700 		if (connp->conn_policy != NULL)
1701 			IPPH_REFRELE(connp->conn_policy);
1702 	}
1703 
1704 	/*
1705 	 * Since we will bzero the entire structure, we need to
1706 	 * remove it and reinsert it in global hash list. We
1707 	 * know the walkers can't get to this conn because we
1708 	 * had set CONDEMNED flag earlier and checked reference
1709 	 * under conn_lock so walker won't pick it and when we
1710 	 * go the ipcl_globalhash_remove() below, no walker
1711 	 * can get to it.
1712 	 */
1713 	ipcl_globalhash_remove(connp);
1714 
1715 	/* Save some state */
1716 	mp = tcp->tcp_timercache;
1717 
1718 	tcp_sack_info = tcp->tcp_sack_info;
1719 	tcp_iphc = tcp->tcp_iphc;
1720 	tcp_iphc_len = tcp->tcp_iphc_len;
1721 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1722 
1723 	if (connp->conn_cred != NULL)
1724 		crfree(connp->conn_cred);
1725 	if (connp->conn_peercred != NULL)
1726 		crfree(connp->conn_peercred);
1727 	bzero(connp, sizeof (conn_t));
1728 	bzero(tcp, sizeof (tcp_t));
1729 
1730 	/* restore the state */
1731 	tcp->tcp_timercache = mp;
1732 
1733 	tcp->tcp_sack_info = tcp_sack_info;
1734 	tcp->tcp_iphc = tcp_iphc;
1735 	tcp->tcp_iphc_len = tcp_iphc_len;
1736 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1737 
1738 
1739 	tcp->tcp_connp = connp;
1740 
1741 	connp->conn_tcp = tcp;
1742 	connp->conn_flags = IPCL_TCPCONN;
1743 	connp->conn_state_flags = CONN_INCIPIENT;
1744 	connp->conn_ulp = IPPROTO_TCP;
1745 	connp->conn_ref = 1;
1746 
1747 	ipcl_globalhash_insert(connp);
1748 }
1749 
1750 /*
1751  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1752  * is done forwards from the head.
1753  */
1754 /* ARGSUSED */
1755 void
1756 tcp_time_wait_collector(void *arg)
1757 {
1758 	tcp_t *tcp;
1759 	clock_t now;
1760 	mblk_t *mp;
1761 	conn_t *connp;
1762 	kmutex_t *lock;
1763 
1764 	squeue_t *sqp = (squeue_t *)arg;
1765 	tcp_squeue_priv_t *tcp_time_wait =
1766 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1767 
1768 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1769 	tcp_time_wait->tcp_time_wait_tid = 0;
1770 
1771 	if (tcp_time_wait->tcp_free_list != NULL &&
1772 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1773 		TCP_STAT(tcp_freelist_cleanup);
1774 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1775 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1776 			CONN_DEC_REF(tcp->tcp_connp);
1777 		}
1778 		tcp_time_wait->tcp_free_list_cnt = 0;
1779 	}
1780 
1781 	/*
1782 	 * In order to reap time waits reliably, we should use a
1783 	 * source of time that is not adjustable by the user -- hence
1784 	 * the call to ddi_get_lbolt().
1785 	 */
1786 	now = ddi_get_lbolt();
1787 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1788 		/*
1789 		 * Compare times using modular arithmetic, since
1790 		 * lbolt can wrapover.
1791 		 */
1792 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1793 			break;
1794 		}
1795 
1796 		tcp_time_wait_remove(tcp, tcp_time_wait);
1797 
1798 		connp = tcp->tcp_connp;
1799 		ASSERT(connp->conn_fanout != NULL);
1800 		lock = &connp->conn_fanout->connf_lock;
1801 		/*
1802 		 * This is essentially a TW reclaim fast path optimization for
1803 		 * performance where the timewait collector checks under the
1804 		 * fanout lock (so that no one else can get access to the
1805 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1806 		 * the classifier hash list. If ref count is indeed 2, we can
1807 		 * just remove the conn under the fanout lock and avoid
1808 		 * cleaning up the conn under the squeue, provided that
1809 		 * clustering callbacks are not enabled. If clustering is
1810 		 * enabled, we need to make the clustering callback before
1811 		 * setting the CONDEMNED flag and after dropping all locks and
1812 		 * so we forego this optimization and fall back to the slow
1813 		 * path. Also please see the comments in tcp_closei_local
1814 		 * regarding the refcnt logic.
1815 		 *
1816 		 * Since we are holding the tcp_time_wait_lock, its better
1817 		 * not to block on the fanout_lock because other connections
1818 		 * can't add themselves to time_wait list. So we do a
1819 		 * tryenter instead of mutex_enter.
1820 		 */
1821 		if (mutex_tryenter(lock)) {
1822 			mutex_enter(&connp->conn_lock);
1823 			if ((connp->conn_ref == 2) &&
1824 			    (cl_inet_disconnect == NULL)) {
1825 				ipcl_hash_remove_locked(connp,
1826 				    connp->conn_fanout);
1827 				/*
1828 				 * Set the CONDEMNED flag now itself so that
1829 				 * the refcnt cannot increase due to any
1830 				 * walker. But we have still not cleaned up
1831 				 * conn_ire_cache. This is still ok since
1832 				 * we are going to clean it up in tcp_cleanup
1833 				 * immediately and any interface unplumb
1834 				 * thread will wait till the ire is blown away
1835 				 */
1836 				connp->conn_state_flags |= CONN_CONDEMNED;
1837 				mutex_exit(lock);
1838 				mutex_exit(&connp->conn_lock);
1839 				if (tcp_time_wait->tcp_free_list_cnt <
1840 				    tcp_free_list_max_cnt) {
1841 					/* Add to head of tcp_free_list */
1842 					mutex_exit(
1843 					    &tcp_time_wait->tcp_time_wait_lock);
1844 					tcp_cleanup(tcp);
1845 					mutex_enter(
1846 					    &tcp_time_wait->tcp_time_wait_lock);
1847 					tcp->tcp_time_wait_next =
1848 					    tcp_time_wait->tcp_free_list;
1849 					tcp_time_wait->tcp_free_list = tcp;
1850 					tcp_time_wait->tcp_free_list_cnt++;
1851 					continue;
1852 				} else {
1853 					/* Do not add to tcp_free_list */
1854 					mutex_exit(
1855 					    &tcp_time_wait->tcp_time_wait_lock);
1856 					tcp_bind_hash_remove(tcp);
1857 					conn_delete_ire(tcp->tcp_connp, NULL);
1858 					CONN_DEC_REF(tcp->tcp_connp);
1859 				}
1860 			} else {
1861 				CONN_INC_REF_LOCKED(connp);
1862 				mutex_exit(lock);
1863 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1864 				mutex_exit(&connp->conn_lock);
1865 				/*
1866 				 * We can reuse the closemp here since conn has
1867 				 * detached (otherwise we wouldn't even be in
1868 				 * time_wait list).
1869 				 */
1870 				mp = &tcp->tcp_closemp;
1871 				squeue_fill(connp->conn_sqp, mp,
1872 				    tcp_timewait_output, connp,
1873 				    SQTAG_TCP_TIMEWAIT);
1874 			}
1875 		} else {
1876 			mutex_enter(&connp->conn_lock);
1877 			CONN_INC_REF_LOCKED(connp);
1878 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1879 			mutex_exit(&connp->conn_lock);
1880 			/*
1881 			 * We can reuse the closemp here since conn has
1882 			 * detached (otherwise we wouldn't even be in
1883 			 * time_wait list).
1884 			 */
1885 			mp = &tcp->tcp_closemp;
1886 			squeue_fill(connp->conn_sqp, mp,
1887 			    tcp_timewait_output, connp, 0);
1888 		}
1889 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1890 	}
1891 
1892 	if (tcp_time_wait->tcp_free_list != NULL)
1893 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1894 
1895 	tcp_time_wait->tcp_time_wait_tid =
1896 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1897 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1898 }
1899 
1900 /*
1901  * Reply to a clients T_CONN_RES TPI message. This function
1902  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1903  * on the acceptor STREAM and processed in tcp_wput_accept().
1904  * Read the block comment on top of tcp_conn_request().
1905  */
1906 static void
1907 tcp_accept(tcp_t *listener, mblk_t *mp)
1908 {
1909 	tcp_t	*acceptor;
1910 	tcp_t	*eager;
1911 	tcp_t   *tcp;
1912 	struct T_conn_res	*tcr;
1913 	t_uscalar_t	acceptor_id;
1914 	t_scalar_t	seqnum;
1915 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1916 	mblk_t	*ok_mp;
1917 	mblk_t	*mp1;
1918 
1919 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1920 		tcp_err_ack(listener, mp, TPROTO, 0);
1921 		return;
1922 	}
1923 	tcr = (struct T_conn_res *)mp->b_rptr;
1924 
1925 	/*
1926 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1927 	 * read side queue of the streams device underneath us i.e. the
1928 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1929 	 * look it up in the queue_hash.  Under LP64 it sends down the
1930 	 * minor_t of the accepting endpoint.
1931 	 *
1932 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1933 	 * fanout hash lock is held.
1934 	 * This prevents any thread from entering the acceptor queue from
1935 	 * below (since it has not been hard bound yet i.e. any inbound
1936 	 * packets will arrive on the listener or default tcp queue and
1937 	 * go through tcp_lookup).
1938 	 * The CONN_INC_REF will prevent the acceptor from closing.
1939 	 *
1940 	 * XXX It is still possible for a tli application to send down data
1941 	 * on the accepting stream while another thread calls t_accept.
1942 	 * This should not be a problem for well-behaved applications since
1943 	 * the T_OK_ACK is sent after the queue swapping is completed.
1944 	 *
1945 	 * If the accepting fd is the same as the listening fd, avoid
1946 	 * queue hash lookup since that will return an eager listener in a
1947 	 * already established state.
1948 	 */
1949 	acceptor_id = tcr->ACCEPTOR_id;
1950 	mutex_enter(&listener->tcp_eager_lock);
1951 	if (listener->tcp_acceptor_id == acceptor_id) {
1952 		eager = listener->tcp_eager_next_q;
1953 		/* only count how many T_CONN_INDs so don't count q0 */
1954 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1955 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1956 			mutex_exit(&listener->tcp_eager_lock);
1957 			tcp_err_ack(listener, mp, TBADF, 0);
1958 			return;
1959 		}
1960 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1961 			/* Throw away all the eagers on q0. */
1962 			tcp_eager_cleanup(listener, 1);
1963 		}
1964 		if (listener->tcp_syn_defense) {
1965 			listener->tcp_syn_defense = B_FALSE;
1966 			if (listener->tcp_ip_addr_cache != NULL) {
1967 				kmem_free(listener->tcp_ip_addr_cache,
1968 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1969 				listener->tcp_ip_addr_cache = NULL;
1970 			}
1971 		}
1972 		/*
1973 		 * Transfer tcp_conn_req_max to the eager so that when
1974 		 * a disconnect occurs we can revert the endpoint to the
1975 		 * listen state.
1976 		 */
1977 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1978 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1979 		/*
1980 		 * Get a reference on the acceptor just like the
1981 		 * tcp_acceptor_hash_lookup below.
1982 		 */
1983 		acceptor = listener;
1984 		CONN_INC_REF(acceptor->tcp_connp);
1985 	} else {
1986 		acceptor = tcp_acceptor_hash_lookup(acceptor_id);
1987 		if (acceptor == NULL) {
1988 			if (listener->tcp_debug) {
1989 				(void) strlog(TCP_MOD_ID, 0, 1,
1990 				    SL_ERROR|SL_TRACE,
1991 				    "tcp_accept: did not find acceptor 0x%x\n",
1992 				    acceptor_id);
1993 			}
1994 			mutex_exit(&listener->tcp_eager_lock);
1995 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1996 			return;
1997 		}
1998 		/*
1999 		 * Verify acceptor state. The acceptable states for an acceptor
2000 		 * include TCPS_IDLE and TCPS_BOUND.
2001 		 */
2002 		switch (acceptor->tcp_state) {
2003 		case TCPS_IDLE:
2004 			/* FALLTHRU */
2005 		case TCPS_BOUND:
2006 			break;
2007 		default:
2008 			CONN_DEC_REF(acceptor->tcp_connp);
2009 			mutex_exit(&listener->tcp_eager_lock);
2010 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2011 			return;
2012 		}
2013 	}
2014 
2015 	/* The listener must be in TCPS_LISTEN */
2016 	if (listener->tcp_state != TCPS_LISTEN) {
2017 		CONN_DEC_REF(acceptor->tcp_connp);
2018 		mutex_exit(&listener->tcp_eager_lock);
2019 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2020 		return;
2021 	}
2022 
2023 	/*
2024 	 * Rendezvous with an eager connection request packet hanging off
2025 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2026 	 * tcp structure when the connection packet arrived in
2027 	 * tcp_conn_request().
2028 	 */
2029 	seqnum = tcr->SEQ_number;
2030 	eager = listener;
2031 	do {
2032 		eager = eager->tcp_eager_next_q;
2033 		if (eager == NULL) {
2034 			CONN_DEC_REF(acceptor->tcp_connp);
2035 			mutex_exit(&listener->tcp_eager_lock);
2036 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2037 			return;
2038 		}
2039 	} while (eager->tcp_conn_req_seqnum != seqnum);
2040 	mutex_exit(&listener->tcp_eager_lock);
2041 
2042 	/*
2043 	 * At this point, both acceptor and listener have 2 ref
2044 	 * that they begin with. Acceptor has one additional ref
2045 	 * we placed in lookup while listener has 3 additional
2046 	 * ref for being behind the squeue (tcp_accept() is
2047 	 * done on listener's squeue); being in classifier hash;
2048 	 * and eager's ref on listener.
2049 	 */
2050 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2051 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2052 
2053 	/*
2054 	 * The eager at this point is set in its own squeue and
2055 	 * could easily have been killed (tcp_accept_finish will
2056 	 * deal with that) because of a TH_RST so we can only
2057 	 * ASSERT for a single ref.
2058 	 */
2059 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2060 
2061 	/* Pre allocate the stroptions mblk also */
2062 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2063 	if (opt_mp == NULL) {
2064 		CONN_DEC_REF(acceptor->tcp_connp);
2065 		CONN_DEC_REF(eager->tcp_connp);
2066 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2067 		return;
2068 	}
2069 	DB_TYPE(opt_mp) = M_SETOPTS;
2070 	opt_mp->b_wptr += sizeof (struct stroptions);
2071 
2072 	/*
2073 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2074 	 * from listener to acceptor. The message is chained on opt_mp
2075 	 * which will be sent onto eager's squeue.
2076 	 */
2077 	if (listener->tcp_bound_if != 0) {
2078 		/* allocate optmgmt req */
2079 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2080 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2081 		    sizeof (int));
2082 		if (mp1 != NULL)
2083 			linkb(opt_mp, mp1);
2084 	}
2085 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2086 		uint_t on = 1;
2087 
2088 		/* allocate optmgmt req */
2089 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2090 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2091 		if (mp1 != NULL)
2092 			linkb(opt_mp, mp1);
2093 	}
2094 
2095 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2096 	if ((mp1 = copymsg(mp)) == NULL) {
2097 		CONN_DEC_REF(acceptor->tcp_connp);
2098 		CONN_DEC_REF(eager->tcp_connp);
2099 		freemsg(opt_mp);
2100 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2101 		return;
2102 	}
2103 
2104 	tcr = (struct T_conn_res *)mp1->b_rptr;
2105 
2106 	/*
2107 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2108 	 * which allocates a larger mblk and appends the new
2109 	 * local address to the ok_ack.  The address is copied by
2110 	 * soaccept() for getsockname().
2111 	 */
2112 	{
2113 		int extra;
2114 
2115 		extra = (eager->tcp_family == AF_INET) ?
2116 		    sizeof (sin_t) : sizeof (sin6_t);
2117 
2118 		/*
2119 		 * Try to re-use mp, if possible.  Otherwise, allocate
2120 		 * an mblk and return it as ok_mp.  In any case, mp
2121 		 * is no longer usable upon return.
2122 		 */
2123 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2124 			CONN_DEC_REF(acceptor->tcp_connp);
2125 			CONN_DEC_REF(eager->tcp_connp);
2126 			freemsg(opt_mp);
2127 			/* Original mp has been freed by now, so use mp1 */
2128 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2129 			return;
2130 		}
2131 
2132 		mp = NULL;	/* We should never use mp after this point */
2133 
2134 		switch (extra) {
2135 		case sizeof (sin_t): {
2136 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2137 
2138 				ok_mp->b_wptr += extra;
2139 				sin->sin_family = AF_INET;
2140 				sin->sin_port = eager->tcp_lport;
2141 				sin->sin_addr.s_addr =
2142 				    eager->tcp_ipha->ipha_src;
2143 				break;
2144 			}
2145 		case sizeof (sin6_t): {
2146 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2147 
2148 				ok_mp->b_wptr += extra;
2149 				sin6->sin6_family = AF_INET6;
2150 				sin6->sin6_port = eager->tcp_lport;
2151 				if (eager->tcp_ipversion == IPV4_VERSION) {
2152 					sin6->sin6_flowinfo = 0;
2153 					IN6_IPADDR_TO_V4MAPPED(
2154 					    eager->tcp_ipha->ipha_src,
2155 					    &sin6->sin6_addr);
2156 				} else {
2157 					ASSERT(eager->tcp_ip6h != NULL);
2158 					sin6->sin6_flowinfo =
2159 					    eager->tcp_ip6h->ip6_vcf &
2160 					    ~IPV6_VERS_AND_FLOW_MASK;
2161 					sin6->sin6_addr =
2162 					    eager->tcp_ip6h->ip6_src;
2163 				}
2164 				break;
2165 			}
2166 		default:
2167 			break;
2168 		}
2169 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2170 	}
2171 
2172 	/*
2173 	 * If there are no options we know that the T_CONN_RES will
2174 	 * succeed. However, we can't send the T_OK_ACK upstream until
2175 	 * the tcp_accept_swap is done since it would be dangerous to
2176 	 * let the application start using the new fd prior to the swap.
2177 	 */
2178 	tcp_accept_swap(listener, acceptor, eager);
2179 
2180 	/*
2181 	 * tcp_accept_swap unlinks eager from listener but does not drop
2182 	 * the eager's reference on the listener.
2183 	 */
2184 	ASSERT(eager->tcp_listener == NULL);
2185 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2186 
2187 	/*
2188 	 * The eager is now associated with its own queue. Insert in
2189 	 * the hash so that the connection can be reused for a future
2190 	 * T_CONN_RES.
2191 	 */
2192 	tcp_acceptor_hash_insert(acceptor_id, eager);
2193 
2194 	/*
2195 	 * We now do the processing of options with T_CONN_RES.
2196 	 * We delay till now since we wanted to have queue to pass to
2197 	 * option processing routines that points back to the right
2198 	 * instance structure which does not happen until after
2199 	 * tcp_accept_swap().
2200 	 *
2201 	 * Note:
2202 	 * The sanity of the logic here assumes that whatever options
2203 	 * are appropriate to inherit from listner=>eager are done
2204 	 * before this point, and whatever were to be overridden (or not)
2205 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2206 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2207 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2208 	 * This may not be true at this point in time but can be fixed
2209 	 * independently. This option processing code starts with
2210 	 * the instantiated acceptor instance and the final queue at
2211 	 * this point.
2212 	 */
2213 
2214 	if (tcr->OPT_length != 0) {
2215 		/* Options to process */
2216 		int t_error = 0;
2217 		int sys_error = 0;
2218 		int do_disconnect = 0;
2219 
2220 		if (tcp_conprim_opt_process(eager, mp1,
2221 		    &do_disconnect, &t_error, &sys_error) < 0) {
2222 			eager->tcp_accept_error = 1;
2223 			if (do_disconnect) {
2224 				/*
2225 				 * An option failed which does not allow
2226 				 * connection to be accepted.
2227 				 *
2228 				 * We allow T_CONN_RES to succeed and
2229 				 * put a T_DISCON_IND on the eager queue.
2230 				 */
2231 				ASSERT(t_error == 0 && sys_error == 0);
2232 				eager->tcp_send_discon_ind = 1;
2233 			} else {
2234 				ASSERT(t_error != 0);
2235 				freemsg(ok_mp);
2236 				/*
2237 				 * Original mp was either freed or set
2238 				 * to ok_mp above, so use mp1 instead.
2239 				 */
2240 				tcp_err_ack(listener, mp1, t_error, sys_error);
2241 				goto finish;
2242 			}
2243 		}
2244 		/*
2245 		 * Most likely success in setting options (except if
2246 		 * eager->tcp_send_discon_ind set).
2247 		 * mp1 option buffer represented by OPT_length/offset
2248 		 * potentially modified and contains results of setting
2249 		 * options at this point
2250 		 */
2251 	}
2252 
2253 	/* We no longer need mp1, since all options processing has passed */
2254 	freemsg(mp1);
2255 
2256 	putnext(listener->tcp_rq, ok_mp);
2257 
2258 	mutex_enter(&listener->tcp_eager_lock);
2259 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2260 		tcp_t	*tail;
2261 		mblk_t	*conn_ind;
2262 
2263 		/*
2264 		 * This path should not be executed if listener and
2265 		 * acceptor streams are the same.
2266 		 */
2267 		ASSERT(listener != acceptor);
2268 
2269 		tcp = listener->tcp_eager_prev_q0;
2270 		/*
2271 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2272 		 * deferred T_conn_ind queue. We need to get to the head of
2273 		 * the queue in order to send up T_conn_ind the same order as
2274 		 * how the 3WHS is completed.
2275 		 */
2276 		while (tcp != listener) {
2277 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2278 				break;
2279 			else
2280 				tcp = tcp->tcp_eager_prev_q0;
2281 		}
2282 		ASSERT(tcp != listener);
2283 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2284 		ASSERT(conn_ind != NULL);
2285 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2286 
2287 		/* Move from q0 to q */
2288 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2289 		listener->tcp_conn_req_cnt_q0--;
2290 		listener->tcp_conn_req_cnt_q++;
2291 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2292 		    tcp->tcp_eager_prev_q0;
2293 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2294 		    tcp->tcp_eager_next_q0;
2295 		tcp->tcp_eager_prev_q0 = NULL;
2296 		tcp->tcp_eager_next_q0 = NULL;
2297 		tcp->tcp_conn_def_q0 = B_FALSE;
2298 
2299 		/*
2300 		 * Insert at end of the queue because sockfs sends
2301 		 * down T_CONN_RES in chronological order. Leaving
2302 		 * the older conn indications at front of the queue
2303 		 * helps reducing search time.
2304 		 */
2305 		tail = listener->tcp_eager_last_q;
2306 		if (tail != NULL)
2307 			tail->tcp_eager_next_q = tcp;
2308 		else
2309 			listener->tcp_eager_next_q = tcp;
2310 		listener->tcp_eager_last_q = tcp;
2311 		tcp->tcp_eager_next_q = NULL;
2312 		mutex_exit(&listener->tcp_eager_lock);
2313 		putnext(tcp->tcp_rq, conn_ind);
2314 	} else {
2315 		mutex_exit(&listener->tcp_eager_lock);
2316 	}
2317 
2318 	/*
2319 	 * Done with the acceptor - free it
2320 	 *
2321 	 * Note: from this point on, no access to listener should be made
2322 	 * as listener can be equal to acceptor.
2323 	 */
2324 finish:
2325 	ASSERT(acceptor->tcp_detached);
2326 	acceptor->tcp_rq = tcp_g_q;
2327 	acceptor->tcp_wq = WR(tcp_g_q);
2328 	(void) tcp_clean_death(acceptor, 0, 2);
2329 	CONN_DEC_REF(acceptor->tcp_connp);
2330 
2331 	/*
2332 	 * In case we already received a FIN we have to make tcp_rput send
2333 	 * the ordrel_ind. This will also send up a window update if the window
2334 	 * has opened up.
2335 	 *
2336 	 * In the normal case of a successful connection acceptance
2337 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2338 	 * indication that this was just accepted. This tells tcp_rput to
2339 	 * pass up any data queued in tcp_rcv_list.
2340 	 *
2341 	 * In the fringe case where options sent with T_CONN_RES failed and
2342 	 * we required, we would be indicating a T_DISCON_IND to blow
2343 	 * away this connection.
2344 	 */
2345 
2346 	/*
2347 	 * XXX: we currently have a problem if XTI application closes the
2348 	 * acceptor stream in between. This problem exists in on10-gate also
2349 	 * and is well know but nothing can be done short of major rewrite
2350 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2351 	 * eager same squeue as listener (we can distinguish non socket
2352 	 * listeners at the time of handling a SYN in tcp_conn_request)
2353 	 * and do most of the work that tcp_accept_finish does here itself
2354 	 * and then get behind the acceptor squeue to access the acceptor
2355 	 * queue.
2356 	 */
2357 	/*
2358 	 * We already have a ref on tcp so no need to do one before squeue_fill
2359 	 */
2360 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2361 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2362 }
2363 
2364 /*
2365  * Swap information between the eager and acceptor for a TLI/XTI client.
2366  * The sockfs accept is done on the acceptor stream and control goes
2367  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2368  * called. In either case, both the eager and listener are in their own
2369  * perimeter (squeue) and the code has to deal with potential race.
2370  *
2371  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2372  */
2373 static void
2374 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2375 {
2376 	conn_t	*econnp, *aconnp;
2377 
2378 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2379 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2380 	ASSERT(!eager->tcp_hard_bound);
2381 	ASSERT(!TCP_IS_SOCKET(acceptor));
2382 	ASSERT(!TCP_IS_SOCKET(eager));
2383 	ASSERT(!TCP_IS_SOCKET(listener));
2384 
2385 	acceptor->tcp_detached = B_TRUE;
2386 	/*
2387 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2388 	 * the acceptor id.
2389 	 */
2390 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2391 
2392 	/* remove eager from listen list... */
2393 	mutex_enter(&listener->tcp_eager_lock);
2394 	tcp_eager_unlink(eager);
2395 	ASSERT(eager->tcp_eager_next_q == NULL &&
2396 	    eager->tcp_eager_last_q == NULL);
2397 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2398 	    eager->tcp_eager_prev_q0 == NULL);
2399 	mutex_exit(&listener->tcp_eager_lock);
2400 	eager->tcp_rq = acceptor->tcp_rq;
2401 	eager->tcp_wq = acceptor->tcp_wq;
2402 
2403 	econnp = eager->tcp_connp;
2404 	aconnp = acceptor->tcp_connp;
2405 
2406 	eager->tcp_rq->q_ptr = econnp;
2407 	eager->tcp_wq->q_ptr = econnp;
2408 	eager->tcp_detached = B_FALSE;
2409 
2410 	ASSERT(eager->tcp_ack_tid == 0);
2411 
2412 	econnp->conn_dev = aconnp->conn_dev;
2413 	if (eager->tcp_cred != NULL)
2414 		crfree(eager->tcp_cred);
2415 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2416 	econnp->conn_zoneid = aconnp->conn_zoneid;
2417 	aconnp->conn_cred = NULL;
2418 
2419 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2420 	aconnp->conn_mac_exempt = B_FALSE;
2421 
2422 	ASSERT(aconnp->conn_peercred == NULL);
2423 
2424 	/* Do the IPC initialization */
2425 	CONN_INC_REF(econnp);
2426 
2427 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2428 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2429 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2430 	econnp->conn_ulp = aconnp->conn_ulp;
2431 
2432 	/* Done with old IPC. Drop its ref on its connp */
2433 	CONN_DEC_REF(aconnp);
2434 }
2435 
2436 
2437 /*
2438  * Adapt to the information, such as rtt and rtt_sd, provided from the
2439  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2440  *
2441  * Checks for multicast and broadcast destination address.
2442  * Returns zero on failure; non-zero if ok.
2443  *
2444  * Note that the MSS calculation here is based on the info given in
2445  * the IRE.  We do not do any calculation based on TCP options.  They
2446  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2447  * knows which options to use.
2448  *
2449  * Note on how TCP gets its parameters for a connection.
2450  *
2451  * When a tcp_t structure is allocated, it gets all the default parameters.
2452  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2453  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2454  * default.  But if there is an associated tcp_host_param, it will override
2455  * the metrics.
2456  *
2457  * An incoming SYN with a multicast or broadcast destination address, is dropped
2458  * in 1 of 2 places.
2459  *
2460  * 1. If the packet was received over the wire it is dropped in
2461  * ip_rput_process_broadcast()
2462  *
2463  * 2. If the packet was received through internal IP loopback, i.e. the packet
2464  * was generated and received on the same machine, it is dropped in
2465  * ip_wput_local()
2466  *
2467  * An incoming SYN with a multicast or broadcast source address is always
2468  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2469  * reject an attempt to connect to a broadcast or multicast (destination)
2470  * address.
2471  */
2472 static int
2473 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2474 {
2475 	tcp_hsp_t	*hsp;
2476 	ire_t		*ire;
2477 	ire_t		*sire = NULL;
2478 	iulp_t		*ire_uinfo = NULL;
2479 	uint32_t	mss_max;
2480 	uint32_t	mss;
2481 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2482 	conn_t		*connp = tcp->tcp_connp;
2483 	boolean_t	ire_cacheable = B_FALSE;
2484 	zoneid_t	zoneid = connp->conn_zoneid;
2485 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2486 			    MATCH_IRE_SECATTR;
2487 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2488 	ill_t		*ill = NULL;
2489 	boolean_t	incoming = (ire_mp == NULL);
2490 
2491 	ASSERT(connp->conn_ire_cache == NULL);
2492 
2493 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2494 
2495 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2496 			BUMP_MIB(&ip_mib, ipInDiscards);
2497 			return (0);
2498 		}
2499 		/*
2500 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2501 		 * for the destination with the nexthop as gateway.
2502 		 * ire_ctable_lookup() is used because this particular
2503 		 * ire, if it exists, will be marked private.
2504 		 * If that is not available, use the interface ire
2505 		 * for the nexthop.
2506 		 *
2507 		 * TSol: tcp_update_label will detect label mismatches based
2508 		 * only on the destination's label, but that would not
2509 		 * detect label mismatches based on the security attributes
2510 		 * of routes or next hop gateway. Hence we need to pass the
2511 		 * label to ire_ftable_lookup below in order to locate the
2512 		 * right prefix (and/or) ire cache. Similarly we also need
2513 		 * pass the label to the ire_cache_lookup below to locate
2514 		 * the right ire that also matches on the label.
2515 		 */
2516 		if (tcp->tcp_connp->conn_nexthop_set) {
2517 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2518 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2519 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2520 			if (ire == NULL) {
2521 				ire = ire_ftable_lookup(
2522 				    tcp->tcp_connp->conn_nexthop_v4,
2523 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2524 				    tsl, match_flags);
2525 				if (ire == NULL)
2526 					return (0);
2527 			} else {
2528 				ire_uinfo = &ire->ire_uinfo;
2529 			}
2530 		} else {
2531 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2532 			    zoneid, tsl);
2533 			if (ire != NULL) {
2534 				ire_cacheable = B_TRUE;
2535 				ire_uinfo = (ire_mp != NULL) ?
2536 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2537 				    &ire->ire_uinfo;
2538 
2539 			} else {
2540 				if (ire_mp == NULL) {
2541 					ire = ire_ftable_lookup(
2542 					    tcp->tcp_connp->conn_rem,
2543 					    0, 0, 0, NULL, &sire, zoneid, 0,
2544 					    tsl, (MATCH_IRE_RECURSIVE |
2545 					    MATCH_IRE_DEFAULT));
2546 					if (ire == NULL)
2547 						return (0);
2548 					ire_uinfo = (sire != NULL) ?
2549 					    &sire->ire_uinfo :
2550 					    &ire->ire_uinfo;
2551 				} else {
2552 					ire = (ire_t *)ire_mp->b_rptr;
2553 					ire_uinfo =
2554 					    &((ire_t *)
2555 					    ire_mp->b_rptr)->ire_uinfo;
2556 				}
2557 			}
2558 		}
2559 		ASSERT(ire != NULL);
2560 
2561 		if ((ire->ire_src_addr == INADDR_ANY) ||
2562 		    (ire->ire_type & IRE_BROADCAST)) {
2563 			/*
2564 			 * ire->ire_mp is non null when ire_mp passed in is used
2565 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2566 			 */
2567 			if (ire->ire_mp == NULL)
2568 				ire_refrele(ire);
2569 			if (sire != NULL)
2570 				ire_refrele(sire);
2571 			return (0);
2572 		}
2573 
2574 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2575 			ipaddr_t src_addr;
2576 
2577 			/*
2578 			 * ip_bind_connected() has stored the correct source
2579 			 * address in conn_src.
2580 			 */
2581 			src_addr = tcp->tcp_connp->conn_src;
2582 			tcp->tcp_ipha->ipha_src = src_addr;
2583 			/*
2584 			 * Copy of the src addr. in tcp_t is needed
2585 			 * for the lookup funcs.
2586 			 */
2587 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2588 		}
2589 		/*
2590 		 * Set the fragment bit so that IP will tell us if the MTU
2591 		 * should change. IP tells us the latest setting of
2592 		 * ip_path_mtu_discovery through ire_frag_flag.
2593 		 */
2594 		if (ip_path_mtu_discovery) {
2595 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2596 			    htons(IPH_DF);
2597 		}
2598 		/*
2599 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2600 		 * for IP_NEXTHOP. No cache ire has been found for the
2601 		 * destination and we are working with the nexthop's
2602 		 * interface ire. Since we need to forward all packets
2603 		 * to the nexthop first, we "blindly" set tcp_localnet
2604 		 * to false, eventhough the destination may also be
2605 		 * onlink.
2606 		 */
2607 		if (ire_uinfo == NULL)
2608 			tcp->tcp_localnet = 0;
2609 		else
2610 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2611 	} else {
2612 		/*
2613 		 * For incoming connection ire_mp = NULL
2614 		 * For outgoing connection ire_mp != NULL
2615 		 * Technically we should check conn_incoming_ill
2616 		 * when ire_mp is NULL and conn_outgoing_ill when
2617 		 * ire_mp is non-NULL. But this is performance
2618 		 * critical path and for IPV*_BOUND_IF, outgoing
2619 		 * and incoming ill are always set to the same value.
2620 		 */
2621 		ill_t	*dst_ill = NULL;
2622 		ipif_t  *dst_ipif = NULL;
2623 
2624 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2625 
2626 		if (connp->conn_outgoing_ill != NULL) {
2627 			/* Outgoing or incoming path */
2628 			int   err;
2629 
2630 			dst_ill = conn_get_held_ill(connp,
2631 			    &connp->conn_outgoing_ill, &err);
2632 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2633 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2634 				return (0);
2635 			}
2636 			match_flags |= MATCH_IRE_ILL;
2637 			dst_ipif = dst_ill->ill_ipif;
2638 		}
2639 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2640 		    0, 0, dst_ipif, zoneid, tsl, match_flags);
2641 
2642 		if (ire != NULL) {
2643 			ire_cacheable = B_TRUE;
2644 			ire_uinfo = (ire_mp != NULL) ?
2645 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2646 			    &ire->ire_uinfo;
2647 		} else {
2648 			if (ire_mp == NULL) {
2649 				ire = ire_ftable_lookup_v6(
2650 				    &tcp->tcp_connp->conn_remv6,
2651 				    0, 0, 0, dst_ipif, &sire, zoneid,
2652 				    0, tsl, match_flags);
2653 				if (ire == NULL) {
2654 					if (dst_ill != NULL)
2655 						ill_refrele(dst_ill);
2656 					return (0);
2657 				}
2658 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2659 				    &ire->ire_uinfo;
2660 			} else {
2661 				ire = (ire_t *)ire_mp->b_rptr;
2662 				ire_uinfo =
2663 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2664 			}
2665 		}
2666 		if (dst_ill != NULL)
2667 			ill_refrele(dst_ill);
2668 
2669 		ASSERT(ire != NULL);
2670 		ASSERT(ire_uinfo != NULL);
2671 
2672 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2673 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2674 			/*
2675 			 * ire->ire_mp is non null when ire_mp passed in is used
2676 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2677 			 */
2678 			if (ire->ire_mp == NULL)
2679 				ire_refrele(ire);
2680 			if (sire != NULL)
2681 				ire_refrele(sire);
2682 			return (0);
2683 		}
2684 
2685 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2686 			in6_addr_t	src_addr;
2687 
2688 			/*
2689 			 * ip_bind_connected_v6() has stored the correct source
2690 			 * address per IPv6 addr. selection policy in
2691 			 * conn_src_v6.
2692 			 */
2693 			src_addr = tcp->tcp_connp->conn_srcv6;
2694 
2695 			tcp->tcp_ip6h->ip6_src = src_addr;
2696 			/*
2697 			 * Copy of the src addr. in tcp_t is needed
2698 			 * for the lookup funcs.
2699 			 */
2700 			tcp->tcp_ip_src_v6 = src_addr;
2701 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2702 			    &connp->conn_srcv6));
2703 		}
2704 		tcp->tcp_localnet =
2705 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2706 	}
2707 
2708 	/*
2709 	 * This allows applications to fail quickly when connections are made
2710 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2711 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2712 	 */
2713 	if ((ire->ire_flags & RTF_REJECT) &&
2714 	    (ire->ire_flags & RTF_PRIVATE))
2715 		goto error;
2716 
2717 	/*
2718 	 * Make use of the cached rtt and rtt_sd values to calculate the
2719 	 * initial RTO.  Note that they are already initialized in
2720 	 * tcp_init_values().
2721 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2722 	 * IP_NEXTHOP, but instead are using the interface ire for the
2723 	 * nexthop, then we do not use the ire_uinfo from that ire to
2724 	 * do any initializations.
2725 	 */
2726 	if (ire_uinfo != NULL) {
2727 		if (ire_uinfo->iulp_rtt != 0) {
2728 			clock_t	rto;
2729 
2730 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2731 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2732 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2733 			    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2734 
2735 			if (rto > tcp_rexmit_interval_max) {
2736 				tcp->tcp_rto = tcp_rexmit_interval_max;
2737 			} else if (rto < tcp_rexmit_interval_min) {
2738 				tcp->tcp_rto = tcp_rexmit_interval_min;
2739 			} else {
2740 				tcp->tcp_rto = rto;
2741 			}
2742 		}
2743 		if (ire_uinfo->iulp_ssthresh != 0)
2744 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2745 		else
2746 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2747 		if (ire_uinfo->iulp_spipe > 0) {
2748 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2749 			    tcp_max_buf);
2750 			if (tcp_snd_lowat_fraction != 0)
2751 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2752 				    tcp_snd_lowat_fraction;
2753 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2754 		}
2755 		/*
2756 		 * Note that up till now, acceptor always inherits receive
2757 		 * window from the listener.  But if there is a metrics
2758 		 * associated with a host, we should use that instead of
2759 		 * inheriting it from listener. Thus we need to pass this
2760 		 * info back to the caller.
2761 		 */
2762 		if (ire_uinfo->iulp_rpipe > 0) {
2763 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2764 		}
2765 
2766 		if (ire_uinfo->iulp_rtomax > 0) {
2767 			tcp->tcp_second_timer_threshold =
2768 			    ire_uinfo->iulp_rtomax;
2769 		}
2770 
2771 		/*
2772 		 * Use the metric option settings, iulp_tstamp_ok and
2773 		 * iulp_wscale_ok, only for active open. What this means
2774 		 * is that if the other side uses timestamp or window
2775 		 * scale option, TCP will also use those options. That
2776 		 * is for passive open.  If the application sets a
2777 		 * large window, window scale is enabled regardless of
2778 		 * the value in iulp_wscale_ok.  This is the behavior
2779 		 * since 2.6.  So we keep it.
2780 		 * The only case left in passive open processing is the
2781 		 * check for SACK.
2782 		 * For ECN, it should probably be like SACK.  But the
2783 		 * current value is binary, so we treat it like the other
2784 		 * cases.  The metric only controls active open.For passive
2785 		 * open, the ndd param, tcp_ecn_permitted, controls the
2786 		 * behavior.
2787 		 */
2788 		if (!tcp_detached) {
2789 			/*
2790 			 * The if check means that the following can only
2791 			 * be turned on by the metrics only IRE, but not off.
2792 			 */
2793 			if (ire_uinfo->iulp_tstamp_ok)
2794 				tcp->tcp_snd_ts_ok = B_TRUE;
2795 			if (ire_uinfo->iulp_wscale_ok)
2796 				tcp->tcp_snd_ws_ok = B_TRUE;
2797 			if (ire_uinfo->iulp_sack == 2)
2798 				tcp->tcp_snd_sack_ok = B_TRUE;
2799 			if (ire_uinfo->iulp_ecn_ok)
2800 				tcp->tcp_ecn_ok = B_TRUE;
2801 		} else {
2802 			/*
2803 			 * Passive open.
2804 			 *
2805 			 * As above, the if check means that SACK can only be
2806 			 * turned on by the metric only IRE.
2807 			 */
2808 			if (ire_uinfo->iulp_sack > 0) {
2809 				tcp->tcp_snd_sack_ok = B_TRUE;
2810 			}
2811 		}
2812 	}
2813 
2814 
2815 	/*
2816 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2817 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2818 	 * length of all those options exceeds 28 bytes.  But because
2819 	 * of the tcp_mss_min check below, we may not have a problem if
2820 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2821 	 * the negative problem still exists.  And the check defeats PMTUd.
2822 	 * In fact, if PMTUd finds that the MSS should be smaller than
2823 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2824 	 * value.
2825 	 *
2826 	 * We do not deal with that now.  All those problems related to
2827 	 * PMTUd will be fixed later.
2828 	 */
2829 	ASSERT(ire->ire_max_frag != 0);
2830 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2831 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2832 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2833 			mss = MIN(mss, IPV6_MIN_MTU);
2834 		}
2835 	}
2836 
2837 	/* Sanity check for MSS value. */
2838 	if (tcp->tcp_ipversion == IPV4_VERSION)
2839 		mss_max = tcp_mss_max_ipv4;
2840 	else
2841 		mss_max = tcp_mss_max_ipv6;
2842 
2843 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2844 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2845 		/*
2846 		 * After receiving an ICMPv6 "packet too big" message with a
2847 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2848 		 * will insert a 8-byte fragment header in every packet; we
2849 		 * reduce the MSS by that amount here.
2850 		 */
2851 		mss -= sizeof (ip6_frag_t);
2852 	}
2853 
2854 	if (tcp->tcp_ipsec_overhead == 0)
2855 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2856 
2857 	mss -= tcp->tcp_ipsec_overhead;
2858 
2859 	if (mss < tcp_mss_min)
2860 		mss = tcp_mss_min;
2861 	if (mss > mss_max)
2862 		mss = mss_max;
2863 
2864 	/* Note that this is the maximum MSS, excluding all options. */
2865 	tcp->tcp_mss = mss;
2866 
2867 	/*
2868 	 * Initialize the ISS here now that we have the full connection ID.
2869 	 * The RFC 1948 method of initial sequence number generation requires
2870 	 * knowledge of the full connection ID before setting the ISS.
2871 	 */
2872 
2873 	tcp_iss_init(tcp);
2874 
2875 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2876 		tcp->tcp_loopback = B_TRUE;
2877 
2878 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2879 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2880 	} else {
2881 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2882 	}
2883 
2884 	if (hsp != NULL) {
2885 		/* Only modify if we're going to make them bigger */
2886 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2887 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2888 			if (tcp_snd_lowat_fraction != 0)
2889 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2890 					tcp_snd_lowat_fraction;
2891 		}
2892 
2893 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2894 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2895 		}
2896 
2897 		/* Copy timestamp flag only for active open */
2898 		if (!tcp_detached)
2899 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2900 	}
2901 
2902 	if (sire != NULL)
2903 		IRE_REFRELE(sire);
2904 
2905 	/*
2906 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2907 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2908 	 */
2909 	if (tcp->tcp_loopback ||
2910 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2911 		/*
2912 		 * For incoming, see if this tcp may be MDT-capable.  For
2913 		 * outgoing, this process has been taken care of through
2914 		 * tcp_rput_other.
2915 		 */
2916 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2917 		tcp->tcp_ire_ill_check_done = B_TRUE;
2918 	}
2919 
2920 	mutex_enter(&connp->conn_lock);
2921 	/*
2922 	 * Make sure that conn is not marked incipient
2923 	 * for incoming connections. A blind
2924 	 * removal of incipient flag is cheaper than
2925 	 * check and removal.
2926 	 */
2927 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2928 
2929 	/* Must not cache forwarding table routes. */
2930 	if (ire_cacheable) {
2931 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2932 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2933 			connp->conn_ire_cache = ire;
2934 			IRE_UNTRACE_REF(ire);
2935 			rw_exit(&ire->ire_bucket->irb_lock);
2936 			mutex_exit(&connp->conn_lock);
2937 			return (1);
2938 		}
2939 		rw_exit(&ire->ire_bucket->irb_lock);
2940 	}
2941 	mutex_exit(&connp->conn_lock);
2942 
2943 	if (ire->ire_mp == NULL)
2944 		ire_refrele(ire);
2945 	return (1);
2946 
2947 error:
2948 	if (ire->ire_mp == NULL)
2949 		ire_refrele(ire);
2950 	if (sire != NULL)
2951 		ire_refrele(sire);
2952 	return (0);
2953 }
2954 
2955 /*
2956  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2957  * O_T_BIND_REQ/T_BIND_REQ message.
2958  */
2959 static void
2960 tcp_bind(tcp_t *tcp, mblk_t *mp)
2961 {
2962 	sin_t	*sin;
2963 	sin6_t	*sin6;
2964 	mblk_t	*mp1;
2965 	in_port_t requested_port;
2966 	in_port_t allocated_port;
2967 	struct T_bind_req *tbr;
2968 	boolean_t	bind_to_req_port_only;
2969 	boolean_t	backlog_update = B_FALSE;
2970 	boolean_t	user_specified;
2971 	in6_addr_t	v6addr;
2972 	ipaddr_t	v4addr;
2973 	uint_t	origipversion;
2974 	int	err;
2975 	queue_t *q = tcp->tcp_wq;
2976 	conn_t	*connp;
2977 	mlp_type_t addrtype, mlptype;
2978 	zone_t	*zone;
2979 	cred_t	*cr;
2980 	in_port_t mlp_port;
2981 
2982 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2983 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2984 		if (tcp->tcp_debug) {
2985 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2986 			    "tcp_bind: bad req, len %u",
2987 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2988 		}
2989 		tcp_err_ack(tcp, mp, TPROTO, 0);
2990 		return;
2991 	}
2992 	/* Make sure the largest address fits */
2993 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2994 	if (mp1 == NULL) {
2995 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2996 		return;
2997 	}
2998 	mp = mp1;
2999 	tbr = (struct T_bind_req *)mp->b_rptr;
3000 	if (tcp->tcp_state >= TCPS_BOUND) {
3001 		if ((tcp->tcp_state == TCPS_BOUND ||
3002 		    tcp->tcp_state == TCPS_LISTEN) &&
3003 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3004 		    tbr->CONIND_number > 0) {
3005 			/*
3006 			 * Handle listen() increasing CONIND_number.
3007 			 * This is more "liberal" then what the TPI spec
3008 			 * requires but is needed to avoid a t_unbind
3009 			 * when handling listen() since the port number
3010 			 * might be "stolen" between the unbind and bind.
3011 			 */
3012 			backlog_update = B_TRUE;
3013 			goto do_bind;
3014 		}
3015 		if (tcp->tcp_debug) {
3016 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3017 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3018 		}
3019 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3020 		return;
3021 	}
3022 	origipversion = tcp->tcp_ipversion;
3023 
3024 	switch (tbr->ADDR_length) {
3025 	case 0:			/* request for a generic port */
3026 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3027 		if (tcp->tcp_family == AF_INET) {
3028 			tbr->ADDR_length = sizeof (sin_t);
3029 			sin = (sin_t *)&tbr[1];
3030 			*sin = sin_null;
3031 			sin->sin_family = AF_INET;
3032 			mp->b_wptr = (uchar_t *)&sin[1];
3033 			tcp->tcp_ipversion = IPV4_VERSION;
3034 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3035 		} else {
3036 			ASSERT(tcp->tcp_family == AF_INET6);
3037 			tbr->ADDR_length = sizeof (sin6_t);
3038 			sin6 = (sin6_t *)&tbr[1];
3039 			*sin6 = sin6_null;
3040 			sin6->sin6_family = AF_INET6;
3041 			mp->b_wptr = (uchar_t *)&sin6[1];
3042 			tcp->tcp_ipversion = IPV6_VERSION;
3043 			V6_SET_ZERO(v6addr);
3044 		}
3045 		requested_port = 0;
3046 		break;
3047 
3048 	case sizeof (sin_t):	/* Complete IPv4 address */
3049 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3050 		    sizeof (sin_t));
3051 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3052 			if (tcp->tcp_debug) {
3053 				(void) strlog(TCP_MOD_ID, 0, 1,
3054 				    SL_ERROR|SL_TRACE,
3055 				    "tcp_bind: bad address parameter, "
3056 				    "offset %d, len %d",
3057 				    tbr->ADDR_offset, tbr->ADDR_length);
3058 			}
3059 			tcp_err_ack(tcp, mp, TPROTO, 0);
3060 			return;
3061 		}
3062 		/*
3063 		 * With sockets sockfs will accept bogus sin_family in
3064 		 * bind() and replace it with the family used in the socket
3065 		 * call.
3066 		 */
3067 		if (sin->sin_family != AF_INET ||
3068 		    tcp->tcp_family != AF_INET) {
3069 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3070 			return;
3071 		}
3072 		requested_port = ntohs(sin->sin_port);
3073 		tcp->tcp_ipversion = IPV4_VERSION;
3074 		v4addr = sin->sin_addr.s_addr;
3075 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3076 		break;
3077 
3078 	case sizeof (sin6_t): /* Complete IPv6 address */
3079 		sin6 = (sin6_t *)mi_offset_param(mp,
3080 		    tbr->ADDR_offset, sizeof (sin6_t));
3081 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3082 			if (tcp->tcp_debug) {
3083 				(void) strlog(TCP_MOD_ID, 0, 1,
3084 				    SL_ERROR|SL_TRACE,
3085 				    "tcp_bind: bad IPv6 address parameter, "
3086 				    "offset %d, len %d", tbr->ADDR_offset,
3087 				    tbr->ADDR_length);
3088 			}
3089 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3090 			return;
3091 		}
3092 		if (sin6->sin6_family != AF_INET6 ||
3093 		    tcp->tcp_family != AF_INET6) {
3094 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3095 			return;
3096 		}
3097 		requested_port = ntohs(sin6->sin6_port);
3098 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3099 		    IPV4_VERSION : IPV6_VERSION;
3100 		v6addr = sin6->sin6_addr;
3101 		break;
3102 
3103 	default:
3104 		if (tcp->tcp_debug) {
3105 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3106 			    "tcp_bind: bad address length, %d",
3107 			    tbr->ADDR_length);
3108 		}
3109 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3110 		return;
3111 	}
3112 	tcp->tcp_bound_source_v6 = v6addr;
3113 
3114 	/* Check for change in ipversion */
3115 	if (origipversion != tcp->tcp_ipversion) {
3116 		ASSERT(tcp->tcp_family == AF_INET6);
3117 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3118 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3119 		if (err) {
3120 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3121 			return;
3122 		}
3123 	}
3124 
3125 	/*
3126 	 * Initialize family specific fields. Copy of the src addr.
3127 	 * in tcp_t is needed for the lookup funcs.
3128 	 */
3129 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3130 		tcp->tcp_ip6h->ip6_src = v6addr;
3131 	} else {
3132 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3133 	}
3134 	tcp->tcp_ip_src_v6 = v6addr;
3135 
3136 	/*
3137 	 * For O_T_BIND_REQ:
3138 	 * Verify that the target port/addr is available, or choose
3139 	 * another.
3140 	 * For  T_BIND_REQ:
3141 	 * Verify that the target port/addr is available or fail.
3142 	 * In both cases when it succeeds the tcp is inserted in the
3143 	 * bind hash table. This ensures that the operation is atomic
3144 	 * under the lock on the hash bucket.
3145 	 */
3146 	bind_to_req_port_only = requested_port != 0 &&
3147 	    tbr->PRIM_type != O_T_BIND_REQ;
3148 	/*
3149 	 * Get a valid port (within the anonymous range and should not
3150 	 * be a privileged one) to use if the user has not given a port.
3151 	 * If multiple threads are here, they may all start with
3152 	 * with the same initial port. But, it should be fine as long as
3153 	 * tcp_bindi will ensure that no two threads will be assigned
3154 	 * the same port.
3155 	 *
3156 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3157 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3158 	 * unless TCP_ANONPRIVBIND option is set.
3159 	 */
3160 	mlptype = mlptSingle;
3161 	mlp_port = requested_port;
3162 	if (requested_port == 0) {
3163 		requested_port = tcp->tcp_anon_priv_bind ?
3164 		    tcp_get_next_priv_port(tcp) :
3165 		    tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
3166 		if (requested_port == 0) {
3167 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3168 			return;
3169 		}
3170 		user_specified = B_FALSE;
3171 
3172 		/*
3173 		 * If the user went through one of the RPC interfaces to create
3174 		 * this socket and RPC is MLP in this zone, then give him an
3175 		 * anonymous MLP.
3176 		 */
3177 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3178 		connp = tcp->tcp_connp;
3179 		if (connp->conn_anon_mlp && is_system_labeled()) {
3180 			zone = crgetzone(cr);
3181 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3182 			    IPV6_VERSION, &v6addr);
3183 			if (addrtype == mlptSingle) {
3184 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3185 				return;
3186 			}
3187 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3188 			    PMAPPORT, addrtype);
3189 			mlp_port = PMAPPORT;
3190 		}
3191 	} else {
3192 		int i;
3193 		boolean_t priv = B_FALSE;
3194 
3195 		/*
3196 		 * If the requested_port is in the well-known privileged range,
3197 		 * verify that the stream was opened by a privileged user.
3198 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3199 		 * but instead the code relies on:
3200 		 * - the fact that the address of the array and its size never
3201 		 *   changes
3202 		 * - the atomic assignment of the elements of the array
3203 		 */
3204 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3205 		if (requested_port < tcp_smallest_nonpriv_port) {
3206 			priv = B_TRUE;
3207 		} else {
3208 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3209 				if (requested_port ==
3210 				    tcp_g_epriv_ports[i]) {
3211 					priv = B_TRUE;
3212 					break;
3213 				}
3214 			}
3215 		}
3216 		if (priv) {
3217 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3218 				if (tcp->tcp_debug) {
3219 					(void) strlog(TCP_MOD_ID, 0, 1,
3220 					    SL_ERROR|SL_TRACE,
3221 					    "tcp_bind: no priv for port %d",
3222 					    requested_port);
3223 				}
3224 				tcp_err_ack(tcp, mp, TACCES, 0);
3225 				return;
3226 			}
3227 		}
3228 		user_specified = B_TRUE;
3229 
3230 		connp = tcp->tcp_connp;
3231 		if (is_system_labeled()) {
3232 			zone = crgetzone(cr);
3233 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3234 			    IPV6_VERSION, &v6addr);
3235 			if (addrtype == mlptSingle) {
3236 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3237 				return;
3238 			}
3239 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3240 			    requested_port, addrtype);
3241 		}
3242 	}
3243 
3244 	if (mlptype != mlptSingle) {
3245 		if (secpolicy_net_bindmlp(cr) != 0) {
3246 			if (tcp->tcp_debug) {
3247 				(void) strlog(TCP_MOD_ID, 0, 1,
3248 				    SL_ERROR|SL_TRACE,
3249 				    "tcp_bind: no priv for multilevel port %d",
3250 				    requested_port);
3251 			}
3252 			tcp_err_ack(tcp, mp, TACCES, 0);
3253 			return;
3254 		}
3255 
3256 		/*
3257 		 * If we're specifically binding a shared IP address and the
3258 		 * port is MLP on shared addresses, then check to see if this
3259 		 * zone actually owns the MLP.  Reject if not.
3260 		 */
3261 		if (mlptype == mlptShared && addrtype == mlptShared) {
3262 			zoneid_t mlpzone;
3263 
3264 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3265 			    htons(mlp_port));
3266 			if (connp->conn_zoneid != mlpzone) {
3267 				if (tcp->tcp_debug) {
3268 					(void) strlog(TCP_MOD_ID, 0, 1,
3269 					    SL_ERROR|SL_TRACE,
3270 					    "tcp_bind: attempt to bind port "
3271 					    "%d on shared addr in zone %d "
3272 					    "(should be %d)",
3273 					    mlp_port, connp->conn_zoneid,
3274 					    mlpzone);
3275 				}
3276 				tcp_err_ack(tcp, mp, TACCES, 0);
3277 				return;
3278 			}
3279 		}
3280 
3281 		if (!user_specified) {
3282 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3283 			    requested_port, B_TRUE);
3284 			if (err != 0) {
3285 				if (tcp->tcp_debug) {
3286 					(void) strlog(TCP_MOD_ID, 0, 1,
3287 					    SL_ERROR|SL_TRACE,
3288 					    "tcp_bind: cannot establish anon "
3289 					    "MLP for port %d",
3290 					    requested_port);
3291 				}
3292 				tcp_err_ack(tcp, mp, TSYSERR, err);
3293 				return;
3294 			}
3295 			connp->conn_anon_port = B_TRUE;
3296 		}
3297 		connp->conn_mlp_type = mlptype;
3298 	}
3299 
3300 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3301 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3302 
3303 	if (allocated_port == 0) {
3304 		connp->conn_mlp_type = mlptSingle;
3305 		if (connp->conn_anon_port) {
3306 			connp->conn_anon_port = B_FALSE;
3307 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3308 			    requested_port, B_FALSE);
3309 		}
3310 		if (bind_to_req_port_only) {
3311 			if (tcp->tcp_debug) {
3312 				(void) strlog(TCP_MOD_ID, 0, 1,
3313 				    SL_ERROR|SL_TRACE,
3314 				    "tcp_bind: requested addr busy");
3315 			}
3316 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3317 		} else {
3318 			/* If we are out of ports, fail the bind. */
3319 			if (tcp->tcp_debug) {
3320 				(void) strlog(TCP_MOD_ID, 0, 1,
3321 				    SL_ERROR|SL_TRACE,
3322 				    "tcp_bind: out of ports?");
3323 			}
3324 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3325 		}
3326 		return;
3327 	}
3328 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3329 do_bind:
3330 	if (!backlog_update) {
3331 		if (tcp->tcp_family == AF_INET)
3332 			sin->sin_port = htons(allocated_port);
3333 		else
3334 			sin6->sin6_port = htons(allocated_port);
3335 	}
3336 	if (tcp->tcp_family == AF_INET) {
3337 		if (tbr->CONIND_number != 0) {
3338 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3339 			    sizeof (sin_t));
3340 		} else {
3341 			/* Just verify the local IP address */
3342 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3343 		}
3344 	} else {
3345 		if (tbr->CONIND_number != 0) {
3346 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3347 			    sizeof (sin6_t));
3348 		} else {
3349 			/* Just verify the local IP address */
3350 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3351 			    IPV6_ADDR_LEN);
3352 		}
3353 	}
3354 	if (mp1 == NULL) {
3355 		if (connp->conn_anon_port) {
3356 			connp->conn_anon_port = B_FALSE;
3357 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3358 			    requested_port, B_FALSE);
3359 		}
3360 		connp->conn_mlp_type = mlptSingle;
3361 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3362 		return;
3363 	}
3364 
3365 	tbr->PRIM_type = T_BIND_ACK;
3366 	mp->b_datap->db_type = M_PCPROTO;
3367 
3368 	/* Chain in the reply mp for tcp_rput() */
3369 	mp1->b_cont = mp;
3370 	mp = mp1;
3371 
3372 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3373 	if (tcp->tcp_conn_req_max) {
3374 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3375 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3376 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3377 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3378 		/*
3379 		 * If this is a listener, do not reset the eager list
3380 		 * and other stuffs.  Note that we don't check if the
3381 		 * existing eager list meets the new tcp_conn_req_max
3382 		 * requirement.
3383 		 */
3384 		if (tcp->tcp_state != TCPS_LISTEN) {
3385 			tcp->tcp_state = TCPS_LISTEN;
3386 			/* Initialize the chain. Don't need the eager_lock */
3387 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3388 			tcp->tcp_second_ctimer_threshold =
3389 			    tcp_ip_abort_linterval;
3390 		}
3391 	}
3392 
3393 	/*
3394 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3395 	 * processing continues in tcp_rput_other().
3396 	 */
3397 	if (tcp->tcp_family == AF_INET6) {
3398 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3399 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3400 	} else {
3401 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3402 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3403 	}
3404 	/*
3405 	 * If the bind cannot complete immediately
3406 	 * IP will arrange to call tcp_rput_other
3407 	 * when the bind completes.
3408 	 */
3409 	if (mp != NULL) {
3410 		tcp_rput_other(tcp, mp);
3411 	} else {
3412 		/*
3413 		 * Bind will be resumed later. Need to ensure
3414 		 * that conn doesn't disappear when that happens.
3415 		 * This will be decremented in ip_resume_tcp_bind().
3416 		 */
3417 		CONN_INC_REF(tcp->tcp_connp);
3418 	}
3419 }
3420 
3421 
3422 /*
3423  * If the "bind_to_req_port_only" parameter is set, if the requested port
3424  * number is available, return it, If not return 0
3425  *
3426  * If "bind_to_req_port_only" parameter is not set and
3427  * If the requested port number is available, return it.  If not, return
3428  * the first anonymous port we happen across.  If no anonymous ports are
3429  * available, return 0. addr is the requested local address, if any.
3430  *
3431  * In either case, when succeeding update the tcp_t to record the port number
3432  * and insert it in the bind hash table.
3433  *
3434  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3435  * without setting SO_REUSEADDR. This is needed so that they
3436  * can be viewed as two independent transport protocols.
3437  */
3438 static in_port_t
3439 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3440     int reuseaddr, boolean_t quick_connect,
3441     boolean_t bind_to_req_port_only, boolean_t user_specified)
3442 {
3443 	/* number of times we have run around the loop */
3444 	int count = 0;
3445 	/* maximum number of times to run around the loop */
3446 	int loopmax;
3447 	conn_t *connp = tcp->tcp_connp;
3448 	zoneid_t zoneid = connp->conn_zoneid;
3449 
3450 	/*
3451 	 * Lookup for free addresses is done in a loop and "loopmax"
3452 	 * influences how long we spin in the loop
3453 	 */
3454 	if (bind_to_req_port_only) {
3455 		/*
3456 		 * If the requested port is busy, don't bother to look
3457 		 * for a new one. Setting loop maximum count to 1 has
3458 		 * that effect.
3459 		 */
3460 		loopmax = 1;
3461 	} else {
3462 		/*
3463 		 * If the requested port is busy, look for a free one
3464 		 * in the anonymous port range.
3465 		 * Set loopmax appropriately so that one does not look
3466 		 * forever in the case all of the anonymous ports are in use.
3467 		 */
3468 		if (tcp->tcp_anon_priv_bind) {
3469 			/*
3470 			 * loopmax =
3471 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3472 			 */
3473 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3474 		} else {
3475 			loopmax = (tcp_largest_anon_port -
3476 			    tcp_smallest_anon_port + 1);
3477 		}
3478 	}
3479 	do {
3480 		uint16_t	lport;
3481 		tf_t		*tbf;
3482 		tcp_t		*ltcp;
3483 		conn_t		*lconnp;
3484 
3485 		lport = htons(port);
3486 
3487 		/*
3488 		 * Ensure that the tcp_t is not currently in the bind hash.
3489 		 * Hold the lock on the hash bucket to ensure that
3490 		 * the duplicate check plus the insertion is an atomic
3491 		 * operation.
3492 		 *
3493 		 * This function does an inline lookup on the bind hash list
3494 		 * Make sure that we access only members of tcp_t
3495 		 * and that we don't look at tcp_tcp, since we are not
3496 		 * doing a CONN_INC_REF.
3497 		 */
3498 		tcp_bind_hash_remove(tcp);
3499 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3500 		mutex_enter(&tbf->tf_lock);
3501 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3502 		    ltcp = ltcp->tcp_bind_hash) {
3503 			if (lport != ltcp->tcp_lport)
3504 				continue;
3505 
3506 			lconnp = ltcp->tcp_connp;
3507 
3508 			/*
3509 			 * On a labeled system, we must treat bindings to ports
3510 			 * on shared IP addresses by sockets with MAC exemption
3511 			 * privilege as being in all zones, as there's
3512 			 * otherwise no way to identify the right receiver.
3513 			 */
3514 			if (lconnp->conn_zoneid != zoneid &&
3515 			    !lconnp->conn_mac_exempt &&
3516 			    !connp->conn_mac_exempt)
3517 				continue;
3518 
3519 			/*
3520 			 * If TCP_EXCLBIND is set for either the bound or
3521 			 * binding endpoint, the semantics of bind
3522 			 * is changed according to the following.
3523 			 *
3524 			 * spec = specified address (v4 or v6)
3525 			 * unspec = unspecified address (v4 or v6)
3526 			 * A = specified addresses are different for endpoints
3527 			 *
3528 			 * bound	bind to		allowed
3529 			 * -------------------------------------
3530 			 * unspec	unspec		no
3531 			 * unspec	spec		no
3532 			 * spec		unspec		no
3533 			 * spec		spec		yes if A
3534 			 *
3535 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3536 			 * as UDP_EXCLBIND, except that zoneid is ignored.
3537 			 *
3538 			 * Note:
3539 			 *
3540 			 * 1. Because of TLI semantics, an endpoint can go
3541 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3542 			 * TCPS_BOUND, depending on whether it is originally
3543 			 * a listener or not.  That is why we need to check
3544 			 * for states greater than or equal to TCPS_BOUND
3545 			 * here.
3546 			 *
3547 			 * 2. Ideally, we should only check for state equals
3548 			 * to TCPS_LISTEN. And the following check should be
3549 			 * added.
3550 			 *
3551 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3552 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3553 			 *		...
3554 			 * }
3555 			 *
3556 			 * The semantics will be changed to this.  If the
3557 			 * endpoint on the list is in state not equal to
3558 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3559 			 * set, let the bind succeed.
3560 			 *
3561 			 * But because of (1), we cannot do that now.  If
3562 			 * in future, we can change this going back semantics,
3563 			 * we can add the above check.
3564 			 */
3565 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind ||
3566 			    lconnp->conn_mac_exempt || connp->conn_mac_exempt) {
3567 				if (V6_OR_V4_INADDR_ANY(
3568 				    ltcp->tcp_bound_source_v6) ||
3569 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3570 				    IN6_ARE_ADDR_EQUAL(laddr,
3571 				    &ltcp->tcp_bound_source_v6)) {
3572 					break;
3573 				}
3574 				continue;
3575 			}
3576 
3577 			/*
3578 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3579 			 * have disjoint port number spaces, if *_EXCLBIND
3580 			 * is not set and only if the application binds to a
3581 			 * specific port. We use the same autoassigned port
3582 			 * number space for IPv4 and IPv6 sockets.
3583 			 */
3584 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3585 			    bind_to_req_port_only)
3586 				continue;
3587 
3588 			/*
3589 			 * Ideally, we should make sure that the source
3590 			 * address, remote address, and remote port in the
3591 			 * four tuple for this tcp-connection is unique.
3592 			 * However, trying to find out the local source
3593 			 * address would require too much code duplication
3594 			 * with IP, since IP needs needs to have that code
3595 			 * to support userland TCP implementations.
3596 			 */
3597 			if (quick_connect &&
3598 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3599 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3600 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3601 				    &ltcp->tcp_remote_v6)))
3602 				continue;
3603 
3604 			if (!reuseaddr) {
3605 				/*
3606 				 * No socket option SO_REUSEADDR.
3607 				 * If existing port is bound to
3608 				 * a non-wildcard IP address
3609 				 * and the requesting stream is
3610 				 * bound to a distinct
3611 				 * different IP addresses
3612 				 * (non-wildcard, also), keep
3613 				 * going.
3614 				 */
3615 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3616 				    !V6_OR_V4_INADDR_ANY(
3617 				    ltcp->tcp_bound_source_v6) &&
3618 				    !IN6_ARE_ADDR_EQUAL(laddr,
3619 					&ltcp->tcp_bound_source_v6))
3620 					continue;
3621 				if (ltcp->tcp_state >= TCPS_BOUND) {
3622 					/*
3623 					 * This port is being used and
3624 					 * its state is >= TCPS_BOUND,
3625 					 * so we can't bind to it.
3626 					 */
3627 					break;
3628 				}
3629 			} else {
3630 				/*
3631 				 * socket option SO_REUSEADDR is set on the
3632 				 * binding tcp_t.
3633 				 *
3634 				 * If two streams are bound to
3635 				 * same IP address or both addr
3636 				 * and bound source are wildcards
3637 				 * (INADDR_ANY), we want to stop
3638 				 * searching.
3639 				 * We have found a match of IP source
3640 				 * address and source port, which is
3641 				 * refused regardless of the
3642 				 * SO_REUSEADDR setting, so we break.
3643 				 */
3644 				if (IN6_ARE_ADDR_EQUAL(laddr,
3645 				    &ltcp->tcp_bound_source_v6) &&
3646 				    (ltcp->tcp_state == TCPS_LISTEN ||
3647 					ltcp->tcp_state == TCPS_BOUND))
3648 					break;
3649 			}
3650 		}
3651 		if (ltcp != NULL) {
3652 			/* The port number is busy */
3653 			mutex_exit(&tbf->tf_lock);
3654 		} else {
3655 			/*
3656 			 * This port is ours. Insert in fanout and mark as
3657 			 * bound to prevent others from getting the port
3658 			 * number.
3659 			 */
3660 			tcp->tcp_state = TCPS_BOUND;
3661 			tcp->tcp_lport = htons(port);
3662 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3663 
3664 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3665 			    tcp->tcp_lport)] == tbf);
3666 			tcp_bind_hash_insert(tbf, tcp, 1);
3667 
3668 			mutex_exit(&tbf->tf_lock);
3669 
3670 			/*
3671 			 * We don't want tcp_next_port_to_try to "inherit"
3672 			 * a port number supplied by the user in a bind.
3673 			 */
3674 			if (user_specified)
3675 				return (port);
3676 
3677 			/*
3678 			 * This is the only place where tcp_next_port_to_try
3679 			 * is updated. After the update, it may or may not
3680 			 * be in the valid range.
3681 			 */
3682 			if (!tcp->tcp_anon_priv_bind)
3683 				tcp_next_port_to_try = port + 1;
3684 			return (port);
3685 		}
3686 
3687 		if (tcp->tcp_anon_priv_bind) {
3688 			port = tcp_get_next_priv_port(tcp);
3689 		} else {
3690 			if (count == 0 && user_specified) {
3691 				/*
3692 				 * We may have to return an anonymous port. So
3693 				 * get one to start with.
3694 				 */
3695 				port =
3696 				    tcp_update_next_port(tcp_next_port_to_try,
3697 					tcp, B_TRUE);
3698 				user_specified = B_FALSE;
3699 			} else {
3700 				port = tcp_update_next_port(port + 1, tcp,
3701 				    B_FALSE);
3702 			}
3703 		}
3704 		if (port == 0)
3705 			break;
3706 
3707 		/*
3708 		 * Don't let this loop run forever in the case where
3709 		 * all of the anonymous ports are in use.
3710 		 */
3711 	} while (++count < loopmax);
3712 	return (0);
3713 }
3714 
3715 /*
3716  * We are dying for some reason.  Try to do it gracefully.  (May be called
3717  * as writer.)
3718  *
3719  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3720  * done by a service procedure).
3721  * TBD - Should the return value distinguish between the tcp_t being
3722  * freed and it being reinitialized?
3723  */
3724 static int
3725 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3726 {
3727 	mblk_t	*mp;
3728 	queue_t	*q;
3729 
3730 	TCP_CLD_STAT(tag);
3731 
3732 #if TCP_TAG_CLEAN_DEATH
3733 	tcp->tcp_cleandeathtag = tag;
3734 #endif
3735 
3736 	if (tcp->tcp_linger_tid != 0 &&
3737 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3738 		tcp_stop_lingering(tcp);
3739 	}
3740 
3741 	ASSERT(tcp != NULL);
3742 	ASSERT((tcp->tcp_family == AF_INET &&
3743 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3744 	    (tcp->tcp_family == AF_INET6 &&
3745 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3746 	    tcp->tcp_ipversion == IPV6_VERSION)));
3747 
3748 	if (TCP_IS_DETACHED(tcp)) {
3749 		if (tcp->tcp_hard_binding) {
3750 			/*
3751 			 * Its an eager that we are dealing with. We close the
3752 			 * eager but in case a conn_ind has already gone to the
3753 			 * listener, let tcp_accept_finish() send a discon_ind
3754 			 * to the listener and drop the last reference. If the
3755 			 * listener doesn't even know about the eager i.e. the
3756 			 * conn_ind hasn't gone up, blow away the eager and drop
3757 			 * the last reference as well. If the conn_ind has gone
3758 			 * up, state should be BOUND. tcp_accept_finish
3759 			 * will figure out that the connection has received a
3760 			 * RST and will send a DISCON_IND to the application.
3761 			 */
3762 			tcp_closei_local(tcp);
3763 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3764 				CONN_DEC_REF(tcp->tcp_connp);
3765 			} else {
3766 				tcp->tcp_state = TCPS_BOUND;
3767 			}
3768 		} else {
3769 			tcp_close_detached(tcp);
3770 		}
3771 		return (0);
3772 	}
3773 
3774 	TCP_STAT(tcp_clean_death_nondetached);
3775 
3776 	/*
3777 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3778 	 * is run) postpone cleaning up the endpoint until service routine
3779 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3780 	 * client_errno since tcp_close uses the client_errno field.
3781 	 */
3782 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3783 		if (err != 0)
3784 			tcp->tcp_client_errno = err;
3785 
3786 		tcp->tcp_deferred_clean_death = B_TRUE;
3787 		return (-1);
3788 	}
3789 
3790 	q = tcp->tcp_rq;
3791 
3792 	/* Trash all inbound data */
3793 	flushq(q, FLUSHALL);
3794 
3795 	/*
3796 	 * If we are at least part way open and there is error
3797 	 * (err==0 implies no error)
3798 	 * notify our client by a T_DISCON_IND.
3799 	 */
3800 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3801 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3802 		    !TCP_IS_SOCKET(tcp)) {
3803 			/*
3804 			 * Send M_FLUSH according to TPI. Because sockets will
3805 			 * (and must) ignore FLUSHR we do that only for TPI
3806 			 * endpoints and sockets in STREAMS mode.
3807 			 */
3808 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3809 		}
3810 		if (tcp->tcp_debug) {
3811 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3812 			    "tcp_clean_death: discon err %d", err);
3813 		}
3814 		mp = mi_tpi_discon_ind(NULL, err, 0);
3815 		if (mp != NULL) {
3816 			putnext(q, mp);
3817 		} else {
3818 			if (tcp->tcp_debug) {
3819 				(void) strlog(TCP_MOD_ID, 0, 1,
3820 				    SL_ERROR|SL_TRACE,
3821 				    "tcp_clean_death, sending M_ERROR");
3822 			}
3823 			(void) putnextctl1(q, M_ERROR, EPROTO);
3824 		}
3825 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3826 			/* SYN_SENT or SYN_RCVD */
3827 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3828 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3829 			/* ESTABLISHED or CLOSE_WAIT */
3830 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3831 		}
3832 	}
3833 
3834 	tcp_reinit(tcp);
3835 	return (-1);
3836 }
3837 
3838 /*
3839  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3840  * to expire, stop the wait and finish the close.
3841  */
3842 static void
3843 tcp_stop_lingering(tcp_t *tcp)
3844 {
3845 	clock_t	delta = 0;
3846 
3847 	tcp->tcp_linger_tid = 0;
3848 	if (tcp->tcp_state > TCPS_LISTEN) {
3849 		tcp_acceptor_hash_remove(tcp);
3850 		if (tcp->tcp_flow_stopped) {
3851 			tcp_clrqfull(tcp);
3852 		}
3853 
3854 		if (tcp->tcp_timer_tid != 0) {
3855 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3856 			tcp->tcp_timer_tid = 0;
3857 		}
3858 		/*
3859 		 * Need to cancel those timers which will not be used when
3860 		 * TCP is detached.  This has to be done before the tcp_wq
3861 		 * is set to the global queue.
3862 		 */
3863 		tcp_timers_stop(tcp);
3864 
3865 
3866 		tcp->tcp_detached = B_TRUE;
3867 		tcp->tcp_rq = tcp_g_q;
3868 		tcp->tcp_wq = WR(tcp_g_q);
3869 
3870 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3871 			tcp_time_wait_append(tcp);
3872 			TCP_DBGSTAT(tcp_detach_time_wait);
3873 			goto finish;
3874 		}
3875 
3876 		/*
3877 		 * If delta is zero the timer event wasn't executed and was
3878 		 * successfully canceled. In this case we need to restart it
3879 		 * with the minimal delta possible.
3880 		 */
3881 		if (delta >= 0) {
3882 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3883 			    delta ? delta : 1);
3884 		}
3885 	} else {
3886 		tcp_closei_local(tcp);
3887 		CONN_DEC_REF(tcp->tcp_connp);
3888 	}
3889 finish:
3890 	/* Signal closing thread that it can complete close */
3891 	mutex_enter(&tcp->tcp_closelock);
3892 	tcp->tcp_detached = B_TRUE;
3893 	tcp->tcp_rq = tcp_g_q;
3894 	tcp->tcp_wq = WR(tcp_g_q);
3895 	tcp->tcp_closed = 1;
3896 	cv_signal(&tcp->tcp_closecv);
3897 	mutex_exit(&tcp->tcp_closelock);
3898 }
3899 
3900 /*
3901  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3902  * expires.
3903  */
3904 static void
3905 tcp_close_linger_timeout(void *arg)
3906 {
3907 	conn_t	*connp = (conn_t *)arg;
3908 	tcp_t 	*tcp = connp->conn_tcp;
3909 
3910 	tcp->tcp_client_errno = ETIMEDOUT;
3911 	tcp_stop_lingering(tcp);
3912 }
3913 
3914 static int
3915 tcp_close(queue_t *q, int flags)
3916 {
3917 	conn_t		*connp = Q_TO_CONN(q);
3918 	tcp_t		*tcp = connp->conn_tcp;
3919 	mblk_t 		*mp = &tcp->tcp_closemp;
3920 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3921 
3922 	ASSERT(WR(q)->q_next == NULL);
3923 	ASSERT(connp->conn_ref >= 2);
3924 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3925 
3926 	/*
3927 	 * We are being closed as /dev/tcp or /dev/tcp6.
3928 	 *
3929 	 * Mark the conn as closing. ill_pending_mp_add will not
3930 	 * add any mp to the pending mp list, after this conn has
3931 	 * started closing. Same for sq_pending_mp_add
3932 	 */
3933 	mutex_enter(&connp->conn_lock);
3934 	connp->conn_state_flags |= CONN_CLOSING;
3935 	if (connp->conn_oper_pending_ill != NULL)
3936 		conn_ioctl_cleanup_reqd = B_TRUE;
3937 	CONN_INC_REF_LOCKED(connp);
3938 	mutex_exit(&connp->conn_lock);
3939 	tcp->tcp_closeflags = (uint8_t)flags;
3940 	ASSERT(connp->conn_ref >= 3);
3941 
3942 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3943 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3944 
3945 	mutex_enter(&tcp->tcp_closelock);
3946 
3947 	while (!tcp->tcp_closed)
3948 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3949 	mutex_exit(&tcp->tcp_closelock);
3950 	/*
3951 	 * In the case of listener streams that have eagers in the q or q0
3952 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3953 	 * tcp_wq of the eagers point to our queues. By waiting for the
3954 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3955 	 * up their queue pointers and also dropped their references to us.
3956 	 */
3957 	if (tcp->tcp_wait_for_eagers) {
3958 		mutex_enter(&connp->conn_lock);
3959 		while (connp->conn_ref != 1) {
3960 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3961 		}
3962 		mutex_exit(&connp->conn_lock);
3963 	}
3964 	/*
3965 	 * ioctl cleanup. The mp is queued in the
3966 	 * ill_pending_mp or in the sq_pending_mp.
3967 	 */
3968 	if (conn_ioctl_cleanup_reqd)
3969 		conn_ioctl_cleanup(connp);
3970 
3971 	qprocsoff(q);
3972 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3973 
3974 	tcp->tcp_cpid = -1;
3975 
3976 	/*
3977 	 * Drop IP's reference on the conn. This is the last reference
3978 	 * on the connp if the state was less than established. If the
3979 	 * connection has gone into timewait state, then we will have
3980 	 * one ref for the TCP and one more ref (total of two) for the
3981 	 * classifier connected hash list (a timewait connections stays
3982 	 * in connected hash till closed).
3983 	 *
3984 	 * We can't assert the references because there might be other
3985 	 * transient reference places because of some walkers or queued
3986 	 * packets in squeue for the timewait state.
3987 	 */
3988 	CONN_DEC_REF(connp);
3989 	q->q_ptr = WR(q)->q_ptr = NULL;
3990 	return (0);
3991 }
3992 
3993 static int
3994 tcpclose_accept(queue_t *q)
3995 {
3996 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3997 
3998 	/*
3999 	 * We had opened an acceptor STREAM for sockfs which is
4000 	 * now being closed due to some error.
4001 	 */
4002 	qprocsoff(q);
4003 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
4004 	q->q_ptr = WR(q)->q_ptr = NULL;
4005 	return (0);
4006 }
4007 
4008 
4009 /*
4010  * Called by streams close routine via squeues when our client blows off her
4011  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4012  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4013  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4014  * acked.
4015  *
4016  * NOTE: tcp_close potentially returns error when lingering.
4017  * However, the stream head currently does not pass these errors
4018  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4019  * errors to the application (from tsleep()) and not errors
4020  * like ECONNRESET caused by receiving a reset packet.
4021  */
4022 
4023 /* ARGSUSED */
4024 static void
4025 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4026 {
4027 	char	*msg;
4028 	conn_t	*connp = (conn_t *)arg;
4029 	tcp_t	*tcp = connp->conn_tcp;
4030 	clock_t	delta = 0;
4031 
4032 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4033 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4034 
4035 	/* Cancel any pending timeout */
4036 	if (tcp->tcp_ordrelid != 0) {
4037 		if (tcp->tcp_timeout) {
4038 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4039 		}
4040 		tcp->tcp_ordrelid = 0;
4041 		tcp->tcp_timeout = B_FALSE;
4042 	}
4043 
4044 	mutex_enter(&tcp->tcp_eager_lock);
4045 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4046 		/* Cleanup for listener */
4047 		tcp_eager_cleanup(tcp, 0);
4048 		tcp->tcp_wait_for_eagers = 1;
4049 	}
4050 	mutex_exit(&tcp->tcp_eager_lock);
4051 
4052 	connp->conn_mdt_ok = B_FALSE;
4053 	tcp->tcp_mdt = B_FALSE;
4054 
4055 	msg = NULL;
4056 	switch (tcp->tcp_state) {
4057 	case TCPS_CLOSED:
4058 	case TCPS_IDLE:
4059 	case TCPS_BOUND:
4060 	case TCPS_LISTEN:
4061 		break;
4062 	case TCPS_SYN_SENT:
4063 		msg = "tcp_close, during connect";
4064 		break;
4065 	case TCPS_SYN_RCVD:
4066 		/*
4067 		 * Close during the connect 3-way handshake
4068 		 * but here there may or may not be pending data
4069 		 * already on queue. Process almost same as in
4070 		 * the ESTABLISHED state.
4071 		 */
4072 		/* FALLTHRU */
4073 	default:
4074 		if (tcp->tcp_fused)
4075 			tcp_unfuse(tcp);
4076 
4077 		/*
4078 		 * If SO_LINGER has set a zero linger time, abort the
4079 		 * connection with a reset.
4080 		 */
4081 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4082 			msg = "tcp_close, zero lingertime";
4083 			break;
4084 		}
4085 
4086 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4087 		/*
4088 		 * Abort connection if there is unread data queued.
4089 		 */
4090 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4091 			msg = "tcp_close, unread data";
4092 			break;
4093 		}
4094 		/*
4095 		 * tcp_hard_bound is now cleared thus all packets go through
4096 		 * tcp_lookup. This fact is used by tcp_detach below.
4097 		 *
4098 		 * We have done a qwait() above which could have possibly
4099 		 * drained more messages in turn causing transition to a
4100 		 * different state. Check whether we have to do the rest
4101 		 * of the processing or not.
4102 		 */
4103 		if (tcp->tcp_state <= TCPS_LISTEN)
4104 			break;
4105 
4106 		/*
4107 		 * Transmit the FIN before detaching the tcp_t.
4108 		 * After tcp_detach returns this queue/perimeter
4109 		 * no longer owns the tcp_t thus others can modify it.
4110 		 */
4111 		(void) tcp_xmit_end(tcp);
4112 
4113 		/*
4114 		 * If lingering on close then wait until the fin is acked,
4115 		 * the SO_LINGER time passes, or a reset is sent/received.
4116 		 */
4117 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4118 		    !(tcp->tcp_fin_acked) &&
4119 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4120 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4121 				tcp->tcp_client_errno = EWOULDBLOCK;
4122 			} else if (tcp->tcp_client_errno == 0) {
4123 
4124 				ASSERT(tcp->tcp_linger_tid == 0);
4125 
4126 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4127 				    tcp_close_linger_timeout,
4128 				    tcp->tcp_lingertime * hz);
4129 
4130 				/* tcp_close_linger_timeout will finish close */
4131 				if (tcp->tcp_linger_tid == 0)
4132 					tcp->tcp_client_errno = ENOSR;
4133 				else
4134 					return;
4135 			}
4136 
4137 			/*
4138 			 * Check if we need to detach or just close
4139 			 * the instance.
4140 			 */
4141 			if (tcp->tcp_state <= TCPS_LISTEN)
4142 				break;
4143 		}
4144 
4145 		/*
4146 		 * Make sure that no other thread will access the tcp_rq of
4147 		 * this instance (through lookups etc.) as tcp_rq will go
4148 		 * away shortly.
4149 		 */
4150 		tcp_acceptor_hash_remove(tcp);
4151 
4152 		if (tcp->tcp_flow_stopped) {
4153 			tcp_clrqfull(tcp);
4154 		}
4155 
4156 		if (tcp->tcp_timer_tid != 0) {
4157 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4158 			tcp->tcp_timer_tid = 0;
4159 		}
4160 		/*
4161 		 * Need to cancel those timers which will not be used when
4162 		 * TCP is detached.  This has to be done before the tcp_wq
4163 		 * is set to the global queue.
4164 		 */
4165 		tcp_timers_stop(tcp);
4166 
4167 		tcp->tcp_detached = B_TRUE;
4168 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4169 			tcp_time_wait_append(tcp);
4170 			TCP_DBGSTAT(tcp_detach_time_wait);
4171 			ASSERT(connp->conn_ref >= 3);
4172 			goto finish;
4173 		}
4174 
4175 		/*
4176 		 * If delta is zero the timer event wasn't executed and was
4177 		 * successfully canceled. In this case we need to restart it
4178 		 * with the minimal delta possible.
4179 		 */
4180 		if (delta >= 0)
4181 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4182 			    delta ? delta : 1);
4183 
4184 		ASSERT(connp->conn_ref >= 3);
4185 		goto finish;
4186 	}
4187 
4188 	/* Detach did not complete. Still need to remove q from stream. */
4189 	if (msg) {
4190 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4191 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4192 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4193 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4194 		    tcp->tcp_state == TCPS_SYN_RCVD)
4195 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4196 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4197 	}
4198 
4199 	tcp_closei_local(tcp);
4200 	CONN_DEC_REF(connp);
4201 	ASSERT(connp->conn_ref >= 2);
4202 
4203 finish:
4204 	/*
4205 	 * Although packets are always processed on the correct
4206 	 * tcp's perimeter and access is serialized via squeue's,
4207 	 * IP still needs a queue when sending packets in time_wait
4208 	 * state so use WR(tcp_g_q) till ip_output() can be
4209 	 * changed to deal with just connp. For read side, we
4210 	 * could have set tcp_rq to NULL but there are some cases
4211 	 * in tcp_rput_data() from early days of this code which
4212 	 * do a putnext without checking if tcp is closed. Those
4213 	 * need to be identified before both tcp_rq and tcp_wq
4214 	 * can be set to NULL and tcp_q_q can disappear forever.
4215 	 */
4216 	mutex_enter(&tcp->tcp_closelock);
4217 	/*
4218 	 * Don't change the queues in the case of a listener that has
4219 	 * eagers in its q or q0. It could surprise the eagers.
4220 	 * Instead wait for the eagers outside the squeue.
4221 	 */
4222 	if (!tcp->tcp_wait_for_eagers) {
4223 		tcp->tcp_detached = B_TRUE;
4224 		tcp->tcp_rq = tcp_g_q;
4225 		tcp->tcp_wq = WR(tcp_g_q);
4226 	}
4227 
4228 	/* Signal tcp_close() to finish closing. */
4229 	tcp->tcp_closed = 1;
4230 	cv_signal(&tcp->tcp_closecv);
4231 	mutex_exit(&tcp->tcp_closelock);
4232 }
4233 
4234 
4235 /*
4236  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4237  * Some stream heads get upset if they see these later on as anything but NULL.
4238  */
4239 static void
4240 tcp_close_mpp(mblk_t **mpp)
4241 {
4242 	mblk_t	*mp;
4243 
4244 	if ((mp = *mpp) != NULL) {
4245 		do {
4246 			mp->b_next = NULL;
4247 			mp->b_prev = NULL;
4248 		} while ((mp = mp->b_cont) != NULL);
4249 
4250 		mp = *mpp;
4251 		*mpp = NULL;
4252 		freemsg(mp);
4253 	}
4254 }
4255 
4256 /* Do detached close. */
4257 static void
4258 tcp_close_detached(tcp_t *tcp)
4259 {
4260 	if (tcp->tcp_fused)
4261 		tcp_unfuse(tcp);
4262 
4263 	/*
4264 	 * Clustering code serializes TCP disconnect callbacks and
4265 	 * cluster tcp list walks by blocking a TCP disconnect callback
4266 	 * if a cluster tcp list walk is in progress. This ensures
4267 	 * accurate accounting of TCPs in the cluster code even though
4268 	 * the TCP list walk itself is not atomic.
4269 	 */
4270 	tcp_closei_local(tcp);
4271 	CONN_DEC_REF(tcp->tcp_connp);
4272 }
4273 
4274 /*
4275  * Stop all TCP timers, and free the timer mblks if requested.
4276  */
4277 void
4278 tcp_timers_stop(tcp_t *tcp)
4279 {
4280 	if (tcp->tcp_timer_tid != 0) {
4281 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4282 		tcp->tcp_timer_tid = 0;
4283 	}
4284 	if (tcp->tcp_ka_tid != 0) {
4285 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4286 		tcp->tcp_ka_tid = 0;
4287 	}
4288 	if (tcp->tcp_ack_tid != 0) {
4289 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4290 		tcp->tcp_ack_tid = 0;
4291 	}
4292 	if (tcp->tcp_push_tid != 0) {
4293 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4294 		tcp->tcp_push_tid = 0;
4295 	}
4296 }
4297 
4298 /*
4299  * The tcp_t is going away. Remove it from all lists and set it
4300  * to TCPS_CLOSED. The freeing up of memory is deferred until
4301  * tcp_inactive. This is needed since a thread in tcp_rput might have
4302  * done a CONN_INC_REF on this structure before it was removed from the
4303  * hashes.
4304  */
4305 static void
4306 tcp_closei_local(tcp_t *tcp)
4307 {
4308 	ire_t 	*ire;
4309 	conn_t	*connp = tcp->tcp_connp;
4310 
4311 	if (!TCP_IS_SOCKET(tcp))
4312 		tcp_acceptor_hash_remove(tcp);
4313 
4314 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4315 	tcp->tcp_ibsegs = 0;
4316 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4317 	tcp->tcp_obsegs = 0;
4318 
4319 	/*
4320 	 * If we are an eager connection hanging off a listener that
4321 	 * hasn't formally accepted the connection yet, get off his
4322 	 * list and blow off any data that we have accumulated.
4323 	 */
4324 	if (tcp->tcp_listener != NULL) {
4325 		tcp_t	*listener = tcp->tcp_listener;
4326 		mutex_enter(&listener->tcp_eager_lock);
4327 		/*
4328 		 * tcp_eager_conn_ind == NULL means that the
4329 		 * conn_ind has already gone to listener. At
4330 		 * this point, eager will be closed but we
4331 		 * leave it in listeners eager list so that
4332 		 * if listener decides to close without doing
4333 		 * accept, we can clean this up. In tcp_wput_accept
4334 		 * we take case of the case of accept on closed
4335 		 * eager.
4336 		 */
4337 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4338 			tcp_eager_unlink(tcp);
4339 			mutex_exit(&listener->tcp_eager_lock);
4340 			/*
4341 			 * We don't want to have any pointers to the
4342 			 * listener queue, after we have released our
4343 			 * reference on the listener
4344 			 */
4345 			tcp->tcp_rq = tcp_g_q;
4346 			tcp->tcp_wq = WR(tcp_g_q);
4347 			CONN_DEC_REF(listener->tcp_connp);
4348 		} else {
4349 			mutex_exit(&listener->tcp_eager_lock);
4350 		}
4351 	}
4352 
4353 	/* Stop all the timers */
4354 	tcp_timers_stop(tcp);
4355 
4356 	if (tcp->tcp_state == TCPS_LISTEN) {
4357 		if (tcp->tcp_ip_addr_cache) {
4358 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4359 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4360 			tcp->tcp_ip_addr_cache = NULL;
4361 		}
4362 	}
4363 	if (tcp->tcp_flow_stopped)
4364 		tcp_clrqfull(tcp);
4365 
4366 	tcp_bind_hash_remove(tcp);
4367 	/*
4368 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4369 	 * is trying to remove this tcp from the time wait list, we will
4370 	 * block in tcp_time_wait_remove while trying to acquire the
4371 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4372 	 * requires the ipcl_hash_remove to be ordered after the
4373 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4374 	 */
4375 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4376 		tcp_time_wait_remove(tcp, NULL);
4377 	CL_INET_DISCONNECT(tcp);
4378 	ipcl_hash_remove(connp);
4379 
4380 	/*
4381 	 * Delete the cached ire in conn_ire_cache and also mark
4382 	 * the conn as CONDEMNED
4383 	 */
4384 	mutex_enter(&connp->conn_lock);
4385 	connp->conn_state_flags |= CONN_CONDEMNED;
4386 	ire = connp->conn_ire_cache;
4387 	connp->conn_ire_cache = NULL;
4388 	mutex_exit(&connp->conn_lock);
4389 	if (ire != NULL)
4390 		IRE_REFRELE_NOTR(ire);
4391 
4392 	/* Need to cleanup any pending ioctls */
4393 	ASSERT(tcp->tcp_time_wait_next == NULL);
4394 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4395 	ASSERT(tcp->tcp_time_wait_expire == 0);
4396 	tcp->tcp_state = TCPS_CLOSED;
4397 
4398 	/* Release any SSL context */
4399 	if (tcp->tcp_kssl_ent != NULL) {
4400 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4401 		tcp->tcp_kssl_ent = NULL;
4402 	}
4403 	if (tcp->tcp_kssl_ctx != NULL) {
4404 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4405 		tcp->tcp_kssl_ctx = NULL;
4406 	}
4407 	tcp->tcp_kssl_pending = B_FALSE;
4408 }
4409 
4410 /*
4411  * tcp is dying (called from ipcl_conn_destroy and error cases).
4412  * Free the tcp_t in either case.
4413  */
4414 void
4415 tcp_free(tcp_t *tcp)
4416 {
4417 	mblk_t	*mp;
4418 	ip6_pkt_t	*ipp;
4419 
4420 	ASSERT(tcp != NULL);
4421 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4422 
4423 	tcp->tcp_rq = NULL;
4424 	tcp->tcp_wq = NULL;
4425 
4426 	tcp_close_mpp(&tcp->tcp_xmit_head);
4427 	tcp_close_mpp(&tcp->tcp_reass_head);
4428 	if (tcp->tcp_rcv_list != NULL) {
4429 		/* Free b_next chain */
4430 		tcp_close_mpp(&tcp->tcp_rcv_list);
4431 	}
4432 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4433 		freemsg(mp);
4434 	}
4435 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4436 		freemsg(mp);
4437 	}
4438 
4439 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4440 		freeb(tcp->tcp_fused_sigurg_mp);
4441 		tcp->tcp_fused_sigurg_mp = NULL;
4442 	}
4443 
4444 	if (tcp->tcp_sack_info != NULL) {
4445 		if (tcp->tcp_notsack_list != NULL) {
4446 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4447 		}
4448 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4449 	}
4450 
4451 	if (tcp->tcp_hopopts != NULL) {
4452 		mi_free(tcp->tcp_hopopts);
4453 		tcp->tcp_hopopts = NULL;
4454 		tcp->tcp_hopoptslen = 0;
4455 	}
4456 	ASSERT(tcp->tcp_hopoptslen == 0);
4457 	if (tcp->tcp_dstopts != NULL) {
4458 		mi_free(tcp->tcp_dstopts);
4459 		tcp->tcp_dstopts = NULL;
4460 		tcp->tcp_dstoptslen = 0;
4461 	}
4462 	ASSERT(tcp->tcp_dstoptslen == 0);
4463 	if (tcp->tcp_rtdstopts != NULL) {
4464 		mi_free(tcp->tcp_rtdstopts);
4465 		tcp->tcp_rtdstopts = NULL;
4466 		tcp->tcp_rtdstoptslen = 0;
4467 	}
4468 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4469 	if (tcp->tcp_rthdr != NULL) {
4470 		mi_free(tcp->tcp_rthdr);
4471 		tcp->tcp_rthdr = NULL;
4472 		tcp->tcp_rthdrlen = 0;
4473 	}
4474 	ASSERT(tcp->tcp_rthdrlen == 0);
4475 
4476 	ipp = &tcp->tcp_sticky_ipp;
4477 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4478 	    IPPF_RTHDR))
4479 		ip6_pkt_free(ipp);
4480 
4481 	/*
4482 	 * Free memory associated with the tcp/ip header template.
4483 	 */
4484 
4485 	if (tcp->tcp_iphc != NULL)
4486 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4487 
4488 	/*
4489 	 * Following is really a blowing away a union.
4490 	 * It happens to have exactly two members of identical size
4491 	 * the following code is enough.
4492 	 */
4493 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4494 
4495 	if (tcp->tcp_tracebuf != NULL) {
4496 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4497 		tcp->tcp_tracebuf = NULL;
4498 	}
4499 }
4500 
4501 
4502 /*
4503  * Put a connection confirmation message upstream built from the
4504  * address information within 'iph' and 'tcph'.  Report our success or failure.
4505  */
4506 static boolean_t
4507 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4508     mblk_t **defermp)
4509 {
4510 	sin_t	sin;
4511 	sin6_t	sin6;
4512 	mblk_t	*mp;
4513 	char	*optp = NULL;
4514 	int	optlen = 0;
4515 	cred_t	*cr;
4516 
4517 	if (defermp != NULL)
4518 		*defermp = NULL;
4519 
4520 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4521 		/*
4522 		 * Return in T_CONN_CON results of option negotiation through
4523 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4524 		 * negotiation, then what is received from remote end needs
4525 		 * to be taken into account but there is no such thing (yet?)
4526 		 * in our TCP/IP.
4527 		 * Note: We do not use mi_offset_param() here as
4528 		 * tcp_opts_conn_req contents do not directly come from
4529 		 * an application and are either generated in kernel or
4530 		 * from user input that was already verified.
4531 		 */
4532 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4533 		optp = (char *)(mp->b_rptr +
4534 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4535 		optlen = (int)
4536 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4537 	}
4538 
4539 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4540 		ipha_t *ipha = (ipha_t *)iphdr;
4541 
4542 		/* packet is IPv4 */
4543 		if (tcp->tcp_family == AF_INET) {
4544 			sin = sin_null;
4545 			sin.sin_addr.s_addr = ipha->ipha_src;
4546 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4547 			sin.sin_family = AF_INET;
4548 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4549 			    (int)sizeof (sin_t), optp, optlen);
4550 		} else {
4551 			sin6 = sin6_null;
4552 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4553 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4554 			sin6.sin6_family = AF_INET6;
4555 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4556 			    (int)sizeof (sin6_t), optp, optlen);
4557 
4558 		}
4559 	} else {
4560 		ip6_t	*ip6h = (ip6_t *)iphdr;
4561 
4562 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4563 		ASSERT(tcp->tcp_family == AF_INET6);
4564 		sin6 = sin6_null;
4565 		sin6.sin6_addr = ip6h->ip6_src;
4566 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4567 		sin6.sin6_family = AF_INET6;
4568 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4569 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4570 		    (int)sizeof (sin6_t), optp, optlen);
4571 	}
4572 
4573 	if (!mp)
4574 		return (B_FALSE);
4575 
4576 	if ((cr = DB_CRED(idmp)) != NULL) {
4577 		mblk_setcred(mp, cr);
4578 		DB_CPID(mp) = DB_CPID(idmp);
4579 	}
4580 
4581 	if (defermp == NULL)
4582 		putnext(tcp->tcp_rq, mp);
4583 	else
4584 		*defermp = mp;
4585 
4586 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4587 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4588 	return (B_TRUE);
4589 }
4590 
4591 /*
4592  * Defense for the SYN attack -
4593  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4594  *    one that doesn't have the dontdrop bit set.
4595  * 2. Don't drop a SYN request before its first timeout. This gives every
4596  *    request at least til the first timeout to complete its 3-way handshake.
4597  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4598  *    requests currently on the queue that has timed out. This will be used
4599  *    as an indicator of whether an attack is under way, so that appropriate
4600  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4601  *    either when eager goes into ESTABLISHED, or gets freed up.)
4602  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4603  *    # of timeout drops back to <= q0len/32 => SYN alert off
4604  */
4605 static boolean_t
4606 tcp_drop_q0(tcp_t *tcp)
4607 {
4608 	tcp_t	*eager;
4609 
4610 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4611 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4612 	/*
4613 	 * New one is added after next_q0 so prev_q0 points to the oldest
4614 	 * Also do not drop any established connections that are deferred on
4615 	 * q0 due to q being full
4616 	 */
4617 
4618 	eager = tcp->tcp_eager_prev_q0;
4619 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4620 		eager = eager->tcp_eager_prev_q0;
4621 		if (eager == tcp) {
4622 			eager = tcp->tcp_eager_prev_q0;
4623 			break;
4624 		}
4625 	}
4626 	if (eager->tcp_syn_rcvd_timeout == 0)
4627 		return (B_FALSE);
4628 
4629 	if (tcp->tcp_debug) {
4630 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4631 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4632 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4633 		    tcp->tcp_conn_req_cnt_q0,
4634 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4635 	}
4636 
4637 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4638 
4639 	/*
4640 	 * need to do refhold here because the selected eager could
4641 	 * be removed by someone else if we release the eager lock.
4642 	 */
4643 	CONN_INC_REF(eager->tcp_connp);
4644 	mutex_exit(&tcp->tcp_eager_lock);
4645 
4646 	/* Mark the IRE created for this SYN request temporary */
4647 	tcp_ip_ire_mark_advice(eager);
4648 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4649 	CONN_DEC_REF(eager->tcp_connp);
4650 
4651 	mutex_enter(&tcp->tcp_eager_lock);
4652 	return (B_TRUE);
4653 }
4654 
4655 int
4656 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4657     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4658 {
4659 	tcp_t 		*ltcp = lconnp->conn_tcp;
4660 	tcp_t		*tcp = connp->conn_tcp;
4661 	mblk_t		*tpi_mp;
4662 	ipha_t		*ipha;
4663 	ip6_t		*ip6h;
4664 	sin6_t 		sin6;
4665 	in6_addr_t 	v6dst;
4666 	int		err;
4667 	int		ifindex = 0;
4668 	cred_t		*cr;
4669 
4670 	if (ipvers == IPV4_VERSION) {
4671 		ipha = (ipha_t *)mp->b_rptr;
4672 
4673 		connp->conn_send = ip_output;
4674 		connp->conn_recv = tcp_input;
4675 
4676 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4677 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4678 
4679 		sin6 = sin6_null;
4680 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4681 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4682 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4683 		sin6.sin6_family = AF_INET6;
4684 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4685 		    lconnp->conn_zoneid);
4686 		if (tcp->tcp_recvdstaddr) {
4687 			sin6_t	sin6d;
4688 
4689 			sin6d = sin6_null;
4690 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4691 			    &sin6d.sin6_addr);
4692 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4693 			sin6d.sin6_family = AF_INET;
4694 			tpi_mp = mi_tpi_extconn_ind(NULL,
4695 			    (char *)&sin6d, sizeof (sin6_t),
4696 			    (char *)&tcp,
4697 			    (t_scalar_t)sizeof (intptr_t),
4698 			    (char *)&sin6d, sizeof (sin6_t),
4699 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4700 		} else {
4701 			tpi_mp = mi_tpi_conn_ind(NULL,
4702 			    (char *)&sin6, sizeof (sin6_t),
4703 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4704 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4705 		}
4706 	} else {
4707 		ip6h = (ip6_t *)mp->b_rptr;
4708 
4709 		connp->conn_send = ip_output_v6;
4710 		connp->conn_recv = tcp_input;
4711 
4712 		connp->conn_srcv6 = ip6h->ip6_dst;
4713 		connp->conn_remv6 = ip6h->ip6_src;
4714 
4715 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4716 		ifindex = (int)DB_CKSUMSTUFF(mp);
4717 		DB_CKSUMSTUFF(mp) = 0;
4718 
4719 		sin6 = sin6_null;
4720 		sin6.sin6_addr = ip6h->ip6_src;
4721 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4722 		sin6.sin6_family = AF_INET6;
4723 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4724 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4725 		    lconnp->conn_zoneid);
4726 
4727 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4728 			/* Pass up the scope_id of remote addr */
4729 			sin6.sin6_scope_id = ifindex;
4730 		} else {
4731 			sin6.sin6_scope_id = 0;
4732 		}
4733 		if (tcp->tcp_recvdstaddr) {
4734 			sin6_t	sin6d;
4735 
4736 			sin6d = sin6_null;
4737 			sin6.sin6_addr = ip6h->ip6_dst;
4738 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4739 			sin6d.sin6_family = AF_INET;
4740 			tpi_mp = mi_tpi_extconn_ind(NULL,
4741 			    (char *)&sin6d, sizeof (sin6_t),
4742 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4743 			    (char *)&sin6d, sizeof (sin6_t),
4744 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4745 		} else {
4746 			tpi_mp = mi_tpi_conn_ind(NULL,
4747 			    (char *)&sin6, sizeof (sin6_t),
4748 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4749 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4750 		}
4751 	}
4752 
4753 	if (tpi_mp == NULL)
4754 		return (ENOMEM);
4755 
4756 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4757 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4758 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4759 	connp->conn_fully_bound = B_FALSE;
4760 
4761 	if (tcp_trace)
4762 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4763 
4764 	/* Inherit information from the "parent" */
4765 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4766 	tcp->tcp_family = ltcp->tcp_family;
4767 	tcp->tcp_wq = ltcp->tcp_wq;
4768 	tcp->tcp_rq = ltcp->tcp_rq;
4769 	tcp->tcp_mss = tcp_mss_def_ipv6;
4770 	tcp->tcp_detached = B_TRUE;
4771 	if ((err = tcp_init_values(tcp)) != 0) {
4772 		freemsg(tpi_mp);
4773 		return (err);
4774 	}
4775 
4776 	if (ipvers == IPV4_VERSION) {
4777 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4778 			freemsg(tpi_mp);
4779 			return (err);
4780 		}
4781 		ASSERT(tcp->tcp_ipha != NULL);
4782 	} else {
4783 		/* ifindex must be already set */
4784 		ASSERT(ifindex != 0);
4785 
4786 		if (ltcp->tcp_bound_if != 0) {
4787 			/*
4788 			 * Set newtcp's bound_if equal to
4789 			 * listener's value. If ifindex is
4790 			 * not the same as ltcp->tcp_bound_if,
4791 			 * it must be a packet for the ipmp group
4792 			 * of interfaces
4793 			 */
4794 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4795 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4796 			tcp->tcp_bound_if = ifindex;
4797 		}
4798 
4799 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4800 		tcp->tcp_recvifindex = 0;
4801 		tcp->tcp_recvhops = 0xffffffffU;
4802 		ASSERT(tcp->tcp_ip6h != NULL);
4803 	}
4804 
4805 	tcp->tcp_lport = ltcp->tcp_lport;
4806 
4807 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4808 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4809 			/*
4810 			 * Listener had options of some sort; eager inherits.
4811 			 * Free up the eager template and allocate one
4812 			 * of the right size.
4813 			 */
4814 			if (tcp->tcp_hdr_grown) {
4815 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4816 			} else {
4817 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4818 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4819 			}
4820 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4821 			    KM_NOSLEEP);
4822 			if (tcp->tcp_iphc == NULL) {
4823 				tcp->tcp_iphc_len = 0;
4824 				freemsg(tpi_mp);
4825 				return (ENOMEM);
4826 			}
4827 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4828 			tcp->tcp_hdr_grown = B_TRUE;
4829 		}
4830 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4831 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4832 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4833 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4834 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4835 
4836 		/*
4837 		 * Copy the IP+TCP header template from listener to eager
4838 		 */
4839 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4840 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4841 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4842 			    IPPROTO_RAW) {
4843 				tcp->tcp_ip6h =
4844 				    (ip6_t *)(tcp->tcp_iphc +
4845 					sizeof (ip6i_t));
4846 			} else {
4847 				tcp->tcp_ip6h =
4848 				    (ip6_t *)(tcp->tcp_iphc);
4849 			}
4850 			tcp->tcp_ipha = NULL;
4851 		} else {
4852 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4853 			tcp->tcp_ip6h = NULL;
4854 		}
4855 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4856 		    tcp->tcp_ip_hdr_len);
4857 	} else {
4858 		/*
4859 		 * only valid case when ipversion of listener and
4860 		 * eager differ is when listener is IPv6 and
4861 		 * eager is IPv4.
4862 		 * Eager header template has been initialized to the
4863 		 * maximum v4 header sizes, which includes space for
4864 		 * TCP and IP options.
4865 		 */
4866 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4867 		    (tcp->tcp_ipversion == IPV4_VERSION));
4868 		ASSERT(tcp->tcp_iphc_len >=
4869 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4870 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4871 		/* copy IP header fields individually */
4872 		tcp->tcp_ipha->ipha_ttl =
4873 		    ltcp->tcp_ip6h->ip6_hops;
4874 		bcopy(ltcp->tcp_tcph->th_lport,
4875 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4876 	}
4877 
4878 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4879 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4880 	    sizeof (in_port_t));
4881 
4882 	if (ltcp->tcp_lport == 0) {
4883 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4884 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4885 		    sizeof (in_port_t));
4886 	}
4887 
4888 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4889 		ASSERT(ipha != NULL);
4890 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4891 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4892 
4893 		/* Source routing option copyover (reverse it) */
4894 		if (tcp_rev_src_routes)
4895 			tcp_opt_reverse(tcp, ipha);
4896 	} else {
4897 		ASSERT(ip6h != NULL);
4898 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4899 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4900 	}
4901 
4902 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4903 	/*
4904 	 * If the SYN contains a credential, it's a loopback packet; attach
4905 	 * the credential to the TPI message.
4906 	 */
4907 	if ((cr = DB_CRED(idmp)) != NULL) {
4908 		mblk_setcred(tpi_mp, cr);
4909 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4910 	}
4911 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4912 
4913 	/* Inherit the listener's SSL protection state */
4914 
4915 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4916 		kssl_hold_ent(tcp->tcp_kssl_ent);
4917 		tcp->tcp_kssl_pending = B_TRUE;
4918 	}
4919 
4920 	return (0);
4921 }
4922 
4923 
4924 int
4925 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4926     tcph_t *tcph, mblk_t *idmp)
4927 {
4928 	tcp_t 		*ltcp = lconnp->conn_tcp;
4929 	tcp_t		*tcp = connp->conn_tcp;
4930 	sin_t		sin;
4931 	mblk_t		*tpi_mp = NULL;
4932 	int		err;
4933 	cred_t		*cr;
4934 
4935 	sin = sin_null;
4936 	sin.sin_addr.s_addr = ipha->ipha_src;
4937 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4938 	sin.sin_family = AF_INET;
4939 	if (ltcp->tcp_recvdstaddr) {
4940 		sin_t	sind;
4941 
4942 		sind = sin_null;
4943 		sind.sin_addr.s_addr = ipha->ipha_dst;
4944 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4945 		sind.sin_family = AF_INET;
4946 		tpi_mp = mi_tpi_extconn_ind(NULL,
4947 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4948 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4949 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4950 	} else {
4951 		tpi_mp = mi_tpi_conn_ind(NULL,
4952 		    (char *)&sin, sizeof (sin_t),
4953 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4954 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4955 	}
4956 
4957 	if (tpi_mp == NULL) {
4958 		return (ENOMEM);
4959 	}
4960 
4961 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4962 	connp->conn_send = ip_output;
4963 	connp->conn_recv = tcp_input;
4964 	connp->conn_fully_bound = B_FALSE;
4965 
4966 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4967 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4968 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4969 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4970 
4971 	if (tcp_trace) {
4972 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4973 	}
4974 
4975 	/* Inherit information from the "parent" */
4976 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4977 	tcp->tcp_family = ltcp->tcp_family;
4978 	tcp->tcp_wq = ltcp->tcp_wq;
4979 	tcp->tcp_rq = ltcp->tcp_rq;
4980 	tcp->tcp_mss = tcp_mss_def_ipv4;
4981 	tcp->tcp_detached = B_TRUE;
4982 	if ((err = tcp_init_values(tcp)) != 0) {
4983 		freemsg(tpi_mp);
4984 		return (err);
4985 	}
4986 
4987 	/*
4988 	 * Let's make sure that eager tcp template has enough space to
4989 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4990 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4991 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4992 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4993 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4994 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4995 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4996 	 */
4997 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4998 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4999 
5000 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5001 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5002 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5003 	tcp->tcp_ttl = ltcp->tcp_ttl;
5004 	tcp->tcp_tos = ltcp->tcp_tos;
5005 
5006 	/* Copy the IP+TCP header template from listener to eager */
5007 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5008 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5009 	tcp->tcp_ip6h = NULL;
5010 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5011 	    tcp->tcp_ip_hdr_len);
5012 
5013 	/* Initialize the IP addresses and Ports */
5014 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5015 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5016 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5017 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5018 
5019 	/* Source routing option copyover (reverse it) */
5020 	if (tcp_rev_src_routes)
5021 		tcp_opt_reverse(tcp, ipha);
5022 
5023 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5024 
5025 	/*
5026 	 * If the SYN contains a credential, it's a loopback packet; attach
5027 	 * the credential to the TPI message.
5028 	 */
5029 	if ((cr = DB_CRED(idmp)) != NULL) {
5030 		mblk_setcred(tpi_mp, cr);
5031 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5032 	}
5033 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5034 
5035 	/* Inherit the listener's SSL protection state */
5036 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5037 		kssl_hold_ent(tcp->tcp_kssl_ent);
5038 		tcp->tcp_kssl_pending = B_TRUE;
5039 	}
5040 
5041 	return (0);
5042 }
5043 
5044 /*
5045  * sets up conn for ipsec.
5046  * if the first mblk is M_CTL it is consumed and mpp is updated.
5047  * in case of error mpp is freed.
5048  */
5049 conn_t *
5050 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5051 {
5052 	conn_t 		*connp = tcp->tcp_connp;
5053 	conn_t 		*econnp;
5054 	squeue_t 	*new_sqp;
5055 	mblk_t 		*first_mp = *mpp;
5056 	mblk_t		*mp = *mpp;
5057 	boolean_t	mctl_present = B_FALSE;
5058 	uint_t		ipvers;
5059 
5060 	econnp = tcp_get_conn(sqp);
5061 	if (econnp == NULL) {
5062 		freemsg(first_mp);
5063 		return (NULL);
5064 	}
5065 	if (DB_TYPE(mp) == M_CTL) {
5066 		if (mp->b_cont == NULL ||
5067 		    mp->b_cont->b_datap->db_type != M_DATA) {
5068 			freemsg(first_mp);
5069 			return (NULL);
5070 		}
5071 		mp = mp->b_cont;
5072 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5073 			freemsg(first_mp);
5074 			return (NULL);
5075 		}
5076 
5077 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5078 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5079 		mctl_present = B_TRUE;
5080 	} else {
5081 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5082 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5083 	}
5084 
5085 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5086 	DB_CKSUMSTART(mp) = 0;
5087 
5088 	ASSERT(OK_32PTR(mp->b_rptr));
5089 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5090 	if (ipvers == IPV4_VERSION) {
5091 		uint16_t  	*up;
5092 		uint32_t	ports;
5093 		ipha_t		*ipha;
5094 
5095 		ipha = (ipha_t *)mp->b_rptr;
5096 		up = (uint16_t *)((uchar_t *)ipha +
5097 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5098 		ports = *(uint32_t *)up;
5099 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5100 		    ipha->ipha_dst, ipha->ipha_src, ports);
5101 	} else {
5102 		uint16_t  	*up;
5103 		uint32_t	ports;
5104 		uint16_t	ip_hdr_len;
5105 		uint8_t		*nexthdrp;
5106 		ip6_t 		*ip6h;
5107 		tcph_t		*tcph;
5108 
5109 		ip6h = (ip6_t *)mp->b_rptr;
5110 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5111 			ip_hdr_len = IPV6_HDR_LEN;
5112 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5113 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5114 			CONN_DEC_REF(econnp);
5115 			freemsg(first_mp);
5116 			return (NULL);
5117 		}
5118 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5119 		up = (uint16_t *)tcph->th_lport;
5120 		ports = *(uint32_t *)up;
5121 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5122 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5123 	}
5124 
5125 	/*
5126 	 * The caller already ensured that there is a sqp present.
5127 	 */
5128 	econnp->conn_sqp = new_sqp;
5129 
5130 	if (connp->conn_policy != NULL) {
5131 		ipsec_in_t *ii;
5132 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5133 		ASSERT(ii->ipsec_in_policy == NULL);
5134 		IPPH_REFHOLD(connp->conn_policy);
5135 		ii->ipsec_in_policy = connp->conn_policy;
5136 
5137 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5138 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5139 			CONN_DEC_REF(econnp);
5140 			freemsg(first_mp);
5141 			return (NULL);
5142 		}
5143 	}
5144 
5145 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5146 		CONN_DEC_REF(econnp);
5147 		freemsg(first_mp);
5148 		return (NULL);
5149 	}
5150 
5151 	/*
5152 	 * If we know we have some policy, pass the "IPSEC"
5153 	 * options size TCP uses this adjust the MSS.
5154 	 */
5155 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5156 	if (mctl_present) {
5157 		freeb(first_mp);
5158 		*mpp = mp;
5159 	}
5160 
5161 	return (econnp);
5162 }
5163 
5164 /*
5165  * tcp_get_conn/tcp_free_conn
5166  *
5167  * tcp_get_conn is used to get a clean tcp connection structure.
5168  * It tries to reuse the connections put on the freelist by the
5169  * time_wait_collector failing which it goes to kmem_cache. This
5170  * way has two benefits compared to just allocating from and
5171  * freeing to kmem_cache.
5172  * 1) The time_wait_collector can free (which includes the cleanup)
5173  * outside the squeue. So when the interrupt comes, we have a clean
5174  * connection sitting in the freelist. Obviously, this buys us
5175  * performance.
5176  *
5177  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5178  * has multiple disadvantages - tying up the squeue during alloc, and the
5179  * fact that IPSec policy initialization has to happen here which
5180  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5181  * But allocating the conn/tcp in IP land is also not the best since
5182  * we can't check the 'q' and 'q0' which are protected by squeue and
5183  * blindly allocate memory which might have to be freed here if we are
5184  * not allowed to accept the connection. By using the freelist and
5185  * putting the conn/tcp back in freelist, we don't pay a penalty for
5186  * allocating memory without checking 'q/q0' and freeing it if we can't
5187  * accept the connection.
5188  *
5189  * Care should be taken to put the conn back in the same squeue's freelist
5190  * from which it was allocated. Best results are obtained if conn is
5191  * allocated from listener's squeue and freed to the same. Time wait
5192  * collector will free up the freelist is the connection ends up sitting
5193  * there for too long.
5194  */
5195 void *
5196 tcp_get_conn(void *arg)
5197 {
5198 	tcp_t			*tcp = NULL;
5199 	conn_t			*connp = NULL;
5200 	squeue_t		*sqp = (squeue_t *)arg;
5201 	tcp_squeue_priv_t 	*tcp_time_wait;
5202 
5203 	tcp_time_wait =
5204 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5205 
5206 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5207 	tcp = tcp_time_wait->tcp_free_list;
5208 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5209 	if (tcp != NULL) {
5210 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5211 		tcp_time_wait->tcp_free_list_cnt--;
5212 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5213 		tcp->tcp_time_wait_next = NULL;
5214 		connp = tcp->tcp_connp;
5215 		connp->conn_flags |= IPCL_REUSED;
5216 		return ((void *)connp);
5217 	}
5218 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5219 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5220 		return (NULL);
5221 	return ((void *)connp);
5222 }
5223 
5224 /*
5225  * Update the cached label for the given tcp_t.  This should be called once per
5226  * connection, and before any packets are sent or tcp_process_options is
5227  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5228  */
5229 static boolean_t
5230 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5231 {
5232 	conn_t *connp = tcp->tcp_connp;
5233 
5234 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5235 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5236 		int added;
5237 
5238 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5239 		    connp->conn_mac_exempt) != 0)
5240 			return (B_FALSE);
5241 
5242 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5243 		if (added == -1)
5244 			return (B_FALSE);
5245 		tcp->tcp_hdr_len += added;
5246 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5247 		tcp->tcp_ip_hdr_len += added;
5248 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5249 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5250 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5251 			    tcp->tcp_hdr_len);
5252 			if (added == -1)
5253 				return (B_FALSE);
5254 			tcp->tcp_hdr_len += added;
5255 			tcp->tcp_tcph = (tcph_t *)
5256 			    ((uchar_t *)tcp->tcp_tcph + added);
5257 			tcp->tcp_ip_hdr_len += added;
5258 		}
5259 	} else {
5260 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5261 
5262 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5263 		    connp->conn_mac_exempt) != 0)
5264 			return (B_FALSE);
5265 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5266 		    &tcp->tcp_label_len, optbuf) != 0)
5267 			return (B_FALSE);
5268 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5269 			return (B_FALSE);
5270 	}
5271 
5272 	connp->conn_ulp_labeled = 1;
5273 
5274 	return (B_TRUE);
5275 }
5276 
5277 /* BEGIN CSTYLED */
5278 /*
5279  *
5280  * The sockfs ACCEPT path:
5281  * =======================
5282  *
5283  * The eager is now established in its own perimeter as soon as SYN is
5284  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5285  * completes the accept processing on the acceptor STREAM. The sending
5286  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5287  * listener but a TLI/XTI listener completes the accept processing
5288  * on the listener perimeter.
5289  *
5290  * Common control flow for 3 way handshake:
5291  * ----------------------------------------
5292  *
5293  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5294  *					-> tcp_conn_request()
5295  *
5296  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5297  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5298  *
5299  * Sockfs ACCEPT Path:
5300  * -------------------
5301  *
5302  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5303  * as STREAM entry point)
5304  *
5305  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5306  *
5307  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5308  * association (we are not behind eager's squeue but sockfs is protecting us
5309  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5310  * is changed to point at tcp_wput().
5311  *
5312  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5313  * listener (done on listener's perimeter).
5314  *
5315  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5316  * accept.
5317  *
5318  * TLI/XTI client ACCEPT path:
5319  * ---------------------------
5320  *
5321  * soaccept() sends T_CONN_RES on the listener STREAM.
5322  *
5323  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5324  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5325  *
5326  * Locks:
5327  * ======
5328  *
5329  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5330  * and listeners->tcp_eager_next_q.
5331  *
5332  * Referencing:
5333  * ============
5334  *
5335  * 1) We start out in tcp_conn_request by eager placing a ref on
5336  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5337  *
5338  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5339  * doing so we place a ref on the eager. This ref is finally dropped at the
5340  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5341  * reference is dropped by the squeue framework.
5342  *
5343  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5344  *
5345  * The reference must be released by the same entity that added the reference
5346  * In the above scheme, the eager is the entity that adds and releases the
5347  * references. Note that tcp_accept_finish executes in the squeue of the eager
5348  * (albeit after it is attached to the acceptor stream). Though 1. executes
5349  * in the listener's squeue, the eager is nascent at this point and the
5350  * reference can be considered to have been added on behalf of the eager.
5351  *
5352  * Eager getting a Reset or listener closing:
5353  * ==========================================
5354  *
5355  * Once the listener and eager are linked, the listener never does the unlink.
5356  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5357  * a message on all eager perimeter. The eager then does the unlink, clears
5358  * any pointers to the listener's queue and drops the reference to the
5359  * listener. The listener waits in tcp_close outside the squeue until its
5360  * refcount has dropped to 1. This ensures that the listener has waited for
5361  * all eagers to clear their association with the listener.
5362  *
5363  * Similarly, if eager decides to go away, it can unlink itself and close.
5364  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5365  * the reference to eager is still valid because of the extra ref we put
5366  * in tcp_send_conn_ind.
5367  *
5368  * Listener can always locate the eager under the protection
5369  * of the listener->tcp_eager_lock, and then do a refhold
5370  * on the eager during the accept processing.
5371  *
5372  * The acceptor stream accesses the eager in the accept processing
5373  * based on the ref placed on eager before sending T_conn_ind.
5374  * The only entity that can negate this refhold is a listener close
5375  * which is mutually exclusive with an active acceptor stream.
5376  *
5377  * Eager's reference on the listener
5378  * ===================================
5379  *
5380  * If the accept happens (even on a closed eager) the eager drops its
5381  * reference on the listener at the start of tcp_accept_finish. If the
5382  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5383  * the reference is dropped in tcp_closei_local. If the listener closes,
5384  * the reference is dropped in tcp_eager_kill. In all cases the reference
5385  * is dropped while executing in the eager's context (squeue).
5386  */
5387 /* END CSTYLED */
5388 
5389 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5390 
5391 /*
5392  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5393  * tcp_rput_data will not see any SYN packets.
5394  */
5395 /* ARGSUSED */
5396 void
5397 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5398 {
5399 	tcph_t		*tcph;
5400 	uint32_t	seg_seq;
5401 	tcp_t		*eager;
5402 	uint_t		ipvers;
5403 	ipha_t		*ipha;
5404 	ip6_t		*ip6h;
5405 	int		err;
5406 	conn_t		*econnp = NULL;
5407 	squeue_t	*new_sqp;
5408 	mblk_t		*mp1;
5409 	uint_t 		ip_hdr_len;
5410 	conn_t		*connp = (conn_t *)arg;
5411 	tcp_t		*tcp = connp->conn_tcp;
5412 	ire_t		*ire;
5413 	cred_t		*credp;
5414 
5415 	if (tcp->tcp_state != TCPS_LISTEN)
5416 		goto error2;
5417 
5418 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5419 
5420 	mutex_enter(&tcp->tcp_eager_lock);
5421 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5422 		mutex_exit(&tcp->tcp_eager_lock);
5423 		TCP_STAT(tcp_listendrop);
5424 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5425 		if (tcp->tcp_debug) {
5426 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5427 			    "tcp_conn_request: listen backlog (max=%d) "
5428 			    "overflow (%d pending) on %s",
5429 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5430 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5431 		}
5432 		goto error2;
5433 	}
5434 
5435 	if (tcp->tcp_conn_req_cnt_q0 >=
5436 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5437 		/*
5438 		 * Q0 is full. Drop a pending half-open req from the queue
5439 		 * to make room for the new SYN req. Also mark the time we
5440 		 * drop a SYN.
5441 		 *
5442 		 * A more aggressive defense against SYN attack will
5443 		 * be to set the "tcp_syn_defense" flag now.
5444 		 */
5445 		TCP_STAT(tcp_listendropq0);
5446 		tcp->tcp_last_rcv_lbolt = lbolt64;
5447 		if (!tcp_drop_q0(tcp)) {
5448 			mutex_exit(&tcp->tcp_eager_lock);
5449 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5450 			if (tcp->tcp_debug) {
5451 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5452 				    "tcp_conn_request: listen half-open queue "
5453 				    "(max=%d) full (%d pending) on %s",
5454 				    tcp_conn_req_max_q0,
5455 				    tcp->tcp_conn_req_cnt_q0,
5456 				    tcp_display(tcp, NULL,
5457 				    DISP_PORT_ONLY));
5458 			}
5459 			goto error2;
5460 		}
5461 	}
5462 	mutex_exit(&tcp->tcp_eager_lock);
5463 
5464 	/*
5465 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5466 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5467 	 * link local address.  If IPSec is enabled, db_struioflag has
5468 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5469 	 * otherwise an error case if neither of them is set.
5470 	 */
5471 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5472 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5473 		DB_CKSUMSTART(mp) = 0;
5474 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5475 		econnp = (conn_t *)tcp_get_conn(arg2);
5476 		if (econnp == NULL)
5477 			goto error2;
5478 		econnp->conn_sqp = new_sqp;
5479 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5480 		/*
5481 		 * mp is updated in tcp_get_ipsec_conn().
5482 		 */
5483 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5484 		if (econnp == NULL) {
5485 			/*
5486 			 * mp freed by tcp_get_ipsec_conn.
5487 			 */
5488 			return;
5489 		}
5490 	} else {
5491 		goto error2;
5492 	}
5493 
5494 	ASSERT(DB_TYPE(mp) == M_DATA);
5495 
5496 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5497 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5498 	ASSERT(OK_32PTR(mp->b_rptr));
5499 	if (ipvers == IPV4_VERSION) {
5500 		ipha = (ipha_t *)mp->b_rptr;
5501 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5502 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5503 	} else {
5504 		ip6h = (ip6_t *)mp->b_rptr;
5505 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5506 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5507 	}
5508 
5509 	if (tcp->tcp_family == AF_INET) {
5510 		ASSERT(ipvers == IPV4_VERSION);
5511 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5512 	} else {
5513 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5514 	}
5515 
5516 	if (err)
5517 		goto error3;
5518 
5519 	eager = econnp->conn_tcp;
5520 
5521 	/* Inherit various TCP parameters from the listener */
5522 	eager->tcp_naglim = tcp->tcp_naglim;
5523 	eager->tcp_first_timer_threshold =
5524 	    tcp->tcp_first_timer_threshold;
5525 	eager->tcp_second_timer_threshold =
5526 	    tcp->tcp_second_timer_threshold;
5527 
5528 	eager->tcp_first_ctimer_threshold =
5529 	    tcp->tcp_first_ctimer_threshold;
5530 	eager->tcp_second_ctimer_threshold =
5531 	    tcp->tcp_second_ctimer_threshold;
5532 
5533 	/*
5534 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5535 	 * If it does not, the eager's receive window will be set to the
5536 	 * listener's receive window later in this function.
5537 	 */
5538 	eager->tcp_rwnd = 0;
5539 
5540 	/*
5541 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5542 	 * calling tcp_process_options() where tcp_mss_set() is called
5543 	 * to set the initial cwnd.
5544 	 */
5545 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5546 
5547 	/*
5548 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5549 	 * zone id before the accept is completed in tcp_wput_accept().
5550 	 */
5551 	econnp->conn_zoneid = connp->conn_zoneid;
5552 
5553 	/* Copy nexthop information from listener to eager */
5554 	if (connp->conn_nexthop_set) {
5555 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5556 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5557 	}
5558 
5559 	/*
5560 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5561 	 * eager is accepted
5562 	 */
5563 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5564 	crhold(credp);
5565 
5566 	/*
5567 	 * If the caller has the process-wide flag set, then default to MAC
5568 	 * exempt mode.  This allows read-down to unlabeled hosts.
5569 	 */
5570 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5571 		econnp->conn_mac_exempt = B_TRUE;
5572 
5573 	if (is_system_labeled()) {
5574 		cred_t *cr;
5575 
5576 		if (connp->conn_mlp_type != mlptSingle) {
5577 			cr = econnp->conn_peercred = DB_CRED(mp);
5578 			if (cr != NULL)
5579 				crhold(cr);
5580 			else
5581 				cr = econnp->conn_cred;
5582 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5583 			    econnp, cred_t *, cr)
5584 		} else {
5585 			cr = econnp->conn_cred;
5586 			DTRACE_PROBE2(syn_accept, conn_t *,
5587 			    econnp, cred_t *, cr)
5588 		}
5589 
5590 		if (!tcp_update_label(eager, cr)) {
5591 			DTRACE_PROBE3(
5592 			    tx__ip__log__error__connrequest__tcp,
5593 			    char *, "eager connp(1) label on SYN mp(2) failed",
5594 			    conn_t *, econnp, mblk_t *, mp);
5595 			goto error3;
5596 		}
5597 	}
5598 
5599 	eager->tcp_hard_binding = B_TRUE;
5600 
5601 	tcp_bind_hash_insert(&tcp_bind_fanout[
5602 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5603 
5604 	CL_INET_CONNECT(eager);
5605 
5606 	/*
5607 	 * No need to check for multicast destination since ip will only pass
5608 	 * up multicasts to those that have expressed interest
5609 	 * TODO: what about rejecting broadcasts?
5610 	 * Also check that source is not a multicast or broadcast address.
5611 	 */
5612 	eager->tcp_state = TCPS_SYN_RCVD;
5613 
5614 
5615 	/*
5616 	 * There should be no ire in the mp as we are being called after
5617 	 * receiving the SYN.
5618 	 */
5619 	ASSERT(tcp_ire_mp(mp) == NULL);
5620 
5621 	/*
5622 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5623 	 */
5624 
5625 	if (tcp_adapt_ire(eager, NULL) == 0) {
5626 		/* Undo the bind_hash_insert */
5627 		tcp_bind_hash_remove(eager);
5628 		goto error3;
5629 	}
5630 
5631 	/* Process all TCP options. */
5632 	tcp_process_options(eager, tcph);
5633 
5634 	/* Is the other end ECN capable? */
5635 	if (tcp_ecn_permitted >= 1 &&
5636 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5637 		eager->tcp_ecn_ok = B_TRUE;
5638 	}
5639 
5640 	/*
5641 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5642 	 * window size changed via SO_RCVBUF option.  First round up the
5643 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5644 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5645 	 * setting.
5646 	 *
5647 	 * Note if there is a rpipe metric associated with the remote host,
5648 	 * we should not inherit receive window size from listener.
5649 	 */
5650 	eager->tcp_rwnd = MSS_ROUNDUP(
5651 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5652 	    eager->tcp_rwnd), eager->tcp_mss);
5653 	if (eager->tcp_snd_ws_ok)
5654 		tcp_set_ws_value(eager);
5655 	/*
5656 	 * Note that this is the only place tcp_rwnd_set() is called for
5657 	 * accepting a connection.  We need to call it here instead of
5658 	 * after the 3-way handshake because we need to tell the other
5659 	 * side our rwnd in the SYN-ACK segment.
5660 	 */
5661 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5662 
5663 	/*
5664 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5665 	 * via soaccept()->soinheritoptions() which essentially applies
5666 	 * all the listener options to the new STREAM. The options that we
5667 	 * need to take care of are:
5668 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5669 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5670 	 * SO_SNDBUF, SO_RCVBUF.
5671 	 *
5672 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5673 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5674 	 *		tcp_maxpsz_set() gets called later from
5675 	 *		tcp_accept_finish(), the option takes effect.
5676 	 *
5677 	 */
5678 	/* Set the TCP options */
5679 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5680 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5681 	eager->tcp_oobinline = tcp->tcp_oobinline;
5682 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5683 	eager->tcp_broadcast = tcp->tcp_broadcast;
5684 	eager->tcp_useloopback = tcp->tcp_useloopback;
5685 	eager->tcp_dontroute = tcp->tcp_dontroute;
5686 	eager->tcp_linger = tcp->tcp_linger;
5687 	eager->tcp_lingertime = tcp->tcp_lingertime;
5688 	if (tcp->tcp_ka_enabled)
5689 		eager->tcp_ka_enabled = 1;
5690 
5691 	/* Set the IP options */
5692 	econnp->conn_broadcast = connp->conn_broadcast;
5693 	econnp->conn_loopback = connp->conn_loopback;
5694 	econnp->conn_dontroute = connp->conn_dontroute;
5695 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5696 
5697 	/* Put a ref on the listener for the eager. */
5698 	CONN_INC_REF(connp);
5699 	mutex_enter(&tcp->tcp_eager_lock);
5700 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5701 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5702 	tcp->tcp_eager_next_q0 = eager;
5703 	eager->tcp_eager_prev_q0 = tcp;
5704 
5705 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5706 	eager->tcp_listener = tcp;
5707 	eager->tcp_saved_listener = tcp;
5708 
5709 	/*
5710 	 * Tag this detached tcp vector for later retrieval
5711 	 * by our listener client in tcp_accept().
5712 	 */
5713 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5714 	tcp->tcp_conn_req_cnt_q0++;
5715 	if (++tcp->tcp_conn_req_seqnum == -1) {
5716 		/*
5717 		 * -1 is "special" and defined in TPI as something
5718 		 * that should never be used in T_CONN_IND
5719 		 */
5720 		++tcp->tcp_conn_req_seqnum;
5721 	}
5722 	mutex_exit(&tcp->tcp_eager_lock);
5723 
5724 	if (tcp->tcp_syn_defense) {
5725 		/* Don't drop the SYN that comes from a good IP source */
5726 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5727 		if (addr_cache != NULL && eager->tcp_remote ==
5728 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5729 			eager->tcp_dontdrop = B_TRUE;
5730 		}
5731 	}
5732 
5733 	/*
5734 	 * We need to insert the eager in its own perimeter but as soon
5735 	 * as we do that, we expose the eager to the classifier and
5736 	 * should not touch any field outside the eager's perimeter.
5737 	 * So do all the work necessary before inserting the eager
5738 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5739 	 * will succeed but undo everything if it fails.
5740 	 */
5741 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5742 	eager->tcp_irs = seg_seq;
5743 	eager->tcp_rack = seg_seq;
5744 	eager->tcp_rnxt = seg_seq + 1;
5745 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5746 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5747 	eager->tcp_state = TCPS_SYN_RCVD;
5748 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5749 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5750 	if (mp1 == NULL)
5751 		goto error1;
5752 	DB_CPID(mp1) = tcp->tcp_cpid;
5753 
5754 	/*
5755 	 * We need to start the rto timer. In normal case, we start
5756 	 * the timer after sending the packet on the wire (or at
5757 	 * least believing that packet was sent by waiting for
5758 	 * CALL_IP_WPUT() to return). Since this is the first packet
5759 	 * being sent on the wire for the eager, our initial tcp_rto
5760 	 * is at least tcp_rexmit_interval_min which is a fairly
5761 	 * large value to allow the algorithm to adjust slowly to large
5762 	 * fluctuations of RTT during first few transmissions.
5763 	 *
5764 	 * Starting the timer first and then sending the packet in this
5765 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5766 	 * is of the order of several 100ms and starting the timer
5767 	 * first and then sending the packet will result in difference
5768 	 * of few micro seconds.
5769 	 *
5770 	 * Without this optimization, we are forced to hold the fanout
5771 	 * lock across the ipcl_bind_insert() and sending the packet
5772 	 * so that we don't race against an incoming packet (maybe RST)
5773 	 * for this eager.
5774 	 */
5775 
5776 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5777 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5778 
5779 
5780 	/*
5781 	 * Insert the eager in its own perimeter now. We are ready to deal
5782 	 * with any packets on eager.
5783 	 */
5784 	if (eager->tcp_ipversion == IPV4_VERSION) {
5785 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5786 			goto error;
5787 		}
5788 	} else {
5789 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5790 			goto error;
5791 		}
5792 	}
5793 
5794 	/* mark conn as fully-bound */
5795 	econnp->conn_fully_bound = B_TRUE;
5796 
5797 	/* Send the SYN-ACK */
5798 	tcp_send_data(eager, eager->tcp_wq, mp1);
5799 	freemsg(mp);
5800 
5801 	return;
5802 error:
5803 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5804 	freemsg(mp1);
5805 error1:
5806 	/* Undo what we did above */
5807 	mutex_enter(&tcp->tcp_eager_lock);
5808 	tcp_eager_unlink(eager);
5809 	mutex_exit(&tcp->tcp_eager_lock);
5810 	/* Drop eager's reference on the listener */
5811 	CONN_DEC_REF(connp);
5812 
5813 	/*
5814 	 * Delete the cached ire in conn_ire_cache and also mark
5815 	 * the conn as CONDEMNED
5816 	 */
5817 	mutex_enter(&econnp->conn_lock);
5818 	econnp->conn_state_flags |= CONN_CONDEMNED;
5819 	ire = econnp->conn_ire_cache;
5820 	econnp->conn_ire_cache = NULL;
5821 	mutex_exit(&econnp->conn_lock);
5822 	if (ire != NULL)
5823 		IRE_REFRELE_NOTR(ire);
5824 
5825 	/*
5826 	 * tcp_accept_comm inserts the eager to the bind_hash
5827 	 * we need to remove it from the hash if ipcl_conn_insert
5828 	 * fails.
5829 	 */
5830 	tcp_bind_hash_remove(eager);
5831 	/* Drop the eager ref placed in tcp_open_detached */
5832 	CONN_DEC_REF(econnp);
5833 
5834 	/*
5835 	 * If a connection already exists, send the mp to that connections so
5836 	 * that it can be appropriately dealt with.
5837 	 */
5838 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5839 		if (!IPCL_IS_CONNECTED(econnp)) {
5840 			/*
5841 			 * Something bad happened. ipcl_conn_insert()
5842 			 * failed because a connection already existed
5843 			 * in connected hash but we can't find it
5844 			 * anymore (someone blew it away). Just
5845 			 * free this message and hopefully remote
5846 			 * will retransmit at which time the SYN can be
5847 			 * treated as a new connection or dealth with
5848 			 * a TH_RST if a connection already exists.
5849 			 */
5850 			freemsg(mp);
5851 		} else {
5852 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5853 			    econnp, SQTAG_TCP_CONN_REQ);
5854 		}
5855 	} else {
5856 		/* Nobody wants this packet */
5857 		freemsg(mp);
5858 	}
5859 	return;
5860 error2:
5861 	freemsg(mp);
5862 	return;
5863 error3:
5864 	CONN_DEC_REF(econnp);
5865 	freemsg(mp);
5866 }
5867 
5868 /*
5869  * In an ideal case of vertical partition in NUMA architecture, its
5870  * beneficial to have the listener and all the incoming connections
5871  * tied to the same squeue. The other constraint is that incoming
5872  * connections should be tied to the squeue attached to interrupted
5873  * CPU for obvious locality reason so this leaves the listener to
5874  * be tied to the same squeue. Our only problem is that when listener
5875  * is binding, the CPU that will get interrupted by the NIC whose
5876  * IP address the listener is binding to is not even known. So
5877  * the code below allows us to change that binding at the time the
5878  * CPU is interrupted by virtue of incoming connection's squeue.
5879  *
5880  * This is usefull only in case of a listener bound to a specific IP
5881  * address. For other kind of listeners, they get bound the
5882  * very first time and there is no attempt to rebind them.
5883  */
5884 void
5885 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5886 {
5887 	conn_t		*connp = (conn_t *)arg;
5888 	squeue_t	*sqp = (squeue_t *)arg2;
5889 	squeue_t	*new_sqp;
5890 	uint32_t	conn_flags;
5891 
5892 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5893 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5894 	} else {
5895 		goto done;
5896 	}
5897 
5898 	if (connp->conn_fanout == NULL)
5899 		goto done;
5900 
5901 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5902 		mutex_enter(&connp->conn_fanout->connf_lock);
5903 		mutex_enter(&connp->conn_lock);
5904 		/*
5905 		 * No one from read or write side can access us now
5906 		 * except for already queued packets on this squeue.
5907 		 * But since we haven't changed the squeue yet, they
5908 		 * can't execute. If they are processed after we have
5909 		 * changed the squeue, they are sent back to the
5910 		 * correct squeue down below.
5911 		 */
5912 		if (connp->conn_sqp != new_sqp) {
5913 			while (connp->conn_sqp != new_sqp)
5914 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5915 		}
5916 
5917 		do {
5918 			conn_flags = connp->conn_flags;
5919 			conn_flags |= IPCL_FULLY_BOUND;
5920 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5921 			    conn_flags);
5922 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5923 
5924 		mutex_exit(&connp->conn_fanout->connf_lock);
5925 		mutex_exit(&connp->conn_lock);
5926 	}
5927 
5928 done:
5929 	if (connp->conn_sqp != sqp) {
5930 		CONN_INC_REF(connp);
5931 		squeue_fill(connp->conn_sqp, mp,
5932 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5933 	} else {
5934 		tcp_conn_request(connp, mp, sqp);
5935 	}
5936 }
5937 
5938 /*
5939  * Successful connect request processing begins when our client passes
5940  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5941  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5942  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5943  *   upstream <- tcp_rput()                <- IP
5944  * After various error checks are completed, tcp_connect() lays
5945  * the target address and port into the composite header template,
5946  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5947  * request followed by an IRE request, and passes the three mblk message
5948  * down to IP looking like this:
5949  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5950  * Processing continues in tcp_rput() when we receive the following message:
5951  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5952  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5953  * to fire off the connection request, and then passes the T_OK_ACK mblk
5954  * upstream that we filled in below.  There are, of course, numerous
5955  * error conditions along the way which truncate the processing described
5956  * above.
5957  */
5958 static void
5959 tcp_connect(tcp_t *tcp, mblk_t *mp)
5960 {
5961 	sin_t		*sin;
5962 	sin6_t		*sin6;
5963 	queue_t		*q = tcp->tcp_wq;
5964 	struct T_conn_req	*tcr;
5965 	ipaddr_t	*dstaddrp;
5966 	in_port_t	dstport;
5967 	uint_t		srcid;
5968 
5969 	tcr = (struct T_conn_req *)mp->b_rptr;
5970 
5971 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5972 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5973 		tcp_err_ack(tcp, mp, TPROTO, 0);
5974 		return;
5975 	}
5976 
5977 	/*
5978 	 * Determine packet type based on type of address passed in
5979 	 * the request should contain an IPv4 or IPv6 address.
5980 	 * Make sure that address family matches the type of
5981 	 * family of the the address passed down
5982 	 */
5983 	switch (tcr->DEST_length) {
5984 	default:
5985 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5986 		return;
5987 
5988 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5989 		/*
5990 		 * XXX: The check for valid DEST_length was not there
5991 		 * in earlier releases and some buggy
5992 		 * TLI apps (e.g Sybase) got away with not feeding
5993 		 * in sin_zero part of address.
5994 		 * We allow that bug to keep those buggy apps humming.
5995 		 * Test suites require the check on DEST_length.
5996 		 * We construct a new mblk with valid DEST_length
5997 		 * free the original so the rest of the code does
5998 		 * not have to keep track of this special shorter
5999 		 * length address case.
6000 		 */
6001 		mblk_t *nmp;
6002 		struct T_conn_req *ntcr;
6003 		sin_t *nsin;
6004 
6005 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6006 		    tcr->OPT_length, BPRI_HI);
6007 		if (nmp == NULL) {
6008 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6009 			return;
6010 		}
6011 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6012 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6013 		ntcr->PRIM_type = T_CONN_REQ;
6014 		ntcr->DEST_length = sizeof (sin_t);
6015 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6016 
6017 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6018 		*nsin = sin_null;
6019 		/* Get pointer to shorter address to copy from original mp */
6020 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6021 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6022 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6023 			freemsg(nmp);
6024 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6025 			return;
6026 		}
6027 		nsin->sin_family = sin->sin_family;
6028 		nsin->sin_port = sin->sin_port;
6029 		nsin->sin_addr = sin->sin_addr;
6030 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6031 		nmp->b_wptr = (uchar_t *)&nsin[1];
6032 		if (tcr->OPT_length != 0) {
6033 			ntcr->OPT_length = tcr->OPT_length;
6034 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6035 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6036 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6037 			    tcr->OPT_length);
6038 			nmp->b_wptr += tcr->OPT_length;
6039 		}
6040 		freemsg(mp);	/* original mp freed */
6041 		mp = nmp;	/* re-initialize original variables */
6042 		tcr = ntcr;
6043 	}
6044 	/* FALLTHRU */
6045 
6046 	case sizeof (sin_t):
6047 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6048 		    sizeof (sin_t));
6049 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6050 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6051 			return;
6052 		}
6053 		if (tcp->tcp_family != AF_INET ||
6054 		    sin->sin_family != AF_INET) {
6055 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6056 			return;
6057 		}
6058 		if (sin->sin_port == 0) {
6059 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6060 			return;
6061 		}
6062 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6063 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6064 			return;
6065 		}
6066 
6067 		break;
6068 
6069 	case sizeof (sin6_t):
6070 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6071 		    sizeof (sin6_t));
6072 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6073 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6074 			return;
6075 		}
6076 		if (tcp->tcp_family != AF_INET6 ||
6077 		    sin6->sin6_family != AF_INET6) {
6078 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6079 			return;
6080 		}
6081 		if (sin6->sin6_port == 0) {
6082 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6083 			return;
6084 		}
6085 		break;
6086 	}
6087 	/*
6088 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6089 	 * should key on their sequence number and cut them loose.
6090 	 */
6091 
6092 	/*
6093 	 * If options passed in, feed it for verification and handling
6094 	 */
6095 	if (tcr->OPT_length != 0) {
6096 		mblk_t	*ok_mp;
6097 		mblk_t	*discon_mp;
6098 		mblk_t  *conn_opts_mp;
6099 		int t_error, sys_error, do_disconnect;
6100 
6101 		conn_opts_mp = NULL;
6102 
6103 		if (tcp_conprim_opt_process(tcp, mp,
6104 			&do_disconnect, &t_error, &sys_error) < 0) {
6105 			if (do_disconnect) {
6106 				ASSERT(t_error == 0 && sys_error == 0);
6107 				discon_mp = mi_tpi_discon_ind(NULL,
6108 				    ECONNREFUSED, 0);
6109 				if (!discon_mp) {
6110 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6111 					    TSYSERR, ENOMEM);
6112 					return;
6113 				}
6114 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6115 				if (!ok_mp) {
6116 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6117 					    TSYSERR, ENOMEM);
6118 					return;
6119 				}
6120 				qreply(q, ok_mp);
6121 				qreply(q, discon_mp); /* no flush! */
6122 			} else {
6123 				ASSERT(t_error != 0);
6124 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6125 				    sys_error);
6126 			}
6127 			return;
6128 		}
6129 		/*
6130 		 * Success in setting options, the mp option buffer represented
6131 		 * by OPT_length/offset has been potentially modified and
6132 		 * contains results of option processing. We copy it in
6133 		 * another mp to save it for potentially influencing returning
6134 		 * it in T_CONN_CONN.
6135 		 */
6136 		if (tcr->OPT_length != 0) { /* there are resulting options */
6137 			conn_opts_mp = copyb(mp);
6138 			if (!conn_opts_mp) {
6139 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6140 				    TSYSERR, ENOMEM);
6141 				return;
6142 			}
6143 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6144 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6145 			/*
6146 			 * Note:
6147 			 * These resulting option negotiation can include any
6148 			 * end-to-end negotiation options but there no such
6149 			 * thing (yet?) in our TCP/IP.
6150 			 */
6151 		}
6152 	}
6153 
6154 	/*
6155 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6156 	 * make sure that the template IP header in the tcp structure is an
6157 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6158 	 * need to this before we call tcp_bindi() so that the port lookup
6159 	 * code will look for ports in the correct port space (IPv4 and
6160 	 * IPv6 have separate port spaces).
6161 	 */
6162 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6163 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6164 		int err = 0;
6165 
6166 		err = tcp_header_init_ipv4(tcp);
6167 		if (err != 0) {
6168 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6169 			goto connect_failed;
6170 		}
6171 		if (tcp->tcp_lport != 0)
6172 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6173 	}
6174 
6175 	switch (tcp->tcp_state) {
6176 	case TCPS_IDLE:
6177 		/*
6178 		 * We support quick connect, refer to comments in
6179 		 * tcp_connect_*()
6180 		 */
6181 		/* FALLTHRU */
6182 	case TCPS_BOUND:
6183 	case TCPS_LISTEN:
6184 		if (tcp->tcp_family == AF_INET6) {
6185 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6186 				tcp_connect_ipv6(tcp, mp,
6187 				    &sin6->sin6_addr,
6188 				    sin6->sin6_port, sin6->sin6_flowinfo,
6189 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6190 				return;
6191 			}
6192 			/*
6193 			 * Destination adress is mapped IPv6 address.
6194 			 * Source bound address should be unspecified or
6195 			 * IPv6 mapped address as well.
6196 			 */
6197 			if (!IN6_IS_ADDR_UNSPECIFIED(
6198 			    &tcp->tcp_bound_source_v6) &&
6199 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6200 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6201 				    EADDRNOTAVAIL);
6202 				break;
6203 			}
6204 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6205 			dstport = sin6->sin6_port;
6206 			srcid = sin6->__sin6_src_id;
6207 		} else {
6208 			dstaddrp = &sin->sin_addr.s_addr;
6209 			dstport = sin->sin_port;
6210 			srcid = 0;
6211 		}
6212 
6213 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6214 		return;
6215 	default:
6216 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6217 		break;
6218 	}
6219 	/*
6220 	 * Note: Code below is the "failure" case
6221 	 */
6222 	/* return error ack and blow away saved option results if any */
6223 connect_failed:
6224 	if (mp != NULL)
6225 		putnext(tcp->tcp_rq, mp);
6226 	else {
6227 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6228 		    TSYSERR, ENOMEM);
6229 	}
6230 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6231 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6232 }
6233 
6234 /*
6235  * Handle connect to IPv4 destinations, including connections for AF_INET6
6236  * sockets connecting to IPv4 mapped IPv6 destinations.
6237  */
6238 static void
6239 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6240     uint_t srcid)
6241 {
6242 	tcph_t	*tcph;
6243 	mblk_t	*mp1;
6244 	ipaddr_t dstaddr = *dstaddrp;
6245 	int32_t	oldstate;
6246 	uint16_t lport;
6247 
6248 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6249 
6250 	/* Check for attempt to connect to INADDR_ANY */
6251 	if (dstaddr == INADDR_ANY)  {
6252 		/*
6253 		 * SunOS 4.x and 4.3 BSD allow an application
6254 		 * to connect a TCP socket to INADDR_ANY.
6255 		 * When they do this, the kernel picks the
6256 		 * address of one interface and uses it
6257 		 * instead.  The kernel usually ends up
6258 		 * picking the address of the loopback
6259 		 * interface.  This is an undocumented feature.
6260 		 * However, we provide the same thing here
6261 		 * in order to have source and binary
6262 		 * compatibility with SunOS 4.x.
6263 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6264 		 * generate the T_CONN_CON.
6265 		 */
6266 		dstaddr = htonl(INADDR_LOOPBACK);
6267 		*dstaddrp = dstaddr;
6268 	}
6269 
6270 	/* Handle __sin6_src_id if socket not bound to an IP address */
6271 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6272 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6273 		    tcp->tcp_connp->conn_zoneid);
6274 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6275 		    tcp->tcp_ipha->ipha_src);
6276 	}
6277 
6278 	/*
6279 	 * Don't let an endpoint connect to itself.  Note that
6280 	 * the test here does not catch the case where the
6281 	 * source IP addr was left unspecified by the user. In
6282 	 * this case, the source addr is set in tcp_adapt_ire()
6283 	 * using the reply to the T_BIND message that we send
6284 	 * down to IP here and the check is repeated in tcp_rput_other.
6285 	 */
6286 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6287 	    dstport == tcp->tcp_lport) {
6288 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6289 		goto failed;
6290 	}
6291 
6292 	tcp->tcp_ipha->ipha_dst = dstaddr;
6293 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6294 
6295 	/*
6296 	 * Massage a source route if any putting the first hop
6297 	 * in iph_dst. Compute a starting value for the checksum which
6298 	 * takes into account that the original iph_dst should be
6299 	 * included in the checksum but that ip will include the
6300 	 * first hop in the source route in the tcp checksum.
6301 	 */
6302 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6303 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6304 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6305 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6306 	if ((int)tcp->tcp_sum < 0)
6307 		tcp->tcp_sum--;
6308 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6309 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6310 	    (tcp->tcp_sum >> 16));
6311 	tcph = tcp->tcp_tcph;
6312 	*(uint16_t *)tcph->th_fport = dstport;
6313 	tcp->tcp_fport = dstport;
6314 
6315 	oldstate = tcp->tcp_state;
6316 	/*
6317 	 * At this point the remote destination address and remote port fields
6318 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6319 	 * have to see which state tcp was in so we can take apropriate action.
6320 	 */
6321 	if (oldstate == TCPS_IDLE) {
6322 		/*
6323 		 * We support a quick connect capability here, allowing
6324 		 * clients to transition directly from IDLE to SYN_SENT
6325 		 * tcp_bindi will pick an unused port, insert the connection
6326 		 * in the bind hash and transition to BOUND state.
6327 		 */
6328 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6329 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6330 		    B_FALSE, B_FALSE);
6331 		if (lport == 0) {
6332 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6333 			goto failed;
6334 		}
6335 	}
6336 	tcp->tcp_state = TCPS_SYN_SENT;
6337 
6338 	/*
6339 	 * TODO: allow data with connect requests
6340 	 * by unlinking M_DATA trailers here and
6341 	 * linking them in behind the T_OK_ACK mblk.
6342 	 * The tcp_rput() bind ack handler would then
6343 	 * feed them to tcp_wput_data() rather than call
6344 	 * tcp_timer().
6345 	 */
6346 	mp = mi_tpi_ok_ack_alloc(mp);
6347 	if (!mp) {
6348 		tcp->tcp_state = oldstate;
6349 		goto failed;
6350 	}
6351 	if (tcp->tcp_family == AF_INET) {
6352 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6353 		    sizeof (ipa_conn_t));
6354 	} else {
6355 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6356 		    sizeof (ipa6_conn_t));
6357 	}
6358 	if (mp1) {
6359 		/* Hang onto the T_OK_ACK for later. */
6360 		linkb(mp1, mp);
6361 		mblk_setcred(mp1, tcp->tcp_cred);
6362 		if (tcp->tcp_family == AF_INET)
6363 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6364 		else {
6365 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6366 			    &tcp->tcp_sticky_ipp);
6367 		}
6368 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6369 		tcp->tcp_active_open = 1;
6370 		/*
6371 		 * If the bind cannot complete immediately
6372 		 * IP will arrange to call tcp_rput_other
6373 		 * when the bind completes.
6374 		 */
6375 		if (mp1 != NULL)
6376 			tcp_rput_other(tcp, mp1);
6377 		return;
6378 	}
6379 	/* Error case */
6380 	tcp->tcp_state = oldstate;
6381 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6382 
6383 failed:
6384 	/* return error ack and blow away saved option results if any */
6385 	if (mp != NULL)
6386 		putnext(tcp->tcp_rq, mp);
6387 	else {
6388 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6389 		    TSYSERR, ENOMEM);
6390 	}
6391 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6392 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6393 
6394 }
6395 
6396 /*
6397  * Handle connect to IPv6 destinations.
6398  */
6399 static void
6400 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6401     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6402 {
6403 	tcph_t	*tcph;
6404 	mblk_t	*mp1;
6405 	ip6_rthdr_t *rth;
6406 	int32_t  oldstate;
6407 	uint16_t lport;
6408 
6409 	ASSERT(tcp->tcp_family == AF_INET6);
6410 
6411 	/*
6412 	 * If we're here, it means that the destination address is a native
6413 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6414 	 * reason why it might not be IPv6 is if the socket was bound to an
6415 	 * IPv4-mapped IPv6 address.
6416 	 */
6417 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6418 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6419 		goto failed;
6420 	}
6421 
6422 	/*
6423 	 * Interpret a zero destination to mean loopback.
6424 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6425 	 * generate the T_CONN_CON.
6426 	 */
6427 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6428 		*dstaddrp = ipv6_loopback;
6429 	}
6430 
6431 	/* Handle __sin6_src_id if socket not bound to an IP address */
6432 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6433 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6434 		    tcp->tcp_connp->conn_zoneid);
6435 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6436 	}
6437 
6438 	/*
6439 	 * Take care of the scope_id now and add ip6i_t
6440 	 * if ip6i_t is not already allocated through TCP
6441 	 * sticky options. At this point tcp_ip6h does not
6442 	 * have dst info, thus use dstaddrp.
6443 	 */
6444 	if (scope_id != 0 &&
6445 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6446 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6447 		ip6i_t  *ip6i;
6448 
6449 		ipp->ipp_ifindex = scope_id;
6450 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6451 
6452 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6453 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6454 			/* Already allocated */
6455 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6456 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6457 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6458 		} else {
6459 			int reterr;
6460 
6461 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6462 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6463 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6464 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6465 			if (reterr != 0)
6466 				goto failed;
6467 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6468 		}
6469 	}
6470 
6471 	/*
6472 	 * Don't let an endpoint connect to itself.  Note that
6473 	 * the test here does not catch the case where the
6474 	 * source IP addr was left unspecified by the user. In
6475 	 * this case, the source addr is set in tcp_adapt_ire()
6476 	 * using the reply to the T_BIND message that we send
6477 	 * down to IP here and the check is repeated in tcp_rput_other.
6478 	 */
6479 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6480 	    (dstport == tcp->tcp_lport)) {
6481 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6482 		goto failed;
6483 	}
6484 
6485 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6486 	tcp->tcp_remote_v6 = *dstaddrp;
6487 	tcp->tcp_ip6h->ip6_vcf =
6488 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6489 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6490 
6491 
6492 	/*
6493 	 * Massage a routing header (if present) putting the first hop
6494 	 * in ip6_dst. Compute a starting value for the checksum which
6495 	 * takes into account that the original ip6_dst should be
6496 	 * included in the checksum but that ip will include the
6497 	 * first hop in the source route in the tcp checksum.
6498 	 */
6499 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6500 	if (rth != NULL) {
6501 
6502 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6503 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6504 		    (tcp->tcp_sum >> 16));
6505 	} else {
6506 		tcp->tcp_sum = 0;
6507 	}
6508 
6509 	tcph = tcp->tcp_tcph;
6510 	*(uint16_t *)tcph->th_fport = dstport;
6511 	tcp->tcp_fport = dstport;
6512 
6513 	oldstate = tcp->tcp_state;
6514 	/*
6515 	 * At this point the remote destination address and remote port fields
6516 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6517 	 * have to see which state tcp was in so we can take apropriate action.
6518 	 */
6519 	if (oldstate == TCPS_IDLE) {
6520 		/*
6521 		 * We support a quick connect capability here, allowing
6522 		 * clients to transition directly from IDLE to SYN_SENT
6523 		 * tcp_bindi will pick an unused port, insert the connection
6524 		 * in the bind hash and transition to BOUND state.
6525 		 */
6526 		lport = tcp_update_next_port(tcp_next_port_to_try, tcp, B_TRUE);
6527 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6528 		    B_FALSE, B_FALSE);
6529 		if (lport == 0) {
6530 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6531 			goto failed;
6532 		}
6533 	}
6534 	tcp->tcp_state = TCPS_SYN_SENT;
6535 	/*
6536 	 * TODO: allow data with connect requests
6537 	 * by unlinking M_DATA trailers here and
6538 	 * linking them in behind the T_OK_ACK mblk.
6539 	 * The tcp_rput() bind ack handler would then
6540 	 * feed them to tcp_wput_data() rather than call
6541 	 * tcp_timer().
6542 	 */
6543 	mp = mi_tpi_ok_ack_alloc(mp);
6544 	if (!mp) {
6545 		tcp->tcp_state = oldstate;
6546 		goto failed;
6547 	}
6548 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6549 	if (mp1) {
6550 		/* Hang onto the T_OK_ACK for later. */
6551 		linkb(mp1, mp);
6552 		mblk_setcred(mp1, tcp->tcp_cred);
6553 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6554 		    &tcp->tcp_sticky_ipp);
6555 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6556 		tcp->tcp_active_open = 1;
6557 		/* ip_bind_v6() may return ACK or ERROR */
6558 		if (mp1 != NULL)
6559 			tcp_rput_other(tcp, mp1);
6560 		return;
6561 	}
6562 	/* Error case */
6563 	tcp->tcp_state = oldstate;
6564 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6565 
6566 failed:
6567 	/* return error ack and blow away saved option results if any */
6568 	if (mp != NULL)
6569 		putnext(tcp->tcp_rq, mp);
6570 	else {
6571 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6572 		    TSYSERR, ENOMEM);
6573 	}
6574 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6575 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6576 }
6577 
6578 /*
6579  * We need a stream q for detached closing tcp connections
6580  * to use.  Our client hereby indicates that this q is the
6581  * one to use.
6582  */
6583 static void
6584 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6585 {
6586 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6587 	queue_t	*q = tcp->tcp_wq;
6588 
6589 	mp->b_datap->db_type = M_IOCACK;
6590 	iocp->ioc_count = 0;
6591 	mutex_enter(&tcp_g_q_lock);
6592 	if (tcp_g_q != NULL) {
6593 		mutex_exit(&tcp_g_q_lock);
6594 		iocp->ioc_error = EALREADY;
6595 	} else {
6596 		mblk_t *mp1;
6597 
6598 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6599 		if (mp1 == NULL) {
6600 			mutex_exit(&tcp_g_q_lock);
6601 			iocp->ioc_error = ENOMEM;
6602 		} else {
6603 			tcp_g_q = tcp->tcp_rq;
6604 			mutex_exit(&tcp_g_q_lock);
6605 			iocp->ioc_error = 0;
6606 			iocp->ioc_rval = 0;
6607 			/*
6608 			 * We are passing tcp_sticky_ipp as NULL
6609 			 * as it is not useful for tcp_default queue
6610 			 */
6611 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6612 			if (mp1 != NULL)
6613 				tcp_rput_other(tcp, mp1);
6614 		}
6615 	}
6616 	qreply(q, mp);
6617 }
6618 
6619 /*
6620  * Our client hereby directs us to reject the connection request
6621  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6622  * of sending the appropriate RST, not an ICMP error.
6623  */
6624 static void
6625 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6626 {
6627 	tcp_t	*ltcp = NULL;
6628 	t_scalar_t seqnum;
6629 	conn_t	*connp;
6630 
6631 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6632 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6633 		tcp_err_ack(tcp, mp, TPROTO, 0);
6634 		return;
6635 	}
6636 
6637 	/*
6638 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6639 	 * when the stream is in BOUND state. Do not send a reset,
6640 	 * since the destination IP address is not valid, and it can
6641 	 * be the initialized value of all zeros (broadcast address).
6642 	 *
6643 	 * If TCP has sent down a bind request to IP and has not
6644 	 * received the reply, reject the request.  Otherwise, TCP
6645 	 * will be confused.
6646 	 */
6647 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6648 		if (tcp->tcp_debug) {
6649 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6650 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6651 		}
6652 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6653 		return;
6654 	}
6655 
6656 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6657 
6658 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6659 
6660 		/*
6661 		 * According to TPI, for non-listeners, ignore seqnum
6662 		 * and disconnect.
6663 		 * Following interpretation of -1 seqnum is historical
6664 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6665 		 * a valid seqnum should not be -1).
6666 		 *
6667 		 *	-1 means disconnect everything
6668 		 *	regardless even on a listener.
6669 		 */
6670 
6671 		int old_state = tcp->tcp_state;
6672 
6673 		/*
6674 		 * The connection can't be on the tcp_time_wait_head list
6675 		 * since it is not detached.
6676 		 */
6677 		ASSERT(tcp->tcp_time_wait_next == NULL);
6678 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6679 		ASSERT(tcp->tcp_time_wait_expire == 0);
6680 		ltcp = NULL;
6681 		/*
6682 		 * If it used to be a listener, check to make sure no one else
6683 		 * has taken the port before switching back to LISTEN state.
6684 		 */
6685 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6686 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6687 			    tcp->tcp_ipha->ipha_src,
6688 			    tcp->tcp_connp->conn_zoneid);
6689 			if (connp != NULL)
6690 				ltcp = connp->conn_tcp;
6691 		} else {
6692 			/* Allow tcp_bound_if listeners? */
6693 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6694 			    &tcp->tcp_ip6h->ip6_src, 0,
6695 			    tcp->tcp_connp->conn_zoneid);
6696 			if (connp != NULL)
6697 				ltcp = connp->conn_tcp;
6698 		}
6699 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6700 			tcp->tcp_state = TCPS_LISTEN;
6701 		} else if (old_state > TCPS_BOUND) {
6702 			tcp->tcp_conn_req_max = 0;
6703 			tcp->tcp_state = TCPS_BOUND;
6704 		}
6705 		if (ltcp != NULL)
6706 			CONN_DEC_REF(ltcp->tcp_connp);
6707 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6708 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6709 		} else if (old_state == TCPS_ESTABLISHED ||
6710 		    old_state == TCPS_CLOSE_WAIT) {
6711 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6712 		}
6713 
6714 		if (tcp->tcp_fused)
6715 			tcp_unfuse(tcp);
6716 
6717 		mutex_enter(&tcp->tcp_eager_lock);
6718 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6719 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6720 			tcp_eager_cleanup(tcp, 0);
6721 		}
6722 		mutex_exit(&tcp->tcp_eager_lock);
6723 
6724 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6725 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6726 
6727 		tcp_reinit(tcp);
6728 
6729 		if (old_state >= TCPS_ESTABLISHED) {
6730 			/* Send M_FLUSH according to TPI */
6731 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6732 		}
6733 		mp = mi_tpi_ok_ack_alloc(mp);
6734 		if (mp)
6735 			putnext(tcp->tcp_rq, mp);
6736 		return;
6737 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6738 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6739 		return;
6740 	}
6741 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6742 		/* Send M_FLUSH according to TPI */
6743 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6744 	}
6745 	mp = mi_tpi_ok_ack_alloc(mp);
6746 	if (mp)
6747 		putnext(tcp->tcp_rq, mp);
6748 }
6749 
6750 /*
6751  * Diagnostic routine used to return a string associated with the tcp state.
6752  * Note that if the caller does not supply a buffer, it will use an internal
6753  * static string.  This means that if multiple threads call this function at
6754  * the same time, output can be corrupted...  Note also that this function
6755  * does not check the size of the supplied buffer.  The caller has to make
6756  * sure that it is big enough.
6757  */
6758 static char *
6759 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6760 {
6761 	char		buf1[30];
6762 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6763 	char		*buf;
6764 	char		*cp;
6765 	in6_addr_t	local, remote;
6766 	char		local_addrbuf[INET6_ADDRSTRLEN];
6767 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6768 
6769 	if (sup_buf != NULL)
6770 		buf = sup_buf;
6771 	else
6772 		buf = priv_buf;
6773 
6774 	if (tcp == NULL)
6775 		return ("NULL_TCP");
6776 	switch (tcp->tcp_state) {
6777 	case TCPS_CLOSED:
6778 		cp = "TCP_CLOSED";
6779 		break;
6780 	case TCPS_IDLE:
6781 		cp = "TCP_IDLE";
6782 		break;
6783 	case TCPS_BOUND:
6784 		cp = "TCP_BOUND";
6785 		break;
6786 	case TCPS_LISTEN:
6787 		cp = "TCP_LISTEN";
6788 		break;
6789 	case TCPS_SYN_SENT:
6790 		cp = "TCP_SYN_SENT";
6791 		break;
6792 	case TCPS_SYN_RCVD:
6793 		cp = "TCP_SYN_RCVD";
6794 		break;
6795 	case TCPS_ESTABLISHED:
6796 		cp = "TCP_ESTABLISHED";
6797 		break;
6798 	case TCPS_CLOSE_WAIT:
6799 		cp = "TCP_CLOSE_WAIT";
6800 		break;
6801 	case TCPS_FIN_WAIT_1:
6802 		cp = "TCP_FIN_WAIT_1";
6803 		break;
6804 	case TCPS_CLOSING:
6805 		cp = "TCP_CLOSING";
6806 		break;
6807 	case TCPS_LAST_ACK:
6808 		cp = "TCP_LAST_ACK";
6809 		break;
6810 	case TCPS_FIN_WAIT_2:
6811 		cp = "TCP_FIN_WAIT_2";
6812 		break;
6813 	case TCPS_TIME_WAIT:
6814 		cp = "TCP_TIME_WAIT";
6815 		break;
6816 	default:
6817 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6818 		cp = buf1;
6819 		break;
6820 	}
6821 	switch (format) {
6822 	case DISP_ADDR_AND_PORT:
6823 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6824 			/*
6825 			 * Note that we use the remote address in the tcp_b
6826 			 * structure.  This means that it will print out
6827 			 * the real destination address, not the next hop's
6828 			 * address if source routing is used.
6829 			 */
6830 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6831 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6832 
6833 		} else {
6834 			local = tcp->tcp_ip_src_v6;
6835 			remote = tcp->tcp_remote_v6;
6836 		}
6837 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6838 		    sizeof (local_addrbuf));
6839 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6840 		    sizeof (remote_addrbuf));
6841 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6842 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6843 		    ntohs(tcp->tcp_fport), cp);
6844 		break;
6845 	case DISP_PORT_ONLY:
6846 	default:
6847 		(void) mi_sprintf(buf, "[%u, %u] %s",
6848 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6849 		break;
6850 	}
6851 
6852 	return (buf);
6853 }
6854 
6855 /*
6856  * Called via squeue to get on to eager's perimeter to send a
6857  * TH_RST. The listener wants the eager to disappear either
6858  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6859  * being called.
6860  */
6861 /* ARGSUSED */
6862 void
6863 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6864 {
6865 	conn_t	*econnp = (conn_t *)arg;
6866 	tcp_t	*eager = econnp->conn_tcp;
6867 	tcp_t	*listener = eager->tcp_listener;
6868 
6869 	/*
6870 	 * We could be called because listener is closing. Since
6871 	 * the eager is using listener's queue's, its not safe.
6872 	 * Better use the default queue just to send the TH_RST
6873 	 * out.
6874 	 */
6875 	eager->tcp_rq = tcp_g_q;
6876 	eager->tcp_wq = WR(tcp_g_q);
6877 
6878 	if (eager->tcp_state > TCPS_LISTEN) {
6879 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6880 		    eager, eager->tcp_snxt, 0, TH_RST);
6881 	}
6882 
6883 	/* We are here because listener wants this eager gone */
6884 	if (listener != NULL) {
6885 		mutex_enter(&listener->tcp_eager_lock);
6886 		tcp_eager_unlink(eager);
6887 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6888 			/*
6889 			 * The eager has sent a conn_ind up to the
6890 			 * listener but listener decides to close
6891 			 * instead. We need to drop the extra ref
6892 			 * placed on eager in tcp_rput_data() before
6893 			 * sending the conn_ind to listener.
6894 			 */
6895 			CONN_DEC_REF(econnp);
6896 		}
6897 		mutex_exit(&listener->tcp_eager_lock);
6898 		CONN_DEC_REF(listener->tcp_connp);
6899 	}
6900 
6901 	if (eager->tcp_state > TCPS_BOUND)
6902 		tcp_close_detached(eager);
6903 }
6904 
6905 /*
6906  * Reset any eager connection hanging off this listener marked
6907  * with 'seqnum' and then reclaim it's resources.
6908  */
6909 static boolean_t
6910 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6911 {
6912 	tcp_t	*eager;
6913 	mblk_t 	*mp;
6914 
6915 	TCP_STAT(tcp_eager_blowoff_calls);
6916 	eager = listener;
6917 	mutex_enter(&listener->tcp_eager_lock);
6918 	do {
6919 		eager = eager->tcp_eager_next_q;
6920 		if (eager == NULL) {
6921 			mutex_exit(&listener->tcp_eager_lock);
6922 			return (B_FALSE);
6923 		}
6924 	} while (eager->tcp_conn_req_seqnum != seqnum);
6925 	CONN_INC_REF(eager->tcp_connp);
6926 	mutex_exit(&listener->tcp_eager_lock);
6927 	mp = &eager->tcp_closemp;
6928 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6929 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6930 	return (B_TRUE);
6931 }
6932 
6933 /*
6934  * Reset any eager connection hanging off this listener
6935  * and then reclaim it's resources.
6936  */
6937 static void
6938 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6939 {
6940 	tcp_t	*eager;
6941 	mblk_t	*mp;
6942 
6943 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6944 
6945 	if (!q0_only) {
6946 		/* First cleanup q */
6947 		TCP_STAT(tcp_eager_blowoff_q);
6948 		eager = listener->tcp_eager_next_q;
6949 		while (eager != NULL) {
6950 			CONN_INC_REF(eager->tcp_connp);
6951 			mp = &eager->tcp_closemp;
6952 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6953 			    tcp_eager_kill, eager->tcp_connp,
6954 			    SQTAG_TCP_EAGER_CLEANUP);
6955 			eager = eager->tcp_eager_next_q;
6956 		}
6957 	}
6958 	/* Then cleanup q0 */
6959 	TCP_STAT(tcp_eager_blowoff_q0);
6960 	eager = listener->tcp_eager_next_q0;
6961 	while (eager != listener) {
6962 		CONN_INC_REF(eager->tcp_connp);
6963 		mp = &eager->tcp_closemp;
6964 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6965 		    tcp_eager_kill, eager->tcp_connp,
6966 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6967 		eager = eager->tcp_eager_next_q0;
6968 	}
6969 }
6970 
6971 /*
6972  * If we are an eager connection hanging off a listener that hasn't
6973  * formally accepted the connection yet, get off his list and blow off
6974  * any data that we have accumulated.
6975  */
6976 static void
6977 tcp_eager_unlink(tcp_t *tcp)
6978 {
6979 	tcp_t	*listener = tcp->tcp_listener;
6980 
6981 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6982 	ASSERT(listener != NULL);
6983 	if (tcp->tcp_eager_next_q0 != NULL) {
6984 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6985 
6986 		/* Remove the eager tcp from q0 */
6987 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6988 		    tcp->tcp_eager_prev_q0;
6989 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6990 		    tcp->tcp_eager_next_q0;
6991 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6992 		listener->tcp_conn_req_cnt_q0--;
6993 
6994 		tcp->tcp_eager_next_q0 = NULL;
6995 		tcp->tcp_eager_prev_q0 = NULL;
6996 
6997 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6998 			/* we have timed out before */
6999 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7000 			listener->tcp_syn_rcvd_timeout--;
7001 		}
7002 	} else {
7003 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7004 		tcp_t	*prev = NULL;
7005 
7006 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7007 			if (tcpp[0] == tcp) {
7008 				if (listener->tcp_eager_last_q == tcp) {
7009 					/*
7010 					 * If we are unlinking the last
7011 					 * element on the list, adjust
7012 					 * tail pointer. Set tail pointer
7013 					 * to nil when list is empty.
7014 					 */
7015 					ASSERT(tcp->tcp_eager_next_q == NULL);
7016 					if (listener->tcp_eager_last_q ==
7017 					    listener->tcp_eager_next_q) {
7018 						listener->tcp_eager_last_q =
7019 						NULL;
7020 					} else {
7021 						/*
7022 						 * We won't get here if there
7023 						 * is only one eager in the
7024 						 * list.
7025 						 */
7026 						ASSERT(prev != NULL);
7027 						listener->tcp_eager_last_q =
7028 						    prev;
7029 					}
7030 				}
7031 				tcpp[0] = tcp->tcp_eager_next_q;
7032 				tcp->tcp_eager_next_q = NULL;
7033 				tcp->tcp_eager_last_q = NULL;
7034 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7035 				listener->tcp_conn_req_cnt_q--;
7036 				break;
7037 			}
7038 			prev = tcpp[0];
7039 		}
7040 	}
7041 	tcp->tcp_listener = NULL;
7042 }
7043 
7044 /* Shorthand to generate and send TPI error acks to our client */
7045 static void
7046 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7047 {
7048 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7049 		putnext(tcp->tcp_rq, mp);
7050 }
7051 
7052 /* Shorthand to generate and send TPI error acks to our client */
7053 static void
7054 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7055     int t_error, int sys_error)
7056 {
7057 	struct T_error_ack	*teackp;
7058 
7059 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7060 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7061 		teackp = (struct T_error_ack *)mp->b_rptr;
7062 		teackp->ERROR_prim = primitive;
7063 		teackp->TLI_error = t_error;
7064 		teackp->UNIX_error = sys_error;
7065 		putnext(tcp->tcp_rq, mp);
7066 	}
7067 }
7068 
7069 /*
7070  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7071  * but instead the code relies on:
7072  * - the fact that the address of the array and its size never changes
7073  * - the atomic assignment of the elements of the array
7074  */
7075 /* ARGSUSED */
7076 static int
7077 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7078 {
7079 	int i;
7080 
7081 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7082 		if (tcp_g_epriv_ports[i] != 0)
7083 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
7084 	}
7085 	return (0);
7086 }
7087 
7088 /*
7089  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7090  * threads from changing it at the same time.
7091  */
7092 /* ARGSUSED */
7093 static int
7094 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7095     cred_t *cr)
7096 {
7097 	long	new_value;
7098 	int	i;
7099 
7100 	/*
7101 	 * Fail the request if the new value does not lie within the
7102 	 * port number limits.
7103 	 */
7104 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7105 	    new_value <= 0 || new_value >= 65536) {
7106 		return (EINVAL);
7107 	}
7108 
7109 	mutex_enter(&tcp_epriv_port_lock);
7110 	/* Check if the value is already in the list */
7111 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7112 		if (new_value == tcp_g_epriv_ports[i]) {
7113 			mutex_exit(&tcp_epriv_port_lock);
7114 			return (EEXIST);
7115 		}
7116 	}
7117 	/* Find an empty slot */
7118 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7119 		if (tcp_g_epriv_ports[i] == 0)
7120 			break;
7121 	}
7122 	if (i == tcp_g_num_epriv_ports) {
7123 		mutex_exit(&tcp_epriv_port_lock);
7124 		return (EOVERFLOW);
7125 	}
7126 	/* Set the new value */
7127 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
7128 	mutex_exit(&tcp_epriv_port_lock);
7129 	return (0);
7130 }
7131 
7132 /*
7133  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7134  * threads from changing it at the same time.
7135  */
7136 /* ARGSUSED */
7137 static int
7138 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7139     cred_t *cr)
7140 {
7141 	long	new_value;
7142 	int	i;
7143 
7144 	/*
7145 	 * Fail the request if the new value does not lie within the
7146 	 * port number limits.
7147 	 */
7148 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7149 	    new_value >= 65536) {
7150 		return (EINVAL);
7151 	}
7152 
7153 	mutex_enter(&tcp_epriv_port_lock);
7154 	/* Check that the value is already in the list */
7155 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
7156 		if (tcp_g_epriv_ports[i] == new_value)
7157 			break;
7158 	}
7159 	if (i == tcp_g_num_epriv_ports) {
7160 		mutex_exit(&tcp_epriv_port_lock);
7161 		return (ESRCH);
7162 	}
7163 	/* Clear the value */
7164 	tcp_g_epriv_ports[i] = 0;
7165 	mutex_exit(&tcp_epriv_port_lock);
7166 	return (0);
7167 }
7168 
7169 /* Return the TPI/TLI equivalent of our current tcp_state */
7170 static int
7171 tcp_tpistate(tcp_t *tcp)
7172 {
7173 	switch (tcp->tcp_state) {
7174 	case TCPS_IDLE:
7175 		return (TS_UNBND);
7176 	case TCPS_LISTEN:
7177 		/*
7178 		 * Return whether there are outstanding T_CONN_IND waiting
7179 		 * for the matching T_CONN_RES. Therefore don't count q0.
7180 		 */
7181 		if (tcp->tcp_conn_req_cnt_q > 0)
7182 			return (TS_WRES_CIND);
7183 		else
7184 			return (TS_IDLE);
7185 	case TCPS_BOUND:
7186 		return (TS_IDLE);
7187 	case TCPS_SYN_SENT:
7188 		return (TS_WCON_CREQ);
7189 	case TCPS_SYN_RCVD:
7190 		/*
7191 		 * Note: assumption: this has to the active open SYN_RCVD.
7192 		 * The passive instance is detached in SYN_RCVD stage of
7193 		 * incoming connection processing so we cannot get request
7194 		 * for T_info_ack on it.
7195 		 */
7196 		return (TS_WACK_CRES);
7197 	case TCPS_ESTABLISHED:
7198 		return (TS_DATA_XFER);
7199 	case TCPS_CLOSE_WAIT:
7200 		return (TS_WREQ_ORDREL);
7201 	case TCPS_FIN_WAIT_1:
7202 		return (TS_WIND_ORDREL);
7203 	case TCPS_FIN_WAIT_2:
7204 		return (TS_WIND_ORDREL);
7205 
7206 	case TCPS_CLOSING:
7207 	case TCPS_LAST_ACK:
7208 	case TCPS_TIME_WAIT:
7209 	case TCPS_CLOSED:
7210 		/*
7211 		 * Following TS_WACK_DREQ7 is a rendition of "not
7212 		 * yet TS_IDLE" TPI state. There is no best match to any
7213 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7214 		 * choose a value chosen that will map to TLI/XTI level
7215 		 * state of TSTATECHNG (state is process of changing) which
7216 		 * captures what this dummy state represents.
7217 		 */
7218 		return (TS_WACK_DREQ7);
7219 	default:
7220 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7221 		    tcp->tcp_state, tcp_display(tcp, NULL,
7222 		    DISP_PORT_ONLY));
7223 		return (TS_UNBND);
7224 	}
7225 }
7226 
7227 static void
7228 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7229 {
7230 	if (tcp->tcp_family == AF_INET6)
7231 		*tia = tcp_g_t_info_ack_v6;
7232 	else
7233 		*tia = tcp_g_t_info_ack;
7234 	tia->CURRENT_state = tcp_tpistate(tcp);
7235 	tia->OPT_size = tcp_max_optsize;
7236 	if (tcp->tcp_mss == 0) {
7237 		/* Not yet set - tcp_open does not set mss */
7238 		if (tcp->tcp_ipversion == IPV4_VERSION)
7239 			tia->TIDU_size = tcp_mss_def_ipv4;
7240 		else
7241 			tia->TIDU_size = tcp_mss_def_ipv6;
7242 	} else {
7243 		tia->TIDU_size = tcp->tcp_mss;
7244 	}
7245 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7246 }
7247 
7248 /*
7249  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7250  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7251  * tcp_g_t_info_ack.  The current state of the stream is copied from
7252  * tcp_state.
7253  */
7254 static void
7255 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7256 {
7257 	t_uscalar_t		cap_bits1;
7258 	struct T_capability_ack	*tcap;
7259 
7260 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7261 		freemsg(mp);
7262 		return;
7263 	}
7264 
7265 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7266 
7267 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7268 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7269 	if (mp == NULL)
7270 		return;
7271 
7272 	tcap = (struct T_capability_ack *)mp->b_rptr;
7273 	tcap->CAP_bits1 = 0;
7274 
7275 	if (cap_bits1 & TC1_INFO) {
7276 		tcp_copy_info(&tcap->INFO_ack, tcp);
7277 		tcap->CAP_bits1 |= TC1_INFO;
7278 	}
7279 
7280 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7281 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7282 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7283 	}
7284 
7285 	putnext(tcp->tcp_rq, mp);
7286 }
7287 
7288 /*
7289  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7290  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7291  * The current state of the stream is copied from tcp_state.
7292  */
7293 static void
7294 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7295 {
7296 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7297 	    T_INFO_ACK);
7298 	if (!mp) {
7299 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7300 		return;
7301 	}
7302 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7303 	putnext(tcp->tcp_rq, mp);
7304 }
7305 
7306 /* Respond to the TPI addr request */
7307 static void
7308 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7309 {
7310 	sin_t	*sin;
7311 	mblk_t	*ackmp;
7312 	struct T_addr_ack *taa;
7313 
7314 	/* Make it large enough for worst case */
7315 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7316 	    2 * sizeof (sin6_t), 1);
7317 	if (ackmp == NULL) {
7318 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7319 		return;
7320 	}
7321 
7322 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7323 		tcp_addr_req_ipv6(tcp, ackmp);
7324 		return;
7325 	}
7326 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7327 
7328 	bzero(taa, sizeof (struct T_addr_ack));
7329 	ackmp->b_wptr = (uchar_t *)&taa[1];
7330 
7331 	taa->PRIM_type = T_ADDR_ACK;
7332 	ackmp->b_datap->db_type = M_PCPROTO;
7333 
7334 	/*
7335 	 * Note: Following code assumes 32 bit alignment of basic
7336 	 * data structures like sin_t and struct T_addr_ack.
7337 	 */
7338 	if (tcp->tcp_state >= TCPS_BOUND) {
7339 		/*
7340 		 * Fill in local address
7341 		 */
7342 		taa->LOCADDR_length = sizeof (sin_t);
7343 		taa->LOCADDR_offset = sizeof (*taa);
7344 
7345 		sin = (sin_t *)&taa[1];
7346 
7347 		/* Fill zeroes and then intialize non-zero fields */
7348 		*sin = sin_null;
7349 
7350 		sin->sin_family = AF_INET;
7351 
7352 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7353 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7354 
7355 		ackmp->b_wptr = (uchar_t *)&sin[1];
7356 
7357 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7358 			/*
7359 			 * Fill in Remote address
7360 			 */
7361 			taa->REMADDR_length = sizeof (sin_t);
7362 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7363 						taa->LOCADDR_length);
7364 
7365 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7366 			*sin = sin_null;
7367 			sin->sin_family = AF_INET;
7368 			sin->sin_addr.s_addr = tcp->tcp_remote;
7369 			sin->sin_port = tcp->tcp_fport;
7370 
7371 			ackmp->b_wptr = (uchar_t *)&sin[1];
7372 		}
7373 	}
7374 	putnext(tcp->tcp_rq, ackmp);
7375 }
7376 
7377 /* Assumes that tcp_addr_req gets enough space and alignment */
7378 static void
7379 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7380 {
7381 	sin6_t	*sin6;
7382 	struct T_addr_ack *taa;
7383 
7384 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7385 	ASSERT(OK_32PTR(ackmp->b_rptr));
7386 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7387 	    2 * sizeof (sin6_t));
7388 
7389 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7390 
7391 	bzero(taa, sizeof (struct T_addr_ack));
7392 	ackmp->b_wptr = (uchar_t *)&taa[1];
7393 
7394 	taa->PRIM_type = T_ADDR_ACK;
7395 	ackmp->b_datap->db_type = M_PCPROTO;
7396 
7397 	/*
7398 	 * Note: Following code assumes 32 bit alignment of basic
7399 	 * data structures like sin6_t and struct T_addr_ack.
7400 	 */
7401 	if (tcp->tcp_state >= TCPS_BOUND) {
7402 		/*
7403 		 * Fill in local address
7404 		 */
7405 		taa->LOCADDR_length = sizeof (sin6_t);
7406 		taa->LOCADDR_offset = sizeof (*taa);
7407 
7408 		sin6 = (sin6_t *)&taa[1];
7409 		*sin6 = sin6_null;
7410 
7411 		sin6->sin6_family = AF_INET6;
7412 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7413 		sin6->sin6_port = tcp->tcp_lport;
7414 
7415 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7416 
7417 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7418 			/*
7419 			 * Fill in Remote address
7420 			 */
7421 			taa->REMADDR_length = sizeof (sin6_t);
7422 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7423 						taa->LOCADDR_length);
7424 
7425 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7426 			*sin6 = sin6_null;
7427 			sin6->sin6_family = AF_INET6;
7428 			sin6->sin6_flowinfo =
7429 			    tcp->tcp_ip6h->ip6_vcf &
7430 			    ~IPV6_VERS_AND_FLOW_MASK;
7431 			sin6->sin6_addr = tcp->tcp_remote_v6;
7432 			sin6->sin6_port = tcp->tcp_fport;
7433 
7434 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7435 		}
7436 	}
7437 	putnext(tcp->tcp_rq, ackmp);
7438 }
7439 
7440 /*
7441  * Handle reinitialization of a tcp structure.
7442  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7443  */
7444 static void
7445 tcp_reinit(tcp_t *tcp)
7446 {
7447 	mblk_t	*mp;
7448 	int 	err;
7449 
7450 	TCP_STAT(tcp_reinit_calls);
7451 
7452 	/* tcp_reinit should never be called for detached tcp_t's */
7453 	ASSERT(tcp->tcp_listener == NULL);
7454 	ASSERT((tcp->tcp_family == AF_INET &&
7455 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7456 	    (tcp->tcp_family == AF_INET6 &&
7457 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7458 	    tcp->tcp_ipversion == IPV6_VERSION)));
7459 
7460 	/* Cancel outstanding timers */
7461 	tcp_timers_stop(tcp);
7462 
7463 	/*
7464 	 * Reset everything in the state vector, after updating global
7465 	 * MIB data from instance counters.
7466 	 */
7467 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7468 	tcp->tcp_ibsegs = 0;
7469 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7470 	tcp->tcp_obsegs = 0;
7471 
7472 	tcp_close_mpp(&tcp->tcp_xmit_head);
7473 	if (tcp->tcp_snd_zcopy_aware)
7474 		tcp_zcopy_notify(tcp);
7475 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7476 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7477 	if (tcp->tcp_flow_stopped &&
7478 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7479 		tcp_clrqfull(tcp);
7480 	}
7481 	tcp_close_mpp(&tcp->tcp_reass_head);
7482 	tcp->tcp_reass_tail = NULL;
7483 	if (tcp->tcp_rcv_list != NULL) {
7484 		/* Free b_next chain */
7485 		tcp_close_mpp(&tcp->tcp_rcv_list);
7486 		tcp->tcp_rcv_last_head = NULL;
7487 		tcp->tcp_rcv_last_tail = NULL;
7488 		tcp->tcp_rcv_cnt = 0;
7489 	}
7490 	tcp->tcp_rcv_last_tail = NULL;
7491 
7492 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7493 		freemsg(mp);
7494 		tcp->tcp_urp_mp = NULL;
7495 	}
7496 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7497 		freemsg(mp);
7498 		tcp->tcp_urp_mark_mp = NULL;
7499 	}
7500 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7501 		freeb(tcp->tcp_fused_sigurg_mp);
7502 		tcp->tcp_fused_sigurg_mp = NULL;
7503 	}
7504 
7505 	/*
7506 	 * Following is a union with two members which are
7507 	 * identical types and size so the following cleanup
7508 	 * is enough.
7509 	 */
7510 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7511 
7512 	CL_INET_DISCONNECT(tcp);
7513 
7514 	/*
7515 	 * The connection can't be on the tcp_time_wait_head list
7516 	 * since it is not detached.
7517 	 */
7518 	ASSERT(tcp->tcp_time_wait_next == NULL);
7519 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7520 	ASSERT(tcp->tcp_time_wait_expire == 0);
7521 
7522 	if (tcp->tcp_kssl_pending) {
7523 		tcp->tcp_kssl_pending = B_FALSE;
7524 
7525 		/* Don't reset if the initialized by bind. */
7526 		if (tcp->tcp_kssl_ent != NULL) {
7527 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7528 			    KSSL_NO_PROXY);
7529 		}
7530 	}
7531 	if (tcp->tcp_kssl_ctx != NULL) {
7532 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7533 		tcp->tcp_kssl_ctx = NULL;
7534 	}
7535 
7536 	/*
7537 	 * Reset/preserve other values
7538 	 */
7539 	tcp_reinit_values(tcp);
7540 	ipcl_hash_remove(tcp->tcp_connp);
7541 	conn_delete_ire(tcp->tcp_connp, NULL);
7542 
7543 	if (tcp->tcp_conn_req_max != 0) {
7544 		/*
7545 		 * This is the case when a TLI program uses the same
7546 		 * transport end point to accept a connection.  This
7547 		 * makes the TCP both a listener and acceptor.  When
7548 		 * this connection is closed, we need to set the state
7549 		 * back to TCPS_LISTEN.  Make sure that the eager list
7550 		 * is reinitialized.
7551 		 *
7552 		 * Note that this stream is still bound to the four
7553 		 * tuples of the previous connection in IP.  If a new
7554 		 * SYN with different foreign address comes in, IP will
7555 		 * not find it and will send it to the global queue.  In
7556 		 * the global queue, TCP will do a tcp_lookup_listener()
7557 		 * to find this stream.  This works because this stream
7558 		 * is only removed from connected hash.
7559 		 *
7560 		 */
7561 		tcp->tcp_state = TCPS_LISTEN;
7562 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7563 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7564 		if (tcp->tcp_family == AF_INET6) {
7565 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7566 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7567 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7568 		} else {
7569 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7570 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7571 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7572 		}
7573 	} else {
7574 		tcp->tcp_state = TCPS_BOUND;
7575 	}
7576 
7577 	/*
7578 	 * Initialize to default values
7579 	 * Can't fail since enough header template space already allocated
7580 	 * at open().
7581 	 */
7582 	err = tcp_init_values(tcp);
7583 	ASSERT(err == 0);
7584 	/* Restore state in tcp_tcph */
7585 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7586 	if (tcp->tcp_ipversion == IPV4_VERSION)
7587 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7588 	else
7589 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7590 	/*
7591 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7592 	 * since the lookup funcs can only lookup on tcp_t
7593 	 */
7594 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7595 
7596 	ASSERT(tcp->tcp_ptpbhn != NULL);
7597 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7598 	tcp->tcp_rwnd = tcp_recv_hiwat;
7599 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7600 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7601 }
7602 
7603 /*
7604  * Force values to zero that need be zero.
7605  * Do not touch values asociated with the BOUND or LISTEN state
7606  * since the connection will end up in that state after the reinit.
7607  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7608  * structure!
7609  */
7610 static void
7611 tcp_reinit_values(tcp)
7612 	tcp_t *tcp;
7613 {
7614 #ifndef	lint
7615 #define	DONTCARE(x)
7616 #define	PRESERVE(x)
7617 #else
7618 #define	DONTCARE(x)	((x) = (x))
7619 #define	PRESERVE(x)	((x) = (x))
7620 #endif	/* lint */
7621 
7622 	PRESERVE(tcp->tcp_bind_hash);
7623 	PRESERVE(tcp->tcp_ptpbhn);
7624 	PRESERVE(tcp->tcp_acceptor_hash);
7625 	PRESERVE(tcp->tcp_ptpahn);
7626 
7627 	/* Should be ASSERT NULL on these with new code! */
7628 	ASSERT(tcp->tcp_time_wait_next == NULL);
7629 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7630 	ASSERT(tcp->tcp_time_wait_expire == 0);
7631 	PRESERVE(tcp->tcp_state);
7632 	PRESERVE(tcp->tcp_rq);
7633 	PRESERVE(tcp->tcp_wq);
7634 
7635 	ASSERT(tcp->tcp_xmit_head == NULL);
7636 	ASSERT(tcp->tcp_xmit_last == NULL);
7637 	ASSERT(tcp->tcp_unsent == 0);
7638 	ASSERT(tcp->tcp_xmit_tail == NULL);
7639 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7640 
7641 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7642 	tcp->tcp_suna = 0;			/* Displayed in mib */
7643 	tcp->tcp_swnd = 0;
7644 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7645 
7646 	ASSERT(tcp->tcp_ibsegs == 0);
7647 	ASSERT(tcp->tcp_obsegs == 0);
7648 
7649 	if (tcp->tcp_iphc != NULL) {
7650 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7651 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7652 	}
7653 
7654 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7655 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7656 	DONTCARE(tcp->tcp_ipha);
7657 	DONTCARE(tcp->tcp_ip6h);
7658 	DONTCARE(tcp->tcp_ip_hdr_len);
7659 	DONTCARE(tcp->tcp_tcph);
7660 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7661 	tcp->tcp_valid_bits = 0;
7662 
7663 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7664 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7665 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7666 	tcp->tcp_last_rcv_lbolt = 0;
7667 
7668 	tcp->tcp_init_cwnd = 0;
7669 
7670 	tcp->tcp_urp_last_valid = 0;
7671 	tcp->tcp_hard_binding = 0;
7672 	tcp->tcp_hard_bound = 0;
7673 	PRESERVE(tcp->tcp_cred);
7674 	PRESERVE(tcp->tcp_cpid);
7675 	PRESERVE(tcp->tcp_exclbind);
7676 
7677 	tcp->tcp_fin_acked = 0;
7678 	tcp->tcp_fin_rcvd = 0;
7679 	tcp->tcp_fin_sent = 0;
7680 	tcp->tcp_ordrel_done = 0;
7681 
7682 	tcp->tcp_debug = 0;
7683 	tcp->tcp_dontroute = 0;
7684 	tcp->tcp_broadcast = 0;
7685 
7686 	tcp->tcp_useloopback = 0;
7687 	tcp->tcp_reuseaddr = 0;
7688 	tcp->tcp_oobinline = 0;
7689 	tcp->tcp_dgram_errind = 0;
7690 
7691 	tcp->tcp_detached = 0;
7692 	tcp->tcp_bind_pending = 0;
7693 	tcp->tcp_unbind_pending = 0;
7694 	tcp->tcp_deferred_clean_death = 0;
7695 
7696 	tcp->tcp_snd_ws_ok = B_FALSE;
7697 	tcp->tcp_snd_ts_ok = B_FALSE;
7698 	tcp->tcp_linger = 0;
7699 	tcp->tcp_ka_enabled = 0;
7700 	tcp->tcp_zero_win_probe = 0;
7701 
7702 	tcp->tcp_loopback = 0;
7703 	tcp->tcp_localnet = 0;
7704 	tcp->tcp_syn_defense = 0;
7705 	tcp->tcp_set_timer = 0;
7706 
7707 	tcp->tcp_active_open = 0;
7708 	ASSERT(tcp->tcp_timeout == B_FALSE);
7709 	tcp->tcp_rexmit = B_FALSE;
7710 	tcp->tcp_xmit_zc_clean = B_FALSE;
7711 
7712 	tcp->tcp_snd_sack_ok = B_FALSE;
7713 	PRESERVE(tcp->tcp_recvdstaddr);
7714 	tcp->tcp_hwcksum = B_FALSE;
7715 
7716 	tcp->tcp_ire_ill_check_done = B_FALSE;
7717 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7718 
7719 	tcp->tcp_mdt = B_FALSE;
7720 	tcp->tcp_mdt_hdr_head = 0;
7721 	tcp->tcp_mdt_hdr_tail = 0;
7722 
7723 	tcp->tcp_conn_def_q0 = 0;
7724 	tcp->tcp_ip_forward_progress = B_FALSE;
7725 	tcp->tcp_anon_priv_bind = 0;
7726 	tcp->tcp_ecn_ok = B_FALSE;
7727 
7728 	tcp->tcp_cwr = B_FALSE;
7729 	tcp->tcp_ecn_echo_on = B_FALSE;
7730 
7731 	if (tcp->tcp_sack_info != NULL) {
7732 		if (tcp->tcp_notsack_list != NULL) {
7733 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7734 		}
7735 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7736 		tcp->tcp_sack_info = NULL;
7737 	}
7738 
7739 	tcp->tcp_rcv_ws = 0;
7740 	tcp->tcp_snd_ws = 0;
7741 	tcp->tcp_ts_recent = 0;
7742 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7743 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7744 	tcp->tcp_if_mtu = 0;
7745 
7746 	ASSERT(tcp->tcp_reass_head == NULL);
7747 	ASSERT(tcp->tcp_reass_tail == NULL);
7748 
7749 	tcp->tcp_cwnd_cnt = 0;
7750 
7751 	ASSERT(tcp->tcp_rcv_list == NULL);
7752 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7753 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7754 	ASSERT(tcp->tcp_rcv_cnt == 0);
7755 
7756 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7757 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7758 	tcp->tcp_csuna = 0;
7759 
7760 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7761 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7762 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7763 	tcp->tcp_rtt_update = 0;
7764 
7765 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7766 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7767 
7768 	tcp->tcp_rack = 0;			/* Displayed in mib */
7769 	tcp->tcp_rack_cnt = 0;
7770 	tcp->tcp_rack_cur_max = 0;
7771 	tcp->tcp_rack_abs_max = 0;
7772 
7773 	tcp->tcp_max_swnd = 0;
7774 
7775 	ASSERT(tcp->tcp_listener == NULL);
7776 
7777 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7778 
7779 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7780 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7781 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7782 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7783 
7784 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7785 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7786 	PRESERVE(tcp->tcp_conn_req_max);
7787 	PRESERVE(tcp->tcp_conn_req_seqnum);
7788 
7789 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7790 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7791 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7792 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7793 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7794 
7795 	tcp->tcp_lingertime = 0;
7796 
7797 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7798 	ASSERT(tcp->tcp_urp_mp == NULL);
7799 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7800 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7801 
7802 	ASSERT(tcp->tcp_eager_next_q == NULL);
7803 	ASSERT(tcp->tcp_eager_last_q == NULL);
7804 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7805 	    tcp->tcp_eager_prev_q0 == NULL) ||
7806 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7807 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7808 
7809 	tcp->tcp_client_errno = 0;
7810 
7811 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7812 
7813 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7814 
7815 	PRESERVE(tcp->tcp_bound_source_v6);
7816 	tcp->tcp_last_sent_len = 0;
7817 	tcp->tcp_dupack_cnt = 0;
7818 
7819 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7820 	PRESERVE(tcp->tcp_lport);
7821 
7822 	PRESERVE(tcp->tcp_acceptor_lockp);
7823 
7824 	ASSERT(tcp->tcp_ordrelid == 0);
7825 	PRESERVE(tcp->tcp_acceptor_id);
7826 	DONTCARE(tcp->tcp_ipsec_overhead);
7827 
7828 	/*
7829 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7830 	 * in tcp structure and now tracing), Re-initialize all
7831 	 * members of tcp_traceinfo.
7832 	 */
7833 	if (tcp->tcp_tracebuf != NULL) {
7834 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7835 	}
7836 
7837 	PRESERVE(tcp->tcp_family);
7838 	if (tcp->tcp_family == AF_INET6) {
7839 		tcp->tcp_ipversion = IPV6_VERSION;
7840 		tcp->tcp_mss = tcp_mss_def_ipv6;
7841 	} else {
7842 		tcp->tcp_ipversion = IPV4_VERSION;
7843 		tcp->tcp_mss = tcp_mss_def_ipv4;
7844 	}
7845 
7846 	tcp->tcp_bound_if = 0;
7847 	tcp->tcp_ipv6_recvancillary = 0;
7848 	tcp->tcp_recvifindex = 0;
7849 	tcp->tcp_recvhops = 0;
7850 	tcp->tcp_closed = 0;
7851 	tcp->tcp_cleandeathtag = 0;
7852 	if (tcp->tcp_hopopts != NULL) {
7853 		mi_free(tcp->tcp_hopopts);
7854 		tcp->tcp_hopopts = NULL;
7855 		tcp->tcp_hopoptslen = 0;
7856 	}
7857 	ASSERT(tcp->tcp_hopoptslen == 0);
7858 	if (tcp->tcp_dstopts != NULL) {
7859 		mi_free(tcp->tcp_dstopts);
7860 		tcp->tcp_dstopts = NULL;
7861 		tcp->tcp_dstoptslen = 0;
7862 	}
7863 	ASSERT(tcp->tcp_dstoptslen == 0);
7864 	if (tcp->tcp_rtdstopts != NULL) {
7865 		mi_free(tcp->tcp_rtdstopts);
7866 		tcp->tcp_rtdstopts = NULL;
7867 		tcp->tcp_rtdstoptslen = 0;
7868 	}
7869 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7870 	if (tcp->tcp_rthdr != NULL) {
7871 		mi_free(tcp->tcp_rthdr);
7872 		tcp->tcp_rthdr = NULL;
7873 		tcp->tcp_rthdrlen = 0;
7874 	}
7875 	ASSERT(tcp->tcp_rthdrlen == 0);
7876 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7877 
7878 	/* Reset fusion-related fields */
7879 	tcp->tcp_fused = B_FALSE;
7880 	tcp->tcp_unfusable = B_FALSE;
7881 	tcp->tcp_fused_sigurg = B_FALSE;
7882 	tcp->tcp_direct_sockfs = B_FALSE;
7883 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7884 	tcp->tcp_loopback_peer = NULL;
7885 	tcp->tcp_fuse_rcv_hiwater = 0;
7886 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7887 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7888 
7889 	tcp->tcp_in_ack_unsent = 0;
7890 	tcp->tcp_cork = B_FALSE;
7891 
7892 	PRESERVE(tcp->tcp_squeue_bytes);
7893 
7894 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7895 	ASSERT(!tcp->tcp_kssl_pending);
7896 	PRESERVE(tcp->tcp_kssl_ent);
7897 
7898 #undef	DONTCARE
7899 #undef	PRESERVE
7900 }
7901 
7902 /*
7903  * Allocate necessary resources and initialize state vector.
7904  * Guaranteed not to fail so that when an error is returned,
7905  * the caller doesn't need to do any additional cleanup.
7906  */
7907 int
7908 tcp_init(tcp_t *tcp, queue_t *q)
7909 {
7910 	int	err;
7911 
7912 	tcp->tcp_rq = q;
7913 	tcp->tcp_wq = WR(q);
7914 	tcp->tcp_state = TCPS_IDLE;
7915 	if ((err = tcp_init_values(tcp)) != 0)
7916 		tcp_timers_stop(tcp);
7917 	return (err);
7918 }
7919 
7920 static int
7921 tcp_init_values(tcp_t *tcp)
7922 {
7923 	int	err;
7924 
7925 	ASSERT((tcp->tcp_family == AF_INET &&
7926 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7927 	    (tcp->tcp_family == AF_INET6 &&
7928 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7929 	    tcp->tcp_ipversion == IPV6_VERSION)));
7930 
7931 	/*
7932 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7933 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7934 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7935 	 * during first few transmissions of a connection as seen in slow
7936 	 * links.
7937 	 */
7938 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7939 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7940 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7941 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7942 	    tcp_conn_grace_period;
7943 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7944 		tcp->tcp_rto = tcp_rexmit_interval_min;
7945 	tcp->tcp_timer_backoff = 0;
7946 	tcp->tcp_ms_we_have_waited = 0;
7947 	tcp->tcp_last_recv_time = lbolt;
7948 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7949 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7950 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7951 
7952 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7953 
7954 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7955 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7956 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7957 	/*
7958 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7959 	 * passive open.
7960 	 */
7961 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7962 
7963 	tcp->tcp_naglim = tcp_naglim_def;
7964 
7965 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7966 
7967 	tcp->tcp_mdt_hdr_head = 0;
7968 	tcp->tcp_mdt_hdr_tail = 0;
7969 
7970 	/* Reset fusion-related fields */
7971 	tcp->tcp_fused = B_FALSE;
7972 	tcp->tcp_unfusable = B_FALSE;
7973 	tcp->tcp_fused_sigurg = B_FALSE;
7974 	tcp->tcp_direct_sockfs = B_FALSE;
7975 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7976 	tcp->tcp_loopback_peer = NULL;
7977 	tcp->tcp_fuse_rcv_hiwater = 0;
7978 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7979 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7980 
7981 	/* Initialize the header template */
7982 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7983 		err = tcp_header_init_ipv4(tcp);
7984 	} else {
7985 		err = tcp_header_init_ipv6(tcp);
7986 	}
7987 	if (err)
7988 		return (err);
7989 
7990 	/*
7991 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7992 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7993 	 */
7994 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7995 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7996 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7997 
7998 	tcp->tcp_cork = B_FALSE;
7999 	/*
8000 	 * Init the tcp_debug option.  This value determines whether TCP
8001 	 * calls strlog() to print out debug messages.  Doing this
8002 	 * initialization here means that this value is not inherited thru
8003 	 * tcp_reinit().
8004 	 */
8005 	tcp->tcp_debug = tcp_dbg;
8006 
8007 	tcp->tcp_ka_interval = tcp_keepalive_interval;
8008 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
8009 
8010 	return (0);
8011 }
8012 
8013 /*
8014  * Initialize the IPv4 header. Loses any record of any IP options.
8015  */
8016 static int
8017 tcp_header_init_ipv4(tcp_t *tcp)
8018 {
8019 	tcph_t		*tcph;
8020 	uint32_t	sum;
8021 	conn_t		*connp;
8022 
8023 	/*
8024 	 * This is a simple initialization. If there's
8025 	 * already a template, it should never be too small,
8026 	 * so reuse it.  Otherwise, allocate space for the new one.
8027 	 */
8028 	if (tcp->tcp_iphc == NULL) {
8029 		ASSERT(tcp->tcp_iphc_len == 0);
8030 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8031 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8032 		if (tcp->tcp_iphc == NULL) {
8033 			tcp->tcp_iphc_len = 0;
8034 			return (ENOMEM);
8035 		}
8036 	}
8037 
8038 	/* options are gone; may need a new label */
8039 	connp = tcp->tcp_connp;
8040 	connp->conn_mlp_type = mlptSingle;
8041 	connp->conn_ulp_labeled = !is_system_labeled();
8042 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8043 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8044 	tcp->tcp_ip6h = NULL;
8045 	tcp->tcp_ipversion = IPV4_VERSION;
8046 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8047 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8048 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8049 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8050 	tcp->tcp_ipha->ipha_version_and_hdr_length
8051 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8052 	tcp->tcp_ipha->ipha_ident = 0;
8053 
8054 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
8055 	tcp->tcp_tos = 0;
8056 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8057 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
8058 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8059 
8060 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8061 	tcp->tcp_tcph = tcph;
8062 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8063 	/*
8064 	 * IP wants our header length in the checksum field to
8065 	 * allow it to perform a single pseudo-header+checksum
8066 	 * calculation on behalf of TCP.
8067 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8068 	 */
8069 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8070 	sum = (sum >> 16) + (sum & 0xFFFF);
8071 	U16_TO_ABE16(sum, tcph->th_sum);
8072 	return (0);
8073 }
8074 
8075 /*
8076  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8077  */
8078 static int
8079 tcp_header_init_ipv6(tcp_t *tcp)
8080 {
8081 	tcph_t	*tcph;
8082 	uint32_t	sum;
8083 	conn_t	*connp;
8084 
8085 	/*
8086 	 * This is a simple initialization. If there's
8087 	 * already a template, it should never be too small,
8088 	 * so reuse it. Otherwise, allocate space for the new one.
8089 	 * Ensure that there is enough space to "downgrade" the tcp_t
8090 	 * to an IPv4 tcp_t. This requires having space for a full load
8091 	 * of IPv4 options, as well as a full load of TCP options
8092 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8093 	 * than a v6 header and a TCP header with a full load of TCP options
8094 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8095 	 * We want to avoid reallocation in the "downgraded" case when
8096 	 * processing outbound IPv4 options.
8097 	 */
8098 	if (tcp->tcp_iphc == NULL) {
8099 		ASSERT(tcp->tcp_iphc_len == 0);
8100 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8101 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8102 		if (tcp->tcp_iphc == NULL) {
8103 			tcp->tcp_iphc_len = 0;
8104 			return (ENOMEM);
8105 		}
8106 	}
8107 
8108 	/* options are gone; may need a new label */
8109 	connp = tcp->tcp_connp;
8110 	connp->conn_mlp_type = mlptSingle;
8111 	connp->conn_ulp_labeled = !is_system_labeled();
8112 
8113 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8114 	tcp->tcp_ipversion = IPV6_VERSION;
8115 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8116 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8117 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8118 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8119 	tcp->tcp_ipha = NULL;
8120 
8121 	/* Initialize the header template */
8122 
8123 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8124 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8125 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8126 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
8127 
8128 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8129 	tcp->tcp_tcph = tcph;
8130 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8131 	/*
8132 	 * IP wants our header length in the checksum field to
8133 	 * allow it to perform a single psuedo-header+checksum
8134 	 * calculation on behalf of TCP.
8135 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8136 	 */
8137 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8138 	sum = (sum >> 16) + (sum & 0xFFFF);
8139 	U16_TO_ABE16(sum, tcph->th_sum);
8140 	return (0);
8141 }
8142 
8143 /* At minimum we need 4 bytes in the TCP header for the lookup */
8144 #define	ICMP_MIN_TCP_HDR	12
8145 
8146 /*
8147  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8148  * passed up by IP. The message is always received on the correct tcp_t.
8149  * Assumes that IP has pulled up everything up to and including the ICMP header.
8150  */
8151 void
8152 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8153 {
8154 	icmph_t *icmph;
8155 	ipha_t	*ipha;
8156 	int	iph_hdr_length;
8157 	tcph_t	*tcph;
8158 	boolean_t ipsec_mctl = B_FALSE;
8159 	boolean_t secure;
8160 	mblk_t *first_mp = mp;
8161 	uint32_t new_mss;
8162 	uint32_t ratio;
8163 	size_t mp_size = MBLKL(mp);
8164 	uint32_t seg_ack;
8165 	uint32_t seg_seq;
8166 
8167 	/* Assume IP provides aligned packets - otherwise toss */
8168 	if (!OK_32PTR(mp->b_rptr)) {
8169 		freemsg(mp);
8170 		return;
8171 	}
8172 
8173 	/*
8174 	 * Since ICMP errors are normal data marked with M_CTL when sent
8175 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8176 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8177 	 */
8178 	if ((mp_size == sizeof (ipsec_info_t)) &&
8179 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8180 		ASSERT(mp->b_cont != NULL);
8181 		mp = mp->b_cont;
8182 		/* IP should have done this */
8183 		ASSERT(OK_32PTR(mp->b_rptr));
8184 		mp_size = MBLKL(mp);
8185 		ipsec_mctl = B_TRUE;
8186 	}
8187 
8188 	/*
8189 	 * Verify that we have a complete outer IP header. If not, drop it.
8190 	 */
8191 	if (mp_size < sizeof (ipha_t)) {
8192 noticmpv4:
8193 		freemsg(first_mp);
8194 		return;
8195 	}
8196 
8197 	ipha = (ipha_t *)mp->b_rptr;
8198 	/*
8199 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8200 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8201 	 */
8202 	switch (IPH_HDR_VERSION(ipha)) {
8203 	case IPV6_VERSION:
8204 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8205 		return;
8206 	case IPV4_VERSION:
8207 		break;
8208 	default:
8209 		goto noticmpv4;
8210 	}
8211 
8212 	/* Skip past the outer IP and ICMP headers */
8213 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8214 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8215 	/*
8216 	 * If we don't have the correct outer IP header length or if the ULP
8217 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8218 	 * send it upstream.
8219 	 */
8220 	if (iph_hdr_length < sizeof (ipha_t) ||
8221 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8222 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8223 		goto noticmpv4;
8224 	}
8225 	ipha = (ipha_t *)&icmph[1];
8226 
8227 	/* Skip past the inner IP and find the ULP header */
8228 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8229 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8230 	/*
8231 	 * If we don't have the correct inner IP header length or if the ULP
8232 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8233 	 * bytes of TCP header, drop it.
8234 	 */
8235 	if (iph_hdr_length < sizeof (ipha_t) ||
8236 	    ipha->ipha_protocol != IPPROTO_TCP ||
8237 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8238 		goto noticmpv4;
8239 	}
8240 
8241 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8242 		if (ipsec_mctl) {
8243 			secure = ipsec_in_is_secure(first_mp);
8244 		} else {
8245 			secure = B_FALSE;
8246 		}
8247 		if (secure) {
8248 			/*
8249 			 * If we are willing to accept this in clear
8250 			 * we don't have to verify policy.
8251 			 */
8252 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8253 				if (!tcp_check_policy(tcp, first_mp,
8254 				    ipha, NULL, secure, ipsec_mctl)) {
8255 					/*
8256 					 * tcp_check_policy called
8257 					 * ip_drop_packet() on failure.
8258 					 */
8259 					return;
8260 				}
8261 			}
8262 		}
8263 	} else if (ipsec_mctl) {
8264 		/*
8265 		 * This is a hard_bound connection. IP has already
8266 		 * verified policy. We don't have to do it again.
8267 		 */
8268 		freeb(first_mp);
8269 		first_mp = mp;
8270 		ipsec_mctl = B_FALSE;
8271 	}
8272 
8273 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8274 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8275 	/*
8276 	 * TCP SHOULD check that the TCP sequence number contained in
8277 	 * payload of the ICMP error message is within the range
8278 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8279 	 */
8280 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8281 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8282 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8283 		/*
8284 		 * If the ICMP message is bogus, should we kill the
8285 		 * connection, or should we just drop the bogus ICMP
8286 		 * message? It would probably make more sense to just
8287 		 * drop the message so that if this one managed to get
8288 		 * in, the real connection should not suffer.
8289 		 */
8290 		goto noticmpv4;
8291 	}
8292 
8293 	switch (icmph->icmph_type) {
8294 	case ICMP_DEST_UNREACHABLE:
8295 		switch (icmph->icmph_code) {
8296 		case ICMP_FRAGMENTATION_NEEDED:
8297 			/*
8298 			 * Reduce the MSS based on the new MTU.  This will
8299 			 * eliminate any fragmentation locally.
8300 			 * N.B.  There may well be some funny side-effects on
8301 			 * the local send policy and the remote receive policy.
8302 			 * Pending further research, we provide
8303 			 * tcp_ignore_path_mtu just in case this proves
8304 			 * disastrous somewhere.
8305 			 *
8306 			 * After updating the MSS, retransmit part of the
8307 			 * dropped segment using the new mss by calling
8308 			 * tcp_wput_data().  Need to adjust all those
8309 			 * params to make sure tcp_wput_data() work properly.
8310 			 */
8311 			if (tcp_ignore_path_mtu)
8312 				break;
8313 
8314 			/*
8315 			 * Decrease the MSS by time stamp options
8316 			 * IP options and IPSEC options. tcp_hdr_len
8317 			 * includes time stamp option and IP option
8318 			 * length.
8319 			 */
8320 
8321 			new_mss = ntohs(icmph->icmph_du_mtu) -
8322 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8323 
8324 			/*
8325 			 * Only update the MSS if the new one is
8326 			 * smaller than the previous one.  This is
8327 			 * to avoid problems when getting multiple
8328 			 * ICMP errors for the same MTU.
8329 			 */
8330 			if (new_mss >= tcp->tcp_mss)
8331 				break;
8332 
8333 			/*
8334 			 * Stop doing PMTU if new_mss is less than 68
8335 			 * or less than tcp_mss_min.
8336 			 * The value 68 comes from rfc 1191.
8337 			 */
8338 			if (new_mss < MAX(68, tcp_mss_min))
8339 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8340 				    0;
8341 
8342 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8343 			ASSERT(ratio >= 1);
8344 			tcp_mss_set(tcp, new_mss);
8345 
8346 			/*
8347 			 * Make sure we have something to
8348 			 * send.
8349 			 */
8350 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8351 			    (tcp->tcp_xmit_head != NULL)) {
8352 				/*
8353 				 * Shrink tcp_cwnd in
8354 				 * proportion to the old MSS/new MSS.
8355 				 */
8356 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8357 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8358 				    (tcp->tcp_unsent == 0)) {
8359 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8360 				} else {
8361 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8362 				}
8363 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8364 				tcp->tcp_rexmit = B_TRUE;
8365 				tcp->tcp_dupack_cnt = 0;
8366 				tcp->tcp_snd_burst = TCP_CWND_SS;
8367 				tcp_ss_rexmit(tcp);
8368 			}
8369 			break;
8370 		case ICMP_PORT_UNREACHABLE:
8371 		case ICMP_PROTOCOL_UNREACHABLE:
8372 			switch (tcp->tcp_state) {
8373 			case TCPS_SYN_SENT:
8374 			case TCPS_SYN_RCVD:
8375 				/*
8376 				 * ICMP can snipe away incipient
8377 				 * TCP connections as long as
8378 				 * seq number is same as initial
8379 				 * send seq number.
8380 				 */
8381 				if (seg_seq == tcp->tcp_iss) {
8382 					(void) tcp_clean_death(tcp,
8383 					    ECONNREFUSED, 6);
8384 				}
8385 				break;
8386 			}
8387 			break;
8388 		case ICMP_HOST_UNREACHABLE:
8389 		case ICMP_NET_UNREACHABLE:
8390 			/* Record the error in case we finally time out. */
8391 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8392 				tcp->tcp_client_errno = EHOSTUNREACH;
8393 			else
8394 				tcp->tcp_client_errno = ENETUNREACH;
8395 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8396 				if (tcp->tcp_listener != NULL &&
8397 				    tcp->tcp_listener->tcp_syn_defense) {
8398 					/*
8399 					 * Ditch the half-open connection if we
8400 					 * suspect a SYN attack is under way.
8401 					 */
8402 					tcp_ip_ire_mark_advice(tcp);
8403 					(void) tcp_clean_death(tcp,
8404 					    tcp->tcp_client_errno, 7);
8405 				}
8406 			}
8407 			break;
8408 		default:
8409 			break;
8410 		}
8411 		break;
8412 	case ICMP_SOURCE_QUENCH: {
8413 		/*
8414 		 * use a global boolean to control
8415 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8416 		 * The default is false.
8417 		 */
8418 		if (tcp_icmp_source_quench) {
8419 			/*
8420 			 * Reduce the sending rate as if we got a
8421 			 * retransmit timeout
8422 			 */
8423 			uint32_t npkt;
8424 
8425 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8426 			    tcp->tcp_mss;
8427 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8428 			tcp->tcp_cwnd = tcp->tcp_mss;
8429 			tcp->tcp_cwnd_cnt = 0;
8430 		}
8431 		break;
8432 	}
8433 	}
8434 	freemsg(first_mp);
8435 }
8436 
8437 /*
8438  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8439  * error messages passed up by IP.
8440  * Assumes that IP has pulled up all the extension headers as well
8441  * as the ICMPv6 header.
8442  */
8443 static void
8444 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8445 {
8446 	icmp6_t *icmp6;
8447 	ip6_t	*ip6h;
8448 	uint16_t	iph_hdr_length;
8449 	tcpha_t	*tcpha;
8450 	uint8_t	*nexthdrp;
8451 	uint32_t new_mss;
8452 	uint32_t ratio;
8453 	boolean_t secure;
8454 	mblk_t *first_mp = mp;
8455 	size_t mp_size;
8456 	uint32_t seg_ack;
8457 	uint32_t seg_seq;
8458 
8459 	/*
8460 	 * The caller has determined if this is an IPSEC_IN packet and
8461 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8462 	 */
8463 	if (ipsec_mctl)
8464 		mp = mp->b_cont;
8465 
8466 	mp_size = MBLKL(mp);
8467 
8468 	/*
8469 	 * Verify that we have a complete IP header. If not, send it upstream.
8470 	 */
8471 	if (mp_size < sizeof (ip6_t)) {
8472 noticmpv6:
8473 		freemsg(first_mp);
8474 		return;
8475 	}
8476 
8477 	/*
8478 	 * Verify this is an ICMPV6 packet, else send it upstream.
8479 	 */
8480 	ip6h = (ip6_t *)mp->b_rptr;
8481 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8482 		iph_hdr_length = IPV6_HDR_LEN;
8483 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8484 	    &nexthdrp) ||
8485 	    *nexthdrp != IPPROTO_ICMPV6) {
8486 		goto noticmpv6;
8487 	}
8488 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8489 	ip6h = (ip6_t *)&icmp6[1];
8490 	/*
8491 	 * Verify if we have a complete ICMP and inner IP header.
8492 	 */
8493 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8494 		goto noticmpv6;
8495 
8496 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8497 		goto noticmpv6;
8498 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8499 	/*
8500 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8501 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8502 	 * packet.
8503 	 */
8504 	if ((*nexthdrp != IPPROTO_TCP) ||
8505 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8506 		goto noticmpv6;
8507 	}
8508 
8509 	/*
8510 	 * ICMP errors come on the right queue or come on
8511 	 * listener/global queue for detached connections and
8512 	 * get switched to the right queue. If it comes on the
8513 	 * right queue, policy check has already been done by IP
8514 	 * and thus free the first_mp without verifying the policy.
8515 	 * If it has come for a non-hard bound connection, we need
8516 	 * to verify policy as IP may not have done it.
8517 	 */
8518 	if (!tcp->tcp_hard_bound) {
8519 		if (ipsec_mctl) {
8520 			secure = ipsec_in_is_secure(first_mp);
8521 		} else {
8522 			secure = B_FALSE;
8523 		}
8524 		if (secure) {
8525 			/*
8526 			 * If we are willing to accept this in clear
8527 			 * we don't have to verify policy.
8528 			 */
8529 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8530 				if (!tcp_check_policy(tcp, first_mp,
8531 				    NULL, ip6h, secure, ipsec_mctl)) {
8532 					/*
8533 					 * tcp_check_policy called
8534 					 * ip_drop_packet() on failure.
8535 					 */
8536 					return;
8537 				}
8538 			}
8539 		}
8540 	} else if (ipsec_mctl) {
8541 		/*
8542 		 * This is a hard_bound connection. IP has already
8543 		 * verified policy. We don't have to do it again.
8544 		 */
8545 		freeb(first_mp);
8546 		first_mp = mp;
8547 		ipsec_mctl = B_FALSE;
8548 	}
8549 
8550 	seg_ack = ntohl(tcpha->tha_ack);
8551 	seg_seq = ntohl(tcpha->tha_seq);
8552 	/*
8553 	 * TCP SHOULD check that the TCP sequence number contained in
8554 	 * payload of the ICMP error message is within the range
8555 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8556 	 */
8557 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8558 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8559 		/*
8560 		 * If the ICMP message is bogus, should we kill the
8561 		 * connection, or should we just drop the bogus ICMP
8562 		 * message? It would probably make more sense to just
8563 		 * drop the message so that if this one managed to get
8564 		 * in, the real connection should not suffer.
8565 		 */
8566 		goto noticmpv6;
8567 	}
8568 
8569 	switch (icmp6->icmp6_type) {
8570 	case ICMP6_PACKET_TOO_BIG:
8571 		/*
8572 		 * Reduce the MSS based on the new MTU.  This will
8573 		 * eliminate any fragmentation locally.
8574 		 * N.B.  There may well be some funny side-effects on
8575 		 * the local send policy and the remote receive policy.
8576 		 * Pending further research, we provide
8577 		 * tcp_ignore_path_mtu just in case this proves
8578 		 * disastrous somewhere.
8579 		 *
8580 		 * After updating the MSS, retransmit part of the
8581 		 * dropped segment using the new mss by calling
8582 		 * tcp_wput_data().  Need to adjust all those
8583 		 * params to make sure tcp_wput_data() work properly.
8584 		 */
8585 		if (tcp_ignore_path_mtu)
8586 			break;
8587 
8588 		/*
8589 		 * Decrease the MSS by time stamp options
8590 		 * IP options and IPSEC options. tcp_hdr_len
8591 		 * includes time stamp option and IP option
8592 		 * length.
8593 		 */
8594 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8595 			    tcp->tcp_ipsec_overhead;
8596 
8597 		/*
8598 		 * Only update the MSS if the new one is
8599 		 * smaller than the previous one.  This is
8600 		 * to avoid problems when getting multiple
8601 		 * ICMP errors for the same MTU.
8602 		 */
8603 		if (new_mss >= tcp->tcp_mss)
8604 			break;
8605 
8606 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8607 		ASSERT(ratio >= 1);
8608 		tcp_mss_set(tcp, new_mss);
8609 
8610 		/*
8611 		 * Make sure we have something to
8612 		 * send.
8613 		 */
8614 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8615 		    (tcp->tcp_xmit_head != NULL)) {
8616 			/*
8617 			 * Shrink tcp_cwnd in
8618 			 * proportion to the old MSS/new MSS.
8619 			 */
8620 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8621 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8622 			    (tcp->tcp_unsent == 0)) {
8623 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8624 			} else {
8625 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8626 			}
8627 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8628 			tcp->tcp_rexmit = B_TRUE;
8629 			tcp->tcp_dupack_cnt = 0;
8630 			tcp->tcp_snd_burst = TCP_CWND_SS;
8631 			tcp_ss_rexmit(tcp);
8632 		}
8633 		break;
8634 
8635 	case ICMP6_DST_UNREACH:
8636 		switch (icmp6->icmp6_code) {
8637 		case ICMP6_DST_UNREACH_NOPORT:
8638 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8639 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8640 			    (seg_seq == tcp->tcp_iss)) {
8641 				(void) tcp_clean_death(tcp,
8642 				    ECONNREFUSED, 8);
8643 			}
8644 			break;
8645 
8646 		case ICMP6_DST_UNREACH_ADMIN:
8647 		case ICMP6_DST_UNREACH_NOROUTE:
8648 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8649 		case ICMP6_DST_UNREACH_ADDR:
8650 			/* Record the error in case we finally time out. */
8651 			tcp->tcp_client_errno = EHOSTUNREACH;
8652 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8653 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8654 			    (seg_seq == tcp->tcp_iss)) {
8655 				if (tcp->tcp_listener != NULL &&
8656 				    tcp->tcp_listener->tcp_syn_defense) {
8657 					/*
8658 					 * Ditch the half-open connection if we
8659 					 * suspect a SYN attack is under way.
8660 					 */
8661 					tcp_ip_ire_mark_advice(tcp);
8662 					(void) tcp_clean_death(tcp,
8663 					    tcp->tcp_client_errno, 9);
8664 				}
8665 			}
8666 
8667 
8668 			break;
8669 		default:
8670 			break;
8671 		}
8672 		break;
8673 
8674 	case ICMP6_PARAM_PROB:
8675 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8676 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8677 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8678 		    (uchar_t *)nexthdrp) {
8679 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8680 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8681 				(void) tcp_clean_death(tcp,
8682 				    ECONNREFUSED, 10);
8683 			}
8684 			break;
8685 		}
8686 		break;
8687 
8688 	case ICMP6_TIME_EXCEEDED:
8689 	default:
8690 		break;
8691 	}
8692 	freemsg(first_mp);
8693 }
8694 
8695 /*
8696  * IP recognizes seven kinds of bind requests:
8697  *
8698  * - A zero-length address binds only to the protocol number.
8699  *
8700  * - A 4-byte address is treated as a request to
8701  * validate that the address is a valid local IPv4
8702  * address, appropriate for an application to bind to.
8703  * IP does the verification, but does not make any note
8704  * of the address at this time.
8705  *
8706  * - A 16-byte address contains is treated as a request
8707  * to validate a local IPv6 address, as the 4-byte
8708  * address case above.
8709  *
8710  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8711  * use it for the inbound fanout of packets.
8712  *
8713  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8714  * use it for the inbound fanout of packets.
8715  *
8716  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8717  * information consisting of local and remote addresses
8718  * and ports.  In this case, the addresses are both
8719  * validated as appropriate for this operation, and, if
8720  * so, the information is retained for use in the
8721  * inbound fanout.
8722  *
8723  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8724  * fanout information, like the 12-byte case above.
8725  *
8726  * IP will also fill in the IRE request mblk with information
8727  * regarding our peer.  In all cases, we notify IP of our protocol
8728  * type by appending a single protocol byte to the bind request.
8729  */
8730 static mblk_t *
8731 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8732 {
8733 	char	*cp;
8734 	mblk_t	*mp;
8735 	struct T_bind_req *tbr;
8736 	ipa_conn_t	*ac;
8737 	ipa6_conn_t	*ac6;
8738 	sin_t		*sin;
8739 	sin6_t		*sin6;
8740 
8741 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8742 	ASSERT((tcp->tcp_family == AF_INET &&
8743 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8744 	    (tcp->tcp_family == AF_INET6 &&
8745 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8746 	    tcp->tcp_ipversion == IPV6_VERSION)));
8747 
8748 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8749 	if (!mp)
8750 		return (mp);
8751 	mp->b_datap->db_type = M_PROTO;
8752 	tbr = (struct T_bind_req *)mp->b_rptr;
8753 	tbr->PRIM_type = bind_prim;
8754 	tbr->ADDR_offset = sizeof (*tbr);
8755 	tbr->CONIND_number = 0;
8756 	tbr->ADDR_length = addr_length;
8757 	cp = (char *)&tbr[1];
8758 	switch (addr_length) {
8759 	case sizeof (ipa_conn_t):
8760 		ASSERT(tcp->tcp_family == AF_INET);
8761 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8762 
8763 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8764 		if (mp->b_cont == NULL) {
8765 			freemsg(mp);
8766 			return (NULL);
8767 		}
8768 		mp->b_cont->b_wptr += sizeof (ire_t);
8769 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8770 
8771 		/* cp known to be 32 bit aligned */
8772 		ac = (ipa_conn_t *)cp;
8773 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8774 		ac->ac_faddr = tcp->tcp_remote;
8775 		ac->ac_fport = tcp->tcp_fport;
8776 		ac->ac_lport = tcp->tcp_lport;
8777 		tcp->tcp_hard_binding = 1;
8778 		break;
8779 
8780 	case sizeof (ipa6_conn_t):
8781 		ASSERT(tcp->tcp_family == AF_INET6);
8782 
8783 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8784 		if (mp->b_cont == NULL) {
8785 			freemsg(mp);
8786 			return (NULL);
8787 		}
8788 		mp->b_cont->b_wptr += sizeof (ire_t);
8789 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8790 
8791 		/* cp known to be 32 bit aligned */
8792 		ac6 = (ipa6_conn_t *)cp;
8793 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8794 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8795 			    &ac6->ac6_laddr);
8796 		} else {
8797 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8798 		}
8799 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8800 		ac6->ac6_fport = tcp->tcp_fport;
8801 		ac6->ac6_lport = tcp->tcp_lport;
8802 		tcp->tcp_hard_binding = 1;
8803 		break;
8804 
8805 	case sizeof (sin_t):
8806 		/*
8807 		 * NOTE: IPV6_ADDR_LEN also has same size.
8808 		 * Use family to discriminate.
8809 		 */
8810 		if (tcp->tcp_family == AF_INET) {
8811 			sin = (sin_t *)cp;
8812 
8813 			*sin = sin_null;
8814 			sin->sin_family = AF_INET;
8815 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8816 			sin->sin_port = tcp->tcp_lport;
8817 			break;
8818 		} else {
8819 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8820 		}
8821 		break;
8822 
8823 	case sizeof (sin6_t):
8824 		ASSERT(tcp->tcp_family == AF_INET6);
8825 		sin6 = (sin6_t *)cp;
8826 
8827 		*sin6 = sin6_null;
8828 		sin6->sin6_family = AF_INET6;
8829 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8830 		sin6->sin6_port = tcp->tcp_lport;
8831 		break;
8832 
8833 	case IP_ADDR_LEN:
8834 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8835 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8836 		break;
8837 
8838 	}
8839 	/* Add protocol number to end */
8840 	cp[addr_length] = (char)IPPROTO_TCP;
8841 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8842 	return (mp);
8843 }
8844 
8845 /*
8846  * Notify IP that we are having trouble with this connection.  IP should
8847  * blow the IRE away and start over.
8848  */
8849 static void
8850 tcp_ip_notify(tcp_t *tcp)
8851 {
8852 	struct iocblk	*iocp;
8853 	ipid_t	*ipid;
8854 	mblk_t	*mp;
8855 
8856 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8857 	if (tcp->tcp_ipversion == IPV6_VERSION)
8858 		return;
8859 
8860 	mp = mkiocb(IP_IOCTL);
8861 	if (mp == NULL)
8862 		return;
8863 
8864 	iocp = (struct iocblk *)mp->b_rptr;
8865 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8866 
8867 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8868 	if (!mp->b_cont) {
8869 		freeb(mp);
8870 		return;
8871 	}
8872 
8873 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8874 	mp->b_cont->b_wptr += iocp->ioc_count;
8875 	bzero(ipid, sizeof (*ipid));
8876 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8877 	ipid->ipid_ire_type = IRE_CACHE;
8878 	ipid->ipid_addr_offset = sizeof (ipid_t);
8879 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8880 	/*
8881 	 * Note: in the case of source routing we want to blow away the
8882 	 * route to the first source route hop.
8883 	 */
8884 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8885 	    sizeof (tcp->tcp_ipha->ipha_dst));
8886 
8887 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8888 }
8889 
8890 /* Unlink and return any mblk that looks like it contains an ire */
8891 static mblk_t *
8892 tcp_ire_mp(mblk_t *mp)
8893 {
8894 	mblk_t	*prev_mp;
8895 
8896 	for (;;) {
8897 		prev_mp = mp;
8898 		mp = mp->b_cont;
8899 		if (mp == NULL)
8900 			break;
8901 		switch (DB_TYPE(mp)) {
8902 		case IRE_DB_TYPE:
8903 		case IRE_DB_REQ_TYPE:
8904 			if (prev_mp != NULL)
8905 				prev_mp->b_cont = mp->b_cont;
8906 			mp->b_cont = NULL;
8907 			return (mp);
8908 		default:
8909 			break;
8910 		}
8911 	}
8912 	return (mp);
8913 }
8914 
8915 /*
8916  * Timer callback routine for keepalive probe.  We do a fake resend of
8917  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8918  * check to see if we have heard anything from the other end for the last
8919  * RTO period.  If we have, set the timer to expire for another
8920  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8921  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8922  * the timeout if we have not heard from the other side.  If for more than
8923  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8924  * kill the connection unless the keepalive abort threshold is 0.  In
8925  * that case, we will probe "forever."
8926  */
8927 static void
8928 tcp_keepalive_killer(void *arg)
8929 {
8930 	mblk_t	*mp;
8931 	conn_t	*connp = (conn_t *)arg;
8932 	tcp_t  	*tcp = connp->conn_tcp;
8933 	int32_t	firetime;
8934 	int32_t	idletime;
8935 	int32_t	ka_intrvl;
8936 
8937 	tcp->tcp_ka_tid = 0;
8938 
8939 	if (tcp->tcp_fused)
8940 		return;
8941 
8942 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8943 	ka_intrvl = tcp->tcp_ka_interval;
8944 
8945 	/*
8946 	 * Keepalive probe should only be sent if the application has not
8947 	 * done a close on the connection.
8948 	 */
8949 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8950 		return;
8951 	}
8952 	/* Timer fired too early, restart it. */
8953 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8954 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8955 		    MSEC_TO_TICK(ka_intrvl));
8956 		return;
8957 	}
8958 
8959 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8960 	/*
8961 	 * If we have not heard from the other side for a long
8962 	 * time, kill the connection unless the keepalive abort
8963 	 * threshold is 0.  In that case, we will probe "forever."
8964 	 */
8965 	if (tcp->tcp_ka_abort_thres != 0 &&
8966 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8967 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8968 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8969 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8970 		return;
8971 	}
8972 
8973 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8974 	    idletime >= ka_intrvl) {
8975 		/* Fake resend of last ACKed byte. */
8976 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8977 
8978 		if (mp1 != NULL) {
8979 			*mp1->b_wptr++ = '\0';
8980 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8981 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8982 			freeb(mp1);
8983 			/*
8984 			 * if allocation failed, fall through to start the
8985 			 * timer back.
8986 			 */
8987 			if (mp != NULL) {
8988 				TCP_RECORD_TRACE(tcp, mp,
8989 				    TCP_TRACE_SEND_PKT);
8990 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8991 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8992 				if (tcp->tcp_ka_last_intrvl != 0) {
8993 					/*
8994 					 * We should probe again at least
8995 					 * in ka_intrvl, but not more than
8996 					 * tcp_rexmit_interval_max.
8997 					 */
8998 					firetime = MIN(ka_intrvl - 1,
8999 					    tcp->tcp_ka_last_intrvl << 1);
9000 					if (firetime > tcp_rexmit_interval_max)
9001 						firetime =
9002 						    tcp_rexmit_interval_max;
9003 				} else {
9004 					firetime = tcp->tcp_rto;
9005 				}
9006 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9007 				    tcp_keepalive_killer,
9008 				    MSEC_TO_TICK(firetime));
9009 				tcp->tcp_ka_last_intrvl = firetime;
9010 				return;
9011 			}
9012 		}
9013 	} else {
9014 		tcp->tcp_ka_last_intrvl = 0;
9015 	}
9016 
9017 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9018 	if ((firetime = ka_intrvl - idletime) < 0) {
9019 		firetime = ka_intrvl;
9020 	}
9021 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9022 	    MSEC_TO_TICK(firetime));
9023 }
9024 
9025 int
9026 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9027 {
9028 	queue_t	*q = tcp->tcp_rq;
9029 	int32_t	mss = tcp->tcp_mss;
9030 	int	maxpsz;
9031 
9032 	if (TCP_IS_DETACHED(tcp))
9033 		return (mss);
9034 
9035 	if (tcp->tcp_fused) {
9036 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9037 		mss = INFPSZ;
9038 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
9039 		/*
9040 		 * Set the sd_qn_maxpsz according to the socket send buffer
9041 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9042 		 * instruct the stream head to copyin user data into contiguous
9043 		 * kernel-allocated buffers without breaking it up into smaller
9044 		 * chunks.  We round up the buffer size to the nearest SMSS.
9045 		 */
9046 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9047 		if (tcp->tcp_kssl_ctx == NULL)
9048 			mss = INFPSZ;
9049 		else
9050 			mss = SSL3_MAX_RECORD_LEN;
9051 	} else {
9052 		/*
9053 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9054 		 * (and a multiple of the mss).  This instructs the stream
9055 		 * head to break down larger than SMSS writes into SMSS-
9056 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9057 		 */
9058 		maxpsz = tcp->tcp_maxpsz * mss;
9059 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9060 			maxpsz = tcp->tcp_xmit_hiwater/2;
9061 			/* Round up to nearest mss */
9062 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9063 		}
9064 	}
9065 	(void) setmaxps(q, maxpsz);
9066 	tcp->tcp_wq->q_maxpsz = maxpsz;
9067 
9068 	if (set_maxblk)
9069 		(void) mi_set_sth_maxblk(q, mss);
9070 
9071 	return (mss);
9072 }
9073 
9074 /*
9075  * Extract option values from a tcp header.  We put any found values into the
9076  * tcpopt struct and return a bitmask saying which options were found.
9077  */
9078 static int
9079 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9080 {
9081 	uchar_t		*endp;
9082 	int		len;
9083 	uint32_t	mss;
9084 	uchar_t		*up = (uchar_t *)tcph;
9085 	int		found = 0;
9086 	int32_t		sack_len;
9087 	tcp_seq		sack_begin, sack_end;
9088 	tcp_t		*tcp;
9089 
9090 	endp = up + TCP_HDR_LENGTH(tcph);
9091 	up += TCP_MIN_HEADER_LENGTH;
9092 	while (up < endp) {
9093 		len = endp - up;
9094 		switch (*up) {
9095 		case TCPOPT_EOL:
9096 			break;
9097 
9098 		case TCPOPT_NOP:
9099 			up++;
9100 			continue;
9101 
9102 		case TCPOPT_MAXSEG:
9103 			if (len < TCPOPT_MAXSEG_LEN ||
9104 			    up[1] != TCPOPT_MAXSEG_LEN)
9105 				break;
9106 
9107 			mss = BE16_TO_U16(up+2);
9108 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9109 			tcpopt->tcp_opt_mss = mss;
9110 			found |= TCP_OPT_MSS_PRESENT;
9111 
9112 			up += TCPOPT_MAXSEG_LEN;
9113 			continue;
9114 
9115 		case TCPOPT_WSCALE:
9116 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9117 				break;
9118 
9119 			if (up[2] > TCP_MAX_WINSHIFT)
9120 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9121 			else
9122 				tcpopt->tcp_opt_wscale = up[2];
9123 			found |= TCP_OPT_WSCALE_PRESENT;
9124 
9125 			up += TCPOPT_WS_LEN;
9126 			continue;
9127 
9128 		case TCPOPT_SACK_PERMITTED:
9129 			if (len < TCPOPT_SACK_OK_LEN ||
9130 			    up[1] != TCPOPT_SACK_OK_LEN)
9131 				break;
9132 			found |= TCP_OPT_SACK_OK_PRESENT;
9133 			up += TCPOPT_SACK_OK_LEN;
9134 			continue;
9135 
9136 		case TCPOPT_SACK:
9137 			if (len <= 2 || up[1] <= 2 || len < up[1])
9138 				break;
9139 
9140 			/* If TCP is not interested in SACK blks... */
9141 			if ((tcp = tcpopt->tcp) == NULL) {
9142 				up += up[1];
9143 				continue;
9144 			}
9145 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9146 			up += TCPOPT_HEADER_LEN;
9147 
9148 			/*
9149 			 * If the list is empty, allocate one and assume
9150 			 * nothing is sack'ed.
9151 			 */
9152 			ASSERT(tcp->tcp_sack_info != NULL);
9153 			if (tcp->tcp_notsack_list == NULL) {
9154 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9155 				    tcp->tcp_suna, tcp->tcp_snxt,
9156 				    &(tcp->tcp_num_notsack_blk),
9157 				    &(tcp->tcp_cnt_notsack_list));
9158 
9159 				/*
9160 				 * Make sure tcp_notsack_list is not NULL.
9161 				 * This happens when kmem_alloc(KM_NOSLEEP)
9162 				 * returns NULL.
9163 				 */
9164 				if (tcp->tcp_notsack_list == NULL) {
9165 					up += sack_len;
9166 					continue;
9167 				}
9168 				tcp->tcp_fack = tcp->tcp_suna;
9169 			}
9170 
9171 			while (sack_len > 0) {
9172 				if (up + 8 > endp) {
9173 					up = endp;
9174 					break;
9175 				}
9176 				sack_begin = BE32_TO_U32(up);
9177 				up += 4;
9178 				sack_end = BE32_TO_U32(up);
9179 				up += 4;
9180 				sack_len -= 8;
9181 				/*
9182 				 * Bounds checking.  Make sure the SACK
9183 				 * info is within tcp_suna and tcp_snxt.
9184 				 * If this SACK blk is out of bound, ignore
9185 				 * it but continue to parse the following
9186 				 * blks.
9187 				 */
9188 				if (SEQ_LEQ(sack_end, sack_begin) ||
9189 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9190 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9191 					continue;
9192 				}
9193 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9194 				    sack_begin, sack_end,
9195 				    &(tcp->tcp_num_notsack_blk),
9196 				    &(tcp->tcp_cnt_notsack_list));
9197 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9198 					tcp->tcp_fack = sack_end;
9199 				}
9200 			}
9201 			found |= TCP_OPT_SACK_PRESENT;
9202 			continue;
9203 
9204 		case TCPOPT_TSTAMP:
9205 			if (len < TCPOPT_TSTAMP_LEN ||
9206 			    up[1] != TCPOPT_TSTAMP_LEN)
9207 				break;
9208 
9209 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9210 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9211 
9212 			found |= TCP_OPT_TSTAMP_PRESENT;
9213 
9214 			up += TCPOPT_TSTAMP_LEN;
9215 			continue;
9216 
9217 		default:
9218 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9219 				break;
9220 			up += up[1];
9221 			continue;
9222 		}
9223 		break;
9224 	}
9225 	return (found);
9226 }
9227 
9228 /*
9229  * Set the mss associated with a particular tcp based on its current value,
9230  * and a new one passed in. Observe minimums and maximums, and reset
9231  * other state variables that we want to view as multiples of mss.
9232  *
9233  * This function is called in various places mainly because
9234  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
9235  *    other side's SYN/SYN-ACK packet arrives.
9236  * 2) PMTUd may get us a new MSS.
9237  * 3) If the other side stops sending us timestamp option, we need to
9238  *    increase the MSS size to use the extra bytes available.
9239  */
9240 static void
9241 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9242 {
9243 	uint32_t	mss_max;
9244 
9245 	if (tcp->tcp_ipversion == IPV4_VERSION)
9246 		mss_max = tcp_mss_max_ipv4;
9247 	else
9248 		mss_max = tcp_mss_max_ipv6;
9249 
9250 	if (mss < tcp_mss_min)
9251 		mss = tcp_mss_min;
9252 	if (mss > mss_max)
9253 		mss = mss_max;
9254 	/*
9255 	 * Unless naglim has been set by our client to
9256 	 * a non-mss value, force naglim to track mss.
9257 	 * This can help to aggregate small writes.
9258 	 */
9259 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9260 		tcp->tcp_naglim = mss;
9261 	/*
9262 	 * TCP should be able to buffer at least 4 MSS data for obvious
9263 	 * performance reason.
9264 	 */
9265 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9266 		tcp->tcp_xmit_hiwater = mss << 2;
9267 
9268 	/*
9269 	 * Check if we need to apply the tcp_init_cwnd here.  If
9270 	 * it is set and the MSS gets bigger (should not happen
9271 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9272 	 * The new tcp_cwnd should not get bigger.
9273 	 */
9274 	if (tcp->tcp_init_cwnd == 0) {
9275 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9276 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9277 	} else {
9278 		if (tcp->tcp_mss < mss) {
9279 			tcp->tcp_cwnd = MAX(1,
9280 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9281 		} else {
9282 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9283 		}
9284 	}
9285 	tcp->tcp_mss = mss;
9286 	tcp->tcp_cwnd_cnt = 0;
9287 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9288 }
9289 
9290 static int
9291 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9292 {
9293 	tcp_t		*tcp = NULL;
9294 	conn_t		*connp;
9295 	int		err;
9296 	dev_t		conn_dev;
9297 	zoneid_t	zoneid = getzoneid();
9298 
9299 	/*
9300 	 * Special case for install: miniroot needs to be able to access files
9301 	 * via NFS as though it were always in the global zone.
9302 	 */
9303 	if (credp == kcred && nfs_global_client_only != 0)
9304 		zoneid = GLOBAL_ZONEID;
9305 
9306 	if (q->q_ptr != NULL)
9307 		return (0);
9308 
9309 	if (sflag == MODOPEN) {
9310 		/*
9311 		 * This is a special case. The purpose of a modopen
9312 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9313 		 * through for MIB browsers. Everything else is failed.
9314 		 */
9315 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9316 
9317 		if (connp == NULL)
9318 			return (ENOMEM);
9319 
9320 		connp->conn_flags |= IPCL_TCPMOD;
9321 		connp->conn_cred = credp;
9322 		connp->conn_zoneid = zoneid;
9323 		q->q_ptr = WR(q)->q_ptr = connp;
9324 		crhold(credp);
9325 		q->q_qinfo = &tcp_mod_rinit;
9326 		WR(q)->q_qinfo = &tcp_mod_winit;
9327 		qprocson(q);
9328 		return (0);
9329 	}
9330 
9331 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9332 		return (EBUSY);
9333 
9334 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9335 
9336 	if (flag & SO_ACCEPTOR) {
9337 		q->q_qinfo = &tcp_acceptor_rinit;
9338 		q->q_ptr = (void *)conn_dev;
9339 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9340 		WR(q)->q_ptr = (void *)conn_dev;
9341 		qprocson(q);
9342 		return (0);
9343 	}
9344 
9345 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9346 	if (connp == NULL) {
9347 		inet_minor_free(ip_minor_arena, conn_dev);
9348 		q->q_ptr = NULL;
9349 		return (ENOSR);
9350 	}
9351 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9352 	tcp = connp->conn_tcp;
9353 
9354 	q->q_ptr = WR(q)->q_ptr = connp;
9355 	if (getmajor(*devp) == TCP6_MAJ) {
9356 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9357 		connp->conn_send = ip_output_v6;
9358 		connp->conn_af_isv6 = B_TRUE;
9359 		connp->conn_pkt_isv6 = B_TRUE;
9360 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9361 		tcp->tcp_ipversion = IPV6_VERSION;
9362 		tcp->tcp_family = AF_INET6;
9363 		tcp->tcp_mss = tcp_mss_def_ipv6;
9364 	} else {
9365 		connp->conn_flags |= IPCL_TCP4;
9366 		connp->conn_send = ip_output;
9367 		connp->conn_af_isv6 = B_FALSE;
9368 		connp->conn_pkt_isv6 = B_FALSE;
9369 		tcp->tcp_ipversion = IPV4_VERSION;
9370 		tcp->tcp_family = AF_INET;
9371 		tcp->tcp_mss = tcp_mss_def_ipv4;
9372 	}
9373 
9374 	/*
9375 	 * TCP keeps a copy of cred for cache locality reasons but
9376 	 * we put a reference only once. If connp->conn_cred
9377 	 * becomes invalid, tcp_cred should also be set to NULL.
9378 	 */
9379 	tcp->tcp_cred = connp->conn_cred = credp;
9380 	crhold(connp->conn_cred);
9381 	tcp->tcp_cpid = curproc->p_pid;
9382 	connp->conn_zoneid = zoneid;
9383 	connp->conn_mlp_type = mlptSingle;
9384 	connp->conn_ulp_labeled = !is_system_labeled();
9385 
9386 	/*
9387 	 * If the caller has the process-wide flag set, then default to MAC
9388 	 * exempt mode.  This allows read-down to unlabeled hosts.
9389 	 */
9390 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9391 		connp->conn_mac_exempt = B_TRUE;
9392 
9393 	connp->conn_dev = conn_dev;
9394 
9395 	ASSERT(q->q_qinfo == &tcp_rinit);
9396 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9397 
9398 	if (flag & SO_SOCKSTR) {
9399 		/*
9400 		 * No need to insert a socket in tcp acceptor hash.
9401 		 * If it was a socket acceptor stream, we dealt with
9402 		 * it above. A socket listener can never accept a
9403 		 * connection and doesn't need acceptor_id.
9404 		 */
9405 		connp->conn_flags |= IPCL_SOCKET;
9406 		tcp->tcp_issocket = 1;
9407 		WR(q)->q_qinfo = &tcp_sock_winit;
9408 	} else {
9409 #ifdef	_ILP32
9410 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9411 #else
9412 		tcp->tcp_acceptor_id = conn_dev;
9413 #endif	/* _ILP32 */
9414 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9415 	}
9416 
9417 	if (tcp_trace)
9418 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9419 
9420 	err = tcp_init(tcp, q);
9421 	if (err != 0) {
9422 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9423 		tcp_acceptor_hash_remove(tcp);
9424 		CONN_DEC_REF(connp);
9425 		q->q_ptr = WR(q)->q_ptr = NULL;
9426 		return (err);
9427 	}
9428 
9429 	RD(q)->q_hiwat = tcp_recv_hiwat;
9430 	tcp->tcp_rwnd = tcp_recv_hiwat;
9431 
9432 	/* Non-zero default values */
9433 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9434 	/*
9435 	 * Put the ref for TCP. Ref for IP was already put
9436 	 * by ipcl_conn_create. Also Make the conn_t globally
9437 	 * visible to walkers
9438 	 */
9439 	mutex_enter(&connp->conn_lock);
9440 	CONN_INC_REF_LOCKED(connp);
9441 	ASSERT(connp->conn_ref == 2);
9442 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9443 	mutex_exit(&connp->conn_lock);
9444 
9445 	qprocson(q);
9446 	return (0);
9447 }
9448 
9449 /*
9450  * Some TCP options can be "set" by requesting them in the option
9451  * buffer. This is needed for XTI feature test though we do not
9452  * allow it in general. We interpret that this mechanism is more
9453  * applicable to OSI protocols and need not be allowed in general.
9454  * This routine filters out options for which it is not allowed (most)
9455  * and lets through those (few) for which it is. [ The XTI interface
9456  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9457  * ever implemented will have to be allowed here ].
9458  */
9459 static boolean_t
9460 tcp_allow_connopt_set(int level, int name)
9461 {
9462 
9463 	switch (level) {
9464 	case IPPROTO_TCP:
9465 		switch (name) {
9466 		case TCP_NODELAY:
9467 			return (B_TRUE);
9468 		default:
9469 			return (B_FALSE);
9470 		}
9471 		/*NOTREACHED*/
9472 	default:
9473 		return (B_FALSE);
9474 	}
9475 	/*NOTREACHED*/
9476 }
9477 
9478 /*
9479  * This routine gets default values of certain options whose default
9480  * values are maintained by protocol specific code
9481  */
9482 /* ARGSUSED */
9483 int
9484 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9485 {
9486 	int32_t	*i1 = (int32_t *)ptr;
9487 
9488 	switch (level) {
9489 	case IPPROTO_TCP:
9490 		switch (name) {
9491 		case TCP_NOTIFY_THRESHOLD:
9492 			*i1 = tcp_ip_notify_interval;
9493 			break;
9494 		case TCP_ABORT_THRESHOLD:
9495 			*i1 = tcp_ip_abort_interval;
9496 			break;
9497 		case TCP_CONN_NOTIFY_THRESHOLD:
9498 			*i1 = tcp_ip_notify_cinterval;
9499 			break;
9500 		case TCP_CONN_ABORT_THRESHOLD:
9501 			*i1 = tcp_ip_abort_cinterval;
9502 			break;
9503 		default:
9504 			return (-1);
9505 		}
9506 		break;
9507 	case IPPROTO_IP:
9508 		switch (name) {
9509 		case IP_TTL:
9510 			*i1 = tcp_ipv4_ttl;
9511 			break;
9512 		default:
9513 			return (-1);
9514 		}
9515 		break;
9516 	case IPPROTO_IPV6:
9517 		switch (name) {
9518 		case IPV6_UNICAST_HOPS:
9519 			*i1 = tcp_ipv6_hoplimit;
9520 			break;
9521 		default:
9522 			return (-1);
9523 		}
9524 		break;
9525 	default:
9526 		return (-1);
9527 	}
9528 	return (sizeof (int));
9529 }
9530 
9531 
9532 /*
9533  * TCP routine to get the values of options.
9534  */
9535 int
9536 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9537 {
9538 	int		*i1 = (int *)ptr;
9539 	conn_t		*connp = Q_TO_CONN(q);
9540 	tcp_t		*tcp = connp->conn_tcp;
9541 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9542 
9543 	switch (level) {
9544 	case SOL_SOCKET:
9545 		switch (name) {
9546 		case SO_LINGER:	{
9547 			struct linger *lgr = (struct linger *)ptr;
9548 
9549 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9550 			lgr->l_linger = tcp->tcp_lingertime;
9551 			}
9552 			return (sizeof (struct linger));
9553 		case SO_DEBUG:
9554 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9555 			break;
9556 		case SO_KEEPALIVE:
9557 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9558 			break;
9559 		case SO_DONTROUTE:
9560 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9561 			break;
9562 		case SO_USELOOPBACK:
9563 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9564 			break;
9565 		case SO_BROADCAST:
9566 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9567 			break;
9568 		case SO_REUSEADDR:
9569 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9570 			break;
9571 		case SO_OOBINLINE:
9572 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9573 			break;
9574 		case SO_DGRAM_ERRIND:
9575 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9576 			break;
9577 		case SO_TYPE:
9578 			*i1 = SOCK_STREAM;
9579 			break;
9580 		case SO_SNDBUF:
9581 			*i1 = tcp->tcp_xmit_hiwater;
9582 			break;
9583 		case SO_RCVBUF:
9584 			*i1 = RD(q)->q_hiwat;
9585 			break;
9586 		case SO_SND_COPYAVOID:
9587 			*i1 = tcp->tcp_snd_zcopy_on ?
9588 			    SO_SND_COPYAVOID : 0;
9589 			break;
9590 		case SO_ANON_MLP:
9591 			*i1 = connp->conn_anon_mlp;
9592 			break;
9593 		case SO_MAC_EXEMPT:
9594 			*i1 = connp->conn_mac_exempt;
9595 			break;
9596 		default:
9597 			return (-1);
9598 		}
9599 		break;
9600 	case IPPROTO_TCP:
9601 		switch (name) {
9602 		case TCP_NODELAY:
9603 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9604 			break;
9605 		case TCP_MAXSEG:
9606 			*i1 = tcp->tcp_mss;
9607 			break;
9608 		case TCP_NOTIFY_THRESHOLD:
9609 			*i1 = (int)tcp->tcp_first_timer_threshold;
9610 			break;
9611 		case TCP_ABORT_THRESHOLD:
9612 			*i1 = tcp->tcp_second_timer_threshold;
9613 			break;
9614 		case TCP_CONN_NOTIFY_THRESHOLD:
9615 			*i1 = tcp->tcp_first_ctimer_threshold;
9616 			break;
9617 		case TCP_CONN_ABORT_THRESHOLD:
9618 			*i1 = tcp->tcp_second_ctimer_threshold;
9619 			break;
9620 		case TCP_RECVDSTADDR:
9621 			*i1 = tcp->tcp_recvdstaddr;
9622 			break;
9623 		case TCP_ANONPRIVBIND:
9624 			*i1 = tcp->tcp_anon_priv_bind;
9625 			break;
9626 		case TCP_EXCLBIND:
9627 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9628 			break;
9629 		case TCP_INIT_CWND:
9630 			*i1 = tcp->tcp_init_cwnd;
9631 			break;
9632 		case TCP_KEEPALIVE_THRESHOLD:
9633 			*i1 = tcp->tcp_ka_interval;
9634 			break;
9635 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9636 			*i1 = tcp->tcp_ka_abort_thres;
9637 			break;
9638 		case TCP_CORK:
9639 			*i1 = tcp->tcp_cork;
9640 			break;
9641 		default:
9642 			return (-1);
9643 		}
9644 		break;
9645 	case IPPROTO_IP:
9646 		if (tcp->tcp_family != AF_INET)
9647 			return (-1);
9648 		switch (name) {
9649 		case IP_OPTIONS:
9650 		case T_IP_OPTIONS: {
9651 			/*
9652 			 * This is compatible with BSD in that in only return
9653 			 * the reverse source route with the final destination
9654 			 * as the last entry. The first 4 bytes of the option
9655 			 * will contain the final destination.
9656 			 */
9657 			int	opt_len;
9658 
9659 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9660 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9661 			ASSERT(opt_len >= 0);
9662 			/* Caller ensures enough space */
9663 			if (opt_len > 0) {
9664 				/*
9665 				 * TODO: Do we have to handle getsockopt on an
9666 				 * initiator as well?
9667 				 */
9668 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9669 			}
9670 			return (0);
9671 			}
9672 		case IP_TOS:
9673 		case T_IP_TOS:
9674 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9675 			break;
9676 		case IP_TTL:
9677 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9678 			break;
9679 		case IP_NEXTHOP:
9680 			/* Handled at IP level */
9681 			return (-EINVAL);
9682 		default:
9683 			return (-1);
9684 		}
9685 		break;
9686 	case IPPROTO_IPV6:
9687 		/*
9688 		 * IPPROTO_IPV6 options are only supported for sockets
9689 		 * that are using IPv6 on the wire.
9690 		 */
9691 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9692 			return (-1);
9693 		}
9694 		switch (name) {
9695 		case IPV6_UNICAST_HOPS:
9696 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9697 			break;	/* goto sizeof (int) option return */
9698 		case IPV6_BOUND_IF:
9699 			/* Zero if not set */
9700 			*i1 = tcp->tcp_bound_if;
9701 			break;	/* goto sizeof (int) option return */
9702 		case IPV6_RECVPKTINFO:
9703 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9704 				*i1 = 1;
9705 			else
9706 				*i1 = 0;
9707 			break;	/* goto sizeof (int) option return */
9708 		case IPV6_RECVTCLASS:
9709 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9710 				*i1 = 1;
9711 			else
9712 				*i1 = 0;
9713 			break;	/* goto sizeof (int) option return */
9714 		case IPV6_RECVHOPLIMIT:
9715 			if (tcp->tcp_ipv6_recvancillary &
9716 			    TCP_IPV6_RECVHOPLIMIT)
9717 				*i1 = 1;
9718 			else
9719 				*i1 = 0;
9720 			break;	/* goto sizeof (int) option return */
9721 		case IPV6_RECVHOPOPTS:
9722 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9723 				*i1 = 1;
9724 			else
9725 				*i1 = 0;
9726 			break;	/* goto sizeof (int) option return */
9727 		case IPV6_RECVDSTOPTS:
9728 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9729 				*i1 = 1;
9730 			else
9731 				*i1 = 0;
9732 			break;	/* goto sizeof (int) option return */
9733 		case _OLD_IPV6_RECVDSTOPTS:
9734 			if (tcp->tcp_ipv6_recvancillary &
9735 			    TCP_OLD_IPV6_RECVDSTOPTS)
9736 				*i1 = 1;
9737 			else
9738 				*i1 = 0;
9739 			break;	/* goto sizeof (int) option return */
9740 		case IPV6_RECVRTHDR:
9741 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9742 				*i1 = 1;
9743 			else
9744 				*i1 = 0;
9745 			break;	/* goto sizeof (int) option return */
9746 		case IPV6_RECVRTHDRDSTOPTS:
9747 			if (tcp->tcp_ipv6_recvancillary &
9748 			    TCP_IPV6_RECVRTDSTOPTS)
9749 				*i1 = 1;
9750 			else
9751 				*i1 = 0;
9752 			break;	/* goto sizeof (int) option return */
9753 		case IPV6_PKTINFO: {
9754 			/* XXX assumes that caller has room for max size! */
9755 			struct in6_pktinfo *pkti;
9756 
9757 			pkti = (struct in6_pktinfo *)ptr;
9758 			if (ipp->ipp_fields & IPPF_IFINDEX)
9759 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9760 			else
9761 				pkti->ipi6_ifindex = 0;
9762 			if (ipp->ipp_fields & IPPF_ADDR)
9763 				pkti->ipi6_addr = ipp->ipp_addr;
9764 			else
9765 				pkti->ipi6_addr = ipv6_all_zeros;
9766 			return (sizeof (struct in6_pktinfo));
9767 		}
9768 		case IPV6_TCLASS:
9769 			if (ipp->ipp_fields & IPPF_TCLASS)
9770 				*i1 = ipp->ipp_tclass;
9771 			else
9772 				*i1 = IPV6_FLOW_TCLASS(
9773 				    IPV6_DEFAULT_VERS_AND_FLOW);
9774 			break;	/* goto sizeof (int) option return */
9775 		case IPV6_NEXTHOP: {
9776 			sin6_t *sin6 = (sin6_t *)ptr;
9777 
9778 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9779 				return (0);
9780 			*sin6 = sin6_null;
9781 			sin6->sin6_family = AF_INET6;
9782 			sin6->sin6_addr = ipp->ipp_nexthop;
9783 			return (sizeof (sin6_t));
9784 		}
9785 		case IPV6_HOPOPTS:
9786 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9787 				return (0);
9788 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9789 				return (0);
9790 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9791 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9792 			if (tcp->tcp_label_len > 0) {
9793 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9794 				ptr[1] = (ipp->ipp_hopoptslen -
9795 				    tcp->tcp_label_len + 7) / 8 - 1;
9796 			}
9797 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9798 		case IPV6_RTHDRDSTOPTS:
9799 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9800 				return (0);
9801 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9802 			return (ipp->ipp_rtdstoptslen);
9803 		case IPV6_RTHDR:
9804 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9805 				return (0);
9806 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9807 			return (ipp->ipp_rthdrlen);
9808 		case IPV6_DSTOPTS:
9809 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9810 				return (0);
9811 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9812 			return (ipp->ipp_dstoptslen);
9813 		case IPV6_SRC_PREFERENCES:
9814 			return (ip6_get_src_preferences(connp,
9815 			    (uint32_t *)ptr));
9816 		case IPV6_PATHMTU: {
9817 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9818 
9819 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9820 				return (-1);
9821 
9822 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9823 				connp->conn_fport, mtuinfo));
9824 		}
9825 		default:
9826 			return (-1);
9827 		}
9828 		break;
9829 	default:
9830 		return (-1);
9831 	}
9832 	return (sizeof (int));
9833 }
9834 
9835 /*
9836  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9837  * Parameters are assumed to be verified by the caller.
9838  */
9839 /* ARGSUSED */
9840 int
9841 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9842     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9843     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9844 {
9845 	conn_t	*connp = Q_TO_CONN(q);
9846 	tcp_t	*tcp = connp->conn_tcp;
9847 	int	*i1 = (int *)invalp;
9848 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9849 	boolean_t checkonly;
9850 	int	reterr;
9851 
9852 	switch (optset_context) {
9853 	case SETFN_OPTCOM_CHECKONLY:
9854 		checkonly = B_TRUE;
9855 		/*
9856 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9857 		 * inlen != 0 implies value supplied and
9858 		 * 	we have to "pretend" to set it.
9859 		 * inlen == 0 implies that there is no
9860 		 * 	value part in T_CHECK request and just validation
9861 		 * done elsewhere should be enough, we just return here.
9862 		 */
9863 		if (inlen == 0) {
9864 			*outlenp = 0;
9865 			return (0);
9866 		}
9867 		break;
9868 	case SETFN_OPTCOM_NEGOTIATE:
9869 		checkonly = B_FALSE;
9870 		break;
9871 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9872 	case SETFN_CONN_NEGOTIATE:
9873 		checkonly = B_FALSE;
9874 		/*
9875 		 * Negotiating local and "association-related" options
9876 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9877 		 * primitives is allowed by XTI, but we choose
9878 		 * to not implement this style negotiation for Internet
9879 		 * protocols (We interpret it is a must for OSI world but
9880 		 * optional for Internet protocols) for all options.
9881 		 * [ Will do only for the few options that enable test
9882 		 * suites that our XTI implementation of this feature
9883 		 * works for transports that do allow it ]
9884 		 */
9885 		if (!tcp_allow_connopt_set(level, name)) {
9886 			*outlenp = 0;
9887 			return (EINVAL);
9888 		}
9889 		break;
9890 	default:
9891 		/*
9892 		 * We should never get here
9893 		 */
9894 		*outlenp = 0;
9895 		return (EINVAL);
9896 	}
9897 
9898 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9899 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9900 
9901 	/*
9902 	 * For TCP, we should have no ancillary data sent down
9903 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9904 	 * has to be zero.
9905 	 */
9906 	ASSERT(thisdg_attrs == NULL);
9907 
9908 	/*
9909 	 * For fixed length options, no sanity check
9910 	 * of passed in length is done. It is assumed *_optcom_req()
9911 	 * routines do the right thing.
9912 	 */
9913 
9914 	switch (level) {
9915 	case SOL_SOCKET:
9916 		switch (name) {
9917 		case SO_LINGER: {
9918 			struct linger *lgr = (struct linger *)invalp;
9919 
9920 			if (!checkonly) {
9921 				if (lgr->l_onoff) {
9922 					tcp->tcp_linger = 1;
9923 					tcp->tcp_lingertime = lgr->l_linger;
9924 				} else {
9925 					tcp->tcp_linger = 0;
9926 					tcp->tcp_lingertime = 0;
9927 				}
9928 				/* struct copy */
9929 				*(struct linger *)outvalp = *lgr;
9930 			} else {
9931 				if (!lgr->l_onoff) {
9932 				    ((struct linger *)outvalp)->l_onoff = 0;
9933 				    ((struct linger *)outvalp)->l_linger = 0;
9934 				} else {
9935 				    /* struct copy */
9936 				    *(struct linger *)outvalp = *lgr;
9937 				}
9938 			}
9939 			*outlenp = sizeof (struct linger);
9940 			return (0);
9941 		}
9942 		case SO_DEBUG:
9943 			if (!checkonly)
9944 				tcp->tcp_debug = onoff;
9945 			break;
9946 		case SO_KEEPALIVE:
9947 			if (checkonly) {
9948 				/* T_CHECK case */
9949 				break;
9950 			}
9951 
9952 			if (!onoff) {
9953 				if (tcp->tcp_ka_enabled) {
9954 					if (tcp->tcp_ka_tid != 0) {
9955 						(void) TCP_TIMER_CANCEL(tcp,
9956 						    tcp->tcp_ka_tid);
9957 						tcp->tcp_ka_tid = 0;
9958 					}
9959 					tcp->tcp_ka_enabled = 0;
9960 				}
9961 				break;
9962 			}
9963 			if (!tcp->tcp_ka_enabled) {
9964 				/* Crank up the keepalive timer */
9965 				tcp->tcp_ka_last_intrvl = 0;
9966 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9967 				    tcp_keepalive_killer,
9968 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9969 				tcp->tcp_ka_enabled = 1;
9970 			}
9971 			break;
9972 		case SO_DONTROUTE:
9973 			/*
9974 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
9975 			 * only of interest to IP.  We track them here only so
9976 			 * that we can report their current value.
9977 			 */
9978 			if (!checkonly) {
9979 				tcp->tcp_dontroute = onoff;
9980 				tcp->tcp_connp->conn_dontroute = onoff;
9981 			}
9982 			break;
9983 		case SO_USELOOPBACK:
9984 			if (!checkonly) {
9985 				tcp->tcp_useloopback = onoff;
9986 				tcp->tcp_connp->conn_loopback = onoff;
9987 			}
9988 			break;
9989 		case SO_BROADCAST:
9990 			if (!checkonly) {
9991 				tcp->tcp_broadcast = onoff;
9992 				tcp->tcp_connp->conn_broadcast = onoff;
9993 			}
9994 			break;
9995 		case SO_REUSEADDR:
9996 			if (!checkonly) {
9997 				tcp->tcp_reuseaddr = onoff;
9998 				tcp->tcp_connp->conn_reuseaddr = onoff;
9999 			}
10000 			break;
10001 		case SO_OOBINLINE:
10002 			if (!checkonly)
10003 				tcp->tcp_oobinline = onoff;
10004 			break;
10005 		case SO_DGRAM_ERRIND:
10006 			if (!checkonly)
10007 				tcp->tcp_dgram_errind = onoff;
10008 			break;
10009 		case SO_SNDBUF: {
10010 			tcp_t *peer_tcp;
10011 
10012 			if (*i1 > tcp_max_buf) {
10013 				*outlenp = 0;
10014 				return (ENOBUFS);
10015 			}
10016 			if (checkonly)
10017 				break;
10018 
10019 			tcp->tcp_xmit_hiwater = *i1;
10020 			if (tcp_snd_lowat_fraction != 0)
10021 				tcp->tcp_xmit_lowater =
10022 				    tcp->tcp_xmit_hiwater /
10023 				    tcp_snd_lowat_fraction;
10024 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10025 			/*
10026 			 * If we are flow-controlled, recheck the condition.
10027 			 * There are apps that increase SO_SNDBUF size when
10028 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10029 			 * control condition to be lifted right away.
10030 			 *
10031 			 * For the fused tcp loopback case, in order to avoid
10032 			 * a race with the peer's tcp_fuse_rrw() we need to
10033 			 * hold its fuse_lock while accessing tcp_flow_stopped.
10034 			 */
10035 			peer_tcp = tcp->tcp_loopback_peer;
10036 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
10037 			if (tcp->tcp_fused)
10038 				mutex_enter(&peer_tcp->tcp_fuse_lock);
10039 
10040 			if (tcp->tcp_flow_stopped &&
10041 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10042 				tcp_clrqfull(tcp);
10043 			}
10044 			if (tcp->tcp_fused)
10045 				mutex_exit(&peer_tcp->tcp_fuse_lock);
10046 			break;
10047 		}
10048 		case SO_RCVBUF:
10049 			if (*i1 > tcp_max_buf) {
10050 				*outlenp = 0;
10051 				return (ENOBUFS);
10052 			}
10053 			/* Silently ignore zero */
10054 			if (!checkonly && *i1 != 0) {
10055 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10056 				(void) tcp_rwnd_set(tcp, *i1);
10057 			}
10058 			/*
10059 			 * XXX should we return the rwnd here
10060 			 * and tcp_opt_get ?
10061 			 */
10062 			break;
10063 		case SO_SND_COPYAVOID:
10064 			if (!checkonly) {
10065 				/* we only allow enable at most once for now */
10066 				if (tcp->tcp_loopback ||
10067 				    (!tcp->tcp_snd_zcopy_aware &&
10068 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10069 					*outlenp = 0;
10070 					return (EOPNOTSUPP);
10071 				}
10072 				tcp->tcp_snd_zcopy_aware = 1;
10073 			}
10074 			break;
10075 		case SO_ANON_MLP:
10076 			if (!checkonly) {
10077 				mutex_enter(&connp->conn_lock);
10078 				connp->conn_anon_mlp = onoff;
10079 				mutex_exit(&connp->conn_lock);
10080 			}
10081 			break;
10082 		case SO_MAC_EXEMPT:
10083 			if (secpolicy_net_mac_aware(cr) != 0 ||
10084 			    IPCL_IS_BOUND(connp))
10085 				return (EACCES);
10086 			if (!checkonly) {
10087 				mutex_enter(&connp->conn_lock);
10088 				connp->conn_mac_exempt = onoff;
10089 				mutex_exit(&connp->conn_lock);
10090 			}
10091 			break;
10092 		default:
10093 			*outlenp = 0;
10094 			return (EINVAL);
10095 		}
10096 		break;
10097 	case IPPROTO_TCP:
10098 		switch (name) {
10099 		case TCP_NODELAY:
10100 			if (!checkonly)
10101 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10102 			break;
10103 		case TCP_NOTIFY_THRESHOLD:
10104 			if (!checkonly)
10105 				tcp->tcp_first_timer_threshold = *i1;
10106 			break;
10107 		case TCP_ABORT_THRESHOLD:
10108 			if (!checkonly)
10109 				tcp->tcp_second_timer_threshold = *i1;
10110 			break;
10111 		case TCP_CONN_NOTIFY_THRESHOLD:
10112 			if (!checkonly)
10113 				tcp->tcp_first_ctimer_threshold = *i1;
10114 			break;
10115 		case TCP_CONN_ABORT_THRESHOLD:
10116 			if (!checkonly)
10117 				tcp->tcp_second_ctimer_threshold = *i1;
10118 			break;
10119 		case TCP_RECVDSTADDR:
10120 			if (tcp->tcp_state > TCPS_LISTEN)
10121 				return (EOPNOTSUPP);
10122 			if (!checkonly)
10123 				tcp->tcp_recvdstaddr = onoff;
10124 			break;
10125 		case TCP_ANONPRIVBIND:
10126 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
10127 				*outlenp = 0;
10128 				return (reterr);
10129 			}
10130 			if (!checkonly) {
10131 				tcp->tcp_anon_priv_bind = onoff;
10132 			}
10133 			break;
10134 		case TCP_EXCLBIND:
10135 			if (!checkonly)
10136 				tcp->tcp_exclbind = onoff;
10137 			break;	/* goto sizeof (int) option return */
10138 		case TCP_INIT_CWND: {
10139 			uint32_t init_cwnd = *((uint32_t *)invalp);
10140 
10141 			if (checkonly)
10142 				break;
10143 
10144 			/*
10145 			 * Only allow socket with network configuration
10146 			 * privilege to set the initial cwnd to be larger
10147 			 * than allowed by RFC 3390.
10148 			 */
10149 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10150 				tcp->tcp_init_cwnd = init_cwnd;
10151 				break;
10152 			}
10153 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
10154 				*outlenp = 0;
10155 				return (reterr);
10156 			}
10157 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10158 				*outlenp = 0;
10159 				return (EINVAL);
10160 			}
10161 			tcp->tcp_init_cwnd = init_cwnd;
10162 			break;
10163 		}
10164 		case TCP_KEEPALIVE_THRESHOLD:
10165 			if (checkonly)
10166 				break;
10167 
10168 			if (*i1 < tcp_keepalive_interval_low ||
10169 			    *i1 > tcp_keepalive_interval_high) {
10170 				*outlenp = 0;
10171 				return (EINVAL);
10172 			}
10173 			if (*i1 != tcp->tcp_ka_interval) {
10174 				tcp->tcp_ka_interval = *i1;
10175 				/*
10176 				 * Check if we need to restart the
10177 				 * keepalive timer.
10178 				 */
10179 				if (tcp->tcp_ka_tid != 0) {
10180 					ASSERT(tcp->tcp_ka_enabled);
10181 					(void) TCP_TIMER_CANCEL(tcp,
10182 					    tcp->tcp_ka_tid);
10183 					tcp->tcp_ka_last_intrvl = 0;
10184 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10185 					    tcp_keepalive_killer,
10186 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10187 				}
10188 			}
10189 			break;
10190 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10191 			if (!checkonly) {
10192 				if (*i1 < tcp_keepalive_abort_interval_low ||
10193 				    *i1 > tcp_keepalive_abort_interval_high) {
10194 					*outlenp = 0;
10195 					return (EINVAL);
10196 				}
10197 				tcp->tcp_ka_abort_thres = *i1;
10198 			}
10199 			break;
10200 		case TCP_CORK:
10201 			if (!checkonly) {
10202 				/*
10203 				 * if tcp->tcp_cork was set and is now
10204 				 * being unset, we have to make sure that
10205 				 * the remaining data gets sent out. Also
10206 				 * unset tcp->tcp_cork so that tcp_wput_data()
10207 				 * can send data even if it is less than mss
10208 				 */
10209 				if (tcp->tcp_cork && onoff == 0 &&
10210 				    tcp->tcp_unsent > 0) {
10211 					tcp->tcp_cork = B_FALSE;
10212 					tcp_wput_data(tcp, NULL, B_FALSE);
10213 				}
10214 				tcp->tcp_cork = onoff;
10215 			}
10216 			break;
10217 		default:
10218 			*outlenp = 0;
10219 			return (EINVAL);
10220 		}
10221 		break;
10222 	case IPPROTO_IP:
10223 		if (tcp->tcp_family != AF_INET) {
10224 			*outlenp = 0;
10225 			return (ENOPROTOOPT);
10226 		}
10227 		switch (name) {
10228 		case IP_OPTIONS:
10229 		case T_IP_OPTIONS:
10230 			reterr = tcp_opt_set_header(tcp, checkonly,
10231 			    invalp, inlen);
10232 			if (reterr) {
10233 				*outlenp = 0;
10234 				return (reterr);
10235 			}
10236 			/* OK return - copy input buffer into output buffer */
10237 			if (invalp != outvalp) {
10238 				/* don't trust bcopy for identical src/dst */
10239 				bcopy(invalp, outvalp, inlen);
10240 			}
10241 			*outlenp = inlen;
10242 			return (0);
10243 		case IP_TOS:
10244 		case T_IP_TOS:
10245 			if (!checkonly) {
10246 				tcp->tcp_ipha->ipha_type_of_service =
10247 				    (uchar_t)*i1;
10248 				tcp->tcp_tos = (uchar_t)*i1;
10249 			}
10250 			break;
10251 		case IP_TTL:
10252 			if (!checkonly) {
10253 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10254 				tcp->tcp_ttl = (uchar_t)*i1;
10255 			}
10256 			break;
10257 		case IP_BOUND_IF:
10258 		case IP_NEXTHOP:
10259 			/* Handled at the IP level */
10260 			return (-EINVAL);
10261 		case IP_SEC_OPT:
10262 			/*
10263 			 * We should not allow policy setting after
10264 			 * we start listening for connections.
10265 			 */
10266 			if (tcp->tcp_state == TCPS_LISTEN) {
10267 				return (EINVAL);
10268 			} else {
10269 				/* Handled at the IP level */
10270 				return (-EINVAL);
10271 			}
10272 		default:
10273 			*outlenp = 0;
10274 			return (EINVAL);
10275 		}
10276 		break;
10277 	case IPPROTO_IPV6: {
10278 		ip6_pkt_t		*ipp;
10279 
10280 		/*
10281 		 * IPPROTO_IPV6 options are only supported for sockets
10282 		 * that are using IPv6 on the wire.
10283 		 */
10284 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10285 			*outlenp = 0;
10286 			return (ENOPROTOOPT);
10287 		}
10288 		/*
10289 		 * Only sticky options; no ancillary data
10290 		 */
10291 		ASSERT(thisdg_attrs == NULL);
10292 		ipp = &tcp->tcp_sticky_ipp;
10293 
10294 		switch (name) {
10295 		case IPV6_UNICAST_HOPS:
10296 			/* -1 means use default */
10297 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10298 				*outlenp = 0;
10299 				return (EINVAL);
10300 			}
10301 			if (!checkonly) {
10302 				if (*i1 == -1) {
10303 					tcp->tcp_ip6h->ip6_hops =
10304 					    ipp->ipp_unicast_hops =
10305 					    (uint8_t)tcp_ipv6_hoplimit;
10306 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10307 					/* Pass modified value to IP. */
10308 					*i1 = tcp->tcp_ip6h->ip6_hops;
10309 				} else {
10310 					tcp->tcp_ip6h->ip6_hops =
10311 					    ipp->ipp_unicast_hops =
10312 					    (uint8_t)*i1;
10313 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10314 				}
10315 				reterr = tcp_build_hdrs(q, tcp);
10316 				if (reterr != 0)
10317 					return (reterr);
10318 			}
10319 			break;
10320 		case IPV6_BOUND_IF:
10321 			if (!checkonly) {
10322 				int error = 0;
10323 
10324 				tcp->tcp_bound_if = *i1;
10325 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10326 				    B_TRUE, checkonly, level, name, mblk);
10327 				if (error != 0) {
10328 					*outlenp = 0;
10329 					return (error);
10330 				}
10331 			}
10332 			break;
10333 		/*
10334 		 * Set boolean switches for ancillary data delivery
10335 		 */
10336 		case IPV6_RECVPKTINFO:
10337 			if (!checkonly) {
10338 				if (onoff)
10339 					tcp->tcp_ipv6_recvancillary |=
10340 					    TCP_IPV6_RECVPKTINFO;
10341 				else
10342 					tcp->tcp_ipv6_recvancillary &=
10343 					    ~TCP_IPV6_RECVPKTINFO;
10344 				/* Force it to be sent up with the next msg */
10345 				tcp->tcp_recvifindex = 0;
10346 			}
10347 			break;
10348 		case IPV6_RECVTCLASS:
10349 			if (!checkonly) {
10350 				if (onoff)
10351 					tcp->tcp_ipv6_recvancillary |=
10352 					    TCP_IPV6_RECVTCLASS;
10353 				else
10354 					tcp->tcp_ipv6_recvancillary &=
10355 					    ~TCP_IPV6_RECVTCLASS;
10356 			}
10357 			break;
10358 		case IPV6_RECVHOPLIMIT:
10359 			if (!checkonly) {
10360 				if (onoff)
10361 					tcp->tcp_ipv6_recvancillary |=
10362 					    TCP_IPV6_RECVHOPLIMIT;
10363 				else
10364 					tcp->tcp_ipv6_recvancillary &=
10365 					    ~TCP_IPV6_RECVHOPLIMIT;
10366 				/* Force it to be sent up with the next msg */
10367 				tcp->tcp_recvhops = 0xffffffffU;
10368 			}
10369 			break;
10370 		case IPV6_RECVHOPOPTS:
10371 			if (!checkonly) {
10372 				if (onoff)
10373 					tcp->tcp_ipv6_recvancillary |=
10374 					    TCP_IPV6_RECVHOPOPTS;
10375 				else
10376 					tcp->tcp_ipv6_recvancillary &=
10377 					    ~TCP_IPV6_RECVHOPOPTS;
10378 			}
10379 			break;
10380 		case IPV6_RECVDSTOPTS:
10381 			if (!checkonly) {
10382 				if (onoff)
10383 					tcp->tcp_ipv6_recvancillary |=
10384 					    TCP_IPV6_RECVDSTOPTS;
10385 				else
10386 					tcp->tcp_ipv6_recvancillary &=
10387 					    ~TCP_IPV6_RECVDSTOPTS;
10388 			}
10389 			break;
10390 		case _OLD_IPV6_RECVDSTOPTS:
10391 			if (!checkonly) {
10392 				if (onoff)
10393 					tcp->tcp_ipv6_recvancillary |=
10394 					    TCP_OLD_IPV6_RECVDSTOPTS;
10395 				else
10396 					tcp->tcp_ipv6_recvancillary &=
10397 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10398 			}
10399 			break;
10400 		case IPV6_RECVRTHDR:
10401 			if (!checkonly) {
10402 				if (onoff)
10403 					tcp->tcp_ipv6_recvancillary |=
10404 					    TCP_IPV6_RECVRTHDR;
10405 				else
10406 					tcp->tcp_ipv6_recvancillary &=
10407 					    ~TCP_IPV6_RECVRTHDR;
10408 			}
10409 			break;
10410 		case IPV6_RECVRTHDRDSTOPTS:
10411 			if (!checkonly) {
10412 				if (onoff)
10413 					tcp->tcp_ipv6_recvancillary |=
10414 					    TCP_IPV6_RECVRTDSTOPTS;
10415 				else
10416 					tcp->tcp_ipv6_recvancillary &=
10417 					    ~TCP_IPV6_RECVRTDSTOPTS;
10418 			}
10419 			break;
10420 		case IPV6_PKTINFO:
10421 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10422 				return (EINVAL);
10423 			if (checkonly)
10424 				break;
10425 
10426 			if (inlen == 0) {
10427 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10428 			} else {
10429 				struct in6_pktinfo *pkti;
10430 
10431 				pkti = (struct in6_pktinfo *)invalp;
10432 				/*
10433 				 * RFC 3542 states that ipi6_addr must be
10434 				 * the unspecified address when setting the
10435 				 * IPV6_PKTINFO sticky socket option on a
10436 				 * TCP socket.
10437 				 */
10438 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10439 					return (EINVAL);
10440 				/*
10441 				 * ip6_set_pktinfo() validates the source
10442 				 * address and interface index.
10443 				 */
10444 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10445 				    pkti, mblk);
10446 				if (reterr != 0)
10447 					return (reterr);
10448 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10449 				ipp->ipp_addr = pkti->ipi6_addr;
10450 				if (ipp->ipp_ifindex != 0)
10451 					ipp->ipp_fields |= IPPF_IFINDEX;
10452 				else
10453 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10454 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10455 					ipp->ipp_fields |= IPPF_ADDR;
10456 				else
10457 					ipp->ipp_fields &= ~IPPF_ADDR;
10458 			}
10459 			reterr = tcp_build_hdrs(q, tcp);
10460 			if (reterr != 0)
10461 				return (reterr);
10462 			break;
10463 		case IPV6_TCLASS:
10464 			if (inlen != 0 && inlen != sizeof (int))
10465 				return (EINVAL);
10466 			if (checkonly)
10467 				break;
10468 
10469 			if (inlen == 0) {
10470 				ipp->ipp_fields &= ~IPPF_TCLASS;
10471 			} else {
10472 				if (*i1 > 255 || *i1 < -1)
10473 					return (EINVAL);
10474 				if (*i1 == -1) {
10475 					ipp->ipp_tclass = 0;
10476 					*i1 = 0;
10477 				} else {
10478 					ipp->ipp_tclass = *i1;
10479 				}
10480 				ipp->ipp_fields |= IPPF_TCLASS;
10481 			}
10482 			reterr = tcp_build_hdrs(q, tcp);
10483 			if (reterr != 0)
10484 				return (reterr);
10485 			break;
10486 		case IPV6_NEXTHOP:
10487 			/*
10488 			 * IP will verify that the nexthop is reachable
10489 			 * and fail for sticky options.
10490 			 */
10491 			if (inlen != 0 && inlen != sizeof (sin6_t))
10492 				return (EINVAL);
10493 			if (checkonly)
10494 				break;
10495 
10496 			if (inlen == 0) {
10497 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10498 			} else {
10499 				sin6_t *sin6 = (sin6_t *)invalp;
10500 
10501 				if (sin6->sin6_family != AF_INET6)
10502 					return (EAFNOSUPPORT);
10503 				if (IN6_IS_ADDR_V4MAPPED(
10504 				    &sin6->sin6_addr))
10505 					return (EADDRNOTAVAIL);
10506 				ipp->ipp_nexthop = sin6->sin6_addr;
10507 				if (!IN6_IS_ADDR_UNSPECIFIED(
10508 				    &ipp->ipp_nexthop))
10509 					ipp->ipp_fields |= IPPF_NEXTHOP;
10510 				else
10511 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10512 			}
10513 			reterr = tcp_build_hdrs(q, tcp);
10514 			if (reterr != 0)
10515 				return (reterr);
10516 			break;
10517 		case IPV6_HOPOPTS: {
10518 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10519 
10520 			/*
10521 			 * Sanity checks - minimum size, size a multiple of
10522 			 * eight bytes, and matching size passed in.
10523 			 */
10524 			if (inlen != 0 &&
10525 			    inlen != (8 * (hopts->ip6h_len + 1)))
10526 				return (EINVAL);
10527 
10528 			if (checkonly)
10529 				break;
10530 
10531 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10532 			    (uchar_t **)&ipp->ipp_hopopts,
10533 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10534 			if (reterr != 0)
10535 				return (reterr);
10536 			if (ipp->ipp_hopoptslen == 0)
10537 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10538 			else
10539 				ipp->ipp_fields |= IPPF_HOPOPTS;
10540 			reterr = tcp_build_hdrs(q, tcp);
10541 			if (reterr != 0)
10542 				return (reterr);
10543 			break;
10544 		}
10545 		case IPV6_RTHDRDSTOPTS: {
10546 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10547 
10548 			/*
10549 			 * Sanity checks - minimum size, size a multiple of
10550 			 * eight bytes, and matching size passed in.
10551 			 */
10552 			if (inlen != 0 &&
10553 			    inlen != (8 * (dopts->ip6d_len + 1)))
10554 				return (EINVAL);
10555 
10556 			if (checkonly)
10557 				break;
10558 
10559 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10560 			    (uchar_t **)&ipp->ipp_rtdstopts,
10561 			    &ipp->ipp_rtdstoptslen, 0);
10562 			if (reterr != 0)
10563 				return (reterr);
10564 			if (ipp->ipp_rtdstoptslen == 0)
10565 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10566 			else
10567 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10568 			reterr = tcp_build_hdrs(q, tcp);
10569 			if (reterr != 0)
10570 				return (reterr);
10571 			break;
10572 		}
10573 		case IPV6_DSTOPTS: {
10574 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10575 
10576 			/*
10577 			 * Sanity checks - minimum size, size a multiple of
10578 			 * eight bytes, and matching size passed in.
10579 			 */
10580 			if (inlen != 0 &&
10581 			    inlen != (8 * (dopts->ip6d_len + 1)))
10582 				return (EINVAL);
10583 
10584 			if (checkonly)
10585 				break;
10586 
10587 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10588 			    (uchar_t **)&ipp->ipp_dstopts,
10589 			    &ipp->ipp_dstoptslen, 0);
10590 			if (reterr != 0)
10591 				return (reterr);
10592 			if (ipp->ipp_dstoptslen == 0)
10593 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10594 			else
10595 				ipp->ipp_fields |= IPPF_DSTOPTS;
10596 			reterr = tcp_build_hdrs(q, tcp);
10597 			if (reterr != 0)
10598 				return (reterr);
10599 			break;
10600 		}
10601 		case IPV6_RTHDR: {
10602 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10603 
10604 			/*
10605 			 * Sanity checks - minimum size, size a multiple of
10606 			 * eight bytes, and matching size passed in.
10607 			 */
10608 			if (inlen != 0 &&
10609 			    inlen != (8 * (rt->ip6r_len + 1)))
10610 				return (EINVAL);
10611 
10612 			if (checkonly)
10613 				break;
10614 
10615 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10616 			    (uchar_t **)&ipp->ipp_rthdr,
10617 			    &ipp->ipp_rthdrlen, 0);
10618 			if (reterr != 0)
10619 				return (reterr);
10620 			if (ipp->ipp_rthdrlen == 0)
10621 				ipp->ipp_fields &= ~IPPF_RTHDR;
10622 			else
10623 				ipp->ipp_fields |= IPPF_RTHDR;
10624 			reterr = tcp_build_hdrs(q, tcp);
10625 			if (reterr != 0)
10626 				return (reterr);
10627 			break;
10628 		}
10629 		case IPV6_V6ONLY:
10630 			if (!checkonly)
10631 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10632 			break;
10633 		case IPV6_USE_MIN_MTU:
10634 			if (inlen != sizeof (int))
10635 				return (EINVAL);
10636 
10637 			if (*i1 < -1 || *i1 > 1)
10638 				return (EINVAL);
10639 
10640 			if (checkonly)
10641 				break;
10642 
10643 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10644 			ipp->ipp_use_min_mtu = *i1;
10645 			break;
10646 		case IPV6_BOUND_PIF:
10647 			/* Handled at the IP level */
10648 			return (-EINVAL);
10649 		case IPV6_SEC_OPT:
10650 			/*
10651 			 * We should not allow policy setting after
10652 			 * we start listening for connections.
10653 			 */
10654 			if (tcp->tcp_state == TCPS_LISTEN) {
10655 				return (EINVAL);
10656 			} else {
10657 				/* Handled at the IP level */
10658 				return (-EINVAL);
10659 			}
10660 		case IPV6_SRC_PREFERENCES:
10661 			if (inlen != sizeof (uint32_t))
10662 				return (EINVAL);
10663 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10664 			    *(uint32_t *)invalp);
10665 			if (reterr != 0) {
10666 				*outlenp = 0;
10667 				return (reterr);
10668 			}
10669 			break;
10670 		default:
10671 			*outlenp = 0;
10672 			return (EINVAL);
10673 		}
10674 		break;
10675 	}		/* end IPPROTO_IPV6 */
10676 	default:
10677 		*outlenp = 0;
10678 		return (EINVAL);
10679 	}
10680 	/*
10681 	 * Common case of OK return with outval same as inval
10682 	 */
10683 	if (invalp != outvalp) {
10684 		/* don't trust bcopy for identical src/dst */
10685 		(void) bcopy(invalp, outvalp, inlen);
10686 	}
10687 	*outlenp = inlen;
10688 	return (0);
10689 }
10690 
10691 /*
10692  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10693  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10694  * headers, and the maximum size tcp header (to avoid reallocation
10695  * on the fly for additional tcp options).
10696  * Returns failure if can't allocate memory.
10697  */
10698 static int
10699 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10700 {
10701 	char	*hdrs;
10702 	uint_t	hdrs_len;
10703 	ip6i_t	*ip6i;
10704 	char	buf[TCP_MAX_HDR_LENGTH];
10705 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10706 	in6_addr_t src, dst;
10707 
10708 	/*
10709 	 * save the existing tcp header and source/dest IP addresses
10710 	 */
10711 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10712 	src = tcp->tcp_ip6h->ip6_src;
10713 	dst = tcp->tcp_ip6h->ip6_dst;
10714 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10715 	ASSERT(hdrs_len != 0);
10716 	if (hdrs_len > tcp->tcp_iphc_len) {
10717 		/* Need to reallocate */
10718 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10719 		if (hdrs == NULL)
10720 			return (ENOMEM);
10721 		if (tcp->tcp_iphc != NULL) {
10722 			if (tcp->tcp_hdr_grown) {
10723 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10724 			} else {
10725 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10726 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10727 			}
10728 			tcp->tcp_iphc_len = 0;
10729 		}
10730 		ASSERT(tcp->tcp_iphc_len == 0);
10731 		tcp->tcp_iphc = hdrs;
10732 		tcp->tcp_iphc_len = hdrs_len;
10733 		tcp->tcp_hdr_grown = B_TRUE;
10734 	}
10735 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10736 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10737 
10738 	/* Set header fields not in ipp */
10739 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10740 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10741 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10742 	} else {
10743 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10744 	}
10745 	/*
10746 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10747 	 *
10748 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10749 	 */
10750 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10751 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10752 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10753 
10754 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10755 
10756 	tcp->tcp_ip6h->ip6_src = src;
10757 	tcp->tcp_ip6h->ip6_dst = dst;
10758 
10759 	/*
10760 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10761 	 * the default value for TCP.
10762 	 */
10763 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10764 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10765 
10766 	/*
10767 	 * If we're setting extension headers after a connection
10768 	 * has been established, and if we have a routing header
10769 	 * among the extension headers, call ip_massage_options_v6 to
10770 	 * manipulate the routing header/ip6_dst set the checksum
10771 	 * difference in the tcp header template.
10772 	 * (This happens in tcp_connect_ipv6 if the routing header
10773 	 * is set prior to the connect.)
10774 	 * Set the tcp_sum to zero first in case we've cleared a
10775 	 * routing header or don't have one at all.
10776 	 */
10777 	tcp->tcp_sum = 0;
10778 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10779 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10780 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10781 		    (uint8_t *)tcp->tcp_tcph);
10782 		if (rth != NULL) {
10783 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10784 			    rth);
10785 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10786 			    (tcp->tcp_sum >> 16));
10787 		}
10788 	}
10789 
10790 	/* Try to get everything in a single mblk */
10791 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10792 	return (0);
10793 }
10794 
10795 /*
10796  * Transfer any source route option from ipha to buf/dst in reversed form.
10797  */
10798 static int
10799 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10800 {
10801 	ipoptp_t	opts;
10802 	uchar_t		*opt;
10803 	uint8_t		optval;
10804 	uint8_t		optlen;
10805 	uint32_t	len = 0;
10806 
10807 	for (optval = ipoptp_first(&opts, ipha);
10808 	    optval != IPOPT_EOL;
10809 	    optval = ipoptp_next(&opts)) {
10810 		opt = opts.ipoptp_cur;
10811 		optlen = opts.ipoptp_len;
10812 		switch (optval) {
10813 			int	off1, off2;
10814 		case IPOPT_SSRR:
10815 		case IPOPT_LSRR:
10816 
10817 			/* Reverse source route */
10818 			/*
10819 			 * First entry should be the next to last one in the
10820 			 * current source route (the last entry is our
10821 			 * address.)
10822 			 * The last entry should be the final destination.
10823 			 */
10824 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10825 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10826 			off1 = IPOPT_MINOFF_SR - 1;
10827 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10828 			if (off2 < 0) {
10829 				/* No entries in source route */
10830 				break;
10831 			}
10832 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10833 			/*
10834 			 * Note: use src since ipha has not had its src
10835 			 * and dst reversed (it is in the state it was
10836 			 * received.
10837 			 */
10838 			bcopy(&ipha->ipha_src, buf + off2,
10839 			    IP_ADDR_LEN);
10840 			off2 -= IP_ADDR_LEN;
10841 
10842 			while (off2 > 0) {
10843 				bcopy(opt + off2, buf + off1,
10844 				    IP_ADDR_LEN);
10845 				off1 += IP_ADDR_LEN;
10846 				off2 -= IP_ADDR_LEN;
10847 			}
10848 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10849 			buf += optlen;
10850 			len += optlen;
10851 			break;
10852 		}
10853 	}
10854 done:
10855 	/* Pad the resulting options */
10856 	while (len & 0x3) {
10857 		*buf++ = IPOPT_EOL;
10858 		len++;
10859 	}
10860 	return (len);
10861 }
10862 
10863 
10864 /*
10865  * Extract and revert a source route from ipha (if any)
10866  * and then update the relevant fields in both tcp_t and the standard header.
10867  */
10868 static void
10869 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10870 {
10871 	char	buf[TCP_MAX_HDR_LENGTH];
10872 	uint_t	tcph_len;
10873 	int	len;
10874 
10875 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10876 	len = IPH_HDR_LENGTH(ipha);
10877 	if (len == IP_SIMPLE_HDR_LENGTH)
10878 		/* Nothing to do */
10879 		return;
10880 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10881 	    (len & 0x3))
10882 		return;
10883 
10884 	tcph_len = tcp->tcp_tcp_hdr_len;
10885 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10886 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10887 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10888 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10889 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10890 	len += IP_SIMPLE_HDR_LENGTH;
10891 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10892 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10893 	if ((int)tcp->tcp_sum < 0)
10894 		tcp->tcp_sum--;
10895 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10896 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10897 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10898 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10899 	tcp->tcp_ip_hdr_len = len;
10900 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10901 	    (IP_VERSION << 4) | (len >> 2);
10902 	len += tcph_len;
10903 	tcp->tcp_hdr_len = len;
10904 }
10905 
10906 /*
10907  * Copy the standard header into its new location,
10908  * lay in the new options and then update the relevant
10909  * fields in both tcp_t and the standard header.
10910  */
10911 static int
10912 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10913 {
10914 	uint_t	tcph_len;
10915 	uint8_t	*ip_optp;
10916 	tcph_t	*new_tcph;
10917 
10918 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10919 		return (EINVAL);
10920 
10921 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
10922 		return (EINVAL);
10923 
10924 	if (checkonly) {
10925 		/*
10926 		 * do not really set, just pretend to - T_CHECK
10927 		 */
10928 		return (0);
10929 	}
10930 
10931 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10932 	if (tcp->tcp_label_len > 0) {
10933 		int padlen;
10934 		uint8_t opt;
10935 
10936 		/* convert list termination to no-ops */
10937 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
10938 		ip_optp += ip_optp[IPOPT_OLEN];
10939 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
10940 		while (--padlen >= 0)
10941 			*ip_optp++ = opt;
10942 	}
10943 	tcph_len = tcp->tcp_tcp_hdr_len;
10944 	new_tcph = (tcph_t *)(ip_optp + len);
10945 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
10946 	tcp->tcp_tcph = new_tcph;
10947 	bcopy(ptr, ip_optp, len);
10948 
10949 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
10950 
10951 	tcp->tcp_ip_hdr_len = len;
10952 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10953 	    (IP_VERSION << 4) | (len >> 2);
10954 	tcp->tcp_hdr_len = len + tcph_len;
10955 	if (!TCP_IS_DETACHED(tcp)) {
10956 		/* Always allocate room for all options. */
10957 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10958 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10959 	}
10960 	return (0);
10961 }
10962 
10963 /* Get callback routine passed to nd_load by tcp_param_register */
10964 /* ARGSUSED */
10965 static int
10966 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10967 {
10968 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10969 
10970 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10971 	return (0);
10972 }
10973 
10974 /*
10975  * Walk through the param array specified registering each element with the
10976  * named dispatch handler.
10977  */
10978 static boolean_t
10979 tcp_param_register(tcpparam_t *tcppa, int cnt)
10980 {
10981 	for (; cnt-- > 0; tcppa++) {
10982 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10983 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10984 			    tcp_param_get, tcp_param_set,
10985 			    (caddr_t)tcppa)) {
10986 				nd_free(&tcp_g_nd);
10987 				return (B_FALSE);
10988 			}
10989 		}
10990 	}
10991 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10992 	    tcp_param_get, tcp_param_set_aligned,
10993 	    (caddr_t)&tcp_wroff_xtra_param)) {
10994 		nd_free(&tcp_g_nd);
10995 		return (B_FALSE);
10996 	}
10997 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10998 	    tcp_param_get, tcp_param_set_aligned,
10999 	    (caddr_t)&tcp_mdt_head_param)) {
11000 		nd_free(&tcp_g_nd);
11001 		return (B_FALSE);
11002 	}
11003 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
11004 	    tcp_param_get, tcp_param_set_aligned,
11005 	    (caddr_t)&tcp_mdt_tail_param)) {
11006 		nd_free(&tcp_g_nd);
11007 		return (B_FALSE);
11008 	}
11009 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
11010 	    tcp_param_get, tcp_param_set,
11011 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
11012 		nd_free(&tcp_g_nd);
11013 		return (B_FALSE);
11014 	}
11015 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
11016 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11017 		nd_free(&tcp_g_nd);
11018 		return (B_FALSE);
11019 	}
11020 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
11021 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11022 		nd_free(&tcp_g_nd);
11023 		return (B_FALSE);
11024 	}
11025 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
11026 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11027 		nd_free(&tcp_g_nd);
11028 		return (B_FALSE);
11029 	}
11030 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
11031 	    NULL)) {
11032 		nd_free(&tcp_g_nd);
11033 		return (B_FALSE);
11034 	}
11035 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
11036 	    NULL, NULL)) {
11037 		nd_free(&tcp_g_nd);
11038 		return (B_FALSE);
11039 	}
11040 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
11041 	    NULL, NULL)) {
11042 		nd_free(&tcp_g_nd);
11043 		return (B_FALSE);
11044 	}
11045 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
11046 	    NULL, NULL)) {
11047 		nd_free(&tcp_g_nd);
11048 		return (B_FALSE);
11049 	}
11050 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
11051 	    NULL, NULL)) {
11052 		nd_free(&tcp_g_nd);
11053 		return (B_FALSE);
11054 	}
11055 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
11056 	    tcp_host_param_set, NULL)) {
11057 		nd_free(&tcp_g_nd);
11058 		return (B_FALSE);
11059 	}
11060 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
11061 	    tcp_host_param_set_ipv6, NULL)) {
11062 		nd_free(&tcp_g_nd);
11063 		return (B_FALSE);
11064 	}
11065 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
11066 	    NULL)) {
11067 		nd_free(&tcp_g_nd);
11068 		return (B_FALSE);
11069 	}
11070 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
11071 	    tcp_reserved_port_list, NULL, NULL)) {
11072 		nd_free(&tcp_g_nd);
11073 		return (B_FALSE);
11074 	}
11075 	/*
11076 	 * Dummy ndd variables - only to convey obsolescence information
11077 	 * through printing of their name (no get or set routines)
11078 	 * XXX Remove in future releases ?
11079 	 */
11080 	if (!nd_load(&tcp_g_nd,
11081 	    "tcp_close_wait_interval(obsoleted - "
11082 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11083 		nd_free(&tcp_g_nd);
11084 		return (B_FALSE);
11085 	}
11086 	return (B_TRUE);
11087 }
11088 
11089 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11090 /* ARGSUSED */
11091 static int
11092 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11093     cred_t *cr)
11094 {
11095 	long new_value;
11096 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11097 
11098 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11099 	    new_value < tcppa->tcp_param_min ||
11100 	    new_value > tcppa->tcp_param_max) {
11101 		return (EINVAL);
11102 	}
11103 	/*
11104 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11105 	 * round it up.  For future 64 bit requirement, we actually make it
11106 	 * a multiple of 8.
11107 	 */
11108 	if (new_value & 0x7) {
11109 		new_value = (new_value & ~0x7) + 0x8;
11110 	}
11111 	tcppa->tcp_param_val = new_value;
11112 	return (0);
11113 }
11114 
11115 /* Set callback routine passed to nd_load by tcp_param_register */
11116 /* ARGSUSED */
11117 static int
11118 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11119 {
11120 	long	new_value;
11121 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11122 
11123 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11124 	    new_value < tcppa->tcp_param_min ||
11125 	    new_value > tcppa->tcp_param_max) {
11126 		return (EINVAL);
11127 	}
11128 	tcppa->tcp_param_val = new_value;
11129 	return (0);
11130 }
11131 
11132 /*
11133  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11134  * is filled, return as much as we can.  The message passed in may be
11135  * multi-part, chained using b_cont.  "start" is the starting sequence
11136  * number for this piece.
11137  */
11138 static mblk_t *
11139 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11140 {
11141 	uint32_t	end;
11142 	mblk_t		*mp1;
11143 	mblk_t		*mp2;
11144 	mblk_t		*next_mp;
11145 	uint32_t	u1;
11146 
11147 	/* Walk through all the new pieces. */
11148 	do {
11149 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11150 		    (uintptr_t)INT_MAX);
11151 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11152 		next_mp = mp->b_cont;
11153 		if (start == end) {
11154 			/* Empty.  Blast it. */
11155 			freeb(mp);
11156 			continue;
11157 		}
11158 		mp->b_cont = NULL;
11159 		TCP_REASS_SET_SEQ(mp, start);
11160 		TCP_REASS_SET_END(mp, end);
11161 		mp1 = tcp->tcp_reass_tail;
11162 		if (!mp1) {
11163 			tcp->tcp_reass_tail = mp;
11164 			tcp->tcp_reass_head = mp;
11165 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11166 			UPDATE_MIB(&tcp_mib,
11167 			    tcpInDataUnorderBytes, end - start);
11168 			continue;
11169 		}
11170 		/* New stuff completely beyond tail? */
11171 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11172 			/* Link it on end. */
11173 			mp1->b_cont = mp;
11174 			tcp->tcp_reass_tail = mp;
11175 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11176 			UPDATE_MIB(&tcp_mib,
11177 			    tcpInDataUnorderBytes, end - start);
11178 			continue;
11179 		}
11180 		mp1 = tcp->tcp_reass_head;
11181 		u1 = TCP_REASS_SEQ(mp1);
11182 		/* New stuff at the front? */
11183 		if (SEQ_LT(start, u1)) {
11184 			/* Yes... Check for overlap. */
11185 			mp->b_cont = mp1;
11186 			tcp->tcp_reass_head = mp;
11187 			tcp_reass_elim_overlap(tcp, mp);
11188 			continue;
11189 		}
11190 		/*
11191 		 * The new piece fits somewhere between the head and tail.
11192 		 * We find our slot, where mp1 precedes us and mp2 trails.
11193 		 */
11194 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11195 			u1 = TCP_REASS_SEQ(mp2);
11196 			if (SEQ_LEQ(start, u1))
11197 				break;
11198 		}
11199 		/* Link ourselves in */
11200 		mp->b_cont = mp2;
11201 		mp1->b_cont = mp;
11202 
11203 		/* Trim overlap with following mblk(s) first */
11204 		tcp_reass_elim_overlap(tcp, mp);
11205 
11206 		/* Trim overlap with preceding mblk */
11207 		tcp_reass_elim_overlap(tcp, mp1);
11208 
11209 	} while (start = end, mp = next_mp);
11210 	mp1 = tcp->tcp_reass_head;
11211 	/* Anything ready to go? */
11212 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11213 		return (NULL);
11214 	/* Eat what we can off the queue */
11215 	for (;;) {
11216 		mp = mp1->b_cont;
11217 		end = TCP_REASS_END(mp1);
11218 		TCP_REASS_SET_SEQ(mp1, 0);
11219 		TCP_REASS_SET_END(mp1, 0);
11220 		if (!mp) {
11221 			tcp->tcp_reass_tail = NULL;
11222 			break;
11223 		}
11224 		if (end != TCP_REASS_SEQ(mp)) {
11225 			mp1->b_cont = NULL;
11226 			break;
11227 		}
11228 		mp1 = mp;
11229 	}
11230 	mp1 = tcp->tcp_reass_head;
11231 	tcp->tcp_reass_head = mp;
11232 	return (mp1);
11233 }
11234 
11235 /* Eliminate any overlap that mp may have over later mblks */
11236 static void
11237 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11238 {
11239 	uint32_t	end;
11240 	mblk_t		*mp1;
11241 	uint32_t	u1;
11242 
11243 	end = TCP_REASS_END(mp);
11244 	while ((mp1 = mp->b_cont) != NULL) {
11245 		u1 = TCP_REASS_SEQ(mp1);
11246 		if (!SEQ_GT(end, u1))
11247 			break;
11248 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11249 			mp->b_wptr -= end - u1;
11250 			TCP_REASS_SET_END(mp, u1);
11251 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11252 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11253 			break;
11254 		}
11255 		mp->b_cont = mp1->b_cont;
11256 		TCP_REASS_SET_SEQ(mp1, 0);
11257 		TCP_REASS_SET_END(mp1, 0);
11258 		freeb(mp1);
11259 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11260 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11261 	}
11262 	if (!mp1)
11263 		tcp->tcp_reass_tail = mp;
11264 }
11265 
11266 /*
11267  * Send up all messages queued on tcp_rcv_list.
11268  */
11269 static uint_t
11270 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11271 {
11272 	mblk_t *mp;
11273 	uint_t ret = 0;
11274 	uint_t thwin;
11275 #ifdef DEBUG
11276 	uint_t cnt = 0;
11277 #endif
11278 	/* Can't drain on an eager connection */
11279 	if (tcp->tcp_listener != NULL)
11280 		return (ret);
11281 
11282 	/*
11283 	 * Handle two cases here: we are currently fused or we were
11284 	 * previously fused and have some urgent data to be delivered
11285 	 * upstream.  The latter happens because we either ran out of
11286 	 * memory or were detached and therefore sending the SIGURG was
11287 	 * deferred until this point.  In either case we pass control
11288 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11289 	 * some work.
11290 	 */
11291 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11292 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11293 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11294 		    &tcp->tcp_fused_sigurg_mp))
11295 			return (ret);
11296 	}
11297 
11298 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11299 		tcp->tcp_rcv_list = mp->b_next;
11300 		mp->b_next = NULL;
11301 #ifdef DEBUG
11302 		cnt += msgdsize(mp);
11303 #endif
11304 		/* Does this need SSL processing first? */
11305 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11306 			tcp_kssl_input(tcp, mp);
11307 			continue;
11308 		}
11309 		putnext(q, mp);
11310 	}
11311 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11312 	tcp->tcp_rcv_last_head = NULL;
11313 	tcp->tcp_rcv_last_tail = NULL;
11314 	tcp->tcp_rcv_cnt = 0;
11315 
11316 	/* Learn the latest rwnd information that we sent to the other side. */
11317 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11318 	    << tcp->tcp_rcv_ws;
11319 	/* This is peer's calculated send window (our receive window). */
11320 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11321 	/*
11322 	 * Increase the receive window to max.  But we need to do receiver
11323 	 * SWS avoidance.  This means that we need to check the increase of
11324 	 * of receive window is at least 1 MSS.
11325 	 */
11326 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11327 		/*
11328 		 * If the window that the other side knows is less than max
11329 		 * deferred acks segments, send an update immediately.
11330 		 */
11331 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11332 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11333 			ret = TH_ACK_NEEDED;
11334 		}
11335 		tcp->tcp_rwnd = q->q_hiwat;
11336 	}
11337 	/* No need for the push timer now. */
11338 	if (tcp->tcp_push_tid != 0) {
11339 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11340 		tcp->tcp_push_tid = 0;
11341 	}
11342 	return (ret);
11343 }
11344 
11345 /*
11346  * Queue data on tcp_rcv_list which is a b_next chain.
11347  * tcp_rcv_last_head/tail is the last element of this chain.
11348  * Each element of the chain is a b_cont chain.
11349  *
11350  * M_DATA messages are added to the current element.
11351  * Other messages are added as new (b_next) elements.
11352  */
11353 void
11354 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11355 {
11356 	ASSERT(seg_len == msgdsize(mp));
11357 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11358 
11359 	if (tcp->tcp_rcv_list == NULL) {
11360 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11361 		tcp->tcp_rcv_list = mp;
11362 		tcp->tcp_rcv_last_head = mp;
11363 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11364 		tcp->tcp_rcv_last_tail->b_cont = mp;
11365 	} else {
11366 		tcp->tcp_rcv_last_head->b_next = mp;
11367 		tcp->tcp_rcv_last_head = mp;
11368 	}
11369 
11370 	while (mp->b_cont)
11371 		mp = mp->b_cont;
11372 
11373 	tcp->tcp_rcv_last_tail = mp;
11374 	tcp->tcp_rcv_cnt += seg_len;
11375 	tcp->tcp_rwnd -= seg_len;
11376 }
11377 
11378 /*
11379  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11380  *
11381  * This is the default entry function into TCP on the read side. TCP is
11382  * always entered via squeue i.e. using squeue's for mutual exclusion.
11383  * When classifier does a lookup to find the tcp, it also puts a reference
11384  * on the conn structure associated so the tcp is guaranteed to exist
11385  * when we come here. We still need to check the state because it might
11386  * as well has been closed. The squeue processing function i.e. squeue_enter,
11387  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11388  * CONN_DEC_REF.
11389  *
11390  * Apart from the default entry point, IP also sends packets directly to
11391  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11392  * connections.
11393  */
11394 void
11395 tcp_input(void *arg, mblk_t *mp, void *arg2)
11396 {
11397 	conn_t	*connp = (conn_t *)arg;
11398 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11399 
11400 	/* arg2 is the sqp */
11401 	ASSERT(arg2 != NULL);
11402 	ASSERT(mp != NULL);
11403 
11404 	/*
11405 	 * Don't accept any input on a closed tcp as this TCP logically does
11406 	 * not exist on the system. Don't proceed further with this TCP.
11407 	 * For eg. this packet could trigger another close of this tcp
11408 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11409 	 * tcp_clean_death / tcp_closei_local must be called at most once
11410 	 * on a TCP. In this case we need to refeed the packet into the
11411 	 * classifier and figure out where the packet should go. Need to
11412 	 * preserve the recv_ill somehow. Until we figure that out, for
11413 	 * now just drop the packet if we can't classify the packet.
11414 	 */
11415 	if (tcp->tcp_state == TCPS_CLOSED ||
11416 	    tcp->tcp_state == TCPS_BOUND) {
11417 		conn_t	*new_connp;
11418 
11419 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11420 		if (new_connp != NULL) {
11421 			tcp_reinput(new_connp, mp, arg2);
11422 			return;
11423 		}
11424 		/* We failed to classify. For now just drop the packet */
11425 		freemsg(mp);
11426 		return;
11427 	}
11428 
11429 	if (DB_TYPE(mp) == M_DATA)
11430 		tcp_rput_data(connp, mp, arg2);
11431 	else
11432 		tcp_rput_common(tcp, mp);
11433 }
11434 
11435 /*
11436  * The read side put procedure.
11437  * The packets passed up by ip are assume to be aligned according to
11438  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11439  */
11440 static void
11441 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11442 {
11443 	/*
11444 	 * tcp_rput_data() does not expect M_CTL except for the case
11445 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11446 	 * type. Need to make sure that any other M_CTLs don't make
11447 	 * it to tcp_rput_data since it is not expecting any and doesn't
11448 	 * check for it.
11449 	 */
11450 	if (DB_TYPE(mp) == M_CTL) {
11451 		switch (*(uint32_t *)(mp->b_rptr)) {
11452 		case TCP_IOC_ABORT_CONN:
11453 			/*
11454 			 * Handle connection abort request.
11455 			 */
11456 			tcp_ioctl_abort_handler(tcp, mp);
11457 			return;
11458 		case IPSEC_IN:
11459 			/*
11460 			 * Only secure icmp arrive in TCP and they
11461 			 * don't go through data path.
11462 			 */
11463 			tcp_icmp_error(tcp, mp);
11464 			return;
11465 		case IN_PKTINFO:
11466 			/*
11467 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11468 			 * sockets that are receiving IPv4 traffic. tcp
11469 			 */
11470 			ASSERT(tcp->tcp_family == AF_INET6);
11471 			ASSERT(tcp->tcp_ipv6_recvancillary &
11472 			    TCP_IPV6_RECVPKTINFO);
11473 			tcp_rput_data(tcp->tcp_connp, mp,
11474 			    tcp->tcp_connp->conn_sqp);
11475 			return;
11476 		case MDT_IOC_INFO_UPDATE:
11477 			/*
11478 			 * Handle Multidata information update; the
11479 			 * following routine will free the message.
11480 			 */
11481 			if (tcp->tcp_connp->conn_mdt_ok) {
11482 				tcp_mdt_update(tcp,
11483 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11484 				    B_FALSE);
11485 			}
11486 			freemsg(mp);
11487 			return;
11488 		default:
11489 			break;
11490 		}
11491 	}
11492 
11493 	/* No point processing the message if tcp is already closed */
11494 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11495 		freemsg(mp);
11496 		return;
11497 	}
11498 
11499 	tcp_rput_other(tcp, mp);
11500 }
11501 
11502 
11503 /* The minimum of smoothed mean deviation in RTO calculation. */
11504 #define	TCP_SD_MIN	400
11505 
11506 /*
11507  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11508  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11509  * are the same as those in Appendix A.2 of that paper.
11510  *
11511  * m = new measurement
11512  * sa = smoothed RTT average (8 * average estimates).
11513  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11514  */
11515 static void
11516 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11517 {
11518 	long m = TICK_TO_MSEC(rtt);
11519 	clock_t sa = tcp->tcp_rtt_sa;
11520 	clock_t sv = tcp->tcp_rtt_sd;
11521 	clock_t rto;
11522 
11523 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11524 	tcp->tcp_rtt_update++;
11525 
11526 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11527 	if (sa != 0) {
11528 		/*
11529 		 * Update average estimator:
11530 		 *	new rtt = 7/8 old rtt + 1/8 Error
11531 		 */
11532 
11533 		/* m is now Error in estimate. */
11534 		m -= sa >> 3;
11535 		if ((sa += m) <= 0) {
11536 			/*
11537 			 * Don't allow the smoothed average to be negative.
11538 			 * We use 0 to denote reinitialization of the
11539 			 * variables.
11540 			 */
11541 			sa = 1;
11542 		}
11543 
11544 		/*
11545 		 * Update deviation estimator:
11546 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11547 		 */
11548 		if (m < 0)
11549 			m = -m;
11550 		m -= sv >> 2;
11551 		sv += m;
11552 	} else {
11553 		/*
11554 		 * This follows BSD's implementation.  So the reinitialized
11555 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11556 		 * link is bandwidth dominated, doubling the window size
11557 		 * during slow start means doubling the RTT.  We want to be
11558 		 * more conservative when we reinitialize our estimates.  3
11559 		 * is just a convenient number.
11560 		 */
11561 		sa = m << 3;
11562 		sv = m << 1;
11563 	}
11564 	if (sv < TCP_SD_MIN) {
11565 		/*
11566 		 * We do not know that if sa captures the delay ACK
11567 		 * effect as in a long train of segments, a receiver
11568 		 * does not delay its ACKs.  So set the minimum of sv
11569 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11570 		 * of BSD DATO.  That means the minimum of mean
11571 		 * deviation is 100 ms.
11572 		 *
11573 		 */
11574 		sv = TCP_SD_MIN;
11575 	}
11576 	tcp->tcp_rtt_sa = sa;
11577 	tcp->tcp_rtt_sd = sv;
11578 	/*
11579 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11580 	 *
11581 	 * Add tcp_rexmit_interval extra in case of extreme environment
11582 	 * where the algorithm fails to work.  The default value of
11583 	 * tcp_rexmit_interval_extra should be 0.
11584 	 *
11585 	 * As we use a finer grained clock than BSD and update
11586 	 * RTO for every ACKs, add in another .25 of RTT to the
11587 	 * deviation of RTO to accomodate burstiness of 1/4 of
11588 	 * window size.
11589 	 */
11590 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11591 
11592 	if (rto > tcp_rexmit_interval_max) {
11593 		tcp->tcp_rto = tcp_rexmit_interval_max;
11594 	} else if (rto < tcp_rexmit_interval_min) {
11595 		tcp->tcp_rto = tcp_rexmit_interval_min;
11596 	} else {
11597 		tcp->tcp_rto = rto;
11598 	}
11599 
11600 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11601 	tcp->tcp_timer_backoff = 0;
11602 }
11603 
11604 /*
11605  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11606  * send queue which starts at the given seq. no.
11607  *
11608  * Parameters:
11609  *	tcp_t *tcp: the tcp instance pointer.
11610  *	uint32_t seq: the starting seq. no of the requested segment.
11611  *	int32_t *off: after the execution, *off will be the offset to
11612  *		the returned mblk which points to the requested seq no.
11613  *		It is the caller's responsibility to send in a non-null off.
11614  *
11615  * Return:
11616  *	A mblk_t pointer pointing to the requested segment in send queue.
11617  */
11618 static mblk_t *
11619 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11620 {
11621 	int32_t	cnt;
11622 	mblk_t	*mp;
11623 
11624 	/* Defensive coding.  Make sure we don't send incorrect data. */
11625 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11626 		return (NULL);
11627 
11628 	cnt = seq - tcp->tcp_suna;
11629 	mp = tcp->tcp_xmit_head;
11630 	while (cnt > 0 && mp != NULL) {
11631 		cnt -= mp->b_wptr - mp->b_rptr;
11632 		if (cnt < 0) {
11633 			cnt += mp->b_wptr - mp->b_rptr;
11634 			break;
11635 		}
11636 		mp = mp->b_cont;
11637 	}
11638 	ASSERT(mp != NULL);
11639 	*off = cnt;
11640 	return (mp);
11641 }
11642 
11643 /*
11644  * This function handles all retransmissions if SACK is enabled for this
11645  * connection.  First it calculates how many segments can be retransmitted
11646  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11647  * segments.  A segment is eligible if sack_cnt for that segment is greater
11648  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11649  * all eligible segments, it checks to see if TCP can send some new segments
11650  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11651  *
11652  * Parameters:
11653  *	tcp_t *tcp: the tcp structure of the connection.
11654  *	uint_t *flags: in return, appropriate value will be set for
11655  *	tcp_rput_data().
11656  */
11657 static void
11658 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11659 {
11660 	notsack_blk_t	*notsack_blk;
11661 	int32_t		usable_swnd;
11662 	int32_t		mss;
11663 	uint32_t	seg_len;
11664 	mblk_t		*xmit_mp;
11665 
11666 	ASSERT(tcp->tcp_sack_info != NULL);
11667 	ASSERT(tcp->tcp_notsack_list != NULL);
11668 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11669 
11670 	/* Defensive coding in case there is a bug... */
11671 	if (tcp->tcp_notsack_list == NULL) {
11672 		return;
11673 	}
11674 	notsack_blk = tcp->tcp_notsack_list;
11675 	mss = tcp->tcp_mss;
11676 
11677 	/*
11678 	 * Limit the num of outstanding data in the network to be
11679 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11680 	 */
11681 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11682 
11683 	/* At least retransmit 1 MSS of data. */
11684 	if (usable_swnd <= 0) {
11685 		usable_swnd = mss;
11686 	}
11687 
11688 	/* Make sure no new RTT samples will be taken. */
11689 	tcp->tcp_csuna = tcp->tcp_snxt;
11690 
11691 	notsack_blk = tcp->tcp_notsack_list;
11692 	while (usable_swnd > 0) {
11693 		mblk_t		*snxt_mp, *tmp_mp;
11694 		tcp_seq		begin = tcp->tcp_sack_snxt;
11695 		tcp_seq		end;
11696 		int32_t		off;
11697 
11698 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11699 			if (SEQ_GT(notsack_blk->end, begin) &&
11700 			    (notsack_blk->sack_cnt >=
11701 			    tcp_dupack_fast_retransmit)) {
11702 				end = notsack_blk->end;
11703 				if (SEQ_LT(begin, notsack_blk->begin)) {
11704 					begin = notsack_blk->begin;
11705 				}
11706 				break;
11707 			}
11708 		}
11709 		/*
11710 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11711 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11712 		 * set to tcp_cwnd_ssthresh.
11713 		 */
11714 		if (notsack_blk == NULL) {
11715 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11716 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11717 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11718 				ASSERT(tcp->tcp_cwnd > 0);
11719 				return;
11720 			} else {
11721 				usable_swnd = usable_swnd / mss;
11722 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11723 				    MAX(usable_swnd * mss, mss);
11724 				*flags |= TH_XMIT_NEEDED;
11725 				return;
11726 			}
11727 		}
11728 
11729 		/*
11730 		 * Note that we may send more than usable_swnd allows here
11731 		 * because of round off, but no more than 1 MSS of data.
11732 		 */
11733 		seg_len = end - begin;
11734 		if (seg_len > mss)
11735 			seg_len = mss;
11736 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11737 		ASSERT(snxt_mp != NULL);
11738 		/* This should not happen.  Defensive coding again... */
11739 		if (snxt_mp == NULL) {
11740 			return;
11741 		}
11742 
11743 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11744 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11745 		if (xmit_mp == NULL)
11746 			return;
11747 
11748 		usable_swnd -= seg_len;
11749 		tcp->tcp_pipe += seg_len;
11750 		tcp->tcp_sack_snxt = begin + seg_len;
11751 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11752 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11753 
11754 		/*
11755 		 * Update the send timestamp to avoid false retransmission.
11756 		 */
11757 		snxt_mp->b_prev = (mblk_t *)lbolt;
11758 
11759 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11760 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11761 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11762 		/*
11763 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11764 		 * This happens when new data sent during fast recovery is
11765 		 * also lost.  If TCP retransmits those new data, it needs
11766 		 * to extend SACK recover phase to avoid starting another
11767 		 * fast retransmit/recovery unnecessarily.
11768 		 */
11769 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11770 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11771 		}
11772 	}
11773 }
11774 
11775 /*
11776  * This function handles policy checking at TCP level for non-hard_bound/
11777  * detached connections.
11778  */
11779 static boolean_t
11780 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11781     boolean_t secure, boolean_t mctl_present)
11782 {
11783 	ipsec_latch_t *ipl = NULL;
11784 	ipsec_action_t *act = NULL;
11785 	mblk_t *data_mp;
11786 	ipsec_in_t *ii;
11787 	const char *reason;
11788 	kstat_named_t *counter;
11789 
11790 	ASSERT(mctl_present || !secure);
11791 
11792 	ASSERT((ipha == NULL && ip6h != NULL) ||
11793 	    (ip6h == NULL && ipha != NULL));
11794 
11795 	/*
11796 	 * We don't necessarily have an ipsec_in_act action to verify
11797 	 * policy because of assymetrical policy where we have only
11798 	 * outbound policy and no inbound policy (possible with global
11799 	 * policy).
11800 	 */
11801 	if (!secure) {
11802 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11803 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11804 			return (B_TRUE);
11805 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11806 		    "tcp_check_policy", ipha, ip6h, secure);
11807 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11808 		    &ipdrops_tcp_clear, &tcp_dropper);
11809 		return (B_FALSE);
11810 	}
11811 
11812 	/*
11813 	 * We have a secure packet.
11814 	 */
11815 	if (act == NULL) {
11816 		ipsec_log_policy_failure(tcp->tcp_wq,
11817 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11818 		    secure);
11819 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11820 		    &ipdrops_tcp_secure, &tcp_dropper);
11821 		return (B_FALSE);
11822 	}
11823 
11824 	/*
11825 	 * XXX This whole routine is currently incorrect.  ipl should
11826 	 * be set to the latch pointer, but is currently not set, so
11827 	 * we initialize it to NULL to avoid picking up random garbage.
11828 	 */
11829 	if (ipl == NULL)
11830 		return (B_TRUE);
11831 
11832 	data_mp = first_mp->b_cont;
11833 
11834 	ii = (ipsec_in_t *)first_mp->b_rptr;
11835 
11836 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11837 	    &counter)) {
11838 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11839 		return (B_TRUE);
11840 	}
11841 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11842 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11843 	    reason);
11844 	BUMP_MIB(&ip_mib, ipsecInFailed);
11845 
11846 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11847 	return (B_FALSE);
11848 }
11849 
11850 /*
11851  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11852  * retransmission after a timeout.
11853  *
11854  * To limit the number of duplicate segments, we limit the number of segment
11855  * to be sent in one time to tcp_snd_burst, the burst variable.
11856  */
11857 static void
11858 tcp_ss_rexmit(tcp_t *tcp)
11859 {
11860 	uint32_t	snxt;
11861 	uint32_t	smax;
11862 	int32_t		win;
11863 	int32_t		mss;
11864 	int32_t		off;
11865 	int32_t		burst = tcp->tcp_snd_burst;
11866 	mblk_t		*snxt_mp;
11867 
11868 	/*
11869 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11870 	 * all unack'ed segments.
11871 	 */
11872 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11873 		smax = tcp->tcp_rexmit_max;
11874 		snxt = tcp->tcp_rexmit_nxt;
11875 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11876 			snxt = tcp->tcp_suna;
11877 		}
11878 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11879 		win -= snxt - tcp->tcp_suna;
11880 		mss = tcp->tcp_mss;
11881 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11882 
11883 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11884 		    (burst > 0) && (snxt_mp != NULL)) {
11885 			mblk_t	*xmit_mp;
11886 			mblk_t	*old_snxt_mp = snxt_mp;
11887 			uint32_t cnt = mss;
11888 
11889 			if (win < cnt) {
11890 				cnt = win;
11891 			}
11892 			if (SEQ_GT(snxt + cnt, smax)) {
11893 				cnt = smax - snxt;
11894 			}
11895 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11896 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11897 			if (xmit_mp == NULL)
11898 				return;
11899 
11900 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11901 
11902 			snxt += cnt;
11903 			win -= cnt;
11904 			/*
11905 			 * Update the send timestamp to avoid false
11906 			 * retransmission.
11907 			 */
11908 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11909 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11910 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11911 
11912 			tcp->tcp_rexmit_nxt = snxt;
11913 			burst--;
11914 		}
11915 		/*
11916 		 * If we have transmitted all we have at the time
11917 		 * we started the retranmission, we can leave
11918 		 * the rest of the job to tcp_wput_data().  But we
11919 		 * need to check the send window first.  If the
11920 		 * win is not 0, go on with tcp_wput_data().
11921 		 */
11922 		if (SEQ_LT(snxt, smax) || win == 0) {
11923 			return;
11924 		}
11925 	}
11926 	/* Only call tcp_wput_data() if there is data to be sent. */
11927 	if (tcp->tcp_unsent) {
11928 		tcp_wput_data(tcp, NULL, B_FALSE);
11929 	}
11930 }
11931 
11932 /*
11933  * Process all TCP option in SYN segment.  Note that this function should
11934  * be called after tcp_adapt_ire() is called so that the necessary info
11935  * from IRE is already set in the tcp structure.
11936  *
11937  * This function sets up the correct tcp_mss value according to the
11938  * MSS option value and our header size.  It also sets up the window scale
11939  * and timestamp values, and initialize SACK info blocks.  But it does not
11940  * change receive window size after setting the tcp_mss value.  The caller
11941  * should do the appropriate change.
11942  */
11943 void
11944 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11945 {
11946 	int options;
11947 	tcp_opt_t tcpopt;
11948 	uint32_t mss_max;
11949 	char *tmp_tcph;
11950 
11951 	tcpopt.tcp = NULL;
11952 	options = tcp_parse_options(tcph, &tcpopt);
11953 
11954 	/*
11955 	 * Process MSS option.  Note that MSS option value does not account
11956 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11957 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11958 	 * IPv6.
11959 	 */
11960 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11961 		if (tcp->tcp_ipversion == IPV4_VERSION)
11962 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11963 		else
11964 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11965 	} else {
11966 		if (tcp->tcp_ipversion == IPV4_VERSION)
11967 			mss_max = tcp_mss_max_ipv4;
11968 		else
11969 			mss_max = tcp_mss_max_ipv6;
11970 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11971 			tcpopt.tcp_opt_mss = tcp_mss_min;
11972 		else if (tcpopt.tcp_opt_mss > mss_max)
11973 			tcpopt.tcp_opt_mss = mss_max;
11974 	}
11975 
11976 	/* Process Window Scale option. */
11977 	if (options & TCP_OPT_WSCALE_PRESENT) {
11978 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11979 		tcp->tcp_snd_ws_ok = B_TRUE;
11980 	} else {
11981 		tcp->tcp_snd_ws = B_FALSE;
11982 		tcp->tcp_snd_ws_ok = B_FALSE;
11983 		tcp->tcp_rcv_ws = B_FALSE;
11984 	}
11985 
11986 	/* Process Timestamp option. */
11987 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11988 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11989 		tmp_tcph = (char *)tcp->tcp_tcph;
11990 
11991 		tcp->tcp_snd_ts_ok = B_TRUE;
11992 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11993 		tcp->tcp_last_rcv_lbolt = lbolt64;
11994 		ASSERT(OK_32PTR(tmp_tcph));
11995 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11996 
11997 		/* Fill in our template header with basic timestamp option. */
11998 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11999 		tmp_tcph[0] = TCPOPT_NOP;
12000 		tmp_tcph[1] = TCPOPT_NOP;
12001 		tmp_tcph[2] = TCPOPT_TSTAMP;
12002 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12003 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12004 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12005 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12006 	} else {
12007 		tcp->tcp_snd_ts_ok = B_FALSE;
12008 	}
12009 
12010 	/*
12011 	 * Process SACK options.  If SACK is enabled for this connection,
12012 	 * then allocate the SACK info structure.  Note the following ways
12013 	 * when tcp_snd_sack_ok is set to true.
12014 	 *
12015 	 * For active connection: in tcp_adapt_ire() called in
12016 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12017 	 * is checked.
12018 	 *
12019 	 * For passive connection: in tcp_adapt_ire() called in
12020 	 * tcp_accept_comm().
12021 	 *
12022 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12023 	 * That check makes sure that if we did not send a SACK OK option,
12024 	 * we will not enable SACK for this connection even though the other
12025 	 * side sends us SACK OK option.  For active connection, the SACK
12026 	 * info structure has already been allocated.  So we need to free
12027 	 * it if SACK is disabled.
12028 	 */
12029 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12030 	    (tcp->tcp_snd_sack_ok ||
12031 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12032 		/* This should be true only in the passive case. */
12033 		if (tcp->tcp_sack_info == NULL) {
12034 			ASSERT(TCP_IS_DETACHED(tcp));
12035 			tcp->tcp_sack_info =
12036 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12037 		}
12038 		if (tcp->tcp_sack_info == NULL) {
12039 			tcp->tcp_snd_sack_ok = B_FALSE;
12040 		} else {
12041 			tcp->tcp_snd_sack_ok = B_TRUE;
12042 			if (tcp->tcp_snd_ts_ok) {
12043 				tcp->tcp_max_sack_blk = 3;
12044 			} else {
12045 				tcp->tcp_max_sack_blk = 4;
12046 			}
12047 		}
12048 	} else {
12049 		/*
12050 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12051 		 * no SACK info will be used for this
12052 		 * connection.  This assumes that SACK usage
12053 		 * permission is negotiated.  This may need
12054 		 * to be changed once this is clarified.
12055 		 */
12056 		if (tcp->tcp_sack_info != NULL) {
12057 			ASSERT(tcp->tcp_notsack_list == NULL);
12058 			kmem_cache_free(tcp_sack_info_cache,
12059 			    tcp->tcp_sack_info);
12060 			tcp->tcp_sack_info = NULL;
12061 		}
12062 		tcp->tcp_snd_sack_ok = B_FALSE;
12063 	}
12064 
12065 	/*
12066 	 * Now we know the exact TCP/IP header length, subtract
12067 	 * that from tcp_mss to get our side's MSS.
12068 	 */
12069 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12070 	/*
12071 	 * Here we assume that the other side's header size will be equal to
12072 	 * our header size.  We calculate the real MSS accordingly.  Need to
12073 	 * take into additional stuffs IPsec puts in.
12074 	 *
12075 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12076 	 */
12077 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12078 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12079 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12080 
12081 	/*
12082 	 * Set MSS to the smaller one of both ends of the connection.
12083 	 * We should not have called tcp_mss_set() before, but our
12084 	 * side of the MSS should have been set to a proper value
12085 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12086 	 * STREAM head parameters properly.
12087 	 *
12088 	 * If we have a larger-than-16-bit window but the other side
12089 	 * didn't want to do window scale, tcp_rwnd_set() will take
12090 	 * care of that.
12091 	 */
12092 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
12093 }
12094 
12095 /*
12096  * Sends the T_CONN_IND to the listener. The caller calls this
12097  * functions via squeue to get inside the listener's perimeter
12098  * once the 3 way hand shake is done a T_CONN_IND needs to be
12099  * sent. As an optimization, the caller can call this directly
12100  * if listener's perimeter is same as eager's.
12101  */
12102 /* ARGSUSED */
12103 void
12104 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12105 {
12106 	conn_t			*lconnp = (conn_t *)arg;
12107 	tcp_t			*listener = lconnp->conn_tcp;
12108 	tcp_t			*tcp;
12109 	struct T_conn_ind	*conn_ind;
12110 	ipaddr_t 		*addr_cache;
12111 	boolean_t		need_send_conn_ind = B_FALSE;
12112 
12113 	/* retrieve the eager */
12114 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12115 	ASSERT(conn_ind->OPT_offset != 0 &&
12116 	    conn_ind->OPT_length == sizeof (intptr_t));
12117 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12118 		conn_ind->OPT_length);
12119 
12120 	/*
12121 	 * TLI/XTI applications will get confused by
12122 	 * sending eager as an option since it violates
12123 	 * the option semantics. So remove the eager as
12124 	 * option since TLI/XTI app doesn't need it anyway.
12125 	 */
12126 	if (!TCP_IS_SOCKET(listener)) {
12127 		conn_ind->OPT_length = 0;
12128 		conn_ind->OPT_offset = 0;
12129 	}
12130 	if (listener->tcp_state == TCPS_CLOSED ||
12131 	    TCP_IS_DETACHED(listener)) {
12132 		/*
12133 		 * If listener has closed, it would have caused a
12134 		 * a cleanup/blowoff to happen for the eager. We
12135 		 * just need to return.
12136 		 */
12137 		freemsg(mp);
12138 		return;
12139 	}
12140 
12141 
12142 	/*
12143 	 * if the conn_req_q is full defer passing up the
12144 	 * T_CONN_IND until space is availabe after t_accept()
12145 	 * processing
12146 	 */
12147 	mutex_enter(&listener->tcp_eager_lock);
12148 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12149 		tcp_t *tail;
12150 
12151 		/*
12152 		 * The eager already has an extra ref put in tcp_rput_data
12153 		 * so that it stays till accept comes back even though it
12154 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12155 		 */
12156 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12157 		listener->tcp_conn_req_cnt_q0--;
12158 		listener->tcp_conn_req_cnt_q++;
12159 
12160 		/* Move from SYN_RCVD to ESTABLISHED list  */
12161 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12162 		    tcp->tcp_eager_prev_q0;
12163 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12164 		    tcp->tcp_eager_next_q0;
12165 		tcp->tcp_eager_prev_q0 = NULL;
12166 		tcp->tcp_eager_next_q0 = NULL;
12167 
12168 		/*
12169 		 * Insert at end of the queue because sockfs
12170 		 * sends down T_CONN_RES in chronological
12171 		 * order. Leaving the older conn indications
12172 		 * at front of the queue helps reducing search
12173 		 * time.
12174 		 */
12175 		tail = listener->tcp_eager_last_q;
12176 		if (tail != NULL)
12177 			tail->tcp_eager_next_q = tcp;
12178 		else
12179 			listener->tcp_eager_next_q = tcp;
12180 		listener->tcp_eager_last_q = tcp;
12181 		tcp->tcp_eager_next_q = NULL;
12182 		/*
12183 		 * Delay sending up the T_conn_ind until we are
12184 		 * done with the eager. Once we have have sent up
12185 		 * the T_conn_ind, the accept can potentially complete
12186 		 * any time and release the refhold we have on the eager.
12187 		 */
12188 		need_send_conn_ind = B_TRUE;
12189 	} else {
12190 		/*
12191 		 * Defer connection on q0 and set deferred
12192 		 * connection bit true
12193 		 */
12194 		tcp->tcp_conn_def_q0 = B_TRUE;
12195 
12196 		/* take tcp out of q0 ... */
12197 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12198 		    tcp->tcp_eager_next_q0;
12199 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12200 		    tcp->tcp_eager_prev_q0;
12201 
12202 		/* ... and place it at the end of q0 */
12203 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12204 		tcp->tcp_eager_next_q0 = listener;
12205 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12206 		listener->tcp_eager_prev_q0 = tcp;
12207 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12208 	}
12209 
12210 	/* we have timed out before */
12211 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12212 		tcp->tcp_syn_rcvd_timeout = 0;
12213 		listener->tcp_syn_rcvd_timeout--;
12214 		if (listener->tcp_syn_defense &&
12215 		    listener->tcp_syn_rcvd_timeout <=
12216 		    (tcp_conn_req_max_q0 >> 5) &&
12217 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12218 			listener->tcp_last_rcv_lbolt)) {
12219 			/*
12220 			 * Turn off the defense mode if we
12221 			 * believe the SYN attack is over.
12222 			 */
12223 			listener->tcp_syn_defense = B_FALSE;
12224 			if (listener->tcp_ip_addr_cache) {
12225 				kmem_free((void *)listener->tcp_ip_addr_cache,
12226 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12227 				listener->tcp_ip_addr_cache = NULL;
12228 			}
12229 		}
12230 	}
12231 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12232 	if (addr_cache != NULL) {
12233 		/*
12234 		 * We have finished a 3-way handshake with this
12235 		 * remote host. This proves the IP addr is good.
12236 		 * Cache it!
12237 		 */
12238 		addr_cache[IP_ADDR_CACHE_HASH(
12239 			tcp->tcp_remote)] = tcp->tcp_remote;
12240 	}
12241 	mutex_exit(&listener->tcp_eager_lock);
12242 	if (need_send_conn_ind)
12243 		putnext(listener->tcp_rq, mp);
12244 }
12245 
12246 mblk_t *
12247 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12248     uint_t *ifindexp, ip6_pkt_t *ippp)
12249 {
12250 	in_pktinfo_t	*pinfo;
12251 	ip6_t		*ip6h;
12252 	uchar_t		*rptr;
12253 	mblk_t		*first_mp = mp;
12254 	boolean_t	mctl_present = B_FALSE;
12255 	uint_t 		ifindex = 0;
12256 	ip6_pkt_t	ipp;
12257 	uint_t		ipvers;
12258 	uint_t		ip_hdr_len;
12259 
12260 	rptr = mp->b_rptr;
12261 	ASSERT(OK_32PTR(rptr));
12262 	ASSERT(tcp != NULL);
12263 	ipp.ipp_fields = 0;
12264 
12265 	switch DB_TYPE(mp) {
12266 	case M_CTL:
12267 		mp = mp->b_cont;
12268 		if (mp == NULL) {
12269 			freemsg(first_mp);
12270 			return (NULL);
12271 		}
12272 		if (DB_TYPE(mp) != M_DATA) {
12273 			freemsg(first_mp);
12274 			return (NULL);
12275 		}
12276 		mctl_present = B_TRUE;
12277 		break;
12278 	case M_DATA:
12279 		break;
12280 	default:
12281 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12282 		freemsg(mp);
12283 		return (NULL);
12284 	}
12285 	ipvers = IPH_HDR_VERSION(rptr);
12286 	if (ipvers == IPV4_VERSION) {
12287 		if (tcp == NULL) {
12288 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12289 			goto done;
12290 		}
12291 
12292 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12293 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12294 
12295 		/*
12296 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12297 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12298 		 */
12299 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12300 		    mctl_present) {
12301 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12302 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12303 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12304 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12305 				ipp.ipp_fields |= IPPF_IFINDEX;
12306 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12307 				ifindex = pinfo->in_pkt_ifindex;
12308 			}
12309 			freeb(first_mp);
12310 			mctl_present = B_FALSE;
12311 		}
12312 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12313 	} else {
12314 		ip6h = (ip6_t *)rptr;
12315 
12316 		ASSERT(ipvers == IPV6_VERSION);
12317 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12318 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12319 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12320 
12321 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12322 			uint8_t	nexthdrp;
12323 
12324 			/* Look for ifindex information */
12325 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12326 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12327 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12328 					BUMP_MIB(&ip_mib, tcpInErrs);
12329 					freemsg(first_mp);
12330 					return (NULL);
12331 				}
12332 
12333 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12334 					ASSERT(ip6i->ip6i_ifindex != 0);
12335 					ipp.ipp_fields |= IPPF_IFINDEX;
12336 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12337 					ifindex = ip6i->ip6i_ifindex;
12338 				}
12339 				rptr = (uchar_t *)&ip6i[1];
12340 				mp->b_rptr = rptr;
12341 				if (rptr == mp->b_wptr) {
12342 					mblk_t *mp1;
12343 					mp1 = mp->b_cont;
12344 					freeb(mp);
12345 					mp = mp1;
12346 					rptr = mp->b_rptr;
12347 				}
12348 				if (MBLKL(mp) < IPV6_HDR_LEN +
12349 				    sizeof (tcph_t)) {
12350 					BUMP_MIB(&ip_mib, tcpInErrs);
12351 					freemsg(first_mp);
12352 					return (NULL);
12353 				}
12354 				ip6h = (ip6_t *)rptr;
12355 			}
12356 
12357 			/*
12358 			 * Find any potentially interesting extension headers
12359 			 * as well as the length of the IPv6 + extension
12360 			 * headers.
12361 			 */
12362 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12363 			/* Verify if this is a TCP packet */
12364 			if (nexthdrp != IPPROTO_TCP) {
12365 				BUMP_MIB(&ip_mib, tcpInErrs);
12366 				freemsg(first_mp);
12367 				return (NULL);
12368 			}
12369 		} else {
12370 			ip_hdr_len = IPV6_HDR_LEN;
12371 		}
12372 	}
12373 
12374 done:
12375 	if (ipversp != NULL)
12376 		*ipversp = ipvers;
12377 	if (ip_hdr_lenp != NULL)
12378 		*ip_hdr_lenp = ip_hdr_len;
12379 	if (ippp != NULL)
12380 		*ippp = ipp;
12381 	if (ifindexp != NULL)
12382 		*ifindexp = ifindex;
12383 	if (mctl_present) {
12384 		freeb(first_mp);
12385 	}
12386 	return (mp);
12387 }
12388 
12389 /*
12390  * Handle M_DATA messages from IP. Its called directly from IP via
12391  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12392  * in this path.
12393  *
12394  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12395  * v4 and v6), we are called through tcp_input() and a M_CTL can
12396  * be present for options but tcp_find_pktinfo() deals with it. We
12397  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12398  *
12399  * The first argument is always the connp/tcp to which the mp belongs.
12400  * There are no exceptions to this rule. The caller has already put
12401  * a reference on this connp/tcp and once tcp_rput_data() returns,
12402  * the squeue will do the refrele.
12403  *
12404  * The TH_SYN for the listener directly go to tcp_conn_request via
12405  * squeue.
12406  *
12407  * sqp: NULL = recursive, sqp != NULL means called from squeue
12408  */
12409 void
12410 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12411 {
12412 	int32_t		bytes_acked;
12413 	int32_t		gap;
12414 	mblk_t		*mp1;
12415 	uint_t		flags;
12416 	uint32_t	new_swnd = 0;
12417 	uchar_t		*iphdr;
12418 	uchar_t		*rptr;
12419 	int32_t		rgap;
12420 	uint32_t	seg_ack;
12421 	int		seg_len;
12422 	uint_t		ip_hdr_len;
12423 	uint32_t	seg_seq;
12424 	tcph_t		*tcph;
12425 	int		urp;
12426 	tcp_opt_t	tcpopt;
12427 	uint_t		ipvers;
12428 	ip6_pkt_t	ipp;
12429 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12430 	uint32_t	cwnd;
12431 	uint32_t	add;
12432 	int		npkt;
12433 	int		mss;
12434 	conn_t		*connp = (conn_t *)arg;
12435 	squeue_t	*sqp = (squeue_t *)arg2;
12436 	tcp_t		*tcp = connp->conn_tcp;
12437 
12438 	/*
12439 	 * RST from fused tcp loopback peer should trigger an unfuse.
12440 	 */
12441 	if (tcp->tcp_fused) {
12442 		TCP_STAT(tcp_fusion_aborted);
12443 		tcp_unfuse(tcp);
12444 	}
12445 
12446 	iphdr = mp->b_rptr;
12447 	rptr = mp->b_rptr;
12448 	ASSERT(OK_32PTR(rptr));
12449 
12450 	/*
12451 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12452 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12453 	 * necessary information.
12454 	 */
12455 	if (IPCL_IS_TCP4(connp)) {
12456 		ipvers = IPV4_VERSION;
12457 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12458 	} else {
12459 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12460 		    NULL, &ipp);
12461 		if (mp == NULL) {
12462 			TCP_STAT(tcp_rput_v6_error);
12463 			return;
12464 		}
12465 		iphdr = mp->b_rptr;
12466 		rptr = mp->b_rptr;
12467 	}
12468 	ASSERT(DB_TYPE(mp) == M_DATA);
12469 
12470 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12471 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12472 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12473 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12474 	seg_len = (int)(mp->b_wptr - rptr) -
12475 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12476 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12477 		do {
12478 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12479 			    (uintptr_t)INT_MAX);
12480 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12481 		} while ((mp1 = mp1->b_cont) != NULL &&
12482 		    mp1->b_datap->db_type == M_DATA);
12483 	}
12484 
12485 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12486 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12487 		    seg_len, tcph);
12488 		return;
12489 	}
12490 
12491 	if (sqp != NULL) {
12492 		/*
12493 		 * This is the correct place to update tcp_last_recv_time. Note
12494 		 * that it is also updated for tcp structure that belongs to
12495 		 * global and listener queues which do not really need updating.
12496 		 * But that should not cause any harm.  And it is updated for
12497 		 * all kinds of incoming segments, not only for data segments.
12498 		 */
12499 		tcp->tcp_last_recv_time = lbolt;
12500 	}
12501 
12502 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12503 
12504 	BUMP_LOCAL(tcp->tcp_ibsegs);
12505 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12506 
12507 	if ((flags & TH_URG) && sqp != NULL) {
12508 		/*
12509 		 * TCP can't handle urgent pointers that arrive before
12510 		 * the connection has been accept()ed since it can't
12511 		 * buffer OOB data.  Discard segment if this happens.
12512 		 *
12513 		 * Nor can it reassemble urgent pointers, so discard
12514 		 * if it's not the next segment expected.
12515 		 *
12516 		 * Otherwise, collapse chain into one mblk (discard if
12517 		 * that fails).  This makes sure the headers, retransmitted
12518 		 * data, and new data all are in the same mblk.
12519 		 */
12520 		ASSERT(mp != NULL);
12521 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12522 			freemsg(mp);
12523 			return;
12524 		}
12525 		/* Update pointers into message */
12526 		iphdr = rptr = mp->b_rptr;
12527 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12528 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12529 			/*
12530 			 * Since we can't handle any data with this urgent
12531 			 * pointer that is out of sequence, we expunge
12532 			 * the data.  This allows us to still register
12533 			 * the urgent mark and generate the M_PCSIG,
12534 			 * which we can do.
12535 			 */
12536 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12537 			seg_len = 0;
12538 		}
12539 	}
12540 
12541 	switch (tcp->tcp_state) {
12542 	case TCPS_SYN_SENT:
12543 		if (flags & TH_ACK) {
12544 			/*
12545 			 * Note that our stack cannot send data before a
12546 			 * connection is established, therefore the
12547 			 * following check is valid.  Otherwise, it has
12548 			 * to be changed.
12549 			 */
12550 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12551 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12552 				freemsg(mp);
12553 				if (flags & TH_RST)
12554 					return;
12555 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12556 				    tcp, seg_ack, 0, TH_RST);
12557 				return;
12558 			}
12559 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12560 		}
12561 		if (flags & TH_RST) {
12562 			freemsg(mp);
12563 			if (flags & TH_ACK)
12564 				(void) tcp_clean_death(tcp,
12565 				    ECONNREFUSED, 13);
12566 			return;
12567 		}
12568 		if (!(flags & TH_SYN)) {
12569 			freemsg(mp);
12570 			return;
12571 		}
12572 
12573 		/* Process all TCP options. */
12574 		tcp_process_options(tcp, tcph);
12575 		/*
12576 		 * The following changes our rwnd to be a multiple of the
12577 		 * MIN(peer MSS, our MSS) for performance reason.
12578 		 */
12579 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12580 		    tcp->tcp_mss));
12581 
12582 		/* Is the other end ECN capable? */
12583 		if (tcp->tcp_ecn_ok) {
12584 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12585 				tcp->tcp_ecn_ok = B_FALSE;
12586 			}
12587 		}
12588 		/*
12589 		 * Clear ECN flags because it may interfere with later
12590 		 * processing.
12591 		 */
12592 		flags &= ~(TH_ECE|TH_CWR);
12593 
12594 		tcp->tcp_irs = seg_seq;
12595 		tcp->tcp_rack = seg_seq;
12596 		tcp->tcp_rnxt = seg_seq + 1;
12597 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12598 		if (!TCP_IS_DETACHED(tcp)) {
12599 			/* Allocate room for SACK options if needed. */
12600 			if (tcp->tcp_snd_sack_ok) {
12601 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12602 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12603 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12604 			} else {
12605 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12606 				    tcp->tcp_hdr_len +
12607 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12608 			}
12609 		}
12610 		if (flags & TH_ACK) {
12611 			/*
12612 			 * If we can't get the confirmation upstream, pretend
12613 			 * we didn't even see this one.
12614 			 *
12615 			 * XXX: how can we pretend we didn't see it if we
12616 			 * have updated rnxt et. al.
12617 			 *
12618 			 * For loopback we defer sending up the T_CONN_CON
12619 			 * until after some checks below.
12620 			 */
12621 			mp1 = NULL;
12622 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12623 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12624 				freemsg(mp);
12625 				return;
12626 			}
12627 			/* SYN was acked - making progress */
12628 			if (tcp->tcp_ipversion == IPV6_VERSION)
12629 				tcp->tcp_ip_forward_progress = B_TRUE;
12630 
12631 			/* One for the SYN */
12632 			tcp->tcp_suna = tcp->tcp_iss + 1;
12633 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12634 			tcp->tcp_state = TCPS_ESTABLISHED;
12635 
12636 			/*
12637 			 * If SYN was retransmitted, need to reset all
12638 			 * retransmission info.  This is because this
12639 			 * segment will be treated as a dup ACK.
12640 			 */
12641 			if (tcp->tcp_rexmit) {
12642 				tcp->tcp_rexmit = B_FALSE;
12643 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12644 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12645 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12646 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12647 				tcp->tcp_ms_we_have_waited = 0;
12648 
12649 				/*
12650 				 * Set tcp_cwnd back to 1 MSS, per
12651 				 * recommendation from
12652 				 * draft-floyd-incr-init-win-01.txt,
12653 				 * Increasing TCP's Initial Window.
12654 				 */
12655 				tcp->tcp_cwnd = tcp->tcp_mss;
12656 			}
12657 
12658 			tcp->tcp_swl1 = seg_seq;
12659 			tcp->tcp_swl2 = seg_ack;
12660 
12661 			new_swnd = BE16_TO_U16(tcph->th_win);
12662 			tcp->tcp_swnd = new_swnd;
12663 			if (new_swnd > tcp->tcp_max_swnd)
12664 				tcp->tcp_max_swnd = new_swnd;
12665 
12666 			/*
12667 			 * Always send the three-way handshake ack immediately
12668 			 * in order to make the connection complete as soon as
12669 			 * possible on the accepting host.
12670 			 */
12671 			flags |= TH_ACK_NEEDED;
12672 
12673 			/*
12674 			 * Special case for loopback.  At this point we have
12675 			 * received SYN-ACK from the remote endpoint.  In
12676 			 * order to ensure that both endpoints reach the
12677 			 * fused state prior to any data exchange, the final
12678 			 * ACK needs to be sent before we indicate T_CONN_CON
12679 			 * to the module upstream.
12680 			 */
12681 			if (tcp->tcp_loopback) {
12682 				mblk_t *ack_mp;
12683 
12684 				ASSERT(!tcp->tcp_unfusable);
12685 				ASSERT(mp1 != NULL);
12686 				/*
12687 				 * For loopback, we always get a pure SYN-ACK
12688 				 * and only need to send back the final ACK
12689 				 * with no data (this is because the other
12690 				 * tcp is ours and we don't do T/TCP).  This
12691 				 * final ACK triggers the passive side to
12692 				 * perform fusion in ESTABLISHED state.
12693 				 */
12694 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12695 					if (tcp->tcp_ack_tid != 0) {
12696 						(void) TCP_TIMER_CANCEL(tcp,
12697 						    tcp->tcp_ack_tid);
12698 						tcp->tcp_ack_tid = 0;
12699 					}
12700 					TCP_RECORD_TRACE(tcp, ack_mp,
12701 					    TCP_TRACE_SEND_PKT);
12702 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12703 					BUMP_LOCAL(tcp->tcp_obsegs);
12704 					BUMP_MIB(&tcp_mib, tcpOutAck);
12705 
12706 					/* Send up T_CONN_CON */
12707 					putnext(tcp->tcp_rq, mp1);
12708 
12709 					freemsg(mp);
12710 					return;
12711 				}
12712 				/*
12713 				 * Forget fusion; we need to handle more
12714 				 * complex cases below.  Send the deferred
12715 				 * T_CONN_CON message upstream and proceed
12716 				 * as usual.  Mark this tcp as not capable
12717 				 * of fusion.
12718 				 */
12719 				TCP_STAT(tcp_fusion_unfusable);
12720 				tcp->tcp_unfusable = B_TRUE;
12721 				putnext(tcp->tcp_rq, mp1);
12722 			}
12723 
12724 			/*
12725 			 * Check to see if there is data to be sent.  If
12726 			 * yes, set the transmit flag.  Then check to see
12727 			 * if received data processing needs to be done.
12728 			 * If not, go straight to xmit_check.  This short
12729 			 * cut is OK as we don't support T/TCP.
12730 			 */
12731 			if (tcp->tcp_unsent)
12732 				flags |= TH_XMIT_NEEDED;
12733 
12734 			if (seg_len == 0 && !(flags & TH_URG)) {
12735 				freemsg(mp);
12736 				goto xmit_check;
12737 			}
12738 
12739 			flags &= ~TH_SYN;
12740 			seg_seq++;
12741 			break;
12742 		}
12743 		tcp->tcp_state = TCPS_SYN_RCVD;
12744 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12745 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12746 		if (mp1) {
12747 			DB_CPID(mp1) = tcp->tcp_cpid;
12748 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12749 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12750 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12751 		}
12752 		freemsg(mp);
12753 		return;
12754 	case TCPS_SYN_RCVD:
12755 		if (flags & TH_ACK) {
12756 			/*
12757 			 * In this state, a SYN|ACK packet is either bogus
12758 			 * because the other side must be ACKing our SYN which
12759 			 * indicates it has seen the ACK for their SYN and
12760 			 * shouldn't retransmit it or we're crossing SYNs
12761 			 * on active open.
12762 			 */
12763 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12764 				freemsg(mp);
12765 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12766 				    tcp, seg_ack, 0, TH_RST);
12767 				return;
12768 			}
12769 			/*
12770 			 * NOTE: RFC 793 pg. 72 says this should be
12771 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12772 			 * but that would mean we have an ack that ignored
12773 			 * our SYN.
12774 			 */
12775 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12776 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12777 				freemsg(mp);
12778 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12779 				    tcp, seg_ack, 0, TH_RST);
12780 				return;
12781 			}
12782 		}
12783 		break;
12784 	case TCPS_LISTEN:
12785 		/*
12786 		 * Only a TLI listener can come through this path when a
12787 		 * acceptor is going back to be a listener and a packet
12788 		 * for the acceptor hits the classifier. For a socket
12789 		 * listener, this can never happen because a listener
12790 		 * can never accept connection on itself and hence a
12791 		 * socket acceptor can not go back to being a listener.
12792 		 */
12793 		ASSERT(!TCP_IS_SOCKET(tcp));
12794 		/*FALLTHRU*/
12795 	case TCPS_CLOSED:
12796 	case TCPS_BOUND: {
12797 		conn_t	*new_connp;
12798 
12799 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12800 		if (new_connp != NULL) {
12801 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12802 			return;
12803 		}
12804 		/* We failed to classify. For now just drop the packet */
12805 		freemsg(mp);
12806 		return;
12807 	}
12808 	case TCPS_IDLE:
12809 		/*
12810 		 * Handle the case where the tcp_clean_death() has happened
12811 		 * on a connection (application hasn't closed yet) but a packet
12812 		 * was already queued on squeue before tcp_clean_death()
12813 		 * was processed. Calling tcp_clean_death() twice on same
12814 		 * connection can result in weird behaviour.
12815 		 */
12816 		freemsg(mp);
12817 		return;
12818 	default:
12819 		break;
12820 	}
12821 
12822 	/*
12823 	 * Already on the correct queue/perimeter.
12824 	 * If this is a detached connection and not an eager
12825 	 * connection hanging off a listener then new data
12826 	 * (past the FIN) will cause a reset.
12827 	 * We do a special check here where it
12828 	 * is out of the main line, rather than check
12829 	 * if we are detached every time we see new
12830 	 * data down below.
12831 	 */
12832 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12833 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12834 		BUMP_MIB(&tcp_mib, tcpInClosed);
12835 		TCP_RECORD_TRACE(tcp,
12836 		    mp, TCP_TRACE_RECV_PKT);
12837 
12838 		freemsg(mp);
12839 		/*
12840 		 * This could be an SSL closure alert. We're detached so just
12841 		 * acknowledge it this last time.
12842 		 */
12843 		if (tcp->tcp_kssl_ctx != NULL) {
12844 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12845 			tcp->tcp_kssl_ctx = NULL;
12846 
12847 			tcp->tcp_rnxt += seg_len;
12848 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12849 			flags |= TH_ACK_NEEDED;
12850 			goto ack_check;
12851 		}
12852 
12853 		tcp_xmit_ctl("new data when detached", tcp,
12854 		    tcp->tcp_snxt, 0, TH_RST);
12855 		(void) tcp_clean_death(tcp, EPROTO, 12);
12856 		return;
12857 	}
12858 
12859 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12860 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12861 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12862 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12863 	mss = tcp->tcp_mss;
12864 
12865 	if (tcp->tcp_snd_ts_ok) {
12866 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12867 			/*
12868 			 * This segment is not acceptable.
12869 			 * Drop it and send back an ACK.
12870 			 */
12871 			freemsg(mp);
12872 			flags |= TH_ACK_NEEDED;
12873 			goto ack_check;
12874 		}
12875 	} else if (tcp->tcp_snd_sack_ok) {
12876 		ASSERT(tcp->tcp_sack_info != NULL);
12877 		tcpopt.tcp = tcp;
12878 		/*
12879 		 * SACK info in already updated in tcp_parse_options.  Ignore
12880 		 * all other TCP options...
12881 		 */
12882 		(void) tcp_parse_options(tcph, &tcpopt);
12883 	}
12884 try_again:;
12885 	gap = seg_seq - tcp->tcp_rnxt;
12886 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12887 	/*
12888 	 * gap is the amount of sequence space between what we expect to see
12889 	 * and what we got for seg_seq.  A positive value for gap means
12890 	 * something got lost.  A negative value means we got some old stuff.
12891 	 */
12892 	if (gap < 0) {
12893 		/* Old stuff present.  Is the SYN in there? */
12894 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12895 		    (seg_len != 0)) {
12896 			flags &= ~TH_SYN;
12897 			seg_seq++;
12898 			urp--;
12899 			/* Recompute the gaps after noting the SYN. */
12900 			goto try_again;
12901 		}
12902 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12903 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12904 		    (seg_len > -gap ? -gap : seg_len));
12905 		/* Remove the old stuff from seg_len. */
12906 		seg_len += gap;
12907 		/*
12908 		 * Anything left?
12909 		 * Make sure to check for unack'd FIN when rest of data
12910 		 * has been previously ack'd.
12911 		 */
12912 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12913 			/*
12914 			 * Resets are only valid if they lie within our offered
12915 			 * window.  If the RST bit is set, we just ignore this
12916 			 * segment.
12917 			 */
12918 			if (flags & TH_RST) {
12919 				freemsg(mp);
12920 				return;
12921 			}
12922 
12923 			/*
12924 			 * The arriving of dup data packets indicate that we
12925 			 * may have postponed an ack for too long, or the other
12926 			 * side's RTT estimate is out of shape. Start acking
12927 			 * more often.
12928 			 */
12929 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12930 			    tcp->tcp_rack_cnt >= 1 &&
12931 			    tcp->tcp_rack_abs_max > 2) {
12932 				tcp->tcp_rack_abs_max--;
12933 			}
12934 			tcp->tcp_rack_cur_max = 1;
12935 
12936 			/*
12937 			 * This segment is "unacceptable".  None of its
12938 			 * sequence space lies within our advertized window.
12939 			 *
12940 			 * Adjust seg_len to the original value for tracing.
12941 			 */
12942 			seg_len -= gap;
12943 			if (tcp->tcp_debug) {
12944 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12945 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12946 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12947 				    "seg_len %d, rnxt %u, snxt %u, %s",
12948 				    gap, rgap, flags, seg_seq, seg_ack,
12949 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12950 				    tcp_display(tcp, NULL,
12951 				    DISP_ADDR_AND_PORT));
12952 			}
12953 
12954 			/*
12955 			 * Arrange to send an ACK in response to the
12956 			 * unacceptable segment per RFC 793 page 69. There
12957 			 * is only one small difference between ours and the
12958 			 * acceptability test in the RFC - we accept ACK-only
12959 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12960 			 * will be generated.
12961 			 *
12962 			 * Note that we have to ACK an ACK-only packet at least
12963 			 * for stacks that send 0-length keep-alives with
12964 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12965 			 * section 4.2.3.6. As long as we don't ever generate
12966 			 * an unacceptable packet in response to an incoming
12967 			 * packet that is unacceptable, it should not cause
12968 			 * "ACK wars".
12969 			 */
12970 			flags |=  TH_ACK_NEEDED;
12971 
12972 			/*
12973 			 * Continue processing this segment in order to use the
12974 			 * ACK information it contains, but skip all other
12975 			 * sequence-number processing.	Processing the ACK
12976 			 * information is necessary in order to
12977 			 * re-synchronize connections that may have lost
12978 			 * synchronization.
12979 			 *
12980 			 * We clear seg_len and flag fields related to
12981 			 * sequence number processing as they are not
12982 			 * to be trusted for an unacceptable segment.
12983 			 */
12984 			seg_len = 0;
12985 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12986 			goto process_ack;
12987 		}
12988 
12989 		/* Fix seg_seq, and chew the gap off the front. */
12990 		seg_seq = tcp->tcp_rnxt;
12991 		urp += gap;
12992 		do {
12993 			mblk_t	*mp2;
12994 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12995 			    (uintptr_t)UINT_MAX);
12996 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12997 			if (gap > 0) {
12998 				mp->b_rptr = mp->b_wptr - gap;
12999 				break;
13000 			}
13001 			mp2 = mp;
13002 			mp = mp->b_cont;
13003 			freeb(mp2);
13004 		} while (gap < 0);
13005 		/*
13006 		 * If the urgent data has already been acknowledged, we
13007 		 * should ignore TH_URG below
13008 		 */
13009 		if (urp < 0)
13010 			flags &= ~TH_URG;
13011 	}
13012 	/*
13013 	 * rgap is the amount of stuff received out of window.  A negative
13014 	 * value is the amount out of window.
13015 	 */
13016 	if (rgap < 0) {
13017 		mblk_t	*mp2;
13018 
13019 		if (tcp->tcp_rwnd == 0) {
13020 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
13021 		} else {
13022 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
13023 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
13024 		}
13025 
13026 		/*
13027 		 * seg_len does not include the FIN, so if more than
13028 		 * just the FIN is out of window, we act like we don't
13029 		 * see it.  (If just the FIN is out of window, rgap
13030 		 * will be zero and we will go ahead and acknowledge
13031 		 * the FIN.)
13032 		 */
13033 		flags &= ~TH_FIN;
13034 
13035 		/* Fix seg_len and make sure there is something left. */
13036 		seg_len += rgap;
13037 		if (seg_len <= 0) {
13038 			/*
13039 			 * Resets are only valid if they lie within our offered
13040 			 * window.  If the RST bit is set, we just ignore this
13041 			 * segment.
13042 			 */
13043 			if (flags & TH_RST) {
13044 				freemsg(mp);
13045 				return;
13046 			}
13047 
13048 			/* Per RFC 793, we need to send back an ACK. */
13049 			flags |= TH_ACK_NEEDED;
13050 
13051 			/*
13052 			 * Send SIGURG as soon as possible i.e. even
13053 			 * if the TH_URG was delivered in a window probe
13054 			 * packet (which will be unacceptable).
13055 			 *
13056 			 * We generate a signal if none has been generated
13057 			 * for this connection or if this is a new urgent
13058 			 * byte. Also send a zero-length "unmarked" message
13059 			 * to inform SIOCATMARK that this is not the mark.
13060 			 *
13061 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13062 			 * is sent up. This plus the check for old data
13063 			 * (gap >= 0) handles the wraparound of the sequence
13064 			 * number space without having to always track the
13065 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13066 			 * this max in its rcv_up variable).
13067 			 *
13068 			 * This prevents duplicate SIGURGS due to a "late"
13069 			 * zero-window probe when the T_EXDATA_IND has already
13070 			 * been sent up.
13071 			 */
13072 			if ((flags & TH_URG) &&
13073 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13074 			    tcp->tcp_urp_last))) {
13075 				mp1 = allocb(0, BPRI_MED);
13076 				if (mp1 == NULL) {
13077 					freemsg(mp);
13078 					return;
13079 				}
13080 				if (!TCP_IS_DETACHED(tcp) &&
13081 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13082 				    SIGURG)) {
13083 					/* Try again on the rexmit. */
13084 					freemsg(mp1);
13085 					freemsg(mp);
13086 					return;
13087 				}
13088 				/*
13089 				 * If the next byte would be the mark
13090 				 * then mark with MARKNEXT else mark
13091 				 * with NOTMARKNEXT.
13092 				 */
13093 				if (gap == 0 && urp == 0)
13094 					mp1->b_flag |= MSGMARKNEXT;
13095 				else
13096 					mp1->b_flag |= MSGNOTMARKNEXT;
13097 				freemsg(tcp->tcp_urp_mark_mp);
13098 				tcp->tcp_urp_mark_mp = mp1;
13099 				flags |= TH_SEND_URP_MARK;
13100 				tcp->tcp_urp_last_valid = B_TRUE;
13101 				tcp->tcp_urp_last = urp + seg_seq;
13102 			}
13103 			/*
13104 			 * If this is a zero window probe, continue to
13105 			 * process the ACK part.  But we need to set seg_len
13106 			 * to 0 to avoid data processing.  Otherwise just
13107 			 * drop the segment and send back an ACK.
13108 			 */
13109 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13110 				flags &= ~(TH_SYN | TH_URG);
13111 				seg_len = 0;
13112 				goto process_ack;
13113 			} else {
13114 				freemsg(mp);
13115 				goto ack_check;
13116 			}
13117 		}
13118 		/* Pitch out of window stuff off the end. */
13119 		rgap = seg_len;
13120 		mp2 = mp;
13121 		do {
13122 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13123 			    (uintptr_t)INT_MAX);
13124 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13125 			if (rgap < 0) {
13126 				mp2->b_wptr += rgap;
13127 				if ((mp1 = mp2->b_cont) != NULL) {
13128 					mp2->b_cont = NULL;
13129 					freemsg(mp1);
13130 				}
13131 				break;
13132 			}
13133 		} while ((mp2 = mp2->b_cont) != NULL);
13134 	}
13135 ok:;
13136 	/*
13137 	 * TCP should check ECN info for segments inside the window only.
13138 	 * Therefore the check should be done here.
13139 	 */
13140 	if (tcp->tcp_ecn_ok) {
13141 		if (flags & TH_CWR) {
13142 			tcp->tcp_ecn_echo_on = B_FALSE;
13143 		}
13144 		/*
13145 		 * Note that both ECN_CE and CWR can be set in the
13146 		 * same segment.  In this case, we once again turn
13147 		 * on ECN_ECHO.
13148 		 */
13149 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13150 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13151 
13152 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13153 				tcp->tcp_ecn_echo_on = B_TRUE;
13154 			}
13155 		} else {
13156 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13157 
13158 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13159 			    htonl(IPH_ECN_CE << 20)) {
13160 				tcp->tcp_ecn_echo_on = B_TRUE;
13161 			}
13162 		}
13163 	}
13164 
13165 	/*
13166 	 * Check whether we can update tcp_ts_recent.  This test is
13167 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13168 	 * Extensions for High Performance: An Update", Internet Draft.
13169 	 */
13170 	if (tcp->tcp_snd_ts_ok &&
13171 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13172 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13173 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13174 		tcp->tcp_last_rcv_lbolt = lbolt64;
13175 	}
13176 
13177 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13178 		/*
13179 		 * FIN in an out of order segment.  We record this in
13180 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13181 		 * Clear the FIN so that any check on FIN flag will fail.
13182 		 * Remember that FIN also counts in the sequence number
13183 		 * space.  So we need to ack out of order FIN only segments.
13184 		 */
13185 		if (flags & TH_FIN) {
13186 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13187 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13188 			flags &= ~TH_FIN;
13189 			flags |= TH_ACK_NEEDED;
13190 		}
13191 		if (seg_len > 0) {
13192 			/* Fill in the SACK blk list. */
13193 			if (tcp->tcp_snd_sack_ok) {
13194 				ASSERT(tcp->tcp_sack_info != NULL);
13195 				tcp_sack_insert(tcp->tcp_sack_list,
13196 				    seg_seq, seg_seq + seg_len,
13197 				    &(tcp->tcp_num_sack_blk));
13198 			}
13199 
13200 			/*
13201 			 * Attempt reassembly and see if we have something
13202 			 * ready to go.
13203 			 */
13204 			mp = tcp_reass(tcp, mp, seg_seq);
13205 			/* Always ack out of order packets */
13206 			flags |= TH_ACK_NEEDED | TH_PUSH;
13207 			if (mp) {
13208 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13209 				    (uintptr_t)INT_MAX);
13210 				seg_len = mp->b_cont ? msgdsize(mp) :
13211 					(int)(mp->b_wptr - mp->b_rptr);
13212 				seg_seq = tcp->tcp_rnxt;
13213 				/*
13214 				 * A gap is filled and the seq num and len
13215 				 * of the gap match that of a previously
13216 				 * received FIN, put the FIN flag back in.
13217 				 */
13218 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13219 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13220 					flags |= TH_FIN;
13221 					tcp->tcp_valid_bits &=
13222 					    ~TCP_OFO_FIN_VALID;
13223 				}
13224 			} else {
13225 				/*
13226 				 * Keep going even with NULL mp.
13227 				 * There may be a useful ACK or something else
13228 				 * we don't want to miss.
13229 				 *
13230 				 * But TCP should not perform fast retransmit
13231 				 * because of the ack number.  TCP uses
13232 				 * seg_len == 0 to determine if it is a pure
13233 				 * ACK.  And this is not a pure ACK.
13234 				 */
13235 				seg_len = 0;
13236 				ofo_seg = B_TRUE;
13237 			}
13238 		}
13239 	} else if (seg_len > 0) {
13240 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13241 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13242 		/*
13243 		 * If an out of order FIN was received before, and the seq
13244 		 * num and len of the new segment match that of the FIN,
13245 		 * put the FIN flag back in.
13246 		 */
13247 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13248 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13249 			flags |= TH_FIN;
13250 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13251 		}
13252 	}
13253 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13254 	if (flags & TH_RST) {
13255 		freemsg(mp);
13256 		switch (tcp->tcp_state) {
13257 		case TCPS_SYN_RCVD:
13258 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13259 			break;
13260 		case TCPS_ESTABLISHED:
13261 		case TCPS_FIN_WAIT_1:
13262 		case TCPS_FIN_WAIT_2:
13263 		case TCPS_CLOSE_WAIT:
13264 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13265 			break;
13266 		case TCPS_CLOSING:
13267 		case TCPS_LAST_ACK:
13268 			(void) tcp_clean_death(tcp, 0, 16);
13269 			break;
13270 		default:
13271 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13272 			(void) tcp_clean_death(tcp, ENXIO, 17);
13273 			break;
13274 		}
13275 		return;
13276 	}
13277 	if (flags & TH_SYN) {
13278 		/*
13279 		 * See RFC 793, Page 71
13280 		 *
13281 		 * The seq number must be in the window as it should
13282 		 * be "fixed" above.  If it is outside window, it should
13283 		 * be already rejected.  Note that we allow seg_seq to be
13284 		 * rnxt + rwnd because we want to accept 0 window probe.
13285 		 */
13286 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13287 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13288 		freemsg(mp);
13289 		/*
13290 		 * If the ACK flag is not set, just use our snxt as the
13291 		 * seq number of the RST segment.
13292 		 */
13293 		if (!(flags & TH_ACK)) {
13294 			seg_ack = tcp->tcp_snxt;
13295 		}
13296 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13297 		    TH_RST|TH_ACK);
13298 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13299 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13300 		return;
13301 	}
13302 	/*
13303 	 * urp could be -1 when the urp field in the packet is 0
13304 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13305 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13306 	 */
13307 	if (flags & TH_URG && urp >= 0) {
13308 		if (!tcp->tcp_urp_last_valid ||
13309 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13310 			/*
13311 			 * If we haven't generated the signal yet for this
13312 			 * urgent pointer value, do it now.  Also, send up a
13313 			 * zero-length M_DATA indicating whether or not this is
13314 			 * the mark. The latter is not needed when a
13315 			 * T_EXDATA_IND is sent up. However, if there are
13316 			 * allocation failures this code relies on the sender
13317 			 * retransmitting and the socket code for determining
13318 			 * the mark should not block waiting for the peer to
13319 			 * transmit. Thus, for simplicity we always send up the
13320 			 * mark indication.
13321 			 */
13322 			mp1 = allocb(0, BPRI_MED);
13323 			if (mp1 == NULL) {
13324 				freemsg(mp);
13325 				return;
13326 			}
13327 			if (!TCP_IS_DETACHED(tcp) &&
13328 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13329 				/* Try again on the rexmit. */
13330 				freemsg(mp1);
13331 				freemsg(mp);
13332 				return;
13333 			}
13334 			/*
13335 			 * Mark with NOTMARKNEXT for now.
13336 			 * The code below will change this to MARKNEXT
13337 			 * if we are at the mark.
13338 			 *
13339 			 * If there are allocation failures (e.g. in dupmsg
13340 			 * below) the next time tcp_rput_data sees the urgent
13341 			 * segment it will send up the MSG*MARKNEXT message.
13342 			 */
13343 			mp1->b_flag |= MSGNOTMARKNEXT;
13344 			freemsg(tcp->tcp_urp_mark_mp);
13345 			tcp->tcp_urp_mark_mp = mp1;
13346 			flags |= TH_SEND_URP_MARK;
13347 #ifdef DEBUG
13348 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13349 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13350 			    "last %x, %s",
13351 			    seg_seq, urp, tcp->tcp_urp_last,
13352 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13353 #endif /* DEBUG */
13354 			tcp->tcp_urp_last_valid = B_TRUE;
13355 			tcp->tcp_urp_last = urp + seg_seq;
13356 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13357 			/*
13358 			 * An allocation failure prevented the previous
13359 			 * tcp_rput_data from sending up the allocated
13360 			 * MSG*MARKNEXT message - send it up this time
13361 			 * around.
13362 			 */
13363 			flags |= TH_SEND_URP_MARK;
13364 		}
13365 
13366 		/*
13367 		 * If the urgent byte is in this segment, make sure that it is
13368 		 * all by itself.  This makes it much easier to deal with the
13369 		 * possibility of an allocation failure on the T_exdata_ind.
13370 		 * Note that seg_len is the number of bytes in the segment, and
13371 		 * urp is the offset into the segment of the urgent byte.
13372 		 * urp < seg_len means that the urgent byte is in this segment.
13373 		 */
13374 		if (urp < seg_len) {
13375 			if (seg_len != 1) {
13376 				uint32_t  tmp_rnxt;
13377 				/*
13378 				 * Break it up and feed it back in.
13379 				 * Re-attach the IP header.
13380 				 */
13381 				mp->b_rptr = iphdr;
13382 				if (urp > 0) {
13383 					/*
13384 					 * There is stuff before the urgent
13385 					 * byte.
13386 					 */
13387 					mp1 = dupmsg(mp);
13388 					if (!mp1) {
13389 						/*
13390 						 * Trim from urgent byte on.
13391 						 * The rest will come back.
13392 						 */
13393 						(void) adjmsg(mp,
13394 						    urp - seg_len);
13395 						tcp_rput_data(connp,
13396 						    mp, NULL);
13397 						return;
13398 					}
13399 					(void) adjmsg(mp1, urp - seg_len);
13400 					/* Feed this piece back in. */
13401 					tmp_rnxt = tcp->tcp_rnxt;
13402 					tcp_rput_data(connp, mp1, NULL);
13403 					/*
13404 					 * If the data passed back in was not
13405 					 * processed (ie: bad ACK) sending
13406 					 * the remainder back in will cause a
13407 					 * loop. In this case, drop the
13408 					 * packet and let the sender try
13409 					 * sending a good packet.
13410 					 */
13411 					if (tmp_rnxt == tcp->tcp_rnxt) {
13412 						freemsg(mp);
13413 						return;
13414 					}
13415 				}
13416 				if (urp != seg_len - 1) {
13417 					uint32_t  tmp_rnxt;
13418 					/*
13419 					 * There is stuff after the urgent
13420 					 * byte.
13421 					 */
13422 					mp1 = dupmsg(mp);
13423 					if (!mp1) {
13424 						/*
13425 						 * Trim everything beyond the
13426 						 * urgent byte.  The rest will
13427 						 * come back.
13428 						 */
13429 						(void) adjmsg(mp,
13430 						    urp + 1 - seg_len);
13431 						tcp_rput_data(connp,
13432 						    mp, NULL);
13433 						return;
13434 					}
13435 					(void) adjmsg(mp1, urp + 1 - seg_len);
13436 					tmp_rnxt = tcp->tcp_rnxt;
13437 					tcp_rput_data(connp, mp1, NULL);
13438 					/*
13439 					 * If the data passed back in was not
13440 					 * processed (ie: bad ACK) sending
13441 					 * the remainder back in will cause a
13442 					 * loop. In this case, drop the
13443 					 * packet and let the sender try
13444 					 * sending a good packet.
13445 					 */
13446 					if (tmp_rnxt == tcp->tcp_rnxt) {
13447 						freemsg(mp);
13448 						return;
13449 					}
13450 				}
13451 				tcp_rput_data(connp, mp, NULL);
13452 				return;
13453 			}
13454 			/*
13455 			 * This segment contains only the urgent byte.  We
13456 			 * have to allocate the T_exdata_ind, if we can.
13457 			 */
13458 			if (!tcp->tcp_urp_mp) {
13459 				struct T_exdata_ind *tei;
13460 				mp1 = allocb(sizeof (struct T_exdata_ind),
13461 				    BPRI_MED);
13462 				if (!mp1) {
13463 					/*
13464 					 * Sigh... It'll be back.
13465 					 * Generate any MSG*MARK message now.
13466 					 */
13467 					freemsg(mp);
13468 					seg_len = 0;
13469 					if (flags & TH_SEND_URP_MARK) {
13470 
13471 
13472 						ASSERT(tcp->tcp_urp_mark_mp);
13473 						tcp->tcp_urp_mark_mp->b_flag &=
13474 							~MSGNOTMARKNEXT;
13475 						tcp->tcp_urp_mark_mp->b_flag |=
13476 							MSGMARKNEXT;
13477 					}
13478 					goto ack_check;
13479 				}
13480 				mp1->b_datap->db_type = M_PROTO;
13481 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13482 				tei->PRIM_type = T_EXDATA_IND;
13483 				tei->MORE_flag = 0;
13484 				mp1->b_wptr = (uchar_t *)&tei[1];
13485 				tcp->tcp_urp_mp = mp1;
13486 #ifdef DEBUG
13487 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13488 				    "tcp_rput: allocated exdata_ind %s",
13489 				    tcp_display(tcp, NULL,
13490 				    DISP_PORT_ONLY));
13491 #endif /* DEBUG */
13492 				/*
13493 				 * There is no need to send a separate MSG*MARK
13494 				 * message since the T_EXDATA_IND will be sent
13495 				 * now.
13496 				 */
13497 				flags &= ~TH_SEND_URP_MARK;
13498 				freemsg(tcp->tcp_urp_mark_mp);
13499 				tcp->tcp_urp_mark_mp = NULL;
13500 			}
13501 			/*
13502 			 * Now we are all set.  On the next putnext upstream,
13503 			 * tcp_urp_mp will be non-NULL and will get prepended
13504 			 * to what has to be this piece containing the urgent
13505 			 * byte.  If for any reason we abort this segment below,
13506 			 * if it comes back, we will have this ready, or it
13507 			 * will get blown off in close.
13508 			 */
13509 		} else if (urp == seg_len) {
13510 			/*
13511 			 * The urgent byte is the next byte after this sequence
13512 			 * number. If there is data it is marked with
13513 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13514 			 * since it is not needed. Otherwise, if the code
13515 			 * above just allocated a zero-length tcp_urp_mark_mp
13516 			 * message, that message is tagged with MSGMARKNEXT.
13517 			 * Sending up these MSGMARKNEXT messages makes
13518 			 * SIOCATMARK work correctly even though
13519 			 * the T_EXDATA_IND will not be sent up until the
13520 			 * urgent byte arrives.
13521 			 */
13522 			if (seg_len != 0) {
13523 				flags |= TH_MARKNEXT_NEEDED;
13524 				freemsg(tcp->tcp_urp_mark_mp);
13525 				tcp->tcp_urp_mark_mp = NULL;
13526 				flags &= ~TH_SEND_URP_MARK;
13527 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13528 				flags |= TH_SEND_URP_MARK;
13529 				tcp->tcp_urp_mark_mp->b_flag &=
13530 					~MSGNOTMARKNEXT;
13531 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13532 			}
13533 #ifdef DEBUG
13534 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13535 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13536 			    seg_len, flags,
13537 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13538 #endif /* DEBUG */
13539 		} else {
13540 			/* Data left until we hit mark */
13541 #ifdef DEBUG
13542 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13543 			    "tcp_rput: URP %d bytes left, %s",
13544 			    urp - seg_len, tcp_display(tcp, NULL,
13545 			    DISP_PORT_ONLY));
13546 #endif /* DEBUG */
13547 		}
13548 	}
13549 
13550 process_ack:
13551 	if (!(flags & TH_ACK)) {
13552 		freemsg(mp);
13553 		goto xmit_check;
13554 	}
13555 	}
13556 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13557 
13558 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13559 		tcp->tcp_ip_forward_progress = B_TRUE;
13560 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13561 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13562 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13563 			/* 3-way handshake complete - pass up the T_CONN_IND */
13564 			tcp_t	*listener = tcp->tcp_listener;
13565 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13566 
13567 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13568 			/*
13569 			 * We are here means eager is fine but it can
13570 			 * get a TH_RST at any point between now and till
13571 			 * accept completes and disappear. We need to
13572 			 * ensure that reference to eager is valid after
13573 			 * we get out of eager's perimeter. So we do
13574 			 * an extra refhold.
13575 			 */
13576 			CONN_INC_REF(connp);
13577 
13578 			/*
13579 			 * The listener also exists because of the refhold
13580 			 * done in tcp_conn_request. Its possible that it
13581 			 * might have closed. We will check that once we
13582 			 * get inside listeners context.
13583 			 */
13584 			CONN_INC_REF(listener->tcp_connp);
13585 			if (listener->tcp_connp->conn_sqp ==
13586 			    connp->conn_sqp) {
13587 				tcp_send_conn_ind(listener->tcp_connp, mp,
13588 				    listener->tcp_connp->conn_sqp);
13589 				CONN_DEC_REF(listener->tcp_connp);
13590 			} else if (!tcp->tcp_loopback) {
13591 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13592 				    tcp_send_conn_ind,
13593 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13594 			} else {
13595 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13596 				    tcp_send_conn_ind, listener->tcp_connp,
13597 				    SQTAG_TCP_CONN_IND);
13598 			}
13599 		}
13600 
13601 		if (tcp->tcp_active_open) {
13602 			/*
13603 			 * We are seeing the final ack in the three way
13604 			 * hand shake of a active open'ed connection
13605 			 * so we must send up a T_CONN_CON
13606 			 */
13607 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13608 				freemsg(mp);
13609 				return;
13610 			}
13611 			/*
13612 			 * Don't fuse the loopback endpoints for
13613 			 * simultaneous active opens.
13614 			 */
13615 			if (tcp->tcp_loopback) {
13616 				TCP_STAT(tcp_fusion_unfusable);
13617 				tcp->tcp_unfusable = B_TRUE;
13618 			}
13619 		}
13620 
13621 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13622 		bytes_acked--;
13623 		/* SYN was acked - making progress */
13624 		if (tcp->tcp_ipversion == IPV6_VERSION)
13625 			tcp->tcp_ip_forward_progress = B_TRUE;
13626 
13627 		/*
13628 		 * If SYN was retransmitted, need to reset all
13629 		 * retransmission info as this segment will be
13630 		 * treated as a dup ACK.
13631 		 */
13632 		if (tcp->tcp_rexmit) {
13633 			tcp->tcp_rexmit = B_FALSE;
13634 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13635 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13636 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13637 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13638 			tcp->tcp_ms_we_have_waited = 0;
13639 			tcp->tcp_cwnd = mss;
13640 		}
13641 
13642 		/*
13643 		 * We set the send window to zero here.
13644 		 * This is needed if there is data to be
13645 		 * processed already on the queue.
13646 		 * Later (at swnd_update label), the
13647 		 * "new_swnd > tcp_swnd" condition is satisfied
13648 		 * the XMIT_NEEDED flag is set in the current
13649 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13650 		 * called if there is already data on queue in
13651 		 * this state.
13652 		 */
13653 		tcp->tcp_swnd = 0;
13654 
13655 		if (new_swnd > tcp->tcp_max_swnd)
13656 			tcp->tcp_max_swnd = new_swnd;
13657 		tcp->tcp_swl1 = seg_seq;
13658 		tcp->tcp_swl2 = seg_ack;
13659 		tcp->tcp_state = TCPS_ESTABLISHED;
13660 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13661 
13662 		/* Fuse when both sides are in ESTABLISHED state */
13663 		if (tcp->tcp_loopback && do_tcp_fusion)
13664 			tcp_fuse(tcp, iphdr, tcph);
13665 
13666 	}
13667 	/* This code follows 4.4BSD-Lite2 mostly. */
13668 	if (bytes_acked < 0)
13669 		goto est;
13670 
13671 	/*
13672 	 * If TCP is ECN capable and the congestion experience bit is
13673 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13674 	 * done once per window (or more loosely, per RTT).
13675 	 */
13676 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13677 		tcp->tcp_cwr = B_FALSE;
13678 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13679 		if (!tcp->tcp_cwr) {
13680 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13681 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13682 			tcp->tcp_cwnd = npkt * mss;
13683 			/*
13684 			 * If the cwnd is 0, use the timer to clock out
13685 			 * new segments.  This is required by the ECN spec.
13686 			 */
13687 			if (npkt == 0) {
13688 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13689 				/*
13690 				 * This makes sure that when the ACK comes
13691 				 * back, we will increase tcp_cwnd by 1 MSS.
13692 				 */
13693 				tcp->tcp_cwnd_cnt = 0;
13694 			}
13695 			tcp->tcp_cwr = B_TRUE;
13696 			/*
13697 			 * This marks the end of the current window of in
13698 			 * flight data.  That is why we don't use
13699 			 * tcp_suna + tcp_swnd.  Only data in flight can
13700 			 * provide ECN info.
13701 			 */
13702 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13703 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13704 		}
13705 	}
13706 
13707 	mp1 = tcp->tcp_xmit_head;
13708 	if (bytes_acked == 0) {
13709 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13710 			int dupack_cnt;
13711 
13712 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13713 			/*
13714 			 * Fast retransmit.  When we have seen exactly three
13715 			 * identical ACKs while we have unacked data
13716 			 * outstanding we take it as a hint that our peer
13717 			 * dropped something.
13718 			 *
13719 			 * If TCP is retransmitting, don't do fast retransmit.
13720 			 */
13721 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13722 			    ! tcp->tcp_rexmit) {
13723 				/* Do Limited Transmit */
13724 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13725 				    tcp_dupack_fast_retransmit) {
13726 					/*
13727 					 * RFC 3042
13728 					 *
13729 					 * What we need to do is temporarily
13730 					 * increase tcp_cwnd so that new
13731 					 * data can be sent if it is allowed
13732 					 * by the receive window (tcp_rwnd).
13733 					 * tcp_wput_data() will take care of
13734 					 * the rest.
13735 					 *
13736 					 * If the connection is SACK capable,
13737 					 * only do limited xmit when there
13738 					 * is SACK info.
13739 					 *
13740 					 * Note how tcp_cwnd is incremented.
13741 					 * The first dup ACK will increase
13742 					 * it by 1 MSS.  The second dup ACK
13743 					 * will increase it by 2 MSS.  This
13744 					 * means that only 1 new segment will
13745 					 * be sent for each dup ACK.
13746 					 */
13747 					if (tcp->tcp_unsent > 0 &&
13748 					    (!tcp->tcp_snd_sack_ok ||
13749 					    (tcp->tcp_snd_sack_ok &&
13750 					    tcp->tcp_notsack_list != NULL))) {
13751 						tcp->tcp_cwnd += mss <<
13752 						    (tcp->tcp_dupack_cnt - 1);
13753 						flags |= TH_LIMIT_XMIT;
13754 					}
13755 				} else if (dupack_cnt ==
13756 				    tcp_dupack_fast_retransmit) {
13757 
13758 				/*
13759 				 * If we have reduced tcp_ssthresh
13760 				 * because of ECN, do not reduce it again
13761 				 * unless it is already one window of data
13762 				 * away.  After one window of data, tcp_cwr
13763 				 * should then be cleared.  Note that
13764 				 * for non ECN capable connection, tcp_cwr
13765 				 * should always be false.
13766 				 *
13767 				 * Adjust cwnd since the duplicate
13768 				 * ack indicates that a packet was
13769 				 * dropped (due to congestion.)
13770 				 */
13771 				if (!tcp->tcp_cwr) {
13772 					npkt = ((tcp->tcp_snxt -
13773 					    tcp->tcp_suna) >> 1) / mss;
13774 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13775 					    mss;
13776 					tcp->tcp_cwnd = (npkt +
13777 					    tcp->tcp_dupack_cnt) * mss;
13778 				}
13779 				if (tcp->tcp_ecn_ok) {
13780 					tcp->tcp_cwr = B_TRUE;
13781 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13782 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13783 				}
13784 
13785 				/*
13786 				 * We do Hoe's algorithm.  Refer to her
13787 				 * paper "Improving the Start-up Behavior
13788 				 * of a Congestion Control Scheme for TCP,"
13789 				 * appeared in SIGCOMM'96.
13790 				 *
13791 				 * Save highest seq no we have sent so far.
13792 				 * Be careful about the invisible FIN byte.
13793 				 */
13794 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13795 				    (tcp->tcp_unsent == 0)) {
13796 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13797 				} else {
13798 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13799 				}
13800 
13801 				/*
13802 				 * Do not allow bursty traffic during.
13803 				 * fast recovery.  Refer to Fall and Floyd's
13804 				 * paper "Simulation-based Comparisons of
13805 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13806 				 * This is a best current practise.
13807 				 */
13808 				tcp->tcp_snd_burst = TCP_CWND_SS;
13809 
13810 				/*
13811 				 * For SACK:
13812 				 * Calculate tcp_pipe, which is the
13813 				 * estimated number of bytes in
13814 				 * network.
13815 				 *
13816 				 * tcp_fack is the highest sack'ed seq num
13817 				 * TCP has received.
13818 				 *
13819 				 * tcp_pipe is explained in the above quoted
13820 				 * Fall and Floyd's paper.  tcp_fack is
13821 				 * explained in Mathis and Mahdavi's
13822 				 * "Forward Acknowledgment: Refining TCP
13823 				 * Congestion Control" in SIGCOMM '96.
13824 				 */
13825 				if (tcp->tcp_snd_sack_ok) {
13826 					ASSERT(tcp->tcp_sack_info != NULL);
13827 					if (tcp->tcp_notsack_list != NULL) {
13828 						tcp->tcp_pipe = tcp->tcp_snxt -
13829 						    tcp->tcp_fack;
13830 						tcp->tcp_sack_snxt = seg_ack;
13831 						flags |= TH_NEED_SACK_REXMIT;
13832 					} else {
13833 						/*
13834 						 * Always initialize tcp_pipe
13835 						 * even though we don't have
13836 						 * any SACK info.  If later
13837 						 * we get SACK info and
13838 						 * tcp_pipe is not initialized,
13839 						 * funny things will happen.
13840 						 */
13841 						tcp->tcp_pipe =
13842 						    tcp->tcp_cwnd_ssthresh;
13843 					}
13844 				} else {
13845 					flags |= TH_REXMIT_NEEDED;
13846 				} /* tcp_snd_sack_ok */
13847 
13848 				} else {
13849 					/*
13850 					 * Here we perform congestion
13851 					 * avoidance, but NOT slow start.
13852 					 * This is known as the Fast
13853 					 * Recovery Algorithm.
13854 					 */
13855 					if (tcp->tcp_snd_sack_ok &&
13856 					    tcp->tcp_notsack_list != NULL) {
13857 						flags |= TH_NEED_SACK_REXMIT;
13858 						tcp->tcp_pipe -= mss;
13859 						if (tcp->tcp_pipe < 0)
13860 							tcp->tcp_pipe = 0;
13861 					} else {
13862 					/*
13863 					 * We know that one more packet has
13864 					 * left the pipe thus we can update
13865 					 * cwnd.
13866 					 */
13867 					cwnd = tcp->tcp_cwnd + mss;
13868 					if (cwnd > tcp->tcp_cwnd_max)
13869 						cwnd = tcp->tcp_cwnd_max;
13870 					tcp->tcp_cwnd = cwnd;
13871 					if (tcp->tcp_unsent > 0)
13872 						flags |= TH_XMIT_NEEDED;
13873 					}
13874 				}
13875 			}
13876 		} else if (tcp->tcp_zero_win_probe) {
13877 			/*
13878 			 * If the window has opened, need to arrange
13879 			 * to send additional data.
13880 			 */
13881 			if (new_swnd != 0) {
13882 				/* tcp_suna != tcp_snxt */
13883 				/* Packet contains a window update */
13884 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13885 				tcp->tcp_zero_win_probe = 0;
13886 				tcp->tcp_timer_backoff = 0;
13887 				tcp->tcp_ms_we_have_waited = 0;
13888 
13889 				/*
13890 				 * Transmit starting with tcp_suna since
13891 				 * the one byte probe is not ack'ed.
13892 				 * If TCP has sent more than one identical
13893 				 * probe, tcp_rexmit will be set.  That means
13894 				 * tcp_ss_rexmit() will send out the one
13895 				 * byte along with new data.  Otherwise,
13896 				 * fake the retransmission.
13897 				 */
13898 				flags |= TH_XMIT_NEEDED;
13899 				if (!tcp->tcp_rexmit) {
13900 					tcp->tcp_rexmit = B_TRUE;
13901 					tcp->tcp_dupack_cnt = 0;
13902 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13903 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13904 				}
13905 			}
13906 		}
13907 		goto swnd_update;
13908 	}
13909 
13910 	/*
13911 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13912 	 * If the ACK value acks something that we have not yet sent, it might
13913 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13914 	 * other side.
13915 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13916 	 * state is handled above, so we can always just drop the segment and
13917 	 * send an ACK here.
13918 	 *
13919 	 * Should we send ACKs in response to ACK only segments?
13920 	 */
13921 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13922 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13923 		/* drop the received segment */
13924 		freemsg(mp);
13925 
13926 		/*
13927 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13928 		 * greater than 0, check if the number of such
13929 		 * bogus ACks is greater than that count.  If yes,
13930 		 * don't send back any ACK.  This prevents TCP from
13931 		 * getting into an ACK storm if somehow an attacker
13932 		 * successfully spoofs an acceptable segment to our
13933 		 * peer.
13934 		 */
13935 		if (tcp_drop_ack_unsent_cnt > 0 &&
13936 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13937 			TCP_STAT(tcp_in_ack_unsent_drop);
13938 			return;
13939 		}
13940 		mp = tcp_ack_mp(tcp);
13941 		if (mp != NULL) {
13942 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13943 			BUMP_LOCAL(tcp->tcp_obsegs);
13944 			BUMP_MIB(&tcp_mib, tcpOutAck);
13945 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13946 		}
13947 		return;
13948 	}
13949 
13950 	/*
13951 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13952 	 * blocks that are covered by this ACK.
13953 	 */
13954 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13955 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13956 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13957 	}
13958 
13959 	/*
13960 	 * If we got an ACK after fast retransmit, check to see
13961 	 * if it is a partial ACK.  If it is not and the congestion
13962 	 * window was inflated to account for the other side's
13963 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13964 	 */
13965 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13966 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13967 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13968 			tcp->tcp_dupack_cnt = 0;
13969 			/*
13970 			 * Restore the orig tcp_cwnd_ssthresh after
13971 			 * fast retransmit phase.
13972 			 */
13973 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13974 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13975 			}
13976 			tcp->tcp_rexmit_max = seg_ack;
13977 			tcp->tcp_cwnd_cnt = 0;
13978 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13979 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13980 
13981 			/*
13982 			 * Remove all notsack info to avoid confusion with
13983 			 * the next fast retrasnmit/recovery phase.
13984 			 */
13985 			if (tcp->tcp_snd_sack_ok &&
13986 			    tcp->tcp_notsack_list != NULL) {
13987 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13988 			}
13989 		} else {
13990 			if (tcp->tcp_snd_sack_ok &&
13991 			    tcp->tcp_notsack_list != NULL) {
13992 				flags |= TH_NEED_SACK_REXMIT;
13993 				tcp->tcp_pipe -= mss;
13994 				if (tcp->tcp_pipe < 0)
13995 					tcp->tcp_pipe = 0;
13996 			} else {
13997 				/*
13998 				 * Hoe's algorithm:
13999 				 *
14000 				 * Retransmit the unack'ed segment and
14001 				 * restart fast recovery.  Note that we
14002 				 * need to scale back tcp_cwnd to the
14003 				 * original value when we started fast
14004 				 * recovery.  This is to prevent overly
14005 				 * aggressive behaviour in sending new
14006 				 * segments.
14007 				 */
14008 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14009 					tcp_dupack_fast_retransmit * mss;
14010 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14011 				flags |= TH_REXMIT_NEEDED;
14012 			}
14013 		}
14014 	} else {
14015 		tcp->tcp_dupack_cnt = 0;
14016 		if (tcp->tcp_rexmit) {
14017 			/*
14018 			 * TCP is retranmitting.  If the ACK ack's all
14019 			 * outstanding data, update tcp_rexmit_max and
14020 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14021 			 * to the correct value.
14022 			 *
14023 			 * Note that SEQ_LEQ() is used.  This is to avoid
14024 			 * unnecessary fast retransmit caused by dup ACKs
14025 			 * received when TCP does slow start retransmission
14026 			 * after a time out.  During this phase, TCP may
14027 			 * send out segments which are already received.
14028 			 * This causes dup ACKs to be sent back.
14029 			 */
14030 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14031 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14032 					tcp->tcp_rexmit_nxt = seg_ack;
14033 				}
14034 				if (seg_ack != tcp->tcp_rexmit_max) {
14035 					flags |= TH_XMIT_NEEDED;
14036 				}
14037 			} else {
14038 				tcp->tcp_rexmit = B_FALSE;
14039 				tcp->tcp_xmit_zc_clean = B_FALSE;
14040 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14041 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14042 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14043 			}
14044 			tcp->tcp_ms_we_have_waited = 0;
14045 		}
14046 	}
14047 
14048 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
14049 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
14050 	tcp->tcp_suna = seg_ack;
14051 	if (tcp->tcp_zero_win_probe != 0) {
14052 		tcp->tcp_zero_win_probe = 0;
14053 		tcp->tcp_timer_backoff = 0;
14054 	}
14055 
14056 	/*
14057 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14058 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14059 	 * will not reach here.
14060 	 */
14061 	if (mp1 == NULL) {
14062 		goto fin_acked;
14063 	}
14064 
14065 	/*
14066 	 * Update the congestion window.
14067 	 *
14068 	 * If TCP is not ECN capable or TCP is ECN capable but the
14069 	 * congestion experience bit is not set, increase the tcp_cwnd as
14070 	 * usual.
14071 	 */
14072 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14073 		cwnd = tcp->tcp_cwnd;
14074 		add = mss;
14075 
14076 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14077 			/*
14078 			 * This is to prevent an increase of less than 1 MSS of
14079 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14080 			 * may send out tinygrams in order to preserve mblk
14081 			 * boundaries.
14082 			 *
14083 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14084 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14085 			 * increased by 1 MSS for every RTTs.
14086 			 */
14087 			if (tcp->tcp_cwnd_cnt <= 0) {
14088 				tcp->tcp_cwnd_cnt = cwnd + add;
14089 			} else {
14090 				tcp->tcp_cwnd_cnt -= add;
14091 				add = 0;
14092 			}
14093 		}
14094 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14095 	}
14096 
14097 	/* See if the latest urgent data has been acknowledged */
14098 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14099 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14100 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14101 
14102 	/* Can we update the RTT estimates? */
14103 	if (tcp->tcp_snd_ts_ok) {
14104 		/* Ignore zero timestamp echo-reply. */
14105 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14106 			tcp_set_rto(tcp, (int32_t)lbolt -
14107 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14108 		}
14109 
14110 		/* If needed, restart the timer. */
14111 		if (tcp->tcp_set_timer == 1) {
14112 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14113 			tcp->tcp_set_timer = 0;
14114 		}
14115 		/*
14116 		 * Update tcp_csuna in case the other side stops sending
14117 		 * us timestamps.
14118 		 */
14119 		tcp->tcp_csuna = tcp->tcp_snxt;
14120 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14121 		/*
14122 		 * An ACK sequence we haven't seen before, so get the RTT
14123 		 * and update the RTO. But first check if the timestamp is
14124 		 * valid to use.
14125 		 */
14126 		if ((mp1->b_next != NULL) &&
14127 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14128 			tcp_set_rto(tcp, (int32_t)lbolt -
14129 			    (int32_t)(intptr_t)mp1->b_prev);
14130 		else
14131 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14132 
14133 		/* Remeber the last sequence to be ACKed */
14134 		tcp->tcp_csuna = seg_ack;
14135 		if (tcp->tcp_set_timer == 1) {
14136 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14137 			tcp->tcp_set_timer = 0;
14138 		}
14139 	} else {
14140 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
14141 	}
14142 
14143 	/* Eat acknowledged bytes off the xmit queue. */
14144 	for (;;) {
14145 		mblk_t	*mp2;
14146 		uchar_t	*wptr;
14147 
14148 		wptr = mp1->b_wptr;
14149 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14150 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14151 		if (bytes_acked < 0) {
14152 			mp1->b_rptr = wptr + bytes_acked;
14153 			/*
14154 			 * Set a new timestamp if all the bytes timed by the
14155 			 * old timestamp have been ack'ed.
14156 			 */
14157 			if (SEQ_GT(seg_ack,
14158 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14159 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14160 				mp1->b_next = NULL;
14161 			}
14162 			break;
14163 		}
14164 		mp1->b_next = NULL;
14165 		mp1->b_prev = NULL;
14166 		mp2 = mp1;
14167 		mp1 = mp1->b_cont;
14168 
14169 		/*
14170 		 * This notification is required for some zero-copy
14171 		 * clients to maintain a copy semantic. After the data
14172 		 * is ack'ed, client is safe to modify or reuse the buffer.
14173 		 */
14174 		if (tcp->tcp_snd_zcopy_aware &&
14175 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14176 			tcp_zcopy_notify(tcp);
14177 		freeb(mp2);
14178 		if (bytes_acked == 0) {
14179 			if (mp1 == NULL) {
14180 				/* Everything is ack'ed, clear the tail. */
14181 				tcp->tcp_xmit_tail = NULL;
14182 				/*
14183 				 * Cancel the timer unless we are still
14184 				 * waiting for an ACK for the FIN packet.
14185 				 */
14186 				if (tcp->tcp_timer_tid != 0 &&
14187 				    tcp->tcp_snxt == tcp->tcp_suna) {
14188 					(void) TCP_TIMER_CANCEL(tcp,
14189 					    tcp->tcp_timer_tid);
14190 					tcp->tcp_timer_tid = 0;
14191 				}
14192 				goto pre_swnd_update;
14193 			}
14194 			if (mp2 != tcp->tcp_xmit_tail)
14195 				break;
14196 			tcp->tcp_xmit_tail = mp1;
14197 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14198 			    (uintptr_t)INT_MAX);
14199 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14200 			    mp1->b_rptr);
14201 			break;
14202 		}
14203 		if (mp1 == NULL) {
14204 			/*
14205 			 * More was acked but there is nothing more
14206 			 * outstanding.  This means that the FIN was
14207 			 * just acked or that we're talking to a clown.
14208 			 */
14209 fin_acked:
14210 			ASSERT(tcp->tcp_fin_sent);
14211 			tcp->tcp_xmit_tail = NULL;
14212 			if (tcp->tcp_fin_sent) {
14213 				/* FIN was acked - making progress */
14214 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14215 				    !tcp->tcp_fin_acked)
14216 					tcp->tcp_ip_forward_progress = B_TRUE;
14217 				tcp->tcp_fin_acked = B_TRUE;
14218 				if (tcp->tcp_linger_tid != 0 &&
14219 				    TCP_TIMER_CANCEL(tcp,
14220 					tcp->tcp_linger_tid) >= 0) {
14221 					tcp_stop_lingering(tcp);
14222 				}
14223 			} else {
14224 				/*
14225 				 * We should never get here because
14226 				 * we have already checked that the
14227 				 * number of bytes ack'ed should be
14228 				 * smaller than or equal to what we
14229 				 * have sent so far (it is the
14230 				 * acceptability check of the ACK).
14231 				 * We can only get here if the send
14232 				 * queue is corrupted.
14233 				 *
14234 				 * Terminate the connection and
14235 				 * panic the system.  It is better
14236 				 * for us to panic instead of
14237 				 * continuing to avoid other disaster.
14238 				 */
14239 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14240 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14241 				panic("Memory corruption "
14242 				    "detected for connection %s.",
14243 				    tcp_display(tcp, NULL,
14244 					DISP_ADDR_AND_PORT));
14245 				/*NOTREACHED*/
14246 			}
14247 			goto pre_swnd_update;
14248 		}
14249 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14250 	}
14251 	if (tcp->tcp_unsent) {
14252 		flags |= TH_XMIT_NEEDED;
14253 	}
14254 pre_swnd_update:
14255 	tcp->tcp_xmit_head = mp1;
14256 swnd_update:
14257 	/*
14258 	 * The following check is different from most other implementations.
14259 	 * For bi-directional transfer, when segments are dropped, the
14260 	 * "normal" check will not accept a window update in those
14261 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14262 	 * segments which are outside receiver's window.  As TCP accepts
14263 	 * the ack in those retransmitted segments, if the window update in
14264 	 * the same segment is not accepted, TCP will incorrectly calculates
14265 	 * that it can send more segments.  This can create a deadlock
14266 	 * with the receiver if its window becomes zero.
14267 	 */
14268 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14269 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14270 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14271 		/*
14272 		 * The criteria for update is:
14273 		 *
14274 		 * 1. the segment acknowledges some data.  Or
14275 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14276 		 * 3. the segment is not old and the advertised window is
14277 		 * larger than the previous advertised window.
14278 		 */
14279 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14280 			flags |= TH_XMIT_NEEDED;
14281 		tcp->tcp_swnd = new_swnd;
14282 		if (new_swnd > tcp->tcp_max_swnd)
14283 			tcp->tcp_max_swnd = new_swnd;
14284 		tcp->tcp_swl1 = seg_seq;
14285 		tcp->tcp_swl2 = seg_ack;
14286 	}
14287 est:
14288 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14289 
14290 		switch (tcp->tcp_state) {
14291 		case TCPS_FIN_WAIT_1:
14292 			if (tcp->tcp_fin_acked) {
14293 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14294 				/*
14295 				 * We implement the non-standard BSD/SunOS
14296 				 * FIN_WAIT_2 flushing algorithm.
14297 				 * If there is no user attached to this
14298 				 * TCP endpoint, then this TCP struct
14299 				 * could hang around forever in FIN_WAIT_2
14300 				 * state if the peer forgets to send us
14301 				 * a FIN.  To prevent this, we wait only
14302 				 * 2*MSL (a convenient time value) for
14303 				 * the FIN to arrive.  If it doesn't show up,
14304 				 * we flush the TCP endpoint.  This algorithm,
14305 				 * though a violation of RFC-793, has worked
14306 				 * for over 10 years in BSD systems.
14307 				 * Note: SunOS 4.x waits 675 seconds before
14308 				 * flushing the FIN_WAIT_2 connection.
14309 				 */
14310 				TCP_TIMER_RESTART(tcp,
14311 				    tcp_fin_wait_2_flush_interval);
14312 			}
14313 			break;
14314 		case TCPS_FIN_WAIT_2:
14315 			break;	/* Shutdown hook? */
14316 		case TCPS_LAST_ACK:
14317 			freemsg(mp);
14318 			if (tcp->tcp_fin_acked) {
14319 				(void) tcp_clean_death(tcp, 0, 19);
14320 				return;
14321 			}
14322 			goto xmit_check;
14323 		case TCPS_CLOSING:
14324 			if (tcp->tcp_fin_acked) {
14325 				tcp->tcp_state = TCPS_TIME_WAIT;
14326 				if (!TCP_IS_DETACHED(tcp)) {
14327 					TCP_TIMER_RESTART(tcp,
14328 					    tcp_time_wait_interval);
14329 				} else {
14330 					tcp_time_wait_append(tcp);
14331 					TCP_DBGSTAT(tcp_rput_time_wait);
14332 				}
14333 			}
14334 			/*FALLTHRU*/
14335 		case TCPS_CLOSE_WAIT:
14336 			freemsg(mp);
14337 			goto xmit_check;
14338 		default:
14339 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14340 			break;
14341 		}
14342 	}
14343 	if (flags & TH_FIN) {
14344 		/* Make sure we ack the fin */
14345 		flags |= TH_ACK_NEEDED;
14346 		if (!tcp->tcp_fin_rcvd) {
14347 			tcp->tcp_fin_rcvd = B_TRUE;
14348 			tcp->tcp_rnxt++;
14349 			tcph = tcp->tcp_tcph;
14350 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14351 
14352 			/*
14353 			 * Generate the ordrel_ind at the end unless we
14354 			 * are an eager guy.
14355 			 * In the eager case tcp_rsrv will do this when run
14356 			 * after tcp_accept is done.
14357 			 */
14358 			if (tcp->tcp_listener == NULL &&
14359 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14360 				flags |= TH_ORDREL_NEEDED;
14361 			switch (tcp->tcp_state) {
14362 			case TCPS_SYN_RCVD:
14363 			case TCPS_ESTABLISHED:
14364 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14365 				/* Keepalive? */
14366 				break;
14367 			case TCPS_FIN_WAIT_1:
14368 				if (!tcp->tcp_fin_acked) {
14369 					tcp->tcp_state = TCPS_CLOSING;
14370 					break;
14371 				}
14372 				/* FALLTHRU */
14373 			case TCPS_FIN_WAIT_2:
14374 				tcp->tcp_state = TCPS_TIME_WAIT;
14375 				if (!TCP_IS_DETACHED(tcp)) {
14376 					TCP_TIMER_RESTART(tcp,
14377 					    tcp_time_wait_interval);
14378 				} else {
14379 					tcp_time_wait_append(tcp);
14380 					TCP_DBGSTAT(tcp_rput_time_wait);
14381 				}
14382 				if (seg_len) {
14383 					/*
14384 					 * implies data piggybacked on FIN.
14385 					 * break to handle data.
14386 					 */
14387 					break;
14388 				}
14389 				freemsg(mp);
14390 				goto ack_check;
14391 			}
14392 		}
14393 	}
14394 	if (mp == NULL)
14395 		goto xmit_check;
14396 	if (seg_len == 0) {
14397 		freemsg(mp);
14398 		goto xmit_check;
14399 	}
14400 	if (mp->b_rptr == mp->b_wptr) {
14401 		/*
14402 		 * The header has been consumed, so we remove the
14403 		 * zero-length mblk here.
14404 		 */
14405 		mp1 = mp;
14406 		mp = mp->b_cont;
14407 		freeb(mp1);
14408 	}
14409 	tcph = tcp->tcp_tcph;
14410 	tcp->tcp_rack_cnt++;
14411 	{
14412 		uint32_t cur_max;
14413 
14414 		cur_max = tcp->tcp_rack_cur_max;
14415 		if (tcp->tcp_rack_cnt >= cur_max) {
14416 			/*
14417 			 * We have more unacked data than we should - send
14418 			 * an ACK now.
14419 			 */
14420 			flags |= TH_ACK_NEEDED;
14421 			cur_max++;
14422 			if (cur_max > tcp->tcp_rack_abs_max)
14423 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14424 			else
14425 				tcp->tcp_rack_cur_max = cur_max;
14426 		} else if (TCP_IS_DETACHED(tcp)) {
14427 			/* We don't have an ACK timer for detached TCP. */
14428 			flags |= TH_ACK_NEEDED;
14429 		} else if (seg_len < mss) {
14430 			/*
14431 			 * If we get a segment that is less than an mss, and we
14432 			 * already have unacknowledged data, and the amount
14433 			 * unacknowledged is not a multiple of mss, then we
14434 			 * better generate an ACK now.  Otherwise, this may be
14435 			 * the tail piece of a transaction, and we would rather
14436 			 * wait for the response.
14437 			 */
14438 			uint32_t udif;
14439 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14440 			    (uintptr_t)INT_MAX);
14441 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14442 			if (udif && (udif % mss))
14443 				flags |= TH_ACK_NEEDED;
14444 			else
14445 				flags |= TH_ACK_TIMER_NEEDED;
14446 		} else {
14447 			/* Start delayed ack timer */
14448 			flags |= TH_ACK_TIMER_NEEDED;
14449 		}
14450 	}
14451 	tcp->tcp_rnxt += seg_len;
14452 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14453 
14454 	/* Update SACK list */
14455 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14456 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14457 		    &(tcp->tcp_num_sack_blk));
14458 	}
14459 
14460 	if (tcp->tcp_urp_mp) {
14461 		tcp->tcp_urp_mp->b_cont = mp;
14462 		mp = tcp->tcp_urp_mp;
14463 		tcp->tcp_urp_mp = NULL;
14464 		/* Ready for a new signal. */
14465 		tcp->tcp_urp_last_valid = B_FALSE;
14466 #ifdef DEBUG
14467 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14468 		    "tcp_rput: sending exdata_ind %s",
14469 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14470 #endif /* DEBUG */
14471 	}
14472 
14473 	/*
14474 	 * Check for ancillary data changes compared to last segment.
14475 	 */
14476 	if (tcp->tcp_ipv6_recvancillary != 0) {
14477 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14478 		if (mp == NULL)
14479 			return;
14480 	}
14481 
14482 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14483 		/*
14484 		 * Side queue inbound data until the accept happens.
14485 		 * tcp_accept/tcp_rput drains this when the accept happens.
14486 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14487 		 * T_EXDATA_IND) it is queued on b_next.
14488 		 * XXX Make urgent data use this. Requires:
14489 		 *	Removing tcp_listener check for TH_URG
14490 		 *	Making M_PCPROTO and MARK messages skip the eager case
14491 		 */
14492 
14493 		if (tcp->tcp_kssl_pending) {
14494 			tcp_kssl_input(tcp, mp);
14495 		} else {
14496 			tcp_rcv_enqueue(tcp, mp, seg_len);
14497 		}
14498 	} else {
14499 		if (mp->b_datap->db_type != M_DATA ||
14500 		    (flags & TH_MARKNEXT_NEEDED)) {
14501 			if (tcp->tcp_rcv_list != NULL) {
14502 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14503 			}
14504 			ASSERT(tcp->tcp_rcv_list == NULL ||
14505 			    tcp->tcp_fused_sigurg);
14506 			if (flags & TH_MARKNEXT_NEEDED) {
14507 #ifdef DEBUG
14508 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14509 				    "tcp_rput: sending MSGMARKNEXT %s",
14510 				    tcp_display(tcp, NULL,
14511 				    DISP_PORT_ONLY));
14512 #endif /* DEBUG */
14513 				mp->b_flag |= MSGMARKNEXT;
14514 				flags &= ~TH_MARKNEXT_NEEDED;
14515 			}
14516 
14517 			/* Does this need SSL processing first? */
14518 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14519 			    (DB_TYPE(mp) == M_DATA)) {
14520 				tcp_kssl_input(tcp, mp);
14521 			} else {
14522 				putnext(tcp->tcp_rq, mp);
14523 				if (!canputnext(tcp->tcp_rq))
14524 					tcp->tcp_rwnd -= seg_len;
14525 			}
14526 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
14527 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
14528 			if (tcp->tcp_rcv_list != NULL) {
14529 				/*
14530 				 * Enqueue the new segment first and then
14531 				 * call tcp_rcv_drain() to send all data
14532 				 * up.  The other way to do this is to
14533 				 * send all queued data up and then call
14534 				 * putnext() to send the new segment up.
14535 				 * This way can remove the else part later
14536 				 * on.
14537 				 *
14538 				 * We don't this to avoid one more call to
14539 				 * canputnext() as tcp_rcv_drain() needs to
14540 				 * call canputnext().
14541 				 */
14542 				tcp_rcv_enqueue(tcp, mp, seg_len);
14543 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14544 			} else {
14545 				/* Does this need SSL processing first? */
14546 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14547 				    (DB_TYPE(mp) == M_DATA)) {
14548 					tcp_kssl_input(tcp, mp);
14549 				} else {
14550 					putnext(tcp->tcp_rq, mp);
14551 					if (!canputnext(tcp->tcp_rq))
14552 						tcp->tcp_rwnd -= seg_len;
14553 				}
14554 			}
14555 		} else {
14556 			/*
14557 			 * Enqueue all packets when processing an mblk
14558 			 * from the co queue and also enqueue normal packets.
14559 			 */
14560 			tcp_rcv_enqueue(tcp, mp, seg_len);
14561 		}
14562 		/*
14563 		 * Make sure the timer is running if we have data waiting
14564 		 * for a push bit. This provides resiliency against
14565 		 * implementations that do not correctly generate push bits.
14566 		 */
14567 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
14568 			/*
14569 			 * The connection may be closed at this point, so don't
14570 			 * do anything for a detached tcp.
14571 			 */
14572 			if (!TCP_IS_DETACHED(tcp))
14573 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14574 				    tcp_push_timer,
14575 				    MSEC_TO_TICK(tcp_push_timer_interval));
14576 		}
14577 	}
14578 xmit_check:
14579 	/* Is there anything left to do? */
14580 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14581 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14582 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14583 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14584 		goto done;
14585 
14586 	/* Any transmit work to do and a non-zero window? */
14587 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14588 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14589 		if (flags & TH_REXMIT_NEEDED) {
14590 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14591 
14592 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14593 			if (snd_size > mss)
14594 				snd_size = mss;
14595 			if (snd_size > tcp->tcp_swnd)
14596 				snd_size = tcp->tcp_swnd;
14597 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14598 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14599 			    B_TRUE);
14600 
14601 			if (mp1 != NULL) {
14602 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14603 				tcp->tcp_csuna = tcp->tcp_snxt;
14604 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14605 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14606 				TCP_RECORD_TRACE(tcp, mp1,
14607 				    TCP_TRACE_SEND_PKT);
14608 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14609 			}
14610 		}
14611 		if (flags & TH_NEED_SACK_REXMIT) {
14612 			tcp_sack_rxmit(tcp, &flags);
14613 		}
14614 		/*
14615 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14616 		 * out new segment.  Note that tcp_rexmit should not be
14617 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14618 		 */
14619 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14620 			if (!tcp->tcp_rexmit) {
14621 				tcp_wput_data(tcp, NULL, B_FALSE);
14622 			} else {
14623 				tcp_ss_rexmit(tcp);
14624 			}
14625 		}
14626 		/*
14627 		 * Adjust tcp_cwnd back to normal value after sending
14628 		 * new data segments.
14629 		 */
14630 		if (flags & TH_LIMIT_XMIT) {
14631 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14632 			/*
14633 			 * This will restart the timer.  Restarting the
14634 			 * timer is used to avoid a timeout before the
14635 			 * limited transmitted segment's ACK gets back.
14636 			 */
14637 			if (tcp->tcp_xmit_head != NULL)
14638 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14639 		}
14640 
14641 		/* Anything more to do? */
14642 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14643 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14644 			goto done;
14645 	}
14646 ack_check:
14647 	if (flags & TH_SEND_URP_MARK) {
14648 		ASSERT(tcp->tcp_urp_mark_mp);
14649 		/*
14650 		 * Send up any queued data and then send the mark message
14651 		 */
14652 		if (tcp->tcp_rcv_list != NULL) {
14653 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14654 		}
14655 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14656 
14657 		mp1 = tcp->tcp_urp_mark_mp;
14658 		tcp->tcp_urp_mark_mp = NULL;
14659 #ifdef DEBUG
14660 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14661 		    "tcp_rput: sending zero-length %s %s",
14662 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14663 		    "MSGNOTMARKNEXT"),
14664 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14665 #endif /* DEBUG */
14666 		putnext(tcp->tcp_rq, mp1);
14667 		flags &= ~TH_SEND_URP_MARK;
14668 	}
14669 	if (flags & TH_ACK_NEEDED) {
14670 		/*
14671 		 * Time to send an ack for some reason.
14672 		 */
14673 		mp1 = tcp_ack_mp(tcp);
14674 
14675 		if (mp1 != NULL) {
14676 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14677 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14678 			BUMP_LOCAL(tcp->tcp_obsegs);
14679 			BUMP_MIB(&tcp_mib, tcpOutAck);
14680 		}
14681 		if (tcp->tcp_ack_tid != 0) {
14682 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14683 			tcp->tcp_ack_tid = 0;
14684 		}
14685 	}
14686 	if (flags & TH_ACK_TIMER_NEEDED) {
14687 		/*
14688 		 * Arrange for deferred ACK or push wait timeout.
14689 		 * Start timer if it is not already running.
14690 		 */
14691 		if (tcp->tcp_ack_tid == 0) {
14692 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14693 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14694 			    (clock_t)tcp_local_dack_interval :
14695 			    (clock_t)tcp_deferred_ack_interval));
14696 		}
14697 	}
14698 	if (flags & TH_ORDREL_NEEDED) {
14699 		/*
14700 		 * Send up the ordrel_ind unless we are an eager guy.
14701 		 * In the eager case tcp_rsrv will do this when run
14702 		 * after tcp_accept is done.
14703 		 */
14704 		ASSERT(tcp->tcp_listener == NULL);
14705 		if (tcp->tcp_rcv_list != NULL) {
14706 			/*
14707 			 * Push any mblk(s) enqueued from co processing.
14708 			 */
14709 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14710 		}
14711 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14712 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14713 			tcp->tcp_ordrel_done = B_TRUE;
14714 			putnext(tcp->tcp_rq, mp1);
14715 			if (tcp->tcp_deferred_clean_death) {
14716 				/*
14717 				 * tcp_clean_death was deferred
14718 				 * for T_ORDREL_IND - do it now
14719 				 */
14720 				(void) tcp_clean_death(tcp,
14721 				    tcp->tcp_client_errno, 20);
14722 				tcp->tcp_deferred_clean_death =	B_FALSE;
14723 			}
14724 		} else {
14725 			/*
14726 			 * Run the orderly release in the
14727 			 * service routine.
14728 			 */
14729 			qenable(tcp->tcp_rq);
14730 			/*
14731 			 * Caveat(XXX): The machine may be so
14732 			 * overloaded that tcp_rsrv() is not scheduled
14733 			 * until after the endpoint has transitioned
14734 			 * to TCPS_TIME_WAIT
14735 			 * and tcp_time_wait_interval expires. Then
14736 			 * tcp_timer() will blow away state in tcp_t
14737 			 * and T_ORDREL_IND will never be delivered
14738 			 * upstream. Unlikely but potentially
14739 			 * a problem.
14740 			 */
14741 		}
14742 	}
14743 done:
14744 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14745 }
14746 
14747 /*
14748  * This function does PAWS protection check. Returns B_TRUE if the
14749  * segment passes the PAWS test, else returns B_FALSE.
14750  */
14751 boolean_t
14752 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14753 {
14754 	uint8_t	flags;
14755 	int	options;
14756 	uint8_t *up;
14757 
14758 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14759 	/*
14760 	 * If timestamp option is aligned nicely, get values inline,
14761 	 * otherwise call general routine to parse.  Only do that
14762 	 * if timestamp is the only option.
14763 	 */
14764 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14765 	    TCPOPT_REAL_TS_LEN &&
14766 	    OK_32PTR((up = ((uint8_t *)tcph) +
14767 	    TCP_MIN_HEADER_LENGTH)) &&
14768 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14769 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14770 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14771 
14772 		options = TCP_OPT_TSTAMP_PRESENT;
14773 	} else {
14774 		if (tcp->tcp_snd_sack_ok) {
14775 			tcpoptp->tcp = tcp;
14776 		} else {
14777 			tcpoptp->tcp = NULL;
14778 		}
14779 		options = tcp_parse_options(tcph, tcpoptp);
14780 	}
14781 
14782 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14783 		/*
14784 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14785 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14786 		 */
14787 		if ((flags & TH_RST) == 0 &&
14788 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14789 		    tcp->tcp_ts_recent)) {
14790 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14791 			    PAWS_TIMEOUT)) {
14792 				/* This segment is not acceptable. */
14793 				return (B_FALSE);
14794 			} else {
14795 				/*
14796 				 * Connection has been idle for
14797 				 * too long.  Reset the timestamp
14798 				 * and assume the segment is valid.
14799 				 */
14800 				tcp->tcp_ts_recent =
14801 				    tcpoptp->tcp_opt_ts_val;
14802 			}
14803 		}
14804 	} else {
14805 		/*
14806 		 * If we don't get a timestamp on every packet, we
14807 		 * figure we can't really trust 'em, so we stop sending
14808 		 * and parsing them.
14809 		 */
14810 		tcp->tcp_snd_ts_ok = B_FALSE;
14811 
14812 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14813 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14814 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14815 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14816 		if (tcp->tcp_snd_sack_ok) {
14817 			ASSERT(tcp->tcp_sack_info != NULL);
14818 			tcp->tcp_max_sack_blk = 4;
14819 		}
14820 	}
14821 	return (B_TRUE);
14822 }
14823 
14824 /*
14825  * Attach ancillary data to a received TCP segments for the
14826  * ancillary pieces requested by the application that are
14827  * different than they were in the previous data segment.
14828  *
14829  * Save the "current" values once memory allocation is ok so that
14830  * when memory allocation fails we can just wait for the next data segment.
14831  */
14832 static mblk_t *
14833 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14834 {
14835 	struct T_optdata_ind *todi;
14836 	int optlen;
14837 	uchar_t *optptr;
14838 	struct T_opthdr *toh;
14839 	uint_t addflag;	/* Which pieces to add */
14840 	mblk_t *mp1;
14841 
14842 	optlen = 0;
14843 	addflag = 0;
14844 	/* If app asked for pktinfo and the index has changed ... */
14845 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14846 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14847 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14848 		optlen += sizeof (struct T_opthdr) +
14849 		    sizeof (struct in6_pktinfo);
14850 		addflag |= TCP_IPV6_RECVPKTINFO;
14851 	}
14852 	/* If app asked for hoplimit and it has changed ... */
14853 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14854 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14855 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14856 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14857 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14858 	}
14859 	/* If app asked for tclass and it has changed ... */
14860 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14861 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14862 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14863 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14864 		addflag |= TCP_IPV6_RECVTCLASS;
14865 	}
14866 	/*
14867 	 * If app asked for hopbyhop headers and it has changed ...
14868 	 * For security labels, note that (1) security labels can't change on
14869 	 * a connected socket at all, (2) we're connected to at most one peer,
14870 	 * (3) if anything changes, then it must be some other extra option.
14871 	 */
14872 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14873 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14874 	    (ipp->ipp_fields & IPPF_HOPOPTS),
14875 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14876 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
14877 		    tcp->tcp_label_len;
14878 		addflag |= TCP_IPV6_RECVHOPOPTS;
14879 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
14880 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
14881 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14882 			return (mp);
14883 	}
14884 	/* If app asked for dst headers before routing headers ... */
14885 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14886 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14887 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14888 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14889 		optlen += sizeof (struct T_opthdr) +
14890 		    ipp->ipp_rtdstoptslen;
14891 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14892 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
14893 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
14894 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14895 			return (mp);
14896 	}
14897 	/* If app asked for routing headers and it has changed ... */
14898 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14899 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14900 	    (ipp->ipp_fields & IPPF_RTHDR),
14901 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14902 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14903 		addflag |= TCP_IPV6_RECVRTHDR;
14904 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
14905 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
14906 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14907 			return (mp);
14908 	}
14909 	/* If app asked for dest headers and it has changed ... */
14910 	if ((tcp->tcp_ipv6_recvancillary &
14911 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14912 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14913 	    (ipp->ipp_fields & IPPF_DSTOPTS),
14914 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14915 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14916 		addflag |= TCP_IPV6_RECVDSTOPTS;
14917 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
14918 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
14919 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14920 			return (mp);
14921 	}
14922 
14923 	if (optlen == 0) {
14924 		/* Nothing to add */
14925 		return (mp);
14926 	}
14927 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14928 	if (mp1 == NULL) {
14929 		/*
14930 		 * Defer sending ancillary data until the next TCP segment
14931 		 * arrives.
14932 		 */
14933 		return (mp);
14934 	}
14935 	mp1->b_cont = mp;
14936 	mp = mp1;
14937 	mp->b_wptr += sizeof (*todi) + optlen;
14938 	mp->b_datap->db_type = M_PROTO;
14939 	todi = (struct T_optdata_ind *)mp->b_rptr;
14940 	todi->PRIM_type = T_OPTDATA_IND;
14941 	todi->DATA_flag = 1;	/* MORE data */
14942 	todi->OPT_length = optlen;
14943 	todi->OPT_offset = sizeof (*todi);
14944 	optptr = (uchar_t *)&todi[1];
14945 	/*
14946 	 * If app asked for pktinfo and the index has changed ...
14947 	 * Note that the local address never changes for the connection.
14948 	 */
14949 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14950 		struct in6_pktinfo *pkti;
14951 
14952 		toh = (struct T_opthdr *)optptr;
14953 		toh->level = IPPROTO_IPV6;
14954 		toh->name = IPV6_PKTINFO;
14955 		toh->len = sizeof (*toh) + sizeof (*pkti);
14956 		toh->status = 0;
14957 		optptr += sizeof (*toh);
14958 		pkti = (struct in6_pktinfo *)optptr;
14959 		if (tcp->tcp_ipversion == IPV6_VERSION)
14960 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14961 		else
14962 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14963 			    &pkti->ipi6_addr);
14964 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14965 		optptr += sizeof (*pkti);
14966 		ASSERT(OK_32PTR(optptr));
14967 		/* Save as "last" value */
14968 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14969 	}
14970 	/* If app asked for hoplimit and it has changed ... */
14971 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14972 		toh = (struct T_opthdr *)optptr;
14973 		toh->level = IPPROTO_IPV6;
14974 		toh->name = IPV6_HOPLIMIT;
14975 		toh->len = sizeof (*toh) + sizeof (uint_t);
14976 		toh->status = 0;
14977 		optptr += sizeof (*toh);
14978 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14979 		optptr += sizeof (uint_t);
14980 		ASSERT(OK_32PTR(optptr));
14981 		/* Save as "last" value */
14982 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14983 	}
14984 	/* If app asked for tclass and it has changed ... */
14985 	if (addflag & TCP_IPV6_RECVTCLASS) {
14986 		toh = (struct T_opthdr *)optptr;
14987 		toh->level = IPPROTO_IPV6;
14988 		toh->name = IPV6_TCLASS;
14989 		toh->len = sizeof (*toh) + sizeof (uint_t);
14990 		toh->status = 0;
14991 		optptr += sizeof (*toh);
14992 		*(uint_t *)optptr = ipp->ipp_tclass;
14993 		optptr += sizeof (uint_t);
14994 		ASSERT(OK_32PTR(optptr));
14995 		/* Save as "last" value */
14996 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14997 	}
14998 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14999 		toh = (struct T_opthdr *)optptr;
15000 		toh->level = IPPROTO_IPV6;
15001 		toh->name = IPV6_HOPOPTS;
15002 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15003 		    tcp->tcp_label_len;
15004 		toh->status = 0;
15005 		optptr += sizeof (*toh);
15006 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15007 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15008 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15009 		ASSERT(OK_32PTR(optptr));
15010 		/* Save as last value */
15011 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15012 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15013 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15014 	}
15015 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15016 		toh = (struct T_opthdr *)optptr;
15017 		toh->level = IPPROTO_IPV6;
15018 		toh->name = IPV6_RTHDRDSTOPTS;
15019 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15020 		toh->status = 0;
15021 		optptr += sizeof (*toh);
15022 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15023 		optptr += ipp->ipp_rtdstoptslen;
15024 		ASSERT(OK_32PTR(optptr));
15025 		/* Save as last value */
15026 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15027 		    &tcp->tcp_rtdstoptslen,
15028 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15029 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15030 	}
15031 	if (addflag & TCP_IPV6_RECVRTHDR) {
15032 		toh = (struct T_opthdr *)optptr;
15033 		toh->level = IPPROTO_IPV6;
15034 		toh->name = IPV6_RTHDR;
15035 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15036 		toh->status = 0;
15037 		optptr += sizeof (*toh);
15038 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15039 		optptr += ipp->ipp_rthdrlen;
15040 		ASSERT(OK_32PTR(optptr));
15041 		/* Save as last value */
15042 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15043 		    (ipp->ipp_fields & IPPF_RTHDR),
15044 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15045 	}
15046 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15047 		toh = (struct T_opthdr *)optptr;
15048 		toh->level = IPPROTO_IPV6;
15049 		toh->name = IPV6_DSTOPTS;
15050 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15051 		toh->status = 0;
15052 		optptr += sizeof (*toh);
15053 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15054 		optptr += ipp->ipp_dstoptslen;
15055 		ASSERT(OK_32PTR(optptr));
15056 		/* Save as last value */
15057 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15058 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15059 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15060 	}
15061 	ASSERT(optptr == mp->b_wptr);
15062 	return (mp);
15063 }
15064 
15065 
15066 /*
15067  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15068  * or a "bad" IRE detected by tcp_adapt_ire.
15069  * We can't tell if the failure was due to the laddr or the faddr
15070  * thus we clear out all addresses and ports.
15071  */
15072 static void
15073 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15074 {
15075 	queue_t	*q = tcp->tcp_rq;
15076 	tcph_t	*tcph;
15077 	struct T_error_ack *tea;
15078 	conn_t	*connp = tcp->tcp_connp;
15079 
15080 
15081 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15082 
15083 	if (mp->b_cont) {
15084 		freemsg(mp->b_cont);
15085 		mp->b_cont = NULL;
15086 	}
15087 	tea = (struct T_error_ack *)mp->b_rptr;
15088 	switch (tea->PRIM_type) {
15089 	case T_BIND_ACK:
15090 		/*
15091 		 * Need to unbind with classifier since we were just told that
15092 		 * our bind succeeded.
15093 		 */
15094 		tcp->tcp_hard_bound = B_FALSE;
15095 		tcp->tcp_hard_binding = B_FALSE;
15096 
15097 		ipcl_hash_remove(connp);
15098 		/* Reuse the mblk if possible */
15099 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15100 			sizeof (*tea));
15101 		mp->b_rptr = mp->b_datap->db_base;
15102 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15103 		tea = (struct T_error_ack *)mp->b_rptr;
15104 		tea->PRIM_type = T_ERROR_ACK;
15105 		tea->TLI_error = TSYSERR;
15106 		tea->UNIX_error = error;
15107 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15108 			tea->ERROR_prim = T_CONN_REQ;
15109 		} else {
15110 			tea->ERROR_prim = O_T_BIND_REQ;
15111 		}
15112 		break;
15113 
15114 	case T_ERROR_ACK:
15115 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15116 			tea->ERROR_prim = T_CONN_REQ;
15117 		break;
15118 	default:
15119 		panic("tcp_bind_failed: unexpected TPI type");
15120 		/*NOTREACHED*/
15121 	}
15122 
15123 	tcp->tcp_state = TCPS_IDLE;
15124 	if (tcp->tcp_ipversion == IPV4_VERSION)
15125 		tcp->tcp_ipha->ipha_src = 0;
15126 	else
15127 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15128 	/*
15129 	 * Copy of the src addr. in tcp_t is needed since
15130 	 * the lookup funcs. can only look at tcp_t
15131 	 */
15132 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15133 
15134 	tcph = tcp->tcp_tcph;
15135 	tcph->th_lport[0] = 0;
15136 	tcph->th_lport[1] = 0;
15137 	tcp_bind_hash_remove(tcp);
15138 	bzero(&connp->u_port, sizeof (connp->u_port));
15139 	/* blow away saved option results if any */
15140 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15141 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15142 
15143 	conn_delete_ire(tcp->tcp_connp, NULL);
15144 	putnext(q, mp);
15145 }
15146 
15147 /*
15148  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15149  * messages.
15150  */
15151 void
15152 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15153 {
15154 	mblk_t	*mp1;
15155 	uchar_t	*rptr = mp->b_rptr;
15156 	queue_t	*q = tcp->tcp_rq;
15157 	struct T_error_ack *tea;
15158 	uint32_t mss;
15159 	mblk_t *syn_mp;
15160 	mblk_t *mdti;
15161 	int	retval;
15162 	mblk_t *ire_mp;
15163 
15164 	switch (mp->b_datap->db_type) {
15165 	case M_PROTO:
15166 	case M_PCPROTO:
15167 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15168 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15169 			break;
15170 		tea = (struct T_error_ack *)rptr;
15171 		switch (tea->PRIM_type) {
15172 		case T_BIND_ACK:
15173 			/*
15174 			 * Adapt Multidata information, if any.  The
15175 			 * following tcp_mdt_update routine will free
15176 			 * the message.
15177 			 */
15178 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15179 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15180 				    b_rptr)->mdt_capab, B_TRUE);
15181 				freemsg(mdti);
15182 			}
15183 
15184 			/* Get the IRE, if we had requested for it */
15185 			ire_mp = tcp_ire_mp(mp);
15186 
15187 			if (tcp->tcp_hard_binding) {
15188 				tcp->tcp_hard_binding = B_FALSE;
15189 				tcp->tcp_hard_bound = B_TRUE;
15190 				CL_INET_CONNECT(tcp);
15191 			} else {
15192 				if (ire_mp != NULL)
15193 					freeb(ire_mp);
15194 				goto after_syn_sent;
15195 			}
15196 
15197 			retval = tcp_adapt_ire(tcp, ire_mp);
15198 			if (ire_mp != NULL)
15199 				freeb(ire_mp);
15200 			if (retval == 0) {
15201 				tcp_bind_failed(tcp, mp,
15202 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15203 				    ENETUNREACH : EADDRNOTAVAIL));
15204 				return;
15205 			}
15206 			/*
15207 			 * Don't let an endpoint connect to itself.
15208 			 * Also checked in tcp_connect() but that
15209 			 * check can't handle the case when the
15210 			 * local IP address is INADDR_ANY.
15211 			 */
15212 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15213 				if ((tcp->tcp_ipha->ipha_dst ==
15214 				    tcp->tcp_ipha->ipha_src) &&
15215 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15216 				    tcp->tcp_tcph->th_fport))) {
15217 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15218 					return;
15219 				}
15220 			} else {
15221 				if (IN6_ARE_ADDR_EQUAL(
15222 				    &tcp->tcp_ip6h->ip6_dst,
15223 				    &tcp->tcp_ip6h->ip6_src) &&
15224 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15225 				    tcp->tcp_tcph->th_fport))) {
15226 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15227 					return;
15228 				}
15229 			}
15230 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15231 			/*
15232 			 * This should not be possible!  Just for
15233 			 * defensive coding...
15234 			 */
15235 			if (tcp->tcp_state != TCPS_SYN_SENT)
15236 				goto after_syn_sent;
15237 
15238 			if (is_system_labeled() &&
15239 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
15240 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
15241 				return;
15242 			}
15243 
15244 			ASSERT(q == tcp->tcp_rq);
15245 			/*
15246 			 * tcp_adapt_ire() does not adjust
15247 			 * for TCP/IP header length.
15248 			 */
15249 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15250 
15251 			/*
15252 			 * Just make sure our rwnd is at
15253 			 * least tcp_recv_hiwat_mss * MSS
15254 			 * large, and round up to the nearest
15255 			 * MSS.
15256 			 *
15257 			 * We do the round up here because
15258 			 * we need to get the interface
15259 			 * MTU first before we can do the
15260 			 * round up.
15261 			 */
15262 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15263 			    tcp_recv_hiwat_minmss * mss);
15264 			q->q_hiwat = tcp->tcp_rwnd;
15265 			tcp_set_ws_value(tcp);
15266 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15267 			    tcp->tcp_tcph->th_win);
15268 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15269 				tcp->tcp_snd_ws_ok = B_TRUE;
15270 
15271 			/*
15272 			 * Set tcp_snd_ts_ok to true
15273 			 * so that tcp_xmit_mp will
15274 			 * include the timestamp
15275 			 * option in the SYN segment.
15276 			 */
15277 			if (tcp_tstamp_always ||
15278 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15279 				tcp->tcp_snd_ts_ok = B_TRUE;
15280 			}
15281 
15282 			/*
15283 			 * tcp_snd_sack_ok can be set in
15284 			 * tcp_adapt_ire() if the sack metric
15285 			 * is set.  So check it here also.
15286 			 */
15287 			if (tcp_sack_permitted == 2 ||
15288 			    tcp->tcp_snd_sack_ok) {
15289 				if (tcp->tcp_sack_info == NULL) {
15290 					tcp->tcp_sack_info =
15291 					kmem_cache_alloc(tcp_sack_info_cache,
15292 					    KM_SLEEP);
15293 				}
15294 				tcp->tcp_snd_sack_ok = B_TRUE;
15295 			}
15296 
15297 			/*
15298 			 * Should we use ECN?  Note that the current
15299 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15300 			 * is 1.  The reason for doing this is that there
15301 			 * are equipments out there that will drop ECN
15302 			 * enabled IP packets.  Setting it to 1 avoids
15303 			 * compatibility problems.
15304 			 */
15305 			if (tcp_ecn_permitted == 2)
15306 				tcp->tcp_ecn_ok = B_TRUE;
15307 
15308 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15309 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15310 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15311 			if (syn_mp) {
15312 				cred_t *cr;
15313 				pid_t pid;
15314 
15315 				/*
15316 				 * Obtain the credential from the
15317 				 * thread calling connect(); the credential
15318 				 * lives on in the second mblk which
15319 				 * originated from T_CONN_REQ and is echoed
15320 				 * with the T_BIND_ACK from ip.  If none
15321 				 * can be found, default to the creator
15322 				 * of the socket.
15323 				 */
15324 				if (mp->b_cont == NULL ||
15325 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15326 					cr = tcp->tcp_cred;
15327 					pid = tcp->tcp_cpid;
15328 				} else {
15329 					pid = DB_CPID(mp->b_cont);
15330 				}
15331 
15332 				TCP_RECORD_TRACE(tcp, syn_mp,
15333 				    TCP_TRACE_SEND_PKT);
15334 				mblk_setcred(syn_mp, cr);
15335 				DB_CPID(syn_mp) = pid;
15336 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15337 			}
15338 		after_syn_sent:
15339 			/*
15340 			 * A trailer mblk indicates a waiting client upstream.
15341 			 * We complete here the processing begun in
15342 			 * either tcp_bind() or tcp_connect() by passing
15343 			 * upstream the reply message they supplied.
15344 			 */
15345 			mp1 = mp;
15346 			mp = mp->b_cont;
15347 			freeb(mp1);
15348 			if (mp)
15349 				break;
15350 			return;
15351 		case T_ERROR_ACK:
15352 			if (tcp->tcp_debug) {
15353 				(void) strlog(TCP_MOD_ID, 0, 1,
15354 				    SL_TRACE|SL_ERROR,
15355 				    "tcp_rput_other: case T_ERROR_ACK, "
15356 				    "ERROR_prim == %d",
15357 				    tea->ERROR_prim);
15358 			}
15359 			switch (tea->ERROR_prim) {
15360 			case O_T_BIND_REQ:
15361 			case T_BIND_REQ:
15362 				tcp_bind_failed(tcp, mp,
15363 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15364 				    ENETUNREACH : EADDRNOTAVAIL));
15365 				return;
15366 			case T_UNBIND_REQ:
15367 				tcp->tcp_hard_binding = B_FALSE;
15368 				tcp->tcp_hard_bound = B_FALSE;
15369 				if (mp->b_cont) {
15370 					freemsg(mp->b_cont);
15371 					mp->b_cont = NULL;
15372 				}
15373 				if (tcp->tcp_unbind_pending)
15374 					tcp->tcp_unbind_pending = 0;
15375 				else {
15376 					/* From tcp_ip_unbind() - free */
15377 					freemsg(mp);
15378 					return;
15379 				}
15380 				break;
15381 			case T_SVR4_OPTMGMT_REQ:
15382 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15383 					/* T_OPTMGMT_REQ generated by TCP */
15384 					printf("T_SVR4_OPTMGMT_REQ failed "
15385 					    "%d/%d - dropped (cnt %d)\n",
15386 					    tea->TLI_error, tea->UNIX_error,
15387 					    tcp->tcp_drop_opt_ack_cnt);
15388 					freemsg(mp);
15389 					tcp->tcp_drop_opt_ack_cnt--;
15390 					return;
15391 				}
15392 				break;
15393 			}
15394 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15395 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15396 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15397 				    "- dropped (cnt %d)\n",
15398 				    tea->TLI_error, tea->UNIX_error,
15399 				    tcp->tcp_drop_opt_ack_cnt);
15400 				freemsg(mp);
15401 				tcp->tcp_drop_opt_ack_cnt--;
15402 				return;
15403 			}
15404 			break;
15405 		case T_OPTMGMT_ACK:
15406 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15407 				/* T_OPTMGMT_REQ generated by TCP */
15408 				freemsg(mp);
15409 				tcp->tcp_drop_opt_ack_cnt--;
15410 				return;
15411 			}
15412 			break;
15413 		default:
15414 			break;
15415 		}
15416 		break;
15417 	case M_CTL:
15418 		/*
15419 		 * ICMP messages.
15420 		 */
15421 		tcp_icmp_error(tcp, mp);
15422 		return;
15423 	case M_FLUSH:
15424 		if (*rptr & FLUSHR)
15425 			flushq(q, FLUSHDATA);
15426 		break;
15427 	default:
15428 		break;
15429 	}
15430 	/*
15431 	 * Make sure we set this bit before sending the ACK for
15432 	 * bind. Otherwise accept could possibly run and free
15433 	 * this tcp struct.
15434 	 */
15435 	putnext(q, mp);
15436 }
15437 
15438 /*
15439  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15440  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15441  * tcp_rsrv() try again.
15442  */
15443 static void
15444 tcp_ordrel_kick(void *arg)
15445 {
15446 	conn_t 	*connp = (conn_t *)arg;
15447 	tcp_t	*tcp = connp->conn_tcp;
15448 
15449 	tcp->tcp_ordrelid = 0;
15450 	tcp->tcp_timeout = B_FALSE;
15451 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15452 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15453 		qenable(tcp->tcp_rq);
15454 	}
15455 }
15456 
15457 /* ARGSUSED */
15458 static void
15459 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15460 {
15461 	conn_t	*connp = (conn_t *)arg;
15462 	tcp_t	*tcp = connp->conn_tcp;
15463 	queue_t	*q = tcp->tcp_rq;
15464 	uint_t	thwin;
15465 
15466 	freeb(mp);
15467 
15468 	TCP_STAT(tcp_rsrv_calls);
15469 
15470 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15471 		return;
15472 	}
15473 
15474 	if (tcp->tcp_fused) {
15475 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15476 
15477 		ASSERT(tcp->tcp_fused);
15478 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15479 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15480 		ASSERT(!TCP_IS_DETACHED(tcp));
15481 		ASSERT(tcp->tcp_connp->conn_sqp ==
15482 		    peer_tcp->tcp_connp->conn_sqp);
15483 
15484 		/*
15485 		 * Normally we would not get backenabled in synchronous
15486 		 * streams mode, but in case this happens, we need to stop
15487 		 * synchronous streams temporarily to prevent a race with
15488 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15489 		 * tcp_rcv_list here because those entry points will return
15490 		 * right away when synchronous streams is stopped.
15491 		 */
15492 		TCP_FUSE_SYNCSTR_STOP(tcp);
15493 		if (tcp->tcp_rcv_list != NULL)
15494 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15495 
15496 		tcp_clrqfull(peer_tcp);
15497 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15498 		TCP_STAT(tcp_fusion_backenabled);
15499 		return;
15500 	}
15501 
15502 	if (canputnext(q)) {
15503 		tcp->tcp_rwnd = q->q_hiwat;
15504 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15505 		    << tcp->tcp_rcv_ws;
15506 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15507 		/*
15508 		 * Send back a window update immediately if TCP is above
15509 		 * ESTABLISHED state and the increase of the rcv window
15510 		 * that the other side knows is at least 1 MSS after flow
15511 		 * control is lifted.
15512 		 */
15513 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15514 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15515 			tcp_xmit_ctl(NULL, tcp,
15516 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15517 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15518 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15519 		}
15520 	}
15521 	/* Handle a failure to allocate a T_ORDREL_IND here */
15522 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15523 		ASSERT(tcp->tcp_listener == NULL);
15524 		if (tcp->tcp_rcv_list != NULL) {
15525 			(void) tcp_rcv_drain(q, tcp);
15526 		}
15527 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15528 		mp = mi_tpi_ordrel_ind();
15529 		if (mp) {
15530 			tcp->tcp_ordrel_done = B_TRUE;
15531 			putnext(q, mp);
15532 			if (tcp->tcp_deferred_clean_death) {
15533 				/*
15534 				 * tcp_clean_death was deferred for
15535 				 * T_ORDREL_IND - do it now
15536 				 */
15537 				tcp->tcp_deferred_clean_death = B_FALSE;
15538 				(void) tcp_clean_death(tcp,
15539 				    tcp->tcp_client_errno, 22);
15540 			}
15541 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15542 			/*
15543 			 * If there isn't already a timer running
15544 			 * start one.  Use a 4 second
15545 			 * timer as a fallback since it can't fail.
15546 			 */
15547 			tcp->tcp_timeout = B_TRUE;
15548 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15549 			    MSEC_TO_TICK(4000));
15550 		}
15551 	}
15552 }
15553 
15554 /*
15555  * The read side service routine is called mostly when we get back-enabled as a
15556  * result of flow control relief.  Since we don't actually queue anything in
15557  * TCP, we have no data to send out of here.  What we do is clear the receive
15558  * window, and send out a window update.
15559  * This routine is also called to drive an orderly release message upstream
15560  * if the attempt in tcp_rput failed.
15561  */
15562 static void
15563 tcp_rsrv(queue_t *q)
15564 {
15565 	conn_t *connp = Q_TO_CONN(q);
15566 	tcp_t	*tcp = connp->conn_tcp;
15567 	mblk_t	*mp;
15568 
15569 	/* No code does a putq on the read side */
15570 	ASSERT(q->q_first == NULL);
15571 
15572 	/* Nothing to do for the default queue */
15573 	if (q == tcp_g_q) {
15574 		return;
15575 	}
15576 
15577 	mp = allocb(0, BPRI_HI);
15578 	if (mp == NULL) {
15579 		/*
15580 		 * We are under memory pressure. Return for now and we
15581 		 * we will be called again later.
15582 		 */
15583 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15584 			/*
15585 			 * If there isn't already a timer running
15586 			 * start one.  Use a 4 second
15587 			 * timer as a fallback since it can't fail.
15588 			 */
15589 			tcp->tcp_timeout = B_TRUE;
15590 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15591 			    MSEC_TO_TICK(4000));
15592 		}
15593 		return;
15594 	}
15595 	CONN_INC_REF(connp);
15596 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15597 	    SQTAG_TCP_RSRV);
15598 }
15599 
15600 /*
15601  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15602  * We do not allow the receive window to shrink.  After setting rwnd,
15603  * set the flow control hiwat of the stream.
15604  *
15605  * This function is called in 2 cases:
15606  *
15607  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15608  *    connection (passive open) and in tcp_rput_data() for active connect.
15609  *    This is called after tcp_mss_set() when the desired MSS value is known.
15610  *    This makes sure that our window size is a mutiple of the other side's
15611  *    MSS.
15612  * 2) Handling SO_RCVBUF option.
15613  *
15614  * It is ASSUMED that the requested size is a multiple of the current MSS.
15615  *
15616  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15617  * user requests so.
15618  */
15619 static int
15620 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15621 {
15622 	uint32_t	mss = tcp->tcp_mss;
15623 	uint32_t	old_max_rwnd;
15624 	uint32_t	max_transmittable_rwnd;
15625 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15626 
15627 	if (tcp->tcp_fused) {
15628 		size_t sth_hiwat;
15629 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15630 
15631 		ASSERT(peer_tcp != NULL);
15632 		/*
15633 		 * Record the stream head's high water mark for
15634 		 * this endpoint; this is used for flow-control
15635 		 * purposes in tcp_fuse_output().
15636 		 */
15637 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15638 		if (!tcp_detached)
15639 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15640 
15641 		/*
15642 		 * In the fusion case, the maxpsz stream head value of
15643 		 * our peer is set according to its send buffer size
15644 		 * and our receive buffer size; since the latter may
15645 		 * have changed we need to update the peer's maxpsz.
15646 		 */
15647 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15648 		return (rwnd);
15649 	}
15650 
15651 	if (tcp_detached)
15652 		old_max_rwnd = tcp->tcp_rwnd;
15653 	else
15654 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15655 
15656 	/*
15657 	 * Insist on a receive window that is at least
15658 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15659 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15660 	 * and delayed acknowledgement.
15661 	 */
15662 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15663 
15664 	/*
15665 	 * If window size info has already been exchanged, TCP should not
15666 	 * shrink the window.  Shrinking window is doable if done carefully.
15667 	 * We may add that support later.  But so far there is not a real
15668 	 * need to do that.
15669 	 */
15670 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15671 		/* MSS may have changed, do a round up again. */
15672 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15673 	}
15674 
15675 	/*
15676 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15677 	 * can be applied even before the window scale option is decided.
15678 	 */
15679 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15680 	if (rwnd > max_transmittable_rwnd) {
15681 		rwnd = max_transmittable_rwnd -
15682 		    (max_transmittable_rwnd % mss);
15683 		if (rwnd < mss)
15684 			rwnd = max_transmittable_rwnd;
15685 		/*
15686 		 * If we're over the limit we may have to back down tcp_rwnd.
15687 		 * The increment below won't work for us. So we set all three
15688 		 * here and the increment below will have no effect.
15689 		 */
15690 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15691 	}
15692 	if (tcp->tcp_localnet) {
15693 		tcp->tcp_rack_abs_max =
15694 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15695 	} else {
15696 		/*
15697 		 * For a remote host on a different subnet (through a router),
15698 		 * we ack every other packet to be conforming to RFC1122.
15699 		 * tcp_deferred_acks_max is default to 2.
15700 		 */
15701 		tcp->tcp_rack_abs_max =
15702 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15703 	}
15704 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15705 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15706 	else
15707 		tcp->tcp_rack_cur_max = 0;
15708 	/*
15709 	 * Increment the current rwnd by the amount the maximum grew (we
15710 	 * can not overwrite it since we might be in the middle of a
15711 	 * connection.)
15712 	 */
15713 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15714 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15715 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15716 		tcp->tcp_cwnd_max = rwnd;
15717 
15718 	if (tcp_detached)
15719 		return (rwnd);
15720 	/*
15721 	 * We set the maximum receive window into rq->q_hiwat.
15722 	 * This is not actually used for flow control.
15723 	 */
15724 	tcp->tcp_rq->q_hiwat = rwnd;
15725 	/*
15726 	 * Set the Stream head high water mark. This doesn't have to be
15727 	 * here, since we are simply using default values, but we would
15728 	 * prefer to choose these values algorithmically, with a likely
15729 	 * relationship to rwnd.
15730 	 */
15731 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15732 	return (rwnd);
15733 }
15734 
15735 /*
15736  * Return SNMP stuff in buffer in mpdata.
15737  */
15738 int
15739 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15740 {
15741 	mblk_t			*mpdata;
15742 	mblk_t			*mp_conn_ctl = NULL;
15743 	mblk_t			*mp_conn_tail;
15744 	mblk_t			*mp_attr_ctl = NULL;
15745 	mblk_t			*mp_attr_tail;
15746 	mblk_t			*mp6_conn_ctl = NULL;
15747 	mblk_t			*mp6_conn_tail;
15748 	mblk_t			*mp6_attr_ctl = NULL;
15749 	mblk_t			*mp6_attr_tail;
15750 	struct opthdr		*optp;
15751 	mib2_tcpConnEntry_t	tce;
15752 	mib2_tcp6ConnEntry_t	tce6;
15753 	mib2_transportMLPEntry_t mlp;
15754 	connf_t			*connfp;
15755 	conn_t			*connp;
15756 	int			i;
15757 	boolean_t 		ispriv;
15758 	zoneid_t 		zoneid;
15759 	int			v4_conn_idx;
15760 	int			v6_conn_idx;
15761 
15762 	if (mpctl == NULL ||
15763 	    (mpdata = mpctl->b_cont) == NULL ||
15764 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15765 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
15766 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
15767 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
15768 		freemsg(mp_conn_ctl);
15769 		freemsg(mp_attr_ctl);
15770 		freemsg(mp6_conn_ctl);
15771 		freemsg(mp6_attr_ctl);
15772 		return (0);
15773 	}
15774 
15775 	/* build table of connections -- need count in fixed part */
15776 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15777 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15778 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15779 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15780 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15781 
15782 	ispriv =
15783 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15784 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15785 
15786 	v4_conn_idx = v6_conn_idx = 0;
15787 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
15788 
15789 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15790 
15791 		connfp = &ipcl_globalhash_fanout[i];
15792 
15793 		connp = NULL;
15794 
15795 		while ((connp =
15796 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15797 			tcp_t *tcp;
15798 			boolean_t needattr;
15799 
15800 			if (connp->conn_zoneid != zoneid)
15801 				continue;	/* not in this zone */
15802 
15803 			tcp = connp->conn_tcp;
15804 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15805 			tcp->tcp_ibsegs = 0;
15806 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15807 			tcp->tcp_obsegs = 0;
15808 
15809 			tce6.tcp6ConnState = tce.tcpConnState =
15810 			    tcp_snmp_state(tcp);
15811 			if (tce.tcpConnState == MIB2_TCP_established ||
15812 			    tce.tcpConnState == MIB2_TCP_closeWait)
15813 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15814 
15815 			needattr = B_FALSE;
15816 			bzero(&mlp, sizeof (mlp));
15817 			if (connp->conn_mlp_type != mlptSingle) {
15818 				if (connp->conn_mlp_type == mlptShared ||
15819 				    connp->conn_mlp_type == mlptBoth)
15820 					mlp.tme_flags |= MIB2_TMEF_SHARED;
15821 				if (connp->conn_mlp_type == mlptPrivate ||
15822 				    connp->conn_mlp_type == mlptBoth)
15823 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
15824 				needattr = B_TRUE;
15825 			}
15826 			if (connp->conn_peercred != NULL) {
15827 				ts_label_t *tsl;
15828 
15829 				tsl = crgetlabel(connp->conn_peercred);
15830 				mlp.tme_doi = label2doi(tsl);
15831 				mlp.tme_label = *label2bslabel(tsl);
15832 				needattr = B_TRUE;
15833 			}
15834 
15835 			/* Create a message to report on IPv6 entries */
15836 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15837 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15838 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15839 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15840 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15841 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15842 			/* Don't want just anybody seeing these... */
15843 			if (ispriv) {
15844 				tce6.tcp6ConnEntryInfo.ce_snxt =
15845 				    tcp->tcp_snxt;
15846 				tce6.tcp6ConnEntryInfo.ce_suna =
15847 				    tcp->tcp_suna;
15848 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15849 				    tcp->tcp_rnxt;
15850 				tce6.tcp6ConnEntryInfo.ce_rack =
15851 				    tcp->tcp_rack;
15852 			} else {
15853 				/*
15854 				 * Netstat, unfortunately, uses this to
15855 				 * get send/receive queue sizes.  How to fix?
15856 				 * Why not compute the difference only?
15857 				 */
15858 				tce6.tcp6ConnEntryInfo.ce_snxt =
15859 				    tcp->tcp_snxt - tcp->tcp_suna;
15860 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15861 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15862 				    tcp->tcp_rnxt - tcp->tcp_rack;
15863 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15864 			}
15865 
15866 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15867 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15868 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15869 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15870 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15871 
15872 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
15873 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
15874 
15875 			mlp.tme_connidx = v6_conn_idx++;
15876 			if (needattr)
15877 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
15878 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
15879 			}
15880 			/*
15881 			 * Create an IPv4 table entry for IPv4 entries and also
15882 			 * for IPv6 entries which are bound to in6addr_any
15883 			 * but don't have IPV6_V6ONLY set.
15884 			 * (i.e. anything an IPv4 peer could connect to)
15885 			 */
15886 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15887 			    (tcp->tcp_state <= TCPS_LISTEN &&
15888 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15889 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15890 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15891 					tce.tcpConnRemAddress = INADDR_ANY;
15892 					tce.tcpConnLocalAddress = INADDR_ANY;
15893 				} else {
15894 					tce.tcpConnRemAddress =
15895 					    tcp->tcp_remote;
15896 					tce.tcpConnLocalAddress =
15897 					    tcp->tcp_ip_src;
15898 				}
15899 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15900 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15901 				/* Don't want just anybody seeing these... */
15902 				if (ispriv) {
15903 					tce.tcpConnEntryInfo.ce_snxt =
15904 					    tcp->tcp_snxt;
15905 					tce.tcpConnEntryInfo.ce_suna =
15906 					    tcp->tcp_suna;
15907 					tce.tcpConnEntryInfo.ce_rnxt =
15908 					    tcp->tcp_rnxt;
15909 					tce.tcpConnEntryInfo.ce_rack =
15910 					    tcp->tcp_rack;
15911 				} else {
15912 					/*
15913 					 * Netstat, unfortunately, uses this to
15914 					 * get send/receive queue sizes.  How
15915 					 * to fix?
15916 					 * Why not compute the difference only?
15917 					 */
15918 					tce.tcpConnEntryInfo.ce_snxt =
15919 					    tcp->tcp_snxt - tcp->tcp_suna;
15920 					tce.tcpConnEntryInfo.ce_suna = 0;
15921 					tce.tcpConnEntryInfo.ce_rnxt =
15922 					    tcp->tcp_rnxt - tcp->tcp_rack;
15923 					tce.tcpConnEntryInfo.ce_rack = 0;
15924 				}
15925 
15926 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15927 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15928 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15929 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15930 				tce.tcpConnEntryInfo.ce_state =
15931 				    tcp->tcp_state;
15932 
15933 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
15934 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15935 
15936 				mlp.tme_connidx = v4_conn_idx++;
15937 				if (needattr)
15938 					(void) snmp_append_data2(
15939 					    mp_attr_ctl->b_cont,
15940 					    &mp_attr_tail, (char *)&mlp,
15941 					    sizeof (mlp));
15942 			}
15943 		}
15944 	}
15945 
15946 	/* fixed length structure for IPv4 and IPv6 counters */
15947 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15948 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15949 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15950 	optp->level = MIB2_TCP;
15951 	optp->name = 0;
15952 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15953 	optp->len = msgdsize(mpdata);
15954 	qreply(q, mpctl);
15955 
15956 	/* table of connections... */
15957 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15958 	    sizeof (struct T_optmgmt_ack)];
15959 	optp->level = MIB2_TCP;
15960 	optp->name = MIB2_TCP_CONN;
15961 	optp->len = msgdsize(mp_conn_ctl->b_cont);
15962 	qreply(q, mp_conn_ctl);
15963 
15964 	/* table of MLP attributes... */
15965 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
15966 	    sizeof (struct T_optmgmt_ack)];
15967 	optp->level = MIB2_TCP;
15968 	optp->name = EXPER_XPORT_MLP;
15969 	optp->len = msgdsize(mp_attr_ctl->b_cont);
15970 	if (optp->len == 0)
15971 		freemsg(mp_attr_ctl);
15972 	else
15973 		qreply(q, mp_attr_ctl);
15974 
15975 	/* table of IPv6 connections... */
15976 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15977 	    sizeof (struct T_optmgmt_ack)];
15978 	optp->level = MIB2_TCP6;
15979 	optp->name = MIB2_TCP6_CONN;
15980 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
15981 	qreply(q, mp6_conn_ctl);
15982 
15983 	/* table of IPv6 MLP attributes... */
15984 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
15985 	    sizeof (struct T_optmgmt_ack)];
15986 	optp->level = MIB2_TCP6;
15987 	optp->name = EXPER_XPORT_MLP;
15988 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
15989 	if (optp->len == 0)
15990 		freemsg(mp6_attr_ctl);
15991 	else
15992 		qreply(q, mp6_attr_ctl);
15993 	return (1);
15994 }
15995 
15996 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15997 /* ARGSUSED */
15998 int
15999 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16000 {
16001 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16002 
16003 	switch (level) {
16004 	case MIB2_TCP:
16005 		switch (name) {
16006 		case 13:
16007 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16008 				return (0);
16009 			/* TODO: delete entry defined by tce */
16010 			return (1);
16011 		default:
16012 			return (0);
16013 		}
16014 	default:
16015 		return (1);
16016 	}
16017 }
16018 
16019 /* Translate TCP state to MIB2 TCP state. */
16020 static int
16021 tcp_snmp_state(tcp_t *tcp)
16022 {
16023 	if (tcp == NULL)
16024 		return (0);
16025 
16026 	switch (tcp->tcp_state) {
16027 	case TCPS_CLOSED:
16028 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16029 	case TCPS_BOUND:
16030 		return (MIB2_TCP_closed);
16031 	case TCPS_LISTEN:
16032 		return (MIB2_TCP_listen);
16033 	case TCPS_SYN_SENT:
16034 		return (MIB2_TCP_synSent);
16035 	case TCPS_SYN_RCVD:
16036 		return (MIB2_TCP_synReceived);
16037 	case TCPS_ESTABLISHED:
16038 		return (MIB2_TCP_established);
16039 	case TCPS_CLOSE_WAIT:
16040 		return (MIB2_TCP_closeWait);
16041 	case TCPS_FIN_WAIT_1:
16042 		return (MIB2_TCP_finWait1);
16043 	case TCPS_CLOSING:
16044 		return (MIB2_TCP_closing);
16045 	case TCPS_LAST_ACK:
16046 		return (MIB2_TCP_lastAck);
16047 	case TCPS_FIN_WAIT_2:
16048 		return (MIB2_TCP_finWait2);
16049 	case TCPS_TIME_WAIT:
16050 		return (MIB2_TCP_timeWait);
16051 	default:
16052 		return (0);
16053 	}
16054 }
16055 
16056 static char tcp_report_header[] =
16057 	"TCP     " MI_COL_HDRPAD_STR
16058 	"zone dest            snxt     suna     "
16059 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16060 	"recent   [lport,fport] state";
16061 
16062 /*
16063  * TCP status report triggered via the Named Dispatch mechanism.
16064  */
16065 /* ARGSUSED */
16066 static void
16067 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16068     cred_t *cr)
16069 {
16070 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16071 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
16072 	char cflag;
16073 	in6_addr_t	v6dst;
16074 	char buf[80];
16075 	uint_t print_len, buf_len;
16076 
16077 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16078 	if (buf_len <= 0)
16079 		return;
16080 
16081 	if (hashval >= 0)
16082 		(void) sprintf(hash, "%03d ", hashval);
16083 	else
16084 		hash[0] = '\0';
16085 
16086 	/*
16087 	 * Note that we use the remote address in the tcp_b  structure.
16088 	 * This means that it will print out the real destination address,
16089 	 * not the next hop's address if source routing is used.  This
16090 	 * avoid the confusion on the output because user may not
16091 	 * know that source routing is used for a connection.
16092 	 */
16093 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16094 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16095 	} else {
16096 		v6dst = tcp->tcp_remote_v6;
16097 	}
16098 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16099 	/*
16100 	 * the ispriv checks are so that normal users cannot determine
16101 	 * sequence number information using NDD.
16102 	 */
16103 
16104 	if (TCP_IS_DETACHED(tcp))
16105 		cflag = '*';
16106 	else
16107 		cflag = ' ';
16108 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16109 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16110 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16111 	    hash,
16112 	    (void *)tcp,
16113 	    tcp->tcp_connp->conn_zoneid,
16114 	    addrbuf,
16115 	    (ispriv) ? tcp->tcp_snxt : 0,
16116 	    (ispriv) ? tcp->tcp_suna : 0,
16117 	    tcp->tcp_swnd,
16118 	    (ispriv) ? tcp->tcp_rnxt : 0,
16119 	    (ispriv) ? tcp->tcp_rack : 0,
16120 	    tcp->tcp_rwnd,
16121 	    tcp->tcp_rto,
16122 	    tcp->tcp_mss,
16123 	    tcp->tcp_snd_ws_ok,
16124 	    tcp->tcp_snd_ws,
16125 	    tcp->tcp_rcv_ws,
16126 	    tcp->tcp_snd_ts_ok,
16127 	    tcp->tcp_ts_recent,
16128 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16129 	if (print_len < buf_len) {
16130 		((mblk_t *)mp)->b_wptr += print_len;
16131 	} else {
16132 		((mblk_t *)mp)->b_wptr += buf_len;
16133 	}
16134 }
16135 
16136 /*
16137  * TCP status report (for listeners only) triggered via the Named Dispatch
16138  * mechanism.
16139  */
16140 /* ARGSUSED */
16141 static void
16142 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16143 {
16144 	char addrbuf[INET6_ADDRSTRLEN];
16145 	in6_addr_t	v6dst;
16146 	uint_t print_len, buf_len;
16147 
16148 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16149 	if (buf_len <= 0)
16150 		return;
16151 
16152 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16153 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16154 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16155 	} else {
16156 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16157 		    addrbuf, sizeof (addrbuf));
16158 	}
16159 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16160 	    "%03d "
16161 	    MI_COL_PTRFMT_STR
16162 	    "%d %s %05u %08u %d/%d/%d%c\n",
16163 	    hashval, (void *)tcp,
16164 	    tcp->tcp_connp->conn_zoneid,
16165 	    addrbuf,
16166 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16167 	    tcp->tcp_conn_req_seqnum,
16168 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16169 	    tcp->tcp_conn_req_max,
16170 	    tcp->tcp_syn_defense ? '*' : ' ');
16171 	if (print_len < buf_len) {
16172 		((mblk_t *)mp)->b_wptr += print_len;
16173 	} else {
16174 		((mblk_t *)mp)->b_wptr += buf_len;
16175 	}
16176 }
16177 
16178 /* TCP status report triggered via the Named Dispatch mechanism. */
16179 /* ARGSUSED */
16180 static int
16181 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16182 {
16183 	tcp_t	*tcp;
16184 	int	i;
16185 	conn_t	*connp;
16186 	connf_t	*connfp;
16187 	zoneid_t zoneid;
16188 
16189 	/*
16190 	 * Because of the ndd constraint, at most we can have 64K buffer
16191 	 * to put in all TCP info.  So to be more efficient, just
16192 	 * allocate a 64K buffer here, assuming we need that large buffer.
16193 	 * This may be a problem as any user can read tcp_status.  Therefore
16194 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16195 	 * This should be OK as normal users should not do this too often.
16196 	 */
16197 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16198 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16199 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16200 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16201 			return (0);
16202 		}
16203 	}
16204 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16205 		/* The following may work even if we cannot get a large buf. */
16206 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16207 		return (0);
16208 	}
16209 
16210 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16211 
16212 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16213 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16214 
16215 		connfp = &ipcl_globalhash_fanout[i];
16216 
16217 		connp = NULL;
16218 
16219 		while ((connp =
16220 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16221 			tcp = connp->conn_tcp;
16222 			if (zoneid != GLOBAL_ZONEID &&
16223 			    zoneid != connp->conn_zoneid)
16224 				continue;
16225 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16226 			    cr);
16227 		}
16228 
16229 	}
16230 
16231 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16232 	return (0);
16233 }
16234 
16235 /* TCP status report triggered via the Named Dispatch mechanism. */
16236 /* ARGSUSED */
16237 static int
16238 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16239 {
16240 	tf_t	*tbf;
16241 	tcp_t	*tcp;
16242 	int	i;
16243 	zoneid_t zoneid;
16244 
16245 	/* Refer to comments in tcp_status_report(). */
16246 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16247 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16248 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16249 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16250 			return (0);
16251 		}
16252 	}
16253 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16254 		/* The following may work even if we cannot get a large buf. */
16255 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16256 		return (0);
16257 	}
16258 
16259 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16260 
16261 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16262 
16263 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16264 		tbf = &tcp_bind_fanout[i];
16265 		mutex_enter(&tbf->tf_lock);
16266 		for (tcp = tbf->tf_tcp; tcp != NULL;
16267 		    tcp = tcp->tcp_bind_hash) {
16268 			if (zoneid != GLOBAL_ZONEID &&
16269 			    zoneid != tcp->tcp_connp->conn_zoneid)
16270 				continue;
16271 			CONN_INC_REF(tcp->tcp_connp);
16272 			tcp_report_item(mp->b_cont, tcp, i,
16273 			    Q_TO_TCP(q), cr);
16274 			CONN_DEC_REF(tcp->tcp_connp);
16275 		}
16276 		mutex_exit(&tbf->tf_lock);
16277 	}
16278 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16279 	return (0);
16280 }
16281 
16282 /* TCP status report triggered via the Named Dispatch mechanism. */
16283 /* ARGSUSED */
16284 static int
16285 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16286 {
16287 	connf_t	*connfp;
16288 	conn_t	*connp;
16289 	tcp_t	*tcp;
16290 	int	i;
16291 	zoneid_t zoneid;
16292 
16293 	/* Refer to comments in tcp_status_report(). */
16294 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16295 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16296 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16297 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16298 			return (0);
16299 		}
16300 	}
16301 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16302 		/* The following may work even if we cannot get a large buf. */
16303 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16304 		return (0);
16305 	}
16306 
16307 	(void) mi_mpprintf(mp,
16308 	    "    TCP    " MI_COL_HDRPAD_STR
16309 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16310 
16311 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16312 
16313 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16314 		connfp =  &ipcl_bind_fanout[i];
16315 		connp = NULL;
16316 		while ((connp =
16317 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16318 			tcp = connp->conn_tcp;
16319 			if (zoneid != GLOBAL_ZONEID &&
16320 			    zoneid != connp->conn_zoneid)
16321 				continue;
16322 			tcp_report_listener(mp->b_cont, tcp, i);
16323 		}
16324 	}
16325 
16326 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16327 	return (0);
16328 }
16329 
16330 /* TCP status report triggered via the Named Dispatch mechanism. */
16331 /* ARGSUSED */
16332 static int
16333 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16334 {
16335 	connf_t	*connfp;
16336 	conn_t	*connp;
16337 	tcp_t	*tcp;
16338 	int	i;
16339 	zoneid_t zoneid;
16340 
16341 	/* Refer to comments in tcp_status_report(). */
16342 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16343 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16344 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16345 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16346 			return (0);
16347 		}
16348 	}
16349 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16350 		/* The following may work even if we cannot get a large buf. */
16351 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16352 		return (0);
16353 	}
16354 
16355 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16356 	    ipcl_conn_fanout_size);
16357 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16358 
16359 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16360 
16361 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16362 		connfp =  &ipcl_conn_fanout[i];
16363 		connp = NULL;
16364 		while ((connp =
16365 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16366 			tcp = connp->conn_tcp;
16367 			if (zoneid != GLOBAL_ZONEID &&
16368 			    zoneid != connp->conn_zoneid)
16369 				continue;
16370 			tcp_report_item(mp->b_cont, tcp, i,
16371 			    Q_TO_TCP(q), cr);
16372 		}
16373 	}
16374 
16375 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16376 	return (0);
16377 }
16378 
16379 /* TCP status report triggered via the Named Dispatch mechanism. */
16380 /* ARGSUSED */
16381 static int
16382 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16383 {
16384 	tf_t	*tf;
16385 	tcp_t	*tcp;
16386 	int	i;
16387 	zoneid_t zoneid;
16388 
16389 	/* Refer to comments in tcp_status_report(). */
16390 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16391 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16392 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16393 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16394 			return (0);
16395 		}
16396 	}
16397 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16398 		/* The following may work even if we cannot get a large buf. */
16399 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16400 		return (0);
16401 	}
16402 
16403 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16404 
16405 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16406 
16407 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16408 		tf = &tcp_acceptor_fanout[i];
16409 		mutex_enter(&tf->tf_lock);
16410 		for (tcp = tf->tf_tcp; tcp != NULL;
16411 		    tcp = tcp->tcp_acceptor_hash) {
16412 			if (zoneid != GLOBAL_ZONEID &&
16413 			    zoneid != tcp->tcp_connp->conn_zoneid)
16414 				continue;
16415 			tcp_report_item(mp->b_cont, tcp, i,
16416 			    Q_TO_TCP(q), cr);
16417 		}
16418 		mutex_exit(&tf->tf_lock);
16419 	}
16420 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16421 	return (0);
16422 }
16423 
16424 /*
16425  * tcp_timer is the timer service routine.  It handles the retransmission,
16426  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16427  * from the state of the tcp instance what kind of action needs to be done
16428  * at the time it is called.
16429  */
16430 static void
16431 tcp_timer(void *arg)
16432 {
16433 	mblk_t		*mp;
16434 	clock_t		first_threshold;
16435 	clock_t		second_threshold;
16436 	clock_t		ms;
16437 	uint32_t	mss;
16438 	conn_t		*connp = (conn_t *)arg;
16439 	tcp_t		*tcp = connp->conn_tcp;
16440 
16441 	tcp->tcp_timer_tid = 0;
16442 
16443 	if (tcp->tcp_fused)
16444 		return;
16445 
16446 	first_threshold =  tcp->tcp_first_timer_threshold;
16447 	second_threshold = tcp->tcp_second_timer_threshold;
16448 	switch (tcp->tcp_state) {
16449 	case TCPS_IDLE:
16450 	case TCPS_BOUND:
16451 	case TCPS_LISTEN:
16452 		return;
16453 	case TCPS_SYN_RCVD: {
16454 		tcp_t	*listener = tcp->tcp_listener;
16455 
16456 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16457 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16458 			/* it's our first timeout */
16459 			tcp->tcp_syn_rcvd_timeout = 1;
16460 			mutex_enter(&listener->tcp_eager_lock);
16461 			listener->tcp_syn_rcvd_timeout++;
16462 			if (!listener->tcp_syn_defense &&
16463 			    (listener->tcp_syn_rcvd_timeout >
16464 			    (tcp_conn_req_max_q0 >> 2)) &&
16465 			    (tcp_conn_req_max_q0 > 200)) {
16466 				/* We may be under attack. Put on a defense. */
16467 				listener->tcp_syn_defense = B_TRUE;
16468 				cmn_err(CE_WARN, "High TCP connect timeout "
16469 				    "rate! System (port %d) may be under a "
16470 				    "SYN flood attack!",
16471 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16472 
16473 				listener->tcp_ip_addr_cache = kmem_zalloc(
16474 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16475 				    KM_NOSLEEP);
16476 			}
16477 			mutex_exit(&listener->tcp_eager_lock);
16478 		}
16479 	}
16480 		/* FALLTHRU */
16481 	case TCPS_SYN_SENT:
16482 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16483 		second_threshold = tcp->tcp_second_ctimer_threshold;
16484 		break;
16485 	case TCPS_ESTABLISHED:
16486 	case TCPS_FIN_WAIT_1:
16487 	case TCPS_CLOSING:
16488 	case TCPS_CLOSE_WAIT:
16489 	case TCPS_LAST_ACK:
16490 		/* If we have data to rexmit */
16491 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16492 			clock_t	time_to_wait;
16493 
16494 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16495 			if (!tcp->tcp_xmit_head)
16496 				break;
16497 			time_to_wait = lbolt -
16498 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16499 			time_to_wait = tcp->tcp_rto -
16500 			    TICK_TO_MSEC(time_to_wait);
16501 			/*
16502 			 * If the timer fires too early, 1 clock tick earlier,
16503 			 * restart the timer.
16504 			 */
16505 			if (time_to_wait > msec_per_tick) {
16506 				TCP_STAT(tcp_timer_fire_early);
16507 				TCP_TIMER_RESTART(tcp, time_to_wait);
16508 				return;
16509 			}
16510 			/*
16511 			 * When we probe zero windows, we force the swnd open.
16512 			 * If our peer acks with a closed window swnd will be
16513 			 * set to zero by tcp_rput(). As long as we are
16514 			 * receiving acks tcp_rput will
16515 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16516 			 * first and second interval actions.  NOTE: the timer
16517 			 * interval is allowed to continue its exponential
16518 			 * backoff.
16519 			 */
16520 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16521 				if (tcp->tcp_debug) {
16522 					(void) strlog(TCP_MOD_ID, 0, 1,
16523 					    SL_TRACE, "tcp_timer: zero win");
16524 				}
16525 			} else {
16526 				/*
16527 				 * After retransmission, we need to do
16528 				 * slow start.  Set the ssthresh to one
16529 				 * half of current effective window and
16530 				 * cwnd to one MSS.  Also reset
16531 				 * tcp_cwnd_cnt.
16532 				 *
16533 				 * Note that if tcp_ssthresh is reduced because
16534 				 * of ECN, do not reduce it again unless it is
16535 				 * already one window of data away (tcp_cwr
16536 				 * should then be cleared) or this is a
16537 				 * timeout for a retransmitted segment.
16538 				 */
16539 				uint32_t npkt;
16540 
16541 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16542 					npkt = ((tcp->tcp_timer_backoff ?
16543 					    tcp->tcp_cwnd_ssthresh :
16544 					    tcp->tcp_snxt -
16545 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16546 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16547 					    tcp->tcp_mss;
16548 				}
16549 				tcp->tcp_cwnd = tcp->tcp_mss;
16550 				tcp->tcp_cwnd_cnt = 0;
16551 				if (tcp->tcp_ecn_ok) {
16552 					tcp->tcp_cwr = B_TRUE;
16553 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16554 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16555 				}
16556 			}
16557 			break;
16558 		}
16559 		/*
16560 		 * We have something to send yet we cannot send.  The
16561 		 * reason can be:
16562 		 *
16563 		 * 1. Zero send window: we need to do zero window probe.
16564 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16565 		 * segments.
16566 		 * 3. SWS avoidance: receiver may have shrunk window,
16567 		 * reset our knowledge.
16568 		 *
16569 		 * Note that condition 2 can happen with either 1 or
16570 		 * 3.  But 1 and 3 are exclusive.
16571 		 */
16572 		if (tcp->tcp_unsent != 0) {
16573 			if (tcp->tcp_cwnd == 0) {
16574 				/*
16575 				 * Set tcp_cwnd to 1 MSS so that a
16576 				 * new segment can be sent out.  We
16577 				 * are "clocking out" new data when
16578 				 * the network is really congested.
16579 				 */
16580 				ASSERT(tcp->tcp_ecn_ok);
16581 				tcp->tcp_cwnd = tcp->tcp_mss;
16582 			}
16583 			if (tcp->tcp_swnd == 0) {
16584 				/* Extend window for zero window probe */
16585 				tcp->tcp_swnd++;
16586 				tcp->tcp_zero_win_probe = B_TRUE;
16587 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16588 			} else {
16589 				/*
16590 				 * Handle timeout from sender SWS avoidance.
16591 				 * Reset our knowledge of the max send window
16592 				 * since the receiver might have reduced its
16593 				 * receive buffer.  Avoid setting tcp_max_swnd
16594 				 * to one since that will essentially disable
16595 				 * the SWS checks.
16596 				 *
16597 				 * Note that since we don't have a SWS
16598 				 * state variable, if the timeout is set
16599 				 * for ECN but not for SWS, this
16600 				 * code will also be executed.  This is
16601 				 * fine as tcp_max_swnd is updated
16602 				 * constantly and it will not affect
16603 				 * anything.
16604 				 */
16605 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16606 			}
16607 			tcp_wput_data(tcp, NULL, B_FALSE);
16608 			return;
16609 		}
16610 		/* Is there a FIN that needs to be to re retransmitted? */
16611 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16612 		    !tcp->tcp_fin_acked)
16613 			break;
16614 		/* Nothing to do, return without restarting timer. */
16615 		TCP_STAT(tcp_timer_fire_miss);
16616 		return;
16617 	case TCPS_FIN_WAIT_2:
16618 		/*
16619 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16620 		 * We waited some time for for peer's FIN, but it hasn't
16621 		 * arrived.  We flush the connection now to avoid
16622 		 * case where the peer has rebooted.
16623 		 */
16624 		if (TCP_IS_DETACHED(tcp)) {
16625 			(void) tcp_clean_death(tcp, 0, 23);
16626 		} else {
16627 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16628 		}
16629 		return;
16630 	case TCPS_TIME_WAIT:
16631 		(void) tcp_clean_death(tcp, 0, 24);
16632 		return;
16633 	default:
16634 		if (tcp->tcp_debug) {
16635 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16636 			    "tcp_timer: strange state (%d) %s",
16637 			    tcp->tcp_state, tcp_display(tcp, NULL,
16638 			    DISP_PORT_ONLY));
16639 		}
16640 		return;
16641 	}
16642 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16643 		/*
16644 		 * For zero window probe, we need to send indefinitely,
16645 		 * unless we have not heard from the other side for some
16646 		 * time...
16647 		 */
16648 		if ((tcp->tcp_zero_win_probe == 0) ||
16649 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16650 		    second_threshold)) {
16651 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16652 			/*
16653 			 * If TCP is in SYN_RCVD state, send back a
16654 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16655 			 * should be zero in TCPS_SYN_RCVD state.
16656 			 */
16657 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16658 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16659 				    "in SYN_RCVD",
16660 				    tcp, tcp->tcp_snxt,
16661 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16662 			}
16663 			(void) tcp_clean_death(tcp,
16664 			    tcp->tcp_client_errno ?
16665 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16666 			return;
16667 		} else {
16668 			/*
16669 			 * Set tcp_ms_we_have_waited to second_threshold
16670 			 * so that in next timeout, we will do the above
16671 			 * check (lbolt - tcp_last_recv_time).  This is
16672 			 * also to avoid overflow.
16673 			 *
16674 			 * We don't need to decrement tcp_timer_backoff
16675 			 * to avoid overflow because it will be decremented
16676 			 * later if new timeout value is greater than
16677 			 * tcp_rexmit_interval_max.  In the case when
16678 			 * tcp_rexmit_interval_max is greater than
16679 			 * second_threshold, it means that we will wait
16680 			 * longer than second_threshold to send the next
16681 			 * window probe.
16682 			 */
16683 			tcp->tcp_ms_we_have_waited = second_threshold;
16684 		}
16685 	} else if (ms > first_threshold) {
16686 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16687 		    tcp->tcp_xmit_head != NULL) {
16688 			tcp->tcp_xmit_head =
16689 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16690 		}
16691 		/*
16692 		 * We have been retransmitting for too long...  The RTT
16693 		 * we calculated is probably incorrect.  Reinitialize it.
16694 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16695 		 * tcp_rtt_update so that we won't accidentally cache a
16696 		 * bad value.  But only do this if this is not a zero
16697 		 * window probe.
16698 		 */
16699 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16700 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16701 			    (tcp->tcp_rtt_sa >> 5);
16702 			tcp->tcp_rtt_sa = 0;
16703 			tcp_ip_notify(tcp);
16704 			tcp->tcp_rtt_update = 0;
16705 		}
16706 	}
16707 	tcp->tcp_timer_backoff++;
16708 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16709 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16710 	    tcp_rexmit_interval_min) {
16711 		/*
16712 		 * This means the original RTO is tcp_rexmit_interval_min.
16713 		 * So we will use tcp_rexmit_interval_min as the RTO value
16714 		 * and do the backoff.
16715 		 */
16716 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16717 	} else {
16718 		ms <<= tcp->tcp_timer_backoff;
16719 	}
16720 	if (ms > tcp_rexmit_interval_max) {
16721 		ms = tcp_rexmit_interval_max;
16722 		/*
16723 		 * ms is at max, decrement tcp_timer_backoff to avoid
16724 		 * overflow.
16725 		 */
16726 		tcp->tcp_timer_backoff--;
16727 	}
16728 	tcp->tcp_ms_we_have_waited += ms;
16729 	if (tcp->tcp_zero_win_probe == 0) {
16730 		tcp->tcp_rto = ms;
16731 	}
16732 	TCP_TIMER_RESTART(tcp, ms);
16733 	/*
16734 	 * This is after a timeout and tcp_rto is backed off.  Set
16735 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16736 	 * restart the timer with a correct value.
16737 	 */
16738 	tcp->tcp_set_timer = 1;
16739 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16740 	if (mss > tcp->tcp_mss)
16741 		mss = tcp->tcp_mss;
16742 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16743 		mss = tcp->tcp_swnd;
16744 
16745 	if ((mp = tcp->tcp_xmit_head) != NULL)
16746 		mp->b_prev = (mblk_t *)lbolt;
16747 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16748 	    B_TRUE);
16749 
16750 	/*
16751 	 * When slow start after retransmission begins, start with
16752 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16753 	 * start phase.  tcp_snd_burst controls how many segments
16754 	 * can be sent because of an ack.
16755 	 */
16756 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16757 	tcp->tcp_snd_burst = TCP_CWND_SS;
16758 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16759 	    (tcp->tcp_unsent == 0)) {
16760 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16761 	} else {
16762 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16763 	}
16764 	tcp->tcp_rexmit = B_TRUE;
16765 	tcp->tcp_dupack_cnt = 0;
16766 
16767 	/*
16768 	 * Remove all rexmit SACK blk to start from fresh.
16769 	 */
16770 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16771 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16772 		tcp->tcp_num_notsack_blk = 0;
16773 		tcp->tcp_cnt_notsack_list = 0;
16774 	}
16775 	if (mp == NULL) {
16776 		return;
16777 	}
16778 	/* Attach credentials to retransmitted initial SYNs. */
16779 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16780 		mblk_setcred(mp, tcp->tcp_cred);
16781 		DB_CPID(mp) = tcp->tcp_cpid;
16782 	}
16783 
16784 	tcp->tcp_csuna = tcp->tcp_snxt;
16785 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16786 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16787 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16788 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16789 
16790 }
16791 
16792 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16793 static void
16794 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16795 {
16796 	conn_t	*connp;
16797 
16798 	switch (tcp->tcp_state) {
16799 	case TCPS_BOUND:
16800 	case TCPS_LISTEN:
16801 		break;
16802 	default:
16803 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16804 		return;
16805 	}
16806 
16807 	/*
16808 	 * Need to clean up all the eagers since after the unbind, segments
16809 	 * will no longer be delivered to this listener stream.
16810 	 */
16811 	mutex_enter(&tcp->tcp_eager_lock);
16812 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16813 		tcp_eager_cleanup(tcp, 0);
16814 	}
16815 	mutex_exit(&tcp->tcp_eager_lock);
16816 
16817 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16818 		tcp->tcp_ipha->ipha_src = 0;
16819 	} else {
16820 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16821 	}
16822 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16823 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16824 	tcp_bind_hash_remove(tcp);
16825 	tcp->tcp_state = TCPS_IDLE;
16826 	tcp->tcp_mdt = B_FALSE;
16827 	/* Send M_FLUSH according to TPI */
16828 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16829 	connp = tcp->tcp_connp;
16830 	connp->conn_mdt_ok = B_FALSE;
16831 	ipcl_hash_remove(connp);
16832 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16833 	mp = mi_tpi_ok_ack_alloc(mp);
16834 	putnext(tcp->tcp_rq, mp);
16835 }
16836 
16837 /*
16838  * Don't let port fall into the privileged range.
16839  * Since the extra privileged ports can be arbitrary we also
16840  * ensure that we exclude those from consideration.
16841  * tcp_g_epriv_ports is not sorted thus we loop over it until
16842  * there are no changes.
16843  *
16844  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16845  * but instead the code relies on:
16846  * - the fact that the address of the array and its size never changes
16847  * - the atomic assignment of the elements of the array
16848  *
16849  * Returns 0 if there are no more ports available.
16850  *
16851  * TS note: skip multilevel ports.
16852  */
16853 static in_port_t
16854 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
16855 {
16856 	int i;
16857 	boolean_t restart = B_FALSE;
16858 
16859 	if (random && tcp_random_anon_port != 0) {
16860 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16861 		    sizeof (in_port_t));
16862 		/*
16863 		 * Unless changed by a sys admin, the smallest anon port
16864 		 * is 32768 and the largest anon port is 65535.  It is
16865 		 * very likely (50%) for the random port to be smaller
16866 		 * than the smallest anon port.  When that happens,
16867 		 * add port % (anon port range) to the smallest anon
16868 		 * port to get the random port.  It should fall into the
16869 		 * valid anon port range.
16870 		 */
16871 		if (port < tcp_smallest_anon_port) {
16872 			port = tcp_smallest_anon_port +
16873 			    port % (tcp_largest_anon_port -
16874 				tcp_smallest_anon_port);
16875 		}
16876 	}
16877 
16878 retry:
16879 	if (port < tcp_smallest_anon_port)
16880 		port = (in_port_t)tcp_smallest_anon_port;
16881 
16882 	if (port > tcp_largest_anon_port) {
16883 		if (restart)
16884 			return (0);
16885 		restart = B_TRUE;
16886 		port = (in_port_t)tcp_smallest_anon_port;
16887 	}
16888 
16889 	if (port < tcp_smallest_nonpriv_port)
16890 		port = (in_port_t)tcp_smallest_nonpriv_port;
16891 
16892 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16893 		if (port == tcp_g_epriv_ports[i]) {
16894 			port++;
16895 			/*
16896 			 * Make sure whether the port is in the
16897 			 * valid range.
16898 			 */
16899 			goto retry;
16900 		}
16901 	}
16902 	if (is_system_labeled() &&
16903 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
16904 	    IPPROTO_TCP, B_TRUE)) != 0) {
16905 		port = i;
16906 		goto retry;
16907 	}
16908 	return (port);
16909 }
16910 
16911 /*
16912  * Return the next anonymous port in the privileged port range for
16913  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16914  * downwards.  This is the same behavior as documented in the userland
16915  * library call rresvport(3N).
16916  *
16917  * TS note: skip multilevel ports.
16918  */
16919 static in_port_t
16920 tcp_get_next_priv_port(const tcp_t *tcp)
16921 {
16922 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16923 	in_port_t nextport;
16924 	boolean_t restart = B_FALSE;
16925 
16926 retry:
16927 	if (next_priv_port < tcp_min_anonpriv_port ||
16928 	    next_priv_port >= IPPORT_RESERVED) {
16929 		next_priv_port = IPPORT_RESERVED - 1;
16930 		if (restart)
16931 			return (0);
16932 		restart = B_TRUE;
16933 	}
16934 	if (is_system_labeled() &&
16935 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
16936 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
16937 		next_priv_port = nextport;
16938 		goto retry;
16939 	}
16940 	return (next_priv_port--);
16941 }
16942 
16943 /* The write side r/w procedure. */
16944 
16945 #if CCS_STATS
16946 struct {
16947 	struct {
16948 		int64_t count, bytes;
16949 	} tot, hit;
16950 } wrw_stats;
16951 #endif
16952 
16953 /*
16954  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16955  * messages.
16956  */
16957 /* ARGSUSED */
16958 static void
16959 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16960 {
16961 	conn_t	*connp = (conn_t *)arg;
16962 	tcp_t	*tcp = connp->conn_tcp;
16963 	queue_t	*q = tcp->tcp_wq;
16964 
16965 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16966 	/*
16967 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16968 	 * Once the close starts, streamhead and sockfs will not let any data
16969 	 * packets come down (close ensures that there are no threads using the
16970 	 * queue and no new threads will come down) but since qprocsoff()
16971 	 * hasn't happened yet, a M_FLUSH or some non data message might
16972 	 * get reflected back (in response to our own FLUSHRW) and get
16973 	 * processed after tcp_close() is done. The conn would still be valid
16974 	 * because a ref would have added but we need to check the state
16975 	 * before actually processing the packet.
16976 	 */
16977 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16978 		freemsg(mp);
16979 		return;
16980 	}
16981 
16982 	switch (DB_TYPE(mp)) {
16983 	case M_IOCDATA:
16984 		tcp_wput_iocdata(tcp, mp);
16985 		break;
16986 	case M_FLUSH:
16987 		tcp_wput_flush(tcp, mp);
16988 		break;
16989 	default:
16990 		CALL_IP_WPUT(connp, q, mp);
16991 		break;
16992 	}
16993 }
16994 
16995 /*
16996  * The TCP fast path write put procedure.
16997  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16998  */
16999 /* ARGSUSED */
17000 void
17001 tcp_output(void *arg, mblk_t *mp, void *arg2)
17002 {
17003 	int		len;
17004 	int		hdrlen;
17005 	int		plen;
17006 	mblk_t		*mp1;
17007 	uchar_t		*rptr;
17008 	uint32_t	snxt;
17009 	tcph_t		*tcph;
17010 	struct datab	*db;
17011 	uint32_t	suna;
17012 	uint32_t	mss;
17013 	ipaddr_t	*dst;
17014 	ipaddr_t	*src;
17015 	uint32_t	sum;
17016 	int		usable;
17017 	conn_t		*connp = (conn_t *)arg;
17018 	tcp_t		*tcp = connp->conn_tcp;
17019 	uint32_t	msize;
17020 
17021 	/*
17022 	 * Try and ASSERT the minimum possible references on the
17023 	 * conn early enough. Since we are executing on write side,
17024 	 * the connection is obviously not detached and that means
17025 	 * there is a ref each for TCP and IP. Since we are behind
17026 	 * the squeue, the minimum references needed are 3. If the
17027 	 * conn is in classifier hash list, there should be an
17028 	 * extra ref for that (we check both the possibilities).
17029 	 */
17030 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17031 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17032 
17033 	ASSERT(DB_TYPE(mp) == M_DATA);
17034 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17035 
17036 	mutex_enter(&connp->conn_lock);
17037 	tcp->tcp_squeue_bytes -= msize;
17038 	mutex_exit(&connp->conn_lock);
17039 
17040 	/* Bypass tcp protocol for fused tcp loopback */
17041 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17042 		return;
17043 
17044 	mss = tcp->tcp_mss;
17045 	if (tcp->tcp_xmit_zc_clean)
17046 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17047 
17048 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17049 	len = (int)(mp->b_wptr - mp->b_rptr);
17050 
17051 	/*
17052 	 * Criteria for fast path:
17053 	 *
17054 	 *   1. no unsent data
17055 	 *   2. single mblk in request
17056 	 *   3. connection established
17057 	 *   4. data in mblk
17058 	 *   5. len <= mss
17059 	 *   6. no tcp_valid bits
17060 	 */
17061 	if ((tcp->tcp_unsent != 0) ||
17062 	    (tcp->tcp_cork) ||
17063 	    (mp->b_cont != NULL) ||
17064 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17065 	    (len == 0) ||
17066 	    (len > mss) ||
17067 	    (tcp->tcp_valid_bits != 0)) {
17068 		tcp_wput_data(tcp, mp, B_FALSE);
17069 		return;
17070 	}
17071 
17072 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17073 	ASSERT(tcp->tcp_fin_sent == 0);
17074 
17075 	/* queue new packet onto retransmission queue */
17076 	if (tcp->tcp_xmit_head == NULL) {
17077 		tcp->tcp_xmit_head = mp;
17078 	} else {
17079 		tcp->tcp_xmit_last->b_cont = mp;
17080 	}
17081 	tcp->tcp_xmit_last = mp;
17082 	tcp->tcp_xmit_tail = mp;
17083 
17084 	/* find out how much we can send */
17085 	/* BEGIN CSTYLED */
17086 	/*
17087 	 *    un-acked           usable
17088 	 *  |--------------|-----------------|
17089 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17090 	 */
17091 	/* END CSTYLED */
17092 
17093 	/* start sending from tcp_snxt */
17094 	snxt = tcp->tcp_snxt;
17095 
17096 	/*
17097 	 * Check to see if this connection has been idled for some
17098 	 * time and no ACK is expected.  If it is, we need to slow
17099 	 * start again to get back the connection's "self-clock" as
17100 	 * described in VJ's paper.
17101 	 *
17102 	 * Refer to the comment in tcp_mss_set() for the calculation
17103 	 * of tcp_cwnd after idle.
17104 	 */
17105 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17106 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17107 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
17108 	}
17109 
17110 	usable = tcp->tcp_swnd;		/* tcp window size */
17111 	if (usable > tcp->tcp_cwnd)
17112 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17113 	usable -= snxt;		/* subtract stuff already sent */
17114 	suna = tcp->tcp_suna;
17115 	usable += suna;
17116 	/* usable can be < 0 if the congestion window is smaller */
17117 	if (len > usable) {
17118 		/* Can't send complete M_DATA in one shot */
17119 		goto slow;
17120 	}
17121 
17122 	if (tcp->tcp_flow_stopped &&
17123 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17124 		tcp_clrqfull(tcp);
17125 	}
17126 
17127 	/*
17128 	 * determine if anything to send (Nagle).
17129 	 *
17130 	 *   1. len < tcp_mss (i.e. small)
17131 	 *   2. unacknowledged data present
17132 	 *   3. len < nagle limit
17133 	 *   4. last packet sent < nagle limit (previous packet sent)
17134 	 */
17135 	if ((len < mss) && (snxt != suna) &&
17136 	    (len < (int)tcp->tcp_naglim) &&
17137 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17138 		/*
17139 		 * This was the first unsent packet and normally
17140 		 * mss < xmit_hiwater so there is no need to worry
17141 		 * about flow control. The next packet will go
17142 		 * through the flow control check in tcp_wput_data().
17143 		 */
17144 		/* leftover work from above */
17145 		tcp->tcp_unsent = len;
17146 		tcp->tcp_xmit_tail_unsent = len;
17147 
17148 		return;
17149 	}
17150 
17151 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17152 
17153 	if (snxt == suna) {
17154 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17155 	}
17156 
17157 	/* we have always sent something */
17158 	tcp->tcp_rack_cnt = 0;
17159 
17160 	tcp->tcp_snxt = snxt + len;
17161 	tcp->tcp_rack = tcp->tcp_rnxt;
17162 
17163 	if ((mp1 = dupb(mp)) == 0)
17164 		goto no_memory;
17165 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17166 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17167 
17168 	/* adjust tcp header information */
17169 	tcph = tcp->tcp_tcph;
17170 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17171 
17172 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17173 	sum = (sum >> 16) + (sum & 0xFFFF);
17174 	U16_TO_ABE16(sum, tcph->th_sum);
17175 
17176 	U32_TO_ABE32(snxt, tcph->th_seq);
17177 
17178 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
17179 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
17180 	BUMP_LOCAL(tcp->tcp_obsegs);
17181 
17182 	/* Update the latest receive window size in TCP header. */
17183 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17184 	    tcph->th_win);
17185 
17186 	tcp->tcp_last_sent_len = (ushort_t)len;
17187 
17188 	plen = len + tcp->tcp_hdr_len;
17189 
17190 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17191 		tcp->tcp_ipha->ipha_length = htons(plen);
17192 	} else {
17193 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17194 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17195 	}
17196 
17197 	/* see if we need to allocate a mblk for the headers */
17198 	hdrlen = tcp->tcp_hdr_len;
17199 	rptr = mp1->b_rptr - hdrlen;
17200 	db = mp1->b_datap;
17201 	if ((db->db_ref != 2) || rptr < db->db_base ||
17202 	    (!OK_32PTR(rptr))) {
17203 		/* NOTE: we assume allocb returns an OK_32PTR */
17204 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17205 		    tcp_wroff_xtra, BPRI_MED);
17206 		if (!mp) {
17207 			freemsg(mp1);
17208 			goto no_memory;
17209 		}
17210 		mp->b_cont = mp1;
17211 		mp1 = mp;
17212 		/* Leave room for Link Level header */
17213 		/* hdrlen = tcp->tcp_hdr_len; */
17214 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
17215 		mp1->b_wptr = &rptr[hdrlen];
17216 	}
17217 	mp1->b_rptr = rptr;
17218 
17219 	/* Fill in the timestamp option. */
17220 	if (tcp->tcp_snd_ts_ok) {
17221 		U32_TO_BE32((uint32_t)lbolt,
17222 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17223 		U32_TO_BE32(tcp->tcp_ts_recent,
17224 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17225 	} else {
17226 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17227 	}
17228 
17229 	/* copy header into outgoing packet */
17230 	dst = (ipaddr_t *)rptr;
17231 	src = (ipaddr_t *)tcp->tcp_iphc;
17232 	dst[0] = src[0];
17233 	dst[1] = src[1];
17234 	dst[2] = src[2];
17235 	dst[3] = src[3];
17236 	dst[4] = src[4];
17237 	dst[5] = src[5];
17238 	dst[6] = src[6];
17239 	dst[7] = src[7];
17240 	dst[8] = src[8];
17241 	dst[9] = src[9];
17242 	if (hdrlen -= 40) {
17243 		hdrlen >>= 2;
17244 		dst += 10;
17245 		src += 10;
17246 		do {
17247 			*dst++ = *src++;
17248 		} while (--hdrlen);
17249 	}
17250 
17251 	/*
17252 	 * Set the ECN info in the TCP header.  Note that this
17253 	 * is not the template header.
17254 	 */
17255 	if (tcp->tcp_ecn_ok) {
17256 		SET_ECT(tcp, rptr);
17257 
17258 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17259 		if (tcp->tcp_ecn_echo_on)
17260 			tcph->th_flags[0] |= TH_ECE;
17261 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17262 			tcph->th_flags[0] |= TH_CWR;
17263 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17264 		}
17265 	}
17266 
17267 	if (tcp->tcp_ip_forward_progress) {
17268 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17269 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17270 		tcp->tcp_ip_forward_progress = B_FALSE;
17271 	}
17272 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17273 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17274 	return;
17275 
17276 	/*
17277 	 * If we ran out of memory, we pretend to have sent the packet
17278 	 * and that it was lost on the wire.
17279 	 */
17280 no_memory:
17281 	return;
17282 
17283 slow:
17284 	/* leftover work from above */
17285 	tcp->tcp_unsent = len;
17286 	tcp->tcp_xmit_tail_unsent = len;
17287 	tcp_wput_data(tcp, NULL, B_FALSE);
17288 }
17289 
17290 /*
17291  * The function called through squeue to get behind eager's perimeter to
17292  * finish the accept processing.
17293  */
17294 /* ARGSUSED */
17295 void
17296 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17297 {
17298 	conn_t			*connp = (conn_t *)arg;
17299 	tcp_t			*tcp = connp->conn_tcp;
17300 	queue_t			*q = tcp->tcp_rq;
17301 	mblk_t			*mp1;
17302 	mblk_t			*stropt_mp = mp;
17303 	struct  stroptions	*stropt;
17304 	uint_t			thwin;
17305 
17306 	/*
17307 	 * Drop the eager's ref on the listener, that was placed when
17308 	 * this eager began life in tcp_conn_request.
17309 	 */
17310 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17311 
17312 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17313 		/*
17314 		 * Someone blewoff the eager before we could finish
17315 		 * the accept.
17316 		 *
17317 		 * The only reason eager exists it because we put in
17318 		 * a ref on it when conn ind went up. We need to send
17319 		 * a disconnect indication up while the last reference
17320 		 * on the eager will be dropped by the squeue when we
17321 		 * return.
17322 		 */
17323 		ASSERT(tcp->tcp_listener == NULL);
17324 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17325 			struct	T_discon_ind	*tdi;
17326 
17327 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17328 			/*
17329 			 * Let us reuse the incoming mblk to avoid memory
17330 			 * allocation failure problems. We know that the
17331 			 * size of the incoming mblk i.e. stroptions is greater
17332 			 * than sizeof T_discon_ind. So the reallocb below
17333 			 * can't fail.
17334 			 */
17335 			freemsg(mp->b_cont);
17336 			mp->b_cont = NULL;
17337 			ASSERT(DB_REF(mp) == 1);
17338 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17339 			    B_FALSE);
17340 			ASSERT(mp != NULL);
17341 			DB_TYPE(mp) = M_PROTO;
17342 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17343 			tdi = (struct T_discon_ind *)mp->b_rptr;
17344 			if (tcp->tcp_issocket) {
17345 				tdi->DISCON_reason = ECONNREFUSED;
17346 				tdi->SEQ_number = 0;
17347 			} else {
17348 				tdi->DISCON_reason = ENOPROTOOPT;
17349 				tdi->SEQ_number =
17350 				    tcp->tcp_conn_req_seqnum;
17351 			}
17352 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17353 			putnext(q, mp);
17354 		} else {
17355 			freemsg(mp);
17356 		}
17357 		if (tcp->tcp_hard_binding) {
17358 			tcp->tcp_hard_binding = B_FALSE;
17359 			tcp->tcp_hard_bound = B_TRUE;
17360 		}
17361 		tcp->tcp_detached = B_FALSE;
17362 		return;
17363 	}
17364 
17365 	mp1 = stropt_mp->b_cont;
17366 	stropt_mp->b_cont = NULL;
17367 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17368 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17369 
17370 	while (mp1 != NULL) {
17371 		mp = mp1;
17372 		mp1 = mp1->b_cont;
17373 		mp->b_cont = NULL;
17374 		tcp->tcp_drop_opt_ack_cnt++;
17375 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17376 	}
17377 	mp = NULL;
17378 
17379 	/*
17380 	 * For a loopback connection with tcp_direct_sockfs on, note that
17381 	 * we don't have to protect tcp_rcv_list yet because synchronous
17382 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17383 	 * possibly race with us.
17384 	 */
17385 
17386 	/*
17387 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17388 	 * properly.  This is the first time we know of the acceptor'
17389 	 * queue.  So we do it here.
17390 	 */
17391 	if (tcp->tcp_rcv_list == NULL) {
17392 		/*
17393 		 * Recv queue is empty, tcp_rwnd should not have changed.
17394 		 * That means it should be equal to the listener's tcp_rwnd.
17395 		 */
17396 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17397 	} else {
17398 #ifdef DEBUG
17399 		uint_t cnt = 0;
17400 
17401 		mp1 = tcp->tcp_rcv_list;
17402 		while ((mp = mp1) != NULL) {
17403 			mp1 = mp->b_next;
17404 			cnt += msgdsize(mp);
17405 		}
17406 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17407 #endif
17408 		/* There is some data, add them back to get the max. */
17409 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17410 	}
17411 
17412 	stropt->so_flags = SO_HIWAT;
17413 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17414 
17415 	stropt->so_flags |= SO_MAXBLK;
17416 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17417 
17418 	/*
17419 	 * This is the first time we run on the correct
17420 	 * queue after tcp_accept. So fix all the q parameters
17421 	 * here.
17422 	 */
17423 	/* Allocate room for SACK options if needed. */
17424 	stropt->so_flags |= SO_WROFF;
17425 	if (tcp->tcp_fused) {
17426 		ASSERT(tcp->tcp_loopback);
17427 		ASSERT(tcp->tcp_loopback_peer != NULL);
17428 		/*
17429 		 * For fused tcp loopback, set the stream head's write
17430 		 * offset value to zero since we won't be needing any room
17431 		 * for TCP/IP headers.  This would also improve performance
17432 		 * since it would reduce the amount of work done by kmem.
17433 		 * Non-fused tcp loopback case is handled separately below.
17434 		 */
17435 		stropt->so_wroff = 0;
17436 		/*
17437 		 * Record the stream head's high water mark for this endpoint;
17438 		 * this is used for flow-control purposes in tcp_fuse_output().
17439 		 */
17440 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17441 		/*
17442 		 * Update the peer's transmit parameters according to
17443 		 * our recently calculated high water mark value.
17444 		 */
17445 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17446 	} else if (tcp->tcp_snd_sack_ok) {
17447 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17448 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17449 	} else {
17450 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17451 		    tcp_wroff_xtra);
17452 	}
17453 
17454 	/*
17455 	 * If this is endpoint is handling SSL, then reserve extra
17456 	 * offset and space at the end.
17457 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17458 	 * overriding the previous setting. The extra cost of signing and
17459 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17460 	 * instead of a single contiguous one by the stream head
17461 	 * largely outweighs the statistical reduction of ACKs, when
17462 	 * applicable. The peer will also save on decyption and verification
17463 	 * costs.
17464 	 */
17465 	if (tcp->tcp_kssl_ctx != NULL) {
17466 		stropt->so_wroff += SSL3_WROFFSET;
17467 
17468 		stropt->so_flags |= SO_TAIL;
17469 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17470 
17471 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17472 	}
17473 
17474 	/* Send the options up */
17475 	putnext(q, stropt_mp);
17476 
17477 	/*
17478 	 * Pass up any data and/or a fin that has been received.
17479 	 *
17480 	 * Adjust receive window in case it had decreased
17481 	 * (because there is data <=> tcp_rcv_list != NULL)
17482 	 * while the connection was detached. Note that
17483 	 * in case the eager was flow-controlled, w/o this
17484 	 * code, the rwnd may never open up again!
17485 	 */
17486 	if (tcp->tcp_rcv_list != NULL) {
17487 		/* We drain directly in case of fused tcp loopback */
17488 		if (!tcp->tcp_fused && canputnext(q)) {
17489 			tcp->tcp_rwnd = q->q_hiwat;
17490 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17491 			    << tcp->tcp_rcv_ws;
17492 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17493 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17494 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17495 				tcp_xmit_ctl(NULL,
17496 				    tcp, (tcp->tcp_swnd == 0) ?
17497 				    tcp->tcp_suna : tcp->tcp_snxt,
17498 				    tcp->tcp_rnxt, TH_ACK);
17499 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17500 			}
17501 
17502 		}
17503 		(void) tcp_rcv_drain(q, tcp);
17504 
17505 		/*
17506 		 * For fused tcp loopback, back-enable peer endpoint
17507 		 * if it's currently flow-controlled.
17508 		 */
17509 		if (tcp->tcp_fused &&
17510 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17511 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17512 
17513 			ASSERT(peer_tcp != NULL);
17514 			ASSERT(peer_tcp->tcp_fused);
17515 
17516 			tcp_clrqfull(peer_tcp);
17517 			TCP_STAT(tcp_fusion_backenabled);
17518 		}
17519 	}
17520 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17521 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17522 		mp = mi_tpi_ordrel_ind();
17523 		if (mp) {
17524 			tcp->tcp_ordrel_done = B_TRUE;
17525 			putnext(q, mp);
17526 			if (tcp->tcp_deferred_clean_death) {
17527 				/*
17528 				 * tcp_clean_death was deferred
17529 				 * for T_ORDREL_IND - do it now
17530 				 */
17531 				(void) tcp_clean_death(tcp,
17532 				    tcp->tcp_client_errno, 21);
17533 				tcp->tcp_deferred_clean_death = B_FALSE;
17534 			}
17535 		} else {
17536 			/*
17537 			 * Run the orderly release in the
17538 			 * service routine.
17539 			 */
17540 			qenable(q);
17541 		}
17542 	}
17543 	if (tcp->tcp_hard_binding) {
17544 		tcp->tcp_hard_binding = B_FALSE;
17545 		tcp->tcp_hard_bound = B_TRUE;
17546 	}
17547 
17548 	tcp->tcp_detached = B_FALSE;
17549 
17550 	/* We can enable synchronous streams now */
17551 	if (tcp->tcp_fused) {
17552 		tcp_fuse_syncstr_enable_pair(tcp);
17553 	}
17554 
17555 	if (tcp->tcp_ka_enabled) {
17556 		tcp->tcp_ka_last_intrvl = 0;
17557 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17558 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17559 	}
17560 
17561 	/*
17562 	 * At this point, eager is fully established and will
17563 	 * have the following references -
17564 	 *
17565 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17566 	 * 1 reference for the squeue which will be dropped by the squeue as
17567 	 *	soon as this function returns.
17568 	 * There will be 1 additonal reference for being in classifier
17569 	 *	hash list provided something bad hasn't happened.
17570 	 */
17571 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17572 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17573 }
17574 
17575 /*
17576  * The function called through squeue to get behind listener's perimeter to
17577  * send a deffered conn_ind.
17578  */
17579 /* ARGSUSED */
17580 void
17581 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17582 {
17583 	conn_t	*connp = (conn_t *)arg;
17584 	tcp_t *listener = connp->conn_tcp;
17585 
17586 	if (listener->tcp_state == TCPS_CLOSED ||
17587 	    TCP_IS_DETACHED(listener)) {
17588 		/*
17589 		 * If listener has closed, it would have caused a
17590 		 * a cleanup/blowoff to happen for the eager.
17591 		 */
17592 		tcp_t *tcp;
17593 		struct T_conn_ind	*conn_ind;
17594 
17595 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17596 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17597 		    conn_ind->OPT_length);
17598 		/*
17599 		 * We need to drop the ref on eager that was put
17600 		 * tcp_rput_data() before trying to send the conn_ind
17601 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17602 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17603 		 * listener is closed so we drop the ref.
17604 		 */
17605 		CONN_DEC_REF(tcp->tcp_connp);
17606 		freemsg(mp);
17607 		return;
17608 	}
17609 	putnext(listener->tcp_rq, mp);
17610 }
17611 
17612 
17613 /*
17614  * This is the STREAMS entry point for T_CONN_RES coming down on
17615  * Acceptor STREAM when  sockfs listener does accept processing.
17616  * Read the block comment on top pf tcp_conn_request().
17617  */
17618 void
17619 tcp_wput_accept(queue_t *q, mblk_t *mp)
17620 {
17621 	queue_t *rq = RD(q);
17622 	struct T_conn_res *conn_res;
17623 	tcp_t *eager;
17624 	tcp_t *listener;
17625 	struct T_ok_ack *ok;
17626 	t_scalar_t PRIM_type;
17627 	mblk_t *opt_mp;
17628 	conn_t *econnp;
17629 
17630 	ASSERT(DB_TYPE(mp) == M_PROTO);
17631 
17632 	conn_res = (struct T_conn_res *)mp->b_rptr;
17633 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17634 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17635 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17636 		if (mp != NULL)
17637 			putnext(rq, mp);
17638 		return;
17639 	}
17640 	switch (conn_res->PRIM_type) {
17641 	case O_T_CONN_RES:
17642 	case T_CONN_RES:
17643 		/*
17644 		 * We pass up an err ack if allocb fails. This will
17645 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17646 		 * tcp_eager_blowoff to be called. sockfs will then call
17647 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17648 		 * we need to do the allocb up here because we have to
17649 		 * make sure rq->q_qinfo->qi_qclose still points to the
17650 		 * correct function (tcpclose_accept) in case allocb
17651 		 * fails.
17652 		 */
17653 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17654 		if (opt_mp == NULL) {
17655 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17656 			if (mp != NULL)
17657 				putnext(rq, mp);
17658 			return;
17659 		}
17660 
17661 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17662 		    &eager, conn_res->OPT_length);
17663 		PRIM_type = conn_res->PRIM_type;
17664 		mp->b_datap->db_type = M_PCPROTO;
17665 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17666 		ok = (struct T_ok_ack *)mp->b_rptr;
17667 		ok->PRIM_type = T_OK_ACK;
17668 		ok->CORRECT_prim = PRIM_type;
17669 		econnp = eager->tcp_connp;
17670 		econnp->conn_dev = (dev_t)q->q_ptr;
17671 		eager->tcp_rq = rq;
17672 		eager->tcp_wq = q;
17673 		rq->q_ptr = econnp;
17674 		rq->q_qinfo = &tcp_rinit;
17675 		q->q_ptr = econnp;
17676 		q->q_qinfo = &tcp_winit;
17677 		listener = eager->tcp_listener;
17678 		eager->tcp_issocket = B_TRUE;
17679 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17680 
17681 		/* Put the ref for IP */
17682 		CONN_INC_REF(econnp);
17683 
17684 		/*
17685 		 * We should have minimum of 3 references on the conn
17686 		 * at this point. One each for TCP and IP and one for
17687 		 * the T_conn_ind that was sent up when the 3-way handshake
17688 		 * completed. In the normal case we would also have another
17689 		 * reference (making a total of 4) for the conn being in the
17690 		 * classifier hash list. However the eager could have received
17691 		 * an RST subsequently and tcp_closei_local could have removed
17692 		 * the eager from the classifier hash list, hence we can't
17693 		 * assert that reference.
17694 		 */
17695 		ASSERT(econnp->conn_ref >= 3);
17696 
17697 		/*
17698 		 * Send the new local address also up to sockfs. There
17699 		 * should already be enough space in the mp that came
17700 		 * down from soaccept().
17701 		 */
17702 		if (eager->tcp_family == AF_INET) {
17703 			sin_t *sin;
17704 
17705 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17706 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17707 			sin = (sin_t *)mp->b_wptr;
17708 			mp->b_wptr += sizeof (sin_t);
17709 			sin->sin_family = AF_INET;
17710 			sin->sin_port = eager->tcp_lport;
17711 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17712 		} else {
17713 			sin6_t *sin6;
17714 
17715 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17716 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17717 			sin6 = (sin6_t *)mp->b_wptr;
17718 			mp->b_wptr += sizeof (sin6_t);
17719 			sin6->sin6_family = AF_INET6;
17720 			sin6->sin6_port = eager->tcp_lport;
17721 			if (eager->tcp_ipversion == IPV4_VERSION) {
17722 				sin6->sin6_flowinfo = 0;
17723 				IN6_IPADDR_TO_V4MAPPED(
17724 					eager->tcp_ipha->ipha_src,
17725 					    &sin6->sin6_addr);
17726 			} else {
17727 				ASSERT(eager->tcp_ip6h != NULL);
17728 				sin6->sin6_flowinfo =
17729 				    eager->tcp_ip6h->ip6_vcf &
17730 				    ~IPV6_VERS_AND_FLOW_MASK;
17731 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17732 			}
17733 			sin6->sin6_scope_id = 0;
17734 			sin6->__sin6_src_id = 0;
17735 		}
17736 
17737 		putnext(rq, mp);
17738 
17739 		opt_mp->b_datap->db_type = M_SETOPTS;
17740 		opt_mp->b_wptr += sizeof (struct stroptions);
17741 
17742 		/*
17743 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17744 		 * from listener to acceptor. The message is chained on the
17745 		 * bind_mp which tcp_rput_other will send down to IP.
17746 		 */
17747 		if (listener->tcp_bound_if != 0) {
17748 			/* allocate optmgmt req */
17749 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17750 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17751 			    sizeof (int));
17752 			if (mp != NULL)
17753 				linkb(opt_mp, mp);
17754 		}
17755 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17756 			uint_t on = 1;
17757 
17758 			/* allocate optmgmt req */
17759 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17760 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17761 			if (mp != NULL)
17762 				linkb(opt_mp, mp);
17763 		}
17764 
17765 
17766 		mutex_enter(&listener->tcp_eager_lock);
17767 
17768 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17769 
17770 			tcp_t *tail;
17771 			tcp_t *tcp;
17772 			mblk_t *mp1;
17773 
17774 			tcp = listener->tcp_eager_prev_q0;
17775 			/*
17776 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17777 			 * deferred T_conn_ind queue. We need to get to the head
17778 			 * of the queue in order to send up T_conn_ind the same
17779 			 * order as how the 3WHS is completed.
17780 			 */
17781 			while (tcp != listener) {
17782 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17783 				    !tcp->tcp_kssl_pending)
17784 					break;
17785 				else
17786 					tcp = tcp->tcp_eager_prev_q0;
17787 			}
17788 			/* None of the pending eagers can be sent up now */
17789 			if (tcp == listener)
17790 				goto no_more_eagers;
17791 
17792 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17793 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17794 			/* Move from q0 to q */
17795 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17796 			listener->tcp_conn_req_cnt_q0--;
17797 			listener->tcp_conn_req_cnt_q++;
17798 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17799 			    tcp->tcp_eager_prev_q0;
17800 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17801 			    tcp->tcp_eager_next_q0;
17802 			tcp->tcp_eager_prev_q0 = NULL;
17803 			tcp->tcp_eager_next_q0 = NULL;
17804 			tcp->tcp_conn_def_q0 = B_FALSE;
17805 
17806 			/*
17807 			 * Insert at end of the queue because sockfs sends
17808 			 * down T_CONN_RES in chronological order. Leaving
17809 			 * the older conn indications at front of the queue
17810 			 * helps reducing search time.
17811 			 */
17812 			tail = listener->tcp_eager_last_q;
17813 			if (tail != NULL) {
17814 				tail->tcp_eager_next_q = tcp;
17815 			} else {
17816 				listener->tcp_eager_next_q = tcp;
17817 			}
17818 			listener->tcp_eager_last_q = tcp;
17819 			tcp->tcp_eager_next_q = NULL;
17820 
17821 			/* Need to get inside the listener perimeter */
17822 			CONN_INC_REF(listener->tcp_connp);
17823 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17824 			    tcp_send_pending, listener->tcp_connp,
17825 			    SQTAG_TCP_SEND_PENDING);
17826 		}
17827 no_more_eagers:
17828 		tcp_eager_unlink(eager);
17829 		mutex_exit(&listener->tcp_eager_lock);
17830 
17831 		/*
17832 		 * At this point, the eager is detached from the listener
17833 		 * but we still have an extra refs on eager (apart from the
17834 		 * usual tcp references). The ref was placed in tcp_rput_data
17835 		 * before sending the conn_ind in tcp_send_conn_ind.
17836 		 * The ref will be dropped in tcp_accept_finish().
17837 		 */
17838 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17839 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17840 		return;
17841 	default:
17842 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17843 		if (mp != NULL)
17844 			putnext(rq, mp);
17845 		return;
17846 	}
17847 }
17848 
17849 void
17850 tcp_wput(queue_t *q, mblk_t *mp)
17851 {
17852 	conn_t	*connp = Q_TO_CONN(q);
17853 	tcp_t	*tcp;
17854 	void (*output_proc)();
17855 	t_scalar_t type;
17856 	uchar_t *rptr;
17857 	struct iocblk	*iocp;
17858 	uint32_t	msize;
17859 
17860 	ASSERT(connp->conn_ref >= 2);
17861 
17862 	switch (DB_TYPE(mp)) {
17863 	case M_DATA:
17864 		tcp = connp->conn_tcp;
17865 		ASSERT(tcp != NULL);
17866 
17867 		msize = msgdsize(mp);
17868 
17869 		mutex_enter(&connp->conn_lock);
17870 		CONN_INC_REF_LOCKED(connp);
17871 
17872 		tcp->tcp_squeue_bytes += msize;
17873 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17874 			mutex_exit(&connp->conn_lock);
17875 			tcp_setqfull(tcp);
17876 		} else
17877 			mutex_exit(&connp->conn_lock);
17878 
17879 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17880 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17881 		return;
17882 	case M_PROTO:
17883 	case M_PCPROTO:
17884 		/*
17885 		 * if it is a snmp message, don't get behind the squeue
17886 		 */
17887 		tcp = connp->conn_tcp;
17888 		rptr = mp->b_rptr;
17889 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17890 			type = ((union T_primitives *)rptr)->type;
17891 		} else {
17892 			if (tcp->tcp_debug) {
17893 				(void) strlog(TCP_MOD_ID, 0, 1,
17894 				    SL_ERROR|SL_TRACE,
17895 				    "tcp_wput_proto, dropping one...");
17896 			}
17897 			freemsg(mp);
17898 			return;
17899 		}
17900 		if (type == T_SVR4_OPTMGMT_REQ) {
17901 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
17902 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17903 			    cr)) {
17904 				/*
17905 				 * This was a SNMP request
17906 				 */
17907 				return;
17908 			} else {
17909 				output_proc = tcp_wput_proto;
17910 			}
17911 		} else {
17912 			output_proc = tcp_wput_proto;
17913 		}
17914 		break;
17915 	case M_IOCTL:
17916 		/*
17917 		 * Most ioctls can be processed right away without going via
17918 		 * squeues - process them right here. Those that do require
17919 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17920 		 * are processed by tcp_wput_ioctl().
17921 		 */
17922 		iocp = (struct iocblk *)mp->b_rptr;
17923 		tcp = connp->conn_tcp;
17924 
17925 		switch (iocp->ioc_cmd) {
17926 		case TCP_IOC_ABORT_CONN:
17927 			tcp_ioctl_abort_conn(q, mp);
17928 			return;
17929 		case TI_GETPEERNAME:
17930 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17931 				iocp->ioc_error = ENOTCONN;
17932 				iocp->ioc_count = 0;
17933 				mp->b_datap->db_type = M_IOCACK;
17934 				qreply(q, mp);
17935 				return;
17936 			}
17937 			/* FALLTHRU */
17938 		case TI_GETMYNAME:
17939 			mi_copyin(q, mp, NULL,
17940 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17941 			return;
17942 		case ND_SET:
17943 			/* nd_getset does the necessary checks */
17944 		case ND_GET:
17945 			if (!nd_getset(q, tcp_g_nd, mp)) {
17946 				CALL_IP_WPUT(connp, q, mp);
17947 				return;
17948 			}
17949 			qreply(q, mp);
17950 			return;
17951 		case TCP_IOC_DEFAULT_Q:
17952 			/*
17953 			 * Wants to be the default wq. Check the credentials
17954 			 * first, the rest is executed via squeue.
17955 			 */
17956 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17957 				iocp->ioc_error = EPERM;
17958 				iocp->ioc_count = 0;
17959 				mp->b_datap->db_type = M_IOCACK;
17960 				qreply(q, mp);
17961 				return;
17962 			}
17963 			output_proc = tcp_wput_ioctl;
17964 			break;
17965 		default:
17966 			output_proc = tcp_wput_ioctl;
17967 			break;
17968 		}
17969 		break;
17970 	default:
17971 		output_proc = tcp_wput_nondata;
17972 		break;
17973 	}
17974 
17975 	CONN_INC_REF(connp);
17976 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17977 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17978 }
17979 
17980 /*
17981  * Initial STREAMS write side put() procedure for sockets. It tries to
17982  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17983  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17984  * are handled by tcp_wput() as usual.
17985  *
17986  * All further messages will also be handled by tcp_wput() because we cannot
17987  * be sure that the above short cut is safe later.
17988  */
17989 static void
17990 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17991 {
17992 	conn_t			*connp = Q_TO_CONN(wq);
17993 	tcp_t			*tcp = connp->conn_tcp;
17994 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17995 
17996 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17997 	wq->q_qinfo = &tcp_winit;
17998 
17999 	ASSERT(IPCL_IS_TCP(connp));
18000 	ASSERT(TCP_IS_SOCKET(tcp));
18001 
18002 	if (DB_TYPE(mp) == M_PCPROTO &&
18003 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18004 	    car->PRIM_type == T_CAPABILITY_REQ) {
18005 		tcp_capability_req(tcp, mp);
18006 		return;
18007 	}
18008 
18009 	tcp_wput(wq, mp);
18010 }
18011 
18012 static boolean_t
18013 tcp_zcopy_check(tcp_t *tcp)
18014 {
18015 	conn_t	*connp = tcp->tcp_connp;
18016 	ire_t	*ire;
18017 	boolean_t	zc_enabled = B_FALSE;
18018 
18019 	if (do_tcpzcopy == 2)
18020 		zc_enabled = B_TRUE;
18021 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18022 	    IPCL_IS_CONNECTED(connp) &&
18023 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18024 	    connp->conn_dontroute == 0 &&
18025 	    !connp->conn_nexthop_set &&
18026 	    connp->conn_xmit_if_ill == NULL &&
18027 	    connp->conn_nofailover_ill == NULL &&
18028 	    do_tcpzcopy == 1) {
18029 		/*
18030 		 * the checks above  closely resemble the fast path checks
18031 		 * in tcp_send_data().
18032 		 */
18033 		mutex_enter(&connp->conn_lock);
18034 		ire = connp->conn_ire_cache;
18035 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18036 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18037 			IRE_REFHOLD(ire);
18038 			if (ire->ire_stq != NULL) {
18039 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18040 
18041 				zc_enabled = ill && (ill->ill_capabilities &
18042 				    ILL_CAPAB_ZEROCOPY) &&
18043 				    (ill->ill_zerocopy_capab->
18044 				    ill_zerocopy_flags != 0);
18045 			}
18046 			IRE_REFRELE(ire);
18047 		}
18048 		mutex_exit(&connp->conn_lock);
18049 	}
18050 	tcp->tcp_snd_zcopy_on = zc_enabled;
18051 	if (!TCP_IS_DETACHED(tcp)) {
18052 		if (zc_enabled) {
18053 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
18054 			TCP_STAT(tcp_zcopy_on);
18055 		} else {
18056 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18057 			TCP_STAT(tcp_zcopy_off);
18058 		}
18059 	}
18060 	return (zc_enabled);
18061 }
18062 
18063 static mblk_t *
18064 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
18065 {
18066 	if (do_tcpzcopy == 2)
18067 		return (bp);
18068 	else if (tcp->tcp_snd_zcopy_on) {
18069 		tcp->tcp_snd_zcopy_on = B_FALSE;
18070 		if (!TCP_IS_DETACHED(tcp)) {
18071 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
18072 			TCP_STAT(tcp_zcopy_disable);
18073 		}
18074 	}
18075 	return (tcp_zcopy_backoff(tcp, bp, 0));
18076 }
18077 
18078 /*
18079  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
18080  * the original desballoca'ed segmapped mblk.
18081  */
18082 static mblk_t *
18083 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
18084 {
18085 	mblk_t *head, *tail, *nbp;
18086 	if (IS_VMLOANED_MBLK(bp)) {
18087 		TCP_STAT(tcp_zcopy_backoff);
18088 		if ((head = copyb(bp)) == NULL) {
18089 			/* fail to backoff; leave it for the next backoff */
18090 			tcp->tcp_xmit_zc_clean = B_FALSE;
18091 			return (bp);
18092 		}
18093 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18094 			if (fix_xmitlist)
18095 				tcp_zcopy_notify(tcp);
18096 			else
18097 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18098 		}
18099 		nbp = bp->b_cont;
18100 		if (fix_xmitlist) {
18101 			head->b_prev = bp->b_prev;
18102 			head->b_next = bp->b_next;
18103 			if (tcp->tcp_xmit_tail == bp)
18104 				tcp->tcp_xmit_tail = head;
18105 		}
18106 		bp->b_next = NULL;
18107 		bp->b_prev = NULL;
18108 		freeb(bp);
18109 	} else {
18110 		head = bp;
18111 		nbp = bp->b_cont;
18112 	}
18113 	tail = head;
18114 	while (nbp) {
18115 		if (IS_VMLOANED_MBLK(nbp)) {
18116 			TCP_STAT(tcp_zcopy_backoff);
18117 			if ((tail->b_cont = copyb(nbp)) == NULL) {
18118 				tcp->tcp_xmit_zc_clean = B_FALSE;
18119 				tail->b_cont = nbp;
18120 				return (head);
18121 			}
18122 			tail = tail->b_cont;
18123 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
18124 				if (fix_xmitlist)
18125 					tcp_zcopy_notify(tcp);
18126 				else
18127 					tail->b_datap->db_struioflag |=
18128 					    STRUIO_ZCNOTIFY;
18129 			}
18130 			bp = nbp;
18131 			nbp = nbp->b_cont;
18132 			if (fix_xmitlist) {
18133 				tail->b_prev = bp->b_prev;
18134 				tail->b_next = bp->b_next;
18135 				if (tcp->tcp_xmit_tail == bp)
18136 					tcp->tcp_xmit_tail = tail;
18137 			}
18138 			bp->b_next = NULL;
18139 			bp->b_prev = NULL;
18140 			freeb(bp);
18141 		} else {
18142 			tail->b_cont = nbp;
18143 			tail = nbp;
18144 			nbp = nbp->b_cont;
18145 		}
18146 	}
18147 	if (fix_xmitlist) {
18148 		tcp->tcp_xmit_last = tail;
18149 		tcp->tcp_xmit_zc_clean = B_TRUE;
18150 	}
18151 	return (head);
18152 }
18153 
18154 static void
18155 tcp_zcopy_notify(tcp_t *tcp)
18156 {
18157 	struct stdata	*stp;
18158 
18159 	if (tcp->tcp_detached)
18160 		return;
18161 	stp = STREAM(tcp->tcp_rq);
18162 	mutex_enter(&stp->sd_lock);
18163 	stp->sd_flag |= STZCNOTIFY;
18164 	cv_broadcast(&stp->sd_zcopy_wait);
18165 	mutex_exit(&stp->sd_lock);
18166 }
18167 
18168 static void
18169 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
18170 {
18171 	ipha_t		*ipha;
18172 	ipaddr_t	src;
18173 	ipaddr_t	dst;
18174 	uint32_t	cksum;
18175 	ire_t		*ire;
18176 	uint16_t	*up;
18177 	ill_t		*ill;
18178 	conn_t		*connp = tcp->tcp_connp;
18179 	uint32_t	hcksum_txflags = 0;
18180 	mblk_t		*ire_fp_mp;
18181 	uint_t		ire_fp_mp_len;
18182 
18183 	ASSERT(DB_TYPE(mp) == M_DATA);
18184 
18185 	if (DB_CRED(mp) == NULL)
18186 		mblk_setcred(mp, CONN_CRED(connp));
18187 
18188 	ipha = (ipha_t *)mp->b_rptr;
18189 	src = ipha->ipha_src;
18190 	dst = ipha->ipha_dst;
18191 
18192 	/*
18193 	 * Drop off fast path for IPv6 and also if options are present or
18194 	 * we need to resolve a TS label.
18195 	 */
18196 	if (tcp->tcp_ipversion != IPV4_VERSION ||
18197 	    !IPCL_IS_CONNECTED(connp) ||
18198 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
18199 	    connp->conn_dontroute ||
18200 	    connp->conn_nexthop_set ||
18201 	    connp->conn_xmit_if_ill != NULL ||
18202 	    connp->conn_nofailover_ill != NULL ||
18203 	    !connp->conn_ulp_labeled ||
18204 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
18205 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
18206 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
18207 		if (tcp->tcp_snd_zcopy_aware)
18208 			mp = tcp_zcopy_disable(tcp, mp);
18209 		TCP_STAT(tcp_ip_send);
18210 		CALL_IP_WPUT(connp, q, mp);
18211 		return;
18212 	}
18213 
18214 	mutex_enter(&connp->conn_lock);
18215 	ire = connp->conn_ire_cache;
18216 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18217 	if (ire != NULL && ire->ire_addr == dst &&
18218 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18219 		IRE_REFHOLD(ire);
18220 		mutex_exit(&connp->conn_lock);
18221 	} else {
18222 		boolean_t cached = B_FALSE;
18223 
18224 		/* force a recheck later on */
18225 		tcp->tcp_ire_ill_check_done = B_FALSE;
18226 
18227 		TCP_DBGSTAT(tcp_ire_null1);
18228 		connp->conn_ire_cache = NULL;
18229 		mutex_exit(&connp->conn_lock);
18230 		if (ire != NULL)
18231 			IRE_REFRELE_NOTR(ire);
18232 		ire = ire_cache_lookup(dst, connp->conn_zoneid,
18233 		    MBLK_GETLABEL(mp));
18234 		if (ire == NULL) {
18235 			if (tcp->tcp_snd_zcopy_aware)
18236 				mp = tcp_zcopy_backoff(tcp, mp, 0);
18237 			TCP_STAT(tcp_ire_null);
18238 			CALL_IP_WPUT(connp, q, mp);
18239 			return;
18240 		}
18241 		IRE_REFHOLD_NOTR(ire);
18242 		/*
18243 		 * Since we are inside the squeue, there cannot be another
18244 		 * thread in TCP trying to set the conn_ire_cache now.  The
18245 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18246 		 * unplumb thread has not yet started cleaning up the conns.
18247 		 * Hence we don't need to grab the conn lock.
18248 		 */
18249 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18250 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18251 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18252 				connp->conn_ire_cache = ire;
18253 				cached = B_TRUE;
18254 			}
18255 			rw_exit(&ire->ire_bucket->irb_lock);
18256 		}
18257 
18258 		/*
18259 		 * We can continue to use the ire but since it was
18260 		 * not cached, we should drop the extra reference.
18261 		 */
18262 		if (!cached)
18263 			IRE_REFRELE_NOTR(ire);
18264 
18265 		/*
18266 		 * Rampart note: no need to select a new label here, since
18267 		 * labels are not allowed to change during the life of a TCP
18268 		 * connection.
18269 		 */
18270 	}
18271 
18272 	if (ire->ire_flags & RTF_MULTIRT ||
18273 	    ire->ire_stq == NULL ||
18274 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18275 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18276 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18277 		if (tcp->tcp_snd_zcopy_aware)
18278 			mp = tcp_zcopy_disable(tcp, mp);
18279 		TCP_STAT(tcp_ip_ire_send);
18280 		IRE_REFRELE(ire);
18281 		CALL_IP_WPUT(connp, q, mp);
18282 		return;
18283 	}
18284 
18285 	ill = ire_to_ill(ire);
18286 	if (connp->conn_outgoing_ill != NULL) {
18287 		ill_t *conn_outgoing_ill = NULL;
18288 		/*
18289 		 * Choose a good ill in the group to send the packets on.
18290 		 */
18291 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18292 		ill = ire_to_ill(ire);
18293 	}
18294 	ASSERT(ill != NULL);
18295 
18296 	if (!tcp->tcp_ire_ill_check_done) {
18297 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18298 		tcp->tcp_ire_ill_check_done = B_TRUE;
18299 	}
18300 
18301 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18302 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18303 #ifndef _BIG_ENDIAN
18304 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18305 #endif
18306 
18307 	/*
18308 	 * Check to see if we need to re-enable MDT for this connection
18309 	 * because it was previously disabled due to changes in the ill;
18310 	 * note that by doing it here, this re-enabling only applies when
18311 	 * the packet is not dispatched through CALL_IP_WPUT().
18312 	 *
18313 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18314 	 * case, since that's how we ended up here.  For IPv6, we do the
18315 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18316 	 */
18317 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18318 		/*
18319 		 * Restore MDT for this connection, so that next time around
18320 		 * it is eligible to go through tcp_multisend() path again.
18321 		 */
18322 		TCP_STAT(tcp_mdt_conn_resumed1);
18323 		tcp->tcp_mdt = B_TRUE;
18324 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18325 		    "interface %s\n", (void *)connp, ill->ill_name));
18326 	}
18327 
18328 	if (tcp->tcp_snd_zcopy_aware) {
18329 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18330 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18331 			mp = tcp_zcopy_disable(tcp, mp);
18332 		/*
18333 		 * we shouldn't need to reset ipha as the mp containing
18334 		 * ipha should never be a zero-copy mp.
18335 		 */
18336 	}
18337 
18338 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18339 		ASSERT(ill->ill_hcksum_capab != NULL);
18340 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18341 	}
18342 
18343 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18344 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18345 
18346 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18347 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18348 
18349 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18350 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18351 
18352 	/* Software checksum? */
18353 	if (DB_CKSUMFLAGS(mp) == 0) {
18354 		TCP_STAT(tcp_out_sw_cksum);
18355 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18356 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18357 	}
18358 
18359 	ipha->ipha_fragment_offset_and_flags |=
18360 	    (uint32_t)htons(ire->ire_frag_flag);
18361 
18362 	/* Calculate IP header checksum if hardware isn't capable */
18363 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18364 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18365 		    ((uint16_t *)ipha)[4]);
18366 	}
18367 
18368 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18369 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18370 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18371 
18372 	UPDATE_OB_PKT_COUNT(ire);
18373 	ire->ire_last_used_time = lbolt;
18374 	BUMP_MIB(&ip_mib, ipOutRequests);
18375 
18376 	if (ILL_DLS_CAPABLE(ill)) {
18377 		/*
18378 		 * Send the packet directly to DLD, where it may be queued
18379 		 * depending on the availability of transmit resources at
18380 		 * the media layer.
18381 		 */
18382 		IP_DLS_ILL_TX(ill, mp);
18383 	} else {
18384 		putnext(ire->ire_stq, mp);
18385 	}
18386 	IRE_REFRELE(ire);
18387 }
18388 
18389 /*
18390  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18391  * if the receiver shrinks the window, i.e. moves the right window to the
18392  * left, the we should not send new data, but should retransmit normally the
18393  * old unacked data between suna and suna + swnd. We might has sent data
18394  * that is now outside the new window, pretend that we didn't send  it.
18395  */
18396 static void
18397 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18398 {
18399 	uint32_t	snxt = tcp->tcp_snxt;
18400 	mblk_t		*xmit_tail;
18401 	int32_t		offset;
18402 
18403 	ASSERT(shrunk_count > 0);
18404 
18405 	/* Pretend we didn't send the data outside the window */
18406 	snxt -= shrunk_count;
18407 
18408 	/* Get the mblk and the offset in it per the shrunk window */
18409 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18410 
18411 	ASSERT(xmit_tail != NULL);
18412 
18413 	/* Reset all the values per the now shrunk window */
18414 	tcp->tcp_snxt = snxt;
18415 	tcp->tcp_xmit_tail = xmit_tail;
18416 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18417 	    offset;
18418 	tcp->tcp_unsent += shrunk_count;
18419 
18420 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18421 		/*
18422 		 * Make sure the timer is running so that we will probe a zero
18423 		 * window.
18424 		 */
18425 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18426 }
18427 
18428 
18429 /*
18430  * The TCP normal data output path.
18431  * NOTE: the logic of the fast path is duplicated from this function.
18432  */
18433 static void
18434 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18435 {
18436 	int		len;
18437 	mblk_t		*local_time;
18438 	mblk_t		*mp1;
18439 	uint32_t	snxt;
18440 	int		tail_unsent;
18441 	int		tcpstate;
18442 	int		usable = 0;
18443 	mblk_t		*xmit_tail;
18444 	queue_t		*q = tcp->tcp_wq;
18445 	int32_t		mss;
18446 	int32_t		num_sack_blk = 0;
18447 	int32_t		tcp_hdr_len;
18448 	int32_t		tcp_tcp_hdr_len;
18449 	int		mdt_thres;
18450 	int		rc;
18451 
18452 	tcpstate = tcp->tcp_state;
18453 	if (mp == NULL) {
18454 		/*
18455 		 * tcp_wput_data() with NULL mp should only be called when
18456 		 * there is unsent data.
18457 		 */
18458 		ASSERT(tcp->tcp_unsent > 0);
18459 		/* Really tacky... but we need this for detached closes. */
18460 		len = tcp->tcp_unsent;
18461 		goto data_null;
18462 	}
18463 
18464 #if CCS_STATS
18465 	wrw_stats.tot.count++;
18466 	wrw_stats.tot.bytes += msgdsize(mp);
18467 #endif
18468 	ASSERT(mp->b_datap->db_type == M_DATA);
18469 	/*
18470 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18471 	 * or before a connection attempt has begun.
18472 	 */
18473 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18474 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18475 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18476 #ifdef DEBUG
18477 			cmn_err(CE_WARN,
18478 			    "tcp_wput_data: data after ordrel, %s",
18479 			    tcp_display(tcp, NULL,
18480 			    DISP_ADDR_AND_PORT));
18481 #else
18482 			if (tcp->tcp_debug) {
18483 				(void) strlog(TCP_MOD_ID, 0, 1,
18484 				    SL_TRACE|SL_ERROR,
18485 				    "tcp_wput_data: data after ordrel, %s\n",
18486 				    tcp_display(tcp, NULL,
18487 				    DISP_ADDR_AND_PORT));
18488 			}
18489 #endif /* DEBUG */
18490 		}
18491 		if (tcp->tcp_snd_zcopy_aware &&
18492 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18493 			tcp_zcopy_notify(tcp);
18494 		freemsg(mp);
18495 		if (tcp->tcp_flow_stopped &&
18496 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18497 			tcp_clrqfull(tcp);
18498 		}
18499 		return;
18500 	}
18501 
18502 	/* Strip empties */
18503 	for (;;) {
18504 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18505 		    (uintptr_t)INT_MAX);
18506 		len = (int)(mp->b_wptr - mp->b_rptr);
18507 		if (len > 0)
18508 			break;
18509 		mp1 = mp;
18510 		mp = mp->b_cont;
18511 		freeb(mp1);
18512 		if (!mp) {
18513 			return;
18514 		}
18515 	}
18516 
18517 	/* If we are the first on the list ... */
18518 	if (tcp->tcp_xmit_head == NULL) {
18519 		tcp->tcp_xmit_head = mp;
18520 		tcp->tcp_xmit_tail = mp;
18521 		tcp->tcp_xmit_tail_unsent = len;
18522 	} else {
18523 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18524 		struct datab *dp;
18525 
18526 		mp1 = tcp->tcp_xmit_last;
18527 		if (len < tcp_tx_pull_len &&
18528 		    (dp = mp1->b_datap)->db_ref == 1 &&
18529 		    dp->db_lim - mp1->b_wptr >= len) {
18530 			ASSERT(len > 0);
18531 			ASSERT(!mp1->b_cont);
18532 			if (len == 1) {
18533 				*mp1->b_wptr++ = *mp->b_rptr;
18534 			} else {
18535 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18536 				mp1->b_wptr += len;
18537 			}
18538 			if (mp1 == tcp->tcp_xmit_tail)
18539 				tcp->tcp_xmit_tail_unsent += len;
18540 			mp1->b_cont = mp->b_cont;
18541 			if (tcp->tcp_snd_zcopy_aware &&
18542 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18543 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18544 			freeb(mp);
18545 			mp = mp1;
18546 		} else {
18547 			tcp->tcp_xmit_last->b_cont = mp;
18548 		}
18549 		len += tcp->tcp_unsent;
18550 	}
18551 
18552 	/* Tack on however many more positive length mblks we have */
18553 	if ((mp1 = mp->b_cont) != NULL) {
18554 		do {
18555 			int tlen;
18556 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18557 			    (uintptr_t)INT_MAX);
18558 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18559 			if (tlen <= 0) {
18560 				mp->b_cont = mp1->b_cont;
18561 				freeb(mp1);
18562 			} else {
18563 				len += tlen;
18564 				mp = mp1;
18565 			}
18566 		} while ((mp1 = mp->b_cont) != NULL);
18567 	}
18568 	tcp->tcp_xmit_last = mp;
18569 	tcp->tcp_unsent = len;
18570 
18571 	if (urgent)
18572 		usable = 1;
18573 
18574 data_null:
18575 	snxt = tcp->tcp_snxt;
18576 	xmit_tail = tcp->tcp_xmit_tail;
18577 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18578 
18579 	/*
18580 	 * Note that tcp_mss has been adjusted to take into account the
18581 	 * timestamp option if applicable.  Because SACK options do not
18582 	 * appear in every TCP segments and they are of variable lengths,
18583 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18584 	 * the actual segment length when we need to send a segment which
18585 	 * includes SACK options.
18586 	 */
18587 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18588 		int32_t	opt_len;
18589 
18590 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18591 		    tcp->tcp_num_sack_blk);
18592 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18593 		    2 + TCPOPT_HEADER_LEN;
18594 		mss = tcp->tcp_mss - opt_len;
18595 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18596 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18597 	} else {
18598 		mss = tcp->tcp_mss;
18599 		tcp_hdr_len = tcp->tcp_hdr_len;
18600 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18601 	}
18602 
18603 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18604 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18605 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18606 	}
18607 	if (tcpstate == TCPS_SYN_RCVD) {
18608 		/*
18609 		 * The three-way connection establishment handshake is not
18610 		 * complete yet. We want to queue the data for transmission
18611 		 * after entering ESTABLISHED state (RFC793). A jump to
18612 		 * "done" label effectively leaves data on the queue.
18613 		 */
18614 		goto done;
18615 	} else {
18616 		int usable_r = tcp->tcp_swnd;
18617 
18618 		/*
18619 		 * In the special case when cwnd is zero, which can only
18620 		 * happen if the connection is ECN capable, return now.
18621 		 * New segments is sent using tcp_timer().  The timer
18622 		 * is set in tcp_rput_data().
18623 		 */
18624 		if (tcp->tcp_cwnd == 0) {
18625 			/*
18626 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18627 			 * finished.
18628 			 */
18629 			ASSERT(tcp->tcp_ecn_ok ||
18630 			    tcp->tcp_state < TCPS_ESTABLISHED);
18631 			return;
18632 		}
18633 
18634 		/* NOTE: trouble if xmitting while SYN not acked? */
18635 		usable_r -= snxt;
18636 		usable_r += tcp->tcp_suna;
18637 
18638 		/*
18639 		 * Check if the receiver has shrunk the window.  If
18640 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18641 		 * cannot be set as there is unsent data, so FIN cannot
18642 		 * be sent out.  Otherwise, we need to take into account
18643 		 * of FIN as it consumes an "invisible" sequence number.
18644 		 */
18645 		ASSERT(tcp->tcp_fin_sent == 0);
18646 		if (usable_r < 0) {
18647 			/*
18648 			 * The receiver has shrunk the window and we have sent
18649 			 * -usable_r date beyond the window, re-adjust.
18650 			 *
18651 			 * If TCP window scaling is enabled, there can be
18652 			 * round down error as the advertised receive window
18653 			 * is actually right shifted n bits.  This means that
18654 			 * the lower n bits info is wiped out.  It will look
18655 			 * like the window is shrunk.  Do a check here to
18656 			 * see if the shrunk amount is actually within the
18657 			 * error in window calculation.  If it is, just
18658 			 * return.  Note that this check is inside the
18659 			 * shrunk window check.  This makes sure that even
18660 			 * though tcp_process_shrunk_swnd() is not called,
18661 			 * we will stop further processing.
18662 			 */
18663 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18664 				tcp_process_shrunk_swnd(tcp, -usable_r);
18665 			}
18666 			return;
18667 		}
18668 
18669 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18670 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18671 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18672 
18673 		/* usable = MIN(usable, unsent) */
18674 		if (usable_r > len)
18675 			usable_r = len;
18676 
18677 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18678 		if (usable_r > 0) {
18679 			usable = usable_r;
18680 		} else {
18681 			/* Bypass all other unnecessary processing. */
18682 			goto done;
18683 		}
18684 	}
18685 
18686 	local_time = (mblk_t *)lbolt;
18687 
18688 	/*
18689 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18690 	 * BSD.  This is more in line with the true intent of Nagle.
18691 	 *
18692 	 * The conditions are:
18693 	 * 1. The amount of unsent data (or amount of data which can be
18694 	 *    sent, whichever is smaller) is less than Nagle limit.
18695 	 * 2. The last sent size is also less than Nagle limit.
18696 	 * 3. There is unack'ed data.
18697 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18698 	 *    Nagle algorithm.  This reduces the probability that urgent
18699 	 *    bytes get "merged" together.
18700 	 * 5. The app has not closed the connection.  This eliminates the
18701 	 *    wait time of the receiving side waiting for the last piece of
18702 	 *    (small) data.
18703 	 *
18704 	 * If all are satisified, exit without sending anything.  Note
18705 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18706 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18707 	 * 4095).
18708 	 */
18709 	if (usable < (int)tcp->tcp_naglim &&
18710 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18711 	    snxt != tcp->tcp_suna &&
18712 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18713 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18714 		goto done;
18715 	}
18716 
18717 	if (tcp->tcp_cork) {
18718 		/*
18719 		 * if the tcp->tcp_cork option is set, then we have to force
18720 		 * TCP not to send partial segment (smaller than MSS bytes).
18721 		 * We are calculating the usable now based on full mss and
18722 		 * will save the rest of remaining data for later.
18723 		 */
18724 		if (usable < mss)
18725 			goto done;
18726 		usable = (usable / mss) * mss;
18727 	}
18728 
18729 	/* Update the latest receive window size in TCP header. */
18730 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18731 	    tcp->tcp_tcph->th_win);
18732 
18733 	/*
18734 	 * Determine if it's worthwhile to attempt MDT, based on:
18735 	 *
18736 	 * 1. Simple TCP/IP{v4,v6} (no options).
18737 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18738 	 * 3. If the TCP connection is in ESTABLISHED state.
18739 	 * 4. The TCP is not detached.
18740 	 *
18741 	 * If any of the above conditions have changed during the
18742 	 * connection, stop using MDT and restore the stream head
18743 	 * parameters accordingly.
18744 	 */
18745 	if (tcp->tcp_mdt &&
18746 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18747 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18748 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18749 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18750 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18751 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18752 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18753 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18754 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18755 		tcp->tcp_mdt = B_FALSE;
18756 
18757 		/* Anything other than detached is considered pathological */
18758 		if (!TCP_IS_DETACHED(tcp)) {
18759 			TCP_STAT(tcp_mdt_conn_halted1);
18760 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18761 		}
18762 	}
18763 
18764 	/* Use MDT if sendable amount is greater than the threshold */
18765 	if (tcp->tcp_mdt &&
18766 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18767 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18768 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18769 	    (tcp->tcp_valid_bits == 0 ||
18770 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18771 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18772 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18773 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18774 		    local_time, mdt_thres);
18775 	} else {
18776 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18777 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18778 		    local_time, INT_MAX);
18779 	}
18780 
18781 	/* Pretend that all we were trying to send really got sent */
18782 	if (rc < 0 && tail_unsent < 0) {
18783 		do {
18784 			xmit_tail = xmit_tail->b_cont;
18785 			xmit_tail->b_prev = local_time;
18786 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18787 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18788 			tail_unsent += (int)(xmit_tail->b_wptr -
18789 			    xmit_tail->b_rptr);
18790 		} while (tail_unsent < 0);
18791 	}
18792 done:;
18793 	tcp->tcp_xmit_tail = xmit_tail;
18794 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18795 	len = tcp->tcp_snxt - snxt;
18796 	if (len) {
18797 		/*
18798 		 * If new data was sent, need to update the notsack
18799 		 * list, which is, afterall, data blocks that have
18800 		 * not been sack'ed by the receiver.  New data is
18801 		 * not sack'ed.
18802 		 */
18803 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18804 			/* len is a negative value. */
18805 			tcp->tcp_pipe -= len;
18806 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18807 			    tcp->tcp_snxt, snxt,
18808 			    &(tcp->tcp_num_notsack_blk),
18809 			    &(tcp->tcp_cnt_notsack_list));
18810 		}
18811 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18812 		tcp->tcp_rack = tcp->tcp_rnxt;
18813 		tcp->tcp_rack_cnt = 0;
18814 		if ((snxt + len) == tcp->tcp_suna) {
18815 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18816 		}
18817 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18818 		/*
18819 		 * Didn't send anything. Make sure the timer is running
18820 		 * so that we will probe a zero window.
18821 		 */
18822 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18823 	}
18824 	/* Note that len is the amount we just sent but with a negative sign */
18825 	tcp->tcp_unsent += len;
18826 	if (tcp->tcp_flow_stopped) {
18827 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18828 			tcp_clrqfull(tcp);
18829 		}
18830 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18831 		tcp_setqfull(tcp);
18832 	}
18833 }
18834 
18835 /*
18836  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18837  * outgoing TCP header with the template header, as well as other
18838  * options such as time-stamp, ECN and/or SACK.
18839  */
18840 static void
18841 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18842 {
18843 	tcph_t *tcp_tmpl, *tcp_h;
18844 	uint32_t *dst, *src;
18845 	int hdrlen;
18846 
18847 	ASSERT(OK_32PTR(rptr));
18848 
18849 	/* Template header */
18850 	tcp_tmpl = tcp->tcp_tcph;
18851 
18852 	/* Header of outgoing packet */
18853 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18854 
18855 	/* dst and src are opaque 32-bit fields, used for copying */
18856 	dst = (uint32_t *)rptr;
18857 	src = (uint32_t *)tcp->tcp_iphc;
18858 	hdrlen = tcp->tcp_hdr_len;
18859 
18860 	/* Fill time-stamp option if needed */
18861 	if (tcp->tcp_snd_ts_ok) {
18862 		U32_TO_BE32((uint32_t)now,
18863 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18864 		U32_TO_BE32(tcp->tcp_ts_recent,
18865 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18866 	} else {
18867 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18868 	}
18869 
18870 	/*
18871 	 * Copy the template header; is this really more efficient than
18872 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18873 	 * but perhaps not for other scenarios.
18874 	 */
18875 	dst[0] = src[0];
18876 	dst[1] = src[1];
18877 	dst[2] = src[2];
18878 	dst[3] = src[3];
18879 	dst[4] = src[4];
18880 	dst[5] = src[5];
18881 	dst[6] = src[6];
18882 	dst[7] = src[7];
18883 	dst[8] = src[8];
18884 	dst[9] = src[9];
18885 	if (hdrlen -= 40) {
18886 		hdrlen >>= 2;
18887 		dst += 10;
18888 		src += 10;
18889 		do {
18890 			*dst++ = *src++;
18891 		} while (--hdrlen);
18892 	}
18893 
18894 	/*
18895 	 * Set the ECN info in the TCP header if it is not a zero
18896 	 * window probe.  Zero window probe is only sent in
18897 	 * tcp_wput_data() and tcp_timer().
18898 	 */
18899 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18900 		SET_ECT(tcp, rptr);
18901 
18902 		if (tcp->tcp_ecn_echo_on)
18903 			tcp_h->th_flags[0] |= TH_ECE;
18904 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18905 			tcp_h->th_flags[0] |= TH_CWR;
18906 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18907 		}
18908 	}
18909 
18910 	/* Fill in SACK options */
18911 	if (num_sack_blk > 0) {
18912 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18913 		sack_blk_t *tmp;
18914 		int32_t	i;
18915 
18916 		wptr[0] = TCPOPT_NOP;
18917 		wptr[1] = TCPOPT_NOP;
18918 		wptr[2] = TCPOPT_SACK;
18919 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18920 		    sizeof (sack_blk_t);
18921 		wptr += TCPOPT_REAL_SACK_LEN;
18922 
18923 		tmp = tcp->tcp_sack_list;
18924 		for (i = 0; i < num_sack_blk; i++) {
18925 			U32_TO_BE32(tmp[i].begin, wptr);
18926 			wptr += sizeof (tcp_seq);
18927 			U32_TO_BE32(tmp[i].end, wptr);
18928 			wptr += sizeof (tcp_seq);
18929 		}
18930 		tcp_h->th_offset_and_rsrvd[0] +=
18931 		    ((num_sack_blk * 2 + 1) << 4);
18932 	}
18933 }
18934 
18935 /*
18936  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18937  * the destination address and SAP attribute, and if necessary, the
18938  * hardware checksum offload attribute to a Multidata message.
18939  */
18940 static int
18941 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18942     const uint32_t start, const uint32_t stuff, const uint32_t end,
18943     const uint32_t flags)
18944 {
18945 	/* Add global destination address & SAP attribute */
18946 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18947 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18948 		    "destination address+SAP\n"));
18949 
18950 		if (dlmp != NULL)
18951 			TCP_STAT(tcp_mdt_allocfail);
18952 		return (-1);
18953 	}
18954 
18955 	/* Add global hwcksum attribute */
18956 	if (hwcksum &&
18957 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18958 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18959 		    "checksum attribute\n"));
18960 
18961 		TCP_STAT(tcp_mdt_allocfail);
18962 		return (-1);
18963 	}
18964 
18965 	return (0);
18966 }
18967 
18968 /*
18969  * Smaller and private version of pdescinfo_t used specifically for TCP,
18970  * which allows for only two payload spans per packet.
18971  */
18972 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18973 
18974 /*
18975  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18976  * scheme, and returns one the following:
18977  *
18978  * -1 = failed allocation.
18979  *  0 = success; burst count reached, or usable send window is too small,
18980  *      and that we'd rather wait until later before sending again.
18981  */
18982 static int
18983 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18984     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18985     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18986     const int mdt_thres)
18987 {
18988 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18989 	multidata_t	*mmd;
18990 	uint_t		obsegs, obbytes, hdr_frag_sz;
18991 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18992 	int		num_burst_seg, max_pld;
18993 	pdesc_t		*pkt;
18994 	tcp_pdescinfo_t	tcp_pkt_info;
18995 	pdescinfo_t	*pkt_info;
18996 	int		pbuf_idx, pbuf_idx_nxt;
18997 	int		seg_len, len, spill, af;
18998 	boolean_t	add_buffer, zcopy, clusterwide;
18999 	boolean_t	rconfirm = B_FALSE;
19000 	boolean_t	done = B_FALSE;
19001 	uint32_t	cksum;
19002 	uint32_t	hwcksum_flags;
19003 	ire_t		*ire;
19004 	ill_t		*ill;
19005 	ipha_t		*ipha;
19006 	ip6_t		*ip6h;
19007 	ipaddr_t	src, dst;
19008 	ill_zerocopy_capab_t *zc_cap = NULL;
19009 	uint16_t	*up;
19010 	int		err;
19011 	conn_t		*connp;
19012 
19013 #ifdef	_BIG_ENDIAN
19014 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
19015 #else
19016 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
19017 #endif
19018 
19019 #define	PREP_NEW_MULTIDATA() {			\
19020 	mmd = NULL;				\
19021 	md_mp = md_hbuf = NULL;			\
19022 	cur_hdr_off = 0;			\
19023 	max_pld = tcp->tcp_mdt_max_pld;		\
19024 	pbuf_idx = pbuf_idx_nxt = -1;		\
19025 	add_buffer = B_TRUE;			\
19026 	zcopy = B_FALSE;			\
19027 }
19028 
19029 #define	PREP_NEW_PBUF() {			\
19030 	md_pbuf = md_pbuf_nxt = NULL;		\
19031 	pbuf_idx = pbuf_idx_nxt = -1;		\
19032 	cur_pld_off = 0;			\
19033 	first_snxt = *snxt;			\
19034 	ASSERT(*tail_unsent > 0);		\
19035 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
19036 }
19037 
19038 	ASSERT(mdt_thres >= mss);
19039 	ASSERT(*usable > 0 && *usable > mdt_thres);
19040 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
19041 	ASSERT(!TCP_IS_DETACHED(tcp));
19042 	ASSERT(tcp->tcp_valid_bits == 0 ||
19043 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
19044 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
19045 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
19046 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19047 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
19048 
19049 	connp = tcp->tcp_connp;
19050 	ASSERT(connp != NULL);
19051 	ASSERT(CONN_IS_MD_FASTPATH(connp));
19052 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
19053 
19054 	/*
19055 	 * Note that tcp will only declare at most 2 payload spans per
19056 	 * packet, which is much lower than the maximum allowable number
19057 	 * of packet spans per Multidata.  For this reason, we use the
19058 	 * privately declared and smaller descriptor info structure, in
19059 	 * order to save some stack space.
19060 	 */
19061 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
19062 
19063 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
19064 	if (af == AF_INET) {
19065 		dst = tcp->tcp_ipha->ipha_dst;
19066 		src = tcp->tcp_ipha->ipha_src;
19067 		ASSERT(!CLASSD(dst));
19068 	}
19069 	ASSERT(af == AF_INET ||
19070 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
19071 
19072 	obsegs = obbytes = 0;
19073 	num_burst_seg = tcp->tcp_snd_burst;
19074 	md_mp_head = NULL;
19075 	PREP_NEW_MULTIDATA();
19076 
19077 	/*
19078 	 * Before we go on further, make sure there is an IRE that we can
19079 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
19080 	 * in proceeding any further, and we should just hand everything
19081 	 * off to the legacy path.
19082 	 */
19083 	mutex_enter(&connp->conn_lock);
19084 	ire = connp->conn_ire_cache;
19085 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19086 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
19087 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
19088 	    &tcp->tcp_ip6h->ip6_dst))) &&
19089 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19090 		IRE_REFHOLD(ire);
19091 		mutex_exit(&connp->conn_lock);
19092 	} else {
19093 		boolean_t cached = B_FALSE;
19094 		ts_label_t *tsl;
19095 
19096 		/* force a recheck later on */
19097 		tcp->tcp_ire_ill_check_done = B_FALSE;
19098 
19099 		TCP_DBGSTAT(tcp_ire_null1);
19100 		connp->conn_ire_cache = NULL;
19101 		mutex_exit(&connp->conn_lock);
19102 
19103 		/* Release the old ire */
19104 		if (ire != NULL)
19105 			IRE_REFRELE_NOTR(ire);
19106 
19107 		tsl = crgetlabel(CONN_CRED(connp));
19108 		ire = (af == AF_INET) ?
19109 		    ire_cache_lookup(dst, connp->conn_zoneid, tsl) :
19110 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19111 		    connp->conn_zoneid, tsl);
19112 
19113 		if (ire == NULL) {
19114 			TCP_STAT(tcp_ire_null);
19115 			goto legacy_send_no_md;
19116 		}
19117 
19118 		IRE_REFHOLD_NOTR(ire);
19119 		/*
19120 		 * Since we are inside the squeue, there cannot be another
19121 		 * thread in TCP trying to set the conn_ire_cache now. The
19122 		 * check for IRE_MARK_CONDEMNED ensures that an interface
19123 		 * unplumb thread has not yet started cleaning up the conns.
19124 		 * Hence we don't need to grab the conn lock.
19125 		 */
19126 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
19127 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19128 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19129 				connp->conn_ire_cache = ire;
19130 				cached = B_TRUE;
19131 			}
19132 			rw_exit(&ire->ire_bucket->irb_lock);
19133 		}
19134 
19135 		/*
19136 		 * We can continue to use the ire but since it was not
19137 		 * cached, we should drop the extra reference.
19138 		 */
19139 		if (!cached)
19140 			IRE_REFRELE_NOTR(ire);
19141 	}
19142 
19143 	ASSERT(ire != NULL);
19144 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
19145 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
19146 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
19147 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19148 	/*
19149 	 * If we do support loopback for MDT (which requires modifications
19150 	 * to the receiving paths), the following assertions should go away,
19151 	 * and we would be sending the Multidata to loopback conn later on.
19152 	 */
19153 	ASSERT(!IRE_IS_LOCAL(ire));
19154 	ASSERT(ire->ire_stq != NULL);
19155 
19156 	ill = ire_to_ill(ire);
19157 	ASSERT(ill != NULL);
19158 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
19159 
19160 	if (!tcp->tcp_ire_ill_check_done) {
19161 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19162 		tcp->tcp_ire_ill_check_done = B_TRUE;
19163 	}
19164 
19165 	/*
19166 	 * If the underlying interface conditions have changed, or if the
19167 	 * new interface does not support MDT, go back to legacy path.
19168 	 */
19169 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
19170 		/* don't go through this path anymore for this connection */
19171 		TCP_STAT(tcp_mdt_conn_halted2);
19172 		tcp->tcp_mdt = B_FALSE;
19173 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
19174 		    "interface %s\n", (void *)connp, ill->ill_name));
19175 		/* IRE will be released prior to returning */
19176 		goto legacy_send_no_md;
19177 	}
19178 
19179 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
19180 		zc_cap = ill->ill_zerocopy_capab;
19181 
19182 	/* go to legacy path if interface doesn't support zerocopy */
19183 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
19184 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
19185 		/* IRE will be released prior to returning */
19186 		goto legacy_send_no_md;
19187 	}
19188 
19189 	/* does the interface support hardware checksum offload? */
19190 	hwcksum_flags = 0;
19191 	if (ILL_HCKSUM_CAPABLE(ill) &&
19192 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
19193 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
19194 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
19195 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19196 		    HCKSUM_IPHDRCKSUM)
19197 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
19198 
19199 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19200 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
19201 			hwcksum_flags |= HCK_FULLCKSUM;
19202 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
19203 		    HCKSUM_INET_PARTIAL)
19204 			hwcksum_flags |= HCK_PARTIALCKSUM;
19205 	}
19206 
19207 	/*
19208 	 * Each header fragment consists of the leading extra space,
19209 	 * followed by the TCP/IP header, and the trailing extra space.
19210 	 * We make sure that each header fragment begins on a 32-bit
19211 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
19212 	 * aligned in tcp_mdt_update).
19213 	 */
19214 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
19215 	    tcp->tcp_mdt_hdr_tail), 4);
19216 
19217 	/* are we starting from the beginning of data block? */
19218 	if (*tail_unsent == 0) {
19219 		*xmit_tail = (*xmit_tail)->b_cont;
19220 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
19221 		*tail_unsent = (int)MBLKL(*xmit_tail);
19222 	}
19223 
19224 	/*
19225 	 * Here we create one or more Multidata messages, each made up of
19226 	 * one header buffer and up to N payload buffers.  This entire
19227 	 * operation is done within two loops:
19228 	 *
19229 	 * The outer loop mostly deals with creating the Multidata message,
19230 	 * as well as the header buffer that gets added to it.  It also
19231 	 * links the Multidata messages together such that all of them can
19232 	 * be sent down to the lower layer in a single putnext call; this
19233 	 * linking behavior depends on the tcp_mdt_chain tunable.
19234 	 *
19235 	 * The inner loop takes an existing Multidata message, and adds
19236 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
19237 	 * packetizes those buffers by filling up the corresponding header
19238 	 * buffer fragments with the proper IP and TCP headers, and by
19239 	 * describing the layout of each packet in the packet descriptors
19240 	 * that get added to the Multidata.
19241 	 */
19242 	do {
19243 		/*
19244 		 * If usable send window is too small, or data blocks in
19245 		 * transmit list are smaller than our threshold (i.e. app
19246 		 * performs large writes followed by small ones), we hand
19247 		 * off the control over to the legacy path.  Note that we'll
19248 		 * get back the control once it encounters a large block.
19249 		 */
19250 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
19251 		    (*xmit_tail)->b_cont != NULL &&
19252 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19253 			/* send down what we've got so far */
19254 			if (md_mp_head != NULL) {
19255 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19256 				    obsegs, obbytes, &rconfirm);
19257 			}
19258 			/*
19259 			 * Pass control over to tcp_send(), but tell it to
19260 			 * return to us once a large-size transmission is
19261 			 * possible.
19262 			 */
19263 			TCP_STAT(tcp_mdt_legacy_small);
19264 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19265 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19266 			    tail_unsent, xmit_tail, local_time,
19267 			    mdt_thres)) <= 0) {
19268 				/* burst count reached, or alloc failed */
19269 				IRE_REFRELE(ire);
19270 				return (err);
19271 			}
19272 
19273 			/* tcp_send() may have sent everything, so check */
19274 			if (*usable <= 0) {
19275 				IRE_REFRELE(ire);
19276 				return (0);
19277 			}
19278 
19279 			TCP_STAT(tcp_mdt_legacy_ret);
19280 			/*
19281 			 * We may have delivered the Multidata, so make sure
19282 			 * to re-initialize before the next round.
19283 			 */
19284 			md_mp_head = NULL;
19285 			obsegs = obbytes = 0;
19286 			num_burst_seg = tcp->tcp_snd_burst;
19287 			PREP_NEW_MULTIDATA();
19288 
19289 			/* are we starting from the beginning of data block? */
19290 			if (*tail_unsent == 0) {
19291 				*xmit_tail = (*xmit_tail)->b_cont;
19292 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19293 				    (uintptr_t)INT_MAX);
19294 				*tail_unsent = (int)MBLKL(*xmit_tail);
19295 			}
19296 		}
19297 
19298 		/*
19299 		 * max_pld limits the number of mblks in tcp's transmit
19300 		 * queue that can be added to a Multidata message.  Once
19301 		 * this counter reaches zero, no more additional mblks
19302 		 * can be added to it.  What happens afterwards depends
19303 		 * on whether or not we are set to chain the Multidata
19304 		 * messages.  If we are to link them together, reset
19305 		 * max_pld to its original value (tcp_mdt_max_pld) and
19306 		 * prepare to create a new Multidata message which will
19307 		 * get linked to md_mp_head.  Else, leave it alone and
19308 		 * let the inner loop break on its own.
19309 		 */
19310 		if (tcp_mdt_chain && max_pld == 0)
19311 			PREP_NEW_MULTIDATA();
19312 
19313 		/* adding a payload buffer; re-initialize values */
19314 		if (add_buffer)
19315 			PREP_NEW_PBUF();
19316 
19317 		/*
19318 		 * If we don't have a Multidata, either because we just
19319 		 * (re)entered this outer loop, or after we branched off
19320 		 * to tcp_send above, setup the Multidata and header
19321 		 * buffer to be used.
19322 		 */
19323 		if (md_mp == NULL) {
19324 			int md_hbuflen;
19325 			uint32_t start, stuff;
19326 
19327 			/*
19328 			 * Calculate Multidata header buffer size large enough
19329 			 * to hold all of the headers that can possibly be
19330 			 * sent at this moment.  We'd rather over-estimate
19331 			 * the size than running out of space; this is okay
19332 			 * since this buffer is small anyway.
19333 			 */
19334 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19335 
19336 			/*
19337 			 * Start and stuff offset for partial hardware
19338 			 * checksum offload; these are currently for IPv4.
19339 			 * For full checksum offload, they are set to zero.
19340 			 */
19341 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19342 				if (af == AF_INET) {
19343 					start = IP_SIMPLE_HDR_LENGTH;
19344 					stuff = IP_SIMPLE_HDR_LENGTH +
19345 					    TCP_CHECKSUM_OFFSET;
19346 				} else {
19347 					start = IPV6_HDR_LEN;
19348 					stuff = IPV6_HDR_LEN +
19349 					    TCP_CHECKSUM_OFFSET;
19350 				}
19351 			} else {
19352 				start = stuff = 0;
19353 			}
19354 
19355 			/*
19356 			 * Create the header buffer, Multidata, as well as
19357 			 * any necessary attributes (destination address,
19358 			 * SAP and hardware checksum offload) that should
19359 			 * be associated with the Multidata message.
19360 			 */
19361 			ASSERT(cur_hdr_off == 0);
19362 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19363 			    ((md_hbuf->b_wptr += md_hbuflen),
19364 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19365 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19366 			    /* fastpath mblk */
19367 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19368 			    ire->ire_nce->nce_res_mp,
19369 			    /* hardware checksum enabled */
19370 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19371 			    /* hardware checksum offsets */
19372 			    start, stuff, 0,
19373 			    /* hardware checksum flag */
19374 			    hwcksum_flags) != 0)) {
19375 legacy_send:
19376 				if (md_mp != NULL) {
19377 					/* Unlink message from the chain */
19378 					if (md_mp_head != NULL) {
19379 						err = (intptr_t)rmvb(md_mp_head,
19380 						    md_mp);
19381 						/*
19382 						 * We can't assert that rmvb
19383 						 * did not return -1, since we
19384 						 * may get here before linkb
19385 						 * happens.  We do, however,
19386 						 * check if we just removed the
19387 						 * only element in the list.
19388 						 */
19389 						if (err == 0)
19390 							md_mp_head = NULL;
19391 					}
19392 					/* md_hbuf gets freed automatically */
19393 					TCP_STAT(tcp_mdt_discarded);
19394 					freeb(md_mp);
19395 				} else {
19396 					/* Either allocb or mmd_alloc failed */
19397 					TCP_STAT(tcp_mdt_allocfail);
19398 					if (md_hbuf != NULL)
19399 						freeb(md_hbuf);
19400 				}
19401 
19402 				/* send down what we've got so far */
19403 				if (md_mp_head != NULL) {
19404 					tcp_multisend_data(tcp, ire, ill,
19405 					    md_mp_head, obsegs, obbytes,
19406 					    &rconfirm);
19407 				}
19408 legacy_send_no_md:
19409 				if (ire != NULL)
19410 					IRE_REFRELE(ire);
19411 				/*
19412 				 * Too bad; let the legacy path handle this.
19413 				 * We specify INT_MAX for the threshold, since
19414 				 * we gave up with the Multidata processings
19415 				 * and let the old path have it all.
19416 				 */
19417 				TCP_STAT(tcp_mdt_legacy_all);
19418 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19419 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19420 				    snxt, tail_unsent, xmit_tail, local_time,
19421 				    INT_MAX));
19422 			}
19423 
19424 			/* link to any existing ones, if applicable */
19425 			TCP_STAT(tcp_mdt_allocd);
19426 			if (md_mp_head == NULL) {
19427 				md_mp_head = md_mp;
19428 			} else if (tcp_mdt_chain) {
19429 				TCP_STAT(tcp_mdt_linked);
19430 				linkb(md_mp_head, md_mp);
19431 			}
19432 		}
19433 
19434 		ASSERT(md_mp_head != NULL);
19435 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19436 		ASSERT(md_mp != NULL && mmd != NULL);
19437 		ASSERT(md_hbuf != NULL);
19438 
19439 		/*
19440 		 * Packetize the transmittable portion of the data block;
19441 		 * each data block is essentially added to the Multidata
19442 		 * as a payload buffer.  We also deal with adding more
19443 		 * than one payload buffers, which happens when the remaining
19444 		 * packetized portion of the current payload buffer is less
19445 		 * than MSS, while the next data block in transmit queue
19446 		 * has enough data to make up for one.  This "spillover"
19447 		 * case essentially creates a split-packet, where portions
19448 		 * of the packet's payload fragments may span across two
19449 		 * virtually discontiguous address blocks.
19450 		 */
19451 		seg_len = mss;
19452 		do {
19453 			len = seg_len;
19454 
19455 			ASSERT(len > 0);
19456 			ASSERT(max_pld >= 0);
19457 			ASSERT(!add_buffer || cur_pld_off == 0);
19458 
19459 			/*
19460 			 * First time around for this payload buffer; note
19461 			 * in the case of a spillover, the following has
19462 			 * been done prior to adding the split-packet
19463 			 * descriptor to Multidata, and we don't want to
19464 			 * repeat the process.
19465 			 */
19466 			if (add_buffer) {
19467 				ASSERT(mmd != NULL);
19468 				ASSERT(md_pbuf == NULL);
19469 				ASSERT(md_pbuf_nxt == NULL);
19470 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19471 
19472 				/*
19473 				 * Have we reached the limit?  We'd get to
19474 				 * this case when we're not chaining the
19475 				 * Multidata messages together, and since
19476 				 * we're done, terminate this loop.
19477 				 */
19478 				if (max_pld == 0)
19479 					break; /* done */
19480 
19481 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19482 					TCP_STAT(tcp_mdt_allocfail);
19483 					goto legacy_send; /* out_of_mem */
19484 				}
19485 
19486 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19487 				    zc_cap != NULL) {
19488 					if (!ip_md_zcopy_attr(mmd, NULL,
19489 					    zc_cap->ill_zerocopy_flags)) {
19490 						freeb(md_pbuf);
19491 						TCP_STAT(tcp_mdt_allocfail);
19492 						/* out_of_mem */
19493 						goto legacy_send;
19494 					}
19495 					zcopy = B_TRUE;
19496 				}
19497 
19498 				md_pbuf->b_rptr += base_pld_off;
19499 
19500 				/*
19501 				 * Add a payload buffer to the Multidata; this
19502 				 * operation must not fail, or otherwise our
19503 				 * logic in this routine is broken.  There
19504 				 * is no memory allocation done by the
19505 				 * routine, so any returned failure simply
19506 				 * tells us that we've done something wrong.
19507 				 *
19508 				 * A failure tells us that either we're adding
19509 				 * the same payload buffer more than once, or
19510 				 * we're trying to add more buffers than
19511 				 * allowed (max_pld calculation is wrong).
19512 				 * None of the above cases should happen, and
19513 				 * we panic because either there's horrible
19514 				 * heap corruption, and/or programming mistake.
19515 				 */
19516 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19517 				if (pbuf_idx < 0) {
19518 					cmn_err(CE_PANIC, "tcp_multisend: "
19519 					    "payload buffer logic error "
19520 					    "detected for tcp %p mmd %p "
19521 					    "pbuf %p (%d)\n",
19522 					    (void *)tcp, (void *)mmd,
19523 					    (void *)md_pbuf, pbuf_idx);
19524 				}
19525 
19526 				ASSERT(max_pld > 0);
19527 				--max_pld;
19528 				add_buffer = B_FALSE;
19529 			}
19530 
19531 			ASSERT(md_mp_head != NULL);
19532 			ASSERT(md_pbuf != NULL);
19533 			ASSERT(md_pbuf_nxt == NULL);
19534 			ASSERT(pbuf_idx != -1);
19535 			ASSERT(pbuf_idx_nxt == -1);
19536 			ASSERT(*usable > 0);
19537 
19538 			/*
19539 			 * We spillover to the next payload buffer only
19540 			 * if all of the following is true:
19541 			 *
19542 			 *   1. There is not enough data on the current
19543 			 *	payload buffer to make up `len',
19544 			 *   2. We are allowed to send `len',
19545 			 *   3. The next payload buffer length is large
19546 			 *	enough to accomodate `spill'.
19547 			 */
19548 			if ((spill = len - *tail_unsent) > 0 &&
19549 			    *usable >= len &&
19550 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19551 			    max_pld > 0) {
19552 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19553 				if (md_pbuf_nxt == NULL) {
19554 					TCP_STAT(tcp_mdt_allocfail);
19555 					goto legacy_send; /* out_of_mem */
19556 				}
19557 
19558 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19559 				    zc_cap != NULL) {
19560 					if (!ip_md_zcopy_attr(mmd, NULL,
19561 					    zc_cap->ill_zerocopy_flags)) {
19562 						freeb(md_pbuf_nxt);
19563 						TCP_STAT(tcp_mdt_allocfail);
19564 						/* out_of_mem */
19565 						goto legacy_send;
19566 					}
19567 					zcopy = B_TRUE;
19568 				}
19569 
19570 				/*
19571 				 * See comments above on the first call to
19572 				 * mmd_addpldbuf for explanation on the panic.
19573 				 */
19574 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19575 				if (pbuf_idx_nxt < 0) {
19576 					panic("tcp_multisend: "
19577 					    "next payload buffer logic error "
19578 					    "detected for tcp %p mmd %p "
19579 					    "pbuf %p (%d)\n",
19580 					    (void *)tcp, (void *)mmd,
19581 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19582 				}
19583 
19584 				ASSERT(max_pld > 0);
19585 				--max_pld;
19586 			} else if (spill > 0) {
19587 				/*
19588 				 * If there's a spillover, but the following
19589 				 * xmit_tail couldn't give us enough octets
19590 				 * to reach "len", then stop the current
19591 				 * Multidata creation and let the legacy
19592 				 * tcp_send() path take over.  We don't want
19593 				 * to send the tiny segment as part of this
19594 				 * Multidata for performance reasons; instead,
19595 				 * we let the legacy path deal with grouping
19596 				 * it with the subsequent small mblks.
19597 				 */
19598 				if (*usable >= len &&
19599 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19600 					max_pld = 0;
19601 					break;	/* done */
19602 				}
19603 
19604 				/*
19605 				 * We can't spillover, and we are near
19606 				 * the end of the current payload buffer,
19607 				 * so send what's left.
19608 				 */
19609 				ASSERT(*tail_unsent > 0);
19610 				len = *tail_unsent;
19611 			}
19612 
19613 			/* tail_unsent is negated if there is a spillover */
19614 			*tail_unsent -= len;
19615 			*usable -= len;
19616 			ASSERT(*usable >= 0);
19617 
19618 			if (*usable < mss)
19619 				seg_len = *usable;
19620 			/*
19621 			 * Sender SWS avoidance; see comments in tcp_send();
19622 			 * everything else is the same, except that we only
19623 			 * do this here if there is no more data to be sent
19624 			 * following the current xmit_tail.  We don't check
19625 			 * for 1-byte urgent data because we shouldn't get
19626 			 * here if TCP_URG_VALID is set.
19627 			 */
19628 			if (*usable > 0 && *usable < mss &&
19629 			    ((md_pbuf_nxt == NULL &&
19630 			    (*xmit_tail)->b_cont == NULL) ||
19631 			    (md_pbuf_nxt != NULL &&
19632 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19633 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19634 			    (tcp->tcp_unsent -
19635 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19636 			    !tcp->tcp_zero_win_probe) {
19637 				if ((*snxt + len) == tcp->tcp_snxt &&
19638 				    (*snxt + len) == tcp->tcp_suna) {
19639 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19640 				}
19641 				done = B_TRUE;
19642 			}
19643 
19644 			/*
19645 			 * Prime pump for IP's checksumming on our behalf;
19646 			 * include the adjustment for a source route if any.
19647 			 * Do this only for software/partial hardware checksum
19648 			 * offload, as this field gets zeroed out later for
19649 			 * the full hardware checksum offload case.
19650 			 */
19651 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19652 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19653 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19654 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19655 			}
19656 
19657 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19658 			*snxt += len;
19659 
19660 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19661 			/*
19662 			 * We set the PUSH bit only if TCP has no more buffered
19663 			 * data to be transmitted (or if sender SWS avoidance
19664 			 * takes place), as opposed to setting it for every
19665 			 * last packet in the burst.
19666 			 */
19667 			if (done ||
19668 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19669 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19670 
19671 			/*
19672 			 * Set FIN bit if this is our last segment; snxt
19673 			 * already includes its length, and it will not
19674 			 * be adjusted after this point.
19675 			 */
19676 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19677 			    *snxt == tcp->tcp_fss) {
19678 				if (!tcp->tcp_fin_acked) {
19679 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19680 					BUMP_MIB(&tcp_mib, tcpOutControl);
19681 				}
19682 				if (!tcp->tcp_fin_sent) {
19683 					tcp->tcp_fin_sent = B_TRUE;
19684 					/*
19685 					 * tcp state must be ESTABLISHED
19686 					 * in order for us to get here in
19687 					 * the first place.
19688 					 */
19689 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19690 
19691 					/*
19692 					 * Upon returning from this routine,
19693 					 * tcp_wput_data() will set tcp_snxt
19694 					 * to be equal to snxt + tcp_fin_sent.
19695 					 * This is essentially the same as
19696 					 * setting it to tcp_fss + 1.
19697 					 */
19698 				}
19699 			}
19700 
19701 			tcp->tcp_last_sent_len = (ushort_t)len;
19702 
19703 			len += tcp_hdr_len;
19704 			if (tcp->tcp_ipversion == IPV4_VERSION)
19705 				tcp->tcp_ipha->ipha_length = htons(len);
19706 			else
19707 				tcp->tcp_ip6h->ip6_plen = htons(len -
19708 				    ((char *)&tcp->tcp_ip6h[1] -
19709 				    tcp->tcp_iphc));
19710 
19711 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19712 
19713 			/* setup header fragment */
19714 			PDESC_HDR_ADD(pkt_info,
19715 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19716 			    tcp->tcp_mdt_hdr_head,		/* head room */
19717 			    tcp_hdr_len,			/* len */
19718 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19719 
19720 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19721 			    hdr_frag_sz);
19722 			ASSERT(MBLKIN(md_hbuf,
19723 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19724 			    PDESC_HDRSIZE(pkt_info)));
19725 
19726 			/* setup first payload fragment */
19727 			PDESC_PLD_INIT(pkt_info);
19728 			PDESC_PLD_SPAN_ADD(pkt_info,
19729 			    pbuf_idx,				/* index */
19730 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19731 			    tcp->tcp_last_sent_len);		/* len */
19732 
19733 			/* create a split-packet in case of a spillover */
19734 			if (md_pbuf_nxt != NULL) {
19735 				ASSERT(spill > 0);
19736 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19737 				ASSERT(!add_buffer);
19738 
19739 				md_pbuf = md_pbuf_nxt;
19740 				md_pbuf_nxt = NULL;
19741 				pbuf_idx = pbuf_idx_nxt;
19742 				pbuf_idx_nxt = -1;
19743 				cur_pld_off = spill;
19744 
19745 				/* trim out first payload fragment */
19746 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19747 
19748 				/* setup second payload fragment */
19749 				PDESC_PLD_SPAN_ADD(pkt_info,
19750 				    pbuf_idx,			/* index */
19751 				    md_pbuf->b_rptr,		/* start */
19752 				    spill);			/* len */
19753 
19754 				if ((*xmit_tail)->b_next == NULL) {
19755 					/*
19756 					 * Store the lbolt used for RTT
19757 					 * estimation. We can only record one
19758 					 * timestamp per mblk so we do it when
19759 					 * we reach the end of the payload
19760 					 * buffer.  Also we only take a new
19761 					 * timestamp sample when the previous
19762 					 * timed data from the same mblk has
19763 					 * been ack'ed.
19764 					 */
19765 					(*xmit_tail)->b_prev = local_time;
19766 					(*xmit_tail)->b_next =
19767 					    (mblk_t *)(uintptr_t)first_snxt;
19768 				}
19769 
19770 				first_snxt = *snxt - spill;
19771 
19772 				/*
19773 				 * Advance xmit_tail; usable could be 0 by
19774 				 * the time we got here, but we made sure
19775 				 * above that we would only spillover to
19776 				 * the next data block if usable includes
19777 				 * the spilled-over amount prior to the
19778 				 * subtraction.  Therefore, we are sure
19779 				 * that xmit_tail->b_cont can't be NULL.
19780 				 */
19781 				ASSERT((*xmit_tail)->b_cont != NULL);
19782 				*xmit_tail = (*xmit_tail)->b_cont;
19783 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19784 				    (uintptr_t)INT_MAX);
19785 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19786 			} else {
19787 				cur_pld_off += tcp->tcp_last_sent_len;
19788 			}
19789 
19790 			/*
19791 			 * Fill in the header using the template header, and
19792 			 * add options such as time-stamp, ECN and/or SACK,
19793 			 * as needed.
19794 			 */
19795 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19796 			    (clock_t)local_time, num_sack_blk);
19797 
19798 			/* take care of some IP header businesses */
19799 			if (af == AF_INET) {
19800 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19801 
19802 				ASSERT(OK_32PTR((uchar_t *)ipha));
19803 				ASSERT(PDESC_HDRL(pkt_info) >=
19804 				    IP_SIMPLE_HDR_LENGTH);
19805 				ASSERT(ipha->ipha_version_and_hdr_length ==
19806 				    IP_SIMPLE_HDR_VERSION);
19807 
19808 				/*
19809 				 * Assign ident value for current packet; see
19810 				 * related comments in ip_wput_ire() about the
19811 				 * contract private interface with clustering
19812 				 * group.
19813 				 */
19814 				clusterwide = B_FALSE;
19815 				if (cl_inet_ipident != NULL) {
19816 					ASSERT(cl_inet_isclusterwide != NULL);
19817 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19818 					    AF_INET,
19819 					    (uint8_t *)(uintptr_t)src)) {
19820 						ipha->ipha_ident =
19821 						    (*cl_inet_ipident)
19822 						    (IPPROTO_IP, AF_INET,
19823 						    (uint8_t *)(uintptr_t)src,
19824 						    (uint8_t *)(uintptr_t)dst);
19825 						clusterwide = B_TRUE;
19826 					}
19827 				}
19828 
19829 				if (!clusterwide) {
19830 					ipha->ipha_ident = (uint16_t)
19831 					    atomic_add_32_nv(
19832 						&ire->ire_ident, 1);
19833 				}
19834 #ifndef _BIG_ENDIAN
19835 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19836 				    (ipha->ipha_ident >> 8);
19837 #endif
19838 			} else {
19839 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19840 
19841 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19842 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19843 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19844 				ASSERT(PDESC_HDRL(pkt_info) >=
19845 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19846 				    TCP_CHECKSUM_SIZE));
19847 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19848 
19849 				if (tcp->tcp_ip_forward_progress) {
19850 					rconfirm = B_TRUE;
19851 					tcp->tcp_ip_forward_progress = B_FALSE;
19852 				}
19853 			}
19854 
19855 			/* at least one payload span, and at most two */
19856 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19857 
19858 			/* add the packet descriptor to Multidata */
19859 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19860 			    KM_NOSLEEP)) == NULL) {
19861 				/*
19862 				 * Any failure other than ENOMEM indicates
19863 				 * that we have passed in invalid pkt_info
19864 				 * or parameters to mmd_addpdesc, which must
19865 				 * not happen.
19866 				 *
19867 				 * EINVAL is a result of failure on boundary
19868 				 * checks against the pkt_info contents.  It
19869 				 * should not happen, and we panic because
19870 				 * either there's horrible heap corruption,
19871 				 * and/or programming mistake.
19872 				 */
19873 				if (err != ENOMEM) {
19874 					cmn_err(CE_PANIC, "tcp_multisend: "
19875 					    "pdesc logic error detected for "
19876 					    "tcp %p mmd %p pinfo %p (%d)\n",
19877 					    (void *)tcp, (void *)mmd,
19878 					    (void *)pkt_info, err);
19879 				}
19880 				TCP_STAT(tcp_mdt_addpdescfail);
19881 				goto legacy_send; /* out_of_mem */
19882 			}
19883 			ASSERT(pkt != NULL);
19884 
19885 			/* calculate IP header and TCP checksums */
19886 			if (af == AF_INET) {
19887 				/* calculate pseudo-header checksum */
19888 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19889 				    (src >> 16) + (src & 0xFFFF);
19890 
19891 				/* offset for TCP header checksum */
19892 				up = IPH_TCPH_CHECKSUMP(ipha,
19893 				    IP_SIMPLE_HDR_LENGTH);
19894 			} else {
19895 				up = (uint16_t *)&ip6h->ip6_src;
19896 
19897 				/* calculate pseudo-header checksum */
19898 				cksum = up[0] + up[1] + up[2] + up[3] +
19899 				    up[4] + up[5] + up[6] + up[7] +
19900 				    up[8] + up[9] + up[10] + up[11] +
19901 				    up[12] + up[13] + up[14] + up[15];
19902 
19903 				/* Fold the initial sum */
19904 				cksum = (cksum & 0xffff) + (cksum >> 16);
19905 
19906 				up = (uint16_t *)(((uchar_t *)ip6h) +
19907 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19908 			}
19909 
19910 			if (hwcksum_flags & HCK_FULLCKSUM) {
19911 				/* clear checksum field for hardware */
19912 				*up = 0;
19913 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19914 				uint32_t sum;
19915 
19916 				/* pseudo-header checksumming */
19917 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19918 				sum = (sum & 0xFFFF) + (sum >> 16);
19919 				*up = (sum & 0xFFFF) + (sum >> 16);
19920 			} else {
19921 				/* software checksumming */
19922 				TCP_STAT(tcp_out_sw_cksum);
19923 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19924 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19925 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19926 				    cksum + IP_TCP_CSUM_COMP);
19927 				if (*up == 0)
19928 					*up = 0xFFFF;
19929 			}
19930 
19931 			/* IPv4 header checksum */
19932 			if (af == AF_INET) {
19933 				ipha->ipha_fragment_offset_and_flags |=
19934 				    (uint32_t)htons(ire->ire_frag_flag);
19935 
19936 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19937 					ipha->ipha_hdr_checksum = 0;
19938 				} else {
19939 					IP_HDR_CKSUM(ipha, cksum,
19940 					    ((uint32_t *)ipha)[0],
19941 					    ((uint16_t *)ipha)[4]);
19942 				}
19943 			}
19944 
19945 			/* advance header offset */
19946 			cur_hdr_off += hdr_frag_sz;
19947 
19948 			obbytes += tcp->tcp_last_sent_len;
19949 			++obsegs;
19950 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19951 		    *tail_unsent > 0);
19952 
19953 		if ((*xmit_tail)->b_next == NULL) {
19954 			/*
19955 			 * Store the lbolt used for RTT estimation. We can only
19956 			 * record one timestamp per mblk so we do it when we
19957 			 * reach the end of the payload buffer. Also we only
19958 			 * take a new timestamp sample when the previous timed
19959 			 * data from the same mblk has been ack'ed.
19960 			 */
19961 			(*xmit_tail)->b_prev = local_time;
19962 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19963 		}
19964 
19965 		ASSERT(*tail_unsent >= 0);
19966 		if (*tail_unsent > 0) {
19967 			/*
19968 			 * We got here because we broke out of the above
19969 			 * loop due to of one of the following cases:
19970 			 *
19971 			 *   1. len < adjusted MSS (i.e. small),
19972 			 *   2. Sender SWS avoidance,
19973 			 *   3. max_pld is zero.
19974 			 *
19975 			 * We are done for this Multidata, so trim our
19976 			 * last payload buffer (if any) accordingly.
19977 			 */
19978 			if (md_pbuf != NULL)
19979 				md_pbuf->b_wptr -= *tail_unsent;
19980 		} else if (*usable > 0) {
19981 			*xmit_tail = (*xmit_tail)->b_cont;
19982 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19983 			    (uintptr_t)INT_MAX);
19984 			*tail_unsent = (int)MBLKL(*xmit_tail);
19985 			add_buffer = B_TRUE;
19986 		}
19987 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19988 	    (tcp_mdt_chain || max_pld > 0));
19989 
19990 	/* send everything down */
19991 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19992 	    &rconfirm);
19993 
19994 #undef PREP_NEW_MULTIDATA
19995 #undef PREP_NEW_PBUF
19996 #undef IPVER
19997 
19998 	IRE_REFRELE(ire);
19999 	return (0);
20000 }
20001 
20002 /*
20003  * A wrapper function for sending one or more Multidata messages down to
20004  * the module below ip; this routine does not release the reference of the
20005  * IRE (caller does that).  This routine is analogous to tcp_send_data().
20006  */
20007 static void
20008 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
20009     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
20010 {
20011 	uint64_t delta;
20012 	nce_t *nce;
20013 
20014 	ASSERT(ire != NULL && ill != NULL);
20015 	ASSERT(ire->ire_stq != NULL);
20016 	ASSERT(md_mp_head != NULL);
20017 	ASSERT(rconfirm != NULL);
20018 
20019 	/* adjust MIBs and IRE timestamp */
20020 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
20021 	tcp->tcp_obsegs += obsegs;
20022 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
20023 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
20024 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
20025 
20026 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20027 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
20028 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
20029 	} else {
20030 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
20031 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
20032 	}
20033 
20034 	ire->ire_ob_pkt_count += obsegs;
20035 	if (ire->ire_ipif != NULL)
20036 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
20037 	ire->ire_last_used_time = lbolt;
20038 
20039 	/* send it down */
20040 	putnext(ire->ire_stq, md_mp_head);
20041 
20042 	/* we're done for TCP/IPv4 */
20043 	if (tcp->tcp_ipversion == IPV4_VERSION)
20044 		return;
20045 
20046 	nce = ire->ire_nce;
20047 
20048 	ASSERT(nce != NULL);
20049 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
20050 	ASSERT(nce->nce_state != ND_INCOMPLETE);
20051 
20052 	/* reachability confirmation? */
20053 	if (*rconfirm) {
20054 		nce->nce_last = TICK_TO_MSEC(lbolt64);
20055 		if (nce->nce_state != ND_REACHABLE) {
20056 			mutex_enter(&nce->nce_lock);
20057 			nce->nce_state = ND_REACHABLE;
20058 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
20059 			mutex_exit(&nce->nce_lock);
20060 			(void) untimeout(nce->nce_timeout_id);
20061 			if (ip_debug > 2) {
20062 				/* ip1dbg */
20063 				pr_addr_dbg("tcp_multisend_data: state "
20064 				    "for %s changed to REACHABLE\n",
20065 				    AF_INET6, &ire->ire_addr_v6);
20066 			}
20067 		}
20068 		/* reset transport reachability confirmation */
20069 		*rconfirm = B_FALSE;
20070 	}
20071 
20072 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
20073 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
20074 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
20075 
20076 	if (delta > (uint64_t)ill->ill_reachable_time) {
20077 		mutex_enter(&nce->nce_lock);
20078 		switch (nce->nce_state) {
20079 		case ND_REACHABLE:
20080 		case ND_STALE:
20081 			/*
20082 			 * ND_REACHABLE is identical to ND_STALE in this
20083 			 * specific case. If reachable time has expired for
20084 			 * this neighbor (delta is greater than reachable
20085 			 * time), conceptually, the neighbor cache is no
20086 			 * longer in REACHABLE state, but already in STALE
20087 			 * state.  So the correct transition here is to
20088 			 * ND_DELAY.
20089 			 */
20090 			nce->nce_state = ND_DELAY;
20091 			mutex_exit(&nce->nce_lock);
20092 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
20093 			if (ip_debug > 3) {
20094 				/* ip2dbg */
20095 				pr_addr_dbg("tcp_multisend_data: state "
20096 				    "for %s changed to DELAY\n",
20097 				    AF_INET6, &ire->ire_addr_v6);
20098 			}
20099 			break;
20100 		case ND_DELAY:
20101 		case ND_PROBE:
20102 			mutex_exit(&nce->nce_lock);
20103 			/* Timers have already started */
20104 			break;
20105 		case ND_UNREACHABLE:
20106 			/*
20107 			 * ndp timer has detected that this nce is
20108 			 * unreachable and initiated deleting this nce
20109 			 * and all its associated IREs. This is a race
20110 			 * where we found the ire before it was deleted
20111 			 * and have just sent out a packet using this
20112 			 * unreachable nce.
20113 			 */
20114 			mutex_exit(&nce->nce_lock);
20115 			break;
20116 		default:
20117 			ASSERT(0);
20118 		}
20119 	}
20120 }
20121 
20122 /*
20123  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
20124  * scheme, and returns one of the following:
20125  *
20126  * -1 = failed allocation.
20127  *  0 = success; burst count reached, or usable send window is too small,
20128  *      and that we'd rather wait until later before sending again.
20129  *  1 = success; we are called from tcp_multisend(), and both usable send
20130  *      window and tail_unsent are greater than the MDT threshold, and thus
20131  *      Multidata Transmit should be used instead.
20132  */
20133 static int
20134 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20135     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20136     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20137     const int mdt_thres)
20138 {
20139 	int num_burst_seg = tcp->tcp_snd_burst;
20140 
20141 	for (;;) {
20142 		struct datab	*db;
20143 		tcph_t		*tcph;
20144 		uint32_t	sum;
20145 		mblk_t		*mp, *mp1;
20146 		uchar_t		*rptr;
20147 		int		len;
20148 
20149 		/*
20150 		 * If we're called by tcp_multisend(), and the amount of
20151 		 * sendable data as well as the size of current xmit_tail
20152 		 * is beyond the MDT threshold, return to the caller and
20153 		 * let the large data transmit be done using MDT.
20154 		 */
20155 		if (*usable > 0 && *usable > mdt_thres &&
20156 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
20157 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
20158 			ASSERT(tcp->tcp_mdt);
20159 			return (1);	/* success; do large send */
20160 		}
20161 
20162 		if (num_burst_seg-- == 0)
20163 			break;		/* success; burst count reached */
20164 
20165 		len = mss;
20166 		if (len > *usable) {
20167 			len = *usable;
20168 			if (len <= 0) {
20169 				/* Terminate the loop */
20170 				break;	/* success; too small */
20171 			}
20172 			/*
20173 			 * Sender silly-window avoidance.
20174 			 * Ignore this if we are going to send a
20175 			 * zero window probe out.
20176 			 *
20177 			 * TODO: force data into microscopic window?
20178 			 *	==> (!pushed || (unsent > usable))
20179 			 */
20180 			if (len < (tcp->tcp_max_swnd >> 1) &&
20181 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
20182 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
20183 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
20184 				/*
20185 				 * If the retransmit timer is not running
20186 				 * we start it so that we will retransmit
20187 				 * in the case when the the receiver has
20188 				 * decremented the window.
20189 				 */
20190 				if (*snxt == tcp->tcp_snxt &&
20191 				    *snxt == tcp->tcp_suna) {
20192 					/*
20193 					 * We are not supposed to send
20194 					 * anything.  So let's wait a little
20195 					 * bit longer before breaking SWS
20196 					 * avoidance.
20197 					 *
20198 					 * What should the value be?
20199 					 * Suggestion: MAX(init rexmit time,
20200 					 * tcp->tcp_rto)
20201 					 */
20202 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20203 				}
20204 				break;	/* success; too small */
20205 			}
20206 		}
20207 
20208 		tcph = tcp->tcp_tcph;
20209 
20210 		*usable -= len; /* Approximate - can be adjusted later */
20211 		if (*usable > 0)
20212 			tcph->th_flags[0] = TH_ACK;
20213 		else
20214 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
20215 
20216 		/*
20217 		 * Prime pump for IP's checksumming on our behalf
20218 		 * Include the adjustment for a source route if any.
20219 		 */
20220 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20221 		sum = (sum >> 16) + (sum & 0xFFFF);
20222 		U16_TO_ABE16(sum, tcph->th_sum);
20223 
20224 		U32_TO_ABE32(*snxt, tcph->th_seq);
20225 
20226 		/*
20227 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
20228 		 * set.  For the case when TCP_FSS_VALID is the only valid
20229 		 * bit (normal active close), branch off only when we think
20230 		 * that the FIN flag needs to be set.  Note for this case,
20231 		 * that (snxt + len) may not reflect the actual seg_len,
20232 		 * as len may be further reduced in tcp_xmit_mp().  If len
20233 		 * gets modified, we will end up here again.
20234 		 */
20235 		if (tcp->tcp_valid_bits != 0 &&
20236 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
20237 		    ((*snxt + len) == tcp->tcp_fss))) {
20238 			uchar_t		*prev_rptr;
20239 			uint32_t	prev_snxt = tcp->tcp_snxt;
20240 
20241 			if (*tail_unsent == 0) {
20242 				ASSERT((*xmit_tail)->b_cont != NULL);
20243 				*xmit_tail = (*xmit_tail)->b_cont;
20244 				prev_rptr = (*xmit_tail)->b_rptr;
20245 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
20246 				    (*xmit_tail)->b_rptr);
20247 			} else {
20248 				prev_rptr = (*xmit_tail)->b_rptr;
20249 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
20250 				    *tail_unsent;
20251 			}
20252 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20253 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20254 			/* Restore tcp_snxt so we get amount sent right. */
20255 			tcp->tcp_snxt = prev_snxt;
20256 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20257 				/*
20258 				 * If the previous timestamp is still in use,
20259 				 * don't stomp on it.
20260 				 */
20261 				if ((*xmit_tail)->b_next == NULL) {
20262 					(*xmit_tail)->b_prev = local_time;
20263 					(*xmit_tail)->b_next =
20264 					    (mblk_t *)(uintptr_t)(*snxt);
20265 				}
20266 			} else
20267 				(*xmit_tail)->b_rptr = prev_rptr;
20268 
20269 			if (mp == NULL)
20270 				return (-1);
20271 			mp1 = mp->b_cont;
20272 
20273 			tcp->tcp_last_sent_len = (ushort_t)len;
20274 			while (mp1->b_cont) {
20275 				*xmit_tail = (*xmit_tail)->b_cont;
20276 				(*xmit_tail)->b_prev = local_time;
20277 				(*xmit_tail)->b_next =
20278 				    (mblk_t *)(uintptr_t)(*snxt);
20279 				mp1 = mp1->b_cont;
20280 			}
20281 			*snxt += len;
20282 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20283 			BUMP_LOCAL(tcp->tcp_obsegs);
20284 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20285 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20286 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20287 			tcp_send_data(tcp, q, mp);
20288 			continue;
20289 		}
20290 
20291 		*snxt += len;	/* Adjust later if we don't send all of len */
20292 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20293 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20294 
20295 		if (*tail_unsent) {
20296 			/* Are the bytes above us in flight? */
20297 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20298 			if (rptr != (*xmit_tail)->b_rptr) {
20299 				*tail_unsent -= len;
20300 				tcp->tcp_last_sent_len = (ushort_t)len;
20301 				len += tcp_hdr_len;
20302 				if (tcp->tcp_ipversion == IPV4_VERSION)
20303 					tcp->tcp_ipha->ipha_length = htons(len);
20304 				else
20305 					tcp->tcp_ip6h->ip6_plen =
20306 					    htons(len -
20307 					    ((char *)&tcp->tcp_ip6h[1] -
20308 					    tcp->tcp_iphc));
20309 				mp = dupb(*xmit_tail);
20310 				if (!mp)
20311 					return (-1);	/* out_of_mem */
20312 				mp->b_rptr = rptr;
20313 				/*
20314 				 * If the old timestamp is no longer in use,
20315 				 * sample a new timestamp now.
20316 				 */
20317 				if ((*xmit_tail)->b_next == NULL) {
20318 					(*xmit_tail)->b_prev = local_time;
20319 					(*xmit_tail)->b_next =
20320 					    (mblk_t *)(uintptr_t)(*snxt-len);
20321 				}
20322 				goto must_alloc;
20323 			}
20324 		} else {
20325 			*xmit_tail = (*xmit_tail)->b_cont;
20326 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20327 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20328 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20329 			    (*xmit_tail)->b_rptr);
20330 		}
20331 
20332 		(*xmit_tail)->b_prev = local_time;
20333 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20334 
20335 		*tail_unsent -= len;
20336 		tcp->tcp_last_sent_len = (ushort_t)len;
20337 
20338 		len += tcp_hdr_len;
20339 		if (tcp->tcp_ipversion == IPV4_VERSION)
20340 			tcp->tcp_ipha->ipha_length = htons(len);
20341 		else
20342 			tcp->tcp_ip6h->ip6_plen = htons(len -
20343 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20344 
20345 		mp = dupb(*xmit_tail);
20346 		if (!mp)
20347 			return (-1);	/* out_of_mem */
20348 
20349 		len = tcp_hdr_len;
20350 		/*
20351 		 * There are four reasons to allocate a new hdr mblk:
20352 		 *  1) The bytes above us are in use by another packet
20353 		 *  2) We don't have good alignment
20354 		 *  3) The mblk is being shared
20355 		 *  4) We don't have enough room for a header
20356 		 */
20357 		rptr = mp->b_rptr - len;
20358 		if (!OK_32PTR(rptr) ||
20359 		    ((db = mp->b_datap), db->db_ref != 2) ||
20360 		    rptr < db->db_base) {
20361 			/* NOTE: we assume allocb returns an OK_32PTR */
20362 
20363 		must_alloc:;
20364 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20365 			    tcp_wroff_xtra, BPRI_MED);
20366 			if (!mp1) {
20367 				freemsg(mp);
20368 				return (-1);	/* out_of_mem */
20369 			}
20370 			mp1->b_cont = mp;
20371 			mp = mp1;
20372 			/* Leave room for Link Level header */
20373 			len = tcp_hdr_len;
20374 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20375 			mp->b_wptr = &rptr[len];
20376 		}
20377 
20378 		/*
20379 		 * Fill in the header using the template header, and add
20380 		 * options such as time-stamp, ECN and/or SACK, as needed.
20381 		 */
20382 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20383 
20384 		mp->b_rptr = rptr;
20385 
20386 		if (*tail_unsent) {
20387 			int spill = *tail_unsent;
20388 
20389 			mp1 = mp->b_cont;
20390 			if (!mp1)
20391 				mp1 = mp;
20392 
20393 			/*
20394 			 * If we're a little short, tack on more mblks until
20395 			 * there is no more spillover.
20396 			 */
20397 			while (spill < 0) {
20398 				mblk_t *nmp;
20399 				int nmpsz;
20400 
20401 				nmp = (*xmit_tail)->b_cont;
20402 				nmpsz = MBLKL(nmp);
20403 
20404 				/*
20405 				 * Excess data in mblk; can we split it?
20406 				 * If MDT is enabled for the connection,
20407 				 * keep on splitting as this is a transient
20408 				 * send path.
20409 				 */
20410 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20411 					/*
20412 					 * Don't split if stream head was
20413 					 * told to break up larger writes
20414 					 * into smaller ones.
20415 					 */
20416 					if (tcp->tcp_maxpsz > 0)
20417 						break;
20418 
20419 					/*
20420 					 * Next mblk is less than SMSS/2
20421 					 * rounded up to nearest 64-byte;
20422 					 * let it get sent as part of the
20423 					 * next segment.
20424 					 */
20425 					if (tcp->tcp_localnet &&
20426 					    !tcp->tcp_cork &&
20427 					    (nmpsz < roundup((mss >> 1), 64)))
20428 						break;
20429 				}
20430 
20431 				*xmit_tail = nmp;
20432 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20433 				/* Stash for rtt use later */
20434 				(*xmit_tail)->b_prev = local_time;
20435 				(*xmit_tail)->b_next =
20436 				    (mblk_t *)(uintptr_t)(*snxt - len);
20437 				mp1->b_cont = dupb(*xmit_tail);
20438 				mp1 = mp1->b_cont;
20439 
20440 				spill += nmpsz;
20441 				if (mp1 == NULL) {
20442 					*tail_unsent = spill;
20443 					freemsg(mp);
20444 					return (-1);	/* out_of_mem */
20445 				}
20446 			}
20447 
20448 			/* Trim back any surplus on the last mblk */
20449 			if (spill >= 0) {
20450 				mp1->b_wptr -= spill;
20451 				*tail_unsent = spill;
20452 			} else {
20453 				/*
20454 				 * We did not send everything we could in
20455 				 * order to remain within the b_cont limit.
20456 				 */
20457 				*usable -= spill;
20458 				*snxt += spill;
20459 				tcp->tcp_last_sent_len += spill;
20460 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20461 				/*
20462 				 * Adjust the checksum
20463 				 */
20464 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20465 				sum += spill;
20466 				sum = (sum >> 16) + (sum & 0xFFFF);
20467 				U16_TO_ABE16(sum, tcph->th_sum);
20468 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20469 					sum = ntohs(
20470 					    ((ipha_t *)rptr)->ipha_length) +
20471 					    spill;
20472 					((ipha_t *)rptr)->ipha_length =
20473 					    htons(sum);
20474 				} else {
20475 					sum = ntohs(
20476 					    ((ip6_t *)rptr)->ip6_plen) +
20477 					    spill;
20478 					((ip6_t *)rptr)->ip6_plen =
20479 					    htons(sum);
20480 				}
20481 				*tail_unsent = 0;
20482 			}
20483 		}
20484 		if (tcp->tcp_ip_forward_progress) {
20485 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20486 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20487 			tcp->tcp_ip_forward_progress = B_FALSE;
20488 		}
20489 
20490 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20491 		tcp_send_data(tcp, q, mp);
20492 		BUMP_LOCAL(tcp->tcp_obsegs);
20493 	}
20494 
20495 	return (0);
20496 }
20497 
20498 /* Unlink and return any mblk that looks like it contains a MDT info */
20499 static mblk_t *
20500 tcp_mdt_info_mp(mblk_t *mp)
20501 {
20502 	mblk_t	*prev_mp;
20503 
20504 	for (;;) {
20505 		prev_mp = mp;
20506 		/* no more to process? */
20507 		if ((mp = mp->b_cont) == NULL)
20508 			break;
20509 
20510 		switch (DB_TYPE(mp)) {
20511 		case M_CTL:
20512 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20513 				continue;
20514 			ASSERT(prev_mp != NULL);
20515 			prev_mp->b_cont = mp->b_cont;
20516 			mp->b_cont = NULL;
20517 			return (mp);
20518 		default:
20519 			break;
20520 		}
20521 	}
20522 	return (mp);
20523 }
20524 
20525 /* MDT info update routine, called when IP notifies us about MDT */
20526 static void
20527 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20528 {
20529 	boolean_t prev_state;
20530 
20531 	/*
20532 	 * IP is telling us to abort MDT on this connection?  We know
20533 	 * this because the capability is only turned off when IP
20534 	 * encounters some pathological cases, e.g. link-layer change
20535 	 * where the new driver doesn't support MDT, or in situation
20536 	 * where MDT usage on the link-layer has been switched off.
20537 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20538 	 * if the link-layer doesn't support MDT, and if it does, it
20539 	 * will indicate that the feature is to be turned on.
20540 	 */
20541 	prev_state = tcp->tcp_mdt;
20542 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20543 	if (!tcp->tcp_mdt && !first) {
20544 		TCP_STAT(tcp_mdt_conn_halted3);
20545 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20546 		    (void *)tcp->tcp_connp));
20547 	}
20548 
20549 	/*
20550 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20551 	 * so disable MDT otherwise.  The checks are done here
20552 	 * and in tcp_wput_data().
20553 	 */
20554 	if (tcp->tcp_mdt &&
20555 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20556 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20557 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20558 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20559 		tcp->tcp_mdt = B_FALSE;
20560 
20561 	if (tcp->tcp_mdt) {
20562 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20563 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20564 			    "version (%d), expected version is %d",
20565 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20566 			tcp->tcp_mdt = B_FALSE;
20567 			return;
20568 		}
20569 
20570 		/*
20571 		 * We need the driver to be able to handle at least three
20572 		 * spans per packet in order for tcp MDT to be utilized.
20573 		 * The first is for the header portion, while the rest are
20574 		 * needed to handle a packet that straddles across two
20575 		 * virtually non-contiguous buffers; a typical tcp packet
20576 		 * therefore consists of only two spans.  Note that we take
20577 		 * a zero as "don't care".
20578 		 */
20579 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20580 		    mdt_capab->ill_mdt_span_limit < 3) {
20581 			tcp->tcp_mdt = B_FALSE;
20582 			return;
20583 		}
20584 
20585 		/* a zero means driver wants default value */
20586 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20587 		    tcp_mdt_max_pbufs);
20588 		if (tcp->tcp_mdt_max_pld == 0)
20589 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20590 
20591 		/* ensure 32-bit alignment */
20592 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20593 		    mdt_capab->ill_mdt_hdr_head), 4);
20594 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20595 		    mdt_capab->ill_mdt_hdr_tail), 4);
20596 
20597 		if (!first && !prev_state) {
20598 			TCP_STAT(tcp_mdt_conn_resumed2);
20599 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20600 			    (void *)tcp->tcp_connp));
20601 		}
20602 	}
20603 }
20604 
20605 static void
20606 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20607 {
20608 	conn_t *connp = tcp->tcp_connp;
20609 
20610 	ASSERT(ire != NULL);
20611 
20612 	/*
20613 	 * We may be in the fastpath here, and although we essentially do
20614 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20615 	 * we try to keep things as brief as possible.  After all, these
20616 	 * are only best-effort checks, and we do more thorough ones prior
20617 	 * to calling tcp_multisend().
20618 	 */
20619 	if (ip_multidata_outbound && check_mdt &&
20620 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20621 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20622 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20623 	    !(ire->ire_flags & RTF_MULTIRT) &&
20624 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20625 	    CONN_IS_MD_FASTPATH(connp)) {
20626 		/* Remember the result */
20627 		connp->conn_mdt_ok = B_TRUE;
20628 
20629 		ASSERT(ill->ill_mdt_capab != NULL);
20630 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20631 			/*
20632 			 * If MDT has been previously turned off in the past,
20633 			 * and we currently can do MDT (due to IPQoS policy
20634 			 * removal, etc.) then enable it for this interface.
20635 			 */
20636 			ill->ill_mdt_capab->ill_mdt_on = 1;
20637 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20638 			    "interface %s\n", (void *)connp, ill->ill_name));
20639 		}
20640 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20641 	}
20642 
20643 	/*
20644 	 * The goal is to reduce the number of generated tcp segments by
20645 	 * setting the maxpsz multiplier to 0; this will have an affect on
20646 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20647 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20648 	 * of outbound segments and incoming ACKs, thus allowing for better
20649 	 * network and system performance.  In contrast the legacy behavior
20650 	 * may result in sending less than SMSS size, because the last mblk
20651 	 * for some packets may have more data than needed to make up SMSS,
20652 	 * and the legacy code refused to "split" it.
20653 	 *
20654 	 * We apply the new behavior on following situations:
20655 	 *
20656 	 *   1) Loopback connections,
20657 	 *   2) Connections in which the remote peer is not on local subnet,
20658 	 *   3) Local subnet connections over the bge interface (see below).
20659 	 *
20660 	 * Ideally, we would like this behavior to apply for interfaces other
20661 	 * than bge.  However, doing so would negatively impact drivers which
20662 	 * perform dynamic mapping and unmapping of DMA resources, which are
20663 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20664 	 * packet will be generated by tcp).  The bge driver does not suffer
20665 	 * from this, as it copies the mblks into pre-mapped buffers, and
20666 	 * therefore does not require more I/O resources than before.
20667 	 *
20668 	 * Otherwise, this behavior is present on all network interfaces when
20669 	 * the destination endpoint is non-local, since reducing the number
20670 	 * of packets in general is good for the network.
20671 	 *
20672 	 * TODO We need to remove this hard-coded conditional for bge once
20673 	 *	a better "self-tuning" mechanism, or a way to comprehend
20674 	 *	the driver transmit strategy is devised.  Until the solution
20675 	 *	is found and well understood, we live with this hack.
20676 	 */
20677 	if (!tcp_static_maxpsz &&
20678 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20679 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20680 		/* override the default value */
20681 		tcp->tcp_maxpsz = 0;
20682 
20683 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20684 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20685 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20686 	}
20687 
20688 	/* set the stream head parameters accordingly */
20689 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20690 }
20691 
20692 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20693 static void
20694 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20695 {
20696 	uchar_t	fval = *mp->b_rptr;
20697 	mblk_t	*tail;
20698 	queue_t	*q = tcp->tcp_wq;
20699 
20700 	/* TODO: How should flush interact with urgent data? */
20701 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20702 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20703 		/*
20704 		 * Flush only data that has not yet been put on the wire.  If
20705 		 * we flush data that we have already transmitted, life, as we
20706 		 * know it, may come to an end.
20707 		 */
20708 		tail = tcp->tcp_xmit_tail;
20709 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20710 		tcp->tcp_xmit_tail_unsent = 0;
20711 		tcp->tcp_unsent = 0;
20712 		if (tail->b_wptr != tail->b_rptr)
20713 			tail = tail->b_cont;
20714 		if (tail) {
20715 			mblk_t **excess = &tcp->tcp_xmit_head;
20716 			for (;;) {
20717 				mblk_t *mp1 = *excess;
20718 				if (mp1 == tail)
20719 					break;
20720 				tcp->tcp_xmit_tail = mp1;
20721 				tcp->tcp_xmit_last = mp1;
20722 				excess = &mp1->b_cont;
20723 			}
20724 			*excess = NULL;
20725 			tcp_close_mpp(&tail);
20726 			if (tcp->tcp_snd_zcopy_aware)
20727 				tcp_zcopy_notify(tcp);
20728 		}
20729 		/*
20730 		 * We have no unsent data, so unsent must be less than
20731 		 * tcp_xmit_lowater, so re-enable flow.
20732 		 */
20733 		if (tcp->tcp_flow_stopped) {
20734 			tcp_clrqfull(tcp);
20735 		}
20736 	}
20737 	/*
20738 	 * TODO: you can't just flush these, you have to increase rwnd for one
20739 	 * thing.  For another, how should urgent data interact?
20740 	 */
20741 	if (fval & FLUSHR) {
20742 		*mp->b_rptr = fval & ~FLUSHW;
20743 		/* XXX */
20744 		qreply(q, mp);
20745 		return;
20746 	}
20747 	freemsg(mp);
20748 }
20749 
20750 /*
20751  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20752  * messages.
20753  */
20754 static void
20755 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20756 {
20757 	mblk_t	*mp1;
20758 	STRUCT_HANDLE(strbuf, sb);
20759 	uint16_t port;
20760 	queue_t 	*q = tcp->tcp_wq;
20761 	in6_addr_t	v6addr;
20762 	ipaddr_t	v4addr;
20763 	uint32_t	flowinfo = 0;
20764 	int		addrlen;
20765 
20766 	/* Make sure it is one of ours. */
20767 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20768 	case TI_GETMYNAME:
20769 	case TI_GETPEERNAME:
20770 		break;
20771 	default:
20772 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20773 		return;
20774 	}
20775 	switch (mi_copy_state(q, mp, &mp1)) {
20776 	case -1:
20777 		return;
20778 	case MI_COPY_CASE(MI_COPY_IN, 1):
20779 		break;
20780 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20781 		/* Copy out the strbuf. */
20782 		mi_copyout(q, mp);
20783 		return;
20784 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20785 		/* All done. */
20786 		mi_copy_done(q, mp, 0);
20787 		return;
20788 	default:
20789 		mi_copy_done(q, mp, EPROTO);
20790 		return;
20791 	}
20792 	/* Check alignment of the strbuf */
20793 	if (!OK_32PTR(mp1->b_rptr)) {
20794 		mi_copy_done(q, mp, EINVAL);
20795 		return;
20796 	}
20797 
20798 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20799 	    (void *)mp1->b_rptr);
20800 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20801 
20802 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20803 		mi_copy_done(q, mp, EINVAL);
20804 		return;
20805 	}
20806 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20807 	case TI_GETMYNAME:
20808 		if (tcp->tcp_family == AF_INET) {
20809 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20810 				v4addr = tcp->tcp_ipha->ipha_src;
20811 			} else {
20812 				/* can't return an address in this case */
20813 				v4addr = 0;
20814 			}
20815 		} else {
20816 			/* tcp->tcp_family == AF_INET6 */
20817 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20818 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20819 				    &v6addr);
20820 			} else {
20821 				v6addr = tcp->tcp_ip6h->ip6_src;
20822 			}
20823 		}
20824 		port = tcp->tcp_lport;
20825 		break;
20826 	case TI_GETPEERNAME:
20827 		if (tcp->tcp_family == AF_INET) {
20828 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20829 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20830 				    v4addr);
20831 			} else {
20832 				/* can't return an address in this case */
20833 				v4addr = 0;
20834 			}
20835 		} else {
20836 			/* tcp->tcp_family == AF_INET6) */
20837 			v6addr = tcp->tcp_remote_v6;
20838 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20839 				/*
20840 				 * No flowinfo if tcp->tcp_ipversion is v4.
20841 				 *
20842 				 * flowinfo was already initialized to zero
20843 				 * where it was declared above, so only
20844 				 * set it if ipversion is v6.
20845 				 */
20846 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20847 				    ~IPV6_VERS_AND_FLOW_MASK;
20848 			}
20849 		}
20850 		port = tcp->tcp_fport;
20851 		break;
20852 	default:
20853 		mi_copy_done(q, mp, EPROTO);
20854 		return;
20855 	}
20856 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20857 	if (!mp1)
20858 		return;
20859 
20860 	if (tcp->tcp_family == AF_INET) {
20861 		sin_t *sin;
20862 
20863 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20864 		sin = (sin_t *)mp1->b_rptr;
20865 		mp1->b_wptr = (uchar_t *)&sin[1];
20866 		*sin = sin_null;
20867 		sin->sin_family = AF_INET;
20868 		sin->sin_addr.s_addr = v4addr;
20869 		sin->sin_port = port;
20870 	} else {
20871 		/* tcp->tcp_family == AF_INET6 */
20872 		sin6_t *sin6;
20873 
20874 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20875 		sin6 = (sin6_t *)mp1->b_rptr;
20876 		mp1->b_wptr = (uchar_t *)&sin6[1];
20877 		*sin6 = sin6_null;
20878 		sin6->sin6_family = AF_INET6;
20879 		sin6->sin6_flowinfo = flowinfo;
20880 		sin6->sin6_addr = v6addr;
20881 		sin6->sin6_port = port;
20882 	}
20883 	/* Copy out the address */
20884 	mi_copyout(q, mp);
20885 }
20886 
20887 /*
20888  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20889  * messages.
20890  */
20891 /* ARGSUSED */
20892 static void
20893 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20894 {
20895 	conn_t 	*connp = (conn_t *)arg;
20896 	tcp_t	*tcp = connp->conn_tcp;
20897 	queue_t	*q = tcp->tcp_wq;
20898 	struct iocblk	*iocp;
20899 
20900 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20901 	/*
20902 	 * Try and ASSERT the minimum possible references on the
20903 	 * conn early enough. Since we are executing on write side,
20904 	 * the connection is obviously not detached and that means
20905 	 * there is a ref each for TCP and IP. Since we are behind
20906 	 * the squeue, the minimum references needed are 3. If the
20907 	 * conn is in classifier hash list, there should be an
20908 	 * extra ref for that (we check both the possibilities).
20909 	 */
20910 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20911 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20912 
20913 	iocp = (struct iocblk *)mp->b_rptr;
20914 	switch (iocp->ioc_cmd) {
20915 	case TCP_IOC_DEFAULT_Q:
20916 		/* Wants to be the default wq. */
20917 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20918 			iocp->ioc_error = EPERM;
20919 			iocp->ioc_count = 0;
20920 			mp->b_datap->db_type = M_IOCACK;
20921 			qreply(q, mp);
20922 			return;
20923 		}
20924 		tcp_def_q_set(tcp, mp);
20925 		return;
20926 	case _SIOCSOCKFALLBACK:
20927 		/*
20928 		 * Either sockmod is about to be popped and the socket
20929 		 * would now be treated as a plain stream, or a module
20930 		 * is about to be pushed so we could no longer use read-
20931 		 * side synchronous streams for fused loopback tcp.
20932 		 * Drain any queued data and disable direct sockfs
20933 		 * interface from now on.
20934 		 */
20935 		if (!tcp->tcp_issocket) {
20936 			DB_TYPE(mp) = M_IOCNAK;
20937 			iocp->ioc_error = EINVAL;
20938 		} else {
20939 #ifdef	_ILP32
20940 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20941 #else
20942 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20943 #endif
20944 			/*
20945 			 * Insert this socket into the acceptor hash.
20946 			 * We might need it for T_CONN_RES message
20947 			 */
20948 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20949 
20950 			if (tcp->tcp_fused) {
20951 				/*
20952 				 * This is a fused loopback tcp; disable
20953 				 * read-side synchronous streams interface
20954 				 * and drain any queued data.  It is okay
20955 				 * to do this for non-synchronous streams
20956 				 * fused tcp as well.
20957 				 */
20958 				tcp_fuse_disable_pair(tcp, B_FALSE);
20959 			}
20960 			tcp->tcp_issocket = B_FALSE;
20961 			TCP_STAT(tcp_sock_fallback);
20962 
20963 			DB_TYPE(mp) = M_IOCACK;
20964 			iocp->ioc_error = 0;
20965 		}
20966 		iocp->ioc_count = 0;
20967 		iocp->ioc_rval = 0;
20968 		qreply(q, mp);
20969 		return;
20970 	}
20971 	CALL_IP_WPUT(connp, q, mp);
20972 }
20973 
20974 /*
20975  * This routine is called by tcp_wput() to handle all TPI requests.
20976  */
20977 /* ARGSUSED */
20978 static void
20979 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20980 {
20981 	conn_t 	*connp = (conn_t *)arg;
20982 	tcp_t	*tcp = connp->conn_tcp;
20983 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20984 	uchar_t *rptr;
20985 	t_scalar_t type;
20986 	int len;
20987 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20988 
20989 	/*
20990 	 * Try and ASSERT the minimum possible references on the
20991 	 * conn early enough. Since we are executing on write side,
20992 	 * the connection is obviously not detached and that means
20993 	 * there is a ref each for TCP and IP. Since we are behind
20994 	 * the squeue, the minimum references needed are 3. If the
20995 	 * conn is in classifier hash list, there should be an
20996 	 * extra ref for that (we check both the possibilities).
20997 	 */
20998 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20999 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
21000 
21001 	rptr = mp->b_rptr;
21002 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21003 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
21004 		type = ((union T_primitives *)rptr)->type;
21005 		if (type == T_EXDATA_REQ) {
21006 			uint32_t msize = msgdsize(mp->b_cont);
21007 
21008 			len = msize - 1;
21009 			if (len < 0) {
21010 				freemsg(mp);
21011 				return;
21012 			}
21013 			/*
21014 			 * Try to force urgent data out on the wire.
21015 			 * Even if we have unsent data this will
21016 			 * at least send the urgent flag.
21017 			 * XXX does not handle more flag correctly.
21018 			 */
21019 			len += tcp->tcp_unsent;
21020 			len += tcp->tcp_snxt;
21021 			tcp->tcp_urg = len;
21022 			tcp->tcp_valid_bits |= TCP_URG_VALID;
21023 
21024 			/* Bypass tcp protocol for fused tcp loopback */
21025 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21026 				return;
21027 		} else if (type != T_DATA_REQ) {
21028 			goto non_urgent_data;
21029 		}
21030 		/* TODO: options, flags, ... from user */
21031 		/* Set length to zero for reclamation below */
21032 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
21033 		freeb(mp);
21034 		return;
21035 	} else {
21036 		if (tcp->tcp_debug) {
21037 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21038 			    "tcp_wput_proto, dropping one...");
21039 		}
21040 		freemsg(mp);
21041 		return;
21042 	}
21043 
21044 non_urgent_data:
21045 
21046 	switch ((int)tprim->type) {
21047 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
21048 		/*
21049 		 * save the kssl_ent_t from the next block, and convert this
21050 		 * back to a normal bind_req.
21051 		 */
21052 		if (mp->b_cont != NULL) {
21053 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
21054 
21055 			if (tcp->tcp_kssl_ent != NULL) {
21056 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
21057 				    KSSL_NO_PROXY);
21058 				tcp->tcp_kssl_ent = NULL;
21059 			}
21060 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
21061 			    sizeof (kssl_ent_t));
21062 			kssl_hold_ent(tcp->tcp_kssl_ent);
21063 			freemsg(mp->b_cont);
21064 			mp->b_cont = NULL;
21065 		}
21066 		tprim->type = T_BIND_REQ;
21067 
21068 	/* FALLTHROUGH */
21069 	case O_T_BIND_REQ:	/* bind request */
21070 	case T_BIND_REQ:	/* new semantics bind request */
21071 		tcp_bind(tcp, mp);
21072 		break;
21073 	case T_UNBIND_REQ:	/* unbind request */
21074 		tcp_unbind(tcp, mp);
21075 		break;
21076 	case O_T_CONN_RES:	/* old connection response XXX */
21077 	case T_CONN_RES:	/* connection response */
21078 		tcp_accept(tcp, mp);
21079 		break;
21080 	case T_CONN_REQ:	/* connection request */
21081 		tcp_connect(tcp, mp);
21082 		break;
21083 	case T_DISCON_REQ:	/* disconnect request */
21084 		tcp_disconnect(tcp, mp);
21085 		break;
21086 	case T_CAPABILITY_REQ:
21087 		tcp_capability_req(tcp, mp);	/* capability request */
21088 		break;
21089 	case T_INFO_REQ:	/* information request */
21090 		tcp_info_req(tcp, mp);
21091 		break;
21092 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
21093 		/* Only IP is allowed to return meaningful value */
21094 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21095 		break;
21096 	case T_OPTMGMT_REQ:
21097 		/*
21098 		 * Note:  no support for snmpcom_req() through new
21099 		 * T_OPTMGMT_REQ. See comments in ip.c
21100 		 */
21101 		/* Only IP is allowed to return meaningful value */
21102 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
21103 		break;
21104 
21105 	case T_UNITDATA_REQ:	/* unitdata request */
21106 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21107 		break;
21108 	case T_ORDREL_REQ:	/* orderly release req */
21109 		freemsg(mp);
21110 
21111 		if (tcp->tcp_fused)
21112 			tcp_unfuse(tcp);
21113 
21114 		if (tcp_xmit_end(tcp) != 0) {
21115 			/*
21116 			 * We were crossing FINs and got a reset from
21117 			 * the other side. Just ignore it.
21118 			 */
21119 			if (tcp->tcp_debug) {
21120 				(void) strlog(TCP_MOD_ID, 0, 1,
21121 				    SL_ERROR|SL_TRACE,
21122 				    "tcp_wput_proto, T_ORDREL_REQ out of "
21123 				    "state %s",
21124 				    tcp_display(tcp, NULL,
21125 				    DISP_ADDR_AND_PORT));
21126 			}
21127 		}
21128 		break;
21129 	case T_ADDR_REQ:
21130 		tcp_addr_req(tcp, mp);
21131 		break;
21132 	default:
21133 		if (tcp->tcp_debug) {
21134 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21135 			    "tcp_wput_proto, bogus TPI msg, type %d",
21136 			    tprim->type);
21137 		}
21138 		/*
21139 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
21140 		 * to recover.
21141 		 */
21142 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
21143 		break;
21144 	}
21145 }
21146 
21147 /*
21148  * The TCP write service routine should never be called...
21149  */
21150 /* ARGSUSED */
21151 static void
21152 tcp_wsrv(queue_t *q)
21153 {
21154 	TCP_STAT(tcp_wsrv_called);
21155 }
21156 
21157 /* Non overlapping byte exchanger */
21158 static void
21159 tcp_xchg(uchar_t *a, uchar_t *b, int len)
21160 {
21161 	uchar_t	uch;
21162 
21163 	while (len-- > 0) {
21164 		uch = a[len];
21165 		a[len] = b[len];
21166 		b[len] = uch;
21167 	}
21168 }
21169 
21170 /*
21171  * Send out a control packet on the tcp connection specified.  This routine
21172  * is typically called where we need a simple ACK or RST generated.
21173  */
21174 static void
21175 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
21176 {
21177 	uchar_t		*rptr;
21178 	tcph_t		*tcph;
21179 	ipha_t		*ipha = NULL;
21180 	ip6_t		*ip6h = NULL;
21181 	uint32_t	sum;
21182 	int		tcp_hdr_len;
21183 	int		tcp_ip_hdr_len;
21184 	mblk_t		*mp;
21185 
21186 	/*
21187 	 * Save sum for use in source route later.
21188 	 */
21189 	ASSERT(tcp != NULL);
21190 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
21191 	tcp_hdr_len = tcp->tcp_hdr_len;
21192 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
21193 
21194 	/* If a text string is passed in with the request, pass it to strlog. */
21195 	if (str != NULL && tcp->tcp_debug) {
21196 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21197 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
21198 		    str, seq, ack, ctl);
21199 	}
21200 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21201 	    BPRI_MED);
21202 	if (mp == NULL) {
21203 		return;
21204 	}
21205 	rptr = &mp->b_rptr[tcp_wroff_xtra];
21206 	mp->b_rptr = rptr;
21207 	mp->b_wptr = &rptr[tcp_hdr_len];
21208 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
21209 
21210 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21211 		ipha = (ipha_t *)rptr;
21212 		ipha->ipha_length = htons(tcp_hdr_len);
21213 	} else {
21214 		ip6h = (ip6_t *)rptr;
21215 		ASSERT(tcp != NULL);
21216 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
21217 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21218 	}
21219 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
21220 	tcph->th_flags[0] = (uint8_t)ctl;
21221 	if (ctl & TH_RST) {
21222 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21223 		BUMP_MIB(&tcp_mib, tcpOutControl);
21224 		/*
21225 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
21226 		 */
21227 		if (tcp->tcp_snd_ts_ok &&
21228 		    tcp->tcp_state > TCPS_SYN_SENT) {
21229 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
21230 			*(mp->b_wptr) = TCPOPT_EOL;
21231 			if (tcp->tcp_ipversion == IPV4_VERSION) {
21232 				ipha->ipha_length = htons(tcp_hdr_len -
21233 				    TCPOPT_REAL_TS_LEN);
21234 			} else {
21235 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
21236 				    TCPOPT_REAL_TS_LEN);
21237 			}
21238 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
21239 			sum -= TCPOPT_REAL_TS_LEN;
21240 		}
21241 	}
21242 	if (ctl & TH_ACK) {
21243 		if (tcp->tcp_snd_ts_ok) {
21244 			U32_TO_BE32(lbolt,
21245 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21246 			U32_TO_BE32(tcp->tcp_ts_recent,
21247 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21248 		}
21249 
21250 		/* Update the latest receive window size in TCP header. */
21251 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21252 		    tcph->th_win);
21253 		tcp->tcp_rack = ack;
21254 		tcp->tcp_rack_cnt = 0;
21255 		BUMP_MIB(&tcp_mib, tcpOutAck);
21256 	}
21257 	BUMP_LOCAL(tcp->tcp_obsegs);
21258 	U32_TO_BE32(seq, tcph->th_seq);
21259 	U32_TO_BE32(ack, tcph->th_ack);
21260 	/*
21261 	 * Include the adjustment for a source route if any.
21262 	 */
21263 	sum = (sum >> 16) + (sum & 0xFFFF);
21264 	U16_TO_BE16(sum, tcph->th_sum);
21265 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21266 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21267 }
21268 
21269 /*
21270  * If this routine returns B_TRUE, TCP can generate a RST in response
21271  * to a segment.  If it returns B_FALSE, TCP should not respond.
21272  */
21273 static boolean_t
21274 tcp_send_rst_chk(void)
21275 {
21276 	clock_t	now;
21277 
21278 	/*
21279 	 * TCP needs to protect itself from generating too many RSTs.
21280 	 * This can be a DoS attack by sending us random segments
21281 	 * soliciting RSTs.
21282 	 *
21283 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21284 	 * in each 1 second interval.  In this way, TCP still generate
21285 	 * RSTs in normal cases but when under attack, the impact is
21286 	 * limited.
21287 	 */
21288 	if (tcp_rst_sent_rate_enabled != 0) {
21289 		now = lbolt;
21290 		/* lbolt can wrap around. */
21291 		if ((tcp_last_rst_intrvl > now) ||
21292 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21293 			tcp_last_rst_intrvl = now;
21294 			tcp_rst_cnt = 1;
21295 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21296 			return (B_FALSE);
21297 		}
21298 	}
21299 	return (B_TRUE);
21300 }
21301 
21302 /*
21303  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21304  */
21305 static void
21306 tcp_ip_ire_mark_advice(tcp_t *tcp)
21307 {
21308 	mblk_t *mp;
21309 	ipic_t *ipic;
21310 
21311 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21312 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21313 		    &ipic);
21314 	} else {
21315 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21316 		    &ipic);
21317 	}
21318 	if (mp == NULL)
21319 		return;
21320 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21321 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21322 }
21323 
21324 /*
21325  * Return an IP advice ioctl mblk and set ipic to be the pointer
21326  * to the advice structure.
21327  */
21328 static mblk_t *
21329 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21330 {
21331 	struct iocblk *ioc;
21332 	mblk_t *mp, *mp1;
21333 
21334 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21335 	if (mp == NULL)
21336 		return (NULL);
21337 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21338 	*ipic = (ipic_t *)mp->b_rptr;
21339 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21340 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21341 
21342 	bcopy(addr, *ipic + 1, addr_len);
21343 
21344 	(*ipic)->ipic_addr_length = addr_len;
21345 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21346 
21347 	mp1 = mkiocb(IP_IOCTL);
21348 	if (mp1 == NULL) {
21349 		freemsg(mp);
21350 		return (NULL);
21351 	}
21352 	mp1->b_cont = mp;
21353 	ioc = (struct iocblk *)mp1->b_rptr;
21354 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21355 
21356 	return (mp1);
21357 }
21358 
21359 /*
21360  * Generate a reset based on an inbound packet for which there is no active
21361  * tcp state that we can find.
21362  *
21363  * IPSEC NOTE : Try to send the reply with the same protection as it came
21364  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21365  * the packet will go out at the same level of protection as it came in by
21366  * converting the IPSEC_IN to IPSEC_OUT.
21367  */
21368 static void
21369 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21370     uint32_t ack, int ctl, uint_t ip_hdr_len)
21371 {
21372 	ipha_t		*ipha = NULL;
21373 	ip6_t		*ip6h = NULL;
21374 	ushort_t	len;
21375 	tcph_t		*tcph;
21376 	int		i;
21377 	mblk_t		*ipsec_mp;
21378 	boolean_t	mctl_present;
21379 	ipic_t		*ipic;
21380 	ipaddr_t	v4addr;
21381 	in6_addr_t	v6addr;
21382 	int		addr_len;
21383 	void		*addr;
21384 	queue_t		*q = tcp_g_q;
21385 	tcp_t		*tcp = Q_TO_TCP(q);
21386 	cred_t		*cr;
21387 
21388 	if (!tcp_send_rst_chk()) {
21389 		tcp_rst_unsent++;
21390 		freemsg(mp);
21391 		return;
21392 	}
21393 
21394 	if (mp->b_datap->db_type == M_CTL) {
21395 		ipsec_mp = mp;
21396 		mp = mp->b_cont;
21397 		mctl_present = B_TRUE;
21398 	} else {
21399 		ipsec_mp = mp;
21400 		mctl_present = B_FALSE;
21401 	}
21402 
21403 	if (str && q && tcp_dbg) {
21404 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21405 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21406 		    "flags 0x%x",
21407 		    str, seq, ack, ctl);
21408 	}
21409 	if (mp->b_datap->db_ref != 1) {
21410 		mblk_t *mp1 = copyb(mp);
21411 		freemsg(mp);
21412 		mp = mp1;
21413 		if (!mp) {
21414 			if (mctl_present)
21415 				freeb(ipsec_mp);
21416 			return;
21417 		} else {
21418 			if (mctl_present) {
21419 				ipsec_mp->b_cont = mp;
21420 			} else {
21421 				ipsec_mp = mp;
21422 			}
21423 		}
21424 	} else if (mp->b_cont) {
21425 		freemsg(mp->b_cont);
21426 		mp->b_cont = NULL;
21427 	}
21428 	/*
21429 	 * We skip reversing source route here.
21430 	 * (for now we replace all IP options with EOL)
21431 	 */
21432 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21433 		ipha = (ipha_t *)mp->b_rptr;
21434 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21435 			mp->b_rptr[i] = IPOPT_EOL;
21436 		/*
21437 		 * Make sure that src address isn't flagrantly invalid.
21438 		 * Not all broadcast address checking for the src address
21439 		 * is possible, since we don't know the netmask of the src
21440 		 * addr.  No check for destination address is done, since
21441 		 * IP will not pass up a packet with a broadcast dest
21442 		 * address to TCP.  Similar checks are done below for IPv6.
21443 		 */
21444 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21445 		    CLASSD(ipha->ipha_src)) {
21446 			freemsg(ipsec_mp);
21447 			BUMP_MIB(&ip_mib, ipInDiscards);
21448 			return;
21449 		}
21450 	} else {
21451 		ip6h = (ip6_t *)mp->b_rptr;
21452 
21453 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21454 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21455 			freemsg(ipsec_mp);
21456 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21457 			return;
21458 		}
21459 
21460 		/* Remove any extension headers assuming partial overlay */
21461 		if (ip_hdr_len > IPV6_HDR_LEN) {
21462 			uint8_t *to;
21463 
21464 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21465 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21466 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21467 			ip_hdr_len = IPV6_HDR_LEN;
21468 			ip6h = (ip6_t *)mp->b_rptr;
21469 			ip6h->ip6_nxt = IPPROTO_TCP;
21470 		}
21471 	}
21472 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21473 	if (tcph->th_flags[0] & TH_RST) {
21474 		freemsg(ipsec_mp);
21475 		return;
21476 	}
21477 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21478 	len = ip_hdr_len + sizeof (tcph_t);
21479 	mp->b_wptr = &mp->b_rptr[len];
21480 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21481 		ipha->ipha_length = htons(len);
21482 		/* Swap addresses */
21483 		v4addr = ipha->ipha_src;
21484 		ipha->ipha_src = ipha->ipha_dst;
21485 		ipha->ipha_dst = v4addr;
21486 		ipha->ipha_ident = 0;
21487 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21488 		addr_len = IP_ADDR_LEN;
21489 		addr = &v4addr;
21490 	} else {
21491 		/* No ip6i_t in this case */
21492 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21493 		/* Swap addresses */
21494 		v6addr = ip6h->ip6_src;
21495 		ip6h->ip6_src = ip6h->ip6_dst;
21496 		ip6h->ip6_dst = v6addr;
21497 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21498 		addr_len = IPV6_ADDR_LEN;
21499 		addr = &v6addr;
21500 	}
21501 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21502 	U32_TO_BE32(ack, tcph->th_ack);
21503 	U32_TO_BE32(seq, tcph->th_seq);
21504 	U16_TO_BE16(0, tcph->th_win);
21505 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21506 	tcph->th_flags[0] = (uint8_t)ctl;
21507 	if (ctl & TH_RST) {
21508 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21509 		BUMP_MIB(&tcp_mib, tcpOutControl);
21510 	}
21511 
21512 	/* IP trusts us to set up labels when required. */
21513 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
21514 	    crgetlabel(cr) != NULL) {
21515 		int err, adjust;
21516 
21517 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
21518 			err = tsol_check_label(cr, &mp, &adjust,
21519 			    tcp->tcp_connp->conn_mac_exempt);
21520 		else
21521 			err = tsol_check_label_v6(cr, &mp, &adjust,
21522 			    tcp->tcp_connp->conn_mac_exempt);
21523 		if (mctl_present)
21524 			ipsec_mp->b_cont = mp;
21525 		else
21526 			ipsec_mp = mp;
21527 		if (err != 0) {
21528 			freemsg(ipsec_mp);
21529 			return;
21530 		}
21531 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21532 			ipha = (ipha_t *)mp->b_rptr;
21533 			adjust += ntohs(ipha->ipha_length);
21534 			ipha->ipha_length = htons(adjust);
21535 		} else {
21536 			ip6h = (ip6_t *)mp->b_rptr;
21537 		}
21538 	}
21539 
21540 	if (mctl_present) {
21541 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21542 
21543 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21544 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21545 			return;
21546 		}
21547 	}
21548 	/*
21549 	 * NOTE:  one might consider tracing a TCP packet here, but
21550 	 * this function has no active TCP state and no tcp structure
21551 	 * that has a trace buffer.  If we traced here, we would have
21552 	 * to keep a local trace buffer in tcp_record_trace().
21553 	 *
21554 	 * TSol note: The mblk that contains the incoming packet was
21555 	 * reused by tcp_xmit_listener_reset, so it already contains
21556 	 * the right credentials and we don't need to call mblk_setcred.
21557 	 * Also the conn's cred is not right since it is associated
21558 	 * with tcp_g_q.
21559 	 */
21560 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21561 
21562 	/*
21563 	 * Tell IP to mark the IRE used for this destination temporary.
21564 	 * This way, we can limit our exposure to DoS attack because IP
21565 	 * creates an IRE for each destination.  If there are too many,
21566 	 * the time to do any routing lookup will be extremely long.  And
21567 	 * the lookup can be in interrupt context.
21568 	 *
21569 	 * Note that in normal circumstances, this marking should not
21570 	 * affect anything.  It would be nice if only 1 message is
21571 	 * needed to inform IP that the IRE created for this RST should
21572 	 * not be added to the cache table.  But there is currently
21573 	 * not such communication mechanism between TCP and IP.  So
21574 	 * the best we can do now is to send the advice ioctl to IP
21575 	 * to mark the IRE temporary.
21576 	 */
21577 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21578 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21579 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21580 	}
21581 }
21582 
21583 /*
21584  * Initiate closedown sequence on an active connection.  (May be called as
21585  * writer.)  Return value zero for OK return, non-zero for error return.
21586  */
21587 static int
21588 tcp_xmit_end(tcp_t *tcp)
21589 {
21590 	ipic_t	*ipic;
21591 	mblk_t	*mp;
21592 
21593 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21594 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21595 		/*
21596 		 * Invalid state, only states TCPS_SYN_RCVD,
21597 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21598 		 */
21599 		return (-1);
21600 	}
21601 
21602 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21603 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21604 	/*
21605 	 * If there is nothing more unsent, send the FIN now.
21606 	 * Otherwise, it will go out with the last segment.
21607 	 */
21608 	if (tcp->tcp_unsent == 0) {
21609 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21610 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21611 
21612 		if (mp) {
21613 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21614 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21615 		} else {
21616 			/*
21617 			 * Couldn't allocate msg.  Pretend we got it out.
21618 			 * Wait for rexmit timeout.
21619 			 */
21620 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21621 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21622 		}
21623 
21624 		/*
21625 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21626 		 * changed.
21627 		 */
21628 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21629 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21630 		}
21631 	} else {
21632 		/*
21633 		 * If tcp->tcp_cork is set, then the data will not get sent,
21634 		 * so we have to check that and unset it first.
21635 		 */
21636 		if (tcp->tcp_cork)
21637 			tcp->tcp_cork = B_FALSE;
21638 		tcp_wput_data(tcp, NULL, B_FALSE);
21639 	}
21640 
21641 	/*
21642 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21643 	 * is 0, don't update the cache.
21644 	 */
21645 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21646 		return (0);
21647 
21648 	/*
21649 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21650 	 * different from the destination.
21651 	 */
21652 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21653 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21654 			return (0);
21655 		}
21656 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21657 		    &ipic);
21658 	} else {
21659 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21660 		    &tcp->tcp_ip6h->ip6_dst))) {
21661 			return (0);
21662 		}
21663 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21664 		    &ipic);
21665 	}
21666 
21667 	/* Record route attributes in the IRE for use by future connections. */
21668 	if (mp == NULL)
21669 		return (0);
21670 
21671 	/*
21672 	 * We do not have a good algorithm to update ssthresh at this time.
21673 	 * So don't do any update.
21674 	 */
21675 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21676 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21677 
21678 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21679 	return (0);
21680 }
21681 
21682 /*
21683  * Generate a "no listener here" RST in response to an "unknown" segment.
21684  * Note that we are reusing the incoming mp to construct the outgoing
21685  * RST.
21686  */
21687 void
21688 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21689 {
21690 	uchar_t		*rptr;
21691 	uint32_t	seg_len;
21692 	tcph_t		*tcph;
21693 	uint32_t	seg_seq;
21694 	uint32_t	seg_ack;
21695 	uint_t		flags;
21696 	mblk_t		*ipsec_mp;
21697 	ipha_t 		*ipha;
21698 	ip6_t 		*ip6h;
21699 	boolean_t	mctl_present = B_FALSE;
21700 	boolean_t	check = B_TRUE;
21701 	boolean_t	policy_present;
21702 
21703 	TCP_STAT(tcp_no_listener);
21704 
21705 	ipsec_mp = mp;
21706 
21707 	if (mp->b_datap->db_type == M_CTL) {
21708 		ipsec_in_t *ii;
21709 
21710 		mctl_present = B_TRUE;
21711 		mp = mp->b_cont;
21712 
21713 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21714 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21715 		if (ii->ipsec_in_dont_check) {
21716 			check = B_FALSE;
21717 			if (!ii->ipsec_in_secure) {
21718 				freeb(ipsec_mp);
21719 				mctl_present = B_FALSE;
21720 				ipsec_mp = mp;
21721 			}
21722 		}
21723 	}
21724 
21725 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21726 		policy_present = ipsec_inbound_v4_policy_present;
21727 		ipha = (ipha_t *)mp->b_rptr;
21728 		ip6h = NULL;
21729 	} else {
21730 		policy_present = ipsec_inbound_v6_policy_present;
21731 		ipha = NULL;
21732 		ip6h = (ip6_t *)mp->b_rptr;
21733 	}
21734 
21735 	if (check && policy_present) {
21736 		/*
21737 		 * The conn_t parameter is NULL because we already know
21738 		 * nobody's home.
21739 		 */
21740 		ipsec_mp = ipsec_check_global_policy(
21741 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21742 		if (ipsec_mp == NULL)
21743 			return;
21744 	}
21745 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
21746 		DTRACE_PROBE2(
21747 		    tx__ip__log__error__nolistener__tcp,
21748 		    char *, "Could not reply with RST to mp(1)",
21749 		    mblk_t *, mp);
21750 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
21751 		freemsg(ipsec_mp);
21752 		return;
21753 	}
21754 
21755 	rptr = mp->b_rptr;
21756 
21757 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21758 	seg_seq = BE32_TO_U32(tcph->th_seq);
21759 	seg_ack = BE32_TO_U32(tcph->th_ack);
21760 	flags = tcph->th_flags[0];
21761 
21762 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21763 	if (flags & TH_RST) {
21764 		freemsg(ipsec_mp);
21765 	} else if (flags & TH_ACK) {
21766 		tcp_xmit_early_reset("no tcp, reset",
21767 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21768 	} else {
21769 		if (flags & TH_SYN) {
21770 			seg_len++;
21771 		} else {
21772 			/*
21773 			 * Here we violate the RFC.  Note that a normal
21774 			 * TCP will never send a segment without the ACK
21775 			 * flag, except for RST or SYN segment.  This
21776 			 * segment is neither.  Just drop it on the
21777 			 * floor.
21778 			 */
21779 			freemsg(ipsec_mp);
21780 			tcp_rst_unsent++;
21781 			return;
21782 		}
21783 
21784 		tcp_xmit_early_reset("no tcp, reset/ack",
21785 		    ipsec_mp, 0, seg_seq + seg_len,
21786 		    TH_RST | TH_ACK, ip_hdr_len);
21787 	}
21788 }
21789 
21790 /*
21791  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21792  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21793  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21794  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21795  * otherwise it will dup partial mblks.)
21796  * Otherwise, an appropriate ACK packet will be generated.  This
21797  * routine is not usually called to send new data for the first time.  It
21798  * is mostly called out of the timer for retransmits, and to generate ACKs.
21799  *
21800  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21801  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21802  * of the original mblk chain will be returned in *offset and *end_mp.
21803  */
21804 static mblk_t *
21805 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21806     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21807     boolean_t rexmit)
21808 {
21809 	int	data_length;
21810 	int32_t	off = 0;
21811 	uint_t	flags;
21812 	mblk_t	*mp1;
21813 	mblk_t	*mp2;
21814 	uchar_t	*rptr;
21815 	tcph_t	*tcph;
21816 	int32_t	num_sack_blk = 0;
21817 	int32_t	sack_opt_len = 0;
21818 
21819 	/* Allocate for our maximum TCP header + link-level */
21820 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21821 	    BPRI_MED);
21822 	if (!mp1)
21823 		return (NULL);
21824 	data_length = 0;
21825 
21826 	/*
21827 	 * Note that tcp_mss has been adjusted to take into account the
21828 	 * timestamp option if applicable.  Because SACK options do not
21829 	 * appear in every TCP segments and they are of variable lengths,
21830 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21831 	 * the actual segment length when we need to send a segment which
21832 	 * includes SACK options.
21833 	 */
21834 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21835 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21836 		    tcp->tcp_num_sack_blk);
21837 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21838 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21839 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21840 			max_to_send -= sack_opt_len;
21841 	}
21842 
21843 	if (offset != NULL) {
21844 		off = *offset;
21845 		/* We use offset as an indicator that end_mp is not NULL. */
21846 		*end_mp = NULL;
21847 	}
21848 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21849 		/* This could be faster with cooperation from downstream */
21850 		if (mp2 != mp1 && !sendall &&
21851 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21852 		    max_to_send)
21853 			/*
21854 			 * Don't send the next mblk since the whole mblk
21855 			 * does not fit.
21856 			 */
21857 			break;
21858 		mp2->b_cont = dupb(mp);
21859 		mp2 = mp2->b_cont;
21860 		if (!mp2) {
21861 			freemsg(mp1);
21862 			return (NULL);
21863 		}
21864 		mp2->b_rptr += off;
21865 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21866 		    (uintptr_t)INT_MAX);
21867 
21868 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21869 		if (data_length > max_to_send) {
21870 			mp2->b_wptr -= data_length - max_to_send;
21871 			data_length = max_to_send;
21872 			off = mp2->b_wptr - mp->b_rptr;
21873 			break;
21874 		} else {
21875 			off = 0;
21876 		}
21877 	}
21878 	if (offset != NULL) {
21879 		*offset = off;
21880 		*end_mp = mp;
21881 	}
21882 	if (seg_len != NULL) {
21883 		*seg_len = data_length;
21884 	}
21885 
21886 	/* Update the latest receive window size in TCP header. */
21887 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21888 	    tcp->tcp_tcph->th_win);
21889 
21890 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21891 	mp1->b_rptr = rptr;
21892 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21893 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21894 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21895 	U32_TO_ABE32(seq, tcph->th_seq);
21896 
21897 	/*
21898 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21899 	 * that this function was called from tcp_wput_data. Thus, when called
21900 	 * to retransmit data the setting of the PUSH bit may appear some
21901 	 * what random in that it might get set when it should not. This
21902 	 * should not pose any performance issues.
21903 	 */
21904 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21905 	    tcp->tcp_unsent == data_length)) {
21906 		flags = TH_ACK | TH_PUSH;
21907 	} else {
21908 		flags = TH_ACK;
21909 	}
21910 
21911 	if (tcp->tcp_ecn_ok) {
21912 		if (tcp->tcp_ecn_echo_on)
21913 			flags |= TH_ECE;
21914 
21915 		/*
21916 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21917 		 * There is no TCP flow control for non-data segments, and
21918 		 * only data segment is transmitted reliably.
21919 		 */
21920 		if (data_length > 0 && !rexmit) {
21921 			SET_ECT(tcp, rptr);
21922 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21923 				flags |= TH_CWR;
21924 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21925 			}
21926 		}
21927 	}
21928 
21929 	if (tcp->tcp_valid_bits) {
21930 		uint32_t u1;
21931 
21932 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21933 		    seq == tcp->tcp_iss) {
21934 			uchar_t	*wptr;
21935 
21936 			/*
21937 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21938 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21939 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21940 			 * our SYN is not ack'ed but the app closes this
21941 			 * TCP connection.
21942 			 */
21943 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21944 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21945 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21946 
21947 			/*
21948 			 * Tack on the MSS option.  It is always needed
21949 			 * for both active and passive open.
21950 			 *
21951 			 * MSS option value should be interface MTU - MIN
21952 			 * TCP/IP header according to RFC 793 as it means
21953 			 * the maximum segment size TCP can receive.  But
21954 			 * to get around some broken middle boxes/end hosts
21955 			 * out there, we allow the option value to be the
21956 			 * same as the MSS option size on the peer side.
21957 			 * In this way, the other side will not send
21958 			 * anything larger than they can receive.
21959 			 *
21960 			 * Note that for SYN_SENT state, the ndd param
21961 			 * tcp_use_smss_as_mss_opt has no effect as we
21962 			 * don't know the peer's MSS option value. So
21963 			 * the only case we need to take care of is in
21964 			 * SYN_RCVD state, which is done later.
21965 			 */
21966 			wptr = mp1->b_wptr;
21967 			wptr[0] = TCPOPT_MAXSEG;
21968 			wptr[1] = TCPOPT_MAXSEG_LEN;
21969 			wptr += 2;
21970 			u1 = tcp->tcp_if_mtu -
21971 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21972 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21973 			    TCP_MIN_HEADER_LENGTH;
21974 			U16_TO_BE16(u1, wptr);
21975 			mp1->b_wptr = wptr + 2;
21976 			/* Update the offset to cover the additional word */
21977 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21978 
21979 			/*
21980 			 * Note that the following way of filling in
21981 			 * TCP options are not optimal.  Some NOPs can
21982 			 * be saved.  But there is no need at this time
21983 			 * to optimize it.  When it is needed, we will
21984 			 * do it.
21985 			 */
21986 			switch (tcp->tcp_state) {
21987 			case TCPS_SYN_SENT:
21988 				flags = TH_SYN;
21989 
21990 				if (tcp->tcp_snd_ts_ok) {
21991 					uint32_t llbolt = (uint32_t)lbolt;
21992 
21993 					wptr = mp1->b_wptr;
21994 					wptr[0] = TCPOPT_NOP;
21995 					wptr[1] = TCPOPT_NOP;
21996 					wptr[2] = TCPOPT_TSTAMP;
21997 					wptr[3] = TCPOPT_TSTAMP_LEN;
21998 					wptr += 4;
21999 					U32_TO_BE32(llbolt, wptr);
22000 					wptr += 4;
22001 					ASSERT(tcp->tcp_ts_recent == 0);
22002 					U32_TO_BE32(0L, wptr);
22003 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
22004 					tcph->th_offset_and_rsrvd[0] +=
22005 					    (3 << 4);
22006 				}
22007 
22008 				/*
22009 				 * Set up all the bits to tell other side
22010 				 * we are ECN capable.
22011 				 */
22012 				if (tcp->tcp_ecn_ok) {
22013 					flags |= (TH_ECE | TH_CWR);
22014 				}
22015 				break;
22016 			case TCPS_SYN_RCVD:
22017 				flags |= TH_SYN;
22018 
22019 				/*
22020 				 * Reset the MSS option value to be SMSS
22021 				 * We should probably add back the bytes
22022 				 * for timestamp option and IPsec.  We
22023 				 * don't do that as this is a workaround
22024 				 * for broken middle boxes/end hosts, it
22025 				 * is better for us to be more cautious.
22026 				 * They may not take these things into
22027 				 * account in their SMSS calculation.  Thus
22028 				 * the peer's calculated SMSS may be smaller
22029 				 * than what it can be.  This should be OK.
22030 				 */
22031 				if (tcp_use_smss_as_mss_opt) {
22032 					u1 = tcp->tcp_mss;
22033 					U16_TO_BE16(u1, wptr);
22034 				}
22035 
22036 				/*
22037 				 * If the other side is ECN capable, reply
22038 				 * that we are also ECN capable.
22039 				 */
22040 				if (tcp->tcp_ecn_ok)
22041 					flags |= TH_ECE;
22042 				break;
22043 			default:
22044 				/*
22045 				 * The above ASSERT() makes sure that this
22046 				 * must be FIN-WAIT-1 state.  Our SYN has
22047 				 * not been ack'ed so retransmit it.
22048 				 */
22049 				flags |= TH_SYN;
22050 				break;
22051 			}
22052 
22053 			if (tcp->tcp_snd_ws_ok) {
22054 				wptr = mp1->b_wptr;
22055 				wptr[0] =  TCPOPT_NOP;
22056 				wptr[1] =  TCPOPT_WSCALE;
22057 				wptr[2] =  TCPOPT_WS_LEN;
22058 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
22059 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
22060 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22061 			}
22062 
22063 			if (tcp->tcp_snd_sack_ok) {
22064 				wptr = mp1->b_wptr;
22065 				wptr[0] = TCPOPT_NOP;
22066 				wptr[1] = TCPOPT_NOP;
22067 				wptr[2] = TCPOPT_SACK_PERMITTED;
22068 				wptr[3] = TCPOPT_SACK_OK_LEN;
22069 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
22070 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
22071 			}
22072 
22073 			/* allocb() of adequate mblk assures space */
22074 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
22075 			    (uintptr_t)INT_MAX);
22076 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
22077 			/*
22078 			 * Get IP set to checksum on our behalf
22079 			 * Include the adjustment for a source route if any.
22080 			 */
22081 			u1 += tcp->tcp_sum;
22082 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
22083 			U16_TO_BE16(u1, tcph->th_sum);
22084 			BUMP_MIB(&tcp_mib, tcpOutControl);
22085 		}
22086 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
22087 		    (seq + data_length) == tcp->tcp_fss) {
22088 			if (!tcp->tcp_fin_acked) {
22089 				flags |= TH_FIN;
22090 				BUMP_MIB(&tcp_mib, tcpOutControl);
22091 			}
22092 			if (!tcp->tcp_fin_sent) {
22093 				tcp->tcp_fin_sent = B_TRUE;
22094 				switch (tcp->tcp_state) {
22095 				case TCPS_SYN_RCVD:
22096 				case TCPS_ESTABLISHED:
22097 					tcp->tcp_state = TCPS_FIN_WAIT_1;
22098 					break;
22099 				case TCPS_CLOSE_WAIT:
22100 					tcp->tcp_state = TCPS_LAST_ACK;
22101 					break;
22102 				}
22103 				if (tcp->tcp_suna == tcp->tcp_snxt)
22104 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
22105 				tcp->tcp_snxt = tcp->tcp_fss + 1;
22106 			}
22107 		}
22108 		/*
22109 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
22110 		 * is smaller than seq, u1 will become a very huge value.
22111 		 * So the comparison will fail.  Also note that tcp_urp
22112 		 * should be positive, see RFC 793 page 17.
22113 		 */
22114 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
22115 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
22116 		    u1 < (uint32_t)(64 * 1024)) {
22117 			flags |= TH_URG;
22118 			BUMP_MIB(&tcp_mib, tcpOutUrg);
22119 			U32_TO_ABE16(u1, tcph->th_urp);
22120 		}
22121 	}
22122 	tcph->th_flags[0] = (uchar_t)flags;
22123 	tcp->tcp_rack = tcp->tcp_rnxt;
22124 	tcp->tcp_rack_cnt = 0;
22125 
22126 	if (tcp->tcp_snd_ts_ok) {
22127 		if (tcp->tcp_state != TCPS_SYN_SENT) {
22128 			uint32_t llbolt = (uint32_t)lbolt;
22129 
22130 			U32_TO_BE32(llbolt,
22131 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22132 			U32_TO_BE32(tcp->tcp_ts_recent,
22133 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22134 		}
22135 	}
22136 
22137 	if (num_sack_blk > 0) {
22138 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22139 		sack_blk_t *tmp;
22140 		int32_t	i;
22141 
22142 		wptr[0] = TCPOPT_NOP;
22143 		wptr[1] = TCPOPT_NOP;
22144 		wptr[2] = TCPOPT_SACK;
22145 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22146 		    sizeof (sack_blk_t);
22147 		wptr += TCPOPT_REAL_SACK_LEN;
22148 
22149 		tmp = tcp->tcp_sack_list;
22150 		for (i = 0; i < num_sack_blk; i++) {
22151 			U32_TO_BE32(tmp[i].begin, wptr);
22152 			wptr += sizeof (tcp_seq);
22153 			U32_TO_BE32(tmp[i].end, wptr);
22154 			wptr += sizeof (tcp_seq);
22155 		}
22156 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
22157 	}
22158 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22159 	data_length += (int)(mp1->b_wptr - rptr);
22160 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22161 		((ipha_t *)rptr)->ipha_length = htons(data_length);
22162 	} else {
22163 		ip6_t *ip6 = (ip6_t *)(rptr +
22164 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22165 		    sizeof (ip6i_t) : 0));
22166 
22167 		ip6->ip6_plen = htons(data_length -
22168 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22169 	}
22170 
22171 	/*
22172 	 * Prime pump for IP
22173 	 * Include the adjustment for a source route if any.
22174 	 */
22175 	data_length -= tcp->tcp_ip_hdr_len;
22176 	data_length += tcp->tcp_sum;
22177 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
22178 	U16_TO_ABE16(data_length, tcph->th_sum);
22179 	if (tcp->tcp_ip_forward_progress) {
22180 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22181 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22182 		tcp->tcp_ip_forward_progress = B_FALSE;
22183 	}
22184 	return (mp1);
22185 }
22186 
22187 /* This function handles the push timeout. */
22188 void
22189 tcp_push_timer(void *arg)
22190 {
22191 	conn_t	*connp = (conn_t *)arg;
22192 	tcp_t *tcp = connp->conn_tcp;
22193 
22194 	TCP_DBGSTAT(tcp_push_timer_cnt);
22195 
22196 	ASSERT(tcp->tcp_listener == NULL);
22197 
22198 	/*
22199 	 * We need to stop synchronous streams temporarily to prevent a race
22200 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
22201 	 * tcp_rcv_list here because those entry points will return right
22202 	 * away when synchronous streams is stopped.
22203 	 */
22204 	TCP_FUSE_SYNCSTR_STOP(tcp);
22205 	tcp->tcp_push_tid = 0;
22206 	if ((tcp->tcp_rcv_list != NULL) &&
22207 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
22208 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
22209 	TCP_FUSE_SYNCSTR_RESUME(tcp);
22210 }
22211 
22212 /*
22213  * This function handles delayed ACK timeout.
22214  */
22215 static void
22216 tcp_ack_timer(void *arg)
22217 {
22218 	conn_t	*connp = (conn_t *)arg;
22219 	tcp_t *tcp = connp->conn_tcp;
22220 	mblk_t *mp;
22221 
22222 	TCP_DBGSTAT(tcp_ack_timer_cnt);
22223 
22224 	tcp->tcp_ack_tid = 0;
22225 
22226 	if (tcp->tcp_fused)
22227 		return;
22228 
22229 	/*
22230 	 * Do not send ACK if there is no outstanding unack'ed data.
22231 	 */
22232 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
22233 		return;
22234 	}
22235 
22236 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
22237 		/*
22238 		 * Make sure we don't allow deferred ACKs to result in
22239 		 * timer-based ACKing.  If we have held off an ACK
22240 		 * when there was more than an mss here, and the timer
22241 		 * goes off, we have to worry about the possibility
22242 		 * that the sender isn't doing slow-start, or is out
22243 		 * of step with us for some other reason.  We fall
22244 		 * permanently back in the direction of
22245 		 * ACK-every-other-packet as suggested in RFC 1122.
22246 		 */
22247 		if (tcp->tcp_rack_abs_max > 2)
22248 			tcp->tcp_rack_abs_max--;
22249 		tcp->tcp_rack_cur_max = 2;
22250 	}
22251 	mp = tcp_ack_mp(tcp);
22252 
22253 	if (mp != NULL) {
22254 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
22255 		BUMP_LOCAL(tcp->tcp_obsegs);
22256 		BUMP_MIB(&tcp_mib, tcpOutAck);
22257 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
22258 		tcp_send_data(tcp, tcp->tcp_wq, mp);
22259 	}
22260 }
22261 
22262 
22263 /* Generate an ACK-only (no data) segment for a TCP endpoint */
22264 static mblk_t *
22265 tcp_ack_mp(tcp_t *tcp)
22266 {
22267 	uint32_t	seq_no;
22268 
22269 	/*
22270 	 * There are a few cases to be considered while setting the sequence no.
22271 	 * Essentially, we can come here while processing an unacceptable pkt
22272 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
22273 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
22274 	 * If we are here for a zero window probe, stick with suna. In all
22275 	 * other cases, we check if suna + swnd encompasses snxt and set
22276 	 * the sequence number to snxt, if so. If snxt falls outside the
22277 	 * window (the receiver probably shrunk its window), we will go with
22278 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
22279 	 * receiver.
22280 	 */
22281 	if (tcp->tcp_zero_win_probe) {
22282 		seq_no = tcp->tcp_suna;
22283 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
22284 		ASSERT(tcp->tcp_swnd == 0);
22285 		seq_no = tcp->tcp_snxt;
22286 	} else {
22287 		seq_no = SEQ_GT(tcp->tcp_snxt,
22288 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
22289 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
22290 	}
22291 
22292 	if (tcp->tcp_valid_bits) {
22293 		/*
22294 		 * For the complex case where we have to send some
22295 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22296 		 */
22297 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22298 		    NULL, B_FALSE));
22299 	} else {
22300 		/* Generate a simple ACK */
22301 		int	data_length;
22302 		uchar_t	*rptr;
22303 		tcph_t	*tcph;
22304 		mblk_t	*mp1;
22305 		int32_t	tcp_hdr_len;
22306 		int32_t	tcp_tcp_hdr_len;
22307 		int32_t	num_sack_blk = 0;
22308 		int32_t sack_opt_len;
22309 
22310 		/*
22311 		 * Allocate space for TCP + IP headers
22312 		 * and link-level header
22313 		 */
22314 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22315 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22316 			    tcp->tcp_num_sack_blk);
22317 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22318 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22319 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22320 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22321 		} else {
22322 			tcp_hdr_len = tcp->tcp_hdr_len;
22323 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22324 		}
22325 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22326 		if (!mp1)
22327 			return (NULL);
22328 
22329 		/* Update the latest receive window size in TCP header. */
22330 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22331 		    tcp->tcp_tcph->th_win);
22332 		/* copy in prototype TCP + IP header */
22333 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22334 		mp1->b_rptr = rptr;
22335 		mp1->b_wptr = rptr + tcp_hdr_len;
22336 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22337 
22338 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22339 
22340 		/* Set the TCP sequence number. */
22341 		U32_TO_ABE32(seq_no, tcph->th_seq);
22342 
22343 		/* Set up the TCP flag field. */
22344 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22345 		if (tcp->tcp_ecn_echo_on)
22346 			tcph->th_flags[0] |= TH_ECE;
22347 
22348 		tcp->tcp_rack = tcp->tcp_rnxt;
22349 		tcp->tcp_rack_cnt = 0;
22350 
22351 		/* fill in timestamp option if in use */
22352 		if (tcp->tcp_snd_ts_ok) {
22353 			uint32_t llbolt = (uint32_t)lbolt;
22354 
22355 			U32_TO_BE32(llbolt,
22356 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22357 			U32_TO_BE32(tcp->tcp_ts_recent,
22358 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22359 		}
22360 
22361 		/* Fill in SACK options */
22362 		if (num_sack_blk > 0) {
22363 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22364 			sack_blk_t *tmp;
22365 			int32_t	i;
22366 
22367 			wptr[0] = TCPOPT_NOP;
22368 			wptr[1] = TCPOPT_NOP;
22369 			wptr[2] = TCPOPT_SACK;
22370 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22371 			    sizeof (sack_blk_t);
22372 			wptr += TCPOPT_REAL_SACK_LEN;
22373 
22374 			tmp = tcp->tcp_sack_list;
22375 			for (i = 0; i < num_sack_blk; i++) {
22376 				U32_TO_BE32(tmp[i].begin, wptr);
22377 				wptr += sizeof (tcp_seq);
22378 				U32_TO_BE32(tmp[i].end, wptr);
22379 				wptr += sizeof (tcp_seq);
22380 			}
22381 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22382 			    << 4);
22383 		}
22384 
22385 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22386 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22387 		} else {
22388 			/* Check for ip6i_t header in sticky hdrs */
22389 			ip6_t *ip6 = (ip6_t *)(rptr +
22390 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22391 			    sizeof (ip6i_t) : 0));
22392 
22393 			ip6->ip6_plen = htons(tcp_hdr_len -
22394 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22395 		}
22396 
22397 		/*
22398 		 * Prime pump for checksum calculation in IP.  Include the
22399 		 * adjustment for a source route if any.
22400 		 */
22401 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22402 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22403 		U16_TO_ABE16(data_length, tcph->th_sum);
22404 
22405 		if (tcp->tcp_ip_forward_progress) {
22406 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22407 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22408 			tcp->tcp_ip_forward_progress = B_FALSE;
22409 		}
22410 		return (mp1);
22411 	}
22412 }
22413 
22414 /*
22415  * To create a temporary tcp structure for inserting into bind hash list.
22416  * The parameter is assumed to be in network byte order, ready for use.
22417  */
22418 /* ARGSUSED */
22419 static tcp_t *
22420 tcp_alloc_temp_tcp(in_port_t port)
22421 {
22422 	conn_t	*connp;
22423 	tcp_t	*tcp;
22424 
22425 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22426 	if (connp == NULL)
22427 		return (NULL);
22428 
22429 	tcp = connp->conn_tcp;
22430 
22431 	/*
22432 	 * Only initialize the necessary info in those structures.  Note
22433 	 * that since INADDR_ANY is all 0, we do not need to set
22434 	 * tcp_bound_source to INADDR_ANY here.
22435 	 */
22436 	tcp->tcp_state = TCPS_BOUND;
22437 	tcp->tcp_lport = port;
22438 	tcp->tcp_exclbind = 1;
22439 	tcp->tcp_reserved_port = 1;
22440 
22441 	/* Just for place holding... */
22442 	tcp->tcp_ipversion = IPV4_VERSION;
22443 
22444 	return (tcp);
22445 }
22446 
22447 /*
22448  * To remove a port range specified by lo_port and hi_port from the
22449  * reserved port ranges.  This is one of the three public functions of
22450  * the reserved port interface.  Note that a port range has to be removed
22451  * as a whole.  Ports in a range cannot be removed individually.
22452  *
22453  * Params:
22454  *	in_port_t lo_port: the beginning port of the reserved port range to
22455  *		be deleted.
22456  *	in_port_t hi_port: the ending port of the reserved port range to
22457  *		be deleted.
22458  *
22459  * Return:
22460  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22461  */
22462 boolean_t
22463 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22464 {
22465 	int	i, j;
22466 	int	size;
22467 	tcp_t	**temp_tcp_array;
22468 	tcp_t	*tcp;
22469 
22470 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22471 
22472 	/* First make sure that the port ranage is indeed reserved. */
22473 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22474 		if (tcp_reserved_port[i].lo_port == lo_port) {
22475 			hi_port = tcp_reserved_port[i].hi_port;
22476 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22477 			break;
22478 		}
22479 	}
22480 	if (i == tcp_reserved_port_array_size) {
22481 		rw_exit(&tcp_reserved_port_lock);
22482 		return (B_FALSE);
22483 	}
22484 
22485 	/*
22486 	 * Remove the range from the array.  This simple loop is possible
22487 	 * because port ranges are inserted in ascending order.
22488 	 */
22489 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22490 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22491 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22492 		tcp_reserved_port[j].temp_tcp_array =
22493 		    tcp_reserved_port[j+1].temp_tcp_array;
22494 	}
22495 
22496 	/* Remove all the temporary tcp structures. */
22497 	size = hi_port - lo_port + 1;
22498 	while (size > 0) {
22499 		tcp = temp_tcp_array[size - 1];
22500 		ASSERT(tcp != NULL);
22501 		tcp_bind_hash_remove(tcp);
22502 		CONN_DEC_REF(tcp->tcp_connp);
22503 		size--;
22504 	}
22505 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22506 	tcp_reserved_port_array_size--;
22507 	rw_exit(&tcp_reserved_port_lock);
22508 	return (B_TRUE);
22509 }
22510 
22511 /*
22512  * Macro to remove temporary tcp structure from the bind hash list.  The
22513  * first parameter is the list of tcp to be removed.  The second parameter
22514  * is the number of tcps in the array.
22515  */
22516 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22517 { \
22518 	while ((num) > 0) { \
22519 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22520 		tf_t *tbf; \
22521 		tcp_t *tcpnext; \
22522 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22523 		mutex_enter(&tbf->tf_lock); \
22524 		tcpnext = tcp->tcp_bind_hash; \
22525 		if (tcpnext) { \
22526 			tcpnext->tcp_ptpbhn = \
22527 				tcp->tcp_ptpbhn; \
22528 		} \
22529 		*tcp->tcp_ptpbhn = tcpnext; \
22530 		mutex_exit(&tbf->tf_lock); \
22531 		kmem_free(tcp, sizeof (tcp_t)); \
22532 		(tcp_array)[(num) - 1] = NULL; \
22533 		(num)--; \
22534 	} \
22535 }
22536 
22537 /*
22538  * The public interface for other modules to call to reserve a port range
22539  * in TCP.  The caller passes in how large a port range it wants.  TCP
22540  * will try to find a range and return it via lo_port and hi_port.  This is
22541  * used by NCA's nca_conn_init.
22542  * NCA can only be used in the global zone so this only affects the global
22543  * zone's ports.
22544  *
22545  * Params:
22546  *	int size: the size of the port range to be reserved.
22547  *	in_port_t *lo_port (referenced): returns the beginning port of the
22548  *		reserved port range added.
22549  *	in_port_t *hi_port (referenced): returns the ending port of the
22550  *		reserved port range added.
22551  *
22552  * Return:
22553  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22554  */
22555 boolean_t
22556 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22557 {
22558 	tcp_t		*tcp;
22559 	tcp_t		*tmp_tcp;
22560 	tcp_t		**temp_tcp_array;
22561 	tf_t		*tbf;
22562 	in_port_t	net_port;
22563 	in_port_t	port;
22564 	int32_t		cur_size;
22565 	int		i, j;
22566 	boolean_t	used;
22567 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22568 	zoneid_t	zoneid = GLOBAL_ZONEID;
22569 
22570 	/* Sanity check. */
22571 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22572 		return (B_FALSE);
22573 	}
22574 
22575 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22576 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22577 		rw_exit(&tcp_reserved_port_lock);
22578 		return (B_FALSE);
22579 	}
22580 
22581 	/*
22582 	 * Find the starting port to try.  Since the port ranges are ordered
22583 	 * in the reserved port array, we can do a simple search here.
22584 	 */
22585 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22586 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22587 	for (i = 0; i < tcp_reserved_port_array_size;
22588 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22589 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22590 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22591 			break;
22592 		}
22593 	}
22594 	/* No available port range. */
22595 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22596 		rw_exit(&tcp_reserved_port_lock);
22597 		return (B_FALSE);
22598 	}
22599 
22600 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22601 	if (temp_tcp_array == NULL) {
22602 		rw_exit(&tcp_reserved_port_lock);
22603 		return (B_FALSE);
22604 	}
22605 
22606 	/* Go thru the port range to see if some ports are already bound. */
22607 	for (port = *lo_port, cur_size = 0;
22608 	    cur_size < size && port <= *hi_port;
22609 	    cur_size++, port++) {
22610 		used = B_FALSE;
22611 		net_port = htons(port);
22612 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22613 		mutex_enter(&tbf->tf_lock);
22614 		for (tcp = tbf->tf_tcp; tcp != NULL;
22615 		    tcp = tcp->tcp_bind_hash) {
22616 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22617 			    net_port == tcp->tcp_lport) {
22618 				/*
22619 				 * A port is already bound.  Search again
22620 				 * starting from port + 1.  Release all
22621 				 * temporary tcps.
22622 				 */
22623 				mutex_exit(&tbf->tf_lock);
22624 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22625 				*lo_port = port + 1;
22626 				cur_size = -1;
22627 				used = B_TRUE;
22628 				break;
22629 			}
22630 		}
22631 		if (!used) {
22632 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22633 				/*
22634 				 * Allocation failure.  Just fail the request.
22635 				 * Need to remove all those temporary tcp
22636 				 * structures.
22637 				 */
22638 				mutex_exit(&tbf->tf_lock);
22639 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22640 				rw_exit(&tcp_reserved_port_lock);
22641 				kmem_free(temp_tcp_array,
22642 				    (hi_port - lo_port + 1) *
22643 				    sizeof (tcp_t *));
22644 				return (B_FALSE);
22645 			}
22646 			temp_tcp_array[cur_size] = tmp_tcp;
22647 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22648 			mutex_exit(&tbf->tf_lock);
22649 		}
22650 	}
22651 
22652 	/*
22653 	 * The current range is not large enough.  We can actually do another
22654 	 * search if this search is done between 2 reserved port ranges.  But
22655 	 * for first release, we just stop here and return saying that no port
22656 	 * range is available.
22657 	 */
22658 	if (cur_size < size) {
22659 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22660 		rw_exit(&tcp_reserved_port_lock);
22661 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22662 		return (B_FALSE);
22663 	}
22664 	*hi_port = port - 1;
22665 
22666 	/*
22667 	 * Insert range into array in ascending order.  Since this function
22668 	 * must not be called often, we choose to use the simplest method.
22669 	 * The above array should not consume excessive stack space as
22670 	 * the size must be very small.  If in future releases, we find
22671 	 * that we should provide more reserved port ranges, this function
22672 	 * has to be modified to be more efficient.
22673 	 */
22674 	if (tcp_reserved_port_array_size == 0) {
22675 		tcp_reserved_port[0].lo_port = *lo_port;
22676 		tcp_reserved_port[0].hi_port = *hi_port;
22677 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22678 	} else {
22679 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22680 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22681 				tmp_ports[j].lo_port = *lo_port;
22682 				tmp_ports[j].hi_port = *hi_port;
22683 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22684 				j++;
22685 			}
22686 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22687 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22688 			tmp_ports[j].temp_tcp_array =
22689 			    tcp_reserved_port[i].temp_tcp_array;
22690 		}
22691 		if (j == i) {
22692 			tmp_ports[j].lo_port = *lo_port;
22693 			tmp_ports[j].hi_port = *hi_port;
22694 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22695 		}
22696 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22697 	}
22698 	tcp_reserved_port_array_size++;
22699 	rw_exit(&tcp_reserved_port_lock);
22700 	return (B_TRUE);
22701 }
22702 
22703 /*
22704  * Check to see if a port is in any reserved port range.
22705  *
22706  * Params:
22707  *	in_port_t port: the port to be verified.
22708  *
22709  * Return:
22710  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22711  */
22712 boolean_t
22713 tcp_reserved_port_check(in_port_t port)
22714 {
22715 	int i;
22716 
22717 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22718 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22719 		if (port >= tcp_reserved_port[i].lo_port ||
22720 		    port <= tcp_reserved_port[i].hi_port) {
22721 			rw_exit(&tcp_reserved_port_lock);
22722 			return (B_TRUE);
22723 		}
22724 	}
22725 	rw_exit(&tcp_reserved_port_lock);
22726 	return (B_FALSE);
22727 }
22728 
22729 /*
22730  * To list all reserved port ranges.  This is the function to handle
22731  * ndd tcp_reserved_port_list.
22732  */
22733 /* ARGSUSED */
22734 static int
22735 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22736 {
22737 	int i;
22738 
22739 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22740 	if (tcp_reserved_port_array_size > 0)
22741 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22742 	else
22743 		(void) mi_mpprintf(mp, "No port is reserved.");
22744 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22745 		(void) mi_mpprintf(mp, "%d-%d",
22746 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22747 	}
22748 	rw_exit(&tcp_reserved_port_lock);
22749 	return (0);
22750 }
22751 
22752 /*
22753  * Hash list insertion routine for tcp_t structures.
22754  * Inserts entries with the ones bound to a specific IP address first
22755  * followed by those bound to INADDR_ANY.
22756  */
22757 static void
22758 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22759 {
22760 	tcp_t	**tcpp;
22761 	tcp_t	*tcpnext;
22762 
22763 	if (tcp->tcp_ptpbhn != NULL) {
22764 		ASSERT(!caller_holds_lock);
22765 		tcp_bind_hash_remove(tcp);
22766 	}
22767 	tcpp = &tbf->tf_tcp;
22768 	if (!caller_holds_lock) {
22769 		mutex_enter(&tbf->tf_lock);
22770 	} else {
22771 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22772 	}
22773 	tcpnext = tcpp[0];
22774 	if (tcpnext) {
22775 		/*
22776 		 * If the new tcp bound to the INADDR_ANY address
22777 		 * and the first one in the list is not bound to
22778 		 * INADDR_ANY we skip all entries until we find the
22779 		 * first one bound to INADDR_ANY.
22780 		 * This makes sure that applications binding to a
22781 		 * specific address get preference over those binding to
22782 		 * INADDR_ANY.
22783 		 */
22784 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22785 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22786 			while ((tcpnext = tcpp[0]) != NULL &&
22787 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22788 				tcpp = &(tcpnext->tcp_bind_hash);
22789 			if (tcpnext)
22790 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22791 		} else
22792 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22793 	}
22794 	tcp->tcp_bind_hash = tcpnext;
22795 	tcp->tcp_ptpbhn = tcpp;
22796 	tcpp[0] = tcp;
22797 	if (!caller_holds_lock)
22798 		mutex_exit(&tbf->tf_lock);
22799 }
22800 
22801 /*
22802  * Hash list removal routine for tcp_t structures.
22803  */
22804 static void
22805 tcp_bind_hash_remove(tcp_t *tcp)
22806 {
22807 	tcp_t	*tcpnext;
22808 	kmutex_t *lockp;
22809 
22810 	if (tcp->tcp_ptpbhn == NULL)
22811 		return;
22812 
22813 	/*
22814 	 * Extract the lock pointer in case there are concurrent
22815 	 * hash_remove's for this instance.
22816 	 */
22817 	ASSERT(tcp->tcp_lport != 0);
22818 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22819 
22820 	ASSERT(lockp != NULL);
22821 	mutex_enter(lockp);
22822 	if (tcp->tcp_ptpbhn) {
22823 		tcpnext = tcp->tcp_bind_hash;
22824 		if (tcpnext) {
22825 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22826 			tcp->tcp_bind_hash = NULL;
22827 		}
22828 		*tcp->tcp_ptpbhn = tcpnext;
22829 		tcp->tcp_ptpbhn = NULL;
22830 	}
22831 	mutex_exit(lockp);
22832 }
22833 
22834 
22835 /*
22836  * Hash list lookup routine for tcp_t structures.
22837  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22838  */
22839 static tcp_t *
22840 tcp_acceptor_hash_lookup(t_uscalar_t id)
22841 {
22842 	tf_t	*tf;
22843 	tcp_t	*tcp;
22844 
22845 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22846 	mutex_enter(&tf->tf_lock);
22847 	for (tcp = tf->tf_tcp; tcp != NULL;
22848 	    tcp = tcp->tcp_acceptor_hash) {
22849 		if (tcp->tcp_acceptor_id == id) {
22850 			CONN_INC_REF(tcp->tcp_connp);
22851 			mutex_exit(&tf->tf_lock);
22852 			return (tcp);
22853 		}
22854 	}
22855 	mutex_exit(&tf->tf_lock);
22856 	return (NULL);
22857 }
22858 
22859 
22860 /*
22861  * Hash list insertion routine for tcp_t structures.
22862  */
22863 void
22864 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22865 {
22866 	tf_t	*tf;
22867 	tcp_t	**tcpp;
22868 	tcp_t	*tcpnext;
22869 
22870 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22871 
22872 	if (tcp->tcp_ptpahn != NULL)
22873 		tcp_acceptor_hash_remove(tcp);
22874 	tcpp = &tf->tf_tcp;
22875 	mutex_enter(&tf->tf_lock);
22876 	tcpnext = tcpp[0];
22877 	if (tcpnext)
22878 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22879 	tcp->tcp_acceptor_hash = tcpnext;
22880 	tcp->tcp_ptpahn = tcpp;
22881 	tcpp[0] = tcp;
22882 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22883 	mutex_exit(&tf->tf_lock);
22884 }
22885 
22886 /*
22887  * Hash list removal routine for tcp_t structures.
22888  */
22889 static void
22890 tcp_acceptor_hash_remove(tcp_t *tcp)
22891 {
22892 	tcp_t	*tcpnext;
22893 	kmutex_t *lockp;
22894 
22895 	/*
22896 	 * Extract the lock pointer in case there are concurrent
22897 	 * hash_remove's for this instance.
22898 	 */
22899 	lockp = tcp->tcp_acceptor_lockp;
22900 
22901 	if (tcp->tcp_ptpahn == NULL)
22902 		return;
22903 
22904 	ASSERT(lockp != NULL);
22905 	mutex_enter(lockp);
22906 	if (tcp->tcp_ptpahn) {
22907 		tcpnext = tcp->tcp_acceptor_hash;
22908 		if (tcpnext) {
22909 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22910 			tcp->tcp_acceptor_hash = NULL;
22911 		}
22912 		*tcp->tcp_ptpahn = tcpnext;
22913 		tcp->tcp_ptpahn = NULL;
22914 	}
22915 	mutex_exit(lockp);
22916 	tcp->tcp_acceptor_lockp = NULL;
22917 }
22918 
22919 /* ARGSUSED */
22920 static int
22921 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22922 {
22923 	int error = 0;
22924 	int retval;
22925 	char *end;
22926 
22927 	tcp_hsp_t *hsp;
22928 	tcp_hsp_t *hspprev;
22929 
22930 	ipaddr_t addr = 0;		/* Address we're looking for */
22931 	in6_addr_t v6addr;		/* Address we're looking for */
22932 	uint32_t hash;			/* Hash of that address */
22933 
22934 	/*
22935 	 * If the following variables are still zero after parsing the input
22936 	 * string, the user didn't specify them and we don't change them in
22937 	 * the HSP.
22938 	 */
22939 
22940 	ipaddr_t mask = 0;		/* Subnet mask */
22941 	in6_addr_t v6mask;
22942 	long sendspace = 0;		/* Send buffer size */
22943 	long recvspace = 0;		/* Receive buffer size */
22944 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22945 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22946 
22947 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22948 
22949 	/* Parse and validate address */
22950 	if (af == AF_INET) {
22951 		retval = inet_pton(af, value, &addr);
22952 		if (retval == 1)
22953 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22954 	} else if (af == AF_INET6) {
22955 		retval = inet_pton(af, value, &v6addr);
22956 	} else {
22957 		error = EINVAL;
22958 		goto done;
22959 	}
22960 	if (retval == 0) {
22961 		error = EINVAL;
22962 		goto done;
22963 	}
22964 
22965 	while ((*value) && *value != ' ')
22966 		value++;
22967 
22968 	/* Parse individual keywords, set variables if found */
22969 	while (*value) {
22970 		/* Skip leading blanks */
22971 
22972 		while (*value == ' ' || *value == '\t')
22973 			value++;
22974 
22975 		/* If at end of string, we're done */
22976 
22977 		if (!*value)
22978 			break;
22979 
22980 		/* We have a word, figure out what it is */
22981 
22982 		if (strncmp("mask", value, 4) == 0) {
22983 			value += 4;
22984 			while (*value == ' ' || *value == '\t')
22985 				value++;
22986 			/* Parse subnet mask */
22987 			if (af == AF_INET) {
22988 				retval = inet_pton(af, value, &mask);
22989 				if (retval == 1) {
22990 					V4MASK_TO_V6(mask, v6mask);
22991 				}
22992 			} else if (af == AF_INET6) {
22993 				retval = inet_pton(af, value, &v6mask);
22994 			}
22995 			if (retval != 1) {
22996 				error = EINVAL;
22997 				goto done;
22998 			}
22999 			while ((*value) && *value != ' ')
23000 				value++;
23001 		} else if (strncmp("sendspace", value, 9) == 0) {
23002 			value += 9;
23003 
23004 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
23005 			    sendspace < TCP_XMIT_HIWATER ||
23006 			    sendspace >= (1L<<30)) {
23007 				error = EINVAL;
23008 				goto done;
23009 			}
23010 			value = end;
23011 		} else if (strncmp("recvspace", value, 9) == 0) {
23012 			value += 9;
23013 
23014 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
23015 			    recvspace < TCP_RECV_HIWATER ||
23016 			    recvspace >= (1L<<30)) {
23017 				error = EINVAL;
23018 				goto done;
23019 			}
23020 			value = end;
23021 		} else if (strncmp("timestamp", value, 9) == 0) {
23022 			value += 9;
23023 
23024 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
23025 			    timestamp < 0 || timestamp > 1) {
23026 				error = EINVAL;
23027 				goto done;
23028 			}
23029 
23030 			/*
23031 			 * We increment timestamp so we know it's been set;
23032 			 * this is undone when we put it in the HSP
23033 			 */
23034 			timestamp++;
23035 			value = end;
23036 		} else if (strncmp("delete", value, 6) == 0) {
23037 			value += 6;
23038 			delete = B_TRUE;
23039 		} else {
23040 			error = EINVAL;
23041 			goto done;
23042 		}
23043 	}
23044 
23045 	/* Hash address for lookup */
23046 
23047 	hash = TCP_HSP_HASH(addr);
23048 
23049 	if (delete) {
23050 		/*
23051 		 * Note that deletes don't return an error if the thing
23052 		 * we're trying to delete isn't there.
23053 		 */
23054 		if (tcp_hsp_hash == NULL)
23055 			goto done;
23056 		hsp = tcp_hsp_hash[hash];
23057 
23058 		if (hsp) {
23059 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23060 			    &v6addr)) {
23061 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
23062 				mi_free((char *)hsp);
23063 			} else {
23064 				hspprev = hsp;
23065 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
23066 					if (IN6_ARE_ADDR_EQUAL(
23067 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
23068 						hspprev->tcp_hsp_next =
23069 						    hsp->tcp_hsp_next;
23070 						mi_free((char *)hsp);
23071 						break;
23072 					}
23073 					hspprev = hsp;
23074 				}
23075 			}
23076 		}
23077 	} else {
23078 		/*
23079 		 * We're adding/modifying an HSP.  If we haven't already done
23080 		 * so, allocate the hash table.
23081 		 */
23082 
23083 		if (!tcp_hsp_hash) {
23084 			tcp_hsp_hash = (tcp_hsp_t **)
23085 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
23086 			if (!tcp_hsp_hash) {
23087 				error = EINVAL;
23088 				goto done;
23089 			}
23090 		}
23091 
23092 		/* Get head of hash chain */
23093 
23094 		hsp = tcp_hsp_hash[hash];
23095 
23096 		/* Try to find pre-existing hsp on hash chain */
23097 		/* Doesn't handle CIDR prefixes. */
23098 		while (hsp) {
23099 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
23100 				break;
23101 			hsp = hsp->tcp_hsp_next;
23102 		}
23103 
23104 		/*
23105 		 * If we didn't, create one with default values and put it
23106 		 * at head of hash chain
23107 		 */
23108 
23109 		if (!hsp) {
23110 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
23111 			if (!hsp) {
23112 				error = EINVAL;
23113 				goto done;
23114 			}
23115 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
23116 			tcp_hsp_hash[hash] = hsp;
23117 		}
23118 
23119 		/* Set values that the user asked us to change */
23120 
23121 		hsp->tcp_hsp_addr_v6 = v6addr;
23122 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
23123 			hsp->tcp_hsp_vers = IPV4_VERSION;
23124 		else
23125 			hsp->tcp_hsp_vers = IPV6_VERSION;
23126 		hsp->tcp_hsp_subnet_v6 = v6mask;
23127 		if (sendspace > 0)
23128 			hsp->tcp_hsp_sendspace = sendspace;
23129 		if (recvspace > 0)
23130 			hsp->tcp_hsp_recvspace = recvspace;
23131 		if (timestamp > 0)
23132 			hsp->tcp_hsp_tstamp = timestamp - 1;
23133 	}
23134 
23135 done:
23136 	rw_exit(&tcp_hsp_lock);
23137 	return (error);
23138 }
23139 
23140 /* Set callback routine passed to nd_load by tcp_param_register. */
23141 /* ARGSUSED */
23142 static int
23143 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
23144 {
23145 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
23146 }
23147 /* ARGSUSED */
23148 static int
23149 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23150     cred_t *cr)
23151 {
23152 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
23153 }
23154 
23155 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
23156 /* ARGSUSED */
23157 static int
23158 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
23159 {
23160 	tcp_hsp_t *hsp;
23161 	int i;
23162 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
23163 
23164 	rw_enter(&tcp_hsp_lock, RW_READER);
23165 	(void) mi_mpprintf(mp,
23166 	    "Hash HSP     " MI_COL_HDRPAD_STR
23167 	    "Address         Subnet Mask     Send       Receive    TStamp");
23168 	if (tcp_hsp_hash) {
23169 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
23170 			hsp = tcp_hsp_hash[i];
23171 			while (hsp) {
23172 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
23173 					(void) inet_ntop(AF_INET,
23174 					    &hsp->tcp_hsp_addr,
23175 					    addrbuf, sizeof (addrbuf));
23176 					(void) inet_ntop(AF_INET,
23177 					    &hsp->tcp_hsp_subnet,
23178 					    subnetbuf, sizeof (subnetbuf));
23179 				} else {
23180 					(void) inet_ntop(AF_INET6,
23181 					    &hsp->tcp_hsp_addr_v6,
23182 					    addrbuf, sizeof (addrbuf));
23183 					(void) inet_ntop(AF_INET6,
23184 					    &hsp->tcp_hsp_subnet_v6,
23185 					    subnetbuf, sizeof (subnetbuf));
23186 				}
23187 				(void) mi_mpprintf(mp,
23188 				    " %03d " MI_COL_PTRFMT_STR
23189 				    "%s %s %010d %010d      %d",
23190 				    i,
23191 				    (void *)hsp,
23192 				    addrbuf,
23193 				    subnetbuf,
23194 				    hsp->tcp_hsp_sendspace,
23195 				    hsp->tcp_hsp_recvspace,
23196 				    hsp->tcp_hsp_tstamp);
23197 
23198 				hsp = hsp->tcp_hsp_next;
23199 			}
23200 		}
23201 	}
23202 	rw_exit(&tcp_hsp_lock);
23203 	return (0);
23204 }
23205 
23206 
23207 /* Data for fast netmask macro used by tcp_hsp_lookup */
23208 
23209 static ipaddr_t netmasks[] = {
23210 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
23211 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
23212 };
23213 
23214 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
23215 
23216 /*
23217  * XXX This routine should go away and instead we should use the metrics
23218  * associated with the routes to determine the default sndspace and rcvspace.
23219  */
23220 static tcp_hsp_t *
23221 tcp_hsp_lookup(ipaddr_t addr)
23222 {
23223 	tcp_hsp_t *hsp = NULL;
23224 
23225 	/* Quick check without acquiring the lock. */
23226 	if (tcp_hsp_hash == NULL)
23227 		return (NULL);
23228 
23229 	rw_enter(&tcp_hsp_lock, RW_READER);
23230 
23231 	/* This routine finds the best-matching HSP for address addr. */
23232 
23233 	if (tcp_hsp_hash) {
23234 		int i;
23235 		ipaddr_t srchaddr;
23236 		tcp_hsp_t *hsp_net;
23237 
23238 		/* We do three passes: host, network, and subnet. */
23239 
23240 		srchaddr = addr;
23241 
23242 		for (i = 1; i <= 3; i++) {
23243 			/* Look for exact match on srchaddr */
23244 
23245 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
23246 			while (hsp) {
23247 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
23248 				    hsp->tcp_hsp_addr == srchaddr)
23249 					break;
23250 				hsp = hsp->tcp_hsp_next;
23251 			}
23252 			ASSERT(hsp == NULL ||
23253 			    hsp->tcp_hsp_vers == IPV4_VERSION);
23254 
23255 			/*
23256 			 * If this is the first pass:
23257 			 *   If we found a match, great, return it.
23258 			 *   If not, search for the network on the second pass.
23259 			 */
23260 
23261 			if (i == 1)
23262 				if (hsp)
23263 					break;
23264 				else
23265 				{
23266 					srchaddr = addr & netmask(addr);
23267 					continue;
23268 				}
23269 
23270 			/*
23271 			 * If this is the second pass:
23272 			 *   If we found a match, but there's a subnet mask,
23273 			 *    save the match but try again using the subnet
23274 			 *    mask on the third pass.
23275 			 *   Otherwise, return whatever we found.
23276 			 */
23277 
23278 			if (i == 2) {
23279 				if (hsp && hsp->tcp_hsp_subnet) {
23280 					hsp_net = hsp;
23281 					srchaddr = addr & hsp->tcp_hsp_subnet;
23282 					continue;
23283 				} else {
23284 					break;
23285 				}
23286 			}
23287 
23288 			/*
23289 			 * This must be the third pass.  If we didn't find
23290 			 * anything, return the saved network HSP instead.
23291 			 */
23292 
23293 			if (!hsp)
23294 				hsp = hsp_net;
23295 		}
23296 	}
23297 
23298 	rw_exit(&tcp_hsp_lock);
23299 	return (hsp);
23300 }
23301 
23302 /*
23303  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23304  * match lookup.
23305  */
23306 static tcp_hsp_t *
23307 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23308 {
23309 	tcp_hsp_t *hsp = NULL;
23310 
23311 	/* Quick check without acquiring the lock. */
23312 	if (tcp_hsp_hash == NULL)
23313 		return (NULL);
23314 
23315 	rw_enter(&tcp_hsp_lock, RW_READER);
23316 
23317 	/* This routine finds the best-matching HSP for address addr. */
23318 
23319 	if (tcp_hsp_hash) {
23320 		int i;
23321 		in6_addr_t v6srchaddr;
23322 		tcp_hsp_t *hsp_net;
23323 
23324 		/* We do three passes: host, network, and subnet. */
23325 
23326 		v6srchaddr = *v6addr;
23327 
23328 		for (i = 1; i <= 3; i++) {
23329 			/* Look for exact match on srchaddr */
23330 
23331 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23332 			    V4_PART_OF_V6(v6srchaddr))];
23333 			while (hsp) {
23334 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23335 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23336 				    &v6srchaddr))
23337 					break;
23338 				hsp = hsp->tcp_hsp_next;
23339 			}
23340 
23341 			/*
23342 			 * If this is the first pass:
23343 			 *   If we found a match, great, return it.
23344 			 *   If not, search for the network on the second pass.
23345 			 */
23346 
23347 			if (i == 1)
23348 				if (hsp)
23349 					break;
23350 				else {
23351 					/* Assume a 64 bit mask */
23352 					v6srchaddr.s6_addr32[0] =
23353 					    v6addr->s6_addr32[0];
23354 					v6srchaddr.s6_addr32[1] =
23355 					    v6addr->s6_addr32[1];
23356 					v6srchaddr.s6_addr32[2] = 0;
23357 					v6srchaddr.s6_addr32[3] = 0;
23358 					continue;
23359 				}
23360 
23361 			/*
23362 			 * If this is the second pass:
23363 			 *   If we found a match, but there's a subnet mask,
23364 			 *    save the match but try again using the subnet
23365 			 *    mask on the third pass.
23366 			 *   Otherwise, return whatever we found.
23367 			 */
23368 
23369 			if (i == 2) {
23370 				ASSERT(hsp == NULL ||
23371 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23372 				if (hsp &&
23373 				    !IN6_IS_ADDR_UNSPECIFIED(
23374 				    &hsp->tcp_hsp_subnet_v6)) {
23375 					hsp_net = hsp;
23376 					V6_MASK_COPY(*v6addr,
23377 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23378 					continue;
23379 				} else {
23380 					break;
23381 				}
23382 			}
23383 
23384 			/*
23385 			 * This must be the third pass.  If we didn't find
23386 			 * anything, return the saved network HSP instead.
23387 			 */
23388 
23389 			if (!hsp)
23390 				hsp = hsp_net;
23391 		}
23392 	}
23393 
23394 	rw_exit(&tcp_hsp_lock);
23395 	return (hsp);
23396 }
23397 
23398 /*
23399  * Type three generator adapted from the random() function in 4.4 BSD:
23400  */
23401 
23402 /*
23403  * Copyright (c) 1983, 1993
23404  *	The Regents of the University of California.  All rights reserved.
23405  *
23406  * Redistribution and use in source and binary forms, with or without
23407  * modification, are permitted provided that the following conditions
23408  * are met:
23409  * 1. Redistributions of source code must retain the above copyright
23410  *    notice, this list of conditions and the following disclaimer.
23411  * 2. Redistributions in binary form must reproduce the above copyright
23412  *    notice, this list of conditions and the following disclaimer in the
23413  *    documentation and/or other materials provided with the distribution.
23414  * 3. All advertising materials mentioning features or use of this software
23415  *    must display the following acknowledgement:
23416  *	This product includes software developed by the University of
23417  *	California, Berkeley and its contributors.
23418  * 4. Neither the name of the University nor the names of its contributors
23419  *    may be used to endorse or promote products derived from this software
23420  *    without specific prior written permission.
23421  *
23422  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23423  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23424  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23425  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23426  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23427  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23428  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23429  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23430  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23431  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23432  * SUCH DAMAGE.
23433  */
23434 
23435 /* Type 3 -- x**31 + x**3 + 1 */
23436 #define	DEG_3		31
23437 #define	SEP_3		3
23438 
23439 
23440 /* Protected by tcp_random_lock */
23441 static int tcp_randtbl[DEG_3 + 1];
23442 
23443 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23444 static int *tcp_random_rptr = &tcp_randtbl[1];
23445 
23446 static int *tcp_random_state = &tcp_randtbl[1];
23447 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23448 
23449 kmutex_t tcp_random_lock;
23450 
23451 void
23452 tcp_random_init(void)
23453 {
23454 	int i;
23455 	hrtime_t hrt;
23456 	time_t wallclock;
23457 	uint64_t result;
23458 
23459 	/*
23460 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23461 	 * a longlong, which may contain resolution down to nanoseconds.
23462 	 * The current time will either be a 32-bit or a 64-bit quantity.
23463 	 * XOR the two together in a 64-bit result variable.
23464 	 * Convert the result to a 32-bit value by multiplying the high-order
23465 	 * 32-bits by the low-order 32-bits.
23466 	 */
23467 
23468 	hrt = gethrtime();
23469 	(void) drv_getparm(TIME, &wallclock);
23470 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23471 	mutex_enter(&tcp_random_lock);
23472 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23473 	    (result & 0xffffffff);
23474 
23475 	for (i = 1; i < DEG_3; i++)
23476 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23477 			+ 12345;
23478 	tcp_random_fptr = &tcp_random_state[SEP_3];
23479 	tcp_random_rptr = &tcp_random_state[0];
23480 	mutex_exit(&tcp_random_lock);
23481 	for (i = 0; i < 10 * DEG_3; i++)
23482 		(void) tcp_random();
23483 }
23484 
23485 /*
23486  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23487  * This range is selected to be approximately centered on TCP_ISS / 2,
23488  * and easy to compute. We get this value by generating a 32-bit random
23489  * number, selecting out the high-order 17 bits, and then adding one so
23490  * that we never return zero.
23491  */
23492 int
23493 tcp_random(void)
23494 {
23495 	int i;
23496 
23497 	mutex_enter(&tcp_random_lock);
23498 	*tcp_random_fptr += *tcp_random_rptr;
23499 
23500 	/*
23501 	 * The high-order bits are more random than the low-order bits,
23502 	 * so we select out the high-order 17 bits and add one so that
23503 	 * we never return zero.
23504 	 */
23505 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23506 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23507 		tcp_random_fptr = tcp_random_state;
23508 		++tcp_random_rptr;
23509 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23510 		tcp_random_rptr = tcp_random_state;
23511 
23512 	mutex_exit(&tcp_random_lock);
23513 	return (i);
23514 }
23515 
23516 /*
23517  * XXX This will go away when TPI is extended to send
23518  * info reqs to sockfs/timod .....
23519  * Given a queue, set the max packet size for the write
23520  * side of the queue below stream head.  This value is
23521  * cached on the stream head.
23522  * Returns 1 on success, 0 otherwise.
23523  */
23524 static int
23525 setmaxps(queue_t *q, int maxpsz)
23526 {
23527 	struct stdata	*stp;
23528 	queue_t		*wq;
23529 	stp = STREAM(q);
23530 
23531 	/*
23532 	 * At this point change of a queue parameter is not allowed
23533 	 * when a multiplexor is sitting on top.
23534 	 */
23535 	if (stp->sd_flag & STPLEX)
23536 		return (0);
23537 
23538 	claimstr(stp->sd_wrq);
23539 	wq = stp->sd_wrq->q_next;
23540 	ASSERT(wq != NULL);
23541 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23542 	releasestr(stp->sd_wrq);
23543 	return (1);
23544 }
23545 
23546 static int
23547 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23548     int *t_errorp, int *sys_errorp)
23549 {
23550 	int error;
23551 	int is_absreq_failure;
23552 	t_scalar_t *opt_lenp;
23553 	t_scalar_t opt_offset;
23554 	int prim_type;
23555 	struct T_conn_req *tcreqp;
23556 	struct T_conn_res *tcresp;
23557 	cred_t *cr;
23558 
23559 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23560 
23561 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23562 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23563 	    prim_type == T_CONN_RES);
23564 
23565 	switch (prim_type) {
23566 	case T_CONN_REQ:
23567 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23568 		opt_offset = tcreqp->OPT_offset;
23569 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23570 		break;
23571 	case O_T_CONN_RES:
23572 	case T_CONN_RES:
23573 		tcresp = (struct T_conn_res *)mp->b_rptr;
23574 		opt_offset = tcresp->OPT_offset;
23575 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23576 		break;
23577 	}
23578 
23579 	*t_errorp = 0;
23580 	*sys_errorp = 0;
23581 	*do_disconnectp = 0;
23582 
23583 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23584 	    opt_offset, cr, &tcp_opt_obj,
23585 	    NULL, &is_absreq_failure);
23586 
23587 	switch (error) {
23588 	case  0:		/* no error */
23589 		ASSERT(is_absreq_failure == 0);
23590 		return (0);
23591 	case ENOPROTOOPT:
23592 		*t_errorp = TBADOPT;
23593 		break;
23594 	case EACCES:
23595 		*t_errorp = TACCES;
23596 		break;
23597 	default:
23598 		*t_errorp = TSYSERR; *sys_errorp = error;
23599 		break;
23600 	}
23601 	if (is_absreq_failure != 0) {
23602 		/*
23603 		 * The connection request should get the local ack
23604 		 * T_OK_ACK and then a T_DISCON_IND.
23605 		 */
23606 		*do_disconnectp = 1;
23607 	}
23608 	return (-1);
23609 }
23610 
23611 /*
23612  * Split this function out so that if the secret changes, I'm okay.
23613  *
23614  * Initialize the tcp_iss_cookie and tcp_iss_key.
23615  */
23616 
23617 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23618 
23619 static void
23620 tcp_iss_key_init(uint8_t *phrase, int len)
23621 {
23622 	struct {
23623 		int32_t current_time;
23624 		uint32_t randnum;
23625 		uint16_t pad;
23626 		uint8_t ether[6];
23627 		uint8_t passwd[PASSWD_SIZE];
23628 	} tcp_iss_cookie;
23629 	time_t t;
23630 
23631 	/*
23632 	 * Start with the current absolute time.
23633 	 */
23634 	(void) drv_getparm(TIME, &t);
23635 	tcp_iss_cookie.current_time = t;
23636 
23637 	/*
23638 	 * XXX - Need a more random number per RFC 1750, not this crap.
23639 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23640 	 */
23641 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23642 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23643 
23644 	/*
23645 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23646 	 * as a good template.
23647 	 */
23648 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23649 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23650 
23651 	/*
23652 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23653 	 */
23654 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23655 
23656 	/*
23657 	 * See 4010593 if this section becomes a problem again,
23658 	 * but the local ethernet address is useful here.
23659 	 */
23660 	(void) localetheraddr(NULL,
23661 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23662 
23663 	/*
23664 	 * Hash 'em all together.  The MD5Final is called per-connection.
23665 	 */
23666 	mutex_enter(&tcp_iss_key_lock);
23667 	MD5Init(&tcp_iss_key);
23668 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23669 	    sizeof (tcp_iss_cookie));
23670 	mutex_exit(&tcp_iss_key_lock);
23671 }
23672 
23673 /*
23674  * Set the RFC 1948 pass phrase
23675  */
23676 /* ARGSUSED */
23677 static int
23678 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23679     cred_t *cr)
23680 {
23681 	/*
23682 	 * Basically, value contains a new pass phrase.  Pass it along!
23683 	 */
23684 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23685 	return (0);
23686 }
23687 
23688 /* ARGSUSED */
23689 static int
23690 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23691 {
23692 	bzero(buf, sizeof (tcp_sack_info_t));
23693 	return (0);
23694 }
23695 
23696 /* ARGSUSED */
23697 static int
23698 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23699 {
23700 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23701 	return (0);
23702 }
23703 
23704 void
23705 tcp_ddi_init(void)
23706 {
23707 	int i;
23708 
23709 	/* Initialize locks */
23710 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23711 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23712 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23713 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23714 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23715 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23716 
23717 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23718 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23719 		    MUTEX_DEFAULT, NULL);
23720 	}
23721 
23722 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23723 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23724 		    MUTEX_DEFAULT, NULL);
23725 	}
23726 
23727 	/* TCP's IPsec code calls the packet dropper. */
23728 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23729 
23730 	if (!tcp_g_nd) {
23731 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23732 			nd_free(&tcp_g_nd);
23733 		}
23734 	}
23735 
23736 	/*
23737 	 * Note: To really walk the device tree you need the devinfo
23738 	 * pointer to your device which is only available after probe/attach.
23739 	 * The following is safe only because it uses ddi_root_node()
23740 	 */
23741 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23742 	    tcp_opt_obj.odb_opt_arr_cnt);
23743 
23744 	tcp_timercache = kmem_cache_create("tcp_timercache",
23745 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23746 	    NULL, NULL, NULL, NULL, NULL, 0);
23747 
23748 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23749 	    sizeof (tcp_sack_info_t), 0,
23750 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23751 
23752 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23753 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23754 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23755 
23756 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23757 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23758 
23759 	ip_squeue_init(tcp_squeue_add);
23760 
23761 	/* Initialize the random number generator */
23762 	tcp_random_init();
23763 
23764 	/*
23765 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23766 	 * by the boot scripts.
23767 	 *
23768 	 * Use NULL name, as the name is caught by the new lockstats.
23769 	 *
23770 	 * Initialize with some random, non-guessable string, like the global
23771 	 * T_INFO_ACK.
23772 	 */
23773 
23774 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23775 	    sizeof (tcp_g_t_info_ack));
23776 
23777 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23778 		"net", KSTAT_TYPE_NAMED,
23779 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23780 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23781 		tcp_kstat->ks_data = &tcp_statistics;
23782 		kstat_install(tcp_kstat);
23783 	}
23784 
23785 	tcp_kstat_init();
23786 }
23787 
23788 void
23789 tcp_ddi_destroy(void)
23790 {
23791 	int i;
23792 
23793 	nd_free(&tcp_g_nd);
23794 
23795 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23796 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23797 	}
23798 
23799 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23800 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23801 	}
23802 
23803 	mutex_destroy(&tcp_iss_key_lock);
23804 	rw_destroy(&tcp_hsp_lock);
23805 	mutex_destroy(&tcp_g_q_lock);
23806 	mutex_destroy(&tcp_random_lock);
23807 	mutex_destroy(&tcp_epriv_port_lock);
23808 	rw_destroy(&tcp_reserved_port_lock);
23809 
23810 	ip_drop_unregister(&tcp_dropper);
23811 
23812 	kmem_cache_destroy(tcp_timercache);
23813 	kmem_cache_destroy(tcp_sack_info_cache);
23814 	kmem_cache_destroy(tcp_iphc_cache);
23815 
23816 	tcp_kstat_fini();
23817 }
23818 
23819 /*
23820  * Generate ISS, taking into account NDD changes may happen halfway through.
23821  * (If the iss is not zero, set it.)
23822  */
23823 
23824 static void
23825 tcp_iss_init(tcp_t *tcp)
23826 {
23827 	MD5_CTX context;
23828 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23829 	uint32_t answer[4];
23830 
23831 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23832 	tcp->tcp_iss = tcp_iss_incr_extra;
23833 	switch (tcp_strong_iss) {
23834 	case 2:
23835 		mutex_enter(&tcp_iss_key_lock);
23836 		context = tcp_iss_key;
23837 		mutex_exit(&tcp_iss_key_lock);
23838 		arg.ports = tcp->tcp_ports;
23839 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23840 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23841 			    &arg.src);
23842 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23843 			    &arg.dst);
23844 		} else {
23845 			arg.src = tcp->tcp_ip6h->ip6_src;
23846 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23847 		}
23848 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23849 		MD5Final((uchar_t *)answer, &context);
23850 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23851 		/*
23852 		 * Now that we've hashed into a unique per-connection sequence
23853 		 * space, add a random increment per strong_iss == 1.  So I
23854 		 * guess we'll have to...
23855 		 */
23856 		/* FALLTHRU */
23857 	case 1:
23858 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23859 		break;
23860 	default:
23861 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23862 		break;
23863 	}
23864 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23865 	tcp->tcp_fss = tcp->tcp_iss - 1;
23866 	tcp->tcp_suna = tcp->tcp_iss;
23867 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23868 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23869 	tcp->tcp_csuna = tcp->tcp_snxt;
23870 }
23871 
23872 /*
23873  * Exported routine for extracting active tcp connection status.
23874  *
23875  * This is used by the Solaris Cluster Networking software to
23876  * gather a list of connections that need to be forwarded to
23877  * specific nodes in the cluster when configuration changes occur.
23878  *
23879  * The callback is invoked for each tcp_t structure. Returning
23880  * non-zero from the callback routine terminates the search.
23881  */
23882 int
23883 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23884 {
23885 	tcp_t *tcp;
23886 	cl_tcp_info_t	cl_tcpi;
23887 	connf_t	*connfp;
23888 	conn_t	*connp;
23889 	int	i;
23890 
23891 	ASSERT(callback != NULL);
23892 
23893 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23894 
23895 		connfp = &ipcl_globalhash_fanout[i];
23896 		connp = NULL;
23897 
23898 		while ((connp =
23899 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23900 
23901 			tcp = connp->conn_tcp;
23902 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23903 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23904 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23905 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23906 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23907 			/*
23908 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23909 			 * addresses. They are copied implicitly below as
23910 			 * mapped addresses.
23911 			 */
23912 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23913 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23914 				cl_tcpi.cl_tcpi_faddr =
23915 				    tcp->tcp_ipha->ipha_dst;
23916 			} else {
23917 				cl_tcpi.cl_tcpi_faddr_v6 =
23918 				    tcp->tcp_ip6h->ip6_dst;
23919 			}
23920 
23921 			/*
23922 			 * If the callback returns non-zero
23923 			 * we terminate the traversal.
23924 			 */
23925 			if ((*callback)(&cl_tcpi, arg) != 0) {
23926 				CONN_DEC_REF(tcp->tcp_connp);
23927 				return (1);
23928 			}
23929 		}
23930 	}
23931 
23932 	return (0);
23933 }
23934 
23935 /*
23936  * Macros used for accessing the different types of sockaddr
23937  * structures inside a tcp_ioc_abort_conn_t.
23938  */
23939 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23940 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23941 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23942 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23943 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23944 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23945 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23946 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23947 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23948 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23949 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23950 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23951 
23952 /*
23953  * Return the correct error code to mimic the behavior
23954  * of a connection reset.
23955  */
23956 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23957 		switch ((state)) {		\
23958 		case TCPS_SYN_SENT:		\
23959 		case TCPS_SYN_RCVD:		\
23960 			(err) = ECONNREFUSED;	\
23961 			break;			\
23962 		case TCPS_ESTABLISHED:		\
23963 		case TCPS_FIN_WAIT_1:		\
23964 		case TCPS_FIN_WAIT_2:		\
23965 		case TCPS_CLOSE_WAIT:		\
23966 			(err) = ECONNRESET;	\
23967 			break;			\
23968 		case TCPS_CLOSING:		\
23969 		case TCPS_LAST_ACK:		\
23970 		case TCPS_TIME_WAIT:		\
23971 			(err) = 0;		\
23972 			break;			\
23973 		default:			\
23974 			(err) = ENXIO;		\
23975 		}				\
23976 	}
23977 
23978 /*
23979  * Check if a tcp structure matches the info in acp.
23980  */
23981 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23982 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23983 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23984 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23985 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23986 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23987 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23988 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23989 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23990 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23991 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23992 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23993 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23994 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23995 	&(tcp)->tcp_ip_src_v6)) &&				\
23996 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23997 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23998 	&(tcp)->tcp_remote_v6)) &&				\
23999 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
24000 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
24001 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
24002 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
24003 	(acp)->ac_start <= (tcp)->tcp_state &&	\
24004 	(acp)->ac_end >= (tcp)->tcp_state))
24005 
24006 #define	TCP_AC_MATCH(acp, tcp)					\
24007 	(((acp)->ac_zoneid == ALL_ZONES ||			\
24008 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
24009 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
24010 
24011 /*
24012  * Build a message containing a tcp_ioc_abort_conn_t structure
24013  * which is filled in with information from acp and tp.
24014  */
24015 static mblk_t *
24016 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
24017 {
24018 	mblk_t *mp;
24019 	tcp_ioc_abort_conn_t *tacp;
24020 
24021 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
24022 	if (mp == NULL)
24023 		return (NULL);
24024 
24025 	mp->b_datap->db_type = M_CTL;
24026 
24027 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
24028 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
24029 		sizeof (uint32_t));
24030 
24031 	tacp->ac_start = acp->ac_start;
24032 	tacp->ac_end = acp->ac_end;
24033 	tacp->ac_zoneid = acp->ac_zoneid;
24034 
24035 	if (acp->ac_local.ss_family == AF_INET) {
24036 		tacp->ac_local.ss_family = AF_INET;
24037 		tacp->ac_remote.ss_family = AF_INET;
24038 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
24039 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
24040 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
24041 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
24042 	} else {
24043 		tacp->ac_local.ss_family = AF_INET6;
24044 		tacp->ac_remote.ss_family = AF_INET6;
24045 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
24046 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
24047 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
24048 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
24049 	}
24050 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
24051 	return (mp);
24052 }
24053 
24054 /*
24055  * Print a tcp_ioc_abort_conn_t structure.
24056  */
24057 static void
24058 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
24059 {
24060 	char lbuf[128];
24061 	char rbuf[128];
24062 	sa_family_t af;
24063 	in_port_t lport, rport;
24064 	ushort_t logflags;
24065 
24066 	af = acp->ac_local.ss_family;
24067 
24068 	if (af == AF_INET) {
24069 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
24070 				lbuf, 128);
24071 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
24072 				rbuf, 128);
24073 		lport = ntohs(TCP_AC_V4LPORT(acp));
24074 		rport = ntohs(TCP_AC_V4RPORT(acp));
24075 	} else {
24076 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
24077 				lbuf, 128);
24078 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
24079 				rbuf, 128);
24080 		lport = ntohs(TCP_AC_V6LPORT(acp));
24081 		rport = ntohs(TCP_AC_V6RPORT(acp));
24082 	}
24083 
24084 	logflags = SL_TRACE | SL_NOTE;
24085 	/*
24086 	 * Don't print this message to the console if the operation was done
24087 	 * to a non-global zone.
24088 	 */
24089 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24090 		logflags |= SL_CONSOLE;
24091 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
24092 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
24093 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
24094 		acp->ac_start, acp->ac_end);
24095 }
24096 
24097 /*
24098  * Called inside tcp_rput when a message built using
24099  * tcp_ioctl_abort_build_msg is put into a queue.
24100  * Note that when we get here there is no wildcard in acp any more.
24101  */
24102 static void
24103 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
24104 {
24105 	tcp_ioc_abort_conn_t *acp;
24106 
24107 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
24108 	if (tcp->tcp_state <= acp->ac_end) {
24109 		/*
24110 		 * If we get here, we are already on the correct
24111 		 * squeue. This ioctl follows the following path
24112 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
24113 		 * ->tcp_ioctl_abort->squeue_fill (if on a
24114 		 * different squeue)
24115 		 */
24116 		int errcode;
24117 
24118 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
24119 		(void) tcp_clean_death(tcp, errcode, 26);
24120 	}
24121 	freemsg(mp);
24122 }
24123 
24124 /*
24125  * Abort all matching connections on a hash chain.
24126  */
24127 static int
24128 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
24129     boolean_t exact)
24130 {
24131 	int nmatch, err = 0;
24132 	tcp_t *tcp;
24133 	MBLKP mp, last, listhead = NULL;
24134 	conn_t	*tconnp;
24135 	connf_t	*connfp = &ipcl_conn_fanout[index];
24136 
24137 startover:
24138 	nmatch = 0;
24139 
24140 	mutex_enter(&connfp->connf_lock);
24141 	for (tconnp = connfp->connf_head; tconnp != NULL;
24142 	    tconnp = tconnp->conn_next) {
24143 		tcp = tconnp->conn_tcp;
24144 		if (TCP_AC_MATCH(acp, tcp)) {
24145 			CONN_INC_REF(tcp->tcp_connp);
24146 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
24147 			if (mp == NULL) {
24148 				err = ENOMEM;
24149 				CONN_DEC_REF(tcp->tcp_connp);
24150 				break;
24151 			}
24152 			mp->b_prev = (mblk_t *)tcp;
24153 
24154 			if (listhead == NULL) {
24155 				listhead = mp;
24156 				last = mp;
24157 			} else {
24158 				last->b_next = mp;
24159 				last = mp;
24160 			}
24161 			nmatch++;
24162 			if (exact)
24163 				break;
24164 		}
24165 
24166 		/* Avoid holding lock for too long. */
24167 		if (nmatch >= 500)
24168 			break;
24169 	}
24170 	mutex_exit(&connfp->connf_lock);
24171 
24172 	/* Pass mp into the correct tcp */
24173 	while ((mp = listhead) != NULL) {
24174 		listhead = listhead->b_next;
24175 		tcp = (tcp_t *)mp->b_prev;
24176 		mp->b_next = mp->b_prev = NULL;
24177 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
24178 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
24179 	}
24180 
24181 	*count += nmatch;
24182 	if (nmatch >= 500 && err == 0)
24183 		goto startover;
24184 	return (err);
24185 }
24186 
24187 /*
24188  * Abort all connections that matches the attributes specified in acp.
24189  */
24190 static int
24191 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
24192 {
24193 	sa_family_t af;
24194 	uint32_t  ports;
24195 	uint16_t *pports;
24196 	int err = 0, count = 0;
24197 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
24198 	int index = -1;
24199 	ushort_t logflags;
24200 
24201 	af = acp->ac_local.ss_family;
24202 
24203 	if (af == AF_INET) {
24204 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
24205 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
24206 			pports = (uint16_t *)&ports;
24207 			pports[1] = TCP_AC_V4LPORT(acp);
24208 			pports[0] = TCP_AC_V4RPORT(acp);
24209 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
24210 		}
24211 	} else {
24212 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
24213 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
24214 			pports = (uint16_t *)&ports;
24215 			pports[1] = TCP_AC_V6LPORT(acp);
24216 			pports[0] = TCP_AC_V6RPORT(acp);
24217 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
24218 		}
24219 	}
24220 
24221 	/*
24222 	 * For cases where remote addr, local port, and remote port are non-
24223 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
24224 	 */
24225 	if (index != -1) {
24226 		err = tcp_ioctl_abort_bucket(acp, index,
24227 			    &count, exact);
24228 	} else {
24229 		/*
24230 		 * loop through all entries for wildcard case
24231 		 */
24232 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
24233 			err = tcp_ioctl_abort_bucket(acp, index,
24234 			    &count, exact);
24235 			if (err != 0)
24236 				break;
24237 		}
24238 	}
24239 
24240 	logflags = SL_TRACE | SL_NOTE;
24241 	/*
24242 	 * Don't print this message to the console if the operation was done
24243 	 * to a non-global zone.
24244 	 */
24245 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
24246 		logflags |= SL_CONSOLE;
24247 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
24248 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
24249 	if (err == 0 && count == 0)
24250 		err = ENOENT;
24251 	return (err);
24252 }
24253 
24254 /*
24255  * Process the TCP_IOC_ABORT_CONN ioctl request.
24256  */
24257 static void
24258 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
24259 {
24260 	int	err;
24261 	IOCP    iocp;
24262 	MBLKP   mp1;
24263 	sa_family_t laf, raf;
24264 	tcp_ioc_abort_conn_t *acp;
24265 	zone_t *zptr;
24266 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
24267 
24268 	iocp = (IOCP)mp->b_rptr;
24269 
24270 	if ((mp1 = mp->b_cont) == NULL ||
24271 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
24272 		err = EINVAL;
24273 		goto out;
24274 	}
24275 
24276 	/* check permissions */
24277 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
24278 		err = EPERM;
24279 		goto out;
24280 	}
24281 
24282 	if (mp1->b_cont != NULL) {
24283 		freemsg(mp1->b_cont);
24284 		mp1->b_cont = NULL;
24285 	}
24286 
24287 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
24288 	laf = acp->ac_local.ss_family;
24289 	raf = acp->ac_remote.ss_family;
24290 
24291 	/* check that a zone with the supplied zoneid exists */
24292 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
24293 		zptr = zone_find_by_id(zoneid);
24294 		if (zptr != NULL) {
24295 			zone_rele(zptr);
24296 		} else {
24297 			err = EINVAL;
24298 			goto out;
24299 		}
24300 	}
24301 
24302 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24303 	    acp->ac_start > acp->ac_end || laf != raf ||
24304 	    (laf != AF_INET && laf != AF_INET6)) {
24305 		err = EINVAL;
24306 		goto out;
24307 	}
24308 
24309 	tcp_ioctl_abort_dump(acp);
24310 	err = tcp_ioctl_abort(acp);
24311 
24312 out:
24313 	if (mp1 != NULL) {
24314 		freemsg(mp1);
24315 		mp->b_cont = NULL;
24316 	}
24317 
24318 	if (err != 0)
24319 		miocnak(q, mp, 0, err);
24320 	else
24321 		miocack(q, mp, 0, 0);
24322 }
24323 
24324 /*
24325  * tcp_time_wait_processing() handles processing of incoming packets when
24326  * the tcp is in the TIME_WAIT state.
24327  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24328  * on the time wait list.
24329  */
24330 void
24331 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24332     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24333 {
24334 	int32_t		bytes_acked;
24335 	int32_t		gap;
24336 	int32_t		rgap;
24337 	tcp_opt_t	tcpopt;
24338 	uint_t		flags;
24339 	uint32_t	new_swnd = 0;
24340 	conn_t		*connp;
24341 
24342 	BUMP_LOCAL(tcp->tcp_ibsegs);
24343 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24344 
24345 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24346 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24347 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24348 	if (tcp->tcp_snd_ts_ok) {
24349 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24350 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24351 			    tcp->tcp_rnxt, TH_ACK);
24352 			goto done;
24353 		}
24354 	}
24355 	gap = seg_seq - tcp->tcp_rnxt;
24356 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24357 	if (gap < 0) {
24358 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24359 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24360 		    (seg_len > -gap ? -gap : seg_len));
24361 		seg_len += gap;
24362 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24363 			if (flags & TH_RST) {
24364 				goto done;
24365 			}
24366 			if ((flags & TH_FIN) && seg_len == -1) {
24367 				/*
24368 				 * When TCP receives a duplicate FIN in
24369 				 * TIME_WAIT state, restart the 2 MSL timer.
24370 				 * See page 73 in RFC 793. Make sure this TCP
24371 				 * is already on the TIME_WAIT list. If not,
24372 				 * just restart the timer.
24373 				 */
24374 				if (TCP_IS_DETACHED(tcp)) {
24375 					tcp_time_wait_remove(tcp, NULL);
24376 					tcp_time_wait_append(tcp);
24377 					TCP_DBGSTAT(tcp_rput_time_wait);
24378 				} else {
24379 					ASSERT(tcp != NULL);
24380 					TCP_TIMER_RESTART(tcp,
24381 					    tcp_time_wait_interval);
24382 				}
24383 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24384 				    tcp->tcp_rnxt, TH_ACK);
24385 				goto done;
24386 			}
24387 			flags |=  TH_ACK_NEEDED;
24388 			seg_len = 0;
24389 			goto process_ack;
24390 		}
24391 
24392 		/* Fix seg_seq, and chew the gap off the front. */
24393 		seg_seq = tcp->tcp_rnxt;
24394 	}
24395 
24396 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24397 		/*
24398 		 * Make sure that when we accept the connection, pick
24399 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24400 		 * old connection.
24401 		 *
24402 		 * The next ISS generated is equal to tcp_iss_incr_extra
24403 		 * + ISS_INCR/2 + other components depending on the
24404 		 * value of tcp_strong_iss.  We pre-calculate the new
24405 		 * ISS here and compare with tcp_snxt to determine if
24406 		 * we need to make adjustment to tcp_iss_incr_extra.
24407 		 *
24408 		 * The above calculation is ugly and is a
24409 		 * waste of CPU cycles...
24410 		 */
24411 		uint32_t new_iss = tcp_iss_incr_extra;
24412 		int32_t adj;
24413 
24414 		switch (tcp_strong_iss) {
24415 		case 2: {
24416 			/* Add time and MD5 components. */
24417 			uint32_t answer[4];
24418 			struct {
24419 				uint32_t ports;
24420 				in6_addr_t src;
24421 				in6_addr_t dst;
24422 			} arg;
24423 			MD5_CTX context;
24424 
24425 			mutex_enter(&tcp_iss_key_lock);
24426 			context = tcp_iss_key;
24427 			mutex_exit(&tcp_iss_key_lock);
24428 			arg.ports = tcp->tcp_ports;
24429 			/* We use MAPPED addresses in tcp_iss_init */
24430 			arg.src = tcp->tcp_ip_src_v6;
24431 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24432 				IN6_IPADDR_TO_V4MAPPED(
24433 					tcp->tcp_ipha->ipha_dst,
24434 					    &arg.dst);
24435 			} else {
24436 				arg.dst =
24437 				    tcp->tcp_ip6h->ip6_dst;
24438 			}
24439 			MD5Update(&context, (uchar_t *)&arg,
24440 			    sizeof (arg));
24441 			MD5Final((uchar_t *)answer, &context);
24442 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24443 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24444 			break;
24445 		}
24446 		case 1:
24447 			/* Add time component and min random (i.e. 1). */
24448 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24449 			break;
24450 		default:
24451 			/* Add only time component. */
24452 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24453 			break;
24454 		}
24455 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24456 			/*
24457 			 * New ISS not guaranteed to be ISS_INCR/2
24458 			 * ahead of the current tcp_snxt, so add the
24459 			 * difference to tcp_iss_incr_extra.
24460 			 */
24461 			tcp_iss_incr_extra += adj;
24462 		}
24463 		/*
24464 		 * If tcp_clean_death() can not perform the task now,
24465 		 * drop the SYN packet and let the other side re-xmit.
24466 		 * Otherwise pass the SYN packet back in, since the
24467 		 * old tcp state has been cleaned up or freed.
24468 		 */
24469 		if (tcp_clean_death(tcp, 0, 27) == -1)
24470 			goto done;
24471 		/*
24472 		 * We will come back to tcp_rput_data
24473 		 * on the global queue. Packets destined
24474 		 * for the global queue will be checked
24475 		 * with global policy. But the policy for
24476 		 * this packet has already been checked as
24477 		 * this was destined for the detached
24478 		 * connection. We need to bypass policy
24479 		 * check this time by attaching a dummy
24480 		 * ipsec_in with ipsec_in_dont_check set.
24481 		 */
24482 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24483 		    NULL) {
24484 			TCP_STAT(tcp_time_wait_syn_success);
24485 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24486 			return;
24487 		}
24488 		goto done;
24489 	}
24490 
24491 	/*
24492 	 * rgap is the amount of stuff received out of window.  A negative
24493 	 * value is the amount out of window.
24494 	 */
24495 	if (rgap < 0) {
24496 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24497 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24498 		/* Fix seg_len and make sure there is something left. */
24499 		seg_len += rgap;
24500 		if (seg_len <= 0) {
24501 			if (flags & TH_RST) {
24502 				goto done;
24503 			}
24504 			flags |=  TH_ACK_NEEDED;
24505 			seg_len = 0;
24506 			goto process_ack;
24507 		}
24508 	}
24509 	/*
24510 	 * Check whether we can update tcp_ts_recent.  This test is
24511 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24512 	 * Extensions for High Performance: An Update", Internet Draft.
24513 	 */
24514 	if (tcp->tcp_snd_ts_ok &&
24515 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24516 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24517 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24518 		tcp->tcp_last_rcv_lbolt = lbolt64;
24519 	}
24520 
24521 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24522 		/* Always ack out of order packets */
24523 		flags |= TH_ACK_NEEDED;
24524 		seg_len = 0;
24525 	} else if (seg_len > 0) {
24526 		BUMP_MIB(&tcp_mib, tcpInClosed);
24527 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24528 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24529 	}
24530 	if (flags & TH_RST) {
24531 		(void) tcp_clean_death(tcp, 0, 28);
24532 		goto done;
24533 	}
24534 	if (flags & TH_SYN) {
24535 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24536 		    TH_RST|TH_ACK);
24537 		/*
24538 		 * Do not delete the TCP structure if it is in
24539 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24540 		 */
24541 		goto done;
24542 	}
24543 process_ack:
24544 	if (flags & TH_ACK) {
24545 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24546 		if (bytes_acked <= 0) {
24547 			if (bytes_acked == 0 && seg_len == 0 &&
24548 			    new_swnd == tcp->tcp_swnd)
24549 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24550 		} else {
24551 			/* Acks something not sent */
24552 			flags |= TH_ACK_NEEDED;
24553 		}
24554 	}
24555 	if (flags & TH_ACK_NEEDED) {
24556 		/*
24557 		 * Time to send an ack for some reason.
24558 		 */
24559 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24560 		    tcp->tcp_rnxt, TH_ACK);
24561 	}
24562 done:
24563 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24564 		DB_CKSUMSTART(mp) = 0;
24565 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24566 		TCP_STAT(tcp_time_wait_syn_fail);
24567 	}
24568 	freemsg(mp);
24569 }
24570 
24571 /*
24572  * Allocate a T_SVR4_OPTMGMT_REQ.
24573  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24574  * that tcp_rput_other can drop the acks.
24575  */
24576 static mblk_t *
24577 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24578 {
24579 	mblk_t *mp;
24580 	struct T_optmgmt_req *tor;
24581 	struct opthdr *oh;
24582 	uint_t size;
24583 	char *optptr;
24584 
24585 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24586 	mp = allocb(size, BPRI_MED);
24587 	if (mp == NULL)
24588 		return (NULL);
24589 
24590 	mp->b_wptr += size;
24591 	mp->b_datap->db_type = M_PROTO;
24592 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24593 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24594 	tor->MGMT_flags = T_NEGOTIATE;
24595 	tor->OPT_length = sizeof (*oh) + optlen;
24596 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24597 
24598 	oh = (struct opthdr *)&tor[1];
24599 	oh->level = level;
24600 	oh->name = cmd;
24601 	oh->len = optlen;
24602 	if (optlen != 0) {
24603 		optptr = (char *)&oh[1];
24604 		bcopy(opt, optptr, optlen);
24605 	}
24606 	return (mp);
24607 }
24608 
24609 /*
24610  * TCP Timers Implementation.
24611  */
24612 timeout_id_t
24613 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24614 {
24615 	mblk_t *mp;
24616 	tcp_timer_t *tcpt;
24617 	tcp_t *tcp = connp->conn_tcp;
24618 
24619 	ASSERT(connp->conn_sqp != NULL);
24620 
24621 	TCP_DBGSTAT(tcp_timeout_calls);
24622 
24623 	if (tcp->tcp_timercache == NULL) {
24624 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24625 	} else {
24626 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24627 		mp = tcp->tcp_timercache;
24628 		tcp->tcp_timercache = mp->b_next;
24629 		mp->b_next = NULL;
24630 		ASSERT(mp->b_wptr == NULL);
24631 	}
24632 
24633 	CONN_INC_REF(connp);
24634 	tcpt = (tcp_timer_t *)mp->b_rptr;
24635 	tcpt->connp = connp;
24636 	tcpt->tcpt_proc = f;
24637 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24638 	return ((timeout_id_t)mp);
24639 }
24640 
24641 static void
24642 tcp_timer_callback(void *arg)
24643 {
24644 	mblk_t *mp = (mblk_t *)arg;
24645 	tcp_timer_t *tcpt;
24646 	conn_t	*connp;
24647 
24648 	tcpt = (tcp_timer_t *)mp->b_rptr;
24649 	connp = tcpt->connp;
24650 	squeue_fill(connp->conn_sqp, mp,
24651 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24652 }
24653 
24654 static void
24655 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24656 {
24657 	tcp_timer_t *tcpt;
24658 	conn_t *connp = (conn_t *)arg;
24659 	tcp_t *tcp = connp->conn_tcp;
24660 
24661 	tcpt = (tcp_timer_t *)mp->b_rptr;
24662 	ASSERT(connp == tcpt->connp);
24663 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24664 
24665 	/*
24666 	 * If the TCP has reached the closed state, don't proceed any
24667 	 * further. This TCP logically does not exist on the system.
24668 	 * tcpt_proc could for example access queues, that have already
24669 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24670 	 */
24671 	if (tcp->tcp_state != TCPS_CLOSED) {
24672 		(*tcpt->tcpt_proc)(connp);
24673 	} else {
24674 		tcp->tcp_timer_tid = 0;
24675 	}
24676 	tcp_timer_free(connp->conn_tcp, mp);
24677 }
24678 
24679 /*
24680  * There is potential race with untimeout and the handler firing at the same
24681  * time. The mblock may be freed by the handler while we are trying to use
24682  * it. But since both should execute on the same squeue, this race should not
24683  * occur.
24684  */
24685 clock_t
24686 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24687 {
24688 	mblk_t	*mp = (mblk_t *)id;
24689 	tcp_timer_t *tcpt;
24690 	clock_t delta;
24691 
24692 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24693 
24694 	if (mp == NULL)
24695 		return (-1);
24696 
24697 	tcpt = (tcp_timer_t *)mp->b_rptr;
24698 	ASSERT(tcpt->connp == connp);
24699 
24700 	delta = untimeout(tcpt->tcpt_tid);
24701 
24702 	if (delta >= 0) {
24703 		TCP_DBGSTAT(tcp_timeout_canceled);
24704 		tcp_timer_free(connp->conn_tcp, mp);
24705 		CONN_DEC_REF(connp);
24706 	}
24707 
24708 	return (delta);
24709 }
24710 
24711 /*
24712  * Allocate space for the timer event. The allocation looks like mblk, but it is
24713  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24714  *
24715  * Dealing with failures: If we can't allocate from the timer cache we try
24716  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24717  * points to b_rptr.
24718  * If we can't allocate anything using allocb_tryhard(), we perform a last
24719  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24720  * save the actual allocation size in b_datap.
24721  */
24722 mblk_t *
24723 tcp_timermp_alloc(int kmflags)
24724 {
24725 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24726 	    kmflags & ~KM_PANIC);
24727 
24728 	if (mp != NULL) {
24729 		mp->b_next = mp->b_prev = NULL;
24730 		mp->b_rptr = (uchar_t *)(&mp[1]);
24731 		mp->b_wptr = NULL;
24732 		mp->b_datap = NULL;
24733 		mp->b_queue = NULL;
24734 	} else if (kmflags & KM_PANIC) {
24735 		/*
24736 		 * Failed to allocate memory for the timer. Try allocating from
24737 		 * dblock caches.
24738 		 */
24739 		TCP_STAT(tcp_timermp_allocfail);
24740 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24741 		if (mp == NULL) {
24742 			size_t size = 0;
24743 			/*
24744 			 * Memory is really low. Try tryhard allocation.
24745 			 */
24746 			TCP_STAT(tcp_timermp_allocdblfail);
24747 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24748 			    sizeof (tcp_timer_t), &size, kmflags);
24749 			mp->b_rptr = (uchar_t *)(&mp[1]);
24750 			mp->b_next = mp->b_prev = NULL;
24751 			mp->b_wptr = (uchar_t *)-1;
24752 			mp->b_datap = (dblk_t *)size;
24753 			mp->b_queue = NULL;
24754 		}
24755 		ASSERT(mp->b_wptr != NULL);
24756 	}
24757 	TCP_DBGSTAT(tcp_timermp_alloced);
24758 
24759 	return (mp);
24760 }
24761 
24762 /*
24763  * Free per-tcp timer cache.
24764  * It can only contain entries from tcp_timercache.
24765  */
24766 void
24767 tcp_timermp_free(tcp_t *tcp)
24768 {
24769 	mblk_t *mp;
24770 
24771 	while ((mp = tcp->tcp_timercache) != NULL) {
24772 		ASSERT(mp->b_wptr == NULL);
24773 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24774 		kmem_cache_free(tcp_timercache, mp);
24775 	}
24776 }
24777 
24778 /*
24779  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24780  * events there already (currently at most two events are cached).
24781  * If the event is not allocated from the timer cache, free it right away.
24782  */
24783 static void
24784 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24785 {
24786 	mblk_t *mp1 = tcp->tcp_timercache;
24787 
24788 	if (mp->b_wptr != NULL) {
24789 		/*
24790 		 * This allocation is not from a timer cache, free it right
24791 		 * away.
24792 		 */
24793 		if (mp->b_wptr != (uchar_t *)-1)
24794 			freeb(mp);
24795 		else
24796 			kmem_free(mp, (size_t)mp->b_datap);
24797 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24798 		/* Cache this timer block for future allocations */
24799 		mp->b_rptr = (uchar_t *)(&mp[1]);
24800 		mp->b_next = mp1;
24801 		tcp->tcp_timercache = mp;
24802 	} else {
24803 		kmem_cache_free(tcp_timercache, mp);
24804 		TCP_DBGSTAT(tcp_timermp_freed);
24805 	}
24806 }
24807 
24808 /*
24809  * End of TCP Timers implementation.
24810  */
24811 
24812 /*
24813  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24814  * on the specified backing STREAMS q. Note, the caller may make the
24815  * decision to call based on the tcp_t.tcp_flow_stopped value which
24816  * when check outside the q's lock is only an advisory check ...
24817  */
24818 
24819 void
24820 tcp_setqfull(tcp_t *tcp)
24821 {
24822 	queue_t *q = tcp->tcp_wq;
24823 
24824 	if (!(q->q_flag & QFULL)) {
24825 		mutex_enter(QLOCK(q));
24826 		if (!(q->q_flag & QFULL)) {
24827 			/* still need to set QFULL */
24828 			q->q_flag |= QFULL;
24829 			tcp->tcp_flow_stopped = B_TRUE;
24830 			mutex_exit(QLOCK(q));
24831 			TCP_STAT(tcp_flwctl_on);
24832 		} else {
24833 			mutex_exit(QLOCK(q));
24834 		}
24835 	}
24836 }
24837 
24838 void
24839 tcp_clrqfull(tcp_t *tcp)
24840 {
24841 	queue_t *q = tcp->tcp_wq;
24842 
24843 	if (q->q_flag & QFULL) {
24844 		mutex_enter(QLOCK(q));
24845 		if (q->q_flag & QFULL) {
24846 			q->q_flag &= ~QFULL;
24847 			tcp->tcp_flow_stopped = B_FALSE;
24848 			mutex_exit(QLOCK(q));
24849 			if (q->q_flag & QWANTW)
24850 				qbackenable(q, 0);
24851 		} else {
24852 			mutex_exit(QLOCK(q));
24853 		}
24854 	}
24855 }
24856 
24857 /*
24858  * TCP Kstats implementation
24859  */
24860 static void
24861 tcp_kstat_init(void)
24862 {
24863 	tcp_named_kstat_t template = {
24864 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24865 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24866 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24867 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24868 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24869 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24870 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24871 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24872 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24873 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24874 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24875 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24876 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24877 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24878 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24879 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24880 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24881 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24882 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24883 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24884 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24885 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24886 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24887 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24888 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24889 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24890 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24891 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24892 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24893 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24894 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24895 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24896 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24897 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24898 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24899 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24900 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24901 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24902 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24903 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24904 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24905 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24906 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24907 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24908 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24909 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24910 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24911 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24912 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24913 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24914 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24915 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24916 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24917 	};
24918 
24919 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24920 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24921 
24922 	if (tcp_mibkp == NULL)
24923 		return;
24924 
24925 	template.rtoAlgorithm.value.ui32 = 4;
24926 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24927 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24928 	template.maxConn.value.i32 = -1;
24929 
24930 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24931 
24932 	tcp_mibkp->ks_update = tcp_kstat_update;
24933 
24934 	kstat_install(tcp_mibkp);
24935 }
24936 
24937 static void
24938 tcp_kstat_fini(void)
24939 {
24940 
24941 	if (tcp_mibkp != NULL) {
24942 		kstat_delete(tcp_mibkp);
24943 		tcp_mibkp = NULL;
24944 	}
24945 }
24946 
24947 static int
24948 tcp_kstat_update(kstat_t *kp, int rw)
24949 {
24950 	tcp_named_kstat_t	*tcpkp;
24951 	tcp_t			*tcp;
24952 	connf_t			*connfp;
24953 	conn_t			*connp;
24954 	int 			i;
24955 
24956 	if (!kp || !kp->ks_data)
24957 		return (EIO);
24958 
24959 	if (rw == KSTAT_WRITE)
24960 		return (EACCES);
24961 
24962 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24963 
24964 	tcpkp->currEstab.value.ui32 = 0;
24965 
24966 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24967 		connfp = &ipcl_globalhash_fanout[i];
24968 		connp = NULL;
24969 		while ((connp =
24970 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24971 			tcp = connp->conn_tcp;
24972 			switch (tcp_snmp_state(tcp)) {
24973 			case MIB2_TCP_established:
24974 			case MIB2_TCP_closeWait:
24975 				tcpkp->currEstab.value.ui32++;
24976 				break;
24977 			}
24978 		}
24979 	}
24980 
24981 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24982 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24983 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24984 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24985 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24986 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24987 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24988 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24989 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24990 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24991 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24992 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24993 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24994 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24995 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24996 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24997 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24998 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24999 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
25000 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
25001 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
25002 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
25003 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
25004 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
25005 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
25006 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
25007 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
25008 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
25009 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
25010 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
25011 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
25012 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
25013 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
25014 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
25015 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
25016 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
25017 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
25018 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
25019 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
25020 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
25021 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
25022 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
25023 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
25024 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
25025 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
25026 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
25027 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
25028 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
25029 
25030 	return (0);
25031 }
25032 
25033 void
25034 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
25035 {
25036 	uint16_t	hdr_len;
25037 	ipha_t		*ipha;
25038 	uint8_t		*nexthdrp;
25039 	tcph_t		*tcph;
25040 
25041 	/* Already has an eager */
25042 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25043 		TCP_STAT(tcp_reinput_syn);
25044 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
25045 		    connp, SQTAG_TCP_REINPUT_EAGER);
25046 		return;
25047 	}
25048 
25049 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
25050 	case IPV4_VERSION:
25051 		ipha = (ipha_t *)mp->b_rptr;
25052 		hdr_len = IPH_HDR_LENGTH(ipha);
25053 		break;
25054 	case IPV6_VERSION:
25055 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
25056 		    &hdr_len, &nexthdrp)) {
25057 			CONN_DEC_REF(connp);
25058 			freemsg(mp);
25059 			return;
25060 		}
25061 		break;
25062 	}
25063 
25064 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
25065 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
25066 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
25067 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
25068 	}
25069 
25070 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
25071 	    SQTAG_TCP_REINPUT);
25072 }
25073 
25074 static squeue_func_t
25075 tcp_squeue_switch(int val)
25076 {
25077 	squeue_func_t rval = squeue_fill;
25078 
25079 	switch (val) {
25080 	case 1:
25081 		rval = squeue_enter_nodrain;
25082 		break;
25083 	case 2:
25084 		rval = squeue_enter;
25085 		break;
25086 	default:
25087 		break;
25088 	}
25089 	return (rval);
25090 }
25091 
25092 static void
25093 tcp_squeue_add(squeue_t *sqp)
25094 {
25095 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
25096 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
25097 
25098 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
25099 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
25100 	    sqp, TCP_TIME_WAIT_DELAY);
25101 	if (tcp_free_list_max_cnt == 0) {
25102 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
25103 			max_ncpus : boot_max_ncpus);
25104 
25105 		/*
25106 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
25107 		 */
25108 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
25109 			(tcp_ncpus * sizeof (tcp_t) * 100);
25110 	}
25111 	tcp_time_wait->tcp_free_list_cnt = 0;
25112 }
25113