xref: /titanic_44/usr/src/uts/common/inet/tcp/tcp.c (revision 7c091311807f3a8bb543af90b74bed749c0d243e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 const char tcp_version[] = "%Z%%M%	%I%	%E% SMI";
31 
32 #include <sys/types.h>
33 #include <sys/stream.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/stropts.h>
37 #include <sys/strlog.h>
38 #include <sys/strsun.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/suntpi.h>
45 #include <sys/xti_inet.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/ethernet.h>
51 #include <sys/cpuvar.h>
52 #include <sys/dlpi.h>
53 #include <sys/multidata.h>
54 #include <sys/multidata_impl.h>
55 #include <sys/pattr.h>
56 #include <sys/policy.h>
57 #include <sys/zone.h>
58 
59 #include <sys/errno.h>
60 #include <sys/signal.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <netinet/in.h>
67 #include <netinet/tcp.h>
68 #include <netinet/ip6.h>
69 #include <netinet/icmp6.h>
70 #include <net/if.h>
71 #include <net/route.h>
72 #include <inet/ipsec_impl.h>
73 
74 #include <inet/common.h>
75 #include <inet/ip.h>
76 #include <inet/ip_impl.h>
77 #include <inet/ip6.h>
78 #include <inet/ip_ndp.h>
79 #include <inet/mi.h>
80 #include <inet/mib2.h>
81 #include <inet/nd.h>
82 #include <inet/optcom.h>
83 #include <inet/snmpcom.h>
84 #include <inet/kstatcom.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipsec_info.h>
89 #include <inet/ipdrop.h>
90 #include <inet/tcp_trace.h>
91 
92 #include <inet/ipclassifier.h>
93 #include <inet/ip_ire.h>
94 #include <inet/ip_if.h>
95 #include <inet/ipp_common.h>
96 #include <sys/squeue.h>
97 #include <inet/kssl/ksslapi.h>
98 
99 /*
100  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
101  *
102  * (Read the detailed design doc in PSARC case directory)
103  *
104  * The entire tcp state is contained in tcp_t and conn_t structure
105  * which are allocated in tandem using ipcl_conn_create() and passing
106  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
107  * the references on the tcp_t. The tcp_t structure is never compressed
108  * and packets always land on the correct TCP perimeter from the time
109  * eager is created till the time tcp_t dies (as such the old mentat
110  * TCP global queue is not used for detached state and no IPSEC checking
111  * is required). The global queue is still allocated to send out resets
112  * for connection which have no listeners and IP directly calls
113  * tcp_xmit_listeners_reset() which does any policy check.
114  *
115  * Protection and Synchronisation mechanism:
116  *
117  * The tcp data structure does not use any kind of lock for protecting
118  * its state but instead uses 'squeues' for mutual exclusion from various
119  * read and write side threads. To access a tcp member, the thread should
120  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
121  * squeue_fill). Since the squeues allow a direct function call, caller
122  * can pass any tcp function having prototype of edesc_t as argument
123  * (different from traditional STREAMs model where packets come in only
124  * designated entry points). The list of functions that can be directly
125  * called via squeue are listed before the usual function prototype.
126  *
127  * Referencing:
128  *
129  * TCP is MT-Hot and we use a reference based scheme to make sure that the
130  * tcp structure doesn't disappear when its needed. When the application
131  * creates an outgoing connection or accepts an incoming connection, we
132  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
133  * The IP reference is just a symbolic reference since ip_tcpclose()
134  * looks at tcp structure after tcp_close_output() returns which could
135  * have dropped the last TCP reference. So as long as the connection is
136  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
137  * conn_t. The classifier puts its own reference when the connection is
138  * inserted in listen or connected hash. Anytime a thread needs to enter
139  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
140  * on write side or by doing a classify on read side and then puts a
141  * reference on the conn before doing squeue_enter/tryenter/fill. For
142  * read side, the classifier itself puts the reference under fanout lock
143  * to make sure that tcp can't disappear before it gets processed. The
144  * squeue will drop this reference automatically so the called function
145  * doesn't have to do a DEC_REF.
146  *
147  * Opening a new connection:
148  *
149  * The outgoing connection open is pretty simple. ip_tcpopen() does the
150  * work in creating the conn/tcp structure and initializing it. The
151  * squeue assignment is done based on the CPU the application
152  * is running on. So for outbound connections, processing is always done
153  * on application CPU which might be different from the incoming CPU
154  * being interrupted by the NIC. An optimal way would be to figure out
155  * the NIC <-> CPU binding at listen time, and assign the outgoing
156  * connection to the squeue attached to the CPU that will be interrupted
157  * for incoming packets (we know the NIC based on the bind IP address).
158  * This might seem like a problem if more data is going out but the
159  * fact is that in most cases the transmit is ACK driven transmit where
160  * the outgoing data normally sits on TCP's xmit queue waiting to be
161  * transmitted.
162  *
163  * Accepting a connection:
164  *
165  * This is a more interesting case because of various races involved in
166  * establishing a eager in its own perimeter. Read the meta comment on
167  * top of tcp_conn_request(). But briefly, the squeue is picked by
168  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
169  *
170  * Closing a connection:
171  *
172  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
173  * via squeue to do the close and mark the tcp as detached if the connection
174  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
175  * reference but tcp_close() drop IP's reference always. So if tcp was
176  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
177  * and 1 because it is in classifier's connected hash. This is the condition
178  * we use to determine that its OK to clean up the tcp outside of squeue
179  * when time wait expires (check the ref under fanout and conn_lock and
180  * if it is 2, remove it from fanout hash and kill it).
181  *
182  * Although close just drops the necessary references and marks the
183  * tcp_detached state, tcp_close needs to know the tcp_detached has been
184  * set (under squeue) before letting the STREAM go away (because a
185  * inbound packet might attempt to go up the STREAM while the close
186  * has happened and tcp_detached is not set). So a special lock and
187  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
188  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
189  * tcp_detached.
190  *
191  * Special provisions and fast paths:
192  *
193  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
194  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
195  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
196  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
197  * check to send packets directly to tcp_rput_data via squeue. Everyone
198  * else comes through tcp_input() on the read side.
199  *
200  * We also make special provisions for sockfs by marking tcp_issocket
201  * whenever we have only sockfs on top of TCP. This allows us to skip
202  * putting the tcp in acceptor hash since a sockfs listener can never
203  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
204  * since eager has already been allocated and the accept now happens
205  * on acceptor STREAM. There is a big blob of comment on top of
206  * tcp_conn_request explaining the new accept. When socket is POP'd,
207  * sockfs sends us an ioctl to mark the fact and we go back to old
208  * behaviour. Once tcp_issocket is unset, its never set for the
209  * life of that connection.
210  *
211  * IPsec notes :
212  *
213  * Since a packet is always executed on the correct TCP perimeter
214  * all IPsec processing is defered to IP including checking new
215  * connections and setting IPSEC policies for new connection. The
216  * only exception is tcp_xmit_listeners_reset() which is called
217  * directly from IP and needs to policy check to see if TH_RST
218  * can be sent out.
219  */
220 
221 
222 extern major_t TCP6_MAJ;
223 
224 /*
225  * Values for squeue switch:
226  * 1: squeue_enter_nodrain
227  * 2: squeue_enter
228  * 3: squeue_fill
229  */
230 int tcp_squeue_close = 2;
231 int tcp_squeue_wput = 2;
232 
233 squeue_func_t tcp_squeue_close_proc;
234 squeue_func_t tcp_squeue_wput_proc;
235 
236 /*
237  * This controls how tiny a write must be before we try to copy it
238  * into the the mblk on the tail of the transmit queue.  Not much
239  * speedup is observed for values larger than sixteen.  Zero will
240  * disable the optimisation.
241  */
242 int tcp_tx_pull_len = 16;
243 
244 /*
245  * TCP Statistics.
246  *
247  * How TCP statistics work.
248  *
249  * There are two types of statistics invoked by two macros.
250  *
251  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
252  * supposed to be used in non MT-hot paths of the code.
253  *
254  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
255  * supposed to be used for DEBUG purposes and may be used on a hot path.
256  *
257  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
258  * (use "kstat tcp" to get them).
259  *
260  * There is also additional debugging facility that marks tcp_clean_death()
261  * instances and saves them in tcp_t structure. It is triggered by
262  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
263  * tcp_clean_death() calls that counts the number of times each tag was hit. It
264  * is triggered by TCP_CLD_COUNTERS define.
265  *
266  * How to add new counters.
267  *
268  * 1) Add a field in the tcp_stat structure describing your counter.
269  * 2) Add a line in tcp_statistics with the name of the counter.
270  *
271  *    IMPORTANT!! - make sure that both are in sync !!
272  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
273  *
274  * Please avoid using private counters which are not kstat-exported.
275  *
276  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
277  * in tcp_t structure.
278  *
279  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
280  */
281 
282 #ifndef TCP_DEBUG_COUNTER
283 #ifdef DEBUG
284 #define	TCP_DEBUG_COUNTER 1
285 #else
286 #define	TCP_DEBUG_COUNTER 0
287 #endif
288 #endif
289 
290 #define	TCP_CLD_COUNTERS 0
291 
292 #define	TCP_TAG_CLEAN_DEATH 1
293 #define	TCP_MAX_CLEAN_DEATH_TAG 32
294 
295 #ifdef lint
296 static int _lint_dummy_;
297 #endif
298 
299 #if TCP_CLD_COUNTERS
300 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
301 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
302 #elif defined(lint)
303 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
304 #else
305 #define	TCP_CLD_STAT(x)
306 #endif
307 
308 #if TCP_DEBUG_COUNTER
309 #define	TCP_DBGSTAT(x) atomic_add_64(&(tcp_statistics.x.value.ui64), 1)
310 #elif defined(lint)
311 #define	TCP_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
312 #else
313 #define	TCP_DBGSTAT(x)
314 #endif
315 
316 tcp_stat_t tcp_statistics = {
317 	{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
318 	{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
319 	{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
320 	{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
321 	{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
322 	{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
323 	{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
324 	{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
325 	{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
326 	{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
327 	{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
328 	{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
329 	{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
330 	{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
331 	{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
332 	{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
333 	{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
334 	{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
335 	{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
336 	{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
337 	{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
338 	{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
339 	{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
340 	{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
341 	{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
342 	{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
343 	{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
344 	{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
345 	{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
346 	{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
347 	{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
348 	{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
349 	{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
350 	{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
351 	{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
352 	{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
353 	{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
354 	{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
355 	{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
356 	{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
357 	{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
358 	{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
359 	{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
360 	{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
361 	{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
362 	{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
363 	{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
364 	{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
365 	{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
366 	{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
367 	{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
368 	{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
369 	{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
370 	{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
371 	{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
372 	{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
373 	{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
374 	{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
375 	{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
376 	{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
377 	{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
378 	{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
379 	{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
380 	{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
381 	{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
382 	{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
383 	{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
384 	{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
385 	{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
386 	{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
387 	{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
388 	{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
389 	{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
390 	{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
391 	{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
392 	{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
393 	{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
394 	{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
395 	{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
396 	{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
397 	{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
398 	{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
399 	{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
400 	{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
401 	{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
402 	{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
403 	{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
404 	{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
405 	{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
406 };
407 
408 static kstat_t *tcp_kstat;
409 
410 /*
411  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
412  * tcp write side.
413  */
414 #define	CALL_IP_WPUT(connp, q, mp) {					\
415 	ASSERT(((q)->q_flag & QREADR) == 0);				\
416 	TCP_DBGSTAT(tcp_ip_output);					\
417 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
418 }
419 
420 /* Macros for timestamp comparisons */
421 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
422 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
423 
424 /*
425  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
426  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
427  * by adding three components: a time component which grows by 1 every 4096
428  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
429  * a per-connection component which grows by 125000 for every new connection;
430  * and an "extra" component that grows by a random amount centered
431  * approximately on 64000.  This causes the the ISS generator to cycle every
432  * 4.89 hours if no TCP connections are made, and faster if connections are
433  * made.
434  *
435  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
436  * components: a time component which grows by 250000 every second; and
437  * a per-connection component which grows by 125000 for every new connections.
438  *
439  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
440  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
441  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
442  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
443  * password.
444  */
445 #define	ISS_INCR	250000
446 #define	ISS_NSEC_SHT	12
447 
448 static uint32_t tcp_iss_incr_extra;	/* Incremented for each connection */
449 static kmutex_t tcp_iss_key_lock;
450 static MD5_CTX tcp_iss_key;
451 static sin_t	sin_null;	/* Zero address for quick clears */
452 static sin6_t	sin6_null;	/* Zero address for quick clears */
453 
454 /* Packet dropper for TCP IPsec policy drops. */
455 static ipdropper_t tcp_dropper;
456 
457 /*
458  * This implementation follows the 4.3BSD interpretation of the urgent
459  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
460  * incompatible changes in protocols like telnet and rlogin.
461  */
462 #define	TCP_OLD_URP_INTERPRETATION	1
463 
464 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
465 	(TCP_IS_DETACHED(tcp) && \
466 	    (!(tcp)->tcp_hard_binding))
467 
468 /*
469  * TCP reassembly macros.  We hide starting and ending sequence numbers in
470  * b_next and b_prev of messages on the reassembly queue.  The messages are
471  * chained using b_cont.  These macros are used in tcp_reass() so we don't
472  * have to see the ugly casts and assignments.
473  */
474 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
475 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
476 					(mblk_t *)(uintptr_t)(u))
477 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
478 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
479 					(mblk_t *)(uintptr_t)(u))
480 
481 /*
482  * Implementation of TCP Timers.
483  * =============================
484  *
485  * INTERFACE:
486  *
487  * There are two basic functions dealing with tcp timers:
488  *
489  *	timeout_id_t	tcp_timeout(connp, func, time)
490  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
491  *	TCP_TIMER_RESTART(tcp, intvl)
492  *
493  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
494  * after 'time' ticks passed. The function called by timeout() must adhere to
495  * the same restrictions as a driver soft interrupt handler - it must not sleep
496  * or call other functions that might sleep. The value returned is the opaque
497  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
498  * cancel the request. The call to tcp_timeout() may fail in which case it
499  * returns zero. This is different from the timeout(9F) function which never
500  * fails.
501  *
502  * The call-back function 'func' always receives 'connp' as its single
503  * argument. It is always executed in the squeue corresponding to the tcp
504  * structure. The tcp structure is guaranteed to be present at the time the
505  * call-back is called.
506  *
507  * NOTE: The call-back function 'func' is never called if tcp is in
508  * 	the TCPS_CLOSED state.
509  *
510  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
511  * request. locks acquired by the call-back routine should not be held across
512  * the call to tcp_timeout_cancel() or a deadlock may result.
513  *
514  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
515  * Otherwise, it returns an integer value greater than or equal to 0. In
516  * particular, if the call-back function is already placed on the squeue, it can
517  * not be canceled.
518  *
519  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
520  * 	within squeue context corresponding to the tcp instance. Since the
521  *	call-back is also called via the same squeue, there are no race
522  *	conditions described in untimeout(9F) manual page since all calls are
523  *	strictly serialized.
524  *
525  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
526  *	stored in tcp_timer_tid and starts a new one using
527  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
528  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
529  *	field.
530  *
531  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
532  *	call-back may still be called, so it is possible tcp_timer() will be
533  *	called several times. This should not be a problem since tcp_timer()
534  *	should always check the tcp instance state.
535  *
536  *
537  * IMPLEMENTATION:
538  *
539  * TCP timers are implemented using three-stage process. The call to
540  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
541  * when the timer expires. The tcp_timer_callback() arranges the call of the
542  * tcp_timer_handler() function via squeue corresponding to the tcp
543  * instance. The tcp_timer_handler() calls actual requested timeout call-back
544  * and passes tcp instance as an argument to it. Information is passed between
545  * stages using the tcp_timer_t structure which contains the connp pointer, the
546  * tcp call-back to call and the timeout id returned by the timeout(9F).
547  *
548  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
549  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
550  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
551  * returns the pointer to this mblk.
552  *
553  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
554  * looks like a normal mblk without actual dblk attached to it.
555  *
556  * To optimize performance each tcp instance holds a small cache of timer
557  * mblocks. In the current implementation it caches up to two timer mblocks per
558  * tcp instance. The cache is preserved over tcp frees and is only freed when
559  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
560  * timer processing happens on a corresponding squeue, the cache manipulation
561  * does not require any locks. Experiments show that majority of timer mblocks
562  * allocations are satisfied from the tcp cache and do not involve kmem calls.
563  *
564  * The tcp_timeout() places a refhold on the connp instance which guarantees
565  * that it will be present at the time the call-back function fires. The
566  * tcp_timer_handler() drops the reference after calling the call-back, so the
567  * call-back function does not need to manipulate the references explicitly.
568  */
569 
570 typedef struct tcp_timer_s {
571 	conn_t	*connp;
572 	void 	(*tcpt_proc)(void *);
573 	timeout_id_t   tcpt_tid;
574 } tcp_timer_t;
575 
576 static kmem_cache_t *tcp_timercache;
577 kmem_cache_t	*tcp_sack_info_cache;
578 kmem_cache_t	*tcp_iphc_cache;
579 
580 /*
581  * For scalability, we must not run a timer for every TCP connection
582  * in TIME_WAIT state.  To see why, consider (for time wait interval of
583  * 4 minutes):
584  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
585  *
586  * This list is ordered by time, so you need only delete from the head
587  * until you get to entries which aren't old enough to delete yet.
588  * The list consists of only the detached TIME_WAIT connections.
589  *
590  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
591  * becomes detached TIME_WAIT (either by changing the state and already
592  * being detached or the other way around). This means that the TIME_WAIT
593  * state can be extended (up to doubled) if the connection doesn't become
594  * detached for a long time.
595  *
596  * The list manipulations (including tcp_time_wait_next/prev)
597  * are protected by the tcp_time_wait_lock. The content of the
598  * detached TIME_WAIT connections is protected by the normal perimeters.
599  */
600 
601 typedef struct tcp_squeue_priv_s {
602 	kmutex_t	tcp_time_wait_lock;
603 				/* Protects the next 3 globals */
604 	timeout_id_t	tcp_time_wait_tid;
605 	tcp_t		*tcp_time_wait_head;
606 	tcp_t		*tcp_time_wait_tail;
607 	tcp_t		*tcp_free_list;
608 	uint_t		tcp_free_list_cnt;
609 } tcp_squeue_priv_t;
610 
611 /*
612  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
613  * Running it every 5 seconds seems to give the best results.
614  */
615 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
616 
617 /*
618  * To prevent memory hog, limit the number of entries in tcp_free_list
619  * to 1% of available memory / number of cpus
620  */
621 uint_t tcp_free_list_max_cnt = 0;
622 
623 #define	TCP_XMIT_LOWATER	4096
624 #define	TCP_XMIT_HIWATER	49152
625 #define	TCP_RECV_LOWATER	2048
626 #define	TCP_RECV_HIWATER	49152
627 
628 /*
629  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
630  */
631 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
632 
633 #define	TIDUSZ	4096	/* transport interface data unit size */
634 
635 /*
636  * Bind hash list size and has function.  It has to be a power of 2 for
637  * hashing.
638  */
639 #define	TCP_BIND_FANOUT_SIZE	512
640 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
641 /*
642  * Size of listen and acceptor hash list.  It has to be a power of 2 for
643  * hashing.
644  */
645 #define	TCP_FANOUT_SIZE		256
646 
647 #ifdef	_ILP32
648 #define	TCP_ACCEPTOR_HASH(accid)					\
649 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
650 #else
651 #define	TCP_ACCEPTOR_HASH(accid)					\
652 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
653 #endif	/* _ILP32 */
654 
655 #define	IP_ADDR_CACHE_SIZE	2048
656 #define	IP_ADDR_CACHE_HASH(faddr)					\
657 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
658 
659 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
660 #define	TCP_HSP_HASH_SIZE 256
661 
662 #define	TCP_HSP_HASH(addr)					\
663 	(((addr>>24) ^ (addr >>16) ^			\
664 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
665 
666 /*
667  * TCP options struct returned from tcp_parse_options.
668  */
669 typedef struct tcp_opt_s {
670 	uint32_t	tcp_opt_mss;
671 	uint32_t	tcp_opt_wscale;
672 	uint32_t	tcp_opt_ts_val;
673 	uint32_t	tcp_opt_ts_ecr;
674 	tcp_t		*tcp;
675 } tcp_opt_t;
676 
677 /*
678  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
679  */
680 
681 #ifdef _BIG_ENDIAN
682 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
683 	(TCPOPT_TSTAMP << 8) | 10)
684 #else
685 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
686 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
687 #endif
688 
689 /*
690  * Flags returned from tcp_parse_options.
691  */
692 #define	TCP_OPT_MSS_PRESENT	1
693 #define	TCP_OPT_WSCALE_PRESENT	2
694 #define	TCP_OPT_TSTAMP_PRESENT	4
695 #define	TCP_OPT_SACK_OK_PRESENT	8
696 #define	TCP_OPT_SACK_PRESENT	16
697 
698 /* TCP option length */
699 #define	TCPOPT_NOP_LEN		1
700 #define	TCPOPT_MAXSEG_LEN	4
701 #define	TCPOPT_WS_LEN		3
702 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
703 #define	TCPOPT_TSTAMP_LEN	10
704 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
705 #define	TCPOPT_SACK_OK_LEN	2
706 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
707 #define	TCPOPT_REAL_SACK_LEN	4
708 #define	TCPOPT_MAX_SACK_LEN	36
709 #define	TCPOPT_HEADER_LEN	2
710 
711 /* TCP cwnd burst factor. */
712 #define	TCP_CWND_INFINITE	65535
713 #define	TCP_CWND_SS		3
714 #define	TCP_CWND_NORMAL		5
715 
716 /* Maximum TCP initial cwin (start/restart). */
717 #define	TCP_MAX_INIT_CWND	8
718 
719 /*
720  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
721  * either tcp_slow_start_initial or tcp_slow_start_after idle
722  * depending on the caller.  If the upper layer has not used the
723  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
724  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
725  * If the upper layer has changed set the tcp_init_cwnd, just use
726  * it to calculate the tcp_cwnd.
727  */
728 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
729 {									\
730 	if ((tcp)->tcp_init_cwnd == 0) {				\
731 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
732 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
733 	} else {							\
734 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
735 	}								\
736 	tcp->tcp_cwnd_cnt = 0;						\
737 }
738 
739 /* TCP Timer control structure */
740 typedef struct tcpt_s {
741 	pfv_t	tcpt_pfv;	/* The routine we are to call */
742 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
743 } tcpt_t;
744 
745 /* Host Specific Parameter structure */
746 typedef struct tcp_hsp {
747 	struct tcp_hsp	*tcp_hsp_next;
748 	in6_addr_t	tcp_hsp_addr_v6;
749 	in6_addr_t	tcp_hsp_subnet_v6;
750 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
751 	int32_t		tcp_hsp_sendspace;
752 	int32_t		tcp_hsp_recvspace;
753 	int32_t		tcp_hsp_tstamp;
754 } tcp_hsp_t;
755 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
756 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
757 
758 /*
759  * Functions called directly via squeue having a prototype of edesc_t.
760  */
761 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
762 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
763 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
764 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
765 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
766 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
767 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
768 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
769 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
770 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
771 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
772 
773 
774 /* Prototype for TCP functions */
775 static void	tcp_random_init(void);
776 int		tcp_random(void);
777 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
778 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
779 		    tcp_t *eager);
780 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
781 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
782     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
783     boolean_t user_specified);
784 static void	tcp_closei_local(tcp_t *tcp);
785 static void	tcp_close_detached(tcp_t *tcp);
786 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
787 			mblk_t *idmp, mblk_t **defermp);
788 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
789 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
790 		    in_port_t dstport, uint_t srcid);
791 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
792 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
793 		    uint32_t scope_id);
794 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
795 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
796 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
797 static char	*tcp_display(tcp_t *tcp, char *, char);
798 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
799 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
800 static void	tcp_eager_unlink(tcp_t *tcp);
801 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
802 		    int unixerr);
803 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
804 		    int tlierr, int unixerr);
805 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
806 		    cred_t *cr);
807 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
808 		    char *value, caddr_t cp, cred_t *cr);
809 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
810 		    char *value, caddr_t cp, cred_t *cr);
811 static int	tcp_tpistate(tcp_t *tcp);
812 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
813     int caller_holds_lock);
814 static void	tcp_bind_hash_remove(tcp_t *tcp);
815 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id);
816 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
817 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
818 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
819 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
820 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
821 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
822 static int	tcp_header_init_ipv4(tcp_t *tcp);
823 static int	tcp_header_init_ipv6(tcp_t *tcp);
824 int		tcp_init(tcp_t *tcp, queue_t *q);
825 static int	tcp_init_values(tcp_t *tcp);
826 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
827 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
828 		    t_scalar_t addr_length);
829 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
830 static void	tcp_ip_notify(tcp_t *tcp);
831 static mblk_t	*tcp_ire_mp(mblk_t *mp);
832 static void	tcp_iss_init(tcp_t *tcp);
833 static void	tcp_keepalive_killer(void *arg);
834 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
835 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
836 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
837 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
838 static boolean_t tcp_allow_connopt_set(int level, int name);
839 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
840 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
841 static int	tcp_opt_get_user(ipha_t *ipha, uchar_t *ptr);
842 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
843 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
844 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
845 		    mblk_t *mblk);
846 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
847 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
848 		    uchar_t *ptr, uint_t len);
849 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
850 static boolean_t tcp_param_register(tcpparam_t *tcppa, int cnt);
851 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
852 		    caddr_t cp, cred_t *cr);
853 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
854 		    caddr_t cp, cred_t *cr);
855 static void	tcp_iss_key_init(uint8_t *phrase, int len);
856 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
857 		    caddr_t cp, cred_t *cr);
858 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
859 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
860 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
861 static void	tcp_reinit(tcp_t *tcp);
862 static void	tcp_reinit_values(tcp_t *tcp);
863 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
864 		    tcp_t *thisstream, cred_t *cr);
865 
866 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
867 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
868 static boolean_t tcp_send_rst_chk(void);
869 static void	tcp_ss_rexmit(tcp_t *tcp);
870 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
871 static void	tcp_process_options(tcp_t *, tcph_t *);
872 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
873 static void	tcp_rsrv(queue_t *q);
874 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
875 static int	tcp_snmp_state(tcp_t *tcp);
876 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
877 		    cred_t *cr);
878 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
879 		    cred_t *cr);
880 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
881 		    cred_t *cr);
882 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
883 		    cred_t *cr);
884 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
885 		    cred_t *cr);
886 static int	tcp_host_param_set(queue_t *q, mblk_t *mp, char *value,
887 		    caddr_t cp, cred_t *cr);
888 static int	tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value,
889 		    caddr_t cp, cred_t *cr);
890 static int	tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp,
891 		    cred_t *cr);
892 static void	tcp_timer(void *arg);
893 static void	tcp_timer_callback(void *);
894 static in_port_t tcp_update_next_port(in_port_t port, boolean_t random);
895 static in_port_t tcp_get_next_priv_port(void);
896 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
897 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
898 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
899 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
900 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
901 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
902 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
903 		    const int num_sack_blk, int *usable, uint_t *snxt,
904 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
905 		    const int mdt_thres);
906 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
907 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
908 		    const int num_sack_blk, int *usable, uint_t *snxt,
909 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
910 		    const int mdt_thres);
911 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
912 		    int num_sack_blk);
913 static void	tcp_wsrv(queue_t *q);
914 static int	tcp_xmit_end(tcp_t *tcp);
915 void		tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len);
916 static mblk_t	*tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send,
917 		    int32_t *offset, mblk_t **end_mp, uint32_t seq,
918 		    boolean_t sendall, uint32_t *seg_len, boolean_t rexmit);
919 static void	tcp_ack_timer(void *arg);
920 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
921 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
922 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len);
923 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
924 		    uint32_t ack, int ctl);
925 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr);
926 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr);
927 static int	setmaxps(queue_t *q, int maxpsz);
928 static void	tcp_set_rto(tcp_t *, time_t);
929 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
930 		    boolean_t, boolean_t);
931 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
932 		    boolean_t ipsec_mctl);
933 static boolean_t tcp_cmpbuf(void *a, uint_t alen,
934 		    boolean_t b_valid, void *b, uint_t blen);
935 static boolean_t tcp_allocbuf(void **dstp, uint_t *dstlenp,
936 		    boolean_t src_valid, void *src, uint_t srclen);
937 static void	tcp_savebuf(void **dstp, uint_t *dstlenp,
938 		    boolean_t src_valid, void *src, uint_t srclen);
939 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
940 		    char *opt, int optlen);
941 static int	tcp_pkt_set(uchar_t *, uint_t, uchar_t **, uint_t *);
942 static int	tcp_build_hdrs(queue_t *, tcp_t *);
943 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
944 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
945 		    tcph_t *tcph);
946 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
947 boolean_t	tcp_reserved_port_add(int, in_port_t *, in_port_t *);
948 boolean_t	tcp_reserved_port_del(in_port_t, in_port_t);
949 boolean_t	tcp_reserved_port_check(in_port_t);
950 static tcp_t	*tcp_alloc_temp_tcp(in_port_t);
951 static int	tcp_reserved_port_list(queue_t *, mblk_t *, caddr_t, cred_t *);
952 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
953 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
954 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
955 		    const boolean_t, const uint32_t, const uint32_t,
956 		    const uint32_t, const uint32_t);
957 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
958 		    const uint_t, const uint_t, boolean_t *);
959 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
960 extern mblk_t	*tcp_timermp_alloc(int);
961 extern void	tcp_timermp_free(tcp_t *);
962 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
963 static void	tcp_stop_lingering(tcp_t *tcp);
964 static void	tcp_close_linger_timeout(void *arg);
965 void		tcp_ddi_init(void);
966 void		tcp_ddi_destroy(void);
967 static void	tcp_kstat_init(void);
968 static void	tcp_kstat_fini(void);
969 static int	tcp_kstat_update(kstat_t *kp, int rw);
970 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
971 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
972 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
973 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
974 			tcph_t *tcph, mblk_t *idmp);
975 static squeue_func_t tcp_squeue_switch(int);
976 
977 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *);
978 static int	tcp_close(queue_t *, int);
979 static int	tcpclose_accept(queue_t *);
980 static int	tcp_modclose(queue_t *);
981 static void	tcp_wput_mod(queue_t *, mblk_t *);
982 
983 static void	tcp_squeue_add(squeue_t *);
984 static boolean_t tcp_zcopy_check(tcp_t *);
985 static void	tcp_zcopy_notify(tcp_t *);
986 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
987 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
988 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
989 
990 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
991 
992 /*
993  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
994  *
995  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
996  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
997  * (defined in tcp.h) needs to be filled in and passed into the kernel
998  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
999  * structure contains the four-tuple of a TCP connection and a range of TCP
1000  * states (specified by ac_start and ac_end). The use of wildcard addresses
1001  * and ports is allowed. Connections with a matching four tuple and a state
1002  * within the specified range will be aborted. The valid states for the
1003  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
1004  * inclusive.
1005  *
1006  * An application which has its connection aborted by this ioctl will receive
1007  * an error that is dependent on the connection state at the time of the abort.
1008  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1009  * though a RST packet has been received.  If the connection state is equal to
1010  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1011  * and all resources associated with the connection will be freed.
1012  */
1013 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1014 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1015 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1016 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *);
1017 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1018 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1019     boolean_t);
1020 
1021 static struct module_info tcp_rinfo =  {
1022 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1023 };
1024 
1025 static struct module_info tcp_winfo =  {
1026 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1027 };
1028 
1029 /*
1030  * Entry points for TCP as a module. It only allows SNMP requests
1031  * to pass through.
1032  */
1033 struct qinit tcp_mod_rinit = {
1034 	(pfi_t)putnext, NULL, tcp_open, ip_snmpmod_close, NULL, &tcp_rinfo,
1035 };
1036 
1037 struct qinit tcp_mod_winit = {
1038 	(pfi_t)ip_snmpmod_wput, NULL, tcp_open, ip_snmpmod_close, NULL,
1039 	&tcp_rinfo
1040 };
1041 
1042 /*
1043  * Entry points for TCP as a device. The normal case which supports
1044  * the TCP functionality.
1045  */
1046 struct qinit tcp_rinit = {
1047 	NULL, (pfi_t)tcp_rsrv, tcp_open, tcp_close, NULL, &tcp_rinfo
1048 };
1049 
1050 struct qinit tcp_winit = {
1051 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1052 };
1053 
1054 /* Initial entry point for TCP in socket mode. */
1055 struct qinit tcp_sock_winit = {
1056 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1057 };
1058 
1059 /*
1060  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1061  * an accept. Avoid allocating data structures since eager has already
1062  * been created.
1063  */
1064 struct qinit tcp_acceptor_rinit = {
1065 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1066 };
1067 
1068 struct qinit tcp_acceptor_winit = {
1069 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1070 };
1071 
1072 /*
1073  * Entry points for TCP loopback (read side only)
1074  */
1075 struct qinit tcp_loopback_rinit = {
1076 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_open, tcp_close, (pfi_t)0,
1077 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1078 };
1079 
1080 struct streamtab tcpinfo = {
1081 	&tcp_rinit, &tcp_winit
1082 };
1083 
1084 extern squeue_func_t tcp_squeue_wput_proc;
1085 extern squeue_func_t tcp_squeue_timer_proc;
1086 
1087 /* Protected by tcp_g_q_lock */
1088 static queue_t	*tcp_g_q;	/* Default queue used during detached closes */
1089 kmutex_t tcp_g_q_lock;
1090 
1091 /* Protected by tcp_hsp_lock */
1092 /*
1093  * XXX The host param mechanism should go away and instead we should use
1094  * the metrics associated with the routes to determine the default sndspace
1095  * and rcvspace.
1096  */
1097 static tcp_hsp_t	**tcp_hsp_hash;	/* Hash table for HSPs */
1098 krwlock_t tcp_hsp_lock;
1099 
1100 /*
1101  * Extra privileged ports. In host byte order.
1102  * Protected by tcp_epriv_port_lock.
1103  */
1104 #define	TCP_NUM_EPRIV_PORTS	64
1105 static int	tcp_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
1106 static uint16_t	tcp_g_epriv_ports[TCP_NUM_EPRIV_PORTS] = { 2049, 4045 };
1107 kmutex_t tcp_epriv_port_lock;
1108 
1109 /*
1110  * The smallest anonymous port in the priviledged port range which TCP
1111  * looks for free port.  Use in the option TCP_ANONPRIVBIND.
1112  */
1113 static in_port_t tcp_min_anonpriv_port = 512;
1114 
1115 /* Only modified during _init and _fini thus no locking is needed. */
1116 static caddr_t	tcp_g_nd;	/* Head of 'named dispatch' variable list */
1117 
1118 /* Hint not protected by any lock */
1119 static uint_t	tcp_next_port_to_try;
1120 
1121 
1122 /* TCP bind hash list - all tcp_t with state >= BOUND. */
1123 tf_t	tcp_bind_fanout[TCP_BIND_FANOUT_SIZE];
1124 
1125 /* TCP queue hash list - all tcp_t in case they will be an acceptor. */
1126 static tf_t	tcp_acceptor_fanout[TCP_FANOUT_SIZE];
1127 
1128 /*
1129  * TCP has a private interface for other kernel modules to reserve a
1130  * port range for them to use.  Once reserved, TCP will not use any ports
1131  * in the range.  This interface relies on the TCP_EXCLBIND feature.  If
1132  * the semantics of TCP_EXCLBIND is changed, implementation of this interface
1133  * has to be verified.
1134  *
1135  * There can be TCP_RESERVED_PORTS_ARRAY_MAX_SIZE port ranges.  Each port
1136  * range can cover at most TCP_RESERVED_PORTS_RANGE_MAX ports.  A port
1137  * range is [port a, port b] inclusive.  And each port range is between
1138  * TCP_LOWESET_RESERVED_PORT and TCP_LARGEST_RESERVED_PORT inclusive.
1139  *
1140  * Note that the default anonymous port range starts from 32768.  There is
1141  * no port "collision" between that and the reserved port range.  If there
1142  * is port collision (because the default smallest anonymous port is lowered
1143  * or some apps specifically bind to ports in the reserved port range), the
1144  * system may not be able to reserve a port range even there are enough
1145  * unbound ports as a reserved port range contains consecutive ports .
1146  */
1147 #define	TCP_RESERVED_PORTS_ARRAY_MAX_SIZE	5
1148 #define	TCP_RESERVED_PORTS_RANGE_MAX		1000
1149 #define	TCP_SMALLEST_RESERVED_PORT		10240
1150 #define	TCP_LARGEST_RESERVED_PORT		20480
1151 
1152 /* Structure to represent those reserved port ranges. */
1153 typedef struct tcp_rport_s {
1154 	in_port_t	lo_port;
1155 	in_port_t	hi_port;
1156 	tcp_t		**temp_tcp_array;
1157 } tcp_rport_t;
1158 
1159 /* The reserved port array. */
1160 static tcp_rport_t tcp_reserved_port[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
1161 
1162 /* Locks to protect the tcp_reserved_ports array. */
1163 static krwlock_t tcp_reserved_port_lock;
1164 
1165 /* The number of ranges in the array. */
1166 uint32_t tcp_reserved_port_array_size = 0;
1167 
1168 /*
1169  * MIB-2 stuff for SNMP
1170  * Note: tcpInErrs {tcp 15} is accumulated in ip.c
1171  */
1172 mib2_tcp_t	tcp_mib;	/* SNMP fixed size info */
1173 kstat_t		*tcp_mibkp;	/* kstat exporting tcp_mib data */
1174 
1175 boolean_t tcp_icmp_source_quench = B_FALSE;
1176 /*
1177  * Following assumes TPI alignment requirements stay along 32 bit
1178  * boundaries
1179  */
1180 #define	ROUNDUP32(x) \
1181 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1182 
1183 /* Template for response to info request. */
1184 static struct T_info_ack tcp_g_t_info_ack = {
1185 	T_INFO_ACK,		/* PRIM_type */
1186 	0,			/* TSDU_size */
1187 	T_INFINITE,		/* ETSDU_size */
1188 	T_INVALID,		/* CDATA_size */
1189 	T_INVALID,		/* DDATA_size */
1190 	sizeof (sin_t),		/* ADDR_size */
1191 	0,			/* OPT_size - not initialized here */
1192 	TIDUSZ,			/* TIDU_size */
1193 	T_COTS_ORD,		/* SERV_type */
1194 	TCPS_IDLE,		/* CURRENT_state */
1195 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1196 };
1197 
1198 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1199 	T_INFO_ACK,		/* PRIM_type */
1200 	0,			/* TSDU_size */
1201 	T_INFINITE,		/* ETSDU_size */
1202 	T_INVALID,		/* CDATA_size */
1203 	T_INVALID,		/* DDATA_size */
1204 	sizeof (sin6_t),	/* ADDR_size */
1205 	0,			/* OPT_size - not initialized here */
1206 	TIDUSZ,		/* TIDU_size */
1207 	T_COTS_ORD,		/* SERV_type */
1208 	TCPS_IDLE,		/* CURRENT_state */
1209 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1210 };
1211 
1212 #define	MS	1L
1213 #define	SECONDS	(1000 * MS)
1214 #define	MINUTES	(60 * SECONDS)
1215 #define	HOURS	(60 * MINUTES)
1216 #define	DAYS	(24 * HOURS)
1217 
1218 #define	PARAM_MAX (~(uint32_t)0)
1219 
1220 /* Max size IP datagram is 64k - 1 */
1221 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1222 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1223 /* Max of the above */
1224 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1225 
1226 /* Largest TCP port number */
1227 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1228 
1229 /*
1230  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1231  * layer header.  It has to be a multiple of 4.
1232  */
1233 static tcpparam_t tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1234 #define	tcp_wroff_xtra	tcp_wroff_xtra_param.tcp_param_val
1235 
1236 /*
1237  * All of these are alterable, within the min/max values given, at run time.
1238  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1239  * per the TCP spec.
1240  */
1241 /* BEGIN CSTYLED */
1242 tcpparam_t	tcp_param_arr[] = {
1243  /*min		max		value		name */
1244  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1245  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1246  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1247  { 1,		1024,		1,		"tcp_conn_req_min" },
1248  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1249  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1250  { 0,		10,		0,		"tcp_debug" },
1251  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1252  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1253  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1254  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1255  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1256  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1257  { 1,		255,		64,		"tcp_ipv4_ttl"},
1258  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1259  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1260  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1261  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1262  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1263  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1264  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1265  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1266  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1267  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1268  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1269  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1270  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1271  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1272  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1273  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1274  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1275  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1276  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1277  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1278  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1279  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1280  { 0,		TCP_MSS_MAX,	64,		"tcp_co_min"},
1281  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1282 /*
1283  * Question:  What default value should I set for tcp_strong_iss?
1284  */
1285  { 0,		2,		1,		"tcp_strong_iss"},
1286  { 0,		65536,		20,		"tcp_rtt_updates"},
1287  { 0,		1,		1,		"tcp_wscale_always"},
1288  { 0,		1,		0,		"tcp_tstamp_always"},
1289  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1290  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1291  { 0,		16,		2,		"tcp_deferred_acks_max"},
1292  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1293  { 1,		4,		4,		"tcp_slow_start_initial"},
1294  { 10*MS,	50*MS,		20*MS,		"tcp_co_timer_interval"},
1295  { 0,		2,		2,		"tcp_sack_permitted"},
1296  { 0,		1,		0,		"tcp_trace"},
1297  { 0,		1,		1,		"tcp_compression_enabled"},
1298  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1299  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1300  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1301  { 0,		1,		0,		"tcp_rev_src_routes"},
1302  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1303  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1304  { 0,		16,		8,		"tcp_local_dacks_max"},
1305  { 0,		2,		1,		"tcp_ecn_permitted"},
1306  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1307  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1308  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1309  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1310  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1311 };
1312 /* END CSTYLED */
1313 
1314 /*
1315  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1316  * each header fragment in the header buffer.  Each parameter value has
1317  * to be a multiple of 4 (32-bit aligned).
1318  */
1319 static tcpparam_t tcp_mdt_head_param = { 32, 256, 32, "tcp_mdt_hdr_head_min" };
1320 static tcpparam_t tcp_mdt_tail_param = { 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1321 #define	tcp_mdt_hdr_head_min	tcp_mdt_head_param.tcp_param_val
1322 #define	tcp_mdt_hdr_tail_min	tcp_mdt_tail_param.tcp_param_val
1323 
1324 /*
1325  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1326  * the maximum number of payload buffers associated per Multidata.
1327  */
1328 static tcpparam_t tcp_mdt_max_pbufs_param =
1329 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1330 #define	tcp_mdt_max_pbufs	tcp_mdt_max_pbufs_param.tcp_param_val
1331 
1332 /* Round up the value to the nearest mss. */
1333 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1334 
1335 /*
1336  * Set ECN capable transport (ECT) code point in IP header.
1337  *
1338  * Note that there are 2 ECT code points '01' and '10', which are called
1339  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1340  * point ECT(0) for TCP as described in RFC 2481.
1341  */
1342 #define	SET_ECT(tcp, iph) \
1343 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1344 		/* We need to clear the code point first. */ \
1345 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1346 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1347 	} else { \
1348 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1349 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1350 	}
1351 
1352 /*
1353  * The format argument to pass to tcp_display().
1354  * DISP_PORT_ONLY means that the returned string has only port info.
1355  * DISP_ADDR_AND_PORT means that the returned string also contains the
1356  * remote and local IP address.
1357  */
1358 #define	DISP_PORT_ONLY		1
1359 #define	DISP_ADDR_AND_PORT	2
1360 
1361 /*
1362  * This controls the rate some ndd info report functions can be used
1363  * by non-priviledged users.  It stores the last time such info is
1364  * requested.  When those report functions are called again, this
1365  * is checked with the current time and compare with the ndd param
1366  * tcp_ndd_get_info_interval.
1367  */
1368 static clock_t tcp_last_ndd_get_info_time = 0;
1369 #define	NDD_TOO_QUICK_MSG \
1370 	"ndd get info rate too high for non-priviledged users, try again " \
1371 	"later.\n"
1372 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1373 
1374 #define	IS_VMLOANED_MBLK(mp) \
1375 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1376 
1377 /*
1378  * These two variables control the rate for TCP to generate RSTs in
1379  * response to segments not belonging to any connections.  We limit
1380  * TCP to sent out tcp_rst_sent_rate (ndd param) number of RSTs in
1381  * each 1 second interval.  This is to protect TCP against DoS attack.
1382  */
1383 static clock_t tcp_last_rst_intrvl;
1384 static uint32_t tcp_rst_cnt;
1385 
1386 /* The number of RST not sent because of the rate limit. */
1387 static uint32_t tcp_rst_unsent;
1388 
1389 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1390 boolean_t tcp_mdt_chain = B_TRUE;
1391 
1392 /*
1393  * MDT threshold in the form of effective send MSS multiplier; we take
1394  * the MDT path if the amount of unsent data exceeds the threshold value
1395  * (default threshold is 1*SMSS).
1396  */
1397 uint_t tcp_mdt_smss_threshold = 1;
1398 
1399 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1400 
1401 /*
1402  * Forces all connections to obey the value of the tcp_maxpsz_multiplier
1403  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1404  * determined dynamically during tcp_adapt_ire(), which is the default.
1405  */
1406 boolean_t tcp_static_maxpsz = B_FALSE;
1407 
1408 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1409 uint32_t tcp_random_anon_port = 1;
1410 
1411 /*
1412  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1413  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1414  * data, TCP will not respond with an ACK.  RFC 793 requires that
1415  * TCP responds with an ACK for such a bogus ACK.  By not following
1416  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1417  * an attacker successfully spoofs an acceptable segment to our
1418  * peer; or when our peer is "confused."
1419  */
1420 uint32_t tcp_drop_ack_unsent_cnt = 10;
1421 
1422 /*
1423  * Hook functions to enable cluster networking
1424  * On non-clustered systems these vectors must always be NULL.
1425  */
1426 
1427 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1428 			    uint8_t *laddrp, in_port_t lport) = NULL;
1429 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1430 			    uint8_t *laddrp, in_port_t lport) = NULL;
1431 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1432 			    uint8_t *laddrp, in_port_t lport,
1433 			    uint8_t *faddrp, in_port_t fport) = NULL;
1434 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1435 			    uint8_t *laddrp, in_port_t lport,
1436 			    uint8_t *faddrp, in_port_t fport) = NULL;
1437 
1438 /*
1439  * The following are defined in ip.c
1440  */
1441 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1442 				uint8_t *laddrp);
1443 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1444 				uint8_t *laddrp, uint8_t *faddrp);
1445 
1446 #define	CL_INET_CONNECT(tcp)		{			\
1447 	if (cl_inet_connect != NULL) {				\
1448 		/*						\
1449 		 * Running in cluster mode - register active connection	\
1450 		 * information						\
1451 		 */							\
1452 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1453 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1454 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1455 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1456 				    (in_port_t)(tcp)->tcp_lport,	\
1457 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1458 				    (in_port_t)(tcp)->tcp_fport);	\
1459 			}						\
1460 		} else {						\
1461 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1462 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1463 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1464 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1465 				    (in_port_t)(tcp)->tcp_lport,	\
1466 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1467 				    (in_port_t)(tcp)->tcp_fport);	\
1468 			}						\
1469 		}							\
1470 	}								\
1471 }
1472 
1473 #define	CL_INET_DISCONNECT(tcp)	{				\
1474 	if (cl_inet_disconnect != NULL) {				\
1475 		/*							\
1476 		 * Running in cluster mode - deregister active		\
1477 		 * connection information				\
1478 		 */							\
1479 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1480 			if ((tcp)->tcp_ip_src != 0) {			\
1481 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1482 				    AF_INET,				\
1483 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1484 				    (in_port_t)(tcp)->tcp_lport,	\
1485 				    (uint8_t *)				\
1486 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1487 				    (in_port_t)(tcp)->tcp_fport);	\
1488 			}						\
1489 		} else {						\
1490 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1491 			    &(tcp)->tcp_ip_src_v6)) {			\
1492 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1493 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1494 				    (in_port_t)(tcp)->tcp_lport,	\
1495 				    (uint8_t *)				\
1496 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1497 				    (in_port_t)(tcp)->tcp_fport);	\
1498 			}						\
1499 		}							\
1500 	}								\
1501 }
1502 
1503 /*
1504  * Cluster networking hook for traversing current connection list.
1505  * This routine is used to extract the current list of live connections
1506  * which must continue to to be dispatched to this node.
1507  */
1508 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1509 
1510 /*
1511  * Figure out the value of window scale opton.  Note that the rwnd is
1512  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1513  * We cannot find the scale value and then do a round up of tcp_rwnd
1514  * because the scale value may not be correct after that.
1515  *
1516  * Set the compiler flag to make this function inline.
1517  */
1518 static void
1519 tcp_set_ws_value(tcp_t *tcp)
1520 {
1521 	int i;
1522 	uint32_t rwnd = tcp->tcp_rwnd;
1523 
1524 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1525 	    i++, rwnd >>= 1)
1526 		;
1527 	tcp->tcp_rcv_ws = i;
1528 }
1529 
1530 /*
1531  * Remove a connection from the list of detached TIME_WAIT connections.
1532  */
1533 static void
1534 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1535 {
1536 	boolean_t	locked = B_FALSE;
1537 
1538 	if (tcp_time_wait == NULL) {
1539 		tcp_time_wait = *((tcp_squeue_priv_t **)
1540 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1541 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1542 		locked = B_TRUE;
1543 	}
1544 
1545 	if (tcp->tcp_time_wait_expire == 0) {
1546 		ASSERT(tcp->tcp_time_wait_next == NULL);
1547 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1548 		if (locked)
1549 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1550 		return;
1551 	}
1552 	ASSERT(TCP_IS_DETACHED(tcp));
1553 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1554 
1555 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1556 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1557 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1558 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1559 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1560 			    NULL;
1561 		} else {
1562 			tcp_time_wait->tcp_time_wait_tail = NULL;
1563 		}
1564 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1565 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1566 		ASSERT(tcp->tcp_time_wait_next == NULL);
1567 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1568 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1569 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1570 	} else {
1571 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1572 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1573 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1574 		    tcp->tcp_time_wait_next;
1575 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1576 		    tcp->tcp_time_wait_prev;
1577 	}
1578 	tcp->tcp_time_wait_next = NULL;
1579 	tcp->tcp_time_wait_prev = NULL;
1580 	tcp->tcp_time_wait_expire = 0;
1581 
1582 	if (locked)
1583 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1584 }
1585 
1586 /*
1587  * Add a connection to the list of detached TIME_WAIT connections
1588  * and set its time to expire.
1589  */
1590 static void
1591 tcp_time_wait_append(tcp_t *tcp)
1592 {
1593 	tcp_squeue_priv_t *tcp_time_wait =
1594 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1595 		SQPRIVATE_TCP));
1596 
1597 	tcp_timers_stop(tcp);
1598 
1599 	/* Freed above */
1600 	ASSERT(tcp->tcp_timer_tid == 0);
1601 	ASSERT(tcp->tcp_ack_tid == 0);
1602 
1603 	/* must have happened at the time of detaching the tcp */
1604 	ASSERT(tcp->tcp_ptpahn == NULL);
1605 	ASSERT(tcp->tcp_flow_stopped == 0);
1606 	ASSERT(tcp->tcp_time_wait_next == NULL);
1607 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1608 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1609 	ASSERT(tcp->tcp_listener == NULL);
1610 
1611 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1612 	/*
1613 	 * The value computed below in tcp->tcp_time_wait_expire may
1614 	 * appear negative or wrap around. That is ok since our
1615 	 * interest is only in the difference between the current lbolt
1616 	 * value and tcp->tcp_time_wait_expire. But the value should not
1617 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1618 	 * The corresponding comparison in tcp_time_wait_collector() uses
1619 	 * modular arithmetic.
1620 	 */
1621 	tcp->tcp_time_wait_expire +=
1622 	    drv_usectohz(tcp_time_wait_interval * 1000);
1623 	if (tcp->tcp_time_wait_expire == 0)
1624 		tcp->tcp_time_wait_expire = 1;
1625 
1626 	ASSERT(TCP_IS_DETACHED(tcp));
1627 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1628 	ASSERT(tcp->tcp_time_wait_next == NULL);
1629 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1630 	TCP_DBGSTAT(tcp_time_wait);
1631 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1632 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1633 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1634 		tcp_time_wait->tcp_time_wait_head = tcp;
1635 	} else {
1636 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1637 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1638 		    TCPS_TIME_WAIT);
1639 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1640 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1641 	}
1642 	tcp_time_wait->tcp_time_wait_tail = tcp;
1643 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1644 }
1645 
1646 /* ARGSUSED */
1647 void
1648 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1649 {
1650 	conn_t	*connp = (conn_t *)arg;
1651 	tcp_t	*tcp = connp->conn_tcp;
1652 
1653 	ASSERT(tcp != NULL);
1654 	if (tcp->tcp_state == TCPS_CLOSED) {
1655 		return;
1656 	}
1657 
1658 	ASSERT((tcp->tcp_family == AF_INET &&
1659 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1660 	    (tcp->tcp_family == AF_INET6 &&
1661 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1662 	    tcp->tcp_ipversion == IPV6_VERSION)));
1663 	ASSERT(!tcp->tcp_listener);
1664 
1665 	TCP_STAT(tcp_time_wait_reap);
1666 	ASSERT(TCP_IS_DETACHED(tcp));
1667 
1668 	/*
1669 	 * Because they have no upstream client to rebind or tcp_close()
1670 	 * them later, we axe the connection here and now.
1671 	 */
1672 	tcp_close_detached(tcp);
1673 }
1674 
1675 void
1676 tcp_cleanup(tcp_t *tcp)
1677 {
1678 	mblk_t		*mp;
1679 	char		*tcp_iphc;
1680 	int		tcp_iphc_len;
1681 	int		tcp_hdr_grown;
1682 	tcp_sack_info_t	*tcp_sack_info;
1683 	conn_t		*connp = tcp->tcp_connp;
1684 
1685 	tcp_bind_hash_remove(tcp);
1686 	tcp_free(tcp);
1687 
1688 	/* Release any SSL context */
1689 	if (tcp->tcp_kssl_ent != NULL) {
1690 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1691 		tcp->tcp_kssl_ent = NULL;
1692 	}
1693 
1694 	if (tcp->tcp_kssl_ctx != NULL) {
1695 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1696 		tcp->tcp_kssl_ctx = NULL;
1697 	}
1698 	tcp->tcp_kssl_pending = B_FALSE;
1699 
1700 	conn_delete_ire(connp, NULL);
1701 	if (connp->conn_flags & IPCL_TCPCONN) {
1702 		if (connp->conn_latch != NULL)
1703 			IPLATCH_REFRELE(connp->conn_latch);
1704 		if (connp->conn_policy != NULL)
1705 			IPPH_REFRELE(connp->conn_policy);
1706 	}
1707 
1708 	/*
1709 	 * Since we will bzero the entire structure, we need to
1710 	 * remove it and reinsert it in global hash list. We
1711 	 * know the walkers can't get to this conn because we
1712 	 * had set CONDEMNED flag earlier and checked reference
1713 	 * under conn_lock so walker won't pick it and when we
1714 	 * go the ipcl_globalhash_remove() below, no walker
1715 	 * can get to it.
1716 	 */
1717 	ipcl_globalhash_remove(connp);
1718 
1719 	/* Save some state */
1720 	mp = tcp->tcp_timercache;
1721 
1722 	tcp_sack_info = tcp->tcp_sack_info;
1723 	tcp_iphc = tcp->tcp_iphc;
1724 	tcp_iphc_len = tcp->tcp_iphc_len;
1725 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1726 
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 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2414 	econnp->conn_zoneid = aconnp->conn_zoneid;
2415 	aconnp->conn_cred = NULL;
2416 
2417 	/* Do the IPC initialization */
2418 	CONN_INC_REF(econnp);
2419 
2420 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2421 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2422 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2423 	econnp->conn_ulp = aconnp->conn_ulp;
2424 
2425 	/* Done with old IPC. Drop its ref on its connp */
2426 	CONN_DEC_REF(aconnp);
2427 }
2428 
2429 
2430 /*
2431  * Adapt to the information, such as rtt and rtt_sd, provided from the
2432  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2433  *
2434  * Checks for multicast and broadcast destination address.
2435  * Returns zero on failure; non-zero if ok.
2436  *
2437  * Note that the MSS calculation here is based on the info given in
2438  * the IRE.  We do not do any calculation based on TCP options.  They
2439  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2440  * knows which options to use.
2441  *
2442  * Note on how TCP gets its parameters for a connection.
2443  *
2444  * When a tcp_t structure is allocated, it gets all the default parameters.
2445  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2446  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2447  * default.  But if there is an associated tcp_host_param, it will override
2448  * the metrics.
2449  *
2450  * An incoming SYN with a multicast or broadcast destination address, is dropped
2451  * in 1 of 2 places.
2452  *
2453  * 1. If the packet was received over the wire it is dropped in
2454  * ip_rput_process_broadcast()
2455  *
2456  * 2. If the packet was received through internal IP loopback, i.e. the packet
2457  * was generated and received on the same machine, it is dropped in
2458  * ip_wput_local()
2459  *
2460  * An incoming SYN with a multicast or broadcast source address is always
2461  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2462  * reject an attempt to connect to a broadcast or multicast (destination)
2463  * address.
2464  */
2465 static int
2466 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2467 {
2468 	tcp_hsp_t	*hsp;
2469 	ire_t		*ire;
2470 	ire_t		*sire = NULL;
2471 	iulp_t		*ire_uinfo;
2472 	uint32_t	mss_max;
2473 	uint32_t	mss;
2474 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2475 	conn_t		*connp = tcp->tcp_connp;
2476 	boolean_t	ire_cacheable = B_FALSE;
2477 	zoneid_t	zoneid = connp->conn_zoneid;
2478 	ill_t		*ill = NULL;
2479 	boolean_t	incoming = (ire_mp == NULL);
2480 
2481 	ASSERT(connp->conn_ire_cache == NULL);
2482 
2483 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2484 
2485 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2486 			BUMP_MIB(&ip_mib, ipInDiscards);
2487 			return (0);
2488 		}
2489 
2490 		ire = ire_cache_lookup(tcp->tcp_connp->conn_rem, zoneid);
2491 		if (ire != NULL) {
2492 			ire_cacheable = B_TRUE;
2493 			ire_uinfo = (ire_mp != NULL) ?
2494 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2495 			    &ire->ire_uinfo;
2496 
2497 		} else {
2498 			if (ire_mp == NULL) {
2499 				ire = ire_ftable_lookup(
2500 				    tcp->tcp_connp->conn_rem,
2501 				    0, 0, 0, NULL, &sire, zoneid, 0,
2502 				    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT));
2503 				if (ire == NULL)
2504 					return (0);
2505 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2506 				    &ire->ire_uinfo;
2507 			} else {
2508 				ire = (ire_t *)ire_mp->b_rptr;
2509 				ire_uinfo =
2510 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2511 			}
2512 		}
2513 		ASSERT(ire != NULL);
2514 		ASSERT(ire_uinfo != NULL);
2515 
2516 		if ((ire->ire_src_addr == INADDR_ANY) ||
2517 		    (ire->ire_type & IRE_BROADCAST)) {
2518 			/*
2519 			 * ire->ire_mp is non null when ire_mp passed in is used
2520 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2521 			 */
2522 			if (ire->ire_mp == NULL)
2523 				ire_refrele(ire);
2524 			if (sire != NULL)
2525 				ire_refrele(sire);
2526 			return (0);
2527 		}
2528 
2529 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2530 			ipaddr_t src_addr;
2531 
2532 			/*
2533 			 * ip_bind_connected() has stored the correct source
2534 			 * address in conn_src.
2535 			 */
2536 			src_addr = tcp->tcp_connp->conn_src;
2537 			tcp->tcp_ipha->ipha_src = src_addr;
2538 			/*
2539 			 * Copy of the src addr. in tcp_t is needed
2540 			 * for the lookup funcs.
2541 			 */
2542 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2543 		}
2544 		/*
2545 		 * Set the fragment bit so that IP will tell us if the MTU
2546 		 * should change. IP tells us the latest setting of
2547 		 * ip_path_mtu_discovery through ire_frag_flag.
2548 		 */
2549 		if (ip_path_mtu_discovery) {
2550 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2551 			    htons(IPH_DF);
2552 		}
2553 		tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2554 	} else {
2555 		/*
2556 		 * For incoming connection ire_mp = NULL
2557 		 * For outgoing connection ire_mp != NULL
2558 		 * Technically we should check conn_incoming_ill
2559 		 * when ire_mp is NULL and conn_outgoing_ill when
2560 		 * ire_mp is non-NULL. But this is performance
2561 		 * critical path and for IPV*_BOUND_IF, outgoing
2562 		 * and incoming ill are always set to the same value.
2563 		 */
2564 		ill_t	*dst_ill = NULL;
2565 		ipif_t  *dst_ipif = NULL;
2566 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
2567 
2568 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2569 
2570 		if (connp->conn_outgoing_ill != NULL) {
2571 			/* Outgoing or incoming path */
2572 			int   err;
2573 
2574 			dst_ill = conn_get_held_ill(connp,
2575 			    &connp->conn_outgoing_ill, &err);
2576 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2577 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2578 				return (0);
2579 			}
2580 			match_flags |= MATCH_IRE_ILL;
2581 			dst_ipif = dst_ill->ill_ipif;
2582 		}
2583 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2584 		    0, 0, dst_ipif, zoneid, match_flags);
2585 
2586 		if (ire != NULL) {
2587 			ire_cacheable = B_TRUE;
2588 			ire_uinfo = (ire_mp != NULL) ?
2589 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2590 			    &ire->ire_uinfo;
2591 		} else {
2592 			if (ire_mp == NULL) {
2593 				ire = ire_ftable_lookup_v6(
2594 				    &tcp->tcp_connp->conn_remv6,
2595 				    0, 0, 0, dst_ipif, &sire, zoneid,
2596 				    0, match_flags);
2597 				if (ire == NULL) {
2598 					if (dst_ill != NULL)
2599 						ill_refrele(dst_ill);
2600 					return (0);
2601 				}
2602 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2603 				    &ire->ire_uinfo;
2604 			} else {
2605 				ire = (ire_t *)ire_mp->b_rptr;
2606 				ire_uinfo =
2607 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2608 			}
2609 		}
2610 		if (dst_ill != NULL)
2611 			ill_refrele(dst_ill);
2612 
2613 		ASSERT(ire != NULL);
2614 		ASSERT(ire_uinfo != NULL);
2615 
2616 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2617 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2618 			/*
2619 			 * ire->ire_mp is non null when ire_mp passed in is used
2620 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2621 			 */
2622 			if (ire->ire_mp == NULL)
2623 				ire_refrele(ire);
2624 			if (sire != NULL)
2625 				ire_refrele(sire);
2626 			return (0);
2627 		}
2628 
2629 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2630 			in6_addr_t	src_addr;
2631 
2632 			/*
2633 			 * ip_bind_connected_v6() has stored the correct source
2634 			 * address per IPv6 addr. selection policy in
2635 			 * conn_src_v6.
2636 			 */
2637 			src_addr = tcp->tcp_connp->conn_srcv6;
2638 
2639 			tcp->tcp_ip6h->ip6_src = src_addr;
2640 			/*
2641 			 * Copy of the src addr. in tcp_t is needed
2642 			 * for the lookup funcs.
2643 			 */
2644 			tcp->tcp_ip_src_v6 = src_addr;
2645 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2646 			    &connp->conn_srcv6));
2647 		}
2648 		tcp->tcp_localnet =
2649 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2650 	}
2651 
2652 	/*
2653 	 * This allows applications to fail quickly when connections are made
2654 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2655 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2656 	 */
2657 	if ((ire->ire_flags & RTF_REJECT) &&
2658 	    (ire->ire_flags & RTF_PRIVATE))
2659 		goto error;
2660 
2661 	/*
2662 	 * Make use of the cached rtt and rtt_sd values to calculate the
2663 	 * initial RTO.  Note that they are already initialized in
2664 	 * tcp_init_values().
2665 	 */
2666 	if (ire_uinfo->iulp_rtt != 0) {
2667 		clock_t	rto;
2668 
2669 		tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2670 		tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2671 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2672 		    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2673 
2674 		if (rto > tcp_rexmit_interval_max) {
2675 			tcp->tcp_rto = tcp_rexmit_interval_max;
2676 		} else if (rto < tcp_rexmit_interval_min) {
2677 			tcp->tcp_rto = tcp_rexmit_interval_min;
2678 		} else {
2679 			tcp->tcp_rto = rto;
2680 		}
2681 	}
2682 	if (ire_uinfo->iulp_ssthresh != 0)
2683 		tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2684 	else
2685 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2686 	if (ire_uinfo->iulp_spipe > 0) {
2687 		tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2688 		    tcp_max_buf);
2689 		if (tcp_snd_lowat_fraction != 0)
2690 			tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2691 			    tcp_snd_lowat_fraction;
2692 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2693 	}
2694 	/*
2695 	 * Note that up till now, acceptor always inherits receive
2696 	 * window from the listener.  But if there is a metrics associated
2697 	 * with a host, we should use that instead of inheriting it from
2698 	 * listener.  Thus we need to pass this info back to the caller.
2699 	 */
2700 	if (ire_uinfo->iulp_rpipe > 0) {
2701 		tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2702 	} else {
2703 		/*
2704 		 * For passive open, set tcp_rwnd to 0 so that the caller
2705 		 * knows that there is no rpipe metric for this connection.
2706 		 */
2707 		if (tcp_detached)
2708 			tcp->tcp_rwnd = 0;
2709 	}
2710 	if (ire_uinfo->iulp_rtomax > 0) {
2711 		tcp->tcp_second_timer_threshold = ire_uinfo->iulp_rtomax;
2712 	}
2713 
2714 	/*
2715 	 * Use the metric option settings, iulp_tstamp_ok and iulp_wscale_ok,
2716 	 * only for active open.  What this means is that if the other side
2717 	 * uses timestamp or window scale option, TCP will also use those
2718 	 * options.  That is for passive open.  If the application sets a
2719 	 * large window, window scale is enabled regardless of the value in
2720 	 * iulp_wscale_ok.  This is the behavior since 2.6.  So we keep it.
2721 	 * The only case left in passive open processing is the check for SACK.
2722 	 *
2723 	 * For ECN, it should probably be like SACK.  But the current
2724 	 * value is binary, so we treat it like the other cases.  The
2725 	 * metric only controls active open.  For passive open, the ndd
2726 	 * param, tcp_ecn_permitted, controls the behavior.
2727 	 */
2728 	if (!tcp_detached) {
2729 		/*
2730 		 * The if check means that the following can only be turned
2731 		 * on by the metrics only IRE, but not off.
2732 		 */
2733 		if (ire_uinfo->iulp_tstamp_ok)
2734 			tcp->tcp_snd_ts_ok = B_TRUE;
2735 		if (ire_uinfo->iulp_wscale_ok)
2736 			tcp->tcp_snd_ws_ok = B_TRUE;
2737 		if (ire_uinfo->iulp_sack == 2)
2738 			tcp->tcp_snd_sack_ok = B_TRUE;
2739 		if (ire_uinfo->iulp_ecn_ok)
2740 			tcp->tcp_ecn_ok = B_TRUE;
2741 	} else {
2742 		/*
2743 		 * Passive open.
2744 		 *
2745 		 * As above, the if check means that SACK can only be
2746 		 * turned on by the metric only IRE.
2747 		 */
2748 		if (ire_uinfo->iulp_sack > 0) {
2749 			tcp->tcp_snd_sack_ok = B_TRUE;
2750 		}
2751 	}
2752 
2753 	/*
2754 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2755 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2756 	 * length of all those options exceeds 28 bytes.  But because
2757 	 * of the tcp_mss_min check below, we may not have a problem if
2758 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2759 	 * the negative problem still exists.  And the check defeats PMTUd.
2760 	 * In fact, if PMTUd finds that the MSS should be smaller than
2761 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2762 	 * value.
2763 	 *
2764 	 * We do not deal with that now.  All those problems related to
2765 	 * PMTUd will be fixed later.
2766 	 */
2767 	ASSERT(ire->ire_max_frag != 0);
2768 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2769 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2770 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2771 			mss = MIN(mss, IPV6_MIN_MTU);
2772 		}
2773 	}
2774 
2775 	/* Sanity check for MSS value. */
2776 	if (tcp->tcp_ipversion == IPV4_VERSION)
2777 		mss_max = tcp_mss_max_ipv4;
2778 	else
2779 		mss_max = tcp_mss_max_ipv6;
2780 
2781 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2782 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2783 		/*
2784 		 * After receiving an ICMPv6 "packet too big" message with a
2785 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2786 		 * will insert a 8-byte fragment header in every packet; we
2787 		 * reduce the MSS by that amount here.
2788 		 */
2789 		mss -= sizeof (ip6_frag_t);
2790 	}
2791 
2792 	if (tcp->tcp_ipsec_overhead == 0)
2793 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2794 
2795 	mss -= tcp->tcp_ipsec_overhead;
2796 
2797 	if (mss < tcp_mss_min)
2798 		mss = tcp_mss_min;
2799 	if (mss > mss_max)
2800 		mss = mss_max;
2801 
2802 	/* Note that this is the maximum MSS, excluding all options. */
2803 	tcp->tcp_mss = mss;
2804 
2805 	/*
2806 	 * Initialize the ISS here now that we have the full connection ID.
2807 	 * The RFC 1948 method of initial sequence number generation requires
2808 	 * knowledge of the full connection ID before setting the ISS.
2809 	 */
2810 
2811 	tcp_iss_init(tcp);
2812 
2813 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2814 		tcp->tcp_loopback = B_TRUE;
2815 
2816 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2817 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2818 	} else {
2819 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2820 	}
2821 
2822 	if (hsp != NULL) {
2823 		/* Only modify if we're going to make them bigger */
2824 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2825 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2826 			if (tcp_snd_lowat_fraction != 0)
2827 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2828 					tcp_snd_lowat_fraction;
2829 		}
2830 
2831 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2832 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2833 		}
2834 
2835 		/* Copy timestamp flag only for active open */
2836 		if (!tcp_detached)
2837 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2838 	}
2839 
2840 	if (sire != NULL)
2841 		IRE_REFRELE(sire);
2842 
2843 	/*
2844 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2845 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2846 	 */
2847 	if (tcp->tcp_loopback ||
2848 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2849 		/*
2850 		 * For incoming, see if this tcp may be MDT-capable.  For
2851 		 * outgoing, this process has been taken care of through
2852 		 * tcp_rput_other.
2853 		 */
2854 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2855 		tcp->tcp_ire_ill_check_done = B_TRUE;
2856 	}
2857 
2858 	mutex_enter(&connp->conn_lock);
2859 	/*
2860 	 * Make sure that conn is not marked incipient
2861 	 * for incoming connections. A blind
2862 	 * removal of incipient flag is cheaper than
2863 	 * check and removal.
2864 	 */
2865 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2866 
2867 	/* Must not cache forwarding table routes. */
2868 	if (ire_cacheable) {
2869 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2870 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2871 			connp->conn_ire_cache = ire;
2872 			IRE_UNTRACE_REF(ire);
2873 			rw_exit(&ire->ire_bucket->irb_lock);
2874 			mutex_exit(&connp->conn_lock);
2875 			return (1);
2876 		}
2877 		rw_exit(&ire->ire_bucket->irb_lock);
2878 	}
2879 	mutex_exit(&connp->conn_lock);
2880 
2881 	if (ire->ire_mp == NULL)
2882 		ire_refrele(ire);
2883 	return (1);
2884 
2885 error:
2886 	if (ire->ire_mp == NULL)
2887 		ire_refrele(ire);
2888 	if (sire != NULL)
2889 		ire_refrele(sire);
2890 	return (0);
2891 }
2892 
2893 /*
2894  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2895  * O_T_BIND_REQ/T_BIND_REQ message.
2896  */
2897 static void
2898 tcp_bind(tcp_t *tcp, mblk_t *mp)
2899 {
2900 	sin_t	*sin;
2901 	sin6_t	*sin6;
2902 	mblk_t	*mp1;
2903 	in_port_t requested_port;
2904 	in_port_t allocated_port;
2905 	struct T_bind_req *tbr;
2906 	boolean_t	bind_to_req_port_only;
2907 	boolean_t	backlog_update = B_FALSE;
2908 	boolean_t	user_specified;
2909 	in6_addr_t	v6addr;
2910 	ipaddr_t	v4addr;
2911 	uint_t	origipversion;
2912 	int	err;
2913 	queue_t *q = tcp->tcp_wq;
2914 
2915 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2916 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2917 		if (tcp->tcp_debug) {
2918 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2919 			    "tcp_bind: bad req, len %u",
2920 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2921 		}
2922 		tcp_err_ack(tcp, mp, TPROTO, 0);
2923 		return;
2924 	}
2925 	/* Make sure the largest address fits */
2926 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2927 	if (mp1 == NULL) {
2928 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2929 		return;
2930 	}
2931 	mp = mp1;
2932 	tbr = (struct T_bind_req *)mp->b_rptr;
2933 	if (tcp->tcp_state >= TCPS_BOUND) {
2934 		if ((tcp->tcp_state == TCPS_BOUND ||
2935 		    tcp->tcp_state == TCPS_LISTEN) &&
2936 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
2937 		    tbr->CONIND_number > 0) {
2938 			/*
2939 			 * Handle listen() increasing CONIND_number.
2940 			 * This is more "liberal" then what the TPI spec
2941 			 * requires but is needed to avoid a t_unbind
2942 			 * when handling listen() since the port number
2943 			 * might be "stolen" between the unbind and bind.
2944 			 */
2945 			backlog_update = B_TRUE;
2946 			goto do_bind;
2947 		}
2948 		if (tcp->tcp_debug) {
2949 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2950 			    "tcp_bind: bad state, %d", tcp->tcp_state);
2951 		}
2952 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
2953 		return;
2954 	}
2955 	origipversion = tcp->tcp_ipversion;
2956 
2957 	switch (tbr->ADDR_length) {
2958 	case 0:			/* request for a generic port */
2959 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2960 		if (tcp->tcp_family == AF_INET) {
2961 			tbr->ADDR_length = sizeof (sin_t);
2962 			sin = (sin_t *)&tbr[1];
2963 			*sin = sin_null;
2964 			sin->sin_family = AF_INET;
2965 			mp->b_wptr = (uchar_t *)&sin[1];
2966 			tcp->tcp_ipversion = IPV4_VERSION;
2967 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
2968 		} else {
2969 			ASSERT(tcp->tcp_family == AF_INET6);
2970 			tbr->ADDR_length = sizeof (sin6_t);
2971 			sin6 = (sin6_t *)&tbr[1];
2972 			*sin6 = sin6_null;
2973 			sin6->sin6_family = AF_INET6;
2974 			mp->b_wptr = (uchar_t *)&sin6[1];
2975 			tcp->tcp_ipversion = IPV6_VERSION;
2976 			V6_SET_ZERO(v6addr);
2977 		}
2978 		requested_port = 0;
2979 		break;
2980 
2981 	case sizeof (sin_t):	/* Complete IPv4 address */
2982 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
2983 		    sizeof (sin_t));
2984 		if (sin == NULL || !OK_32PTR((char *)sin)) {
2985 			if (tcp->tcp_debug) {
2986 				(void) strlog(TCP_MOD_ID, 0, 1,
2987 				    SL_ERROR|SL_TRACE,
2988 				    "tcp_bind: bad address parameter, "
2989 				    "offset %d, len %d",
2990 				    tbr->ADDR_offset, tbr->ADDR_length);
2991 			}
2992 			tcp_err_ack(tcp, mp, TPROTO, 0);
2993 			return;
2994 		}
2995 		/*
2996 		 * With sockets sockfs will accept bogus sin_family in
2997 		 * bind() and replace it with the family used in the socket
2998 		 * call.
2999 		 */
3000 		if (sin->sin_family != AF_INET ||
3001 		    tcp->tcp_family != AF_INET) {
3002 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3003 			return;
3004 		}
3005 		requested_port = ntohs(sin->sin_port);
3006 		tcp->tcp_ipversion = IPV4_VERSION;
3007 		v4addr = sin->sin_addr.s_addr;
3008 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3009 		break;
3010 
3011 	case sizeof (sin6_t): /* Complete IPv6 address */
3012 		sin6 = (sin6_t *)mi_offset_param(mp,
3013 		    tbr->ADDR_offset, sizeof (sin6_t));
3014 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3015 			if (tcp->tcp_debug) {
3016 				(void) strlog(TCP_MOD_ID, 0, 1,
3017 				    SL_ERROR|SL_TRACE,
3018 				    "tcp_bind: bad IPv6 address parameter, "
3019 				    "offset %d, len %d", tbr->ADDR_offset,
3020 				    tbr->ADDR_length);
3021 			}
3022 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3023 			return;
3024 		}
3025 		if (sin6->sin6_family != AF_INET6 ||
3026 		    tcp->tcp_family != AF_INET6) {
3027 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3028 			return;
3029 		}
3030 		requested_port = ntohs(sin6->sin6_port);
3031 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3032 		    IPV4_VERSION : IPV6_VERSION;
3033 		v6addr = sin6->sin6_addr;
3034 		break;
3035 
3036 	default:
3037 		if (tcp->tcp_debug) {
3038 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3039 			    "tcp_bind: bad address length, %d",
3040 			    tbr->ADDR_length);
3041 		}
3042 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3043 		return;
3044 	}
3045 	tcp->tcp_bound_source_v6 = v6addr;
3046 
3047 	/* Check for change in ipversion */
3048 	if (origipversion != tcp->tcp_ipversion) {
3049 		ASSERT(tcp->tcp_family == AF_INET6);
3050 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3051 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3052 		if (err) {
3053 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3054 			return;
3055 		}
3056 	}
3057 
3058 	/*
3059 	 * Initialize family specific fields. Copy of the src addr.
3060 	 * in tcp_t is needed for the lookup funcs.
3061 	 */
3062 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3063 		tcp->tcp_ip6h->ip6_src = v6addr;
3064 	} else {
3065 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3066 	}
3067 	tcp->tcp_ip_src_v6 = v6addr;
3068 
3069 	/*
3070 	 * For O_T_BIND_REQ:
3071 	 * Verify that the target port/addr is available, or choose
3072 	 * another.
3073 	 * For  T_BIND_REQ:
3074 	 * Verify that the target port/addr is available or fail.
3075 	 * In both cases when it succeeds the tcp is inserted in the
3076 	 * bind hash table. This ensures that the operation is atomic
3077 	 * under the lock on the hash bucket.
3078 	 */
3079 	bind_to_req_port_only = requested_port != 0 &&
3080 	    tbr->PRIM_type != O_T_BIND_REQ;
3081 	/*
3082 	 * Get a valid port (within the anonymous range and should not
3083 	 * be a privileged one) to use if the user has not given a port.
3084 	 * If multiple threads are here, they may all start with
3085 	 * with the same initial port. But, it should be fine as long as
3086 	 * tcp_bindi will ensure that no two threads will be assigned
3087 	 * the same port.
3088 	 *
3089 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3090 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3091 	 * unless TCP_ANONPRIVBIND option is set.
3092 	 */
3093 	if (requested_port == 0) {
3094 		requested_port = tcp->tcp_anon_priv_bind ?
3095 		    tcp_get_next_priv_port() :
3096 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3097 		user_specified = B_FALSE;
3098 	} else {
3099 		int i;
3100 		boolean_t priv = B_FALSE;
3101 		/*
3102 		 * If the requested_port is in the well-known privileged range,
3103 		 * verify that the stream was opened by a privileged user.
3104 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3105 		 * but instead the code relies on:
3106 		 * - the fact that the address of the array and its size never
3107 		 *   changes
3108 		 * - the atomic assignment of the elements of the array
3109 		 */
3110 		if (requested_port < tcp_smallest_nonpriv_port) {
3111 			priv = B_TRUE;
3112 		} else {
3113 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3114 				if (requested_port ==
3115 				    tcp_g_epriv_ports[i]) {
3116 					priv = B_TRUE;
3117 					break;
3118 				}
3119 			}
3120 		}
3121 		if (priv) {
3122 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3123 
3124 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3125 				if (tcp->tcp_debug) {
3126 					(void) strlog(TCP_MOD_ID, 0, 1,
3127 					    SL_ERROR|SL_TRACE,
3128 					    "tcp_bind: no priv for port %d",
3129 					    requested_port);
3130 				}
3131 				tcp_err_ack(tcp, mp, TACCES, 0);
3132 				return;
3133 			}
3134 		}
3135 		user_specified = B_TRUE;
3136 	}
3137 
3138 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3139 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3140 
3141 	if (allocated_port == 0) {
3142 		if (bind_to_req_port_only) {
3143 			if (tcp->tcp_debug) {
3144 				(void) strlog(TCP_MOD_ID, 0, 1,
3145 				    SL_ERROR|SL_TRACE,
3146 				    "tcp_bind: requested addr busy");
3147 			}
3148 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3149 		} else {
3150 			/* If we are out of ports, fail the bind. */
3151 			if (tcp->tcp_debug) {
3152 				(void) strlog(TCP_MOD_ID, 0, 1,
3153 				    SL_ERROR|SL_TRACE,
3154 				    "tcp_bind: out of ports?");
3155 			}
3156 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3157 		}
3158 		return;
3159 	}
3160 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3161 do_bind:
3162 	if (!backlog_update) {
3163 		if (tcp->tcp_family == AF_INET)
3164 			sin->sin_port = htons(allocated_port);
3165 		else
3166 			sin6->sin6_port = htons(allocated_port);
3167 	}
3168 	if (tcp->tcp_family == AF_INET) {
3169 		if (tbr->CONIND_number != 0) {
3170 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3171 			    sizeof (sin_t));
3172 		} else {
3173 			/* Just verify the local IP address */
3174 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3175 		}
3176 	} else {
3177 		if (tbr->CONIND_number != 0) {
3178 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3179 			    sizeof (sin6_t));
3180 		} else {
3181 			/* Just verify the local IP address */
3182 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3183 			    IPV6_ADDR_LEN);
3184 		}
3185 	}
3186 	if (!mp1) {
3187 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3188 		return;
3189 	}
3190 
3191 	tbr->PRIM_type = T_BIND_ACK;
3192 	mp->b_datap->db_type = M_PCPROTO;
3193 
3194 	/* Chain in the reply mp for tcp_rput() */
3195 	mp1->b_cont = mp;
3196 	mp = mp1;
3197 
3198 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3199 	if (tcp->tcp_conn_req_max) {
3200 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3201 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3202 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3203 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3204 		/*
3205 		 * If this is a listener, do not reset the eager list
3206 		 * and other stuffs.  Note that we don't check if the
3207 		 * existing eager list meets the new tcp_conn_req_max
3208 		 * requirement.
3209 		 */
3210 		if (tcp->tcp_state != TCPS_LISTEN) {
3211 			tcp->tcp_state = TCPS_LISTEN;
3212 			/* Initialize the chain. Don't need the eager_lock */
3213 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3214 			tcp->tcp_second_ctimer_threshold =
3215 			    tcp_ip_abort_linterval;
3216 		}
3217 	}
3218 
3219 	/*
3220 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3221 	 * processing continues in tcp_rput_other().
3222 	 */
3223 	if (tcp->tcp_family == AF_INET6) {
3224 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3225 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3226 	} else {
3227 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3228 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3229 	}
3230 	/*
3231 	 * If the bind cannot complete immediately
3232 	 * IP will arrange to call tcp_rput_other
3233 	 * when the bind completes.
3234 	 */
3235 	if (mp != NULL) {
3236 		tcp_rput_other(tcp, mp);
3237 	} else {
3238 		/*
3239 		 * Bind will be resumed later. Need to ensure
3240 		 * that conn doesn't disappear when that happens.
3241 		 * This will be decremented in ip_resume_tcp_bind().
3242 		 */
3243 		CONN_INC_REF(tcp->tcp_connp);
3244 	}
3245 }
3246 
3247 
3248 /*
3249  * If the "bind_to_req_port_only" parameter is set, if the requested port
3250  * number is available, return it, If not return 0
3251  *
3252  * If "bind_to_req_port_only" parameter is not set and
3253  * If the requested port number is available, return it.  If not, return
3254  * the first anonymous port we happen across.  If no anonymous ports are
3255  * available, return 0. addr is the requested local address, if any.
3256  *
3257  * In either case, when succeeding update the tcp_t to record the port number
3258  * and insert it in the bind hash table.
3259  *
3260  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3261  * without setting SO_REUSEADDR. This is needed so that they
3262  * can be viewed as two independent transport protocols.
3263  */
3264 static in_port_t
3265 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3266     int reuseaddr, boolean_t quick_connect,
3267     boolean_t bind_to_req_port_only, boolean_t user_specified)
3268 {
3269 	/* number of times we have run around the loop */
3270 	int count = 0;
3271 	/* maximum number of times to run around the loop */
3272 	int loopmax;
3273 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
3274 
3275 	/*
3276 	 * Lookup for free addresses is done in a loop and "loopmax"
3277 	 * influences how long we spin in the loop
3278 	 */
3279 	if (bind_to_req_port_only) {
3280 		/*
3281 		 * If the requested port is busy, don't bother to look
3282 		 * for a new one. Setting loop maximum count to 1 has
3283 		 * that effect.
3284 		 */
3285 		loopmax = 1;
3286 	} else {
3287 		/*
3288 		 * If the requested port is busy, look for a free one
3289 		 * in the anonymous port range.
3290 		 * Set loopmax appropriately so that one does not look
3291 		 * forever in the case all of the anonymous ports are in use.
3292 		 */
3293 		if (tcp->tcp_anon_priv_bind) {
3294 			/*
3295 			 * loopmax =
3296 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3297 			 */
3298 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3299 		} else {
3300 			loopmax = (tcp_largest_anon_port -
3301 			    tcp_smallest_anon_port + 1);
3302 		}
3303 	}
3304 	do {
3305 		uint16_t	lport;
3306 		tf_t		*tbf;
3307 		tcp_t		*ltcp;
3308 
3309 		lport = htons(port);
3310 
3311 		/*
3312 		 * Ensure that the tcp_t is not currently in the bind hash.
3313 		 * Hold the lock on the hash bucket to ensure that
3314 		 * the duplicate check plus the insertion is an atomic
3315 		 * operation.
3316 		 *
3317 		 * This function does an inline lookup on the bind hash list
3318 		 * Make sure that we access only members of tcp_t
3319 		 * and that we don't look at tcp_tcp, since we are not
3320 		 * doing a CONN_INC_REF.
3321 		 */
3322 		tcp_bind_hash_remove(tcp);
3323 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3324 		mutex_enter(&tbf->tf_lock);
3325 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3326 		    ltcp = ltcp->tcp_bind_hash) {
3327 			if (lport != ltcp->tcp_lport ||
3328 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
3329 				continue;
3330 			}
3331 
3332 			/*
3333 			 * If TCP_EXCLBIND is set for either the bound or
3334 			 * binding endpoint, the semantics of bind
3335 			 * is changed according to the following.
3336 			 *
3337 			 * spec = specified address (v4 or v6)
3338 			 * unspec = unspecified address (v4 or v6)
3339 			 * A = specified addresses are different for endpoints
3340 			 *
3341 			 * bound	bind to		allowed
3342 			 * -------------------------------------
3343 			 * unspec	unspec		no
3344 			 * unspec	spec		no
3345 			 * spec		unspec		no
3346 			 * spec		spec		yes if A
3347 			 *
3348 			 * Note:
3349 			 *
3350 			 * 1. Because of TLI semantics, an endpoint can go
3351 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3352 			 * TCPS_BOUND, depending on whether it is originally
3353 			 * a listener or not.  That is why we need to check
3354 			 * for states greater than or equal to TCPS_BOUND
3355 			 * here.
3356 			 *
3357 			 * 2. Ideally, we should only check for state equals
3358 			 * to TCPS_LISTEN. And the following check should be
3359 			 * added.
3360 			 *
3361 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3362 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3363 			 *		...
3364 			 * }
3365 			 *
3366 			 * The semantics will be changed to this.  If the
3367 			 * endpoint on the list is in state not equal to
3368 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3369 			 * set, let the bind succeed.
3370 			 *
3371 			 * But because of (1), we cannot do that now.  If
3372 			 * in future, we can change this going back semantics,
3373 			 * we can add the above check.
3374 			 */
3375 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
3376 				if (V6_OR_V4_INADDR_ANY(
3377 				    ltcp->tcp_bound_source_v6) ||
3378 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3379 				    IN6_ARE_ADDR_EQUAL(laddr,
3380 				    &ltcp->tcp_bound_source_v6)) {
3381 					break;
3382 				}
3383 				continue;
3384 			}
3385 
3386 			/*
3387 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3388 			 * have disjoint port number spaces, if *_EXCLBIND
3389 			 * is not set and only if the application binds to a
3390 			 * specific port. We use the same autoassigned port
3391 			 * number space for IPv4 and IPv6 sockets.
3392 			 */
3393 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3394 			    bind_to_req_port_only)
3395 				continue;
3396 
3397 			/*
3398 			 * Ideally, we should make sure that the source
3399 			 * address, remote address, and remote port in the
3400 			 * four tuple for this tcp-connection is unique.
3401 			 * However, trying to find out the local source
3402 			 * address would require too much code duplication
3403 			 * with IP, since IP needs needs to have that code
3404 			 * to support userland TCP implementations.
3405 			 */
3406 			if (quick_connect &&
3407 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3408 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3409 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3410 				    &ltcp->tcp_remote_v6)))
3411 				continue;
3412 
3413 			if (!reuseaddr) {
3414 				/*
3415 				 * No socket option SO_REUSEADDR.
3416 				 * If existing port is bound to
3417 				 * a non-wildcard IP address
3418 				 * and the requesting stream is
3419 				 * bound to a distinct
3420 				 * different IP addresses
3421 				 * (non-wildcard, also), keep
3422 				 * going.
3423 				 */
3424 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3425 				    !V6_OR_V4_INADDR_ANY(
3426 				    ltcp->tcp_bound_source_v6) &&
3427 				    !IN6_ARE_ADDR_EQUAL(laddr,
3428 					&ltcp->tcp_bound_source_v6))
3429 					continue;
3430 				if (ltcp->tcp_state >= TCPS_BOUND) {
3431 					/*
3432 					 * This port is being used and
3433 					 * its state is >= TCPS_BOUND,
3434 					 * so we can't bind to it.
3435 					 */
3436 					break;
3437 				}
3438 			} else {
3439 				/*
3440 				 * socket option SO_REUSEADDR is set on the
3441 				 * binding tcp_t.
3442 				 *
3443 				 * If two streams are bound to
3444 				 * same IP address or both addr
3445 				 * and bound source are wildcards
3446 				 * (INADDR_ANY), we want to stop
3447 				 * searching.
3448 				 * We have found a match of IP source
3449 				 * address and source port, which is
3450 				 * refused regardless of the
3451 				 * SO_REUSEADDR setting, so we break.
3452 				 */
3453 				if (IN6_ARE_ADDR_EQUAL(laddr,
3454 				    &ltcp->tcp_bound_source_v6) &&
3455 				    (ltcp->tcp_state == TCPS_LISTEN ||
3456 					ltcp->tcp_state == TCPS_BOUND))
3457 					break;
3458 			}
3459 		}
3460 		if (ltcp != NULL) {
3461 			/* The port number is busy */
3462 			mutex_exit(&tbf->tf_lock);
3463 		} else {
3464 			/*
3465 			 * This port is ours. Insert in fanout and mark as
3466 			 * bound to prevent others from getting the port
3467 			 * number.
3468 			 */
3469 			tcp->tcp_state = TCPS_BOUND;
3470 			tcp->tcp_lport = htons(port);
3471 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3472 
3473 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3474 			    tcp->tcp_lport)] == tbf);
3475 			tcp_bind_hash_insert(tbf, tcp, 1);
3476 
3477 			mutex_exit(&tbf->tf_lock);
3478 
3479 			/*
3480 			 * We don't want tcp_next_port_to_try to "inherit"
3481 			 * a port number supplied by the user in a bind.
3482 			 */
3483 			if (user_specified)
3484 				return (port);
3485 
3486 			/*
3487 			 * This is the only place where tcp_next_port_to_try
3488 			 * is updated. After the update, it may or may not
3489 			 * be in the valid range.
3490 			 */
3491 			if (!tcp->tcp_anon_priv_bind)
3492 				tcp_next_port_to_try = port + 1;
3493 			return (port);
3494 		}
3495 
3496 		if (tcp->tcp_anon_priv_bind) {
3497 			port = tcp_get_next_priv_port();
3498 		} else {
3499 			if (count == 0 && user_specified) {
3500 				/*
3501 				 * We may have to return an anonymous port. So
3502 				 * get one to start with.
3503 				 */
3504 				port =
3505 				    tcp_update_next_port(tcp_next_port_to_try,
3506 					B_TRUE);
3507 				user_specified = B_FALSE;
3508 			} else {
3509 				port = tcp_update_next_port(port + 1, B_FALSE);
3510 			}
3511 		}
3512 
3513 		/*
3514 		 * Don't let this loop run forever in the case where
3515 		 * all of the anonymous ports are in use.
3516 		 */
3517 	} while (++count < loopmax);
3518 	return (0);
3519 }
3520 
3521 /*
3522  * We are dying for some reason.  Try to do it gracefully.  (May be called
3523  * as writer.)
3524  *
3525  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3526  * done by a service procedure).
3527  * TBD - Should the return value distinguish between the tcp_t being
3528  * freed and it being reinitialized?
3529  */
3530 static int
3531 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3532 {
3533 	mblk_t	*mp;
3534 	queue_t	*q;
3535 
3536 	TCP_CLD_STAT(tag);
3537 
3538 #if TCP_TAG_CLEAN_DEATH
3539 	tcp->tcp_cleandeathtag = tag;
3540 #endif
3541 
3542 	if (tcp->tcp_linger_tid != 0 &&
3543 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3544 		tcp_stop_lingering(tcp);
3545 	}
3546 
3547 	ASSERT(tcp != NULL);
3548 	ASSERT((tcp->tcp_family == AF_INET &&
3549 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3550 	    (tcp->tcp_family == AF_INET6 &&
3551 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3552 	    tcp->tcp_ipversion == IPV6_VERSION)));
3553 
3554 	if (TCP_IS_DETACHED(tcp)) {
3555 		if (tcp->tcp_hard_binding) {
3556 			/*
3557 			 * Its an eager that we are dealing with. We close the
3558 			 * eager but in case a conn_ind has already gone to the
3559 			 * listener, let tcp_accept_finish() send a discon_ind
3560 			 * to the listener and drop the last reference. If the
3561 			 * listener doesn't even know about the eager i.e. the
3562 			 * conn_ind hasn't gone up, blow away the eager and drop
3563 			 * the last reference as well. If the conn_ind has gone
3564 			 * up, state should be BOUND. tcp_accept_finish
3565 			 * will figure out that the connection has received a
3566 			 * RST and will send a DISCON_IND to the application.
3567 			 */
3568 			tcp_closei_local(tcp);
3569 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3570 				CONN_DEC_REF(tcp->tcp_connp);
3571 			} else {
3572 				tcp->tcp_state = TCPS_BOUND;
3573 			}
3574 		} else {
3575 			tcp_close_detached(tcp);
3576 		}
3577 		return (0);
3578 	}
3579 
3580 	TCP_STAT(tcp_clean_death_nondetached);
3581 
3582 	/*
3583 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3584 	 * is run) postpone cleaning up the endpoint until service routine
3585 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3586 	 * client_errno since tcp_close uses the client_errno field.
3587 	 */
3588 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3589 		if (err != 0)
3590 			tcp->tcp_client_errno = err;
3591 
3592 		tcp->tcp_deferred_clean_death = B_TRUE;
3593 		return (-1);
3594 	}
3595 
3596 	q = tcp->tcp_rq;
3597 
3598 	/* Trash all inbound data */
3599 	flushq(q, FLUSHALL);
3600 
3601 	/*
3602 	 * If we are at least part way open and there is error
3603 	 * (err==0 implies no error)
3604 	 * notify our client by a T_DISCON_IND.
3605 	 */
3606 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3607 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3608 		    !TCP_IS_SOCKET(tcp)) {
3609 			/*
3610 			 * Send M_FLUSH according to TPI. Because sockets will
3611 			 * (and must) ignore FLUSHR we do that only for TPI
3612 			 * endpoints and sockets in STREAMS mode.
3613 			 */
3614 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3615 		}
3616 		if (tcp->tcp_debug) {
3617 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3618 			    "tcp_clean_death: discon err %d", err);
3619 		}
3620 		mp = mi_tpi_discon_ind(NULL, err, 0);
3621 		if (mp != NULL) {
3622 			putnext(q, mp);
3623 		} else {
3624 			if (tcp->tcp_debug) {
3625 				(void) strlog(TCP_MOD_ID, 0, 1,
3626 				    SL_ERROR|SL_TRACE,
3627 				    "tcp_clean_death, sending M_ERROR");
3628 			}
3629 			(void) putnextctl1(q, M_ERROR, EPROTO);
3630 		}
3631 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3632 			/* SYN_SENT or SYN_RCVD */
3633 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3634 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3635 			/* ESTABLISHED or CLOSE_WAIT */
3636 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3637 		}
3638 	}
3639 
3640 	tcp_reinit(tcp);
3641 	return (-1);
3642 }
3643 
3644 /*
3645  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3646  * to expire, stop the wait and finish the close.
3647  */
3648 static void
3649 tcp_stop_lingering(tcp_t *tcp)
3650 {
3651 	clock_t	delta = 0;
3652 
3653 	tcp->tcp_linger_tid = 0;
3654 	if (tcp->tcp_state > TCPS_LISTEN) {
3655 		tcp_acceptor_hash_remove(tcp);
3656 		if (tcp->tcp_flow_stopped) {
3657 			tcp_clrqfull(tcp);
3658 		}
3659 
3660 		if (tcp->tcp_timer_tid != 0) {
3661 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3662 			tcp->tcp_timer_tid = 0;
3663 		}
3664 		/*
3665 		 * Need to cancel those timers which will not be used when
3666 		 * TCP is detached.  This has to be done before the tcp_wq
3667 		 * is set to the global queue.
3668 		 */
3669 		tcp_timers_stop(tcp);
3670 
3671 
3672 		tcp->tcp_detached = B_TRUE;
3673 		tcp->tcp_rq = tcp_g_q;
3674 		tcp->tcp_wq = WR(tcp_g_q);
3675 
3676 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3677 			tcp_time_wait_append(tcp);
3678 			TCP_DBGSTAT(tcp_detach_time_wait);
3679 			goto finish;
3680 		}
3681 
3682 		/*
3683 		 * If delta is zero the timer event wasn't executed and was
3684 		 * successfully canceled. In this case we need to restart it
3685 		 * with the minimal delta possible.
3686 		 */
3687 		if (delta >= 0) {
3688 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3689 			    delta ? delta : 1);
3690 		}
3691 	} else {
3692 		tcp_closei_local(tcp);
3693 		CONN_DEC_REF(tcp->tcp_connp);
3694 	}
3695 finish:
3696 	/* Signal closing thread that it can complete close */
3697 	mutex_enter(&tcp->tcp_closelock);
3698 	tcp->tcp_detached = B_TRUE;
3699 	tcp->tcp_rq = tcp_g_q;
3700 	tcp->tcp_wq = WR(tcp_g_q);
3701 	tcp->tcp_closed = 1;
3702 	cv_signal(&tcp->tcp_closecv);
3703 	mutex_exit(&tcp->tcp_closelock);
3704 }
3705 
3706 /*
3707  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3708  * expires.
3709  */
3710 static void
3711 tcp_close_linger_timeout(void *arg)
3712 {
3713 	conn_t	*connp = (conn_t *)arg;
3714 	tcp_t 	*tcp = connp->conn_tcp;
3715 
3716 	tcp->tcp_client_errno = ETIMEDOUT;
3717 	tcp_stop_lingering(tcp);
3718 }
3719 
3720 static int
3721 tcp_close(queue_t *q, int flags)
3722 {
3723 	conn_t		*connp = Q_TO_CONN(q);
3724 	tcp_t		*tcp = connp->conn_tcp;
3725 	mblk_t 		*mp = &tcp->tcp_closemp;
3726 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3727 
3728 	ASSERT(WR(q)->q_next == NULL);
3729 	ASSERT(connp->conn_ref >= 2);
3730 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3731 
3732 	/*
3733 	 * We are being closed as /dev/tcp or /dev/tcp6.
3734 	 *
3735 	 * Mark the conn as closing. ill_pending_mp_add will not
3736 	 * add any mp to the pending mp list, after this conn has
3737 	 * started closing. Same for sq_pending_mp_add
3738 	 */
3739 	mutex_enter(&connp->conn_lock);
3740 	connp->conn_state_flags |= CONN_CLOSING;
3741 	if (connp->conn_oper_pending_ill != NULL)
3742 		conn_ioctl_cleanup_reqd = B_TRUE;
3743 	CONN_INC_REF_LOCKED(connp);
3744 	mutex_exit(&connp->conn_lock);
3745 	tcp->tcp_closeflags = (uint8_t)flags;
3746 	ASSERT(connp->conn_ref >= 3);
3747 
3748 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3749 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3750 
3751 	mutex_enter(&tcp->tcp_closelock);
3752 
3753 	while (!tcp->tcp_closed)
3754 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3755 	mutex_exit(&tcp->tcp_closelock);
3756 	/*
3757 	 * In the case of listener streams that have eagers in the q or q0
3758 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3759 	 * tcp_wq of the eagers point to our queues. By waiting for the
3760 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3761 	 * up their queue pointers and also dropped their references to us.
3762 	 */
3763 	if (tcp->tcp_wait_for_eagers) {
3764 		mutex_enter(&connp->conn_lock);
3765 		while (connp->conn_ref != 1) {
3766 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3767 		}
3768 		mutex_exit(&connp->conn_lock);
3769 	}
3770 	/*
3771 	 * ioctl cleanup. The mp is queued in the
3772 	 * ill_pending_mp or in the sq_pending_mp.
3773 	 */
3774 	if (conn_ioctl_cleanup_reqd)
3775 		conn_ioctl_cleanup(connp);
3776 
3777 	qprocsoff(q);
3778 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3779 
3780 	ASSERT(connp->conn_cred != NULL);
3781 	crfree(connp->conn_cred);
3782 	tcp->tcp_cred = connp->conn_cred = NULL;
3783 	tcp->tcp_cpid = -1;
3784 
3785 	/*
3786 	 * Drop IP's reference on the conn. This is the last reference
3787 	 * on the connp if the state was less than established. If the
3788 	 * connection has gone into timewait state, then we will have
3789 	 * one ref for the TCP and one more ref (total of two) for the
3790 	 * classifier connected hash list (a timewait connections stays
3791 	 * in connected hash till closed).
3792 	 *
3793 	 * We can't assert the references because there might be other
3794 	 * transient reference places because of some walkers or queued
3795 	 * packets in squeue for the timewait state.
3796 	 */
3797 	CONN_DEC_REF(connp);
3798 	q->q_ptr = WR(q)->q_ptr = NULL;
3799 	return (0);
3800 }
3801 
3802 static int
3803 tcpclose_accept(queue_t *q)
3804 {
3805 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3806 
3807 	/*
3808 	 * We had opened an acceptor STREAM for sockfs which is
3809 	 * now being closed due to some error.
3810 	 */
3811 	qprocsoff(q);
3812 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
3813 	q->q_ptr = WR(q)->q_ptr = NULL;
3814 	return (0);
3815 }
3816 
3817 
3818 /*
3819  * Called by streams close routine via squeues when our client blows off her
3820  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3821  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3822  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3823  * acked.
3824  *
3825  * NOTE: tcp_close potentially returns error when lingering.
3826  * However, the stream head currently does not pass these errors
3827  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3828  * errors to the application (from tsleep()) and not errors
3829  * like ECONNRESET caused by receiving a reset packet.
3830  */
3831 
3832 /* ARGSUSED */
3833 static void
3834 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3835 {
3836 	char	*msg;
3837 	conn_t	*connp = (conn_t *)arg;
3838 	tcp_t	*tcp = connp->conn_tcp;
3839 	clock_t	delta = 0;
3840 
3841 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3842 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3843 
3844 	/* Cancel any pending timeout */
3845 	if (tcp->tcp_ordrelid != 0) {
3846 		if (tcp->tcp_timeout) {
3847 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
3848 		}
3849 		tcp->tcp_ordrelid = 0;
3850 		tcp->tcp_timeout = B_FALSE;
3851 	}
3852 
3853 	mutex_enter(&tcp->tcp_eager_lock);
3854 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3855 		/* Cleanup for listener */
3856 		tcp_eager_cleanup(tcp, 0);
3857 		tcp->tcp_wait_for_eagers = 1;
3858 	}
3859 	mutex_exit(&tcp->tcp_eager_lock);
3860 
3861 	connp->conn_mdt_ok = B_FALSE;
3862 	tcp->tcp_mdt = B_FALSE;
3863 
3864 	msg = NULL;
3865 	switch (tcp->tcp_state) {
3866 	case TCPS_CLOSED:
3867 	case TCPS_IDLE:
3868 	case TCPS_BOUND:
3869 	case TCPS_LISTEN:
3870 		break;
3871 	case TCPS_SYN_SENT:
3872 		msg = "tcp_close, during connect";
3873 		break;
3874 	case TCPS_SYN_RCVD:
3875 		/*
3876 		 * Close during the connect 3-way handshake
3877 		 * but here there may or may not be pending data
3878 		 * already on queue. Process almost same as in
3879 		 * the ESTABLISHED state.
3880 		 */
3881 		/* FALLTHRU */
3882 	default:
3883 		if (tcp->tcp_fused)
3884 			tcp_unfuse(tcp);
3885 
3886 		/*
3887 		 * If SO_LINGER has set a zero linger time, abort the
3888 		 * connection with a reset.
3889 		 */
3890 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3891 			msg = "tcp_close, zero lingertime";
3892 			break;
3893 		}
3894 
3895 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3896 		/*
3897 		 * Abort connection if there is unread data queued.
3898 		 */
3899 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3900 			msg = "tcp_close, unread data";
3901 			break;
3902 		}
3903 		/*
3904 		 * tcp_hard_bound is now cleared thus all packets go through
3905 		 * tcp_lookup. This fact is used by tcp_detach below.
3906 		 *
3907 		 * We have done a qwait() above which could have possibly
3908 		 * drained more messages in turn causing transition to a
3909 		 * different state. Check whether we have to do the rest
3910 		 * of the processing or not.
3911 		 */
3912 		if (tcp->tcp_state <= TCPS_LISTEN)
3913 			break;
3914 
3915 		/*
3916 		 * Transmit the FIN before detaching the tcp_t.
3917 		 * After tcp_detach returns this queue/perimeter
3918 		 * no longer owns the tcp_t thus others can modify it.
3919 		 */
3920 		(void) tcp_xmit_end(tcp);
3921 
3922 		/*
3923 		 * If lingering on close then wait until the fin is acked,
3924 		 * the SO_LINGER time passes, or a reset is sent/received.
3925 		 */
3926 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3927 		    !(tcp->tcp_fin_acked) &&
3928 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3929 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3930 				tcp->tcp_client_errno = EWOULDBLOCK;
3931 			} else if (tcp->tcp_client_errno == 0) {
3932 
3933 				ASSERT(tcp->tcp_linger_tid == 0);
3934 
3935 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3936 				    tcp_close_linger_timeout,
3937 				    tcp->tcp_lingertime * hz);
3938 
3939 				/* tcp_close_linger_timeout will finish close */
3940 				if (tcp->tcp_linger_tid == 0)
3941 					tcp->tcp_client_errno = ENOSR;
3942 				else
3943 					return;
3944 			}
3945 
3946 			/*
3947 			 * Check if we need to detach or just close
3948 			 * the instance.
3949 			 */
3950 			if (tcp->tcp_state <= TCPS_LISTEN)
3951 				break;
3952 		}
3953 
3954 		/*
3955 		 * Make sure that no other thread will access the tcp_rq of
3956 		 * this instance (through lookups etc.) as tcp_rq will go
3957 		 * away shortly.
3958 		 */
3959 		tcp_acceptor_hash_remove(tcp);
3960 
3961 		if (tcp->tcp_flow_stopped) {
3962 			tcp_clrqfull(tcp);
3963 		}
3964 
3965 		if (tcp->tcp_timer_tid != 0) {
3966 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3967 			tcp->tcp_timer_tid = 0;
3968 		}
3969 		/*
3970 		 * Need to cancel those timers which will not be used when
3971 		 * TCP is detached.  This has to be done before the tcp_wq
3972 		 * is set to the global queue.
3973 		 */
3974 		tcp_timers_stop(tcp);
3975 
3976 		tcp->tcp_detached = B_TRUE;
3977 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3978 			tcp_time_wait_append(tcp);
3979 			TCP_DBGSTAT(tcp_detach_time_wait);
3980 			ASSERT(connp->conn_ref >= 3);
3981 			goto finish;
3982 		}
3983 
3984 		/*
3985 		 * If delta is zero the timer event wasn't executed and was
3986 		 * successfully canceled. In this case we need to restart it
3987 		 * with the minimal delta possible.
3988 		 */
3989 		if (delta >= 0)
3990 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3991 			    delta ? delta : 1);
3992 
3993 		ASSERT(connp->conn_ref >= 3);
3994 		goto finish;
3995 	}
3996 
3997 	/* Detach did not complete. Still need to remove q from stream. */
3998 	if (msg) {
3999 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4000 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4001 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4002 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4003 		    tcp->tcp_state == TCPS_SYN_RCVD)
4004 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4005 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4006 	}
4007 
4008 	tcp_closei_local(tcp);
4009 	CONN_DEC_REF(connp);
4010 	ASSERT(connp->conn_ref >= 2);
4011 
4012 finish:
4013 	/*
4014 	 * Although packets are always processed on the correct
4015 	 * tcp's perimeter and access is serialized via squeue's,
4016 	 * IP still needs a queue when sending packets in time_wait
4017 	 * state so use WR(tcp_g_q) till ip_output() can be
4018 	 * changed to deal with just connp. For read side, we
4019 	 * could have set tcp_rq to NULL but there are some cases
4020 	 * in tcp_rput_data() from early days of this code which
4021 	 * do a putnext without checking if tcp is closed. Those
4022 	 * need to be identified before both tcp_rq and tcp_wq
4023 	 * can be set to NULL and tcp_q_q can disappear forever.
4024 	 */
4025 	mutex_enter(&tcp->tcp_closelock);
4026 	/*
4027 	 * Don't change the queues in the case of a listener that has
4028 	 * eagers in its q or q0. It could surprise the eagers.
4029 	 * Instead wait for the eagers outside the squeue.
4030 	 */
4031 	if (!tcp->tcp_wait_for_eagers) {
4032 		tcp->tcp_detached = B_TRUE;
4033 		tcp->tcp_rq = tcp_g_q;
4034 		tcp->tcp_wq = WR(tcp_g_q);
4035 	}
4036 
4037 	/* Signal tcp_close() to finish closing. */
4038 	tcp->tcp_closed = 1;
4039 	cv_signal(&tcp->tcp_closecv);
4040 	mutex_exit(&tcp->tcp_closelock);
4041 }
4042 
4043 
4044 /*
4045  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4046  * Some stream heads get upset if they see these later on as anything but NULL.
4047  */
4048 static void
4049 tcp_close_mpp(mblk_t **mpp)
4050 {
4051 	mblk_t	*mp;
4052 
4053 	if ((mp = *mpp) != NULL) {
4054 		do {
4055 			mp->b_next = NULL;
4056 			mp->b_prev = NULL;
4057 		} while ((mp = mp->b_cont) != NULL);
4058 
4059 		mp = *mpp;
4060 		*mpp = NULL;
4061 		freemsg(mp);
4062 	}
4063 }
4064 
4065 /* Do detached close. */
4066 static void
4067 tcp_close_detached(tcp_t *tcp)
4068 {
4069 	if (tcp->tcp_fused)
4070 		tcp_unfuse(tcp);
4071 
4072 	/*
4073 	 * Clustering code serializes TCP disconnect callbacks and
4074 	 * cluster tcp list walks by blocking a TCP disconnect callback
4075 	 * if a cluster tcp list walk is in progress. This ensures
4076 	 * accurate accounting of TCPs in the cluster code even though
4077 	 * the TCP list walk itself is not atomic.
4078 	 */
4079 	tcp_closei_local(tcp);
4080 	CONN_DEC_REF(tcp->tcp_connp);
4081 }
4082 
4083 /*
4084  * Stop all TCP timers, and free the timer mblks if requested.
4085  */
4086 void
4087 tcp_timers_stop(tcp_t *tcp)
4088 {
4089 	if (tcp->tcp_timer_tid != 0) {
4090 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4091 		tcp->tcp_timer_tid = 0;
4092 	}
4093 	if (tcp->tcp_ka_tid != 0) {
4094 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4095 		tcp->tcp_ka_tid = 0;
4096 	}
4097 	if (tcp->tcp_ack_tid != 0) {
4098 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4099 		tcp->tcp_ack_tid = 0;
4100 	}
4101 	if (tcp->tcp_push_tid != 0) {
4102 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4103 		tcp->tcp_push_tid = 0;
4104 	}
4105 }
4106 
4107 /*
4108  * The tcp_t is going away. Remove it from all lists and set it
4109  * to TCPS_CLOSED. The freeing up of memory is deferred until
4110  * tcp_inactive. This is needed since a thread in tcp_rput might have
4111  * done a CONN_INC_REF on this structure before it was removed from the
4112  * hashes.
4113  */
4114 static void
4115 tcp_closei_local(tcp_t *tcp)
4116 {
4117 	ire_t 	*ire;
4118 	conn_t	*connp = tcp->tcp_connp;
4119 
4120 	if (!TCP_IS_SOCKET(tcp))
4121 		tcp_acceptor_hash_remove(tcp);
4122 
4123 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4124 	tcp->tcp_ibsegs = 0;
4125 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4126 	tcp->tcp_obsegs = 0;
4127 
4128 	/*
4129 	 * If we are an eager connection hanging off a listener that
4130 	 * hasn't formally accepted the connection yet, get off his
4131 	 * list and blow off any data that we have accumulated.
4132 	 */
4133 	if (tcp->tcp_listener != NULL) {
4134 		tcp_t	*listener = tcp->tcp_listener;
4135 		mutex_enter(&listener->tcp_eager_lock);
4136 		/*
4137 		 * tcp_eager_conn_ind == NULL means that the
4138 		 * conn_ind has already gone to listener. At
4139 		 * this point, eager will be closed but we
4140 		 * leave it in listeners eager list so that
4141 		 * if listener decides to close without doing
4142 		 * accept, we can clean this up. In tcp_wput_accept
4143 		 * we take case of the case of accept on closed
4144 		 * eager.
4145 		 */
4146 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4147 			tcp_eager_unlink(tcp);
4148 			mutex_exit(&listener->tcp_eager_lock);
4149 			/*
4150 			 * We don't want to have any pointers to the
4151 			 * listener queue, after we have released our
4152 			 * reference on the listener
4153 			 */
4154 			tcp->tcp_rq = tcp_g_q;
4155 			tcp->tcp_wq = WR(tcp_g_q);
4156 			CONN_DEC_REF(listener->tcp_connp);
4157 		} else {
4158 			mutex_exit(&listener->tcp_eager_lock);
4159 		}
4160 	}
4161 
4162 	/* Stop all the timers */
4163 	tcp_timers_stop(tcp);
4164 
4165 	if (tcp->tcp_state == TCPS_LISTEN) {
4166 		if (tcp->tcp_ip_addr_cache) {
4167 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4168 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4169 			tcp->tcp_ip_addr_cache = NULL;
4170 		}
4171 	}
4172 	if (tcp->tcp_flow_stopped)
4173 		tcp_clrqfull(tcp);
4174 
4175 	tcp_bind_hash_remove(tcp);
4176 	/*
4177 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4178 	 * is trying to remove this tcp from the time wait list, we will
4179 	 * block in tcp_time_wait_remove while trying to acquire the
4180 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4181 	 * requires the ipcl_hash_remove to be ordered after the
4182 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4183 	 */
4184 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4185 		tcp_time_wait_remove(tcp, NULL);
4186 	CL_INET_DISCONNECT(tcp);
4187 	ipcl_hash_remove(connp);
4188 
4189 	/*
4190 	 * Delete the cached ire in conn_ire_cache and also mark
4191 	 * the conn as CONDEMNED
4192 	 */
4193 	mutex_enter(&connp->conn_lock);
4194 	connp->conn_state_flags |= CONN_CONDEMNED;
4195 	ire = connp->conn_ire_cache;
4196 	connp->conn_ire_cache = NULL;
4197 	mutex_exit(&connp->conn_lock);
4198 	if (ire != NULL)
4199 		IRE_REFRELE_NOTR(ire);
4200 
4201 	/* Need to cleanup any pending ioctls */
4202 	ASSERT(tcp->tcp_time_wait_next == NULL);
4203 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4204 	ASSERT(tcp->tcp_time_wait_expire == 0);
4205 	tcp->tcp_state = TCPS_CLOSED;
4206 
4207 	/* Release any SSL context */
4208 	if (tcp->tcp_kssl_ent != NULL) {
4209 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4210 		tcp->tcp_kssl_ent = NULL;
4211 	}
4212 	if (tcp->tcp_kssl_ctx != NULL) {
4213 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4214 		tcp->tcp_kssl_ctx = NULL;
4215 	}
4216 	tcp->tcp_kssl_pending = B_FALSE;
4217 }
4218 
4219 /*
4220  * tcp is dying (called from ipcl_conn_destroy and error cases).
4221  * Free the tcp_t in either case.
4222  */
4223 void
4224 tcp_free(tcp_t *tcp)
4225 {
4226 	mblk_t	*mp;
4227 	ip6_pkt_t	*ipp;
4228 
4229 	ASSERT(tcp != NULL);
4230 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4231 
4232 	tcp->tcp_rq = NULL;
4233 	tcp->tcp_wq = NULL;
4234 
4235 	tcp_close_mpp(&tcp->tcp_xmit_head);
4236 	tcp_close_mpp(&tcp->tcp_reass_head);
4237 	if (tcp->tcp_rcv_list != NULL) {
4238 		/* Free b_next chain */
4239 		tcp_close_mpp(&tcp->tcp_rcv_list);
4240 	}
4241 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4242 		freemsg(mp);
4243 	}
4244 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4245 		freemsg(mp);
4246 	}
4247 
4248 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4249 		freeb(tcp->tcp_fused_sigurg_mp);
4250 		tcp->tcp_fused_sigurg_mp = NULL;
4251 	}
4252 
4253 	if (tcp->tcp_sack_info != NULL) {
4254 		if (tcp->tcp_notsack_list != NULL) {
4255 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4256 		}
4257 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4258 	}
4259 
4260 	if (tcp->tcp_hopopts != NULL) {
4261 		mi_free(tcp->tcp_hopopts);
4262 		tcp->tcp_hopopts = NULL;
4263 		tcp->tcp_hopoptslen = 0;
4264 	}
4265 	ASSERT(tcp->tcp_hopoptslen == 0);
4266 	if (tcp->tcp_dstopts != NULL) {
4267 		mi_free(tcp->tcp_dstopts);
4268 		tcp->tcp_dstopts = NULL;
4269 		tcp->tcp_dstoptslen = 0;
4270 	}
4271 	ASSERT(tcp->tcp_dstoptslen == 0);
4272 	if (tcp->tcp_rtdstopts != NULL) {
4273 		mi_free(tcp->tcp_rtdstopts);
4274 		tcp->tcp_rtdstopts = NULL;
4275 		tcp->tcp_rtdstoptslen = 0;
4276 	}
4277 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4278 	if (tcp->tcp_rthdr != NULL) {
4279 		mi_free(tcp->tcp_rthdr);
4280 		tcp->tcp_rthdr = NULL;
4281 		tcp->tcp_rthdrlen = 0;
4282 	}
4283 	ASSERT(tcp->tcp_rthdrlen == 0);
4284 
4285 	ipp = &tcp->tcp_sticky_ipp;
4286 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4287 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
4288 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
4289 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
4290 			ipp->ipp_hopopts = NULL;
4291 			ipp->ipp_hopoptslen = 0;
4292 		}
4293 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4294 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
4295 			ipp->ipp_rtdstopts = NULL;
4296 			ipp->ipp_rtdstoptslen = 0;
4297 		}
4298 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4299 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
4300 			ipp->ipp_dstopts = NULL;
4301 			ipp->ipp_dstoptslen = 0;
4302 		}
4303 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
4304 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
4305 			ipp->ipp_rthdr = NULL;
4306 			ipp->ipp_rthdrlen = 0;
4307 		}
4308 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4309 		    IPPF_DSTOPTS | IPPF_RTHDR);
4310 	}
4311 
4312 	/*
4313 	 * Free memory associated with the tcp/ip header template.
4314 	 */
4315 
4316 	if (tcp->tcp_iphc != NULL)
4317 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4318 
4319 	/*
4320 	 * Following is really a blowing away a union.
4321 	 * It happens to have exactly two members of identical size
4322 	 * the following code is enough.
4323 	 */
4324 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4325 
4326 	if (tcp->tcp_tracebuf != NULL) {
4327 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4328 		tcp->tcp_tracebuf = NULL;
4329 	}
4330 }
4331 
4332 
4333 /*
4334  * Put a connection confirmation message upstream built from the
4335  * address information within 'iph' and 'tcph'.  Report our success or failure.
4336  */
4337 static boolean_t
4338 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4339     mblk_t **defermp)
4340 {
4341 	sin_t	sin;
4342 	sin6_t	sin6;
4343 	mblk_t	*mp;
4344 	char	*optp = NULL;
4345 	int	optlen = 0;
4346 	cred_t	*cr;
4347 
4348 	if (defermp != NULL)
4349 		*defermp = NULL;
4350 
4351 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4352 		/*
4353 		 * Return in T_CONN_CON results of option negotiation through
4354 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4355 		 * negotiation, then what is received from remote end needs
4356 		 * to be taken into account but there is no such thing (yet?)
4357 		 * in our TCP/IP.
4358 		 * Note: We do not use mi_offset_param() here as
4359 		 * tcp_opts_conn_req contents do not directly come from
4360 		 * an application and are either generated in kernel or
4361 		 * from user input that was already verified.
4362 		 */
4363 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4364 		optp = (char *)(mp->b_rptr +
4365 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4366 		optlen = (int)
4367 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4368 	}
4369 
4370 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4371 		ipha_t *ipha = (ipha_t *)iphdr;
4372 
4373 		/* packet is IPv4 */
4374 		if (tcp->tcp_family == AF_INET) {
4375 			sin = sin_null;
4376 			sin.sin_addr.s_addr = ipha->ipha_src;
4377 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4378 			sin.sin_family = AF_INET;
4379 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4380 			    (int)sizeof (sin_t), optp, optlen);
4381 		} else {
4382 			sin6 = sin6_null;
4383 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4384 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4385 			sin6.sin6_family = AF_INET6;
4386 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4387 			    (int)sizeof (sin6_t), optp, optlen);
4388 
4389 		}
4390 	} else {
4391 		ip6_t	*ip6h = (ip6_t *)iphdr;
4392 
4393 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4394 		ASSERT(tcp->tcp_family == AF_INET6);
4395 		sin6 = sin6_null;
4396 		sin6.sin6_addr = ip6h->ip6_src;
4397 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4398 		sin6.sin6_family = AF_INET6;
4399 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4400 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4401 		    (int)sizeof (sin6_t), optp, optlen);
4402 	}
4403 
4404 	if (!mp)
4405 		return (B_FALSE);
4406 
4407 	if ((cr = DB_CRED(idmp)) != NULL) {
4408 		mblk_setcred(mp, cr);
4409 		DB_CPID(mp) = DB_CPID(idmp);
4410 	}
4411 
4412 	if (defermp == NULL)
4413 		putnext(tcp->tcp_rq, mp);
4414 	else
4415 		*defermp = mp;
4416 
4417 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4418 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4419 	return (B_TRUE);
4420 }
4421 
4422 /*
4423  * Defense for the SYN attack -
4424  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4425  *    one that doesn't have the dontdrop bit set.
4426  * 2. Don't drop a SYN request before its first timeout. This gives every
4427  *    request at least til the first timeout to complete its 3-way handshake.
4428  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4429  *    requests currently on the queue that has timed out. This will be used
4430  *    as an indicator of whether an attack is under way, so that appropriate
4431  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4432  *    either when eager goes into ESTABLISHED, or gets freed up.)
4433  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4434  *    # of timeout drops back to <= q0len/32 => SYN alert off
4435  */
4436 static boolean_t
4437 tcp_drop_q0(tcp_t *tcp)
4438 {
4439 	tcp_t	*eager;
4440 
4441 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4442 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4443 	/*
4444 	 * New one is added after next_q0 so prev_q0 points to the oldest
4445 	 * Also do not drop any established connections that are deferred on
4446 	 * q0 due to q being full
4447 	 */
4448 
4449 	eager = tcp->tcp_eager_prev_q0;
4450 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4451 		eager = eager->tcp_eager_prev_q0;
4452 		if (eager == tcp) {
4453 			eager = tcp->tcp_eager_prev_q0;
4454 			break;
4455 		}
4456 	}
4457 	if (eager->tcp_syn_rcvd_timeout == 0)
4458 		return (B_FALSE);
4459 
4460 	if (tcp->tcp_debug) {
4461 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4462 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4463 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4464 		    tcp->tcp_conn_req_cnt_q0,
4465 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4466 	}
4467 
4468 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4469 
4470 	/*
4471 	 * need to do refhold here because the selected eager could
4472 	 * be removed by someone else if we release the eager lock.
4473 	 */
4474 	CONN_INC_REF(eager->tcp_connp);
4475 	mutex_exit(&tcp->tcp_eager_lock);
4476 
4477 	/* Mark the IRE created for this SYN request temporary */
4478 	tcp_ip_ire_mark_advice(eager);
4479 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4480 	CONN_DEC_REF(eager->tcp_connp);
4481 
4482 	mutex_enter(&tcp->tcp_eager_lock);
4483 	return (B_TRUE);
4484 }
4485 
4486 int
4487 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4488     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4489 {
4490 	tcp_t 		*ltcp = lconnp->conn_tcp;
4491 	tcp_t		*tcp = connp->conn_tcp;
4492 	mblk_t		*tpi_mp;
4493 	ipha_t		*ipha;
4494 	ip6_t		*ip6h;
4495 	sin6_t 		sin6;
4496 	in6_addr_t 	v6dst;
4497 	int		err;
4498 	int		ifindex = 0;
4499 	cred_t		*cr;
4500 
4501 	if (ipvers == IPV4_VERSION) {
4502 		ipha = (ipha_t *)mp->b_rptr;
4503 
4504 		connp->conn_send = ip_output;
4505 		connp->conn_recv = tcp_input;
4506 
4507 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4508 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4509 
4510 		sin6 = sin6_null;
4511 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4512 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4513 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4514 		sin6.sin6_family = AF_INET6;
4515 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4516 		    lconnp->conn_zoneid);
4517 		if (tcp->tcp_recvdstaddr) {
4518 			sin6_t	sin6d;
4519 
4520 			sin6d = sin6_null;
4521 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4522 			    &sin6d.sin6_addr);
4523 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4524 			sin6d.sin6_family = AF_INET;
4525 			tpi_mp = mi_tpi_extconn_ind(NULL,
4526 			    (char *)&sin6d, sizeof (sin6_t),
4527 			    (char *)&tcp,
4528 			    (t_scalar_t)sizeof (intptr_t),
4529 			    (char *)&sin6d, sizeof (sin6_t),
4530 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4531 		} else {
4532 			tpi_mp = mi_tpi_conn_ind(NULL,
4533 			    (char *)&sin6, sizeof (sin6_t),
4534 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4535 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4536 		}
4537 	} else {
4538 		ip6h = (ip6_t *)mp->b_rptr;
4539 
4540 		connp->conn_send = ip_output_v6;
4541 		connp->conn_recv = tcp_input;
4542 
4543 		connp->conn_srcv6 = ip6h->ip6_dst;
4544 		connp->conn_remv6 = ip6h->ip6_src;
4545 
4546 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4547 		ifindex = (int)DB_CKSUMSTUFF(mp);
4548 		DB_CKSUMSTUFF(mp) = 0;
4549 
4550 		sin6 = sin6_null;
4551 		sin6.sin6_addr = ip6h->ip6_src;
4552 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4553 		sin6.sin6_family = AF_INET6;
4554 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4555 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4556 		    lconnp->conn_zoneid);
4557 
4558 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4559 			/* Pass up the scope_id of remote addr */
4560 			sin6.sin6_scope_id = ifindex;
4561 		} else {
4562 			sin6.sin6_scope_id = 0;
4563 		}
4564 		if (tcp->tcp_recvdstaddr) {
4565 			sin6_t	sin6d;
4566 
4567 			sin6d = sin6_null;
4568 			sin6.sin6_addr = ip6h->ip6_dst;
4569 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4570 			sin6d.sin6_family = AF_INET;
4571 			tpi_mp = mi_tpi_extconn_ind(NULL,
4572 			    (char *)&sin6d, sizeof (sin6_t),
4573 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4574 			    (char *)&sin6d, sizeof (sin6_t),
4575 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4576 		} else {
4577 			tpi_mp = mi_tpi_conn_ind(NULL,
4578 			    (char *)&sin6, sizeof (sin6_t),
4579 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4580 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4581 		}
4582 	}
4583 
4584 	if (tpi_mp == NULL)
4585 		return (ENOMEM);
4586 
4587 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4588 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4589 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4590 	connp->conn_fully_bound = B_FALSE;
4591 
4592 	if (tcp_trace)
4593 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4594 
4595 	/* Inherit information from the "parent" */
4596 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4597 	tcp->tcp_family = ltcp->tcp_family;
4598 	tcp->tcp_wq = ltcp->tcp_wq;
4599 	tcp->tcp_rq = ltcp->tcp_rq;
4600 	tcp->tcp_mss = tcp_mss_def_ipv6;
4601 	tcp->tcp_detached = B_TRUE;
4602 	if ((err = tcp_init_values(tcp)) != 0) {
4603 		freemsg(tpi_mp);
4604 		return (err);
4605 	}
4606 
4607 	if (ipvers == IPV4_VERSION) {
4608 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4609 			freemsg(tpi_mp);
4610 			return (err);
4611 		}
4612 		ASSERT(tcp->tcp_ipha != NULL);
4613 	} else {
4614 		/* ifindex must be already set */
4615 		ASSERT(ifindex != 0);
4616 
4617 		if (ltcp->tcp_bound_if != 0) {
4618 			/*
4619 			 * Set newtcp's bound_if equal to
4620 			 * listener's value. If ifindex is
4621 			 * not the same as ltcp->tcp_bound_if,
4622 			 * it must be a packet for the ipmp group
4623 			 * of interfaces
4624 			 */
4625 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4626 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4627 			tcp->tcp_bound_if = ifindex;
4628 		}
4629 
4630 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4631 		tcp->tcp_recvifindex = 0;
4632 		tcp->tcp_recvhops = 0xffffffffU;
4633 		ASSERT(tcp->tcp_ip6h != NULL);
4634 	}
4635 
4636 	tcp->tcp_lport = ltcp->tcp_lport;
4637 
4638 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4639 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4640 			/*
4641 			 * Listener had options of some sort; eager inherits.
4642 			 * Free up the eager template and allocate one
4643 			 * of the right size.
4644 			 */
4645 			if (tcp->tcp_hdr_grown) {
4646 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4647 			} else {
4648 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4649 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4650 			}
4651 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4652 			    KM_NOSLEEP);
4653 			if (tcp->tcp_iphc == NULL) {
4654 				tcp->tcp_iphc_len = 0;
4655 				freemsg(tpi_mp);
4656 				return (ENOMEM);
4657 			}
4658 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4659 			tcp->tcp_hdr_grown = B_TRUE;
4660 		}
4661 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4662 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4663 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4664 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4665 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4666 
4667 		/*
4668 		 * Copy the IP+TCP header template from listener to eager
4669 		 */
4670 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4671 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4672 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4673 			    IPPROTO_RAW) {
4674 				tcp->tcp_ip6h =
4675 				    (ip6_t *)(tcp->tcp_iphc +
4676 					sizeof (ip6i_t));
4677 			} else {
4678 				tcp->tcp_ip6h =
4679 				    (ip6_t *)(tcp->tcp_iphc);
4680 			}
4681 			tcp->tcp_ipha = NULL;
4682 		} else {
4683 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4684 			tcp->tcp_ip6h = NULL;
4685 		}
4686 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4687 		    tcp->tcp_ip_hdr_len);
4688 	} else {
4689 		/*
4690 		 * only valid case when ipversion of listener and
4691 		 * eager differ is when listener is IPv6 and
4692 		 * eager is IPv4.
4693 		 * Eager header template has been initialized to the
4694 		 * maximum v4 header sizes, which includes space for
4695 		 * TCP and IP options.
4696 		 */
4697 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4698 		    (tcp->tcp_ipversion == IPV4_VERSION));
4699 		ASSERT(tcp->tcp_iphc_len >=
4700 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4701 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4702 		/* copy IP header fields individually */
4703 		tcp->tcp_ipha->ipha_ttl =
4704 		    ltcp->tcp_ip6h->ip6_hops;
4705 		bcopy(ltcp->tcp_tcph->th_lport,
4706 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4707 	}
4708 
4709 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4710 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4711 	    sizeof (in_port_t));
4712 
4713 	if (ltcp->tcp_lport == 0) {
4714 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4715 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4716 		    sizeof (in_port_t));
4717 	}
4718 
4719 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4720 		ASSERT(ipha != NULL);
4721 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4722 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4723 
4724 		/* Source routing option copyover (reverse it) */
4725 		if (tcp_rev_src_routes)
4726 			tcp_opt_reverse(tcp, ipha);
4727 	} else {
4728 		ASSERT(ip6h != NULL);
4729 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4730 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4731 	}
4732 
4733 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4734 	/*
4735 	 * If the SYN contains a credential, it's a loopback packet; attach
4736 	 * the credential to the TPI message.
4737 	 */
4738 	if ((cr = DB_CRED(idmp)) != NULL) {
4739 		mblk_setcred(tpi_mp, cr);
4740 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4741 	}
4742 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4743 
4744 	/* Inherit the listener's SSL protection state */
4745 
4746 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4747 		kssl_hold_ent(tcp->tcp_kssl_ent);
4748 		tcp->tcp_kssl_pending = B_TRUE;
4749 	}
4750 
4751 	return (0);
4752 }
4753 
4754 
4755 int
4756 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4757     tcph_t *tcph, mblk_t *idmp)
4758 {
4759 	tcp_t 		*ltcp = lconnp->conn_tcp;
4760 	tcp_t		*tcp = connp->conn_tcp;
4761 	sin_t		sin;
4762 	mblk_t		*tpi_mp = NULL;
4763 	int		err;
4764 	cred_t		*cr;
4765 
4766 	sin = sin_null;
4767 	sin.sin_addr.s_addr = ipha->ipha_src;
4768 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4769 	sin.sin_family = AF_INET;
4770 	if (ltcp->tcp_recvdstaddr) {
4771 		sin_t	sind;
4772 
4773 		sind = sin_null;
4774 		sind.sin_addr.s_addr = ipha->ipha_dst;
4775 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4776 		sind.sin_family = AF_INET;
4777 		tpi_mp = mi_tpi_extconn_ind(NULL,
4778 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4779 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4780 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4781 	} else {
4782 		tpi_mp = mi_tpi_conn_ind(NULL,
4783 		    (char *)&sin, sizeof (sin_t),
4784 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4785 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4786 	}
4787 
4788 	if (tpi_mp == NULL) {
4789 		return (ENOMEM);
4790 	}
4791 
4792 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4793 	connp->conn_send = ip_output;
4794 	connp->conn_recv = tcp_input;
4795 	connp->conn_fully_bound = B_FALSE;
4796 
4797 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4798 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4799 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4800 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4801 
4802 	if (tcp_trace) {
4803 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4804 	}
4805 
4806 	/* Inherit information from the "parent" */
4807 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4808 	tcp->tcp_family = ltcp->tcp_family;
4809 	tcp->tcp_wq = ltcp->tcp_wq;
4810 	tcp->tcp_rq = ltcp->tcp_rq;
4811 	tcp->tcp_mss = tcp_mss_def_ipv4;
4812 	tcp->tcp_detached = B_TRUE;
4813 	if ((err = tcp_init_values(tcp)) != 0) {
4814 		freemsg(tpi_mp);
4815 		return (err);
4816 	}
4817 
4818 	/*
4819 	 * Let's make sure that eager tcp template has enough space to
4820 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4821 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4822 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4823 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4824 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4825 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4826 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4827 	 */
4828 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4829 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4830 
4831 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4832 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4833 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4834 	tcp->tcp_ttl = ltcp->tcp_ttl;
4835 	tcp->tcp_tos = ltcp->tcp_tos;
4836 
4837 	/* Copy the IP+TCP header template from listener to eager */
4838 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4839 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4840 	tcp->tcp_ip6h = NULL;
4841 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4842 	    tcp->tcp_ip_hdr_len);
4843 
4844 	/* Initialize the IP addresses and Ports */
4845 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4846 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4847 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4848 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4849 
4850 	/* Source routing option copyover (reverse it) */
4851 	if (tcp_rev_src_routes)
4852 		tcp_opt_reverse(tcp, ipha);
4853 
4854 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4855 
4856 	/*
4857 	 * If the SYN contains a credential, it's a loopback packet; attach
4858 	 * the credential to the TPI message.
4859 	 */
4860 	if ((cr = DB_CRED(idmp)) != NULL) {
4861 		mblk_setcred(tpi_mp, cr);
4862 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4863 	}
4864 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4865 
4866 	/* Inherit the listener's SSL protection state */
4867 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4868 		kssl_hold_ent(tcp->tcp_kssl_ent);
4869 		tcp->tcp_kssl_pending = B_TRUE;
4870 	}
4871 
4872 	return (0);
4873 }
4874 
4875 /*
4876  * sets up conn for ipsec.
4877  * if the first mblk is M_CTL it is consumed and mpp is updated.
4878  * in case of error mpp is freed.
4879  */
4880 conn_t *
4881 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4882 {
4883 	conn_t 		*connp = tcp->tcp_connp;
4884 	conn_t 		*econnp;
4885 	squeue_t 	*new_sqp;
4886 	mblk_t 		*first_mp = *mpp;
4887 	mblk_t		*mp = *mpp;
4888 	boolean_t	mctl_present = B_FALSE;
4889 	uint_t		ipvers;
4890 
4891 	econnp = tcp_get_conn(sqp);
4892 	if (econnp == NULL) {
4893 		freemsg(first_mp);
4894 		return (NULL);
4895 	}
4896 	if (DB_TYPE(mp) == M_CTL) {
4897 		if (mp->b_cont == NULL ||
4898 		    mp->b_cont->b_datap->db_type != M_DATA) {
4899 			freemsg(first_mp);
4900 			return (NULL);
4901 		}
4902 		mp = mp->b_cont;
4903 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4904 			freemsg(first_mp);
4905 			return (NULL);
4906 		}
4907 
4908 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4909 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4910 		mctl_present = B_TRUE;
4911 	} else {
4912 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4913 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4914 	}
4915 
4916 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4917 	DB_CKSUMSTART(mp) = 0;
4918 
4919 	ASSERT(OK_32PTR(mp->b_rptr));
4920 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4921 	if (ipvers == IPV4_VERSION) {
4922 		uint16_t  	*up;
4923 		uint32_t	ports;
4924 		ipha_t		*ipha;
4925 
4926 		ipha = (ipha_t *)mp->b_rptr;
4927 		up = (uint16_t *)((uchar_t *)ipha +
4928 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4929 		ports = *(uint32_t *)up;
4930 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4931 		    ipha->ipha_dst, ipha->ipha_src, ports);
4932 	} else {
4933 		uint16_t  	*up;
4934 		uint32_t	ports;
4935 		uint16_t	ip_hdr_len;
4936 		uint8_t		*nexthdrp;
4937 		ip6_t 		*ip6h;
4938 		tcph_t		*tcph;
4939 
4940 		ip6h = (ip6_t *)mp->b_rptr;
4941 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4942 			ip_hdr_len = IPV6_HDR_LEN;
4943 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4944 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4945 			CONN_DEC_REF(econnp);
4946 			freemsg(first_mp);
4947 			return (NULL);
4948 		}
4949 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4950 		up = (uint16_t *)tcph->th_lport;
4951 		ports = *(uint32_t *)up;
4952 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4953 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4954 	}
4955 
4956 	/*
4957 	 * The caller already ensured that there is a sqp present.
4958 	 */
4959 	econnp->conn_sqp = new_sqp;
4960 
4961 	if (connp->conn_policy != NULL) {
4962 		ipsec_in_t *ii;
4963 		ii = (ipsec_in_t *)(first_mp->b_rptr);
4964 		ASSERT(ii->ipsec_in_policy == NULL);
4965 		IPPH_REFHOLD(connp->conn_policy);
4966 		ii->ipsec_in_policy = connp->conn_policy;
4967 
4968 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
4969 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
4970 			CONN_DEC_REF(econnp);
4971 			freemsg(first_mp);
4972 			return (NULL);
4973 		}
4974 	}
4975 
4976 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
4977 		CONN_DEC_REF(econnp);
4978 		freemsg(first_mp);
4979 		return (NULL);
4980 	}
4981 
4982 	/*
4983 	 * If we know we have some policy, pass the "IPSEC"
4984 	 * options size TCP uses this adjust the MSS.
4985 	 */
4986 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
4987 	if (mctl_present) {
4988 		freeb(first_mp);
4989 		*mpp = mp;
4990 	}
4991 
4992 	return (econnp);
4993 }
4994 
4995 /*
4996  * tcp_get_conn/tcp_free_conn
4997  *
4998  * tcp_get_conn is used to get a clean tcp connection structure.
4999  * It tries to reuse the connections put on the freelist by the
5000  * time_wait_collector failing which it goes to kmem_cache. This
5001  * way has two benefits compared to just allocating from and
5002  * freeing to kmem_cache.
5003  * 1) The time_wait_collector can free (which includes the cleanup)
5004  * outside the squeue. So when the interrupt comes, we have a clean
5005  * connection sitting in the freelist. Obviously, this buys us
5006  * performance.
5007  *
5008  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5009  * has multiple disadvantages - tying up the squeue during alloc, and the
5010  * fact that IPSec policy initialization has to happen here which
5011  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5012  * But allocating the conn/tcp in IP land is also not the best since
5013  * we can't check the 'q' and 'q0' which are protected by squeue and
5014  * blindly allocate memory which might have to be freed here if we are
5015  * not allowed to accept the connection. By using the freelist and
5016  * putting the conn/tcp back in freelist, we don't pay a penalty for
5017  * allocating memory without checking 'q/q0' and freeing it if we can't
5018  * accept the connection.
5019  *
5020  * Care should be taken to put the conn back in the same squeue's freelist
5021  * from which it was allocated. Best results are obtained if conn is
5022  * allocated from listener's squeue and freed to the same. Time wait
5023  * collector will free up the freelist is the connection ends up sitting
5024  * there for too long.
5025  */
5026 void *
5027 tcp_get_conn(void *arg)
5028 {
5029 	tcp_t			*tcp = NULL;
5030 	conn_t			*connp = NULL;
5031 	squeue_t		*sqp = (squeue_t *)arg;
5032 	tcp_squeue_priv_t 	*tcp_time_wait;
5033 
5034 	tcp_time_wait =
5035 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5036 
5037 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5038 	tcp = tcp_time_wait->tcp_free_list;
5039 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5040 	if (tcp != NULL) {
5041 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5042 		tcp_time_wait->tcp_free_list_cnt--;
5043 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5044 		tcp->tcp_time_wait_next = NULL;
5045 		connp = tcp->tcp_connp;
5046 		connp->conn_flags |= IPCL_REUSED;
5047 		return ((void *)connp);
5048 	}
5049 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5050 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5051 		return (NULL);
5052 	return ((void *)connp);
5053 }
5054 
5055 /* BEGIN CSTYLED */
5056 /*
5057  *
5058  * The sockfs ACCEPT path:
5059  * =======================
5060  *
5061  * The eager is now established in its own perimeter as soon as SYN is
5062  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5063  * completes the accept processing on the acceptor STREAM. The sending
5064  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5065  * listener but a TLI/XTI listener completes the accept processing
5066  * on the listener perimeter.
5067  *
5068  * Common control flow for 3 way handshake:
5069  * ----------------------------------------
5070  *
5071  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5072  *					-> tcp_conn_request()
5073  *
5074  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5075  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5076  *
5077  * Sockfs ACCEPT Path:
5078  * -------------------
5079  *
5080  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5081  * as STREAM entry point)
5082  *
5083  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5084  *
5085  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5086  * association (we are not behind eager's squeue but sockfs is protecting us
5087  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5088  * is changed to point at tcp_wput().
5089  *
5090  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5091  * listener (done on listener's perimeter).
5092  *
5093  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5094  * accept.
5095  *
5096  * TLI/XTI client ACCEPT path:
5097  * ---------------------------
5098  *
5099  * soaccept() sends T_CONN_RES on the listener STREAM.
5100  *
5101  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5102  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5103  *
5104  * Locks:
5105  * ======
5106  *
5107  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5108  * and listeners->tcp_eager_next_q.
5109  *
5110  * Referencing:
5111  * ============
5112  *
5113  * 1) We start out in tcp_conn_request by eager placing a ref on
5114  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5115  *
5116  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5117  * doing so we place a ref on the eager. This ref is finally dropped at the
5118  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5119  * reference is dropped by the squeue framework.
5120  *
5121  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5122  *
5123  * The reference must be released by the same entity that added the reference
5124  * In the above scheme, the eager is the entity that adds and releases the
5125  * references. Note that tcp_accept_finish executes in the squeue of the eager
5126  * (albeit after it is attached to the acceptor stream). Though 1. executes
5127  * in the listener's squeue, the eager is nascent at this point and the
5128  * reference can be considered to have been added on behalf of the eager.
5129  *
5130  * Eager getting a Reset or listener closing:
5131  * ==========================================
5132  *
5133  * Once the listener and eager are linked, the listener never does the unlink.
5134  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5135  * a message on all eager perimeter. The eager then does the unlink, clears
5136  * any pointers to the listener's queue and drops the reference to the
5137  * listener. The listener waits in tcp_close outside the squeue until its
5138  * refcount has dropped to 1. This ensures that the listener has waited for
5139  * all eagers to clear their association with the listener.
5140  *
5141  * Similarly, if eager decides to go away, it can unlink itself and close.
5142  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5143  * the reference to eager is still valid because of the extra ref we put
5144  * in tcp_send_conn_ind.
5145  *
5146  * Listener can always locate the eager under the protection
5147  * of the listener->tcp_eager_lock, and then do a refhold
5148  * on the eager during the accept processing.
5149  *
5150  * The acceptor stream accesses the eager in the accept processing
5151  * based on the ref placed on eager before sending T_conn_ind.
5152  * The only entity that can negate this refhold is a listener close
5153  * which is mutually exclusive with an active acceptor stream.
5154  *
5155  * Eager's reference on the listener
5156  * ===================================
5157  *
5158  * If the accept happens (even on a closed eager) the eager drops its
5159  * reference on the listener at the start of tcp_accept_finish. If the
5160  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5161  * the reference is dropped in tcp_closei_local. If the listener closes,
5162  * the reference is dropped in tcp_eager_kill. In all cases the reference
5163  * is dropped while executing in the eager's context (squeue).
5164  */
5165 /* END CSTYLED */
5166 
5167 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5168 
5169 /*
5170  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5171  * tcp_rput_data will not see any SYN packets.
5172  */
5173 /* ARGSUSED */
5174 void
5175 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5176 {
5177 	tcph_t		*tcph;
5178 	uint32_t	seg_seq;
5179 	tcp_t		*eager;
5180 	uint_t		ipvers;
5181 	ipha_t		*ipha;
5182 	ip6_t		*ip6h;
5183 	int		err;
5184 	conn_t		*econnp = NULL;
5185 	squeue_t	*new_sqp;
5186 	mblk_t		*mp1;
5187 	uint_t 		ip_hdr_len;
5188 	conn_t		*connp = (conn_t *)arg;
5189 	tcp_t		*tcp = connp->conn_tcp;
5190 	ire_t		*ire;
5191 
5192 	if (tcp->tcp_state != TCPS_LISTEN)
5193 		goto error2;
5194 
5195 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5196 
5197 	mutex_enter(&tcp->tcp_eager_lock);
5198 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5199 		mutex_exit(&tcp->tcp_eager_lock);
5200 		TCP_STAT(tcp_listendrop);
5201 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5202 		if (tcp->tcp_debug) {
5203 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5204 			    "tcp_conn_request: listen backlog (max=%d) "
5205 			    "overflow (%d pending) on %s",
5206 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5207 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5208 		}
5209 		goto error2;
5210 	}
5211 
5212 	if (tcp->tcp_conn_req_cnt_q0 >=
5213 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5214 		/*
5215 		 * Q0 is full. Drop a pending half-open req from the queue
5216 		 * to make room for the new SYN req. Also mark the time we
5217 		 * drop a SYN.
5218 		 *
5219 		 * A more aggressive defense against SYN attack will
5220 		 * be to set the "tcp_syn_defense" flag now.
5221 		 */
5222 		TCP_STAT(tcp_listendropq0);
5223 		tcp->tcp_last_rcv_lbolt = lbolt64;
5224 		if (!tcp_drop_q0(tcp)) {
5225 			mutex_exit(&tcp->tcp_eager_lock);
5226 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5227 			if (tcp->tcp_debug) {
5228 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5229 				    "tcp_conn_request: listen half-open queue "
5230 				    "(max=%d) full (%d pending) on %s",
5231 				    tcp_conn_req_max_q0,
5232 				    tcp->tcp_conn_req_cnt_q0,
5233 				    tcp_display(tcp, NULL,
5234 				    DISP_PORT_ONLY));
5235 			}
5236 			goto error2;
5237 		}
5238 	}
5239 	mutex_exit(&tcp->tcp_eager_lock);
5240 
5241 	/*
5242 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5243 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5244 	 * link local address.  If IPSec is enabled, db_struioflag has
5245 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5246 	 * otherwise an error case if neither of them is set.
5247 	 */
5248 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5249 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5250 		DB_CKSUMSTART(mp) = 0;
5251 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5252 		econnp = (conn_t *)tcp_get_conn(arg2);
5253 		if (econnp == NULL)
5254 			goto error2;
5255 		econnp->conn_sqp = new_sqp;
5256 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5257 		/*
5258 		 * mp is updated in tcp_get_ipsec_conn().
5259 		 */
5260 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5261 		if (econnp == NULL) {
5262 			/*
5263 			 * mp freed by tcp_get_ipsec_conn.
5264 			 */
5265 			return;
5266 		}
5267 	} else {
5268 		goto error2;
5269 	}
5270 
5271 	ASSERT(DB_TYPE(mp) == M_DATA);
5272 
5273 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5274 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5275 	ASSERT(OK_32PTR(mp->b_rptr));
5276 	if (ipvers == IPV4_VERSION) {
5277 		ipha = (ipha_t *)mp->b_rptr;
5278 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5279 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5280 	} else {
5281 		ip6h = (ip6_t *)mp->b_rptr;
5282 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5283 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5284 	}
5285 
5286 	if (tcp->tcp_family == AF_INET) {
5287 		ASSERT(ipvers == IPV4_VERSION);
5288 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5289 	} else {
5290 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5291 	}
5292 
5293 	if (err)
5294 		goto error3;
5295 
5296 	eager = econnp->conn_tcp;
5297 
5298 	/* Inherit various TCP parameters from the listener */
5299 	eager->tcp_naglim = tcp->tcp_naglim;
5300 	eager->tcp_first_timer_threshold =
5301 	    tcp->tcp_first_timer_threshold;
5302 	eager->tcp_second_timer_threshold =
5303 	    tcp->tcp_second_timer_threshold;
5304 
5305 	eager->tcp_first_ctimer_threshold =
5306 	    tcp->tcp_first_ctimer_threshold;
5307 	eager->tcp_second_ctimer_threshold =
5308 	    tcp->tcp_second_ctimer_threshold;
5309 
5310 	/*
5311 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5312 	 * zone id before the accept is completed in tcp_wput_accept().
5313 	 */
5314 	econnp->conn_zoneid = connp->conn_zoneid;
5315 
5316 	eager->tcp_hard_binding = B_TRUE;
5317 
5318 	tcp_bind_hash_insert(&tcp_bind_fanout[
5319 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5320 
5321 	CL_INET_CONNECT(eager);
5322 
5323 	/*
5324 	 * No need to check for multicast destination since ip will only pass
5325 	 * up multicasts to those that have expressed interest
5326 	 * TODO: what about rejecting broadcasts?
5327 	 * Also check that source is not a multicast or broadcast address.
5328 	 */
5329 	eager->tcp_state = TCPS_SYN_RCVD;
5330 
5331 
5332 	/*
5333 	 * There should be no ire in the mp as we are being called after
5334 	 * receiving the SYN.
5335 	 */
5336 	ASSERT(tcp_ire_mp(mp) == NULL);
5337 
5338 	/*
5339 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5340 	 */
5341 
5342 	if (tcp_adapt_ire(eager, NULL) == 0) {
5343 		/* Undo the bind_hash_insert */
5344 		tcp_bind_hash_remove(eager);
5345 		goto error3;
5346 	}
5347 
5348 	/* Process all TCP options. */
5349 	tcp_process_options(eager, tcph);
5350 
5351 	/* Is the other end ECN capable? */
5352 	if (tcp_ecn_permitted >= 1 &&
5353 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5354 		eager->tcp_ecn_ok = B_TRUE;
5355 	}
5356 
5357 	/*
5358 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5359 	 * window size changed via SO_RCVBUF option.  First round up the
5360 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5361 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5362 	 * setting.
5363 	 *
5364 	 * Note if there is a rpipe metric associated with the remote host,
5365 	 * we should not inherit receive window size from listener.
5366 	 */
5367 	eager->tcp_rwnd = MSS_ROUNDUP(
5368 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5369 	    eager->tcp_rwnd), eager->tcp_mss);
5370 	if (eager->tcp_snd_ws_ok)
5371 		tcp_set_ws_value(eager);
5372 	/*
5373 	 * Note that this is the only place tcp_rwnd_set() is called for
5374 	 * accepting a connection.  We need to call it here instead of
5375 	 * after the 3-way handshake because we need to tell the other
5376 	 * side our rwnd in the SYN-ACK segment.
5377 	 */
5378 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5379 
5380 	/*
5381 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5382 	 * via soaccept()->soinheritoptions() which essentially applies
5383 	 * all the listener options to the new STREAM. The options that we
5384 	 * need to take care of are:
5385 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5386 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5387 	 * SO_SNDBUF, SO_RCVBUF.
5388 	 *
5389 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5390 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5391 	 *		tcp_maxpsz_set() gets called later from
5392 	 *		tcp_accept_finish(), the option takes effect.
5393 	 *
5394 	 */
5395 	/* Set the TCP options */
5396 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5397 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5398 	eager->tcp_oobinline = tcp->tcp_oobinline;
5399 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5400 	eager->tcp_broadcast = tcp->tcp_broadcast;
5401 	eager->tcp_useloopback = tcp->tcp_useloopback;
5402 	eager->tcp_dontroute = tcp->tcp_dontroute;
5403 	eager->tcp_linger = tcp->tcp_linger;
5404 	eager->tcp_lingertime = tcp->tcp_lingertime;
5405 	if (tcp->tcp_ka_enabled)
5406 		eager->tcp_ka_enabled = 1;
5407 
5408 	/* Set the IP options */
5409 	econnp->conn_broadcast = connp->conn_broadcast;
5410 	econnp->conn_loopback = connp->conn_loopback;
5411 	econnp->conn_dontroute = connp->conn_dontroute;
5412 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5413 
5414 	/* Put a ref on the listener for the eager. */
5415 	CONN_INC_REF(connp);
5416 	mutex_enter(&tcp->tcp_eager_lock);
5417 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5418 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5419 	tcp->tcp_eager_next_q0 = eager;
5420 	eager->tcp_eager_prev_q0 = tcp;
5421 
5422 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5423 	eager->tcp_listener = tcp;
5424 	eager->tcp_saved_listener = tcp;
5425 
5426 	/*
5427 	 * Tag this detached tcp vector for later retrieval
5428 	 * by our listener client in tcp_accept().
5429 	 */
5430 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5431 	tcp->tcp_conn_req_cnt_q0++;
5432 	if (++tcp->tcp_conn_req_seqnum == -1) {
5433 		/*
5434 		 * -1 is "special" and defined in TPI as something
5435 		 * that should never be used in T_CONN_IND
5436 		 */
5437 		++tcp->tcp_conn_req_seqnum;
5438 	}
5439 	mutex_exit(&tcp->tcp_eager_lock);
5440 
5441 	if (tcp->tcp_syn_defense) {
5442 		/* Don't drop the SYN that comes from a good IP source */
5443 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5444 		if (addr_cache != NULL && eager->tcp_remote ==
5445 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5446 			eager->tcp_dontdrop = B_TRUE;
5447 		}
5448 	}
5449 
5450 	/*
5451 	 * We need to insert the eager in its own perimeter but as soon
5452 	 * as we do that, we expose the eager to the classifier and
5453 	 * should not touch any field outside the eager's perimeter.
5454 	 * So do all the work necessary before inserting the eager
5455 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5456 	 * will succeed but undo everything if it fails.
5457 	 */
5458 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5459 	eager->tcp_irs = seg_seq;
5460 	eager->tcp_rack = seg_seq;
5461 	eager->tcp_rnxt = seg_seq + 1;
5462 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5463 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5464 	eager->tcp_state = TCPS_SYN_RCVD;
5465 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5466 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5467 	if (mp1 == NULL)
5468 		goto error1;
5469 	mblk_setcred(mp1, tcp->tcp_cred);
5470 	DB_CPID(mp1) = tcp->tcp_cpid;
5471 
5472 	/*
5473 	 * We need to start the rto timer. In normal case, we start
5474 	 * the timer after sending the packet on the wire (or at
5475 	 * least believing that packet was sent by waiting for
5476 	 * CALL_IP_WPUT() to return). Since this is the first packet
5477 	 * being sent on the wire for the eager, our initial tcp_rto
5478 	 * is at least tcp_rexmit_interval_min which is a fairly
5479 	 * large value to allow the algorithm to adjust slowly to large
5480 	 * fluctuations of RTT during first few transmissions.
5481 	 *
5482 	 * Starting the timer first and then sending the packet in this
5483 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5484 	 * is of the order of several 100ms and starting the timer
5485 	 * first and then sending the packet will result in difference
5486 	 * of few micro seconds.
5487 	 *
5488 	 * Without this optimization, we are forced to hold the fanout
5489 	 * lock across the ipcl_bind_insert() and sending the packet
5490 	 * so that we don't race against an incoming packet (maybe RST)
5491 	 * for this eager.
5492 	 */
5493 
5494 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5495 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5496 
5497 
5498 	/*
5499 	 * Insert the eager in its own perimeter now. We are ready to deal
5500 	 * with any packets on eager.
5501 	 */
5502 	if (eager->tcp_ipversion == IPV4_VERSION) {
5503 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5504 			goto error;
5505 		}
5506 	} else {
5507 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5508 			goto error;
5509 		}
5510 	}
5511 
5512 	/* mark conn as fully-bound */
5513 	econnp->conn_fully_bound = B_TRUE;
5514 
5515 	/* Send the SYN-ACK */
5516 	tcp_send_data(eager, eager->tcp_wq, mp1);
5517 	freemsg(mp);
5518 
5519 	return;
5520 error:
5521 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5522 	freemsg(mp1);
5523 error1:
5524 	/* Undo what we did above */
5525 	mutex_enter(&tcp->tcp_eager_lock);
5526 	tcp_eager_unlink(eager);
5527 	mutex_exit(&tcp->tcp_eager_lock);
5528 	/* Drop eager's reference on the listener */
5529 	CONN_DEC_REF(connp);
5530 
5531 	/*
5532 	 * Delete the cached ire in conn_ire_cache and also mark
5533 	 * the conn as CONDEMNED
5534 	 */
5535 	mutex_enter(&econnp->conn_lock);
5536 	econnp->conn_state_flags |= CONN_CONDEMNED;
5537 	ire = econnp->conn_ire_cache;
5538 	econnp->conn_ire_cache = NULL;
5539 	mutex_exit(&econnp->conn_lock);
5540 	if (ire != NULL)
5541 		IRE_REFRELE_NOTR(ire);
5542 
5543 	/*
5544 	 * tcp_accept_comm inserts the eager to the bind_hash
5545 	 * we need to remove it from the hash if ipcl_conn_insert
5546 	 * fails.
5547 	 */
5548 	tcp_bind_hash_remove(eager);
5549 	/* Drop the eager ref placed in tcp_open_detached */
5550 	CONN_DEC_REF(econnp);
5551 
5552 	/*
5553 	 * If a connection already exists, send the mp to that connections so
5554 	 * that it can be appropriately dealt with.
5555 	 */
5556 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5557 		if (!IPCL_IS_CONNECTED(econnp)) {
5558 			/*
5559 			 * Something bad happened. ipcl_conn_insert()
5560 			 * failed because a connection already existed
5561 			 * in connected hash but we can't find it
5562 			 * anymore (someone blew it away). Just
5563 			 * free this message and hopefully remote
5564 			 * will retransmit at which time the SYN can be
5565 			 * treated as a new connection or dealth with
5566 			 * a TH_RST if a connection already exists.
5567 			 */
5568 			freemsg(mp);
5569 		} else {
5570 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5571 			    econnp, SQTAG_TCP_CONN_REQ);
5572 		}
5573 	} else {
5574 		/* Nobody wants this packet */
5575 		freemsg(mp);
5576 	}
5577 	return;
5578 error2:
5579 	freemsg(mp);
5580 	return;
5581 error3:
5582 	CONN_DEC_REF(econnp);
5583 	freemsg(mp);
5584 }
5585 
5586 /*
5587  * In an ideal case of vertical partition in NUMA architecture, its
5588  * beneficial to have the listener and all the incoming connections
5589  * tied to the same squeue. The other constraint is that incoming
5590  * connections should be tied to the squeue attached to interrupted
5591  * CPU for obvious locality reason so this leaves the listener to
5592  * be tied to the same squeue. Our only problem is that when listener
5593  * is binding, the CPU that will get interrupted by the NIC whose
5594  * IP address the listener is binding to is not even known. So
5595  * the code below allows us to change that binding at the time the
5596  * CPU is interrupted by virtue of incoming connection's squeue.
5597  *
5598  * This is usefull only in case of a listener bound to a specific IP
5599  * address. For other kind of listeners, they get bound the
5600  * very first time and there is no attempt to rebind them.
5601  */
5602 void
5603 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5604 {
5605 	conn_t		*connp = (conn_t *)arg;
5606 	squeue_t	*sqp = (squeue_t *)arg2;
5607 	squeue_t	*new_sqp;
5608 	uint32_t	conn_flags;
5609 
5610 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5611 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5612 	} else {
5613 		goto done;
5614 	}
5615 
5616 	if (connp->conn_fanout == NULL)
5617 		goto done;
5618 
5619 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5620 		mutex_enter(&connp->conn_fanout->connf_lock);
5621 		mutex_enter(&connp->conn_lock);
5622 		/*
5623 		 * No one from read or write side can access us now
5624 		 * except for already queued packets on this squeue.
5625 		 * But since we haven't changed the squeue yet, they
5626 		 * can't execute. If they are processed after we have
5627 		 * changed the squeue, they are sent back to the
5628 		 * correct squeue down below.
5629 		 */
5630 		if (connp->conn_sqp != new_sqp) {
5631 			while (connp->conn_sqp != new_sqp)
5632 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5633 		}
5634 
5635 		do {
5636 			conn_flags = connp->conn_flags;
5637 			conn_flags |= IPCL_FULLY_BOUND;
5638 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5639 			    conn_flags);
5640 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5641 
5642 		mutex_exit(&connp->conn_fanout->connf_lock);
5643 		mutex_exit(&connp->conn_lock);
5644 	}
5645 
5646 done:
5647 	if (connp->conn_sqp != sqp) {
5648 		CONN_INC_REF(connp);
5649 		squeue_fill(connp->conn_sqp, mp,
5650 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5651 	} else {
5652 		tcp_conn_request(connp, mp, sqp);
5653 	}
5654 }
5655 
5656 /*
5657  * Successful connect request processing begins when our client passes
5658  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5659  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5660  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5661  *   upstream <- tcp_rput()                <- IP
5662  * After various error checks are completed, tcp_connect() lays
5663  * the target address and port into the composite header template,
5664  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5665  * request followed by an IRE request, and passes the three mblk message
5666  * down to IP looking like this:
5667  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5668  * Processing continues in tcp_rput() when we receive the following message:
5669  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5670  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5671  * to fire off the connection request, and then passes the T_OK_ACK mblk
5672  * upstream that we filled in below.  There are, of course, numerous
5673  * error conditions along the way which truncate the processing described
5674  * above.
5675  */
5676 static void
5677 tcp_connect(tcp_t *tcp, mblk_t *mp)
5678 {
5679 	sin_t		*sin;
5680 	sin6_t		*sin6;
5681 	queue_t		*q = tcp->tcp_wq;
5682 	struct T_conn_req	*tcr;
5683 	ipaddr_t	*dstaddrp;
5684 	in_port_t	dstport;
5685 	uint_t		srcid;
5686 
5687 	tcr = (struct T_conn_req *)mp->b_rptr;
5688 
5689 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5690 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5691 		tcp_err_ack(tcp, mp, TPROTO, 0);
5692 		return;
5693 	}
5694 
5695 	/*
5696 	 * Determine packet type based on type of address passed in
5697 	 * the request should contain an IPv4 or IPv6 address.
5698 	 * Make sure that address family matches the type of
5699 	 * family of the the address passed down
5700 	 */
5701 	switch (tcr->DEST_length) {
5702 	default:
5703 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5704 		return;
5705 
5706 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5707 		/*
5708 		 * XXX: The check for valid DEST_length was not there
5709 		 * in earlier releases and some buggy
5710 		 * TLI apps (e.g Sybase) got away with not feeding
5711 		 * in sin_zero part of address.
5712 		 * We allow that bug to keep those buggy apps humming.
5713 		 * Test suites require the check on DEST_length.
5714 		 * We construct a new mblk with valid DEST_length
5715 		 * free the original so the rest of the code does
5716 		 * not have to keep track of this special shorter
5717 		 * length address case.
5718 		 */
5719 		mblk_t *nmp;
5720 		struct T_conn_req *ntcr;
5721 		sin_t *nsin;
5722 
5723 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5724 		    tcr->OPT_length, BPRI_HI);
5725 		if (nmp == NULL) {
5726 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5727 			return;
5728 		}
5729 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5730 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5731 		ntcr->PRIM_type = T_CONN_REQ;
5732 		ntcr->DEST_length = sizeof (sin_t);
5733 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5734 
5735 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5736 		*nsin = sin_null;
5737 		/* Get pointer to shorter address to copy from original mp */
5738 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5739 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5740 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5741 			freemsg(nmp);
5742 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5743 			return;
5744 		}
5745 		nsin->sin_family = sin->sin_family;
5746 		nsin->sin_port = sin->sin_port;
5747 		nsin->sin_addr = sin->sin_addr;
5748 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5749 		nmp->b_wptr = (uchar_t *)&nsin[1];
5750 		if (tcr->OPT_length != 0) {
5751 			ntcr->OPT_length = tcr->OPT_length;
5752 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5753 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5754 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5755 			    tcr->OPT_length);
5756 			nmp->b_wptr += tcr->OPT_length;
5757 		}
5758 		freemsg(mp);	/* original mp freed */
5759 		mp = nmp;	/* re-initialize original variables */
5760 		tcr = ntcr;
5761 	}
5762 	/* FALLTHRU */
5763 
5764 	case sizeof (sin_t):
5765 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5766 		    sizeof (sin_t));
5767 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5768 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5769 			return;
5770 		}
5771 		if (tcp->tcp_family != AF_INET ||
5772 		    sin->sin_family != AF_INET) {
5773 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5774 			return;
5775 		}
5776 		if (sin->sin_port == 0) {
5777 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5778 			return;
5779 		}
5780 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
5781 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5782 			return;
5783 		}
5784 
5785 		break;
5786 
5787 	case sizeof (sin6_t):
5788 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
5789 		    sizeof (sin6_t));
5790 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
5791 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5792 			return;
5793 		}
5794 		if (tcp->tcp_family != AF_INET6 ||
5795 		    sin6->sin6_family != AF_INET6) {
5796 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5797 			return;
5798 		}
5799 		if (sin6->sin6_port == 0) {
5800 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5801 			return;
5802 		}
5803 		break;
5804 	}
5805 	/*
5806 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5807 	 * should key on their sequence number and cut them loose.
5808 	 */
5809 
5810 	/*
5811 	 * If options passed in, feed it for verification and handling
5812 	 */
5813 	if (tcr->OPT_length != 0) {
5814 		mblk_t	*ok_mp;
5815 		mblk_t	*discon_mp;
5816 		mblk_t  *conn_opts_mp;
5817 		int t_error, sys_error, do_disconnect;
5818 
5819 		conn_opts_mp = NULL;
5820 
5821 		if (tcp_conprim_opt_process(tcp, mp,
5822 			&do_disconnect, &t_error, &sys_error) < 0) {
5823 			if (do_disconnect) {
5824 				ASSERT(t_error == 0 && sys_error == 0);
5825 				discon_mp = mi_tpi_discon_ind(NULL,
5826 				    ECONNREFUSED, 0);
5827 				if (!discon_mp) {
5828 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5829 					    TSYSERR, ENOMEM);
5830 					return;
5831 				}
5832 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5833 				if (!ok_mp) {
5834 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5835 					    TSYSERR, ENOMEM);
5836 					return;
5837 				}
5838 				qreply(q, ok_mp);
5839 				qreply(q, discon_mp); /* no flush! */
5840 			} else {
5841 				ASSERT(t_error != 0);
5842 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5843 				    sys_error);
5844 			}
5845 			return;
5846 		}
5847 		/*
5848 		 * Success in setting options, the mp option buffer represented
5849 		 * by OPT_length/offset has been potentially modified and
5850 		 * contains results of option processing. We copy it in
5851 		 * another mp to save it for potentially influencing returning
5852 		 * it in T_CONN_CONN.
5853 		 */
5854 		if (tcr->OPT_length != 0) { /* there are resulting options */
5855 			conn_opts_mp = copyb(mp);
5856 			if (!conn_opts_mp) {
5857 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5858 				    TSYSERR, ENOMEM);
5859 				return;
5860 			}
5861 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5862 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5863 			/*
5864 			 * Note:
5865 			 * These resulting option negotiation can include any
5866 			 * end-to-end negotiation options but there no such
5867 			 * thing (yet?) in our TCP/IP.
5868 			 */
5869 		}
5870 	}
5871 
5872 	/*
5873 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
5874 	 * make sure that the template IP header in the tcp structure is an
5875 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
5876 	 * need to this before we call tcp_bindi() so that the port lookup
5877 	 * code will look for ports in the correct port space (IPv4 and
5878 	 * IPv6 have separate port spaces).
5879 	 */
5880 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
5881 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5882 		int err = 0;
5883 
5884 		err = tcp_header_init_ipv4(tcp);
5885 		if (err != 0) {
5886 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
5887 			goto connect_failed;
5888 		}
5889 		if (tcp->tcp_lport != 0)
5890 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
5891 	}
5892 
5893 	switch (tcp->tcp_state) {
5894 	case TCPS_IDLE:
5895 		/*
5896 		 * We support quick connect, refer to comments in
5897 		 * tcp_connect_*()
5898 		 */
5899 		/* FALLTHRU */
5900 	case TCPS_BOUND:
5901 	case TCPS_LISTEN:
5902 		if (tcp->tcp_family == AF_INET6) {
5903 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5904 				tcp_connect_ipv6(tcp, mp,
5905 				    &sin6->sin6_addr,
5906 				    sin6->sin6_port, sin6->sin6_flowinfo,
5907 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
5908 				return;
5909 			}
5910 			/*
5911 			 * Destination adress is mapped IPv6 address.
5912 			 * Source bound address should be unspecified or
5913 			 * IPv6 mapped address as well.
5914 			 */
5915 			if (!IN6_IS_ADDR_UNSPECIFIED(
5916 			    &tcp->tcp_bound_source_v6) &&
5917 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
5918 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
5919 				    EADDRNOTAVAIL);
5920 				break;
5921 			}
5922 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
5923 			dstport = sin6->sin6_port;
5924 			srcid = sin6->__sin6_src_id;
5925 		} else {
5926 			dstaddrp = &sin->sin_addr.s_addr;
5927 			dstport = sin->sin_port;
5928 			srcid = 0;
5929 		}
5930 
5931 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
5932 		return;
5933 	default:
5934 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
5935 		break;
5936 	}
5937 	/*
5938 	 * Note: Code below is the "failure" case
5939 	 */
5940 	/* return error ack and blow away saved option results if any */
5941 connect_failed:
5942 	if (mp != NULL)
5943 		putnext(tcp->tcp_rq, mp);
5944 	else {
5945 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5946 		    TSYSERR, ENOMEM);
5947 	}
5948 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
5949 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
5950 }
5951 
5952 /*
5953  * Handle connect to IPv4 destinations, including connections for AF_INET6
5954  * sockets connecting to IPv4 mapped IPv6 destinations.
5955  */
5956 static void
5957 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
5958     uint_t srcid)
5959 {
5960 	tcph_t	*tcph;
5961 	mblk_t	*mp1;
5962 	ipaddr_t dstaddr = *dstaddrp;
5963 	int32_t	oldstate;
5964 	uint16_t lport;
5965 
5966 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
5967 
5968 	/* Check for attempt to connect to INADDR_ANY */
5969 	if (dstaddr == INADDR_ANY)  {
5970 		/*
5971 		 * SunOS 4.x and 4.3 BSD allow an application
5972 		 * to connect a TCP socket to INADDR_ANY.
5973 		 * When they do this, the kernel picks the
5974 		 * address of one interface and uses it
5975 		 * instead.  The kernel usually ends up
5976 		 * picking the address of the loopback
5977 		 * interface.  This is an undocumented feature.
5978 		 * However, we provide the same thing here
5979 		 * in order to have source and binary
5980 		 * compatibility with SunOS 4.x.
5981 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5982 		 * generate the T_CONN_CON.
5983 		 */
5984 		dstaddr = htonl(INADDR_LOOPBACK);
5985 		*dstaddrp = dstaddr;
5986 	}
5987 
5988 	/* Handle __sin6_src_id if socket not bound to an IP address */
5989 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
5990 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
5991 		    tcp->tcp_connp->conn_zoneid);
5992 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
5993 		    tcp->tcp_ipha->ipha_src);
5994 	}
5995 
5996 	/*
5997 	 * Don't let an endpoint connect to itself.  Note that
5998 	 * the test here does not catch the case where the
5999 	 * source IP addr was left unspecified by the user. In
6000 	 * this case, the source addr is set in tcp_adapt_ire()
6001 	 * using the reply to the T_BIND message that we send
6002 	 * down to IP here and the check is repeated in tcp_rput_other.
6003 	 */
6004 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6005 	    dstport == tcp->tcp_lport) {
6006 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6007 		goto failed;
6008 	}
6009 
6010 	tcp->tcp_ipha->ipha_dst = dstaddr;
6011 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6012 
6013 	/*
6014 	 * Massage a source route if any putting the first hop
6015 	 * in iph_dst. Compute a starting value for the checksum which
6016 	 * takes into account that the original iph_dst should be
6017 	 * included in the checksum but that ip will include the
6018 	 * first hop in the source route in the tcp checksum.
6019 	 */
6020 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6021 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6022 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6023 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6024 	if ((int)tcp->tcp_sum < 0)
6025 		tcp->tcp_sum--;
6026 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6027 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6028 	    (tcp->tcp_sum >> 16));
6029 	tcph = tcp->tcp_tcph;
6030 	*(uint16_t *)tcph->th_fport = dstport;
6031 	tcp->tcp_fport = dstport;
6032 
6033 	oldstate = tcp->tcp_state;
6034 	/*
6035 	 * At this point the remote destination address and remote port fields
6036 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6037 	 * have to see which state tcp was in so we can take apropriate action.
6038 	 */
6039 	if (oldstate == TCPS_IDLE) {
6040 		/*
6041 		 * We support a quick connect capability here, allowing
6042 		 * clients to transition directly from IDLE to SYN_SENT
6043 		 * tcp_bindi will pick an unused port, insert the connection
6044 		 * in the bind hash and transition to BOUND state.
6045 		 */
6046 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6047 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6048 		    B_FALSE, B_FALSE);
6049 		if (lport == 0) {
6050 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6051 			goto failed;
6052 		}
6053 	}
6054 	tcp->tcp_state = TCPS_SYN_SENT;
6055 
6056 	/*
6057 	 * TODO: allow data with connect requests
6058 	 * by unlinking M_DATA trailers here and
6059 	 * linking them in behind the T_OK_ACK mblk.
6060 	 * The tcp_rput() bind ack handler would then
6061 	 * feed them to tcp_wput_data() rather than call
6062 	 * tcp_timer().
6063 	 */
6064 	mp = mi_tpi_ok_ack_alloc(mp);
6065 	if (!mp) {
6066 		tcp->tcp_state = oldstate;
6067 		goto failed;
6068 	}
6069 	if (tcp->tcp_family == AF_INET) {
6070 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6071 		    sizeof (ipa_conn_t));
6072 	} else {
6073 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6074 		    sizeof (ipa6_conn_t));
6075 	}
6076 	if (mp1) {
6077 		/* Hang onto the T_OK_ACK for later. */
6078 		linkb(mp1, mp);
6079 		if (tcp->tcp_family == AF_INET)
6080 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6081 		else {
6082 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6083 			    &tcp->tcp_sticky_ipp);
6084 		}
6085 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6086 		tcp->tcp_active_open = 1;
6087 		/*
6088 		 * If the bind cannot complete immediately
6089 		 * IP will arrange to call tcp_rput_other
6090 		 * when the bind completes.
6091 		 */
6092 		if (mp1 != NULL)
6093 			tcp_rput_other(tcp, mp1);
6094 		return;
6095 	}
6096 	/* Error case */
6097 	tcp->tcp_state = oldstate;
6098 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6099 
6100 failed:
6101 	/* return error ack and blow away saved option results if any */
6102 	if (mp != NULL)
6103 		putnext(tcp->tcp_rq, mp);
6104 	else {
6105 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6106 		    TSYSERR, ENOMEM);
6107 	}
6108 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6109 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6110 
6111 }
6112 
6113 /*
6114  * Handle connect to IPv6 destinations.
6115  */
6116 static void
6117 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6118     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6119 {
6120 	tcph_t	*tcph;
6121 	mblk_t	*mp1;
6122 	ip6_rthdr_t *rth;
6123 	int32_t  oldstate;
6124 	uint16_t lport;
6125 
6126 	ASSERT(tcp->tcp_family == AF_INET6);
6127 
6128 	/*
6129 	 * If we're here, it means that the destination address is a native
6130 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6131 	 * reason why it might not be IPv6 is if the socket was bound to an
6132 	 * IPv4-mapped IPv6 address.
6133 	 */
6134 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6135 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6136 		goto failed;
6137 	}
6138 
6139 	/*
6140 	 * Interpret a zero destination to mean loopback.
6141 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6142 	 * generate the T_CONN_CON.
6143 	 */
6144 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6145 		*dstaddrp = ipv6_loopback;
6146 	}
6147 
6148 	/* Handle __sin6_src_id if socket not bound to an IP address */
6149 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6150 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6151 		    tcp->tcp_connp->conn_zoneid);
6152 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6153 	}
6154 
6155 	/*
6156 	 * Take care of the scope_id now and add ip6i_t
6157 	 * if ip6i_t is not already allocated through TCP
6158 	 * sticky options. At this point tcp_ip6h does not
6159 	 * have dst info, thus use dstaddrp.
6160 	 */
6161 	if (scope_id != 0 &&
6162 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6163 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6164 		ip6i_t  *ip6i;
6165 
6166 		ipp->ipp_ifindex = scope_id;
6167 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6168 
6169 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6170 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6171 			/* Already allocated */
6172 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6173 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6174 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6175 		} else {
6176 			int reterr;
6177 
6178 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6179 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6180 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6181 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6182 			if (reterr != 0)
6183 				goto failed;
6184 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6185 		}
6186 	}
6187 
6188 	/*
6189 	 * Don't let an endpoint connect to itself.  Note that
6190 	 * the test here does not catch the case where the
6191 	 * source IP addr was left unspecified by the user. In
6192 	 * this case, the source addr is set in tcp_adapt_ire()
6193 	 * using the reply to the T_BIND message that we send
6194 	 * down to IP here and the check is repeated in tcp_rput_other.
6195 	 */
6196 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6197 	    (dstport == tcp->tcp_lport)) {
6198 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6199 		goto failed;
6200 	}
6201 
6202 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6203 	tcp->tcp_remote_v6 = *dstaddrp;
6204 	tcp->tcp_ip6h->ip6_vcf =
6205 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6206 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6207 
6208 
6209 	/*
6210 	 * Massage a routing header (if present) putting the first hop
6211 	 * in ip6_dst. Compute a starting value for the checksum which
6212 	 * takes into account that the original ip6_dst should be
6213 	 * included in the checksum but that ip will include the
6214 	 * first hop in the source route in the tcp checksum.
6215 	 */
6216 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6217 	if (rth != NULL) {
6218 
6219 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6220 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6221 		    (tcp->tcp_sum >> 16));
6222 	} else {
6223 		tcp->tcp_sum = 0;
6224 	}
6225 
6226 	tcph = tcp->tcp_tcph;
6227 	*(uint16_t *)tcph->th_fport = dstport;
6228 	tcp->tcp_fport = dstport;
6229 
6230 	oldstate = tcp->tcp_state;
6231 	/*
6232 	 * At this point the remote destination address and remote port fields
6233 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6234 	 * have to see which state tcp was in so we can take apropriate action.
6235 	 */
6236 	if (oldstate == TCPS_IDLE) {
6237 		/*
6238 		 * We support a quick connect capability here, allowing
6239 		 * clients to transition directly from IDLE to SYN_SENT
6240 		 * tcp_bindi will pick an unused port, insert the connection
6241 		 * in the bind hash and transition to BOUND state.
6242 		 */
6243 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6244 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6245 		    B_FALSE, B_FALSE);
6246 		if (lport == 0) {
6247 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6248 			goto failed;
6249 		}
6250 	}
6251 	tcp->tcp_state = TCPS_SYN_SENT;
6252 	/*
6253 	 * TODO: allow data with connect requests
6254 	 * by unlinking M_DATA trailers here and
6255 	 * linking them in behind the T_OK_ACK mblk.
6256 	 * The tcp_rput() bind ack handler would then
6257 	 * feed them to tcp_wput_data() rather than call
6258 	 * tcp_timer().
6259 	 */
6260 	mp = mi_tpi_ok_ack_alloc(mp);
6261 	if (!mp) {
6262 		tcp->tcp_state = oldstate;
6263 		goto failed;
6264 	}
6265 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6266 	if (mp1) {
6267 		/* Hang onto the T_OK_ACK for later. */
6268 		linkb(mp1, mp);
6269 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6270 		    &tcp->tcp_sticky_ipp);
6271 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6272 		tcp->tcp_active_open = 1;
6273 		/* ip_bind_v6() may return ACK or ERROR */
6274 		if (mp1 != NULL)
6275 			tcp_rput_other(tcp, mp1);
6276 		return;
6277 	}
6278 	/* Error case */
6279 	tcp->tcp_state = oldstate;
6280 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6281 
6282 failed:
6283 	/* return error ack and blow away saved option results if any */
6284 	if (mp != NULL)
6285 		putnext(tcp->tcp_rq, mp);
6286 	else {
6287 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6288 		    TSYSERR, ENOMEM);
6289 	}
6290 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6291 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6292 }
6293 
6294 /*
6295  * We need a stream q for detached closing tcp connections
6296  * to use.  Our client hereby indicates that this q is the
6297  * one to use.
6298  */
6299 static void
6300 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6301 {
6302 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6303 	queue_t	*q = tcp->tcp_wq;
6304 
6305 	mp->b_datap->db_type = M_IOCACK;
6306 	iocp->ioc_count = 0;
6307 	mutex_enter(&tcp_g_q_lock);
6308 	if (tcp_g_q != NULL) {
6309 		mutex_exit(&tcp_g_q_lock);
6310 		iocp->ioc_error = EALREADY;
6311 	} else {
6312 		mblk_t *mp1;
6313 
6314 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6315 		if (mp1 == NULL) {
6316 			mutex_exit(&tcp_g_q_lock);
6317 			iocp->ioc_error = ENOMEM;
6318 		} else {
6319 			tcp_g_q = tcp->tcp_rq;
6320 			mutex_exit(&tcp_g_q_lock);
6321 			iocp->ioc_error = 0;
6322 			iocp->ioc_rval = 0;
6323 			/*
6324 			 * We are passing tcp_sticky_ipp as NULL
6325 			 * as it is not useful for tcp_default queue
6326 			 */
6327 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6328 			if (mp1 != NULL)
6329 				tcp_rput_other(tcp, mp1);
6330 		}
6331 	}
6332 	qreply(q, mp);
6333 }
6334 
6335 /*
6336  * Our client hereby directs us to reject the connection request
6337  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6338  * of sending the appropriate RST, not an ICMP error.
6339  */
6340 static void
6341 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6342 {
6343 	tcp_t	*ltcp = NULL;
6344 	t_scalar_t seqnum;
6345 	conn_t	*connp;
6346 
6347 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6348 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6349 		tcp_err_ack(tcp, mp, TPROTO, 0);
6350 		return;
6351 	}
6352 
6353 	/*
6354 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6355 	 * when the stream is in BOUND state. Do not send a reset,
6356 	 * since the destination IP address is not valid, and it can
6357 	 * be the initialized value of all zeros (broadcast address).
6358 	 *
6359 	 * If TCP has sent down a bind request to IP and has not
6360 	 * received the reply, reject the request.  Otherwise, TCP
6361 	 * will be confused.
6362 	 */
6363 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6364 		if (tcp->tcp_debug) {
6365 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6366 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6367 		}
6368 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6369 		return;
6370 	}
6371 
6372 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6373 
6374 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6375 
6376 		/*
6377 		 * According to TPI, for non-listeners, ignore seqnum
6378 		 * and disconnect.
6379 		 * Following interpretation of -1 seqnum is historical
6380 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6381 		 * a valid seqnum should not be -1).
6382 		 *
6383 		 *	-1 means disconnect everything
6384 		 *	regardless even on a listener.
6385 		 */
6386 
6387 		int old_state = tcp->tcp_state;
6388 
6389 		/*
6390 		 * The connection can't be on the tcp_time_wait_head list
6391 		 * since it is not detached.
6392 		 */
6393 		ASSERT(tcp->tcp_time_wait_next == NULL);
6394 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6395 		ASSERT(tcp->tcp_time_wait_expire == 0);
6396 		ltcp = NULL;
6397 		/*
6398 		 * If it used to be a listener, check to make sure no one else
6399 		 * has taken the port before switching back to LISTEN state.
6400 		 */
6401 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6402 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6403 			    tcp->tcp_ipha->ipha_src,
6404 			    tcp->tcp_connp->conn_zoneid);
6405 			if (connp != NULL)
6406 				ltcp = connp->conn_tcp;
6407 		} else {
6408 			/* Allow tcp_bound_if listeners? */
6409 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6410 			    &tcp->tcp_ip6h->ip6_src, 0,
6411 			    tcp->tcp_connp->conn_zoneid);
6412 			if (connp != NULL)
6413 				ltcp = connp->conn_tcp;
6414 		}
6415 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6416 			tcp->tcp_state = TCPS_LISTEN;
6417 		} else if (old_state > TCPS_BOUND) {
6418 			tcp->tcp_conn_req_max = 0;
6419 			tcp->tcp_state = TCPS_BOUND;
6420 		}
6421 		if (ltcp != NULL)
6422 			CONN_DEC_REF(ltcp->tcp_connp);
6423 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6424 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6425 		} else if (old_state == TCPS_ESTABLISHED ||
6426 		    old_state == TCPS_CLOSE_WAIT) {
6427 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6428 		}
6429 
6430 		if (tcp->tcp_fused)
6431 			tcp_unfuse(tcp);
6432 
6433 		mutex_enter(&tcp->tcp_eager_lock);
6434 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6435 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6436 			tcp_eager_cleanup(tcp, 0);
6437 		}
6438 		mutex_exit(&tcp->tcp_eager_lock);
6439 
6440 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6441 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6442 
6443 		tcp_reinit(tcp);
6444 
6445 		if (old_state >= TCPS_ESTABLISHED) {
6446 			/* Send M_FLUSH according to TPI */
6447 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6448 		}
6449 		mp = mi_tpi_ok_ack_alloc(mp);
6450 		if (mp)
6451 			putnext(tcp->tcp_rq, mp);
6452 		return;
6453 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6454 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6455 		return;
6456 	}
6457 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6458 		/* Send M_FLUSH according to TPI */
6459 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6460 	}
6461 	mp = mi_tpi_ok_ack_alloc(mp);
6462 	if (mp)
6463 		putnext(tcp->tcp_rq, mp);
6464 }
6465 
6466 /*
6467  * Diagnostic routine used to return a string associated with the tcp state.
6468  * Note that if the caller does not supply a buffer, it will use an internal
6469  * static string.  This means that if multiple threads call this function at
6470  * the same time, output can be corrupted...  Note also that this function
6471  * does not check the size of the supplied buffer.  The caller has to make
6472  * sure that it is big enough.
6473  */
6474 static char *
6475 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6476 {
6477 	char		buf1[30];
6478 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6479 	char		*buf;
6480 	char		*cp;
6481 	in6_addr_t	local, remote;
6482 	char		local_addrbuf[INET6_ADDRSTRLEN];
6483 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6484 
6485 	if (sup_buf != NULL)
6486 		buf = sup_buf;
6487 	else
6488 		buf = priv_buf;
6489 
6490 	if (tcp == NULL)
6491 		return ("NULL_TCP");
6492 	switch (tcp->tcp_state) {
6493 	case TCPS_CLOSED:
6494 		cp = "TCP_CLOSED";
6495 		break;
6496 	case TCPS_IDLE:
6497 		cp = "TCP_IDLE";
6498 		break;
6499 	case TCPS_BOUND:
6500 		cp = "TCP_BOUND";
6501 		break;
6502 	case TCPS_LISTEN:
6503 		cp = "TCP_LISTEN";
6504 		break;
6505 	case TCPS_SYN_SENT:
6506 		cp = "TCP_SYN_SENT";
6507 		break;
6508 	case TCPS_SYN_RCVD:
6509 		cp = "TCP_SYN_RCVD";
6510 		break;
6511 	case TCPS_ESTABLISHED:
6512 		cp = "TCP_ESTABLISHED";
6513 		break;
6514 	case TCPS_CLOSE_WAIT:
6515 		cp = "TCP_CLOSE_WAIT";
6516 		break;
6517 	case TCPS_FIN_WAIT_1:
6518 		cp = "TCP_FIN_WAIT_1";
6519 		break;
6520 	case TCPS_CLOSING:
6521 		cp = "TCP_CLOSING";
6522 		break;
6523 	case TCPS_LAST_ACK:
6524 		cp = "TCP_LAST_ACK";
6525 		break;
6526 	case TCPS_FIN_WAIT_2:
6527 		cp = "TCP_FIN_WAIT_2";
6528 		break;
6529 	case TCPS_TIME_WAIT:
6530 		cp = "TCP_TIME_WAIT";
6531 		break;
6532 	default:
6533 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6534 		cp = buf1;
6535 		break;
6536 	}
6537 	switch (format) {
6538 	case DISP_ADDR_AND_PORT:
6539 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6540 			/*
6541 			 * Note that we use the remote address in the tcp_b
6542 			 * structure.  This means that it will print out
6543 			 * the real destination address, not the next hop's
6544 			 * address if source routing is used.
6545 			 */
6546 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6547 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6548 
6549 		} else {
6550 			local = tcp->tcp_ip_src_v6;
6551 			remote = tcp->tcp_remote_v6;
6552 		}
6553 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6554 		    sizeof (local_addrbuf));
6555 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6556 		    sizeof (remote_addrbuf));
6557 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6558 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6559 		    ntohs(tcp->tcp_fport), cp);
6560 		break;
6561 	case DISP_PORT_ONLY:
6562 	default:
6563 		(void) mi_sprintf(buf, "[%u, %u] %s",
6564 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6565 		break;
6566 	}
6567 
6568 	return (buf);
6569 }
6570 
6571 /*
6572  * Called via squeue to get on to eager's perimeter to send a
6573  * TH_RST. The listener wants the eager to disappear either
6574  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6575  * being called.
6576  */
6577 /* ARGSUSED */
6578 void
6579 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6580 {
6581 	conn_t	*econnp = (conn_t *)arg;
6582 	tcp_t	*eager = econnp->conn_tcp;
6583 	tcp_t	*listener = eager->tcp_listener;
6584 
6585 	/*
6586 	 * We could be called because listener is closing. Since
6587 	 * the eager is using listener's queue's, its not safe.
6588 	 * Better use the default queue just to send the TH_RST
6589 	 * out.
6590 	 */
6591 	eager->tcp_rq = tcp_g_q;
6592 	eager->tcp_wq = WR(tcp_g_q);
6593 
6594 	if (eager->tcp_state > TCPS_LISTEN) {
6595 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6596 		    eager, eager->tcp_snxt, 0, TH_RST);
6597 	}
6598 
6599 	/* We are here because listener wants this eager gone */
6600 	if (listener != NULL) {
6601 		mutex_enter(&listener->tcp_eager_lock);
6602 		tcp_eager_unlink(eager);
6603 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6604 			/*
6605 			 * The eager has sent a conn_ind up to the
6606 			 * listener but listener decides to close
6607 			 * instead. We need to drop the extra ref
6608 			 * placed on eager in tcp_rput_data() before
6609 			 * sending the conn_ind to listener.
6610 			 */
6611 			CONN_DEC_REF(econnp);
6612 		}
6613 		mutex_exit(&listener->tcp_eager_lock);
6614 		CONN_DEC_REF(listener->tcp_connp);
6615 	}
6616 
6617 	if (eager->tcp_state > TCPS_BOUND)
6618 		tcp_close_detached(eager);
6619 }
6620 
6621 /*
6622  * Reset any eager connection hanging off this listener marked
6623  * with 'seqnum' and then reclaim it's resources.
6624  */
6625 static boolean_t
6626 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6627 {
6628 	tcp_t	*eager;
6629 	mblk_t 	*mp;
6630 
6631 	TCP_STAT(tcp_eager_blowoff_calls);
6632 	eager = listener;
6633 	mutex_enter(&listener->tcp_eager_lock);
6634 	do {
6635 		eager = eager->tcp_eager_next_q;
6636 		if (eager == NULL) {
6637 			mutex_exit(&listener->tcp_eager_lock);
6638 			return (B_FALSE);
6639 		}
6640 	} while (eager->tcp_conn_req_seqnum != seqnum);
6641 	CONN_INC_REF(eager->tcp_connp);
6642 	mutex_exit(&listener->tcp_eager_lock);
6643 	mp = &eager->tcp_closemp;
6644 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6645 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6646 	return (B_TRUE);
6647 }
6648 
6649 /*
6650  * Reset any eager connection hanging off this listener
6651  * and then reclaim it's resources.
6652  */
6653 static void
6654 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6655 {
6656 	tcp_t	*eager;
6657 	mblk_t	*mp;
6658 
6659 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6660 
6661 	if (!q0_only) {
6662 		/* First cleanup q */
6663 		TCP_STAT(tcp_eager_blowoff_q);
6664 		eager = listener->tcp_eager_next_q;
6665 		while (eager != NULL) {
6666 			CONN_INC_REF(eager->tcp_connp);
6667 			mp = &eager->tcp_closemp;
6668 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6669 			    tcp_eager_kill, eager->tcp_connp,
6670 			    SQTAG_TCP_EAGER_CLEANUP);
6671 			eager = eager->tcp_eager_next_q;
6672 		}
6673 	}
6674 	/* Then cleanup q0 */
6675 	TCP_STAT(tcp_eager_blowoff_q0);
6676 	eager = listener->tcp_eager_next_q0;
6677 	while (eager != listener) {
6678 		CONN_INC_REF(eager->tcp_connp);
6679 		mp = &eager->tcp_closemp;
6680 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6681 		    tcp_eager_kill, eager->tcp_connp,
6682 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6683 		eager = eager->tcp_eager_next_q0;
6684 	}
6685 }
6686 
6687 /*
6688  * If we are an eager connection hanging off a listener that hasn't
6689  * formally accepted the connection yet, get off his list and blow off
6690  * any data that we have accumulated.
6691  */
6692 static void
6693 tcp_eager_unlink(tcp_t *tcp)
6694 {
6695 	tcp_t	*listener = tcp->tcp_listener;
6696 
6697 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6698 	ASSERT(listener != NULL);
6699 	if (tcp->tcp_eager_next_q0 != NULL) {
6700 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6701 
6702 		/* Remove the eager tcp from q0 */
6703 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6704 		    tcp->tcp_eager_prev_q0;
6705 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6706 		    tcp->tcp_eager_next_q0;
6707 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6708 		listener->tcp_conn_req_cnt_q0--;
6709 
6710 		tcp->tcp_eager_next_q0 = NULL;
6711 		tcp->tcp_eager_prev_q0 = NULL;
6712 
6713 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6714 			/* we have timed out before */
6715 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6716 			listener->tcp_syn_rcvd_timeout--;
6717 		}
6718 	} else {
6719 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6720 		tcp_t	*prev = NULL;
6721 
6722 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6723 			if (tcpp[0] == tcp) {
6724 				if (listener->tcp_eager_last_q == tcp) {
6725 					/*
6726 					 * If we are unlinking the last
6727 					 * element on the list, adjust
6728 					 * tail pointer. Set tail pointer
6729 					 * to nil when list is empty.
6730 					 */
6731 					ASSERT(tcp->tcp_eager_next_q == NULL);
6732 					if (listener->tcp_eager_last_q ==
6733 					    listener->tcp_eager_next_q) {
6734 						listener->tcp_eager_last_q =
6735 						NULL;
6736 					} else {
6737 						/*
6738 						 * We won't get here if there
6739 						 * is only one eager in the
6740 						 * list.
6741 						 */
6742 						ASSERT(prev != NULL);
6743 						listener->tcp_eager_last_q =
6744 						    prev;
6745 					}
6746 				}
6747 				tcpp[0] = tcp->tcp_eager_next_q;
6748 				tcp->tcp_eager_next_q = NULL;
6749 				tcp->tcp_eager_last_q = NULL;
6750 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6751 				listener->tcp_conn_req_cnt_q--;
6752 				break;
6753 			}
6754 			prev = tcpp[0];
6755 		}
6756 	}
6757 	tcp->tcp_listener = NULL;
6758 }
6759 
6760 /* Shorthand to generate and send TPI error acks to our client */
6761 static void
6762 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6763 {
6764 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6765 		putnext(tcp->tcp_rq, mp);
6766 }
6767 
6768 /* Shorthand to generate and send TPI error acks to our client */
6769 static void
6770 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6771     int t_error, int sys_error)
6772 {
6773 	struct T_error_ack	*teackp;
6774 
6775 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6776 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6777 		teackp = (struct T_error_ack *)mp->b_rptr;
6778 		teackp->ERROR_prim = primitive;
6779 		teackp->TLI_error = t_error;
6780 		teackp->UNIX_error = sys_error;
6781 		putnext(tcp->tcp_rq, mp);
6782 	}
6783 }
6784 
6785 /*
6786  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6787  * but instead the code relies on:
6788  * - the fact that the address of the array and its size never changes
6789  * - the atomic assignment of the elements of the array
6790  */
6791 /* ARGSUSED */
6792 static int
6793 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6794 {
6795 	int i;
6796 
6797 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6798 		if (tcp_g_epriv_ports[i] != 0)
6799 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
6800 	}
6801 	return (0);
6802 }
6803 
6804 /*
6805  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6806  * threads from changing it at the same time.
6807  */
6808 /* ARGSUSED */
6809 static int
6810 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6811     cred_t *cr)
6812 {
6813 	long	new_value;
6814 	int	i;
6815 
6816 	/*
6817 	 * Fail the request if the new value does not lie within the
6818 	 * port number limits.
6819 	 */
6820 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6821 	    new_value <= 0 || new_value >= 65536) {
6822 		return (EINVAL);
6823 	}
6824 
6825 	mutex_enter(&tcp_epriv_port_lock);
6826 	/* Check if the value is already in the list */
6827 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6828 		if (new_value == tcp_g_epriv_ports[i]) {
6829 			mutex_exit(&tcp_epriv_port_lock);
6830 			return (EEXIST);
6831 		}
6832 	}
6833 	/* Find an empty slot */
6834 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6835 		if (tcp_g_epriv_ports[i] == 0)
6836 			break;
6837 	}
6838 	if (i == tcp_g_num_epriv_ports) {
6839 		mutex_exit(&tcp_epriv_port_lock);
6840 		return (EOVERFLOW);
6841 	}
6842 	/* Set the new value */
6843 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
6844 	mutex_exit(&tcp_epriv_port_lock);
6845 	return (0);
6846 }
6847 
6848 /*
6849  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6850  * threads from changing it at the same time.
6851  */
6852 /* ARGSUSED */
6853 static int
6854 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6855     cred_t *cr)
6856 {
6857 	long	new_value;
6858 	int	i;
6859 
6860 	/*
6861 	 * Fail the request if the new value does not lie within the
6862 	 * port number limits.
6863 	 */
6864 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6865 	    new_value >= 65536) {
6866 		return (EINVAL);
6867 	}
6868 
6869 	mutex_enter(&tcp_epriv_port_lock);
6870 	/* Check that the value is already in the list */
6871 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6872 		if (tcp_g_epriv_ports[i] == new_value)
6873 			break;
6874 	}
6875 	if (i == tcp_g_num_epriv_ports) {
6876 		mutex_exit(&tcp_epriv_port_lock);
6877 		return (ESRCH);
6878 	}
6879 	/* Clear the value */
6880 	tcp_g_epriv_ports[i] = 0;
6881 	mutex_exit(&tcp_epriv_port_lock);
6882 	return (0);
6883 }
6884 
6885 /* Return the TPI/TLI equivalent of our current tcp_state */
6886 static int
6887 tcp_tpistate(tcp_t *tcp)
6888 {
6889 	switch (tcp->tcp_state) {
6890 	case TCPS_IDLE:
6891 		return (TS_UNBND);
6892 	case TCPS_LISTEN:
6893 		/*
6894 		 * Return whether there are outstanding T_CONN_IND waiting
6895 		 * for the matching T_CONN_RES. Therefore don't count q0.
6896 		 */
6897 		if (tcp->tcp_conn_req_cnt_q > 0)
6898 			return (TS_WRES_CIND);
6899 		else
6900 			return (TS_IDLE);
6901 	case TCPS_BOUND:
6902 		return (TS_IDLE);
6903 	case TCPS_SYN_SENT:
6904 		return (TS_WCON_CREQ);
6905 	case TCPS_SYN_RCVD:
6906 		/*
6907 		 * Note: assumption: this has to the active open SYN_RCVD.
6908 		 * The passive instance is detached in SYN_RCVD stage of
6909 		 * incoming connection processing so we cannot get request
6910 		 * for T_info_ack on it.
6911 		 */
6912 		return (TS_WACK_CRES);
6913 	case TCPS_ESTABLISHED:
6914 		return (TS_DATA_XFER);
6915 	case TCPS_CLOSE_WAIT:
6916 		return (TS_WREQ_ORDREL);
6917 	case TCPS_FIN_WAIT_1:
6918 		return (TS_WIND_ORDREL);
6919 	case TCPS_FIN_WAIT_2:
6920 		return (TS_WIND_ORDREL);
6921 
6922 	case TCPS_CLOSING:
6923 	case TCPS_LAST_ACK:
6924 	case TCPS_TIME_WAIT:
6925 	case TCPS_CLOSED:
6926 		/*
6927 		 * Following TS_WACK_DREQ7 is a rendition of "not
6928 		 * yet TS_IDLE" TPI state. There is no best match to any
6929 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6930 		 * choose a value chosen that will map to TLI/XTI level
6931 		 * state of TSTATECHNG (state is process of changing) which
6932 		 * captures what this dummy state represents.
6933 		 */
6934 		return (TS_WACK_DREQ7);
6935 	default:
6936 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6937 		    tcp->tcp_state, tcp_display(tcp, NULL,
6938 		    DISP_PORT_ONLY));
6939 		return (TS_UNBND);
6940 	}
6941 }
6942 
6943 static void
6944 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6945 {
6946 	if (tcp->tcp_family == AF_INET6)
6947 		*tia = tcp_g_t_info_ack_v6;
6948 	else
6949 		*tia = tcp_g_t_info_ack;
6950 	tia->CURRENT_state = tcp_tpistate(tcp);
6951 	tia->OPT_size = tcp_max_optsize;
6952 	if (tcp->tcp_mss == 0) {
6953 		/* Not yet set - tcp_open does not set mss */
6954 		if (tcp->tcp_ipversion == IPV4_VERSION)
6955 			tia->TIDU_size = tcp_mss_def_ipv4;
6956 		else
6957 			tia->TIDU_size = tcp_mss_def_ipv6;
6958 	} else {
6959 		tia->TIDU_size = tcp->tcp_mss;
6960 	}
6961 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6962 }
6963 
6964 /*
6965  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6966  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6967  * tcp_g_t_info_ack.  The current state of the stream is copied from
6968  * tcp_state.
6969  */
6970 static void
6971 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6972 {
6973 	t_uscalar_t		cap_bits1;
6974 	struct T_capability_ack	*tcap;
6975 
6976 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6977 		freemsg(mp);
6978 		return;
6979 	}
6980 
6981 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6982 
6983 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6984 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6985 	if (mp == NULL)
6986 		return;
6987 
6988 	tcap = (struct T_capability_ack *)mp->b_rptr;
6989 	tcap->CAP_bits1 = 0;
6990 
6991 	if (cap_bits1 & TC1_INFO) {
6992 		tcp_copy_info(&tcap->INFO_ack, tcp);
6993 		tcap->CAP_bits1 |= TC1_INFO;
6994 	}
6995 
6996 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6997 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6998 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6999 	}
7000 
7001 	putnext(tcp->tcp_rq, mp);
7002 }
7003 
7004 /*
7005  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7006  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7007  * The current state of the stream is copied from tcp_state.
7008  */
7009 static void
7010 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7011 {
7012 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7013 	    T_INFO_ACK);
7014 	if (!mp) {
7015 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7016 		return;
7017 	}
7018 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7019 	putnext(tcp->tcp_rq, mp);
7020 }
7021 
7022 /* Respond to the TPI addr request */
7023 static void
7024 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7025 {
7026 	sin_t	*sin;
7027 	mblk_t	*ackmp;
7028 	struct T_addr_ack *taa;
7029 
7030 	/* Make it large enough for worst case */
7031 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7032 	    2 * sizeof (sin6_t), 1);
7033 	if (ackmp == NULL) {
7034 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7035 		return;
7036 	}
7037 
7038 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7039 		tcp_addr_req_ipv6(tcp, ackmp);
7040 		return;
7041 	}
7042 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7043 
7044 	bzero(taa, sizeof (struct T_addr_ack));
7045 	ackmp->b_wptr = (uchar_t *)&taa[1];
7046 
7047 	taa->PRIM_type = T_ADDR_ACK;
7048 	ackmp->b_datap->db_type = M_PCPROTO;
7049 
7050 	/*
7051 	 * Note: Following code assumes 32 bit alignment of basic
7052 	 * data structures like sin_t and struct T_addr_ack.
7053 	 */
7054 	if (tcp->tcp_state >= TCPS_BOUND) {
7055 		/*
7056 		 * Fill in local address
7057 		 */
7058 		taa->LOCADDR_length = sizeof (sin_t);
7059 		taa->LOCADDR_offset = sizeof (*taa);
7060 
7061 		sin = (sin_t *)&taa[1];
7062 
7063 		/* Fill zeroes and then intialize non-zero fields */
7064 		*sin = sin_null;
7065 
7066 		sin->sin_family = AF_INET;
7067 
7068 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7069 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7070 
7071 		ackmp->b_wptr = (uchar_t *)&sin[1];
7072 
7073 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7074 			/*
7075 			 * Fill in Remote address
7076 			 */
7077 			taa->REMADDR_length = sizeof (sin_t);
7078 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7079 						taa->LOCADDR_length);
7080 
7081 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7082 			*sin = sin_null;
7083 			sin->sin_family = AF_INET;
7084 			sin->sin_addr.s_addr = tcp->tcp_remote;
7085 			sin->sin_port = tcp->tcp_fport;
7086 
7087 			ackmp->b_wptr = (uchar_t *)&sin[1];
7088 		}
7089 	}
7090 	putnext(tcp->tcp_rq, ackmp);
7091 }
7092 
7093 /* Assumes that tcp_addr_req gets enough space and alignment */
7094 static void
7095 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7096 {
7097 	sin6_t	*sin6;
7098 	struct T_addr_ack *taa;
7099 
7100 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7101 	ASSERT(OK_32PTR(ackmp->b_rptr));
7102 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7103 	    2 * sizeof (sin6_t));
7104 
7105 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7106 
7107 	bzero(taa, sizeof (struct T_addr_ack));
7108 	ackmp->b_wptr = (uchar_t *)&taa[1];
7109 
7110 	taa->PRIM_type = T_ADDR_ACK;
7111 	ackmp->b_datap->db_type = M_PCPROTO;
7112 
7113 	/*
7114 	 * Note: Following code assumes 32 bit alignment of basic
7115 	 * data structures like sin6_t and struct T_addr_ack.
7116 	 */
7117 	if (tcp->tcp_state >= TCPS_BOUND) {
7118 		/*
7119 		 * Fill in local address
7120 		 */
7121 		taa->LOCADDR_length = sizeof (sin6_t);
7122 		taa->LOCADDR_offset = sizeof (*taa);
7123 
7124 		sin6 = (sin6_t *)&taa[1];
7125 		*sin6 = sin6_null;
7126 
7127 		sin6->sin6_family = AF_INET6;
7128 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7129 		sin6->sin6_port = tcp->tcp_lport;
7130 
7131 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7132 
7133 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7134 			/*
7135 			 * Fill in Remote address
7136 			 */
7137 			taa->REMADDR_length = sizeof (sin6_t);
7138 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7139 						taa->LOCADDR_length);
7140 
7141 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7142 			*sin6 = sin6_null;
7143 			sin6->sin6_family = AF_INET6;
7144 			sin6->sin6_flowinfo =
7145 			    tcp->tcp_ip6h->ip6_vcf &
7146 			    ~IPV6_VERS_AND_FLOW_MASK;
7147 			sin6->sin6_addr = tcp->tcp_remote_v6;
7148 			sin6->sin6_port = tcp->tcp_fport;
7149 
7150 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7151 		}
7152 	}
7153 	putnext(tcp->tcp_rq, ackmp);
7154 }
7155 
7156 /*
7157  * Handle reinitialization of a tcp structure.
7158  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7159  */
7160 static void
7161 tcp_reinit(tcp_t *tcp)
7162 {
7163 	mblk_t	*mp;
7164 	int 	err;
7165 
7166 	TCP_STAT(tcp_reinit_calls);
7167 
7168 	/* tcp_reinit should never be called for detached tcp_t's */
7169 	ASSERT(tcp->tcp_listener == NULL);
7170 	ASSERT((tcp->tcp_family == AF_INET &&
7171 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7172 	    (tcp->tcp_family == AF_INET6 &&
7173 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7174 	    tcp->tcp_ipversion == IPV6_VERSION)));
7175 
7176 	/* Cancel outstanding timers */
7177 	tcp_timers_stop(tcp);
7178 
7179 	/*
7180 	 * Reset everything in the state vector, after updating global
7181 	 * MIB data from instance counters.
7182 	 */
7183 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7184 	tcp->tcp_ibsegs = 0;
7185 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7186 	tcp->tcp_obsegs = 0;
7187 
7188 	tcp_close_mpp(&tcp->tcp_xmit_head);
7189 	if (tcp->tcp_snd_zcopy_aware)
7190 		tcp_zcopy_notify(tcp);
7191 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7192 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7193 	if (tcp->tcp_flow_stopped &&
7194 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7195 		tcp_clrqfull(tcp);
7196 	}
7197 	tcp_close_mpp(&tcp->tcp_reass_head);
7198 	tcp->tcp_reass_tail = NULL;
7199 	if (tcp->tcp_rcv_list != NULL) {
7200 		/* Free b_next chain */
7201 		tcp_close_mpp(&tcp->tcp_rcv_list);
7202 		tcp->tcp_rcv_last_head = NULL;
7203 		tcp->tcp_rcv_last_tail = NULL;
7204 		tcp->tcp_rcv_cnt = 0;
7205 	}
7206 	tcp->tcp_rcv_last_tail = NULL;
7207 
7208 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7209 		freemsg(mp);
7210 		tcp->tcp_urp_mp = NULL;
7211 	}
7212 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7213 		freemsg(mp);
7214 		tcp->tcp_urp_mark_mp = NULL;
7215 	}
7216 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7217 		freeb(tcp->tcp_fused_sigurg_mp);
7218 		tcp->tcp_fused_sigurg_mp = NULL;
7219 	}
7220 
7221 	/*
7222 	 * Following is a union with two members which are
7223 	 * identical types and size so the following cleanup
7224 	 * is enough.
7225 	 */
7226 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7227 
7228 	CL_INET_DISCONNECT(tcp);
7229 
7230 	/*
7231 	 * The connection can't be on the tcp_time_wait_head list
7232 	 * since it is not detached.
7233 	 */
7234 	ASSERT(tcp->tcp_time_wait_next == NULL);
7235 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7236 	ASSERT(tcp->tcp_time_wait_expire == 0);
7237 
7238 	if (tcp->tcp_kssl_pending) {
7239 		tcp->tcp_kssl_pending = B_FALSE;
7240 
7241 		/* Don't reset if the initialized by bind. */
7242 		if (tcp->tcp_kssl_ent != NULL) {
7243 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7244 			    KSSL_NO_PROXY);
7245 		}
7246 	}
7247 	if (tcp->tcp_kssl_ctx != NULL) {
7248 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7249 		tcp->tcp_kssl_ctx = NULL;
7250 	}
7251 
7252 	/*
7253 	 * Reset/preserve other values
7254 	 */
7255 	tcp_reinit_values(tcp);
7256 	ipcl_hash_remove(tcp->tcp_connp);
7257 	conn_delete_ire(tcp->tcp_connp, NULL);
7258 
7259 	if (tcp->tcp_conn_req_max != 0) {
7260 		/*
7261 		 * This is the case when a TLI program uses the same
7262 		 * transport end point to accept a connection.  This
7263 		 * makes the TCP both a listener and acceptor.  When
7264 		 * this connection is closed, we need to set the state
7265 		 * back to TCPS_LISTEN.  Make sure that the eager list
7266 		 * is reinitialized.
7267 		 *
7268 		 * Note that this stream is still bound to the four
7269 		 * tuples of the previous connection in IP.  If a new
7270 		 * SYN with different foreign address comes in, IP will
7271 		 * not find it and will send it to the global queue.  In
7272 		 * the global queue, TCP will do a tcp_lookup_listener()
7273 		 * to find this stream.  This works because this stream
7274 		 * is only removed from connected hash.
7275 		 *
7276 		 */
7277 		tcp->tcp_state = TCPS_LISTEN;
7278 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7279 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7280 		if (tcp->tcp_family == AF_INET6) {
7281 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7282 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7283 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7284 		} else {
7285 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7286 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7287 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7288 		}
7289 	} else {
7290 		tcp->tcp_state = TCPS_BOUND;
7291 	}
7292 
7293 	/*
7294 	 * Initialize to default values
7295 	 * Can't fail since enough header template space already allocated
7296 	 * at open().
7297 	 */
7298 	err = tcp_init_values(tcp);
7299 	ASSERT(err == 0);
7300 	/* Restore state in tcp_tcph */
7301 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7302 	if (tcp->tcp_ipversion == IPV4_VERSION)
7303 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7304 	else
7305 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7306 	/*
7307 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7308 	 * since the lookup funcs can only lookup on tcp_t
7309 	 */
7310 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7311 
7312 	ASSERT(tcp->tcp_ptpbhn != NULL);
7313 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7314 	tcp->tcp_rwnd = tcp_recv_hiwat;
7315 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7316 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7317 }
7318 
7319 /*
7320  * Force values to zero that need be zero.
7321  * Do not touch values asociated with the BOUND or LISTEN state
7322  * since the connection will end up in that state after the reinit.
7323  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7324  * structure!
7325  */
7326 static void
7327 tcp_reinit_values(tcp)
7328 	tcp_t *tcp;
7329 {
7330 #ifndef	lint
7331 #define	DONTCARE(x)
7332 #define	PRESERVE(x)
7333 #else
7334 #define	DONTCARE(x)	((x) = (x))
7335 #define	PRESERVE(x)	((x) = (x))
7336 #endif	/* lint */
7337 
7338 	PRESERVE(tcp->tcp_bind_hash);
7339 	PRESERVE(tcp->tcp_ptpbhn);
7340 	PRESERVE(tcp->tcp_acceptor_hash);
7341 	PRESERVE(tcp->tcp_ptpahn);
7342 
7343 	/* Should be ASSERT NULL on these with new code! */
7344 	ASSERT(tcp->tcp_time_wait_next == NULL);
7345 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7346 	ASSERT(tcp->tcp_time_wait_expire == 0);
7347 	PRESERVE(tcp->tcp_state);
7348 	PRESERVE(tcp->tcp_rq);
7349 	PRESERVE(tcp->tcp_wq);
7350 
7351 	ASSERT(tcp->tcp_xmit_head == NULL);
7352 	ASSERT(tcp->tcp_xmit_last == NULL);
7353 	ASSERT(tcp->tcp_unsent == 0);
7354 	ASSERT(tcp->tcp_xmit_tail == NULL);
7355 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7356 
7357 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7358 	tcp->tcp_suna = 0;			/* Displayed in mib */
7359 	tcp->tcp_swnd = 0;
7360 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7361 
7362 	ASSERT(tcp->tcp_ibsegs == 0);
7363 	ASSERT(tcp->tcp_obsegs == 0);
7364 
7365 	if (tcp->tcp_iphc != NULL) {
7366 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7367 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7368 	}
7369 
7370 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7371 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7372 	DONTCARE(tcp->tcp_ipha);
7373 	DONTCARE(tcp->tcp_ip6h);
7374 	DONTCARE(tcp->tcp_ip_hdr_len);
7375 	DONTCARE(tcp->tcp_tcph);
7376 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7377 	tcp->tcp_valid_bits = 0;
7378 
7379 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7380 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7381 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7382 	tcp->tcp_last_rcv_lbolt = 0;
7383 
7384 	tcp->tcp_init_cwnd = 0;
7385 
7386 	tcp->tcp_urp_last_valid = 0;
7387 	tcp->tcp_hard_binding = 0;
7388 	tcp->tcp_hard_bound = 0;
7389 	PRESERVE(tcp->tcp_cred);
7390 	PRESERVE(tcp->tcp_cpid);
7391 	PRESERVE(tcp->tcp_exclbind);
7392 
7393 	tcp->tcp_fin_acked = 0;
7394 	tcp->tcp_fin_rcvd = 0;
7395 	tcp->tcp_fin_sent = 0;
7396 	tcp->tcp_ordrel_done = 0;
7397 
7398 	tcp->tcp_debug = 0;
7399 	tcp->tcp_dontroute = 0;
7400 	tcp->tcp_broadcast = 0;
7401 
7402 	tcp->tcp_useloopback = 0;
7403 	tcp->tcp_reuseaddr = 0;
7404 	tcp->tcp_oobinline = 0;
7405 	tcp->tcp_dgram_errind = 0;
7406 
7407 	tcp->tcp_detached = 0;
7408 	tcp->tcp_bind_pending = 0;
7409 	tcp->tcp_unbind_pending = 0;
7410 	tcp->tcp_deferred_clean_death = 0;
7411 
7412 	tcp->tcp_snd_ws_ok = B_FALSE;
7413 	tcp->tcp_snd_ts_ok = B_FALSE;
7414 	tcp->tcp_linger = 0;
7415 	tcp->tcp_ka_enabled = 0;
7416 	tcp->tcp_zero_win_probe = 0;
7417 
7418 	tcp->tcp_loopback = 0;
7419 	tcp->tcp_localnet = 0;
7420 	tcp->tcp_syn_defense = 0;
7421 	tcp->tcp_set_timer = 0;
7422 
7423 	tcp->tcp_active_open = 0;
7424 	ASSERT(tcp->tcp_timeout == B_FALSE);
7425 	tcp->tcp_rexmit = B_FALSE;
7426 	tcp->tcp_xmit_zc_clean = B_FALSE;
7427 
7428 	tcp->tcp_snd_sack_ok = B_FALSE;
7429 	PRESERVE(tcp->tcp_recvdstaddr);
7430 	tcp->tcp_hwcksum = B_FALSE;
7431 
7432 	tcp->tcp_ire_ill_check_done = B_FALSE;
7433 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7434 
7435 	tcp->tcp_mdt = B_FALSE;
7436 	tcp->tcp_mdt_hdr_head = 0;
7437 	tcp->tcp_mdt_hdr_tail = 0;
7438 
7439 	tcp->tcp_conn_def_q0 = 0;
7440 	tcp->tcp_ip_forward_progress = B_FALSE;
7441 	tcp->tcp_anon_priv_bind = 0;
7442 	tcp->tcp_ecn_ok = B_FALSE;
7443 
7444 	tcp->tcp_cwr = B_FALSE;
7445 	tcp->tcp_ecn_echo_on = B_FALSE;
7446 
7447 	if (tcp->tcp_sack_info != NULL) {
7448 		if (tcp->tcp_notsack_list != NULL) {
7449 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7450 		}
7451 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7452 		tcp->tcp_sack_info = NULL;
7453 	}
7454 
7455 	tcp->tcp_rcv_ws = 0;
7456 	tcp->tcp_snd_ws = 0;
7457 	tcp->tcp_ts_recent = 0;
7458 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7459 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7460 	tcp->tcp_if_mtu = 0;
7461 
7462 	ASSERT(tcp->tcp_reass_head == NULL);
7463 	ASSERT(tcp->tcp_reass_tail == NULL);
7464 
7465 	tcp->tcp_cwnd_cnt = 0;
7466 
7467 	ASSERT(tcp->tcp_rcv_list == NULL);
7468 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7469 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7470 	ASSERT(tcp->tcp_rcv_cnt == 0);
7471 
7472 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7473 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7474 	tcp->tcp_csuna = 0;
7475 
7476 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7477 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7478 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7479 	tcp->tcp_rtt_update = 0;
7480 
7481 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7482 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7483 
7484 	tcp->tcp_rack = 0;			/* Displayed in mib */
7485 	tcp->tcp_rack_cnt = 0;
7486 	tcp->tcp_rack_cur_max = 0;
7487 	tcp->tcp_rack_abs_max = 0;
7488 
7489 	tcp->tcp_max_swnd = 0;
7490 
7491 	ASSERT(tcp->tcp_listener == NULL);
7492 
7493 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7494 
7495 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7496 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7497 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7498 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7499 
7500 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7501 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7502 	PRESERVE(tcp->tcp_conn_req_max);
7503 	PRESERVE(tcp->tcp_conn_req_seqnum);
7504 
7505 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7506 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7507 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7508 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7509 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7510 
7511 	tcp->tcp_lingertime = 0;
7512 
7513 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7514 	ASSERT(tcp->tcp_urp_mp == NULL);
7515 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7516 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7517 
7518 	ASSERT(tcp->tcp_eager_next_q == NULL);
7519 	ASSERT(tcp->tcp_eager_last_q == NULL);
7520 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7521 	    tcp->tcp_eager_prev_q0 == NULL) ||
7522 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7523 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7524 
7525 	tcp->tcp_client_errno = 0;
7526 
7527 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7528 
7529 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7530 
7531 	PRESERVE(tcp->tcp_bound_source_v6);
7532 	tcp->tcp_last_sent_len = 0;
7533 	tcp->tcp_dupack_cnt = 0;
7534 
7535 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7536 	PRESERVE(tcp->tcp_lport);
7537 
7538 	PRESERVE(tcp->tcp_acceptor_lockp);
7539 
7540 	ASSERT(tcp->tcp_ordrelid == 0);
7541 	PRESERVE(tcp->tcp_acceptor_id);
7542 	DONTCARE(tcp->tcp_ipsec_overhead);
7543 
7544 	/*
7545 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7546 	 * in tcp structure and now tracing), Re-initialize all
7547 	 * members of tcp_traceinfo.
7548 	 */
7549 	if (tcp->tcp_tracebuf != NULL) {
7550 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7551 	}
7552 
7553 	PRESERVE(tcp->tcp_family);
7554 	if (tcp->tcp_family == AF_INET6) {
7555 		tcp->tcp_ipversion = IPV6_VERSION;
7556 		tcp->tcp_mss = tcp_mss_def_ipv6;
7557 	} else {
7558 		tcp->tcp_ipversion = IPV4_VERSION;
7559 		tcp->tcp_mss = tcp_mss_def_ipv4;
7560 	}
7561 
7562 	tcp->tcp_bound_if = 0;
7563 	tcp->tcp_ipv6_recvancillary = 0;
7564 	tcp->tcp_recvifindex = 0;
7565 	tcp->tcp_recvhops = 0;
7566 	tcp->tcp_closed = 0;
7567 	tcp->tcp_cleandeathtag = 0;
7568 	if (tcp->tcp_hopopts != NULL) {
7569 		mi_free(tcp->tcp_hopopts);
7570 		tcp->tcp_hopopts = NULL;
7571 		tcp->tcp_hopoptslen = 0;
7572 	}
7573 	ASSERT(tcp->tcp_hopoptslen == 0);
7574 	if (tcp->tcp_dstopts != NULL) {
7575 		mi_free(tcp->tcp_dstopts);
7576 		tcp->tcp_dstopts = NULL;
7577 		tcp->tcp_dstoptslen = 0;
7578 	}
7579 	ASSERT(tcp->tcp_dstoptslen == 0);
7580 	if (tcp->tcp_rtdstopts != NULL) {
7581 		mi_free(tcp->tcp_rtdstopts);
7582 		tcp->tcp_rtdstopts = NULL;
7583 		tcp->tcp_rtdstoptslen = 0;
7584 	}
7585 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7586 	if (tcp->tcp_rthdr != NULL) {
7587 		mi_free(tcp->tcp_rthdr);
7588 		tcp->tcp_rthdr = NULL;
7589 		tcp->tcp_rthdrlen = 0;
7590 	}
7591 	ASSERT(tcp->tcp_rthdrlen == 0);
7592 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7593 
7594 	/* Reset fusion-related fields */
7595 	tcp->tcp_fused = B_FALSE;
7596 	tcp->tcp_unfusable = B_FALSE;
7597 	tcp->tcp_fused_sigurg = B_FALSE;
7598 	tcp->tcp_direct_sockfs = B_FALSE;
7599 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7600 	tcp->tcp_loopback_peer = NULL;
7601 	tcp->tcp_fuse_rcv_hiwater = 0;
7602 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7603 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7604 
7605 	tcp->tcp_in_ack_unsent = 0;
7606 	tcp->tcp_cork = B_FALSE;
7607 
7608 	PRESERVE(tcp->tcp_squeue_bytes);
7609 
7610 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7611 	ASSERT(!tcp->tcp_kssl_pending);
7612 	PRESERVE(tcp->tcp_kssl_ent);
7613 
7614 #undef	DONTCARE
7615 #undef	PRESERVE
7616 }
7617 
7618 /*
7619  * Allocate necessary resources and initialize state vector.
7620  * Guaranteed not to fail so that when an error is returned,
7621  * the caller doesn't need to do any additional cleanup.
7622  */
7623 int
7624 tcp_init(tcp_t *tcp, queue_t *q)
7625 {
7626 	int	err;
7627 
7628 	tcp->tcp_rq = q;
7629 	tcp->tcp_wq = WR(q);
7630 	tcp->tcp_state = TCPS_IDLE;
7631 	if ((err = tcp_init_values(tcp)) != 0)
7632 		tcp_timers_stop(tcp);
7633 	return (err);
7634 }
7635 
7636 static int
7637 tcp_init_values(tcp_t *tcp)
7638 {
7639 	int	err;
7640 
7641 	ASSERT((tcp->tcp_family == AF_INET &&
7642 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7643 	    (tcp->tcp_family == AF_INET6 &&
7644 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7645 	    tcp->tcp_ipversion == IPV6_VERSION)));
7646 
7647 	/*
7648 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7649 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7650 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7651 	 * during first few transmissions of a connection as seen in slow
7652 	 * links.
7653 	 */
7654 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7655 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7656 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7657 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7658 	    tcp_conn_grace_period;
7659 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7660 		tcp->tcp_rto = tcp_rexmit_interval_min;
7661 	tcp->tcp_timer_backoff = 0;
7662 	tcp->tcp_ms_we_have_waited = 0;
7663 	tcp->tcp_last_recv_time = lbolt;
7664 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7665 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7666 
7667 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7668 
7669 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7670 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7671 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7672 	/*
7673 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7674 	 * passive open.
7675 	 */
7676 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7677 
7678 	tcp->tcp_naglim = tcp_naglim_def;
7679 
7680 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7681 
7682 	tcp->tcp_mdt_hdr_head = 0;
7683 	tcp->tcp_mdt_hdr_tail = 0;
7684 
7685 	/* Reset fusion-related fields */
7686 	tcp->tcp_fused = B_FALSE;
7687 	tcp->tcp_unfusable = B_FALSE;
7688 	tcp->tcp_fused_sigurg = B_FALSE;
7689 	tcp->tcp_direct_sockfs = B_FALSE;
7690 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7691 	tcp->tcp_loopback_peer = NULL;
7692 	tcp->tcp_fuse_rcv_hiwater = 0;
7693 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7694 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7695 
7696 	/* Initialize the header template */
7697 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7698 		err = tcp_header_init_ipv4(tcp);
7699 	} else {
7700 		err = tcp_header_init_ipv6(tcp);
7701 	}
7702 	if (err)
7703 		return (err);
7704 
7705 	/*
7706 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7707 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7708 	 */
7709 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7710 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7711 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7712 
7713 	tcp->tcp_cork = B_FALSE;
7714 	/*
7715 	 * Init the tcp_debug option.  This value determines whether TCP
7716 	 * calls strlog() to print out debug messages.  Doing this
7717 	 * initialization here means that this value is not inherited thru
7718 	 * tcp_reinit().
7719 	 */
7720 	tcp->tcp_debug = tcp_dbg;
7721 
7722 	tcp->tcp_ka_interval = tcp_keepalive_interval;
7723 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
7724 
7725 	return (0);
7726 }
7727 
7728 /*
7729  * Initialize the IPv4 header. Loses any record of any IP options.
7730  */
7731 static int
7732 tcp_header_init_ipv4(tcp_t *tcp)
7733 {
7734 	tcph_t		*tcph;
7735 	uint32_t	sum;
7736 
7737 	/*
7738 	 * This is a simple initialization. If there's
7739 	 * already a template, it should never be too small,
7740 	 * so reuse it.  Otherwise, allocate space for the new one.
7741 	 */
7742 	if (tcp->tcp_iphc == NULL) {
7743 		ASSERT(tcp->tcp_iphc_len == 0);
7744 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7745 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7746 		if (tcp->tcp_iphc == NULL) {
7747 			tcp->tcp_iphc_len = 0;
7748 			return (ENOMEM);
7749 		}
7750 	}
7751 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7752 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
7753 	tcp->tcp_ip6h = NULL;
7754 	tcp->tcp_ipversion = IPV4_VERSION;
7755 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
7756 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7757 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
7758 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
7759 	tcp->tcp_ipha->ipha_version_and_hdr_length
7760 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
7761 	tcp->tcp_ipha->ipha_ident = 0;
7762 
7763 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
7764 	tcp->tcp_tos = 0;
7765 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7766 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
7767 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
7768 
7769 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
7770 	tcp->tcp_tcph = tcph;
7771 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7772 	/*
7773 	 * IP wants our header length in the checksum field to
7774 	 * allow it to perform a single pseudo-header+checksum
7775 	 * calculation on behalf of TCP.
7776 	 * Include the adjustment for a source route once IP_OPTIONS is set.
7777 	 */
7778 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7779 	sum = (sum >> 16) + (sum & 0xFFFF);
7780 	U16_TO_ABE16(sum, tcph->th_sum);
7781 	return (0);
7782 }
7783 
7784 /*
7785  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
7786  */
7787 static int
7788 tcp_header_init_ipv6(tcp_t *tcp)
7789 {
7790 	tcph_t	*tcph;
7791 	uint32_t	sum;
7792 
7793 	/*
7794 	 * This is a simple initialization. If there's
7795 	 * already a template, it should never be too small,
7796 	 * so reuse it. Otherwise, allocate space for the new one.
7797 	 * Ensure that there is enough space to "downgrade" the tcp_t
7798 	 * to an IPv4 tcp_t. This requires having space for a full load
7799 	 * of IPv4 options, as well as a full load of TCP options
7800 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
7801 	 * than a v6 header and a TCP header with a full load of TCP options
7802 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
7803 	 * We want to avoid reallocation in the "downgraded" case when
7804 	 * processing outbound IPv4 options.
7805 	 */
7806 	if (tcp->tcp_iphc == NULL) {
7807 		ASSERT(tcp->tcp_iphc_len == 0);
7808 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7809 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7810 		if (tcp->tcp_iphc == NULL) {
7811 			tcp->tcp_iphc_len = 0;
7812 			return (ENOMEM);
7813 		}
7814 	}
7815 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7816 	tcp->tcp_ipversion = IPV6_VERSION;
7817 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
7818 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7819 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
7820 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
7821 	tcp->tcp_ipha = NULL;
7822 
7823 	/* Initialize the header template */
7824 
7825 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7826 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
7827 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
7828 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
7829 
7830 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
7831 	tcp->tcp_tcph = tcph;
7832 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7833 	/*
7834 	 * IP wants our header length in the checksum field to
7835 	 * allow it to perform a single psuedo-header+checksum
7836 	 * calculation on behalf of TCP.
7837 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
7838 	 */
7839 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7840 	sum = (sum >> 16) + (sum & 0xFFFF);
7841 	U16_TO_ABE16(sum, tcph->th_sum);
7842 	return (0);
7843 }
7844 
7845 /* At minimum we need 4 bytes in the TCP header for the lookup */
7846 #define	ICMP_MIN_TCP_HDR	4
7847 
7848 /*
7849  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
7850  * passed up by IP. The message is always received on the correct tcp_t.
7851  * Assumes that IP has pulled up everything up to and including the ICMP header.
7852  */
7853 void
7854 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
7855 {
7856 	icmph_t *icmph;
7857 	ipha_t	*ipha;
7858 	int	iph_hdr_length;
7859 	tcph_t	*tcph;
7860 	boolean_t ipsec_mctl = B_FALSE;
7861 	boolean_t secure;
7862 	mblk_t *first_mp = mp;
7863 	uint32_t new_mss;
7864 	uint32_t ratio;
7865 	size_t mp_size = MBLKL(mp);
7866 	uint32_t seg_ack;
7867 	uint32_t seg_seq;
7868 
7869 	/* Assume IP provides aligned packets - otherwise toss */
7870 	if (!OK_32PTR(mp->b_rptr)) {
7871 		freemsg(mp);
7872 		return;
7873 	}
7874 
7875 	/*
7876 	 * Since ICMP errors are normal data marked with M_CTL when sent
7877 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
7878 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
7879 	 */
7880 	if ((mp_size == sizeof (ipsec_info_t)) &&
7881 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
7882 		ASSERT(mp->b_cont != NULL);
7883 		mp = mp->b_cont;
7884 		/* IP should have done this */
7885 		ASSERT(OK_32PTR(mp->b_rptr));
7886 		mp_size = MBLKL(mp);
7887 		ipsec_mctl = B_TRUE;
7888 	}
7889 
7890 	/*
7891 	 * Verify that we have a complete outer IP header. If not, drop it.
7892 	 */
7893 	if (mp_size < sizeof (ipha_t)) {
7894 noticmpv4:
7895 		freemsg(first_mp);
7896 		return;
7897 	}
7898 
7899 	ipha = (ipha_t *)mp->b_rptr;
7900 	/*
7901 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
7902 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
7903 	 */
7904 	switch (IPH_HDR_VERSION(ipha)) {
7905 	case IPV6_VERSION:
7906 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
7907 		return;
7908 	case IPV4_VERSION:
7909 		break;
7910 	default:
7911 		goto noticmpv4;
7912 	}
7913 
7914 	/* Skip past the outer IP and ICMP headers */
7915 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7916 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7917 	/*
7918 	 * If we don't have the correct outer IP header length or if the ULP
7919 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
7920 	 * send it upstream.
7921 	 */
7922 	if (iph_hdr_length < sizeof (ipha_t) ||
7923 	    ipha->ipha_protocol != IPPROTO_ICMP ||
7924 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7925 		goto noticmpv4;
7926 	}
7927 	ipha = (ipha_t *)&icmph[1];
7928 
7929 	/* Skip past the inner IP and find the ULP header */
7930 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7931 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
7932 	/*
7933 	 * If we don't have the correct inner IP header length or if the ULP
7934 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7935 	 * bytes of TCP header, drop it.
7936 	 */
7937 	if (iph_hdr_length < sizeof (ipha_t) ||
7938 	    ipha->ipha_protocol != IPPROTO_TCP ||
7939 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7940 		goto noticmpv4;
7941 	}
7942 
7943 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
7944 		if (ipsec_mctl) {
7945 			secure = ipsec_in_is_secure(first_mp);
7946 		} else {
7947 			secure = B_FALSE;
7948 		}
7949 		if (secure) {
7950 			/*
7951 			 * If we are willing to accept this in clear
7952 			 * we don't have to verify policy.
7953 			 */
7954 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
7955 				if (!tcp_check_policy(tcp, first_mp,
7956 				    ipha, NULL, secure, ipsec_mctl)) {
7957 					/*
7958 					 * tcp_check_policy called
7959 					 * ip_drop_packet() on failure.
7960 					 */
7961 					return;
7962 				}
7963 			}
7964 		}
7965 	} else if (ipsec_mctl) {
7966 		/*
7967 		 * This is a hard_bound connection. IP has already
7968 		 * verified policy. We don't have to do it again.
7969 		 */
7970 		freeb(first_mp);
7971 		first_mp = mp;
7972 		ipsec_mctl = B_FALSE;
7973 	}
7974 
7975 	seg_ack = ABE32_TO_U32(tcph->th_ack);
7976 	seg_seq = ABE32_TO_U32(tcph->th_seq);
7977 	/*
7978 	 * TCP SHOULD check that the TCP sequence number contained in
7979 	 * payload of the ICMP error message is within the range
7980 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
7981 	 */
7982 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
7983 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
7984 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
7985 		/*
7986 		 * If the ICMP message is bogus, should we kill the
7987 		 * connection, or should we just drop the bogus ICMP
7988 		 * message? It would probably make more sense to just
7989 		 * drop the message so that if this one managed to get
7990 		 * in, the real connection should not suffer.
7991 		 */
7992 		goto noticmpv4;
7993 	}
7994 
7995 	switch (icmph->icmph_type) {
7996 	case ICMP_DEST_UNREACHABLE:
7997 		switch (icmph->icmph_code) {
7998 		case ICMP_FRAGMENTATION_NEEDED:
7999 			/*
8000 			 * Reduce the MSS based on the new MTU.  This will
8001 			 * eliminate any fragmentation locally.
8002 			 * N.B.  There may well be some funny side-effects on
8003 			 * the local send policy and the remote receive policy.
8004 			 * Pending further research, we provide
8005 			 * tcp_ignore_path_mtu just in case this proves
8006 			 * disastrous somewhere.
8007 			 *
8008 			 * After updating the MSS, retransmit part of the
8009 			 * dropped segment using the new mss by calling
8010 			 * tcp_wput_data().  Need to adjust all those
8011 			 * params to make sure tcp_wput_data() work properly.
8012 			 */
8013 			if (tcp_ignore_path_mtu)
8014 				break;
8015 
8016 			/*
8017 			 * Decrease the MSS by time stamp options
8018 			 * IP options and IPSEC options. tcp_hdr_len
8019 			 * includes time stamp option and IP option
8020 			 * length.
8021 			 */
8022 
8023 			new_mss = ntohs(icmph->icmph_du_mtu) -
8024 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8025 
8026 			/*
8027 			 * Only update the MSS if the new one is
8028 			 * smaller than the previous one.  This is
8029 			 * to avoid problems when getting multiple
8030 			 * ICMP errors for the same MTU.
8031 			 */
8032 			if (new_mss >= tcp->tcp_mss)
8033 				break;
8034 
8035 			/*
8036 			 * Stop doing PMTU if new_mss is less than 68
8037 			 * or less than tcp_mss_min.
8038 			 * The value 68 comes from rfc 1191.
8039 			 */
8040 			if (new_mss < MAX(68, tcp_mss_min))
8041 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8042 				    0;
8043 
8044 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8045 			ASSERT(ratio >= 1);
8046 			tcp_mss_set(tcp, new_mss);
8047 
8048 			/*
8049 			 * Make sure we have something to
8050 			 * send.
8051 			 */
8052 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8053 			    (tcp->tcp_xmit_head != NULL)) {
8054 				/*
8055 				 * Shrink tcp_cwnd in
8056 				 * proportion to the old MSS/new MSS.
8057 				 */
8058 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8059 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8060 				    (tcp->tcp_unsent == 0)) {
8061 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8062 				} else {
8063 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8064 				}
8065 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8066 				tcp->tcp_rexmit = B_TRUE;
8067 				tcp->tcp_dupack_cnt = 0;
8068 				tcp->tcp_snd_burst = TCP_CWND_SS;
8069 				tcp_ss_rexmit(tcp);
8070 			}
8071 			break;
8072 		case ICMP_PORT_UNREACHABLE:
8073 		case ICMP_PROTOCOL_UNREACHABLE:
8074 			switch (tcp->tcp_state) {
8075 			case TCPS_SYN_SENT:
8076 			case TCPS_SYN_RCVD:
8077 				/*
8078 				 * ICMP can snipe away incipient
8079 				 * TCP connections as long as
8080 				 * seq number is same as initial
8081 				 * send seq number.
8082 				 */
8083 				if (seg_seq == tcp->tcp_iss) {
8084 					(void) tcp_clean_death(tcp,
8085 					    ECONNREFUSED, 6);
8086 				}
8087 				break;
8088 			}
8089 			break;
8090 		case ICMP_HOST_UNREACHABLE:
8091 		case ICMP_NET_UNREACHABLE:
8092 			/* Record the error in case we finally time out. */
8093 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8094 				tcp->tcp_client_errno = EHOSTUNREACH;
8095 			else
8096 				tcp->tcp_client_errno = ENETUNREACH;
8097 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8098 				if (tcp->tcp_listener != NULL &&
8099 				    tcp->tcp_listener->tcp_syn_defense) {
8100 					/*
8101 					 * Ditch the half-open connection if we
8102 					 * suspect a SYN attack is under way.
8103 					 */
8104 					tcp_ip_ire_mark_advice(tcp);
8105 					(void) tcp_clean_death(tcp,
8106 					    tcp->tcp_client_errno, 7);
8107 				}
8108 			}
8109 			break;
8110 		default:
8111 			break;
8112 		}
8113 		break;
8114 	case ICMP_SOURCE_QUENCH: {
8115 		/*
8116 		 * use a global boolean to control
8117 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8118 		 * The default is false.
8119 		 */
8120 		if (tcp_icmp_source_quench) {
8121 			/*
8122 			 * Reduce the sending rate as if we got a
8123 			 * retransmit timeout
8124 			 */
8125 			uint32_t npkt;
8126 
8127 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8128 			    tcp->tcp_mss;
8129 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8130 			tcp->tcp_cwnd = tcp->tcp_mss;
8131 			tcp->tcp_cwnd_cnt = 0;
8132 		}
8133 		break;
8134 	}
8135 	}
8136 	freemsg(first_mp);
8137 }
8138 
8139 /*
8140  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8141  * error messages passed up by IP.
8142  * Assumes that IP has pulled up all the extension headers as well
8143  * as the ICMPv6 header.
8144  */
8145 static void
8146 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8147 {
8148 	icmp6_t *icmp6;
8149 	ip6_t	*ip6h;
8150 	uint16_t	iph_hdr_length;
8151 	tcpha_t	*tcpha;
8152 	uint8_t	*nexthdrp;
8153 	uint32_t new_mss;
8154 	uint32_t ratio;
8155 	boolean_t secure;
8156 	mblk_t *first_mp = mp;
8157 	size_t mp_size;
8158 	uint32_t seg_ack;
8159 	uint32_t seg_seq;
8160 
8161 	/*
8162 	 * The caller has determined if this is an IPSEC_IN packet and
8163 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8164 	 */
8165 	if (ipsec_mctl)
8166 		mp = mp->b_cont;
8167 
8168 	mp_size = MBLKL(mp);
8169 
8170 	/*
8171 	 * Verify that we have a complete IP header. If not, send it upstream.
8172 	 */
8173 	if (mp_size < sizeof (ip6_t)) {
8174 noticmpv6:
8175 		freemsg(first_mp);
8176 		return;
8177 	}
8178 
8179 	/*
8180 	 * Verify this is an ICMPV6 packet, else send it upstream.
8181 	 */
8182 	ip6h = (ip6_t *)mp->b_rptr;
8183 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8184 		iph_hdr_length = IPV6_HDR_LEN;
8185 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8186 	    &nexthdrp) ||
8187 	    *nexthdrp != IPPROTO_ICMPV6) {
8188 		goto noticmpv6;
8189 	}
8190 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8191 	ip6h = (ip6_t *)&icmp6[1];
8192 	/*
8193 	 * Verify if we have a complete ICMP and inner IP header.
8194 	 */
8195 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8196 		goto noticmpv6;
8197 
8198 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8199 		goto noticmpv6;
8200 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8201 	/*
8202 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8203 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8204 	 * packet.
8205 	 */
8206 	if ((*nexthdrp != IPPROTO_TCP) ||
8207 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8208 		goto noticmpv6;
8209 	}
8210 
8211 	/*
8212 	 * ICMP errors come on the right queue or come on
8213 	 * listener/global queue for detached connections and
8214 	 * get switched to the right queue. If it comes on the
8215 	 * right queue, policy check has already been done by IP
8216 	 * and thus free the first_mp without verifying the policy.
8217 	 * If it has come for a non-hard bound connection, we need
8218 	 * to verify policy as IP may not have done it.
8219 	 */
8220 	if (!tcp->tcp_hard_bound) {
8221 		if (ipsec_mctl) {
8222 			secure = ipsec_in_is_secure(first_mp);
8223 		} else {
8224 			secure = B_FALSE;
8225 		}
8226 		if (secure) {
8227 			/*
8228 			 * If we are willing to accept this in clear
8229 			 * we don't have to verify policy.
8230 			 */
8231 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8232 				if (!tcp_check_policy(tcp, first_mp,
8233 				    NULL, ip6h, secure, ipsec_mctl)) {
8234 					/*
8235 					 * tcp_check_policy called
8236 					 * ip_drop_packet() on failure.
8237 					 */
8238 					return;
8239 				}
8240 			}
8241 		}
8242 	} else if (ipsec_mctl) {
8243 		/*
8244 		 * This is a hard_bound connection. IP has already
8245 		 * verified policy. We don't have to do it again.
8246 		 */
8247 		freeb(first_mp);
8248 		first_mp = mp;
8249 		ipsec_mctl = B_FALSE;
8250 	}
8251 
8252 	seg_ack = ntohl(tcpha->tha_ack);
8253 	seg_seq = ntohl(tcpha->tha_seq);
8254 	/*
8255 	 * TCP SHOULD check that the TCP sequence number contained in
8256 	 * payload of the ICMP error message is within the range
8257 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8258 	 */
8259 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8260 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8261 		/*
8262 		 * If the ICMP message is bogus, should we kill the
8263 		 * connection, or should we just drop the bogus ICMP
8264 		 * message? It would probably make more sense to just
8265 		 * drop the message so that if this one managed to get
8266 		 * in, the real connection should not suffer.
8267 		 */
8268 		goto noticmpv6;
8269 	}
8270 
8271 	switch (icmp6->icmp6_type) {
8272 	case ICMP6_PACKET_TOO_BIG:
8273 		/*
8274 		 * Reduce the MSS based on the new MTU.  This will
8275 		 * eliminate any fragmentation locally.
8276 		 * N.B.  There may well be some funny side-effects on
8277 		 * the local send policy and the remote receive policy.
8278 		 * Pending further research, we provide
8279 		 * tcp_ignore_path_mtu just in case this proves
8280 		 * disastrous somewhere.
8281 		 *
8282 		 * After updating the MSS, retransmit part of the
8283 		 * dropped segment using the new mss by calling
8284 		 * tcp_wput_data().  Need to adjust all those
8285 		 * params to make sure tcp_wput_data() work properly.
8286 		 */
8287 		if (tcp_ignore_path_mtu)
8288 			break;
8289 
8290 		/*
8291 		 * Decrease the MSS by time stamp options
8292 		 * IP options and IPSEC options. tcp_hdr_len
8293 		 * includes time stamp option and IP option
8294 		 * length.
8295 		 */
8296 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8297 			    tcp->tcp_ipsec_overhead;
8298 
8299 		/*
8300 		 * Only update the MSS if the new one is
8301 		 * smaller than the previous one.  This is
8302 		 * to avoid problems when getting multiple
8303 		 * ICMP errors for the same MTU.
8304 		 */
8305 		if (new_mss >= tcp->tcp_mss)
8306 			break;
8307 
8308 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8309 		ASSERT(ratio >= 1);
8310 		tcp_mss_set(tcp, new_mss);
8311 
8312 		/*
8313 		 * Make sure we have something to
8314 		 * send.
8315 		 */
8316 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8317 		    (tcp->tcp_xmit_head != NULL)) {
8318 			/*
8319 			 * Shrink tcp_cwnd in
8320 			 * proportion to the old MSS/new MSS.
8321 			 */
8322 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8323 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8324 			    (tcp->tcp_unsent == 0)) {
8325 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8326 			} else {
8327 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8328 			}
8329 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8330 			tcp->tcp_rexmit = B_TRUE;
8331 			tcp->tcp_dupack_cnt = 0;
8332 			tcp->tcp_snd_burst = TCP_CWND_SS;
8333 			tcp_ss_rexmit(tcp);
8334 		}
8335 		break;
8336 
8337 	case ICMP6_DST_UNREACH:
8338 		switch (icmp6->icmp6_code) {
8339 		case ICMP6_DST_UNREACH_NOPORT:
8340 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8341 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8342 			    (seg_seq == tcp->tcp_iss)) {
8343 				(void) tcp_clean_death(tcp,
8344 				    ECONNREFUSED, 8);
8345 			}
8346 			break;
8347 
8348 		case ICMP6_DST_UNREACH_ADMIN:
8349 		case ICMP6_DST_UNREACH_NOROUTE:
8350 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8351 		case ICMP6_DST_UNREACH_ADDR:
8352 			/* Record the error in case we finally time out. */
8353 			tcp->tcp_client_errno = EHOSTUNREACH;
8354 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8355 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8356 			    (seg_seq == tcp->tcp_iss)) {
8357 				if (tcp->tcp_listener != NULL &&
8358 				    tcp->tcp_listener->tcp_syn_defense) {
8359 					/*
8360 					 * Ditch the half-open connection if we
8361 					 * suspect a SYN attack is under way.
8362 					 */
8363 					tcp_ip_ire_mark_advice(tcp);
8364 					(void) tcp_clean_death(tcp,
8365 					    tcp->tcp_client_errno, 9);
8366 				}
8367 			}
8368 
8369 
8370 			break;
8371 		default:
8372 			break;
8373 		}
8374 		break;
8375 
8376 	case ICMP6_PARAM_PROB:
8377 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8378 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8379 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8380 		    (uchar_t *)nexthdrp) {
8381 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8382 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8383 				(void) tcp_clean_death(tcp,
8384 				    ECONNREFUSED, 10);
8385 			}
8386 			break;
8387 		}
8388 		break;
8389 
8390 	case ICMP6_TIME_EXCEEDED:
8391 	default:
8392 		break;
8393 	}
8394 	freemsg(first_mp);
8395 }
8396 
8397 /*
8398  * IP recognizes seven kinds of bind requests:
8399  *
8400  * - A zero-length address binds only to the protocol number.
8401  *
8402  * - A 4-byte address is treated as a request to
8403  * validate that the address is a valid local IPv4
8404  * address, appropriate for an application to bind to.
8405  * IP does the verification, but does not make any note
8406  * of the address at this time.
8407  *
8408  * - A 16-byte address contains is treated as a request
8409  * to validate a local IPv6 address, as the 4-byte
8410  * address case above.
8411  *
8412  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8413  * use it for the inbound fanout of packets.
8414  *
8415  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8416  * use it for the inbound fanout of packets.
8417  *
8418  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8419  * information consisting of local and remote addresses
8420  * and ports.  In this case, the addresses are both
8421  * validated as appropriate for this operation, and, if
8422  * so, the information is retained for use in the
8423  * inbound fanout.
8424  *
8425  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8426  * fanout information, like the 12-byte case above.
8427  *
8428  * IP will also fill in the IRE request mblk with information
8429  * regarding our peer.  In all cases, we notify IP of our protocol
8430  * type by appending a single protocol byte to the bind request.
8431  */
8432 static mblk_t *
8433 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8434 {
8435 	char	*cp;
8436 	mblk_t	*mp;
8437 	struct T_bind_req *tbr;
8438 	ipa_conn_t	*ac;
8439 	ipa6_conn_t	*ac6;
8440 	sin_t		*sin;
8441 	sin6_t		*sin6;
8442 
8443 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8444 	ASSERT((tcp->tcp_family == AF_INET &&
8445 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8446 	    (tcp->tcp_family == AF_INET6 &&
8447 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8448 	    tcp->tcp_ipversion == IPV6_VERSION)));
8449 
8450 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8451 	if (!mp)
8452 		return (mp);
8453 	mp->b_datap->db_type = M_PROTO;
8454 	tbr = (struct T_bind_req *)mp->b_rptr;
8455 	tbr->PRIM_type = bind_prim;
8456 	tbr->ADDR_offset = sizeof (*tbr);
8457 	tbr->CONIND_number = 0;
8458 	tbr->ADDR_length = addr_length;
8459 	cp = (char *)&tbr[1];
8460 	switch (addr_length) {
8461 	case sizeof (ipa_conn_t):
8462 		ASSERT(tcp->tcp_family == AF_INET);
8463 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8464 
8465 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8466 		if (mp->b_cont == NULL) {
8467 			freemsg(mp);
8468 			return (NULL);
8469 		}
8470 		mp->b_cont->b_wptr += sizeof (ire_t);
8471 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8472 
8473 		/* cp known to be 32 bit aligned */
8474 		ac = (ipa_conn_t *)cp;
8475 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8476 		ac->ac_faddr = tcp->tcp_remote;
8477 		ac->ac_fport = tcp->tcp_fport;
8478 		ac->ac_lport = tcp->tcp_lport;
8479 		tcp->tcp_hard_binding = 1;
8480 		break;
8481 
8482 	case sizeof (ipa6_conn_t):
8483 		ASSERT(tcp->tcp_family == AF_INET6);
8484 
8485 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8486 		if (mp->b_cont == NULL) {
8487 			freemsg(mp);
8488 			return (NULL);
8489 		}
8490 		mp->b_cont->b_wptr += sizeof (ire_t);
8491 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8492 
8493 		/* cp known to be 32 bit aligned */
8494 		ac6 = (ipa6_conn_t *)cp;
8495 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8496 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8497 			    &ac6->ac6_laddr);
8498 		} else {
8499 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8500 		}
8501 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8502 		ac6->ac6_fport = tcp->tcp_fport;
8503 		ac6->ac6_lport = tcp->tcp_lport;
8504 		tcp->tcp_hard_binding = 1;
8505 		break;
8506 
8507 	case sizeof (sin_t):
8508 		/*
8509 		 * NOTE: IPV6_ADDR_LEN also has same size.
8510 		 * Use family to discriminate.
8511 		 */
8512 		if (tcp->tcp_family == AF_INET) {
8513 			sin = (sin_t *)cp;
8514 
8515 			*sin = sin_null;
8516 			sin->sin_family = AF_INET;
8517 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8518 			sin->sin_port = tcp->tcp_lport;
8519 			break;
8520 		} else {
8521 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8522 		}
8523 		break;
8524 
8525 	case sizeof (sin6_t):
8526 		ASSERT(tcp->tcp_family == AF_INET6);
8527 		sin6 = (sin6_t *)cp;
8528 
8529 		*sin6 = sin6_null;
8530 		sin6->sin6_family = AF_INET6;
8531 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8532 		sin6->sin6_port = tcp->tcp_lport;
8533 		break;
8534 
8535 	case IP_ADDR_LEN:
8536 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8537 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8538 		break;
8539 
8540 	}
8541 	/* Add protocol number to end */
8542 	cp[addr_length] = (char)IPPROTO_TCP;
8543 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8544 	return (mp);
8545 }
8546 
8547 /*
8548  * Notify IP that we are having trouble with this connection.  IP should
8549  * blow the IRE away and start over.
8550  */
8551 static void
8552 tcp_ip_notify(tcp_t *tcp)
8553 {
8554 	struct iocblk	*iocp;
8555 	ipid_t	*ipid;
8556 	mblk_t	*mp;
8557 
8558 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8559 	if (tcp->tcp_ipversion == IPV6_VERSION)
8560 		return;
8561 
8562 	mp = mkiocb(IP_IOCTL);
8563 	if (mp == NULL)
8564 		return;
8565 
8566 	iocp = (struct iocblk *)mp->b_rptr;
8567 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8568 
8569 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8570 	if (!mp->b_cont) {
8571 		freeb(mp);
8572 		return;
8573 	}
8574 
8575 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8576 	mp->b_cont->b_wptr += iocp->ioc_count;
8577 	bzero(ipid, sizeof (*ipid));
8578 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8579 	ipid->ipid_ire_type = IRE_CACHE;
8580 	ipid->ipid_addr_offset = sizeof (ipid_t);
8581 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8582 	/*
8583 	 * Note: in the case of source routing we want to blow away the
8584 	 * route to the first source route hop.
8585 	 */
8586 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8587 	    sizeof (tcp->tcp_ipha->ipha_dst));
8588 
8589 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8590 }
8591 
8592 /* Unlink and return any mblk that looks like it contains an ire */
8593 static mblk_t *
8594 tcp_ire_mp(mblk_t *mp)
8595 {
8596 	mblk_t	*prev_mp;
8597 
8598 	for (;;) {
8599 		prev_mp = mp;
8600 		mp = mp->b_cont;
8601 		if (mp == NULL)
8602 			break;
8603 		switch (DB_TYPE(mp)) {
8604 		case IRE_DB_TYPE:
8605 		case IRE_DB_REQ_TYPE:
8606 			if (prev_mp != NULL)
8607 				prev_mp->b_cont = mp->b_cont;
8608 			mp->b_cont = NULL;
8609 			return (mp);
8610 		default:
8611 			break;
8612 		}
8613 	}
8614 	return (mp);
8615 }
8616 
8617 /*
8618  * Timer callback routine for keepalive probe.  We do a fake resend of
8619  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8620  * check to see if we have heard anything from the other end for the last
8621  * RTO period.  If we have, set the timer to expire for another
8622  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8623  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8624  * the timeout if we have not heard from the other side.  If for more than
8625  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8626  * kill the connection unless the keepalive abort threshold is 0.  In
8627  * that case, we will probe "forever."
8628  */
8629 static void
8630 tcp_keepalive_killer(void *arg)
8631 {
8632 	mblk_t	*mp;
8633 	conn_t	*connp = (conn_t *)arg;
8634 	tcp_t  	*tcp = connp->conn_tcp;
8635 	int32_t	firetime;
8636 	int32_t	idletime;
8637 	int32_t	ka_intrvl;
8638 
8639 	tcp->tcp_ka_tid = 0;
8640 
8641 	if (tcp->tcp_fused)
8642 		return;
8643 
8644 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8645 	ka_intrvl = tcp->tcp_ka_interval;
8646 
8647 	/*
8648 	 * Keepalive probe should only be sent if the application has not
8649 	 * done a close on the connection.
8650 	 */
8651 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8652 		return;
8653 	}
8654 	/* Timer fired too early, restart it. */
8655 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8656 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8657 		    MSEC_TO_TICK(ka_intrvl));
8658 		return;
8659 	}
8660 
8661 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8662 	/*
8663 	 * If we have not heard from the other side for a long
8664 	 * time, kill the connection unless the keepalive abort
8665 	 * threshold is 0.  In that case, we will probe "forever."
8666 	 */
8667 	if (tcp->tcp_ka_abort_thres != 0 &&
8668 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8669 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8670 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8671 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8672 		return;
8673 	}
8674 
8675 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8676 	    idletime >= ka_intrvl) {
8677 		/* Fake resend of last ACKed byte. */
8678 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8679 
8680 		if (mp1 != NULL) {
8681 			*mp1->b_wptr++ = '\0';
8682 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8683 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8684 			freeb(mp1);
8685 			/*
8686 			 * if allocation failed, fall through to start the
8687 			 * timer back.
8688 			 */
8689 			if (mp != NULL) {
8690 				TCP_RECORD_TRACE(tcp, mp,
8691 				    TCP_TRACE_SEND_PKT);
8692 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8693 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8694 				if (tcp->tcp_ka_last_intrvl != 0) {
8695 					/*
8696 					 * We should probe again at least
8697 					 * in ka_intrvl, but not more than
8698 					 * tcp_rexmit_interval_max.
8699 					 */
8700 					firetime = MIN(ka_intrvl - 1,
8701 					    tcp->tcp_ka_last_intrvl << 1);
8702 					if (firetime > tcp_rexmit_interval_max)
8703 						firetime =
8704 						    tcp_rexmit_interval_max;
8705 				} else {
8706 					firetime = tcp->tcp_rto;
8707 				}
8708 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8709 				    tcp_keepalive_killer,
8710 				    MSEC_TO_TICK(firetime));
8711 				tcp->tcp_ka_last_intrvl = firetime;
8712 				return;
8713 			}
8714 		}
8715 	} else {
8716 		tcp->tcp_ka_last_intrvl = 0;
8717 	}
8718 
8719 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8720 	if ((firetime = ka_intrvl - idletime) < 0) {
8721 		firetime = ka_intrvl;
8722 	}
8723 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8724 	    MSEC_TO_TICK(firetime));
8725 }
8726 
8727 int
8728 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8729 {
8730 	queue_t	*q = tcp->tcp_rq;
8731 	int32_t	mss = tcp->tcp_mss;
8732 	int	maxpsz;
8733 
8734 	if (TCP_IS_DETACHED(tcp))
8735 		return (mss);
8736 
8737 	if (tcp->tcp_fused) {
8738 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8739 		mss = INFPSZ;
8740 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
8741 		/*
8742 		 * Set the sd_qn_maxpsz according to the socket send buffer
8743 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8744 		 * instruct the stream head to copyin user data into contiguous
8745 		 * kernel-allocated buffers without breaking it up into smaller
8746 		 * chunks.  We round up the buffer size to the nearest SMSS.
8747 		 */
8748 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8749 		if (tcp->tcp_kssl_ctx == NULL)
8750 			mss = INFPSZ;
8751 		else
8752 			mss = SSL3_MAX_RECORD_LEN;
8753 	} else {
8754 		/*
8755 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8756 		 * (and a multiple of the mss).  This instructs the stream
8757 		 * head to break down larger than SMSS writes into SMSS-
8758 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8759 		 */
8760 		maxpsz = tcp->tcp_maxpsz * mss;
8761 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8762 			maxpsz = tcp->tcp_xmit_hiwater/2;
8763 			/* Round up to nearest mss */
8764 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8765 		}
8766 	}
8767 	(void) setmaxps(q, maxpsz);
8768 	tcp->tcp_wq->q_maxpsz = maxpsz;
8769 
8770 	if (set_maxblk)
8771 		(void) mi_set_sth_maxblk(q, mss);
8772 
8773 	return (mss);
8774 }
8775 
8776 /*
8777  * Extract option values from a tcp header.  We put any found values into the
8778  * tcpopt struct and return a bitmask saying which options were found.
8779  */
8780 static int
8781 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8782 {
8783 	uchar_t		*endp;
8784 	int		len;
8785 	uint32_t	mss;
8786 	uchar_t		*up = (uchar_t *)tcph;
8787 	int		found = 0;
8788 	int32_t		sack_len;
8789 	tcp_seq		sack_begin, sack_end;
8790 	tcp_t		*tcp;
8791 
8792 	endp = up + TCP_HDR_LENGTH(tcph);
8793 	up += TCP_MIN_HEADER_LENGTH;
8794 	while (up < endp) {
8795 		len = endp - up;
8796 		switch (*up) {
8797 		case TCPOPT_EOL:
8798 			break;
8799 
8800 		case TCPOPT_NOP:
8801 			up++;
8802 			continue;
8803 
8804 		case TCPOPT_MAXSEG:
8805 			if (len < TCPOPT_MAXSEG_LEN ||
8806 			    up[1] != TCPOPT_MAXSEG_LEN)
8807 				break;
8808 
8809 			mss = BE16_TO_U16(up+2);
8810 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8811 			tcpopt->tcp_opt_mss = mss;
8812 			found |= TCP_OPT_MSS_PRESENT;
8813 
8814 			up += TCPOPT_MAXSEG_LEN;
8815 			continue;
8816 
8817 		case TCPOPT_WSCALE:
8818 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8819 				break;
8820 
8821 			if (up[2] > TCP_MAX_WINSHIFT)
8822 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8823 			else
8824 				tcpopt->tcp_opt_wscale = up[2];
8825 			found |= TCP_OPT_WSCALE_PRESENT;
8826 
8827 			up += TCPOPT_WS_LEN;
8828 			continue;
8829 
8830 		case TCPOPT_SACK_PERMITTED:
8831 			if (len < TCPOPT_SACK_OK_LEN ||
8832 			    up[1] != TCPOPT_SACK_OK_LEN)
8833 				break;
8834 			found |= TCP_OPT_SACK_OK_PRESENT;
8835 			up += TCPOPT_SACK_OK_LEN;
8836 			continue;
8837 
8838 		case TCPOPT_SACK:
8839 			if (len <= 2 || up[1] <= 2 || len < up[1])
8840 				break;
8841 
8842 			/* If TCP is not interested in SACK blks... */
8843 			if ((tcp = tcpopt->tcp) == NULL) {
8844 				up += up[1];
8845 				continue;
8846 			}
8847 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8848 			up += TCPOPT_HEADER_LEN;
8849 
8850 			/*
8851 			 * If the list is empty, allocate one and assume
8852 			 * nothing is sack'ed.
8853 			 */
8854 			ASSERT(tcp->tcp_sack_info != NULL);
8855 			if (tcp->tcp_notsack_list == NULL) {
8856 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8857 				    tcp->tcp_suna, tcp->tcp_snxt,
8858 				    &(tcp->tcp_num_notsack_blk),
8859 				    &(tcp->tcp_cnt_notsack_list));
8860 
8861 				/*
8862 				 * Make sure tcp_notsack_list is not NULL.
8863 				 * This happens when kmem_alloc(KM_NOSLEEP)
8864 				 * returns NULL.
8865 				 */
8866 				if (tcp->tcp_notsack_list == NULL) {
8867 					up += sack_len;
8868 					continue;
8869 				}
8870 				tcp->tcp_fack = tcp->tcp_suna;
8871 			}
8872 
8873 			while (sack_len > 0) {
8874 				if (up + 8 > endp) {
8875 					up = endp;
8876 					break;
8877 				}
8878 				sack_begin = BE32_TO_U32(up);
8879 				up += 4;
8880 				sack_end = BE32_TO_U32(up);
8881 				up += 4;
8882 				sack_len -= 8;
8883 				/*
8884 				 * Bounds checking.  Make sure the SACK
8885 				 * info is within tcp_suna and tcp_snxt.
8886 				 * If this SACK blk is out of bound, ignore
8887 				 * it but continue to parse the following
8888 				 * blks.
8889 				 */
8890 				if (SEQ_LEQ(sack_end, sack_begin) ||
8891 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
8892 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
8893 					continue;
8894 				}
8895 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
8896 				    sack_begin, sack_end,
8897 				    &(tcp->tcp_num_notsack_blk),
8898 				    &(tcp->tcp_cnt_notsack_list));
8899 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
8900 					tcp->tcp_fack = sack_end;
8901 				}
8902 			}
8903 			found |= TCP_OPT_SACK_PRESENT;
8904 			continue;
8905 
8906 		case TCPOPT_TSTAMP:
8907 			if (len < TCPOPT_TSTAMP_LEN ||
8908 			    up[1] != TCPOPT_TSTAMP_LEN)
8909 				break;
8910 
8911 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
8912 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
8913 
8914 			found |= TCP_OPT_TSTAMP_PRESENT;
8915 
8916 			up += TCPOPT_TSTAMP_LEN;
8917 			continue;
8918 
8919 		default:
8920 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
8921 				break;
8922 			up += up[1];
8923 			continue;
8924 		}
8925 		break;
8926 	}
8927 	return (found);
8928 }
8929 
8930 /*
8931  * Set the mss associated with a particular tcp based on its current value,
8932  * and a new one passed in. Observe minimums and maximums, and reset
8933  * other state variables that we want to view as multiples of mss.
8934  *
8935  * This function is called in various places mainly because
8936  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
8937  *    other side's SYN/SYN-ACK packet arrives.
8938  * 2) PMTUd may get us a new MSS.
8939  * 3) If the other side stops sending us timestamp option, we need to
8940  *    increase the MSS size to use the extra bytes available.
8941  */
8942 static void
8943 tcp_mss_set(tcp_t *tcp, uint32_t mss)
8944 {
8945 	uint32_t	mss_max;
8946 
8947 	if (tcp->tcp_ipversion == IPV4_VERSION)
8948 		mss_max = tcp_mss_max_ipv4;
8949 	else
8950 		mss_max = tcp_mss_max_ipv6;
8951 
8952 	if (mss < tcp_mss_min)
8953 		mss = tcp_mss_min;
8954 	if (mss > mss_max)
8955 		mss = mss_max;
8956 	/*
8957 	 * Unless naglim has been set by our client to
8958 	 * a non-mss value, force naglim to track mss.
8959 	 * This can help to aggregate small writes.
8960 	 */
8961 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
8962 		tcp->tcp_naglim = mss;
8963 	/*
8964 	 * TCP should be able to buffer at least 4 MSS data for obvious
8965 	 * performance reason.
8966 	 */
8967 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
8968 		tcp->tcp_xmit_hiwater = mss << 2;
8969 
8970 	/*
8971 	 * Check if we need to apply the tcp_init_cwnd here.  If
8972 	 * it is set and the MSS gets bigger (should not happen
8973 	 * normally), we need to adjust the resulting tcp_cwnd properly.
8974 	 * The new tcp_cwnd should not get bigger.
8975 	 */
8976 	if (tcp->tcp_init_cwnd == 0) {
8977 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
8978 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
8979 	} else {
8980 		if (tcp->tcp_mss < mss) {
8981 			tcp->tcp_cwnd = MAX(1,
8982 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
8983 		} else {
8984 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
8985 		}
8986 	}
8987 	tcp->tcp_mss = mss;
8988 	tcp->tcp_cwnd_cnt = 0;
8989 	(void) tcp_maxpsz_set(tcp, B_TRUE);
8990 }
8991 
8992 static int
8993 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
8994 {
8995 	tcp_t		*tcp = NULL;
8996 	conn_t		*connp;
8997 	int		err;
8998 	dev_t		conn_dev;
8999 	zoneid_t	zoneid = getzoneid();
9000 
9001 	/*
9002 	 * Special case for install: miniroot needs to be able to access files
9003 	 * via NFS as though it were always in the global zone.
9004 	 */
9005 	if (credp == kcred && nfs_global_client_only != 0)
9006 		zoneid = GLOBAL_ZONEID;
9007 
9008 	if (q->q_ptr != NULL)
9009 		return (0);
9010 
9011 	if (sflag == MODOPEN) {
9012 		/*
9013 		 * This is a special case. The purpose of a modopen
9014 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9015 		 * through for MIB browsers. Everything else is failed.
9016 		 */
9017 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9018 
9019 		if (connp == NULL)
9020 			return (ENOMEM);
9021 
9022 		connp->conn_flags |= IPCL_TCPMOD;
9023 		connp->conn_cred = credp;
9024 		connp->conn_zoneid = zoneid;
9025 		q->q_ptr = WR(q)->q_ptr = connp;
9026 		crhold(credp);
9027 		q->q_qinfo = &tcp_mod_rinit;
9028 		WR(q)->q_qinfo = &tcp_mod_winit;
9029 		qprocson(q);
9030 		return (0);
9031 	}
9032 
9033 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9034 		return (EBUSY);
9035 
9036 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9037 
9038 	if (flag & SO_ACCEPTOR) {
9039 		q->q_qinfo = &tcp_acceptor_rinit;
9040 		q->q_ptr = (void *)conn_dev;
9041 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9042 		WR(q)->q_ptr = (void *)conn_dev;
9043 		qprocson(q);
9044 		return (0);
9045 	}
9046 
9047 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9048 	if (connp == NULL) {
9049 		inet_minor_free(ip_minor_arena, conn_dev);
9050 		q->q_ptr = NULL;
9051 		return (ENOSR);
9052 	}
9053 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9054 	tcp = connp->conn_tcp;
9055 
9056 	q->q_ptr = WR(q)->q_ptr = connp;
9057 	if (getmajor(*devp) == TCP6_MAJ) {
9058 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9059 		connp->conn_send = ip_output_v6;
9060 		connp->conn_af_isv6 = B_TRUE;
9061 		connp->conn_pkt_isv6 = B_TRUE;
9062 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9063 		tcp->tcp_ipversion = IPV6_VERSION;
9064 		tcp->tcp_family = AF_INET6;
9065 		tcp->tcp_mss = tcp_mss_def_ipv6;
9066 	} else {
9067 		connp->conn_flags |= IPCL_TCP4;
9068 		connp->conn_send = ip_output;
9069 		connp->conn_af_isv6 = B_FALSE;
9070 		connp->conn_pkt_isv6 = B_FALSE;
9071 		tcp->tcp_ipversion = IPV4_VERSION;
9072 		tcp->tcp_family = AF_INET;
9073 		tcp->tcp_mss = tcp_mss_def_ipv4;
9074 	}
9075 
9076 	/*
9077 	 * TCP keeps a copy of cred for cache locality reasons but
9078 	 * we put a reference only once. If connp->conn_cred
9079 	 * becomes invalid, tcp_cred should also be set to NULL.
9080 	 */
9081 	tcp->tcp_cred = connp->conn_cred = credp;
9082 	crhold(connp->conn_cred);
9083 	tcp->tcp_cpid = curproc->p_pid;
9084 	connp->conn_zoneid = zoneid;
9085 
9086 	connp->conn_dev = conn_dev;
9087 
9088 	ASSERT(q->q_qinfo == &tcp_rinit);
9089 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9090 
9091 	if (flag & SO_SOCKSTR) {
9092 		/*
9093 		 * No need to insert a socket in tcp acceptor hash.
9094 		 * If it was a socket acceptor stream, we dealt with
9095 		 * it above. A socket listener can never accept a
9096 		 * connection and doesn't need acceptor_id.
9097 		 */
9098 		connp->conn_flags |= IPCL_SOCKET;
9099 		tcp->tcp_issocket = 1;
9100 		WR(q)->q_qinfo = &tcp_sock_winit;
9101 	} else {
9102 #ifdef	_ILP32
9103 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9104 #else
9105 		tcp->tcp_acceptor_id = conn_dev;
9106 #endif	/* _ILP32 */
9107 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9108 	}
9109 
9110 	if (tcp_trace)
9111 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9112 
9113 	err = tcp_init(tcp, q);
9114 	if (err != 0) {
9115 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9116 		tcp_acceptor_hash_remove(tcp);
9117 		CONN_DEC_REF(connp);
9118 		q->q_ptr = WR(q)->q_ptr = NULL;
9119 		return (err);
9120 	}
9121 
9122 	RD(q)->q_hiwat = tcp_recv_hiwat;
9123 	tcp->tcp_rwnd = tcp_recv_hiwat;
9124 
9125 	/* Non-zero default values */
9126 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9127 	/*
9128 	 * Put the ref for TCP. Ref for IP was already put
9129 	 * by ipcl_conn_create. Also Make the conn_t globally
9130 	 * visible to walkers
9131 	 */
9132 	mutex_enter(&connp->conn_lock);
9133 	CONN_INC_REF_LOCKED(connp);
9134 	ASSERT(connp->conn_ref == 2);
9135 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9136 	mutex_exit(&connp->conn_lock);
9137 
9138 	qprocson(q);
9139 	return (0);
9140 }
9141 
9142 /*
9143  * Some TCP options can be "set" by requesting them in the option
9144  * buffer. This is needed for XTI feature test though we do not
9145  * allow it in general. We interpret that this mechanism is more
9146  * applicable to OSI protocols and need not be allowed in general.
9147  * This routine filters out options for which it is not allowed (most)
9148  * and lets through those (few) for which it is. [ The XTI interface
9149  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9150  * ever implemented will have to be allowed here ].
9151  */
9152 static boolean_t
9153 tcp_allow_connopt_set(int level, int name)
9154 {
9155 
9156 	switch (level) {
9157 	case IPPROTO_TCP:
9158 		switch (name) {
9159 		case TCP_NODELAY:
9160 			return (B_TRUE);
9161 		default:
9162 			return (B_FALSE);
9163 		}
9164 		/*NOTREACHED*/
9165 	default:
9166 		return (B_FALSE);
9167 	}
9168 	/*NOTREACHED*/
9169 }
9170 
9171 /*
9172  * This routine gets default values of certain options whose default
9173  * values are maintained by protocol specific code
9174  */
9175 /* ARGSUSED */
9176 int
9177 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9178 {
9179 	int32_t	*i1 = (int32_t *)ptr;
9180 
9181 	switch (level) {
9182 	case IPPROTO_TCP:
9183 		switch (name) {
9184 		case TCP_NOTIFY_THRESHOLD:
9185 			*i1 = tcp_ip_notify_interval;
9186 			break;
9187 		case TCP_ABORT_THRESHOLD:
9188 			*i1 = tcp_ip_abort_interval;
9189 			break;
9190 		case TCP_CONN_NOTIFY_THRESHOLD:
9191 			*i1 = tcp_ip_notify_cinterval;
9192 			break;
9193 		case TCP_CONN_ABORT_THRESHOLD:
9194 			*i1 = tcp_ip_abort_cinterval;
9195 			break;
9196 		default:
9197 			return (-1);
9198 		}
9199 		break;
9200 	case IPPROTO_IP:
9201 		switch (name) {
9202 		case IP_TTL:
9203 			*i1 = tcp_ipv4_ttl;
9204 			break;
9205 		default:
9206 			return (-1);
9207 		}
9208 		break;
9209 	case IPPROTO_IPV6:
9210 		switch (name) {
9211 		case IPV6_UNICAST_HOPS:
9212 			*i1 = tcp_ipv6_hoplimit;
9213 			break;
9214 		default:
9215 			return (-1);
9216 		}
9217 		break;
9218 	default:
9219 		return (-1);
9220 	}
9221 	return (sizeof (int));
9222 }
9223 
9224 
9225 /*
9226  * TCP routine to get the values of options.
9227  */
9228 int
9229 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9230 {
9231 	int		*i1 = (int *)ptr;
9232 	conn_t		*connp = Q_TO_CONN(q);
9233 	tcp_t		*tcp = connp->conn_tcp;
9234 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9235 
9236 	switch (level) {
9237 	case SOL_SOCKET:
9238 		switch (name) {
9239 		case SO_LINGER:	{
9240 			struct linger *lgr = (struct linger *)ptr;
9241 
9242 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9243 			lgr->l_linger = tcp->tcp_lingertime;
9244 			}
9245 			return (sizeof (struct linger));
9246 		case SO_DEBUG:
9247 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9248 			break;
9249 		case SO_KEEPALIVE:
9250 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9251 			break;
9252 		case SO_DONTROUTE:
9253 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9254 			break;
9255 		case SO_USELOOPBACK:
9256 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9257 			break;
9258 		case SO_BROADCAST:
9259 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9260 			break;
9261 		case SO_REUSEADDR:
9262 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9263 			break;
9264 		case SO_OOBINLINE:
9265 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9266 			break;
9267 		case SO_DGRAM_ERRIND:
9268 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9269 			break;
9270 		case SO_TYPE:
9271 			*i1 = SOCK_STREAM;
9272 			break;
9273 		case SO_SNDBUF:
9274 			*i1 = tcp->tcp_xmit_hiwater;
9275 			break;
9276 		case SO_RCVBUF:
9277 			*i1 = RD(q)->q_hiwat;
9278 			break;
9279 		case SO_SND_COPYAVOID:
9280 			*i1 = tcp->tcp_snd_zcopy_on ?
9281 			    SO_SND_COPYAVOID : 0;
9282 			break;
9283 		default:
9284 			return (-1);
9285 		}
9286 		break;
9287 	case IPPROTO_TCP:
9288 		switch (name) {
9289 		case TCP_NODELAY:
9290 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9291 			break;
9292 		case TCP_MAXSEG:
9293 			*i1 = tcp->tcp_mss;
9294 			break;
9295 		case TCP_NOTIFY_THRESHOLD:
9296 			*i1 = (int)tcp->tcp_first_timer_threshold;
9297 			break;
9298 		case TCP_ABORT_THRESHOLD:
9299 			*i1 = tcp->tcp_second_timer_threshold;
9300 			break;
9301 		case TCP_CONN_NOTIFY_THRESHOLD:
9302 			*i1 = tcp->tcp_first_ctimer_threshold;
9303 			break;
9304 		case TCP_CONN_ABORT_THRESHOLD:
9305 			*i1 = tcp->tcp_second_ctimer_threshold;
9306 			break;
9307 		case TCP_RECVDSTADDR:
9308 			*i1 = tcp->tcp_recvdstaddr;
9309 			break;
9310 		case TCP_ANONPRIVBIND:
9311 			*i1 = tcp->tcp_anon_priv_bind;
9312 			break;
9313 		case TCP_EXCLBIND:
9314 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9315 			break;
9316 		case TCP_INIT_CWND:
9317 			*i1 = tcp->tcp_init_cwnd;
9318 			break;
9319 		case TCP_KEEPALIVE_THRESHOLD:
9320 			*i1 = tcp->tcp_ka_interval;
9321 			break;
9322 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9323 			*i1 = tcp->tcp_ka_abort_thres;
9324 			break;
9325 		case TCP_CORK:
9326 			*i1 = tcp->tcp_cork;
9327 			break;
9328 		default:
9329 			return (-1);
9330 		}
9331 		break;
9332 	case IPPROTO_IP:
9333 		if (tcp->tcp_family != AF_INET)
9334 			return (-1);
9335 		switch (name) {
9336 		case IP_OPTIONS:
9337 		case T_IP_OPTIONS: {
9338 			/*
9339 			 * This is compatible with BSD in that in only return
9340 			 * the reverse source route with the final destination
9341 			 * as the last entry. The first 4 bytes of the option
9342 			 * will contain the final destination.
9343 			 */
9344 			char	*opt_ptr;
9345 			int	opt_len;
9346 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
9347 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
9348 			/* Caller ensures enough space */
9349 			if (opt_len > 0) {
9350 				/*
9351 				 * TODO: Do we have to handle getsockopt on an
9352 				 * initiator as well?
9353 				 */
9354 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
9355 			}
9356 			return (0);
9357 			}
9358 		case IP_TOS:
9359 		case T_IP_TOS:
9360 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9361 			break;
9362 		case IP_TTL:
9363 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9364 			break;
9365 		default:
9366 			return (-1);
9367 		}
9368 		break;
9369 	case IPPROTO_IPV6:
9370 		/*
9371 		 * IPPROTO_IPV6 options are only supported for sockets
9372 		 * that are using IPv6 on the wire.
9373 		 */
9374 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9375 			return (-1);
9376 		}
9377 		switch (name) {
9378 		case IPV6_UNICAST_HOPS:
9379 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9380 			break;	/* goto sizeof (int) option return */
9381 		case IPV6_BOUND_IF:
9382 			/* Zero if not set */
9383 			*i1 = tcp->tcp_bound_if;
9384 			break;	/* goto sizeof (int) option return */
9385 		case IPV6_RECVPKTINFO:
9386 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9387 				*i1 = 1;
9388 			else
9389 				*i1 = 0;
9390 			break;	/* goto sizeof (int) option return */
9391 		case IPV6_RECVTCLASS:
9392 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9393 				*i1 = 1;
9394 			else
9395 				*i1 = 0;
9396 			break;	/* goto sizeof (int) option return */
9397 		case IPV6_RECVHOPLIMIT:
9398 			if (tcp->tcp_ipv6_recvancillary &
9399 			    TCP_IPV6_RECVHOPLIMIT)
9400 				*i1 = 1;
9401 			else
9402 				*i1 = 0;
9403 			break;	/* goto sizeof (int) option return */
9404 		case IPV6_RECVHOPOPTS:
9405 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9406 				*i1 = 1;
9407 			else
9408 				*i1 = 0;
9409 			break;	/* goto sizeof (int) option return */
9410 		case IPV6_RECVDSTOPTS:
9411 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9412 				*i1 = 1;
9413 			else
9414 				*i1 = 0;
9415 			break;	/* goto sizeof (int) option return */
9416 		case _OLD_IPV6_RECVDSTOPTS:
9417 			if (tcp->tcp_ipv6_recvancillary &
9418 			    TCP_OLD_IPV6_RECVDSTOPTS)
9419 				*i1 = 1;
9420 			else
9421 				*i1 = 0;
9422 			break;	/* goto sizeof (int) option return */
9423 		case IPV6_RECVRTHDR:
9424 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9425 				*i1 = 1;
9426 			else
9427 				*i1 = 0;
9428 			break;	/* goto sizeof (int) option return */
9429 		case IPV6_RECVRTHDRDSTOPTS:
9430 			if (tcp->tcp_ipv6_recvancillary &
9431 			    TCP_IPV6_RECVRTDSTOPTS)
9432 				*i1 = 1;
9433 			else
9434 				*i1 = 0;
9435 			break;	/* goto sizeof (int) option return */
9436 		case IPV6_PKTINFO: {
9437 			/* XXX assumes that caller has room for max size! */
9438 			struct in6_pktinfo *pkti;
9439 
9440 			pkti = (struct in6_pktinfo *)ptr;
9441 			if (ipp->ipp_fields & IPPF_IFINDEX)
9442 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9443 			else
9444 				pkti->ipi6_ifindex = 0;
9445 			if (ipp->ipp_fields & IPPF_ADDR)
9446 				pkti->ipi6_addr = ipp->ipp_addr;
9447 			else
9448 				pkti->ipi6_addr = ipv6_all_zeros;
9449 			return (sizeof (struct in6_pktinfo));
9450 		}
9451 		case IPV6_TCLASS:
9452 			if (ipp->ipp_fields & IPPF_TCLASS)
9453 				*i1 = ipp->ipp_tclass;
9454 			else
9455 				*i1 = IPV6_FLOW_TCLASS(
9456 				    IPV6_DEFAULT_VERS_AND_FLOW);
9457 			break;	/* goto sizeof (int) option return */
9458 		case IPV6_NEXTHOP: {
9459 			sin6_t *sin6 = (sin6_t *)ptr;
9460 
9461 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9462 				return (0);
9463 			*sin6 = sin6_null;
9464 			sin6->sin6_family = AF_INET6;
9465 			sin6->sin6_addr = ipp->ipp_nexthop;
9466 			return (sizeof (sin6_t));
9467 		}
9468 		case IPV6_HOPOPTS:
9469 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9470 				return (0);
9471 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
9472 			return (ipp->ipp_hopoptslen);
9473 		case IPV6_RTHDRDSTOPTS:
9474 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9475 				return (0);
9476 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9477 			return (ipp->ipp_rtdstoptslen);
9478 		case IPV6_RTHDR:
9479 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9480 				return (0);
9481 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9482 			return (ipp->ipp_rthdrlen);
9483 		case IPV6_DSTOPTS:
9484 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9485 				return (0);
9486 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9487 			return (ipp->ipp_dstoptslen);
9488 		case IPV6_SRC_PREFERENCES:
9489 			return (ip6_get_src_preferences(connp,
9490 			    (uint32_t *)ptr));
9491 		case IPV6_PATHMTU: {
9492 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9493 
9494 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9495 				return (-1);
9496 
9497 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9498 				connp->conn_fport, mtuinfo));
9499 		}
9500 		default:
9501 			return (-1);
9502 		}
9503 		break;
9504 	default:
9505 		return (-1);
9506 	}
9507 	return (sizeof (int));
9508 }
9509 
9510 /*
9511  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9512  * Parameters are assumed to be verified by the caller.
9513  */
9514 /* ARGSUSED */
9515 int
9516 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9517     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9518     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9519 {
9520 	tcp_t	*tcp = Q_TO_TCP(q);
9521 	int	*i1 = (int *)invalp;
9522 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9523 	boolean_t checkonly;
9524 	int	reterr;
9525 
9526 	switch (optset_context) {
9527 	case SETFN_OPTCOM_CHECKONLY:
9528 		checkonly = B_TRUE;
9529 		/*
9530 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9531 		 * inlen != 0 implies value supplied and
9532 		 * 	we have to "pretend" to set it.
9533 		 * inlen == 0 implies that there is no
9534 		 * 	value part in T_CHECK request and just validation
9535 		 * done elsewhere should be enough, we just return here.
9536 		 */
9537 		if (inlen == 0) {
9538 			*outlenp = 0;
9539 			return (0);
9540 		}
9541 		break;
9542 	case SETFN_OPTCOM_NEGOTIATE:
9543 		checkonly = B_FALSE;
9544 		break;
9545 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9546 	case SETFN_CONN_NEGOTIATE:
9547 		checkonly = B_FALSE;
9548 		/*
9549 		 * Negotiating local and "association-related" options
9550 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9551 		 * primitives is allowed by XTI, but we choose
9552 		 * to not implement this style negotiation for Internet
9553 		 * protocols (We interpret it is a must for OSI world but
9554 		 * optional for Internet protocols) for all options.
9555 		 * [ Will do only for the few options that enable test
9556 		 * suites that our XTI implementation of this feature
9557 		 * works for transports that do allow it ]
9558 		 */
9559 		if (!tcp_allow_connopt_set(level, name)) {
9560 			*outlenp = 0;
9561 			return (EINVAL);
9562 		}
9563 		break;
9564 	default:
9565 		/*
9566 		 * We should never get here
9567 		 */
9568 		*outlenp = 0;
9569 		return (EINVAL);
9570 	}
9571 
9572 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9573 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9574 
9575 	/*
9576 	 * For TCP, we should have no ancillary data sent down
9577 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9578 	 * has to be zero.
9579 	 */
9580 	ASSERT(thisdg_attrs == NULL);
9581 
9582 	/*
9583 	 * For fixed length options, no sanity check
9584 	 * of passed in length is done. It is assumed *_optcom_req()
9585 	 * routines do the right thing.
9586 	 */
9587 
9588 	switch (level) {
9589 	case SOL_SOCKET:
9590 		switch (name) {
9591 		case SO_LINGER: {
9592 			struct linger *lgr = (struct linger *)invalp;
9593 
9594 			if (!checkonly) {
9595 				if (lgr->l_onoff) {
9596 					tcp->tcp_linger = 1;
9597 					tcp->tcp_lingertime = lgr->l_linger;
9598 				} else {
9599 					tcp->tcp_linger = 0;
9600 					tcp->tcp_lingertime = 0;
9601 				}
9602 				/* struct copy */
9603 				*(struct linger *)outvalp = *lgr;
9604 			} else {
9605 				if (!lgr->l_onoff) {
9606 				    ((struct linger *)outvalp)->l_onoff = 0;
9607 				    ((struct linger *)outvalp)->l_linger = 0;
9608 				} else {
9609 				    /* struct copy */
9610 				    *(struct linger *)outvalp = *lgr;
9611 				}
9612 			}
9613 			*outlenp = sizeof (struct linger);
9614 			return (0);
9615 		}
9616 		case SO_DEBUG:
9617 			if (!checkonly)
9618 				tcp->tcp_debug = onoff;
9619 			break;
9620 		case SO_KEEPALIVE:
9621 			if (checkonly) {
9622 				/* T_CHECK case */
9623 				break;
9624 			}
9625 
9626 			if (!onoff) {
9627 				if (tcp->tcp_ka_enabled) {
9628 					if (tcp->tcp_ka_tid != 0) {
9629 						(void) TCP_TIMER_CANCEL(tcp,
9630 						    tcp->tcp_ka_tid);
9631 						tcp->tcp_ka_tid = 0;
9632 					}
9633 					tcp->tcp_ka_enabled = 0;
9634 				}
9635 				break;
9636 			}
9637 			if (!tcp->tcp_ka_enabled) {
9638 				/* Crank up the keepalive timer */
9639 				tcp->tcp_ka_last_intrvl = 0;
9640 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9641 				    tcp_keepalive_killer,
9642 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9643 				tcp->tcp_ka_enabled = 1;
9644 			}
9645 			break;
9646 		case SO_DONTROUTE:
9647 			/*
9648 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
9649 			 * only of interest to IP.  We track them here only so
9650 			 * that we can report their current value.
9651 			 */
9652 			if (!checkonly) {
9653 				tcp->tcp_dontroute = onoff;
9654 				tcp->tcp_connp->conn_dontroute = onoff;
9655 			}
9656 			break;
9657 		case SO_USELOOPBACK:
9658 			if (!checkonly) {
9659 				tcp->tcp_useloopback = onoff;
9660 				tcp->tcp_connp->conn_loopback = onoff;
9661 			}
9662 			break;
9663 		case SO_BROADCAST:
9664 			if (!checkonly) {
9665 				tcp->tcp_broadcast = onoff;
9666 				tcp->tcp_connp->conn_broadcast = onoff;
9667 			}
9668 			break;
9669 		case SO_REUSEADDR:
9670 			if (!checkonly) {
9671 				tcp->tcp_reuseaddr = onoff;
9672 				tcp->tcp_connp->conn_reuseaddr = onoff;
9673 			}
9674 			break;
9675 		case SO_OOBINLINE:
9676 			if (!checkonly)
9677 				tcp->tcp_oobinline = onoff;
9678 			break;
9679 		case SO_DGRAM_ERRIND:
9680 			if (!checkonly)
9681 				tcp->tcp_dgram_errind = onoff;
9682 			break;
9683 		case SO_SNDBUF: {
9684 			tcp_t *peer_tcp;
9685 
9686 			if (*i1 > tcp_max_buf) {
9687 				*outlenp = 0;
9688 				return (ENOBUFS);
9689 			}
9690 			if (checkonly)
9691 				break;
9692 
9693 			tcp->tcp_xmit_hiwater = *i1;
9694 			if (tcp_snd_lowat_fraction != 0)
9695 				tcp->tcp_xmit_lowater =
9696 				    tcp->tcp_xmit_hiwater /
9697 				    tcp_snd_lowat_fraction;
9698 			(void) tcp_maxpsz_set(tcp, B_TRUE);
9699 			/*
9700 			 * If we are flow-controlled, recheck the condition.
9701 			 * There are apps that increase SO_SNDBUF size when
9702 			 * flow-controlled (EWOULDBLOCK), and expect the flow
9703 			 * control condition to be lifted right away.
9704 			 *
9705 			 * For the fused tcp loopback case, in order to avoid
9706 			 * a race with the peer's tcp_fuse_rrw() we need to
9707 			 * hold its fuse_lock while accessing tcp_flow_stopped.
9708 			 */
9709 			peer_tcp = tcp->tcp_loopback_peer;
9710 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
9711 			if (tcp->tcp_fused)
9712 				mutex_enter(&peer_tcp->tcp_fuse_lock);
9713 
9714 			if (tcp->tcp_flow_stopped &&
9715 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
9716 				tcp_clrqfull(tcp);
9717 			}
9718 			if (tcp->tcp_fused)
9719 				mutex_exit(&peer_tcp->tcp_fuse_lock);
9720 			break;
9721 		}
9722 		case SO_RCVBUF:
9723 			if (*i1 > tcp_max_buf) {
9724 				*outlenp = 0;
9725 				return (ENOBUFS);
9726 			}
9727 			/* Silently ignore zero */
9728 			if (!checkonly && *i1 != 0) {
9729 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
9730 				(void) tcp_rwnd_set(tcp, *i1);
9731 			}
9732 			/*
9733 			 * XXX should we return the rwnd here
9734 			 * and tcp_opt_get ?
9735 			 */
9736 			break;
9737 		case SO_SND_COPYAVOID:
9738 			if (!checkonly) {
9739 				/* we only allow enable at most once for now */
9740 				if (tcp->tcp_loopback ||
9741 				    (!tcp->tcp_snd_zcopy_aware &&
9742 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
9743 					*outlenp = 0;
9744 					return (EOPNOTSUPP);
9745 				}
9746 				tcp->tcp_snd_zcopy_aware = 1;
9747 			}
9748 			break;
9749 		default:
9750 			*outlenp = 0;
9751 			return (EINVAL);
9752 		}
9753 		break;
9754 	case IPPROTO_TCP:
9755 		switch (name) {
9756 		case TCP_NODELAY:
9757 			if (!checkonly)
9758 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
9759 			break;
9760 		case TCP_NOTIFY_THRESHOLD:
9761 			if (!checkonly)
9762 				tcp->tcp_first_timer_threshold = *i1;
9763 			break;
9764 		case TCP_ABORT_THRESHOLD:
9765 			if (!checkonly)
9766 				tcp->tcp_second_timer_threshold = *i1;
9767 			break;
9768 		case TCP_CONN_NOTIFY_THRESHOLD:
9769 			if (!checkonly)
9770 				tcp->tcp_first_ctimer_threshold = *i1;
9771 			break;
9772 		case TCP_CONN_ABORT_THRESHOLD:
9773 			if (!checkonly)
9774 				tcp->tcp_second_ctimer_threshold = *i1;
9775 			break;
9776 		case TCP_RECVDSTADDR:
9777 			if (tcp->tcp_state > TCPS_LISTEN)
9778 				return (EOPNOTSUPP);
9779 			if (!checkonly)
9780 				tcp->tcp_recvdstaddr = onoff;
9781 			break;
9782 		case TCP_ANONPRIVBIND:
9783 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
9784 				*outlenp = 0;
9785 				return (reterr);
9786 			}
9787 			if (!checkonly) {
9788 				tcp->tcp_anon_priv_bind = onoff;
9789 			}
9790 			break;
9791 		case TCP_EXCLBIND:
9792 			if (!checkonly)
9793 				tcp->tcp_exclbind = onoff;
9794 			break;	/* goto sizeof (int) option return */
9795 		case TCP_INIT_CWND: {
9796 			uint32_t init_cwnd = *((uint32_t *)invalp);
9797 
9798 			if (checkonly)
9799 				break;
9800 
9801 			/*
9802 			 * Only allow socket with network configuration
9803 			 * privilege to set the initial cwnd to be larger
9804 			 * than allowed by RFC 3390.
9805 			 */
9806 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
9807 				tcp->tcp_init_cwnd = init_cwnd;
9808 				break;
9809 			}
9810 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
9811 				*outlenp = 0;
9812 				return (reterr);
9813 			}
9814 			if (init_cwnd > TCP_MAX_INIT_CWND) {
9815 				*outlenp = 0;
9816 				return (EINVAL);
9817 			}
9818 			tcp->tcp_init_cwnd = init_cwnd;
9819 			break;
9820 		}
9821 		case TCP_KEEPALIVE_THRESHOLD:
9822 			if (checkonly)
9823 				break;
9824 
9825 			if (*i1 < tcp_keepalive_interval_low ||
9826 			    *i1 > tcp_keepalive_interval_high) {
9827 				*outlenp = 0;
9828 				return (EINVAL);
9829 			}
9830 			if (*i1 != tcp->tcp_ka_interval) {
9831 				tcp->tcp_ka_interval = *i1;
9832 				/*
9833 				 * Check if we need to restart the
9834 				 * keepalive timer.
9835 				 */
9836 				if (tcp->tcp_ka_tid != 0) {
9837 					ASSERT(tcp->tcp_ka_enabled);
9838 					(void) TCP_TIMER_CANCEL(tcp,
9839 					    tcp->tcp_ka_tid);
9840 					tcp->tcp_ka_last_intrvl = 0;
9841 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
9842 					    tcp_keepalive_killer,
9843 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
9844 				}
9845 			}
9846 			break;
9847 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9848 			if (!checkonly) {
9849 				if (*i1 < tcp_keepalive_abort_interval_low ||
9850 				    *i1 > tcp_keepalive_abort_interval_high) {
9851 					*outlenp = 0;
9852 					return (EINVAL);
9853 				}
9854 				tcp->tcp_ka_abort_thres = *i1;
9855 			}
9856 			break;
9857 		case TCP_CORK:
9858 			if (!checkonly) {
9859 				/*
9860 				 * if tcp->tcp_cork was set and is now
9861 				 * being unset, we have to make sure that
9862 				 * the remaining data gets sent out. Also
9863 				 * unset tcp->tcp_cork so that tcp_wput_data()
9864 				 * can send data even if it is less than mss
9865 				 */
9866 				if (tcp->tcp_cork && onoff == 0 &&
9867 				    tcp->tcp_unsent > 0) {
9868 					tcp->tcp_cork = B_FALSE;
9869 					tcp_wput_data(tcp, NULL, B_FALSE);
9870 				}
9871 				tcp->tcp_cork = onoff;
9872 			}
9873 			break;
9874 		default:
9875 			*outlenp = 0;
9876 			return (EINVAL);
9877 		}
9878 		break;
9879 	case IPPROTO_IP:
9880 		if (tcp->tcp_family != AF_INET) {
9881 			*outlenp = 0;
9882 			return (ENOPROTOOPT);
9883 		}
9884 		switch (name) {
9885 		case IP_OPTIONS:
9886 		case T_IP_OPTIONS:
9887 			reterr = tcp_opt_set_header(tcp, checkonly,
9888 			    invalp, inlen);
9889 			if (reterr) {
9890 				*outlenp = 0;
9891 				return (reterr);
9892 			}
9893 			/* OK return - copy input buffer into output buffer */
9894 			if (invalp != outvalp) {
9895 				/* don't trust bcopy for identical src/dst */
9896 				bcopy(invalp, outvalp, inlen);
9897 			}
9898 			*outlenp = inlen;
9899 			return (0);
9900 		case IP_TOS:
9901 		case T_IP_TOS:
9902 			if (!checkonly) {
9903 				tcp->tcp_ipha->ipha_type_of_service =
9904 				    (uchar_t)*i1;
9905 				tcp->tcp_tos = (uchar_t)*i1;
9906 			}
9907 			break;
9908 		case IP_TTL:
9909 			if (!checkonly) {
9910 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
9911 				tcp->tcp_ttl = (uchar_t)*i1;
9912 			}
9913 			break;
9914 		case IP_BOUND_IF:
9915 			/* Handled at the IP level */
9916 			return (-EINVAL);
9917 		case IP_SEC_OPT:
9918 			/*
9919 			 * We should not allow policy setting after
9920 			 * we start listening for connections.
9921 			 */
9922 			if (tcp->tcp_state == TCPS_LISTEN) {
9923 				return (EINVAL);
9924 			} else {
9925 				/* Handled at the IP level */
9926 				return (-EINVAL);
9927 			}
9928 		default:
9929 			*outlenp = 0;
9930 			return (EINVAL);
9931 		}
9932 		break;
9933 	case IPPROTO_IPV6: {
9934 		ip6_pkt_t		*ipp;
9935 
9936 		/*
9937 		 * IPPROTO_IPV6 options are only supported for sockets
9938 		 * that are using IPv6 on the wire.
9939 		 */
9940 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9941 			*outlenp = 0;
9942 			return (ENOPROTOOPT);
9943 		}
9944 		/*
9945 		 * Only sticky options; no ancillary data
9946 		 */
9947 		ASSERT(thisdg_attrs == NULL);
9948 		ipp = &tcp->tcp_sticky_ipp;
9949 
9950 		switch (name) {
9951 		case IPV6_UNICAST_HOPS:
9952 			/* -1 means use default */
9953 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
9954 				*outlenp = 0;
9955 				return (EINVAL);
9956 			}
9957 			if (!checkonly) {
9958 				if (*i1 == -1) {
9959 					tcp->tcp_ip6h->ip6_hops =
9960 					    ipp->ipp_unicast_hops =
9961 					    (uint8_t)tcp_ipv6_hoplimit;
9962 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
9963 					/* Pass modified value to IP. */
9964 					*i1 = tcp->tcp_ip6h->ip6_hops;
9965 				} else {
9966 					tcp->tcp_ip6h->ip6_hops =
9967 					    ipp->ipp_unicast_hops =
9968 					    (uint8_t)*i1;
9969 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
9970 				}
9971 				reterr = tcp_build_hdrs(q, tcp);
9972 				if (reterr != 0)
9973 					return (reterr);
9974 			}
9975 			break;
9976 		case IPV6_BOUND_IF:
9977 			if (!checkonly) {
9978 				int error = 0;
9979 
9980 				tcp->tcp_bound_if = *i1;
9981 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
9982 				    B_TRUE, checkonly, level, name, mblk);
9983 				if (error != 0) {
9984 					*outlenp = 0;
9985 					return (error);
9986 				}
9987 			}
9988 			break;
9989 		/*
9990 		 * Set boolean switches for ancillary data delivery
9991 		 */
9992 		case IPV6_RECVPKTINFO:
9993 			if (!checkonly) {
9994 				if (onoff)
9995 					tcp->tcp_ipv6_recvancillary |=
9996 					    TCP_IPV6_RECVPKTINFO;
9997 				else
9998 					tcp->tcp_ipv6_recvancillary &=
9999 					    ~TCP_IPV6_RECVPKTINFO;
10000 				/* Force it to be sent up with the next msg */
10001 				tcp->tcp_recvifindex = 0;
10002 			}
10003 			break;
10004 		case IPV6_RECVTCLASS:
10005 			if (!checkonly) {
10006 				if (onoff)
10007 					tcp->tcp_ipv6_recvancillary |=
10008 					    TCP_IPV6_RECVTCLASS;
10009 				else
10010 					tcp->tcp_ipv6_recvancillary &=
10011 					    ~TCP_IPV6_RECVTCLASS;
10012 			}
10013 			break;
10014 		case IPV6_RECVHOPLIMIT:
10015 			if (!checkonly) {
10016 				if (onoff)
10017 					tcp->tcp_ipv6_recvancillary |=
10018 					    TCP_IPV6_RECVHOPLIMIT;
10019 				else
10020 					tcp->tcp_ipv6_recvancillary &=
10021 					    ~TCP_IPV6_RECVHOPLIMIT;
10022 				/* Force it to be sent up with the next msg */
10023 				tcp->tcp_recvhops = 0xffffffffU;
10024 			}
10025 			break;
10026 		case IPV6_RECVHOPOPTS:
10027 			if (!checkonly) {
10028 				if (onoff)
10029 					tcp->tcp_ipv6_recvancillary |=
10030 					    TCP_IPV6_RECVHOPOPTS;
10031 				else
10032 					tcp->tcp_ipv6_recvancillary &=
10033 					    ~TCP_IPV6_RECVHOPOPTS;
10034 			}
10035 			break;
10036 		case IPV6_RECVDSTOPTS:
10037 			if (!checkonly) {
10038 				if (onoff)
10039 					tcp->tcp_ipv6_recvancillary |=
10040 					    TCP_IPV6_RECVDSTOPTS;
10041 				else
10042 					tcp->tcp_ipv6_recvancillary &=
10043 					    ~TCP_IPV6_RECVDSTOPTS;
10044 			}
10045 			break;
10046 		case _OLD_IPV6_RECVDSTOPTS:
10047 			if (!checkonly) {
10048 				if (onoff)
10049 					tcp->tcp_ipv6_recvancillary |=
10050 					    TCP_OLD_IPV6_RECVDSTOPTS;
10051 				else
10052 					tcp->tcp_ipv6_recvancillary &=
10053 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10054 			}
10055 			break;
10056 		case IPV6_RECVRTHDR:
10057 			if (!checkonly) {
10058 				if (onoff)
10059 					tcp->tcp_ipv6_recvancillary |=
10060 					    TCP_IPV6_RECVRTHDR;
10061 				else
10062 					tcp->tcp_ipv6_recvancillary &=
10063 					    ~TCP_IPV6_RECVRTHDR;
10064 			}
10065 			break;
10066 		case IPV6_RECVRTHDRDSTOPTS:
10067 			if (!checkonly) {
10068 				if (onoff)
10069 					tcp->tcp_ipv6_recvancillary |=
10070 					    TCP_IPV6_RECVRTDSTOPTS;
10071 				else
10072 					tcp->tcp_ipv6_recvancillary &=
10073 					    ~TCP_IPV6_RECVRTDSTOPTS;
10074 			}
10075 			break;
10076 		case IPV6_PKTINFO:
10077 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10078 				return (EINVAL);
10079 			if (checkonly)
10080 				break;
10081 
10082 			if (inlen == 0) {
10083 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10084 			} else {
10085 				struct in6_pktinfo *pkti;
10086 
10087 				pkti = (struct in6_pktinfo *)invalp;
10088 				/*
10089 				 * RFC 3542 states that ipi6_addr must be
10090 				 * the unspecified address when setting the
10091 				 * IPV6_PKTINFO sticky socket option on a
10092 				 * TCP socket.
10093 				 */
10094 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10095 					return (EINVAL);
10096 				/*
10097 				 * ip6_set_pktinfo() validates the source
10098 				 * address and interface index.
10099 				 */
10100 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10101 				    pkti, mblk);
10102 				if (reterr != 0)
10103 					return (reterr);
10104 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10105 				ipp->ipp_addr = pkti->ipi6_addr;
10106 				if (ipp->ipp_ifindex != 0)
10107 					ipp->ipp_fields |= IPPF_IFINDEX;
10108 				else
10109 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10110 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10111 					ipp->ipp_fields |= IPPF_ADDR;
10112 				else
10113 					ipp->ipp_fields &= ~IPPF_ADDR;
10114 			}
10115 			reterr = tcp_build_hdrs(q, tcp);
10116 			if (reterr != 0)
10117 				return (reterr);
10118 			break;
10119 		case IPV6_TCLASS:
10120 			if (inlen != 0 && inlen != sizeof (int))
10121 				return (EINVAL);
10122 			if (checkonly)
10123 				break;
10124 
10125 			if (inlen == 0) {
10126 				ipp->ipp_fields &= ~IPPF_TCLASS;
10127 			} else {
10128 				if (*i1 > 255 || *i1 < -1)
10129 					return (EINVAL);
10130 				if (*i1 == -1) {
10131 					ipp->ipp_tclass = 0;
10132 					*i1 = 0;
10133 				} else {
10134 					ipp->ipp_tclass = *i1;
10135 				}
10136 				ipp->ipp_fields |= IPPF_TCLASS;
10137 			}
10138 			reterr = tcp_build_hdrs(q, tcp);
10139 			if (reterr != 0)
10140 				return (reterr);
10141 			break;
10142 		case IPV6_NEXTHOP:
10143 			/*
10144 			 * IP will verify that the nexthop is reachable
10145 			 * and fail for sticky options.
10146 			 */
10147 			if (inlen != 0 && inlen != sizeof (sin6_t))
10148 				return (EINVAL);
10149 			if (checkonly)
10150 				break;
10151 
10152 			if (inlen == 0) {
10153 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10154 			} else {
10155 				sin6_t *sin6 = (sin6_t *)invalp;
10156 
10157 				if (sin6->sin6_family != AF_INET6)
10158 					return (EAFNOSUPPORT);
10159 				if (IN6_IS_ADDR_V4MAPPED(
10160 				    &sin6->sin6_addr))
10161 					return (EADDRNOTAVAIL);
10162 				ipp->ipp_nexthop = sin6->sin6_addr;
10163 				if (!IN6_IS_ADDR_UNSPECIFIED(
10164 				    &ipp->ipp_nexthop))
10165 					ipp->ipp_fields |= IPPF_NEXTHOP;
10166 				else
10167 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10168 			}
10169 			reterr = tcp_build_hdrs(q, tcp);
10170 			if (reterr != 0)
10171 				return (reterr);
10172 			break;
10173 		case IPV6_HOPOPTS: {
10174 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10175 			/*
10176 			 * Sanity checks - minimum size, size a multiple of
10177 			 * eight bytes, and matching size passed in.
10178 			 */
10179 			if (inlen != 0 &&
10180 			    inlen != (8 * (hopts->ip6h_len + 1)))
10181 				return (EINVAL);
10182 
10183 			if (checkonly)
10184 				break;
10185 
10186 			if (inlen == 0) {
10187 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10188 					kmem_free(ipp->ipp_hopopts,
10189 					    ipp->ipp_hopoptslen);
10190 					ipp->ipp_hopopts = NULL;
10191 					ipp->ipp_hopoptslen = 0;
10192 				}
10193 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10194 			} else {
10195 				reterr = tcp_pkt_set(invalp, inlen,
10196 				    (uchar_t **)&ipp->ipp_hopopts,
10197 				    &ipp->ipp_hopoptslen);
10198 				if (reterr != 0)
10199 					return (reterr);
10200 				ipp->ipp_fields |= IPPF_HOPOPTS;
10201 			}
10202 			reterr = tcp_build_hdrs(q, tcp);
10203 			if (reterr != 0)
10204 				return (reterr);
10205 			break;
10206 		}
10207 		case IPV6_RTHDRDSTOPTS: {
10208 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10209 
10210 			/*
10211 			 * Sanity checks - minimum size, size a multiple of
10212 			 * eight bytes, and matching size passed in.
10213 			 */
10214 			if (inlen != 0 &&
10215 			    inlen != (8 * (dopts->ip6d_len + 1)))
10216 				return (EINVAL);
10217 
10218 			if (checkonly)
10219 				break;
10220 
10221 			if (inlen == 0) {
10222 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10223 					kmem_free(ipp->ipp_rtdstopts,
10224 					    ipp->ipp_rtdstoptslen);
10225 					ipp->ipp_rtdstopts = NULL;
10226 					ipp->ipp_rtdstoptslen = 0;
10227 				}
10228 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10229 			} else {
10230 				reterr = tcp_pkt_set(invalp, inlen,
10231 				    (uchar_t **)&ipp->ipp_rtdstopts,
10232 				    &ipp->ipp_rtdstoptslen);
10233 				if (reterr != 0)
10234 					return (reterr);
10235 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10236 			}
10237 			reterr = tcp_build_hdrs(q, tcp);
10238 			if (reterr != 0)
10239 				return (reterr);
10240 			break;
10241 		}
10242 		case IPV6_DSTOPTS: {
10243 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10244 
10245 			/*
10246 			 * Sanity checks - minimum size, size a multiple of
10247 			 * eight bytes, and matching size passed in.
10248 			 */
10249 			if (inlen != 0 &&
10250 			    inlen != (8 * (dopts->ip6d_len + 1)))
10251 				return (EINVAL);
10252 
10253 			if (checkonly)
10254 				break;
10255 
10256 			if (inlen == 0) {
10257 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
10258 					kmem_free(ipp->ipp_dstopts,
10259 					    ipp->ipp_dstoptslen);
10260 					ipp->ipp_dstopts = NULL;
10261 					ipp->ipp_dstoptslen = 0;
10262 				}
10263 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10264 			} else {
10265 				reterr = tcp_pkt_set(invalp, inlen,
10266 				    (uchar_t **)&ipp->ipp_dstopts,
10267 				    &ipp->ipp_dstoptslen);
10268 				if (reterr != 0)
10269 					return (reterr);
10270 				ipp->ipp_fields |= IPPF_DSTOPTS;
10271 			}
10272 			reterr = tcp_build_hdrs(q, tcp);
10273 			if (reterr != 0)
10274 				return (reterr);
10275 			break;
10276 		}
10277 		case IPV6_RTHDR: {
10278 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10279 
10280 			/*
10281 			 * Sanity checks - minimum size, size a multiple of
10282 			 * eight bytes, and matching size passed in.
10283 			 */
10284 			if (inlen != 0 &&
10285 			    inlen != (8 * (rt->ip6r_len + 1)))
10286 				return (EINVAL);
10287 
10288 			if (checkonly)
10289 				break;
10290 
10291 			if (inlen == 0) {
10292 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
10293 					kmem_free(ipp->ipp_rthdr,
10294 					    ipp->ipp_rthdrlen);
10295 					ipp->ipp_rthdr = NULL;
10296 					ipp->ipp_rthdrlen = 0;
10297 				}
10298 				ipp->ipp_fields &= ~IPPF_RTHDR;
10299 			} else {
10300 				reterr = tcp_pkt_set(invalp, inlen,
10301 				    (uchar_t **)&ipp->ipp_rthdr,
10302 				    &ipp->ipp_rthdrlen);
10303 				if (reterr != 0)
10304 					return (reterr);
10305 				ipp->ipp_fields |= IPPF_RTHDR;
10306 			}
10307 			reterr = tcp_build_hdrs(q, tcp);
10308 			if (reterr != 0)
10309 				return (reterr);
10310 			break;
10311 		}
10312 		case IPV6_V6ONLY:
10313 			if (!checkonly)
10314 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10315 			break;
10316 		case IPV6_USE_MIN_MTU:
10317 			if (inlen != sizeof (int))
10318 				return (EINVAL);
10319 
10320 			if (*i1 < -1 || *i1 > 1)
10321 				return (EINVAL);
10322 
10323 			if (checkonly)
10324 				break;
10325 
10326 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10327 			ipp->ipp_use_min_mtu = *i1;
10328 			break;
10329 		case IPV6_BOUND_PIF:
10330 			/* Handled at the IP level */
10331 			return (-EINVAL);
10332 		case IPV6_SEC_OPT:
10333 			/*
10334 			 * We should not allow policy setting after
10335 			 * we start listening for connections.
10336 			 */
10337 			if (tcp->tcp_state == TCPS_LISTEN) {
10338 				return (EINVAL);
10339 			} else {
10340 				/* Handled at the IP level */
10341 				return (-EINVAL);
10342 			}
10343 		case IPV6_SRC_PREFERENCES:
10344 			if (inlen != sizeof (uint32_t))
10345 				return (EINVAL);
10346 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10347 			    *(uint32_t *)invalp);
10348 			if (reterr != 0) {
10349 				*outlenp = 0;
10350 				return (reterr);
10351 			}
10352 			break;
10353 		default:
10354 			*outlenp = 0;
10355 			return (EINVAL);
10356 		}
10357 		break;
10358 	}		/* end IPPROTO_IPV6 */
10359 	default:
10360 		*outlenp = 0;
10361 		return (EINVAL);
10362 	}
10363 	/*
10364 	 * Common case of OK return with outval same as inval
10365 	 */
10366 	if (invalp != outvalp) {
10367 		/* don't trust bcopy for identical src/dst */
10368 		(void) bcopy(invalp, outvalp, inlen);
10369 	}
10370 	*outlenp = inlen;
10371 	return (0);
10372 }
10373 
10374 /*
10375  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10376  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10377  * headers, and the maximum size tcp header (to avoid reallocation
10378  * on the fly for additional tcp options).
10379  * Returns failure if can't allocate memory.
10380  */
10381 static int
10382 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10383 {
10384 	char	*hdrs;
10385 	uint_t	hdrs_len;
10386 	ip6i_t	*ip6i;
10387 	char	buf[TCP_MAX_HDR_LENGTH];
10388 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10389 	in6_addr_t src, dst;
10390 
10391 	/*
10392 	 * save the existing tcp header and source/dest IP addresses
10393 	 */
10394 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10395 	src = tcp->tcp_ip6h->ip6_src;
10396 	dst = tcp->tcp_ip6h->ip6_dst;
10397 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10398 	ASSERT(hdrs_len != 0);
10399 	if (hdrs_len > tcp->tcp_iphc_len) {
10400 		/* Need to reallocate */
10401 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10402 		if (hdrs == NULL)
10403 			return (ENOMEM);
10404 		if (tcp->tcp_iphc != NULL) {
10405 			if (tcp->tcp_hdr_grown) {
10406 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10407 			} else {
10408 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10409 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10410 			}
10411 			tcp->tcp_iphc_len = 0;
10412 		}
10413 		ASSERT(tcp->tcp_iphc_len == 0);
10414 		tcp->tcp_iphc = hdrs;
10415 		tcp->tcp_iphc_len = hdrs_len;
10416 		tcp->tcp_hdr_grown = B_TRUE;
10417 	}
10418 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10419 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10420 
10421 	/* Set header fields not in ipp */
10422 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10423 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10424 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10425 	} else {
10426 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10427 	}
10428 	/*
10429 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10430 	 *
10431 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10432 	 */
10433 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10434 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10435 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10436 
10437 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10438 
10439 	tcp->tcp_ip6h->ip6_src = src;
10440 	tcp->tcp_ip6h->ip6_dst = dst;
10441 
10442 	/*
10443 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10444 	 * the default value for TCP.
10445 	 */
10446 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10447 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10448 
10449 	/*
10450 	 * If we're setting extension headers after a connection
10451 	 * has been established, and if we have a routing header
10452 	 * among the extension headers, call ip_massage_options_v6 to
10453 	 * manipulate the routing header/ip6_dst set the checksum
10454 	 * difference in the tcp header template.
10455 	 * (This happens in tcp_connect_ipv6 if the routing header
10456 	 * is set prior to the connect.)
10457 	 * Set the tcp_sum to zero first in case we've cleared a
10458 	 * routing header or don't have one at all.
10459 	 */
10460 	tcp->tcp_sum = 0;
10461 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10462 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10463 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10464 		    (uint8_t *)tcp->tcp_tcph);
10465 		if (rth != NULL) {
10466 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10467 			    rth);
10468 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10469 			    (tcp->tcp_sum >> 16));
10470 		}
10471 	}
10472 
10473 	/* Try to get everything in a single mblk */
10474 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10475 	return (0);
10476 }
10477 
10478 /*
10479  * Set optbuf and optlen for the option.
10480  * Allocate memory (if not already present).
10481  * Otherwise just point optbuf and optlen at invalp and inlen.
10482  * Returns failure if memory can not be allocated.
10483  */
10484 static int
10485 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
10486 {
10487 	uchar_t *optbuf;
10488 
10489 	if (inlen == *optlenp) {
10490 		/* Unchanged length - no need to realocate */
10491 		bcopy(invalp, *optbufp, inlen);
10492 		return (0);
10493 	}
10494 	if (inlen != 0) {
10495 		/* Allocate new buffer before free */
10496 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
10497 		if (optbuf == NULL)
10498 			return (ENOMEM);
10499 	} else {
10500 		optbuf = NULL;
10501 	}
10502 	/* Free old buffer */
10503 	if (*optlenp != 0)
10504 		kmem_free(*optbufp, *optlenp);
10505 
10506 	bcopy(invalp, optbuf, inlen);
10507 	*optbufp = optbuf;
10508 	*optlenp = inlen;
10509 	return (0);
10510 }
10511 
10512 
10513 /*
10514  * Use the outgoing IP header to create an IP_OPTIONS option the way
10515  * it was passed down from the application.
10516  */
10517 static int
10518 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
10519 {
10520 	ipoptp_t	opts;
10521 	uchar_t		*opt;
10522 	uint8_t		optval;
10523 	uint8_t		optlen;
10524 	uint32_t	len = 0;
10525 	uchar_t	*buf1 = buf;
10526 
10527 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
10528 	len += IP_ADDR_LEN;
10529 	bzero(buf1, IP_ADDR_LEN);
10530 
10531 	for (optval = ipoptp_first(&opts, ipha);
10532 	    optval != IPOPT_EOL;
10533 	    optval = ipoptp_next(&opts)) {
10534 		opt = opts.ipoptp_cur;
10535 		optlen = opts.ipoptp_len;
10536 		switch (optval) {
10537 			int	off;
10538 		case IPOPT_SSRR:
10539 		case IPOPT_LSRR:
10540 
10541 			/*
10542 			 * Insert ipha_dst as the first entry in the source
10543 			 * route and move down the entries on step.
10544 			 * The last entry gets placed at buf1.
10545 			 */
10546 			buf[IPOPT_OPTVAL] = optval;
10547 			buf[IPOPT_OLEN] = optlen;
10548 			buf[IPOPT_OFFSET] = optlen;
10549 
10550 			off = optlen - IP_ADDR_LEN;
10551 			if (off < 0) {
10552 				/* No entries in source route */
10553 				break;
10554 			}
10555 			/* Last entry in source route */
10556 			bcopy(opt + off, buf1, IP_ADDR_LEN);
10557 			off -= IP_ADDR_LEN;
10558 
10559 			while (off > 0) {
10560 				bcopy(opt + off,
10561 				    buf + off + IP_ADDR_LEN,
10562 				    IP_ADDR_LEN);
10563 				off -= IP_ADDR_LEN;
10564 			}
10565 			/* ipha_dst into first slot */
10566 			bcopy(&ipha->ipha_dst,
10567 			    buf + off + IP_ADDR_LEN,
10568 			    IP_ADDR_LEN);
10569 			buf += optlen;
10570 			len += optlen;
10571 			break;
10572 		default:
10573 			bcopy(opt, buf, optlen);
10574 			buf += optlen;
10575 			len += optlen;
10576 			break;
10577 		}
10578 	}
10579 done:
10580 	/* Pad the resulting options */
10581 	while (len & 0x3) {
10582 		*buf++ = IPOPT_EOL;
10583 		len++;
10584 	}
10585 	return (len);
10586 }
10587 
10588 /*
10589  * Transfer any source route option from ipha to buf/dst in reversed form.
10590  */
10591 static int
10592 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10593 {
10594 	ipoptp_t	opts;
10595 	uchar_t		*opt;
10596 	uint8_t		optval;
10597 	uint8_t		optlen;
10598 	uint32_t	len = 0;
10599 
10600 	for (optval = ipoptp_first(&opts, ipha);
10601 	    optval != IPOPT_EOL;
10602 	    optval = ipoptp_next(&opts)) {
10603 		opt = opts.ipoptp_cur;
10604 		optlen = opts.ipoptp_len;
10605 		switch (optval) {
10606 			int	off1, off2;
10607 		case IPOPT_SSRR:
10608 		case IPOPT_LSRR:
10609 
10610 			/* Reverse source route */
10611 			/*
10612 			 * First entry should be the next to last one in the
10613 			 * current source route (the last entry is our
10614 			 * address.)
10615 			 * The last entry should be the final destination.
10616 			 */
10617 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10618 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10619 			off1 = IPOPT_MINOFF_SR - 1;
10620 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10621 			if (off2 < 0) {
10622 				/* No entries in source route */
10623 				break;
10624 			}
10625 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10626 			/*
10627 			 * Note: use src since ipha has not had its src
10628 			 * and dst reversed (it is in the state it was
10629 			 * received.
10630 			 */
10631 			bcopy(&ipha->ipha_src, buf + off2,
10632 			    IP_ADDR_LEN);
10633 			off2 -= IP_ADDR_LEN;
10634 
10635 			while (off2 > 0) {
10636 				bcopy(opt + off2, buf + off1,
10637 				    IP_ADDR_LEN);
10638 				off1 += IP_ADDR_LEN;
10639 				off2 -= IP_ADDR_LEN;
10640 			}
10641 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10642 			buf += optlen;
10643 			len += optlen;
10644 			break;
10645 		}
10646 	}
10647 done:
10648 	/* Pad the resulting options */
10649 	while (len & 0x3) {
10650 		*buf++ = IPOPT_EOL;
10651 		len++;
10652 	}
10653 	return (len);
10654 }
10655 
10656 
10657 /*
10658  * Extract and revert a source route from ipha (if any)
10659  * and then update the relevant fields in both tcp_t and the standard header.
10660  */
10661 static void
10662 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10663 {
10664 	char	buf[TCP_MAX_HDR_LENGTH];
10665 	uint_t	tcph_len;
10666 	int	len;
10667 
10668 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10669 	len = IPH_HDR_LENGTH(ipha);
10670 	if (len == IP_SIMPLE_HDR_LENGTH)
10671 		/* Nothing to do */
10672 		return;
10673 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10674 	    (len & 0x3))
10675 		return;
10676 
10677 	tcph_len = tcp->tcp_tcp_hdr_len;
10678 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10679 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10680 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10681 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10682 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10683 	len += IP_SIMPLE_HDR_LENGTH;
10684 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10685 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10686 	if ((int)tcp->tcp_sum < 0)
10687 		tcp->tcp_sum--;
10688 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10689 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10690 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10691 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10692 	tcp->tcp_ip_hdr_len = len;
10693 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10694 	    (IP_VERSION << 4) | (len >> 2);
10695 	len += tcph_len;
10696 	tcp->tcp_hdr_len = len;
10697 }
10698 
10699 /*
10700  * Copy the standard header into its new location,
10701  * lay in the new options and then update the relevant
10702  * fields in both tcp_t and the standard header.
10703  */
10704 static int
10705 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10706 {
10707 	uint_t	tcph_len;
10708 	char	*ip_optp;
10709 	tcph_t	*new_tcph;
10710 
10711 	if (checkonly) {
10712 		/*
10713 		 * do not really set, just pretend to - T_CHECK
10714 		 */
10715 		if (len != 0) {
10716 			/*
10717 			 * there is value supplied, validate it as if
10718 			 * for a real set operation.
10719 			 */
10720 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10721 				return (EINVAL);
10722 		}
10723 		return (0);
10724 	}
10725 
10726 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10727 		return (EINVAL);
10728 
10729 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10730 	tcph_len = tcp->tcp_tcp_hdr_len;
10731 	new_tcph = (tcph_t *)(ip_optp + len);
10732 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
10733 	tcp->tcp_tcph = new_tcph;
10734 	bcopy(ptr, ip_optp, len);
10735 
10736 	len += IP_SIMPLE_HDR_LENGTH;
10737 
10738 	tcp->tcp_ip_hdr_len = len;
10739 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10740 		(IP_VERSION << 4) | (len >> 2);
10741 	len += tcph_len;
10742 	tcp->tcp_hdr_len = len;
10743 	if (!TCP_IS_DETACHED(tcp)) {
10744 		/* Always allocate room for all options. */
10745 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10746 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10747 	}
10748 	return (0);
10749 }
10750 
10751 /* Get callback routine passed to nd_load by tcp_param_register */
10752 /* ARGSUSED */
10753 static int
10754 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10755 {
10756 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10757 
10758 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10759 	return (0);
10760 }
10761 
10762 /*
10763  * Walk through the param array specified registering each element with the
10764  * named dispatch handler.
10765  */
10766 static boolean_t
10767 tcp_param_register(tcpparam_t *tcppa, int cnt)
10768 {
10769 	for (; cnt-- > 0; tcppa++) {
10770 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10771 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10772 			    tcp_param_get, tcp_param_set,
10773 			    (caddr_t)tcppa)) {
10774 				nd_free(&tcp_g_nd);
10775 				return (B_FALSE);
10776 			}
10777 		}
10778 	}
10779 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10780 	    tcp_param_get, tcp_param_set_aligned,
10781 	    (caddr_t)&tcp_wroff_xtra_param)) {
10782 		nd_free(&tcp_g_nd);
10783 		return (B_FALSE);
10784 	}
10785 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10786 	    tcp_param_get, tcp_param_set_aligned,
10787 	    (caddr_t)&tcp_mdt_head_param)) {
10788 		nd_free(&tcp_g_nd);
10789 		return (B_FALSE);
10790 	}
10791 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
10792 	    tcp_param_get, tcp_param_set_aligned,
10793 	    (caddr_t)&tcp_mdt_tail_param)) {
10794 		nd_free(&tcp_g_nd);
10795 		return (B_FALSE);
10796 	}
10797 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
10798 	    tcp_param_get, tcp_param_set,
10799 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
10800 		nd_free(&tcp_g_nd);
10801 		return (B_FALSE);
10802 	}
10803 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
10804 	    tcp_extra_priv_ports_get, NULL, NULL)) {
10805 		nd_free(&tcp_g_nd);
10806 		return (B_FALSE);
10807 	}
10808 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
10809 	    NULL, tcp_extra_priv_ports_add, NULL)) {
10810 		nd_free(&tcp_g_nd);
10811 		return (B_FALSE);
10812 	}
10813 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
10814 	    NULL, tcp_extra_priv_ports_del, NULL)) {
10815 		nd_free(&tcp_g_nd);
10816 		return (B_FALSE);
10817 	}
10818 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
10819 	    NULL)) {
10820 		nd_free(&tcp_g_nd);
10821 		return (B_FALSE);
10822 	}
10823 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
10824 	    NULL, NULL)) {
10825 		nd_free(&tcp_g_nd);
10826 		return (B_FALSE);
10827 	}
10828 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
10829 	    NULL, NULL)) {
10830 		nd_free(&tcp_g_nd);
10831 		return (B_FALSE);
10832 	}
10833 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
10834 	    NULL, NULL)) {
10835 		nd_free(&tcp_g_nd);
10836 		return (B_FALSE);
10837 	}
10838 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
10839 	    NULL, NULL)) {
10840 		nd_free(&tcp_g_nd);
10841 		return (B_FALSE);
10842 	}
10843 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
10844 	    tcp_host_param_set, NULL)) {
10845 		nd_free(&tcp_g_nd);
10846 		return (B_FALSE);
10847 	}
10848 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
10849 	    tcp_host_param_set_ipv6, NULL)) {
10850 		nd_free(&tcp_g_nd);
10851 		return (B_FALSE);
10852 	}
10853 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
10854 	    NULL)) {
10855 		nd_free(&tcp_g_nd);
10856 		return (B_FALSE);
10857 	}
10858 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
10859 	    tcp_reserved_port_list, NULL, NULL)) {
10860 		nd_free(&tcp_g_nd);
10861 		return (B_FALSE);
10862 	}
10863 	/*
10864 	 * Dummy ndd variables - only to convey obsolescence information
10865 	 * through printing of their name (no get or set routines)
10866 	 * XXX Remove in future releases ?
10867 	 */
10868 	if (!nd_load(&tcp_g_nd,
10869 	    "tcp_close_wait_interval(obsoleted - "
10870 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
10871 		nd_free(&tcp_g_nd);
10872 		return (B_FALSE);
10873 	}
10874 	return (B_TRUE);
10875 }
10876 
10877 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
10878 /* ARGSUSED */
10879 static int
10880 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
10881     cred_t *cr)
10882 {
10883 	long new_value;
10884 	tcpparam_t *tcppa = (tcpparam_t *)cp;
10885 
10886 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10887 	    new_value < tcppa->tcp_param_min ||
10888 	    new_value > tcppa->tcp_param_max) {
10889 		return (EINVAL);
10890 	}
10891 	/*
10892 	 * Need to make sure new_value is a multiple of 4.  If it is not,
10893 	 * round it up.  For future 64 bit requirement, we actually make it
10894 	 * a multiple of 8.
10895 	 */
10896 	if (new_value & 0x7) {
10897 		new_value = (new_value & ~0x7) + 0x8;
10898 	}
10899 	tcppa->tcp_param_val = new_value;
10900 	return (0);
10901 }
10902 
10903 /* Set callback routine passed to nd_load by tcp_param_register */
10904 /* ARGSUSED */
10905 static int
10906 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
10907 {
10908 	long	new_value;
10909 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10910 
10911 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10912 	    new_value < tcppa->tcp_param_min ||
10913 	    new_value > tcppa->tcp_param_max) {
10914 		return (EINVAL);
10915 	}
10916 	tcppa->tcp_param_val = new_value;
10917 	return (0);
10918 }
10919 
10920 /*
10921  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
10922  * is filled, return as much as we can.  The message passed in may be
10923  * multi-part, chained using b_cont.  "start" is the starting sequence
10924  * number for this piece.
10925  */
10926 static mblk_t *
10927 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
10928 {
10929 	uint32_t	end;
10930 	mblk_t		*mp1;
10931 	mblk_t		*mp2;
10932 	mblk_t		*next_mp;
10933 	uint32_t	u1;
10934 
10935 	/* Walk through all the new pieces. */
10936 	do {
10937 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10938 		    (uintptr_t)INT_MAX);
10939 		end = start + (int)(mp->b_wptr - mp->b_rptr);
10940 		next_mp = mp->b_cont;
10941 		if (start == end) {
10942 			/* Empty.  Blast it. */
10943 			freeb(mp);
10944 			continue;
10945 		}
10946 		mp->b_cont = NULL;
10947 		TCP_REASS_SET_SEQ(mp, start);
10948 		TCP_REASS_SET_END(mp, end);
10949 		mp1 = tcp->tcp_reass_tail;
10950 		if (!mp1) {
10951 			tcp->tcp_reass_tail = mp;
10952 			tcp->tcp_reass_head = mp;
10953 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10954 			UPDATE_MIB(&tcp_mib,
10955 			    tcpInDataUnorderBytes, end - start);
10956 			continue;
10957 		}
10958 		/* New stuff completely beyond tail? */
10959 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
10960 			/* Link it on end. */
10961 			mp1->b_cont = mp;
10962 			tcp->tcp_reass_tail = mp;
10963 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
10964 			UPDATE_MIB(&tcp_mib,
10965 			    tcpInDataUnorderBytes, end - start);
10966 			continue;
10967 		}
10968 		mp1 = tcp->tcp_reass_head;
10969 		u1 = TCP_REASS_SEQ(mp1);
10970 		/* New stuff at the front? */
10971 		if (SEQ_LT(start, u1)) {
10972 			/* Yes... Check for overlap. */
10973 			mp->b_cont = mp1;
10974 			tcp->tcp_reass_head = mp;
10975 			tcp_reass_elim_overlap(tcp, mp);
10976 			continue;
10977 		}
10978 		/*
10979 		 * The new piece fits somewhere between the head and tail.
10980 		 * We find our slot, where mp1 precedes us and mp2 trails.
10981 		 */
10982 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
10983 			u1 = TCP_REASS_SEQ(mp2);
10984 			if (SEQ_LEQ(start, u1))
10985 				break;
10986 		}
10987 		/* Link ourselves in */
10988 		mp->b_cont = mp2;
10989 		mp1->b_cont = mp;
10990 
10991 		/* Trim overlap with following mblk(s) first */
10992 		tcp_reass_elim_overlap(tcp, mp);
10993 
10994 		/* Trim overlap with preceding mblk */
10995 		tcp_reass_elim_overlap(tcp, mp1);
10996 
10997 	} while (start = end, mp = next_mp);
10998 	mp1 = tcp->tcp_reass_head;
10999 	/* Anything ready to go? */
11000 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11001 		return (NULL);
11002 	/* Eat what we can off the queue */
11003 	for (;;) {
11004 		mp = mp1->b_cont;
11005 		end = TCP_REASS_END(mp1);
11006 		TCP_REASS_SET_SEQ(mp1, 0);
11007 		TCP_REASS_SET_END(mp1, 0);
11008 		if (!mp) {
11009 			tcp->tcp_reass_tail = NULL;
11010 			break;
11011 		}
11012 		if (end != TCP_REASS_SEQ(mp)) {
11013 			mp1->b_cont = NULL;
11014 			break;
11015 		}
11016 		mp1 = mp;
11017 	}
11018 	mp1 = tcp->tcp_reass_head;
11019 	tcp->tcp_reass_head = mp;
11020 	return (mp1);
11021 }
11022 
11023 /* Eliminate any overlap that mp may have over later mblks */
11024 static void
11025 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11026 {
11027 	uint32_t	end;
11028 	mblk_t		*mp1;
11029 	uint32_t	u1;
11030 
11031 	end = TCP_REASS_END(mp);
11032 	while ((mp1 = mp->b_cont) != NULL) {
11033 		u1 = TCP_REASS_SEQ(mp1);
11034 		if (!SEQ_GT(end, u1))
11035 			break;
11036 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11037 			mp->b_wptr -= end - u1;
11038 			TCP_REASS_SET_END(mp, u1);
11039 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11040 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11041 			break;
11042 		}
11043 		mp->b_cont = mp1->b_cont;
11044 		TCP_REASS_SET_SEQ(mp1, 0);
11045 		TCP_REASS_SET_END(mp1, 0);
11046 		freeb(mp1);
11047 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11048 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11049 	}
11050 	if (!mp1)
11051 		tcp->tcp_reass_tail = mp;
11052 }
11053 
11054 /*
11055  * Send up all messages queued on tcp_rcv_list.
11056  */
11057 static uint_t
11058 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11059 {
11060 	mblk_t *mp;
11061 	uint_t ret = 0;
11062 	uint_t thwin;
11063 #ifdef DEBUG
11064 	uint_t cnt = 0;
11065 #endif
11066 	/* Can't drain on an eager connection */
11067 	if (tcp->tcp_listener != NULL)
11068 		return (ret);
11069 
11070 	/*
11071 	 * Handle two cases here: we are currently fused or we were
11072 	 * previously fused and have some urgent data to be delivered
11073 	 * upstream.  The latter happens because we either ran out of
11074 	 * memory or were detached and therefore sending the SIGURG was
11075 	 * deferred until this point.  In either case we pass control
11076 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11077 	 * some work.
11078 	 */
11079 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11080 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11081 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11082 		    &tcp->tcp_fused_sigurg_mp))
11083 			return (ret);
11084 	}
11085 
11086 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11087 		tcp->tcp_rcv_list = mp->b_next;
11088 		mp->b_next = NULL;
11089 #ifdef DEBUG
11090 		cnt += msgdsize(mp);
11091 #endif
11092 		/* Does this need SSL processing first? */
11093 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11094 			tcp_kssl_input(tcp, mp);
11095 			continue;
11096 		}
11097 		putnext(q, mp);
11098 	}
11099 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11100 	tcp->tcp_rcv_last_head = NULL;
11101 	tcp->tcp_rcv_last_tail = NULL;
11102 	tcp->tcp_rcv_cnt = 0;
11103 
11104 	/* Learn the latest rwnd information that we sent to the other side. */
11105 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11106 	    << tcp->tcp_rcv_ws;
11107 	/* This is peer's calculated send window (our receive window). */
11108 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11109 	/*
11110 	 * Increase the receive window to max.  But we need to do receiver
11111 	 * SWS avoidance.  This means that we need to check the increase of
11112 	 * of receive window is at least 1 MSS.
11113 	 */
11114 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11115 		/*
11116 		 * If the window that the other side knows is less than max
11117 		 * deferred acks segments, send an update immediately.
11118 		 */
11119 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11120 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11121 			ret = TH_ACK_NEEDED;
11122 		}
11123 		tcp->tcp_rwnd = q->q_hiwat;
11124 	}
11125 	/* No need for the push timer now. */
11126 	if (tcp->tcp_push_tid != 0) {
11127 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11128 		tcp->tcp_push_tid = 0;
11129 	}
11130 	return (ret);
11131 }
11132 
11133 /*
11134  * Queue data on tcp_rcv_list which is a b_next chain.
11135  * tcp_rcv_last_head/tail is the last element of this chain.
11136  * Each element of the chain is a b_cont chain.
11137  *
11138  * M_DATA messages are added to the current element.
11139  * Other messages are added as new (b_next) elements.
11140  */
11141 void
11142 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11143 {
11144 	ASSERT(seg_len == msgdsize(mp));
11145 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11146 
11147 	if (tcp->tcp_rcv_list == NULL) {
11148 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11149 		tcp->tcp_rcv_list = mp;
11150 		tcp->tcp_rcv_last_head = mp;
11151 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11152 		tcp->tcp_rcv_last_tail->b_cont = mp;
11153 	} else {
11154 		tcp->tcp_rcv_last_head->b_next = mp;
11155 		tcp->tcp_rcv_last_head = mp;
11156 	}
11157 
11158 	while (mp->b_cont)
11159 		mp = mp->b_cont;
11160 
11161 	tcp->tcp_rcv_last_tail = mp;
11162 	tcp->tcp_rcv_cnt += seg_len;
11163 	tcp->tcp_rwnd -= seg_len;
11164 }
11165 
11166 /*
11167  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11168  *
11169  * This is the default entry function into TCP on the read side. TCP is
11170  * always entered via squeue i.e. using squeue's for mutual exclusion.
11171  * When classifier does a lookup to find the tcp, it also puts a reference
11172  * on the conn structure associated so the tcp is guaranteed to exist
11173  * when we come here. We still need to check the state because it might
11174  * as well has been closed. The squeue processing function i.e. squeue_enter,
11175  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11176  * CONN_DEC_REF.
11177  *
11178  * Apart from the default entry point, IP also sends packets directly to
11179  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11180  * connections.
11181  */
11182 void
11183 tcp_input(void *arg, mblk_t *mp, void *arg2)
11184 {
11185 	conn_t	*connp = (conn_t *)arg;
11186 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11187 
11188 	/* arg2 is the sqp */
11189 	ASSERT(arg2 != NULL);
11190 	ASSERT(mp != NULL);
11191 
11192 	/*
11193 	 * Don't accept any input on a closed tcp as this TCP logically does
11194 	 * not exist on the system. Don't proceed further with this TCP.
11195 	 * For eg. this packet could trigger another close of this tcp
11196 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11197 	 * tcp_clean_death / tcp_closei_local must be called at most once
11198 	 * on a TCP. In this case we need to refeed the packet into the
11199 	 * classifier and figure out where the packet should go. Need to
11200 	 * preserve the recv_ill somehow. Until we figure that out, for
11201 	 * now just drop the packet if we can't classify the packet.
11202 	 */
11203 	if (tcp->tcp_state == TCPS_CLOSED ||
11204 	    tcp->tcp_state == TCPS_BOUND) {
11205 		conn_t	*new_connp;
11206 
11207 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11208 		if (new_connp != NULL) {
11209 			tcp_reinput(new_connp, mp, arg2);
11210 			return;
11211 		}
11212 		/* We failed to classify. For now just drop the packet */
11213 		freemsg(mp);
11214 		return;
11215 	}
11216 
11217 	if (DB_TYPE(mp) == M_DATA)
11218 		tcp_rput_data(connp, mp, arg2);
11219 	else
11220 		tcp_rput_common(tcp, mp);
11221 }
11222 
11223 /*
11224  * The read side put procedure.
11225  * The packets passed up by ip are assume to be aligned according to
11226  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11227  */
11228 static void
11229 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11230 {
11231 	/*
11232 	 * tcp_rput_data() does not expect M_CTL except for the case
11233 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11234 	 * type. Need to make sure that any other M_CTLs don't make
11235 	 * it to tcp_rput_data since it is not expecting any and doesn't
11236 	 * check for it.
11237 	 */
11238 	if (DB_TYPE(mp) == M_CTL) {
11239 		switch (*(uint32_t *)(mp->b_rptr)) {
11240 		case TCP_IOC_ABORT_CONN:
11241 			/*
11242 			 * Handle connection abort request.
11243 			 */
11244 			tcp_ioctl_abort_handler(tcp, mp);
11245 			return;
11246 		case IPSEC_IN:
11247 			/*
11248 			 * Only secure icmp arrive in TCP and they
11249 			 * don't go through data path.
11250 			 */
11251 			tcp_icmp_error(tcp, mp);
11252 			return;
11253 		case IN_PKTINFO:
11254 			/*
11255 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11256 			 * sockets that are receiving IPv4 traffic. tcp
11257 			 */
11258 			ASSERT(tcp->tcp_family == AF_INET6);
11259 			ASSERT(tcp->tcp_ipv6_recvancillary &
11260 			    TCP_IPV6_RECVPKTINFO);
11261 			tcp_rput_data(tcp->tcp_connp, mp,
11262 			    tcp->tcp_connp->conn_sqp);
11263 			return;
11264 		case MDT_IOC_INFO_UPDATE:
11265 			/*
11266 			 * Handle Multidata information update; the
11267 			 * following routine will free the message.
11268 			 */
11269 			if (tcp->tcp_connp->conn_mdt_ok) {
11270 				tcp_mdt_update(tcp,
11271 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11272 				    B_FALSE);
11273 			}
11274 			freemsg(mp);
11275 			return;
11276 		default:
11277 			break;
11278 		}
11279 	}
11280 
11281 	/* No point processing the message if tcp is already closed */
11282 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11283 		freemsg(mp);
11284 		return;
11285 	}
11286 
11287 	tcp_rput_other(tcp, mp);
11288 }
11289 
11290 
11291 /* The minimum of smoothed mean deviation in RTO calculation. */
11292 #define	TCP_SD_MIN	400
11293 
11294 /*
11295  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11296  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11297  * are the same as those in Appendix A.2 of that paper.
11298  *
11299  * m = new measurement
11300  * sa = smoothed RTT average (8 * average estimates).
11301  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11302  */
11303 static void
11304 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11305 {
11306 	long m = TICK_TO_MSEC(rtt);
11307 	clock_t sa = tcp->tcp_rtt_sa;
11308 	clock_t sv = tcp->tcp_rtt_sd;
11309 	clock_t rto;
11310 
11311 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11312 	tcp->tcp_rtt_update++;
11313 
11314 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11315 	if (sa != 0) {
11316 		/*
11317 		 * Update average estimator:
11318 		 *	new rtt = 7/8 old rtt + 1/8 Error
11319 		 */
11320 
11321 		/* m is now Error in estimate. */
11322 		m -= sa >> 3;
11323 		if ((sa += m) <= 0) {
11324 			/*
11325 			 * Don't allow the smoothed average to be negative.
11326 			 * We use 0 to denote reinitialization of the
11327 			 * variables.
11328 			 */
11329 			sa = 1;
11330 		}
11331 
11332 		/*
11333 		 * Update deviation estimator:
11334 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11335 		 */
11336 		if (m < 0)
11337 			m = -m;
11338 		m -= sv >> 2;
11339 		sv += m;
11340 	} else {
11341 		/*
11342 		 * This follows BSD's implementation.  So the reinitialized
11343 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11344 		 * link is bandwidth dominated, doubling the window size
11345 		 * during slow start means doubling the RTT.  We want to be
11346 		 * more conservative when we reinitialize our estimates.  3
11347 		 * is just a convenient number.
11348 		 */
11349 		sa = m << 3;
11350 		sv = m << 1;
11351 	}
11352 	if (sv < TCP_SD_MIN) {
11353 		/*
11354 		 * We do not know that if sa captures the delay ACK
11355 		 * effect as in a long train of segments, a receiver
11356 		 * does not delay its ACKs.  So set the minimum of sv
11357 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11358 		 * of BSD DATO.  That means the minimum of mean
11359 		 * deviation is 100 ms.
11360 		 *
11361 		 */
11362 		sv = TCP_SD_MIN;
11363 	}
11364 	tcp->tcp_rtt_sa = sa;
11365 	tcp->tcp_rtt_sd = sv;
11366 	/*
11367 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11368 	 *
11369 	 * Add tcp_rexmit_interval extra in case of extreme environment
11370 	 * where the algorithm fails to work.  The default value of
11371 	 * tcp_rexmit_interval_extra should be 0.
11372 	 *
11373 	 * As we use a finer grained clock than BSD and update
11374 	 * RTO for every ACKs, add in another .25 of RTT to the
11375 	 * deviation of RTO to accomodate burstiness of 1/4 of
11376 	 * window size.
11377 	 */
11378 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11379 
11380 	if (rto > tcp_rexmit_interval_max) {
11381 		tcp->tcp_rto = tcp_rexmit_interval_max;
11382 	} else if (rto < tcp_rexmit_interval_min) {
11383 		tcp->tcp_rto = tcp_rexmit_interval_min;
11384 	} else {
11385 		tcp->tcp_rto = rto;
11386 	}
11387 
11388 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11389 	tcp->tcp_timer_backoff = 0;
11390 }
11391 
11392 /*
11393  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11394  * send queue which starts at the given seq. no.
11395  *
11396  * Parameters:
11397  *	tcp_t *tcp: the tcp instance pointer.
11398  *	uint32_t seq: the starting seq. no of the requested segment.
11399  *	int32_t *off: after the execution, *off will be the offset to
11400  *		the returned mblk which points to the requested seq no.
11401  *		It is the caller's responsibility to send in a non-null off.
11402  *
11403  * Return:
11404  *	A mblk_t pointer pointing to the requested segment in send queue.
11405  */
11406 static mblk_t *
11407 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11408 {
11409 	int32_t	cnt;
11410 	mblk_t	*mp;
11411 
11412 	/* Defensive coding.  Make sure we don't send incorrect data. */
11413 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11414 		return (NULL);
11415 
11416 	cnt = seq - tcp->tcp_suna;
11417 	mp = tcp->tcp_xmit_head;
11418 	while (cnt > 0 && mp != NULL) {
11419 		cnt -= mp->b_wptr - mp->b_rptr;
11420 		if (cnt < 0) {
11421 			cnt += mp->b_wptr - mp->b_rptr;
11422 			break;
11423 		}
11424 		mp = mp->b_cont;
11425 	}
11426 	ASSERT(mp != NULL);
11427 	*off = cnt;
11428 	return (mp);
11429 }
11430 
11431 /*
11432  * This function handles all retransmissions if SACK is enabled for this
11433  * connection.  First it calculates how many segments can be retransmitted
11434  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11435  * segments.  A segment is eligible if sack_cnt for that segment is greater
11436  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11437  * all eligible segments, it checks to see if TCP can send some new segments
11438  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11439  *
11440  * Parameters:
11441  *	tcp_t *tcp: the tcp structure of the connection.
11442  *	uint_t *flags: in return, appropriate value will be set for
11443  *	tcp_rput_data().
11444  */
11445 static void
11446 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11447 {
11448 	notsack_blk_t	*notsack_blk;
11449 	int32_t		usable_swnd;
11450 	int32_t		mss;
11451 	uint32_t	seg_len;
11452 	mblk_t		*xmit_mp;
11453 
11454 	ASSERT(tcp->tcp_sack_info != NULL);
11455 	ASSERT(tcp->tcp_notsack_list != NULL);
11456 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11457 
11458 	/* Defensive coding in case there is a bug... */
11459 	if (tcp->tcp_notsack_list == NULL) {
11460 		return;
11461 	}
11462 	notsack_blk = tcp->tcp_notsack_list;
11463 	mss = tcp->tcp_mss;
11464 
11465 	/*
11466 	 * Limit the num of outstanding data in the network to be
11467 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11468 	 */
11469 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11470 
11471 	/* At least retransmit 1 MSS of data. */
11472 	if (usable_swnd <= 0) {
11473 		usable_swnd = mss;
11474 	}
11475 
11476 	/* Make sure no new RTT samples will be taken. */
11477 	tcp->tcp_csuna = tcp->tcp_snxt;
11478 
11479 	notsack_blk = tcp->tcp_notsack_list;
11480 	while (usable_swnd > 0) {
11481 		mblk_t		*snxt_mp, *tmp_mp;
11482 		tcp_seq		begin = tcp->tcp_sack_snxt;
11483 		tcp_seq		end;
11484 		int32_t		off;
11485 
11486 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11487 			if (SEQ_GT(notsack_blk->end, begin) &&
11488 			    (notsack_blk->sack_cnt >=
11489 			    tcp_dupack_fast_retransmit)) {
11490 				end = notsack_blk->end;
11491 				if (SEQ_LT(begin, notsack_blk->begin)) {
11492 					begin = notsack_blk->begin;
11493 				}
11494 				break;
11495 			}
11496 		}
11497 		/*
11498 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11499 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11500 		 * set to tcp_cwnd_ssthresh.
11501 		 */
11502 		if (notsack_blk == NULL) {
11503 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11504 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11505 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11506 				ASSERT(tcp->tcp_cwnd > 0);
11507 				return;
11508 			} else {
11509 				usable_swnd = usable_swnd / mss;
11510 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11511 				    MAX(usable_swnd * mss, mss);
11512 				*flags |= TH_XMIT_NEEDED;
11513 				return;
11514 			}
11515 		}
11516 
11517 		/*
11518 		 * Note that we may send more than usable_swnd allows here
11519 		 * because of round off, but no more than 1 MSS of data.
11520 		 */
11521 		seg_len = end - begin;
11522 		if (seg_len > mss)
11523 			seg_len = mss;
11524 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11525 		ASSERT(snxt_mp != NULL);
11526 		/* This should not happen.  Defensive coding again... */
11527 		if (snxt_mp == NULL) {
11528 			return;
11529 		}
11530 
11531 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11532 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11533 		if (xmit_mp == NULL)
11534 			return;
11535 
11536 		usable_swnd -= seg_len;
11537 		tcp->tcp_pipe += seg_len;
11538 		tcp->tcp_sack_snxt = begin + seg_len;
11539 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11540 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11541 
11542 		/*
11543 		 * Update the send timestamp to avoid false retransmission.
11544 		 */
11545 		snxt_mp->b_prev = (mblk_t *)lbolt;
11546 
11547 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11548 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11549 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11550 		/*
11551 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11552 		 * This happens when new data sent during fast recovery is
11553 		 * also lost.  If TCP retransmits those new data, it needs
11554 		 * to extend SACK recover phase to avoid starting another
11555 		 * fast retransmit/recovery unnecessarily.
11556 		 */
11557 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11558 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11559 		}
11560 	}
11561 }
11562 
11563 /*
11564  * This function handles policy checking at TCP level for non-hard_bound/
11565  * detached connections.
11566  */
11567 static boolean_t
11568 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11569     boolean_t secure, boolean_t mctl_present)
11570 {
11571 	ipsec_latch_t *ipl = NULL;
11572 	ipsec_action_t *act = NULL;
11573 	mblk_t *data_mp;
11574 	ipsec_in_t *ii;
11575 	const char *reason;
11576 	kstat_named_t *counter;
11577 
11578 	ASSERT(mctl_present || !secure);
11579 
11580 	ASSERT((ipha == NULL && ip6h != NULL) ||
11581 	    (ip6h == NULL && ipha != NULL));
11582 
11583 	/*
11584 	 * We don't necessarily have an ipsec_in_act action to verify
11585 	 * policy because of assymetrical policy where we have only
11586 	 * outbound policy and no inbound policy (possible with global
11587 	 * policy).
11588 	 */
11589 	if (!secure) {
11590 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11591 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11592 			return (B_TRUE);
11593 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11594 		    "tcp_check_policy", ipha, ip6h, secure);
11595 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11596 		    &ipdrops_tcp_clear, &tcp_dropper);
11597 		return (B_FALSE);
11598 	}
11599 
11600 	/*
11601 	 * We have a secure packet.
11602 	 */
11603 	if (act == NULL) {
11604 		ipsec_log_policy_failure(tcp->tcp_wq,
11605 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11606 		    secure);
11607 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11608 		    &ipdrops_tcp_secure, &tcp_dropper);
11609 		return (B_FALSE);
11610 	}
11611 
11612 	/*
11613 	 * XXX This whole routine is currently incorrect.  ipl should
11614 	 * be set to the latch pointer, but is currently not set, so
11615 	 * we initialize it to NULL to avoid picking up random garbage.
11616 	 */
11617 	if (ipl == NULL)
11618 		return (B_TRUE);
11619 
11620 	data_mp = first_mp->b_cont;
11621 
11622 	ii = (ipsec_in_t *)first_mp->b_rptr;
11623 
11624 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11625 	    &counter)) {
11626 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11627 		return (B_TRUE);
11628 	}
11629 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11630 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11631 	    reason);
11632 	BUMP_MIB(&ip_mib, ipsecInFailed);
11633 
11634 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11635 	return (B_FALSE);
11636 }
11637 
11638 /*
11639  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11640  * retransmission after a timeout.
11641  *
11642  * To limit the number of duplicate segments, we limit the number of segment
11643  * to be sent in one time to tcp_snd_burst, the burst variable.
11644  */
11645 static void
11646 tcp_ss_rexmit(tcp_t *tcp)
11647 {
11648 	uint32_t	snxt;
11649 	uint32_t	smax;
11650 	int32_t		win;
11651 	int32_t		mss;
11652 	int32_t		off;
11653 	int32_t		burst = tcp->tcp_snd_burst;
11654 	mblk_t		*snxt_mp;
11655 
11656 	/*
11657 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11658 	 * all unack'ed segments.
11659 	 */
11660 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11661 		smax = tcp->tcp_rexmit_max;
11662 		snxt = tcp->tcp_rexmit_nxt;
11663 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11664 			snxt = tcp->tcp_suna;
11665 		}
11666 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11667 		win -= snxt - tcp->tcp_suna;
11668 		mss = tcp->tcp_mss;
11669 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11670 
11671 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11672 		    (burst > 0) && (snxt_mp != NULL)) {
11673 			mblk_t	*xmit_mp;
11674 			mblk_t	*old_snxt_mp = snxt_mp;
11675 			uint32_t cnt = mss;
11676 
11677 			if (win < cnt) {
11678 				cnt = win;
11679 			}
11680 			if (SEQ_GT(snxt + cnt, smax)) {
11681 				cnt = smax - snxt;
11682 			}
11683 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11684 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11685 			if (xmit_mp == NULL)
11686 				return;
11687 
11688 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11689 
11690 			snxt += cnt;
11691 			win -= cnt;
11692 			/*
11693 			 * Update the send timestamp to avoid false
11694 			 * retransmission.
11695 			 */
11696 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11697 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11698 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11699 
11700 			tcp->tcp_rexmit_nxt = snxt;
11701 			burst--;
11702 		}
11703 		/*
11704 		 * If we have transmitted all we have at the time
11705 		 * we started the retranmission, we can leave
11706 		 * the rest of the job to tcp_wput_data().  But we
11707 		 * need to check the send window first.  If the
11708 		 * win is not 0, go on with tcp_wput_data().
11709 		 */
11710 		if (SEQ_LT(snxt, smax) || win == 0) {
11711 			return;
11712 		}
11713 	}
11714 	/* Only call tcp_wput_data() if there is data to be sent. */
11715 	if (tcp->tcp_unsent) {
11716 		tcp_wput_data(tcp, NULL, B_FALSE);
11717 	}
11718 }
11719 
11720 /*
11721  * Process all TCP option in SYN segment.  Note that this function should
11722  * be called after tcp_adapt_ire() is called so that the necessary info
11723  * from IRE is already set in the tcp structure.
11724  *
11725  * This function sets up the correct tcp_mss value according to the
11726  * MSS option value and our header size.  It also sets up the window scale
11727  * and timestamp values, and initialize SACK info blocks.  But it does not
11728  * change receive window size after setting the tcp_mss value.  The caller
11729  * should do the appropriate change.
11730  */
11731 void
11732 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11733 {
11734 	int options;
11735 	tcp_opt_t tcpopt;
11736 	uint32_t mss_max;
11737 	char *tmp_tcph;
11738 
11739 	tcpopt.tcp = NULL;
11740 	options = tcp_parse_options(tcph, &tcpopt);
11741 
11742 	/*
11743 	 * Process MSS option.  Note that MSS option value does not account
11744 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11745 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11746 	 * IPv6.
11747 	 */
11748 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11749 		if (tcp->tcp_ipversion == IPV4_VERSION)
11750 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11751 		else
11752 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11753 	} else {
11754 		if (tcp->tcp_ipversion == IPV4_VERSION)
11755 			mss_max = tcp_mss_max_ipv4;
11756 		else
11757 			mss_max = tcp_mss_max_ipv6;
11758 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11759 			tcpopt.tcp_opt_mss = tcp_mss_min;
11760 		else if (tcpopt.tcp_opt_mss > mss_max)
11761 			tcpopt.tcp_opt_mss = mss_max;
11762 	}
11763 
11764 	/* Process Window Scale option. */
11765 	if (options & TCP_OPT_WSCALE_PRESENT) {
11766 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11767 		tcp->tcp_snd_ws_ok = B_TRUE;
11768 	} else {
11769 		tcp->tcp_snd_ws = B_FALSE;
11770 		tcp->tcp_snd_ws_ok = B_FALSE;
11771 		tcp->tcp_rcv_ws = B_FALSE;
11772 	}
11773 
11774 	/* Process Timestamp option. */
11775 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11776 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11777 		tmp_tcph = (char *)tcp->tcp_tcph;
11778 
11779 		tcp->tcp_snd_ts_ok = B_TRUE;
11780 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11781 		tcp->tcp_last_rcv_lbolt = lbolt64;
11782 		ASSERT(OK_32PTR(tmp_tcph));
11783 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11784 
11785 		/* Fill in our template header with basic timestamp option. */
11786 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11787 		tmp_tcph[0] = TCPOPT_NOP;
11788 		tmp_tcph[1] = TCPOPT_NOP;
11789 		tmp_tcph[2] = TCPOPT_TSTAMP;
11790 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
11791 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11792 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11793 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
11794 	} else {
11795 		tcp->tcp_snd_ts_ok = B_FALSE;
11796 	}
11797 
11798 	/*
11799 	 * Process SACK options.  If SACK is enabled for this connection,
11800 	 * then allocate the SACK info structure.  Note the following ways
11801 	 * when tcp_snd_sack_ok is set to true.
11802 	 *
11803 	 * For active connection: in tcp_adapt_ire() called in
11804 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
11805 	 * is checked.
11806 	 *
11807 	 * For passive connection: in tcp_adapt_ire() called in
11808 	 * tcp_accept_comm().
11809 	 *
11810 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
11811 	 * That check makes sure that if we did not send a SACK OK option,
11812 	 * we will not enable SACK for this connection even though the other
11813 	 * side sends us SACK OK option.  For active connection, the SACK
11814 	 * info structure has already been allocated.  So we need to free
11815 	 * it if SACK is disabled.
11816 	 */
11817 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
11818 	    (tcp->tcp_snd_sack_ok ||
11819 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
11820 		/* This should be true only in the passive case. */
11821 		if (tcp->tcp_sack_info == NULL) {
11822 			ASSERT(TCP_IS_DETACHED(tcp));
11823 			tcp->tcp_sack_info =
11824 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
11825 		}
11826 		if (tcp->tcp_sack_info == NULL) {
11827 			tcp->tcp_snd_sack_ok = B_FALSE;
11828 		} else {
11829 			tcp->tcp_snd_sack_ok = B_TRUE;
11830 			if (tcp->tcp_snd_ts_ok) {
11831 				tcp->tcp_max_sack_blk = 3;
11832 			} else {
11833 				tcp->tcp_max_sack_blk = 4;
11834 			}
11835 		}
11836 	} else {
11837 		/*
11838 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
11839 		 * no SACK info will be used for this
11840 		 * connection.  This assumes that SACK usage
11841 		 * permission is negotiated.  This may need
11842 		 * to be changed once this is clarified.
11843 		 */
11844 		if (tcp->tcp_sack_info != NULL) {
11845 			ASSERT(tcp->tcp_notsack_list == NULL);
11846 			kmem_cache_free(tcp_sack_info_cache,
11847 			    tcp->tcp_sack_info);
11848 			tcp->tcp_sack_info = NULL;
11849 		}
11850 		tcp->tcp_snd_sack_ok = B_FALSE;
11851 	}
11852 
11853 	/*
11854 	 * Now we know the exact TCP/IP header length, subtract
11855 	 * that from tcp_mss to get our side's MSS.
11856 	 */
11857 	tcp->tcp_mss -= tcp->tcp_hdr_len;
11858 	/*
11859 	 * Here we assume that the other side's header size will be equal to
11860 	 * our header size.  We calculate the real MSS accordingly.  Need to
11861 	 * take into additional stuffs IPsec puts in.
11862 	 *
11863 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
11864 	 */
11865 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
11866 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
11867 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
11868 
11869 	/*
11870 	 * Set MSS to the smaller one of both ends of the connection.
11871 	 * We should not have called tcp_mss_set() before, but our
11872 	 * side of the MSS should have been set to a proper value
11873 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
11874 	 * STREAM head parameters properly.
11875 	 *
11876 	 * If we have a larger-than-16-bit window but the other side
11877 	 * didn't want to do window scale, tcp_rwnd_set() will take
11878 	 * care of that.
11879 	 */
11880 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
11881 }
11882 
11883 /*
11884  * Sends the T_CONN_IND to the listener. The caller calls this
11885  * functions via squeue to get inside the listener's perimeter
11886  * once the 3 way hand shake is done a T_CONN_IND needs to be
11887  * sent. As an optimization, the caller can call this directly
11888  * if listener's perimeter is same as eager's.
11889  */
11890 /* ARGSUSED */
11891 void
11892 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
11893 {
11894 	conn_t			*lconnp = (conn_t *)arg;
11895 	tcp_t			*listener = lconnp->conn_tcp;
11896 	tcp_t			*tcp;
11897 	struct T_conn_ind	*conn_ind;
11898 	ipaddr_t 		*addr_cache;
11899 	boolean_t		need_send_conn_ind = B_FALSE;
11900 
11901 	/* retrieve the eager */
11902 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
11903 	ASSERT(conn_ind->OPT_offset != 0 &&
11904 	    conn_ind->OPT_length == sizeof (intptr_t));
11905 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
11906 		conn_ind->OPT_length);
11907 
11908 	/*
11909 	 * TLI/XTI applications will get confused by
11910 	 * sending eager as an option since it violates
11911 	 * the option semantics. So remove the eager as
11912 	 * option since TLI/XTI app doesn't need it anyway.
11913 	 */
11914 	if (!TCP_IS_SOCKET(listener)) {
11915 		conn_ind->OPT_length = 0;
11916 		conn_ind->OPT_offset = 0;
11917 	}
11918 	if (listener->tcp_state == TCPS_CLOSED ||
11919 	    TCP_IS_DETACHED(listener)) {
11920 		/*
11921 		 * If listener has closed, it would have caused a
11922 		 * a cleanup/blowoff to happen for the eager. We
11923 		 * just need to return.
11924 		 */
11925 		freemsg(mp);
11926 		return;
11927 	}
11928 
11929 
11930 	/*
11931 	 * if the conn_req_q is full defer passing up the
11932 	 * T_CONN_IND until space is availabe after t_accept()
11933 	 * processing
11934 	 */
11935 	mutex_enter(&listener->tcp_eager_lock);
11936 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
11937 		tcp_t *tail;
11938 
11939 		/*
11940 		 * The eager already has an extra ref put in tcp_rput_data
11941 		 * so that it stays till accept comes back even though it
11942 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
11943 		 */
11944 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
11945 		listener->tcp_conn_req_cnt_q0--;
11946 		listener->tcp_conn_req_cnt_q++;
11947 
11948 		/* Move from SYN_RCVD to ESTABLISHED list  */
11949 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11950 		    tcp->tcp_eager_prev_q0;
11951 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11952 		    tcp->tcp_eager_next_q0;
11953 		tcp->tcp_eager_prev_q0 = NULL;
11954 		tcp->tcp_eager_next_q0 = NULL;
11955 
11956 		/*
11957 		 * Insert at end of the queue because sockfs
11958 		 * sends down T_CONN_RES in chronological
11959 		 * order. Leaving the older conn indications
11960 		 * at front of the queue helps reducing search
11961 		 * time.
11962 		 */
11963 		tail = listener->tcp_eager_last_q;
11964 		if (tail != NULL)
11965 			tail->tcp_eager_next_q = tcp;
11966 		else
11967 			listener->tcp_eager_next_q = tcp;
11968 		listener->tcp_eager_last_q = tcp;
11969 		tcp->tcp_eager_next_q = NULL;
11970 		/*
11971 		 * Delay sending up the T_conn_ind until we are
11972 		 * done with the eager. Once we have have sent up
11973 		 * the T_conn_ind, the accept can potentially complete
11974 		 * any time and release the refhold we have on the eager.
11975 		 */
11976 		need_send_conn_ind = B_TRUE;
11977 	} else {
11978 		/*
11979 		 * Defer connection on q0 and set deferred
11980 		 * connection bit true
11981 		 */
11982 		tcp->tcp_conn_def_q0 = B_TRUE;
11983 
11984 		/* take tcp out of q0 ... */
11985 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
11986 		    tcp->tcp_eager_next_q0;
11987 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
11988 		    tcp->tcp_eager_prev_q0;
11989 
11990 		/* ... and place it at the end of q0 */
11991 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
11992 		tcp->tcp_eager_next_q0 = listener;
11993 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
11994 		listener->tcp_eager_prev_q0 = tcp;
11995 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
11996 	}
11997 
11998 	/* we have timed out before */
11999 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12000 		tcp->tcp_syn_rcvd_timeout = 0;
12001 		listener->tcp_syn_rcvd_timeout--;
12002 		if (listener->tcp_syn_defense &&
12003 		    listener->tcp_syn_rcvd_timeout <=
12004 		    (tcp_conn_req_max_q0 >> 5) &&
12005 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12006 			listener->tcp_last_rcv_lbolt)) {
12007 			/*
12008 			 * Turn off the defense mode if we
12009 			 * believe the SYN attack is over.
12010 			 */
12011 			listener->tcp_syn_defense = B_FALSE;
12012 			if (listener->tcp_ip_addr_cache) {
12013 				kmem_free((void *)listener->tcp_ip_addr_cache,
12014 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12015 				listener->tcp_ip_addr_cache = NULL;
12016 			}
12017 		}
12018 	}
12019 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12020 	if (addr_cache != NULL) {
12021 		/*
12022 		 * We have finished a 3-way handshake with this
12023 		 * remote host. This proves the IP addr is good.
12024 		 * Cache it!
12025 		 */
12026 		addr_cache[IP_ADDR_CACHE_HASH(
12027 			tcp->tcp_remote)] = tcp->tcp_remote;
12028 	}
12029 	mutex_exit(&listener->tcp_eager_lock);
12030 	if (need_send_conn_ind)
12031 		putnext(listener->tcp_rq, mp);
12032 }
12033 
12034 mblk_t *
12035 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12036     uint_t *ifindexp, ip6_pkt_t *ippp)
12037 {
12038 	in_pktinfo_t	*pinfo;
12039 	ip6_t		*ip6h;
12040 	uchar_t		*rptr;
12041 	mblk_t		*first_mp = mp;
12042 	boolean_t	mctl_present = B_FALSE;
12043 	uint_t 		ifindex = 0;
12044 	ip6_pkt_t	ipp;
12045 	uint_t		ipvers;
12046 	uint_t		ip_hdr_len;
12047 
12048 	rptr = mp->b_rptr;
12049 	ASSERT(OK_32PTR(rptr));
12050 	ASSERT(tcp != NULL);
12051 	ipp.ipp_fields = 0;
12052 
12053 	switch DB_TYPE(mp) {
12054 	case M_CTL:
12055 		mp = mp->b_cont;
12056 		if (mp == NULL) {
12057 			freemsg(first_mp);
12058 			return (NULL);
12059 		}
12060 		if (DB_TYPE(mp) != M_DATA) {
12061 			freemsg(first_mp);
12062 			return (NULL);
12063 		}
12064 		mctl_present = B_TRUE;
12065 		break;
12066 	case M_DATA:
12067 		break;
12068 	default:
12069 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12070 		freemsg(mp);
12071 		return (NULL);
12072 	}
12073 	ipvers = IPH_HDR_VERSION(rptr);
12074 	if (ipvers == IPV4_VERSION) {
12075 		if (tcp == NULL) {
12076 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12077 			goto done;
12078 		}
12079 
12080 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12081 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12082 
12083 		/*
12084 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12085 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12086 		 */
12087 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12088 		    mctl_present) {
12089 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12090 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12091 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12092 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12093 				ipp.ipp_fields |= IPPF_IFINDEX;
12094 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12095 				ifindex = pinfo->in_pkt_ifindex;
12096 			}
12097 			freeb(first_mp);
12098 			mctl_present = B_FALSE;
12099 		}
12100 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12101 	} else {
12102 		ip6h = (ip6_t *)rptr;
12103 
12104 		ASSERT(ipvers == IPV6_VERSION);
12105 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12106 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12107 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12108 
12109 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12110 			uint8_t	nexthdrp;
12111 
12112 			/* Look for ifindex information */
12113 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12114 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12115 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12116 					BUMP_MIB(&ip_mib, tcpInErrs);
12117 					freemsg(first_mp);
12118 					return (NULL);
12119 				}
12120 
12121 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12122 					ASSERT(ip6i->ip6i_ifindex != 0);
12123 					ipp.ipp_fields |= IPPF_IFINDEX;
12124 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12125 					ifindex = ip6i->ip6i_ifindex;
12126 				}
12127 				rptr = (uchar_t *)&ip6i[1];
12128 				mp->b_rptr = rptr;
12129 				if (rptr == mp->b_wptr) {
12130 					mblk_t *mp1;
12131 					mp1 = mp->b_cont;
12132 					freeb(mp);
12133 					mp = mp1;
12134 					rptr = mp->b_rptr;
12135 				}
12136 				if (MBLKL(mp) < IPV6_HDR_LEN +
12137 				    sizeof (tcph_t)) {
12138 					BUMP_MIB(&ip_mib, tcpInErrs);
12139 					freemsg(first_mp);
12140 					return (NULL);
12141 				}
12142 				ip6h = (ip6_t *)rptr;
12143 			}
12144 
12145 			/*
12146 			 * Find any potentially interesting extension headers
12147 			 * as well as the length of the IPv6 + extension
12148 			 * headers.
12149 			 */
12150 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12151 			/* Verify if this is a TCP packet */
12152 			if (nexthdrp != IPPROTO_TCP) {
12153 				BUMP_MIB(&ip_mib, tcpInErrs);
12154 				freemsg(first_mp);
12155 				return (NULL);
12156 			}
12157 		} else {
12158 			ip_hdr_len = IPV6_HDR_LEN;
12159 		}
12160 	}
12161 
12162 done:
12163 	if (ipversp != NULL)
12164 		*ipversp = ipvers;
12165 	if (ip_hdr_lenp != NULL)
12166 		*ip_hdr_lenp = ip_hdr_len;
12167 	if (ippp != NULL)
12168 		*ippp = ipp;
12169 	if (ifindexp != NULL)
12170 		*ifindexp = ifindex;
12171 	if (mctl_present) {
12172 		freeb(first_mp);
12173 	}
12174 	return (mp);
12175 }
12176 
12177 /*
12178  * Handle M_DATA messages from IP. Its called directly from IP via
12179  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12180  * in this path.
12181  *
12182  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12183  * v4 and v6), we are called through tcp_input() and a M_CTL can
12184  * be present for options but tcp_find_pktinfo() deals with it. We
12185  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12186  *
12187  * The first argument is always the connp/tcp to which the mp belongs.
12188  * There are no exceptions to this rule. The caller has already put
12189  * a reference on this connp/tcp and once tcp_rput_data() returns,
12190  * the squeue will do the refrele.
12191  *
12192  * The TH_SYN for the listener directly go to tcp_conn_request via
12193  * squeue.
12194  *
12195  * sqp: NULL = recursive, sqp != NULL means called from squeue
12196  */
12197 void
12198 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12199 {
12200 	int32_t		bytes_acked;
12201 	int32_t		gap;
12202 	mblk_t		*mp1;
12203 	uint_t		flags;
12204 	uint32_t	new_swnd = 0;
12205 	uchar_t		*iphdr;
12206 	uchar_t		*rptr;
12207 	int32_t		rgap;
12208 	uint32_t	seg_ack;
12209 	int		seg_len;
12210 	uint_t		ip_hdr_len;
12211 	uint32_t	seg_seq;
12212 	tcph_t		*tcph;
12213 	int		urp;
12214 	tcp_opt_t	tcpopt;
12215 	uint_t		ipvers;
12216 	ip6_pkt_t	ipp;
12217 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12218 	uint32_t	cwnd;
12219 	uint32_t	add;
12220 	int		npkt;
12221 	int		mss;
12222 	conn_t		*connp = (conn_t *)arg;
12223 	squeue_t	*sqp = (squeue_t *)arg2;
12224 	tcp_t		*tcp = connp->conn_tcp;
12225 
12226 	/*
12227 	 * RST from fused tcp loopback peer should trigger an unfuse.
12228 	 */
12229 	if (tcp->tcp_fused) {
12230 		TCP_STAT(tcp_fusion_aborted);
12231 		tcp_unfuse(tcp);
12232 	}
12233 
12234 	iphdr = mp->b_rptr;
12235 	rptr = mp->b_rptr;
12236 	ASSERT(OK_32PTR(rptr));
12237 
12238 	/*
12239 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12240 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12241 	 * necessary information.
12242 	 */
12243 	if (IPCL_IS_TCP4(connp)) {
12244 		ipvers = IPV4_VERSION;
12245 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12246 	} else {
12247 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12248 		    NULL, &ipp);
12249 		if (mp == NULL) {
12250 			TCP_STAT(tcp_rput_v6_error);
12251 			return;
12252 		}
12253 		iphdr = mp->b_rptr;
12254 		rptr = mp->b_rptr;
12255 	}
12256 	ASSERT(DB_TYPE(mp) == M_DATA);
12257 
12258 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12259 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12260 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12261 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12262 	seg_len = (int)(mp->b_wptr - rptr) -
12263 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12264 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12265 		do {
12266 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12267 			    (uintptr_t)INT_MAX);
12268 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12269 		} while ((mp1 = mp1->b_cont) != NULL &&
12270 		    mp1->b_datap->db_type == M_DATA);
12271 	}
12272 
12273 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12274 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12275 		    seg_len, tcph);
12276 		return;
12277 	}
12278 
12279 	if (sqp != NULL) {
12280 		/*
12281 		 * This is the correct place to update tcp_last_recv_time. Note
12282 		 * that it is also updated for tcp structure that belongs to
12283 		 * global and listener queues which do not really need updating.
12284 		 * But that should not cause any harm.  And it is updated for
12285 		 * all kinds of incoming segments, not only for data segments.
12286 		 */
12287 		tcp->tcp_last_recv_time = lbolt;
12288 	}
12289 
12290 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12291 
12292 	BUMP_LOCAL(tcp->tcp_ibsegs);
12293 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12294 
12295 	if ((flags & TH_URG) && sqp != NULL) {
12296 		/*
12297 		 * TCP can't handle urgent pointers that arrive before
12298 		 * the connection has been accept()ed since it can't
12299 		 * buffer OOB data.  Discard segment if this happens.
12300 		 *
12301 		 * Nor can it reassemble urgent pointers, so discard
12302 		 * if it's not the next segment expected.
12303 		 *
12304 		 * Otherwise, collapse chain into one mblk (discard if
12305 		 * that fails).  This makes sure the headers, retransmitted
12306 		 * data, and new data all are in the same mblk.
12307 		 */
12308 		ASSERT(mp != NULL);
12309 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12310 			freemsg(mp);
12311 			return;
12312 		}
12313 		/* Update pointers into message */
12314 		iphdr = rptr = mp->b_rptr;
12315 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12316 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12317 			/*
12318 			 * Since we can't handle any data with this urgent
12319 			 * pointer that is out of sequence, we expunge
12320 			 * the data.  This allows us to still register
12321 			 * the urgent mark and generate the M_PCSIG,
12322 			 * which we can do.
12323 			 */
12324 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12325 			seg_len = 0;
12326 		}
12327 	}
12328 
12329 	switch (tcp->tcp_state) {
12330 	case TCPS_SYN_SENT:
12331 		if (flags & TH_ACK) {
12332 			/*
12333 			 * Note that our stack cannot send data before a
12334 			 * connection is established, therefore the
12335 			 * following check is valid.  Otherwise, it has
12336 			 * to be changed.
12337 			 */
12338 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12339 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12340 				freemsg(mp);
12341 				if (flags & TH_RST)
12342 					return;
12343 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12344 				    tcp, seg_ack, 0, TH_RST);
12345 				return;
12346 			}
12347 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12348 		}
12349 		if (flags & TH_RST) {
12350 			freemsg(mp);
12351 			if (flags & TH_ACK)
12352 				(void) tcp_clean_death(tcp,
12353 				    ECONNREFUSED, 13);
12354 			return;
12355 		}
12356 		if (!(flags & TH_SYN)) {
12357 			freemsg(mp);
12358 			return;
12359 		}
12360 
12361 		/* Process all TCP options. */
12362 		tcp_process_options(tcp, tcph);
12363 		/*
12364 		 * The following changes our rwnd to be a multiple of the
12365 		 * MIN(peer MSS, our MSS) for performance reason.
12366 		 */
12367 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12368 		    tcp->tcp_mss));
12369 
12370 		/* Is the other end ECN capable? */
12371 		if (tcp->tcp_ecn_ok) {
12372 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12373 				tcp->tcp_ecn_ok = B_FALSE;
12374 			}
12375 		}
12376 		/*
12377 		 * Clear ECN flags because it may interfere with later
12378 		 * processing.
12379 		 */
12380 		flags &= ~(TH_ECE|TH_CWR);
12381 
12382 		tcp->tcp_irs = seg_seq;
12383 		tcp->tcp_rack = seg_seq;
12384 		tcp->tcp_rnxt = seg_seq + 1;
12385 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12386 		if (!TCP_IS_DETACHED(tcp)) {
12387 			/* Allocate room for SACK options if needed. */
12388 			if (tcp->tcp_snd_sack_ok) {
12389 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12390 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12391 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12392 			} else {
12393 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12394 				    tcp->tcp_hdr_len +
12395 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12396 			}
12397 		}
12398 		if (flags & TH_ACK) {
12399 			/*
12400 			 * If we can't get the confirmation upstream, pretend
12401 			 * we didn't even see this one.
12402 			 *
12403 			 * XXX: how can we pretend we didn't see it if we
12404 			 * have updated rnxt et. al.
12405 			 *
12406 			 * For loopback we defer sending up the T_CONN_CON
12407 			 * until after some checks below.
12408 			 */
12409 			mp1 = NULL;
12410 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12411 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12412 				freemsg(mp);
12413 				return;
12414 			}
12415 			/* SYN was acked - making progress */
12416 			if (tcp->tcp_ipversion == IPV6_VERSION)
12417 				tcp->tcp_ip_forward_progress = B_TRUE;
12418 
12419 			/* One for the SYN */
12420 			tcp->tcp_suna = tcp->tcp_iss + 1;
12421 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12422 			tcp->tcp_state = TCPS_ESTABLISHED;
12423 
12424 			/*
12425 			 * If SYN was retransmitted, need to reset all
12426 			 * retransmission info.  This is because this
12427 			 * segment will be treated as a dup ACK.
12428 			 */
12429 			if (tcp->tcp_rexmit) {
12430 				tcp->tcp_rexmit = B_FALSE;
12431 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12432 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12433 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12434 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12435 				tcp->tcp_ms_we_have_waited = 0;
12436 
12437 				/*
12438 				 * Set tcp_cwnd back to 1 MSS, per
12439 				 * recommendation from
12440 				 * draft-floyd-incr-init-win-01.txt,
12441 				 * Increasing TCP's Initial Window.
12442 				 */
12443 				tcp->tcp_cwnd = tcp->tcp_mss;
12444 			}
12445 
12446 			tcp->tcp_swl1 = seg_seq;
12447 			tcp->tcp_swl2 = seg_ack;
12448 
12449 			new_swnd = BE16_TO_U16(tcph->th_win);
12450 			tcp->tcp_swnd = new_swnd;
12451 			if (new_swnd > tcp->tcp_max_swnd)
12452 				tcp->tcp_max_swnd = new_swnd;
12453 
12454 			/*
12455 			 * Always send the three-way handshake ack immediately
12456 			 * in order to make the connection complete as soon as
12457 			 * possible on the accepting host.
12458 			 */
12459 			flags |= TH_ACK_NEEDED;
12460 
12461 			/*
12462 			 * Special case for loopback.  At this point we have
12463 			 * received SYN-ACK from the remote endpoint.  In
12464 			 * order to ensure that both endpoints reach the
12465 			 * fused state prior to any data exchange, the final
12466 			 * ACK needs to be sent before we indicate T_CONN_CON
12467 			 * to the module upstream.
12468 			 */
12469 			if (tcp->tcp_loopback) {
12470 				mblk_t *ack_mp;
12471 
12472 				ASSERT(!tcp->tcp_unfusable);
12473 				ASSERT(mp1 != NULL);
12474 				/*
12475 				 * For loopback, we always get a pure SYN-ACK
12476 				 * and only need to send back the final ACK
12477 				 * with no data (this is because the other
12478 				 * tcp is ours and we don't do T/TCP).  This
12479 				 * final ACK triggers the passive side to
12480 				 * perform fusion in ESTABLISHED state.
12481 				 */
12482 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12483 					if (tcp->tcp_ack_tid != 0) {
12484 						(void) TCP_TIMER_CANCEL(tcp,
12485 						    tcp->tcp_ack_tid);
12486 						tcp->tcp_ack_tid = 0;
12487 					}
12488 					TCP_RECORD_TRACE(tcp, ack_mp,
12489 					    TCP_TRACE_SEND_PKT);
12490 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12491 					BUMP_LOCAL(tcp->tcp_obsegs);
12492 					BUMP_MIB(&tcp_mib, tcpOutAck);
12493 
12494 					/* Send up T_CONN_CON */
12495 					putnext(tcp->tcp_rq, mp1);
12496 
12497 					freemsg(mp);
12498 					return;
12499 				}
12500 				/*
12501 				 * Forget fusion; we need to handle more
12502 				 * complex cases below.  Send the deferred
12503 				 * T_CONN_CON message upstream and proceed
12504 				 * as usual.  Mark this tcp as not capable
12505 				 * of fusion.
12506 				 */
12507 				TCP_STAT(tcp_fusion_unfusable);
12508 				tcp->tcp_unfusable = B_TRUE;
12509 				putnext(tcp->tcp_rq, mp1);
12510 			}
12511 
12512 			/*
12513 			 * Check to see if there is data to be sent.  If
12514 			 * yes, set the transmit flag.  Then check to see
12515 			 * if received data processing needs to be done.
12516 			 * If not, go straight to xmit_check.  This short
12517 			 * cut is OK as we don't support T/TCP.
12518 			 */
12519 			if (tcp->tcp_unsent)
12520 				flags |= TH_XMIT_NEEDED;
12521 
12522 			if (seg_len == 0 && !(flags & TH_URG)) {
12523 				freemsg(mp);
12524 				goto xmit_check;
12525 			}
12526 
12527 			flags &= ~TH_SYN;
12528 			seg_seq++;
12529 			break;
12530 		}
12531 		tcp->tcp_state = TCPS_SYN_RCVD;
12532 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12533 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12534 		if (mp1) {
12535 			mblk_setcred(mp1, tcp->tcp_cred);
12536 			DB_CPID(mp1) = tcp->tcp_cpid;
12537 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12538 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12539 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12540 		}
12541 		freemsg(mp);
12542 		return;
12543 	case TCPS_SYN_RCVD:
12544 		if (flags & TH_ACK) {
12545 			/*
12546 			 * In this state, a SYN|ACK packet is either bogus
12547 			 * because the other side must be ACKing our SYN which
12548 			 * indicates it has seen the ACK for their SYN and
12549 			 * shouldn't retransmit it or we're crossing SYNs
12550 			 * on active open.
12551 			 */
12552 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12553 				freemsg(mp);
12554 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12555 				    tcp, seg_ack, 0, TH_RST);
12556 				return;
12557 			}
12558 			/*
12559 			 * NOTE: RFC 793 pg. 72 says this should be
12560 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12561 			 * but that would mean we have an ack that ignored
12562 			 * our SYN.
12563 			 */
12564 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12565 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12566 				freemsg(mp);
12567 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12568 				    tcp, seg_ack, 0, TH_RST);
12569 				return;
12570 			}
12571 		}
12572 		break;
12573 	case TCPS_LISTEN:
12574 		/*
12575 		 * Only a TLI listener can come through this path when a
12576 		 * acceptor is going back to be a listener and a packet
12577 		 * for the acceptor hits the classifier. For a socket
12578 		 * listener, this can never happen because a listener
12579 		 * can never accept connection on itself and hence a
12580 		 * socket acceptor can not go back to being a listener.
12581 		 */
12582 		ASSERT(!TCP_IS_SOCKET(tcp));
12583 		/*FALLTHRU*/
12584 	case TCPS_CLOSED:
12585 	case TCPS_BOUND: {
12586 		conn_t	*new_connp;
12587 
12588 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12589 		if (new_connp != NULL) {
12590 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12591 			return;
12592 		}
12593 		/* We failed to classify. For now just drop the packet */
12594 		freemsg(mp);
12595 		return;
12596 	}
12597 	case TCPS_IDLE:
12598 		/*
12599 		 * Handle the case where the tcp_clean_death() has happened
12600 		 * on a connection (application hasn't closed yet) but a packet
12601 		 * was already queued on squeue before tcp_clean_death()
12602 		 * was processed. Calling tcp_clean_death() twice on same
12603 		 * connection can result in weird behaviour.
12604 		 */
12605 		freemsg(mp);
12606 		return;
12607 	default:
12608 		break;
12609 	}
12610 
12611 	/*
12612 	 * Already on the correct queue/perimeter.
12613 	 * If this is a detached connection and not an eager
12614 	 * connection hanging off a listener then new data
12615 	 * (past the FIN) will cause a reset.
12616 	 * We do a special check here where it
12617 	 * is out of the main line, rather than check
12618 	 * if we are detached every time we see new
12619 	 * data down below.
12620 	 */
12621 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12622 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12623 		BUMP_MIB(&tcp_mib, tcpInClosed);
12624 		TCP_RECORD_TRACE(tcp,
12625 		    mp, TCP_TRACE_RECV_PKT);
12626 
12627 		freemsg(mp);
12628 		/*
12629 		 * This could be an SSL closure alert. We're detached so just
12630 		 * acknowledge it this last time.
12631 		 */
12632 		if (tcp->tcp_kssl_ctx != NULL) {
12633 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12634 			tcp->tcp_kssl_ctx = NULL;
12635 
12636 			tcp->tcp_rnxt += seg_len;
12637 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12638 			flags |= TH_ACK_NEEDED;
12639 			goto ack_check;
12640 		}
12641 
12642 		tcp_xmit_ctl("new data when detached", tcp,
12643 		    tcp->tcp_snxt, 0, TH_RST);
12644 		(void) tcp_clean_death(tcp, EPROTO, 12);
12645 		return;
12646 	}
12647 
12648 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12649 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12650 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12651 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12652 	mss = tcp->tcp_mss;
12653 
12654 	if (tcp->tcp_snd_ts_ok) {
12655 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12656 			/*
12657 			 * This segment is not acceptable.
12658 			 * Drop it and send back an ACK.
12659 			 */
12660 			freemsg(mp);
12661 			flags |= TH_ACK_NEEDED;
12662 			goto ack_check;
12663 		}
12664 	} else if (tcp->tcp_snd_sack_ok) {
12665 		ASSERT(tcp->tcp_sack_info != NULL);
12666 		tcpopt.tcp = tcp;
12667 		/*
12668 		 * SACK info in already updated in tcp_parse_options.  Ignore
12669 		 * all other TCP options...
12670 		 */
12671 		(void) tcp_parse_options(tcph, &tcpopt);
12672 	}
12673 try_again:;
12674 	gap = seg_seq - tcp->tcp_rnxt;
12675 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12676 	/*
12677 	 * gap is the amount of sequence space between what we expect to see
12678 	 * and what we got for seg_seq.  A positive value for gap means
12679 	 * something got lost.  A negative value means we got some old stuff.
12680 	 */
12681 	if (gap < 0) {
12682 		/* Old stuff present.  Is the SYN in there? */
12683 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12684 		    (seg_len != 0)) {
12685 			flags &= ~TH_SYN;
12686 			seg_seq++;
12687 			urp--;
12688 			/* Recompute the gaps after noting the SYN. */
12689 			goto try_again;
12690 		}
12691 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12692 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12693 		    (seg_len > -gap ? -gap : seg_len));
12694 		/* Remove the old stuff from seg_len. */
12695 		seg_len += gap;
12696 		/*
12697 		 * Anything left?
12698 		 * Make sure to check for unack'd FIN when rest of data
12699 		 * has been previously ack'd.
12700 		 */
12701 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12702 			/*
12703 			 * Resets are only valid if they lie within our offered
12704 			 * window.  If the RST bit is set, we just ignore this
12705 			 * segment.
12706 			 */
12707 			if (flags & TH_RST) {
12708 				freemsg(mp);
12709 				return;
12710 			}
12711 
12712 			/*
12713 			 * The arriving of dup data packets indicate that we
12714 			 * may have postponed an ack for too long, or the other
12715 			 * side's RTT estimate is out of shape. Start acking
12716 			 * more often.
12717 			 */
12718 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12719 			    tcp->tcp_rack_cnt >= 1 &&
12720 			    tcp->tcp_rack_abs_max > 2) {
12721 				tcp->tcp_rack_abs_max--;
12722 			}
12723 			tcp->tcp_rack_cur_max = 1;
12724 
12725 			/*
12726 			 * This segment is "unacceptable".  None of its
12727 			 * sequence space lies within our advertized window.
12728 			 *
12729 			 * Adjust seg_len to the original value for tracing.
12730 			 */
12731 			seg_len -= gap;
12732 			if (tcp->tcp_debug) {
12733 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12734 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12735 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12736 				    "seg_len %d, rnxt %u, snxt %u, %s",
12737 				    gap, rgap, flags, seg_seq, seg_ack,
12738 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12739 				    tcp_display(tcp, NULL,
12740 				    DISP_ADDR_AND_PORT));
12741 			}
12742 
12743 			/*
12744 			 * Arrange to send an ACK in response to the
12745 			 * unacceptable segment per RFC 793 page 69. There
12746 			 * is only one small difference between ours and the
12747 			 * acceptability test in the RFC - we accept ACK-only
12748 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12749 			 * will be generated.
12750 			 *
12751 			 * Note that we have to ACK an ACK-only packet at least
12752 			 * for stacks that send 0-length keep-alives with
12753 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12754 			 * section 4.2.3.6. As long as we don't ever generate
12755 			 * an unacceptable packet in response to an incoming
12756 			 * packet that is unacceptable, it should not cause
12757 			 * "ACK wars".
12758 			 */
12759 			flags |=  TH_ACK_NEEDED;
12760 
12761 			/*
12762 			 * Continue processing this segment in order to use the
12763 			 * ACK information it contains, but skip all other
12764 			 * sequence-number processing.	Processing the ACK
12765 			 * information is necessary in order to
12766 			 * re-synchronize connections that may have lost
12767 			 * synchronization.
12768 			 *
12769 			 * We clear seg_len and flag fields related to
12770 			 * sequence number processing as they are not
12771 			 * to be trusted for an unacceptable segment.
12772 			 */
12773 			seg_len = 0;
12774 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12775 			goto process_ack;
12776 		}
12777 
12778 		/* Fix seg_seq, and chew the gap off the front. */
12779 		seg_seq = tcp->tcp_rnxt;
12780 		urp += gap;
12781 		do {
12782 			mblk_t	*mp2;
12783 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12784 			    (uintptr_t)UINT_MAX);
12785 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12786 			if (gap > 0) {
12787 				mp->b_rptr = mp->b_wptr - gap;
12788 				break;
12789 			}
12790 			mp2 = mp;
12791 			mp = mp->b_cont;
12792 			freeb(mp2);
12793 		} while (gap < 0);
12794 		/*
12795 		 * If the urgent data has already been acknowledged, we
12796 		 * should ignore TH_URG below
12797 		 */
12798 		if (urp < 0)
12799 			flags &= ~TH_URG;
12800 	}
12801 	/*
12802 	 * rgap is the amount of stuff received out of window.  A negative
12803 	 * value is the amount out of window.
12804 	 */
12805 	if (rgap < 0) {
12806 		mblk_t	*mp2;
12807 
12808 		if (tcp->tcp_rwnd == 0) {
12809 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
12810 		} else {
12811 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
12812 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
12813 		}
12814 
12815 		/*
12816 		 * seg_len does not include the FIN, so if more than
12817 		 * just the FIN is out of window, we act like we don't
12818 		 * see it.  (If just the FIN is out of window, rgap
12819 		 * will be zero and we will go ahead and acknowledge
12820 		 * the FIN.)
12821 		 */
12822 		flags &= ~TH_FIN;
12823 
12824 		/* Fix seg_len and make sure there is something left. */
12825 		seg_len += rgap;
12826 		if (seg_len <= 0) {
12827 			/*
12828 			 * Resets are only valid if they lie within our offered
12829 			 * window.  If the RST bit is set, we just ignore this
12830 			 * segment.
12831 			 */
12832 			if (flags & TH_RST) {
12833 				freemsg(mp);
12834 				return;
12835 			}
12836 
12837 			/* Per RFC 793, we need to send back an ACK. */
12838 			flags |= TH_ACK_NEEDED;
12839 
12840 			/*
12841 			 * Send SIGURG as soon as possible i.e. even
12842 			 * if the TH_URG was delivered in a window probe
12843 			 * packet (which will be unacceptable).
12844 			 *
12845 			 * We generate a signal if none has been generated
12846 			 * for this connection or if this is a new urgent
12847 			 * byte. Also send a zero-length "unmarked" message
12848 			 * to inform SIOCATMARK that this is not the mark.
12849 			 *
12850 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
12851 			 * is sent up. This plus the check for old data
12852 			 * (gap >= 0) handles the wraparound of the sequence
12853 			 * number space without having to always track the
12854 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
12855 			 * this max in its rcv_up variable).
12856 			 *
12857 			 * This prevents duplicate SIGURGS due to a "late"
12858 			 * zero-window probe when the T_EXDATA_IND has already
12859 			 * been sent up.
12860 			 */
12861 			if ((flags & TH_URG) &&
12862 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
12863 			    tcp->tcp_urp_last))) {
12864 				mp1 = allocb(0, BPRI_MED);
12865 				if (mp1 == NULL) {
12866 					freemsg(mp);
12867 					return;
12868 				}
12869 				if (!TCP_IS_DETACHED(tcp) &&
12870 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
12871 				    SIGURG)) {
12872 					/* Try again on the rexmit. */
12873 					freemsg(mp1);
12874 					freemsg(mp);
12875 					return;
12876 				}
12877 				/*
12878 				 * If the next byte would be the mark
12879 				 * then mark with MARKNEXT else mark
12880 				 * with NOTMARKNEXT.
12881 				 */
12882 				if (gap == 0 && urp == 0)
12883 					mp1->b_flag |= MSGMARKNEXT;
12884 				else
12885 					mp1->b_flag |= MSGNOTMARKNEXT;
12886 				freemsg(tcp->tcp_urp_mark_mp);
12887 				tcp->tcp_urp_mark_mp = mp1;
12888 				flags |= TH_SEND_URP_MARK;
12889 				tcp->tcp_urp_last_valid = B_TRUE;
12890 				tcp->tcp_urp_last = urp + seg_seq;
12891 			}
12892 			/*
12893 			 * If this is a zero window probe, continue to
12894 			 * process the ACK part.  But we need to set seg_len
12895 			 * to 0 to avoid data processing.  Otherwise just
12896 			 * drop the segment and send back an ACK.
12897 			 */
12898 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
12899 				flags &= ~(TH_SYN | TH_URG);
12900 				seg_len = 0;
12901 				goto process_ack;
12902 			} else {
12903 				freemsg(mp);
12904 				goto ack_check;
12905 			}
12906 		}
12907 		/* Pitch out of window stuff off the end. */
12908 		rgap = seg_len;
12909 		mp2 = mp;
12910 		do {
12911 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
12912 			    (uintptr_t)INT_MAX);
12913 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
12914 			if (rgap < 0) {
12915 				mp2->b_wptr += rgap;
12916 				if ((mp1 = mp2->b_cont) != NULL) {
12917 					mp2->b_cont = NULL;
12918 					freemsg(mp1);
12919 				}
12920 				break;
12921 			}
12922 		} while ((mp2 = mp2->b_cont) != NULL);
12923 	}
12924 ok:;
12925 	/*
12926 	 * TCP should check ECN info for segments inside the window only.
12927 	 * Therefore the check should be done here.
12928 	 */
12929 	if (tcp->tcp_ecn_ok) {
12930 		if (flags & TH_CWR) {
12931 			tcp->tcp_ecn_echo_on = B_FALSE;
12932 		}
12933 		/*
12934 		 * Note that both ECN_CE and CWR can be set in the
12935 		 * same segment.  In this case, we once again turn
12936 		 * on ECN_ECHO.
12937 		 */
12938 		if (tcp->tcp_ipversion == IPV4_VERSION) {
12939 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
12940 
12941 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
12942 				tcp->tcp_ecn_echo_on = B_TRUE;
12943 			}
12944 		} else {
12945 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
12946 
12947 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
12948 			    htonl(IPH_ECN_CE << 20)) {
12949 				tcp->tcp_ecn_echo_on = B_TRUE;
12950 			}
12951 		}
12952 	}
12953 
12954 	/*
12955 	 * Check whether we can update tcp_ts_recent.  This test is
12956 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
12957 	 * Extensions for High Performance: An Update", Internet Draft.
12958 	 */
12959 	if (tcp->tcp_snd_ts_ok &&
12960 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
12961 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
12962 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12963 		tcp->tcp_last_rcv_lbolt = lbolt64;
12964 	}
12965 
12966 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
12967 		/*
12968 		 * FIN in an out of order segment.  We record this in
12969 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
12970 		 * Clear the FIN so that any check on FIN flag will fail.
12971 		 * Remember that FIN also counts in the sequence number
12972 		 * space.  So we need to ack out of order FIN only segments.
12973 		 */
12974 		if (flags & TH_FIN) {
12975 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
12976 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
12977 			flags &= ~TH_FIN;
12978 			flags |= TH_ACK_NEEDED;
12979 		}
12980 		if (seg_len > 0) {
12981 			/* Fill in the SACK blk list. */
12982 			if (tcp->tcp_snd_sack_ok) {
12983 				ASSERT(tcp->tcp_sack_info != NULL);
12984 				tcp_sack_insert(tcp->tcp_sack_list,
12985 				    seg_seq, seg_seq + seg_len,
12986 				    &(tcp->tcp_num_sack_blk));
12987 			}
12988 
12989 			/*
12990 			 * Attempt reassembly and see if we have something
12991 			 * ready to go.
12992 			 */
12993 			mp = tcp_reass(tcp, mp, seg_seq);
12994 			/* Always ack out of order packets */
12995 			flags |= TH_ACK_NEEDED | TH_PUSH;
12996 			if (mp) {
12997 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12998 				    (uintptr_t)INT_MAX);
12999 				seg_len = mp->b_cont ? msgdsize(mp) :
13000 					(int)(mp->b_wptr - mp->b_rptr);
13001 				seg_seq = tcp->tcp_rnxt;
13002 				/*
13003 				 * A gap is filled and the seq num and len
13004 				 * of the gap match that of a previously
13005 				 * received FIN, put the FIN flag back in.
13006 				 */
13007 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13008 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13009 					flags |= TH_FIN;
13010 					tcp->tcp_valid_bits &=
13011 					    ~TCP_OFO_FIN_VALID;
13012 				}
13013 			} else {
13014 				/*
13015 				 * Keep going even with NULL mp.
13016 				 * There may be a useful ACK or something else
13017 				 * we don't want to miss.
13018 				 *
13019 				 * But TCP should not perform fast retransmit
13020 				 * because of the ack number.  TCP uses
13021 				 * seg_len == 0 to determine if it is a pure
13022 				 * ACK.  And this is not a pure ACK.
13023 				 */
13024 				seg_len = 0;
13025 				ofo_seg = B_TRUE;
13026 			}
13027 		}
13028 	} else if (seg_len > 0) {
13029 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13030 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13031 		/*
13032 		 * If an out of order FIN was received before, and the seq
13033 		 * num and len of the new segment match that of the FIN,
13034 		 * put the FIN flag back in.
13035 		 */
13036 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13037 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13038 			flags |= TH_FIN;
13039 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13040 		}
13041 	}
13042 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13043 	if (flags & TH_RST) {
13044 		freemsg(mp);
13045 		switch (tcp->tcp_state) {
13046 		case TCPS_SYN_RCVD:
13047 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13048 			break;
13049 		case TCPS_ESTABLISHED:
13050 		case TCPS_FIN_WAIT_1:
13051 		case TCPS_FIN_WAIT_2:
13052 		case TCPS_CLOSE_WAIT:
13053 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13054 			break;
13055 		case TCPS_CLOSING:
13056 		case TCPS_LAST_ACK:
13057 			(void) tcp_clean_death(tcp, 0, 16);
13058 			break;
13059 		default:
13060 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13061 			(void) tcp_clean_death(tcp, ENXIO, 17);
13062 			break;
13063 		}
13064 		return;
13065 	}
13066 	if (flags & TH_SYN) {
13067 		/*
13068 		 * See RFC 793, Page 71
13069 		 *
13070 		 * The seq number must be in the window as it should
13071 		 * be "fixed" above.  If it is outside window, it should
13072 		 * be already rejected.  Note that we allow seg_seq to be
13073 		 * rnxt + rwnd because we want to accept 0 window probe.
13074 		 */
13075 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13076 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13077 		freemsg(mp);
13078 		/*
13079 		 * If the ACK flag is not set, just use our snxt as the
13080 		 * seq number of the RST segment.
13081 		 */
13082 		if (!(flags & TH_ACK)) {
13083 			seg_ack = tcp->tcp_snxt;
13084 		}
13085 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13086 		    TH_RST|TH_ACK);
13087 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13088 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13089 		return;
13090 	}
13091 	/*
13092 	 * urp could be -1 when the urp field in the packet is 0
13093 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13094 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13095 	 */
13096 	if (flags & TH_URG && urp >= 0) {
13097 		if (!tcp->tcp_urp_last_valid ||
13098 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13099 			/*
13100 			 * If we haven't generated the signal yet for this
13101 			 * urgent pointer value, do it now.  Also, send up a
13102 			 * zero-length M_DATA indicating whether or not this is
13103 			 * the mark. The latter is not needed when a
13104 			 * T_EXDATA_IND is sent up. However, if there are
13105 			 * allocation failures this code relies on the sender
13106 			 * retransmitting and the socket code for determining
13107 			 * the mark should not block waiting for the peer to
13108 			 * transmit. Thus, for simplicity we always send up the
13109 			 * mark indication.
13110 			 */
13111 			mp1 = allocb(0, BPRI_MED);
13112 			if (mp1 == NULL) {
13113 				freemsg(mp);
13114 				return;
13115 			}
13116 			if (!TCP_IS_DETACHED(tcp) &&
13117 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13118 				/* Try again on the rexmit. */
13119 				freemsg(mp1);
13120 				freemsg(mp);
13121 				return;
13122 			}
13123 			/*
13124 			 * Mark with NOTMARKNEXT for now.
13125 			 * The code below will change this to MARKNEXT
13126 			 * if we are at the mark.
13127 			 *
13128 			 * If there are allocation failures (e.g. in dupmsg
13129 			 * below) the next time tcp_rput_data sees the urgent
13130 			 * segment it will send up the MSG*MARKNEXT message.
13131 			 */
13132 			mp1->b_flag |= MSGNOTMARKNEXT;
13133 			freemsg(tcp->tcp_urp_mark_mp);
13134 			tcp->tcp_urp_mark_mp = mp1;
13135 			flags |= TH_SEND_URP_MARK;
13136 #ifdef DEBUG
13137 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13138 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13139 			    "last %x, %s",
13140 			    seg_seq, urp, tcp->tcp_urp_last,
13141 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13142 #endif /* DEBUG */
13143 			tcp->tcp_urp_last_valid = B_TRUE;
13144 			tcp->tcp_urp_last = urp + seg_seq;
13145 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13146 			/*
13147 			 * An allocation failure prevented the previous
13148 			 * tcp_rput_data from sending up the allocated
13149 			 * MSG*MARKNEXT message - send it up this time
13150 			 * around.
13151 			 */
13152 			flags |= TH_SEND_URP_MARK;
13153 		}
13154 
13155 		/*
13156 		 * If the urgent byte is in this segment, make sure that it is
13157 		 * all by itself.  This makes it much easier to deal with the
13158 		 * possibility of an allocation failure on the T_exdata_ind.
13159 		 * Note that seg_len is the number of bytes in the segment, and
13160 		 * urp is the offset into the segment of the urgent byte.
13161 		 * urp < seg_len means that the urgent byte is in this segment.
13162 		 */
13163 		if (urp < seg_len) {
13164 			if (seg_len != 1) {
13165 				uint32_t  tmp_rnxt;
13166 				/*
13167 				 * Break it up and feed it back in.
13168 				 * Re-attach the IP header.
13169 				 */
13170 				mp->b_rptr = iphdr;
13171 				if (urp > 0) {
13172 					/*
13173 					 * There is stuff before the urgent
13174 					 * byte.
13175 					 */
13176 					mp1 = dupmsg(mp);
13177 					if (!mp1) {
13178 						/*
13179 						 * Trim from urgent byte on.
13180 						 * The rest will come back.
13181 						 */
13182 						(void) adjmsg(mp,
13183 						    urp - seg_len);
13184 						tcp_rput_data(connp,
13185 						    mp, NULL);
13186 						return;
13187 					}
13188 					(void) adjmsg(mp1, urp - seg_len);
13189 					/* Feed this piece back in. */
13190 					tmp_rnxt = tcp->tcp_rnxt;
13191 					tcp_rput_data(connp, mp1, NULL);
13192 					/*
13193 					 * If the data passed back in was not
13194 					 * processed (ie: bad ACK) sending
13195 					 * the remainder back in will cause a
13196 					 * loop. In this case, drop the
13197 					 * packet and let the sender try
13198 					 * sending a good packet.
13199 					 */
13200 					if (tmp_rnxt == tcp->tcp_rnxt) {
13201 						freemsg(mp);
13202 						return;
13203 					}
13204 				}
13205 				if (urp != seg_len - 1) {
13206 					uint32_t  tmp_rnxt;
13207 					/*
13208 					 * There is stuff after the urgent
13209 					 * byte.
13210 					 */
13211 					mp1 = dupmsg(mp);
13212 					if (!mp1) {
13213 						/*
13214 						 * Trim everything beyond the
13215 						 * urgent byte.  The rest will
13216 						 * come back.
13217 						 */
13218 						(void) adjmsg(mp,
13219 						    urp + 1 - seg_len);
13220 						tcp_rput_data(connp,
13221 						    mp, NULL);
13222 						return;
13223 					}
13224 					(void) adjmsg(mp1, urp + 1 - seg_len);
13225 					tmp_rnxt = tcp->tcp_rnxt;
13226 					tcp_rput_data(connp, mp1, NULL);
13227 					/*
13228 					 * If the data passed back in was not
13229 					 * processed (ie: bad ACK) sending
13230 					 * the remainder back in will cause a
13231 					 * loop. In this case, drop the
13232 					 * packet and let the sender try
13233 					 * sending a good packet.
13234 					 */
13235 					if (tmp_rnxt == tcp->tcp_rnxt) {
13236 						freemsg(mp);
13237 						return;
13238 					}
13239 				}
13240 				tcp_rput_data(connp, mp, NULL);
13241 				return;
13242 			}
13243 			/*
13244 			 * This segment contains only the urgent byte.  We
13245 			 * have to allocate the T_exdata_ind, if we can.
13246 			 */
13247 			if (!tcp->tcp_urp_mp) {
13248 				struct T_exdata_ind *tei;
13249 				mp1 = allocb(sizeof (struct T_exdata_ind),
13250 				    BPRI_MED);
13251 				if (!mp1) {
13252 					/*
13253 					 * Sigh... It'll be back.
13254 					 * Generate any MSG*MARK message now.
13255 					 */
13256 					freemsg(mp);
13257 					seg_len = 0;
13258 					if (flags & TH_SEND_URP_MARK) {
13259 
13260 
13261 						ASSERT(tcp->tcp_urp_mark_mp);
13262 						tcp->tcp_urp_mark_mp->b_flag &=
13263 							~MSGNOTMARKNEXT;
13264 						tcp->tcp_urp_mark_mp->b_flag |=
13265 							MSGMARKNEXT;
13266 					}
13267 					goto ack_check;
13268 				}
13269 				mp1->b_datap->db_type = M_PROTO;
13270 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13271 				tei->PRIM_type = T_EXDATA_IND;
13272 				tei->MORE_flag = 0;
13273 				mp1->b_wptr = (uchar_t *)&tei[1];
13274 				tcp->tcp_urp_mp = mp1;
13275 #ifdef DEBUG
13276 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13277 				    "tcp_rput: allocated exdata_ind %s",
13278 				    tcp_display(tcp, NULL,
13279 				    DISP_PORT_ONLY));
13280 #endif /* DEBUG */
13281 				/*
13282 				 * There is no need to send a separate MSG*MARK
13283 				 * message since the T_EXDATA_IND will be sent
13284 				 * now.
13285 				 */
13286 				flags &= ~TH_SEND_URP_MARK;
13287 				freemsg(tcp->tcp_urp_mark_mp);
13288 				tcp->tcp_urp_mark_mp = NULL;
13289 			}
13290 			/*
13291 			 * Now we are all set.  On the next putnext upstream,
13292 			 * tcp_urp_mp will be non-NULL and will get prepended
13293 			 * to what has to be this piece containing the urgent
13294 			 * byte.  If for any reason we abort this segment below,
13295 			 * if it comes back, we will have this ready, or it
13296 			 * will get blown off in close.
13297 			 */
13298 		} else if (urp == seg_len) {
13299 			/*
13300 			 * The urgent byte is the next byte after this sequence
13301 			 * number. If there is data it is marked with
13302 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13303 			 * since it is not needed. Otherwise, if the code
13304 			 * above just allocated a zero-length tcp_urp_mark_mp
13305 			 * message, that message is tagged with MSGMARKNEXT.
13306 			 * Sending up these MSGMARKNEXT messages makes
13307 			 * SIOCATMARK work correctly even though
13308 			 * the T_EXDATA_IND will not be sent up until the
13309 			 * urgent byte arrives.
13310 			 */
13311 			if (seg_len != 0) {
13312 				flags |= TH_MARKNEXT_NEEDED;
13313 				freemsg(tcp->tcp_urp_mark_mp);
13314 				tcp->tcp_urp_mark_mp = NULL;
13315 				flags &= ~TH_SEND_URP_MARK;
13316 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13317 				flags |= TH_SEND_URP_MARK;
13318 				tcp->tcp_urp_mark_mp->b_flag &=
13319 					~MSGNOTMARKNEXT;
13320 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13321 			}
13322 #ifdef DEBUG
13323 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13324 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13325 			    seg_len, flags,
13326 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13327 #endif /* DEBUG */
13328 		} else {
13329 			/* Data left until we hit mark */
13330 #ifdef DEBUG
13331 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13332 			    "tcp_rput: URP %d bytes left, %s",
13333 			    urp - seg_len, tcp_display(tcp, NULL,
13334 			    DISP_PORT_ONLY));
13335 #endif /* DEBUG */
13336 		}
13337 	}
13338 
13339 process_ack:
13340 	if (!(flags & TH_ACK)) {
13341 		freemsg(mp);
13342 		goto xmit_check;
13343 	}
13344 	}
13345 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13346 
13347 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13348 		tcp->tcp_ip_forward_progress = B_TRUE;
13349 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13350 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13351 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13352 			/* 3-way handshake complete - pass up the T_CONN_IND */
13353 			tcp_t	*listener = tcp->tcp_listener;
13354 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13355 
13356 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13357 			/*
13358 			 * We are here means eager is fine but it can
13359 			 * get a TH_RST at any point between now and till
13360 			 * accept completes and disappear. We need to
13361 			 * ensure that reference to eager is valid after
13362 			 * we get out of eager's perimeter. So we do
13363 			 * an extra refhold.
13364 			 */
13365 			CONN_INC_REF(connp);
13366 
13367 			/*
13368 			 * The listener also exists because of the refhold
13369 			 * done in tcp_conn_request. Its possible that it
13370 			 * might have closed. We will check that once we
13371 			 * get inside listeners context.
13372 			 */
13373 			CONN_INC_REF(listener->tcp_connp);
13374 			if (listener->tcp_connp->conn_sqp ==
13375 			    connp->conn_sqp) {
13376 				tcp_send_conn_ind(listener->tcp_connp, mp,
13377 				    listener->tcp_connp->conn_sqp);
13378 				CONN_DEC_REF(listener->tcp_connp);
13379 			} else if (!tcp->tcp_loopback) {
13380 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13381 				    tcp_send_conn_ind,
13382 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13383 			} else {
13384 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13385 				    tcp_send_conn_ind, listener->tcp_connp,
13386 				    SQTAG_TCP_CONN_IND);
13387 			}
13388 		}
13389 
13390 		if (tcp->tcp_active_open) {
13391 			/*
13392 			 * We are seeing the final ack in the three way
13393 			 * hand shake of a active open'ed connection
13394 			 * so we must send up a T_CONN_CON
13395 			 */
13396 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13397 				freemsg(mp);
13398 				return;
13399 			}
13400 			/*
13401 			 * Don't fuse the loopback endpoints for
13402 			 * simultaneous active opens.
13403 			 */
13404 			if (tcp->tcp_loopback) {
13405 				TCP_STAT(tcp_fusion_unfusable);
13406 				tcp->tcp_unfusable = B_TRUE;
13407 			}
13408 		}
13409 
13410 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13411 		bytes_acked--;
13412 		/* SYN was acked - making progress */
13413 		if (tcp->tcp_ipversion == IPV6_VERSION)
13414 			tcp->tcp_ip_forward_progress = B_TRUE;
13415 
13416 		/*
13417 		 * If SYN was retransmitted, need to reset all
13418 		 * retransmission info as this segment will be
13419 		 * treated as a dup ACK.
13420 		 */
13421 		if (tcp->tcp_rexmit) {
13422 			tcp->tcp_rexmit = B_FALSE;
13423 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13424 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13425 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13426 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13427 			tcp->tcp_ms_we_have_waited = 0;
13428 			tcp->tcp_cwnd = mss;
13429 		}
13430 
13431 		/*
13432 		 * We set the send window to zero here.
13433 		 * This is needed if there is data to be
13434 		 * processed already on the queue.
13435 		 * Later (at swnd_update label), the
13436 		 * "new_swnd > tcp_swnd" condition is satisfied
13437 		 * the XMIT_NEEDED flag is set in the current
13438 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13439 		 * called if there is already data on queue in
13440 		 * this state.
13441 		 */
13442 		tcp->tcp_swnd = 0;
13443 
13444 		if (new_swnd > tcp->tcp_max_swnd)
13445 			tcp->tcp_max_swnd = new_swnd;
13446 		tcp->tcp_swl1 = seg_seq;
13447 		tcp->tcp_swl2 = seg_ack;
13448 		tcp->tcp_state = TCPS_ESTABLISHED;
13449 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13450 
13451 		/* Fuse when both sides are in ESTABLISHED state */
13452 		if (tcp->tcp_loopback && do_tcp_fusion)
13453 			tcp_fuse(tcp, iphdr, tcph);
13454 
13455 	}
13456 	/* This code follows 4.4BSD-Lite2 mostly. */
13457 	if (bytes_acked < 0)
13458 		goto est;
13459 
13460 	/*
13461 	 * If TCP is ECN capable and the congestion experience bit is
13462 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13463 	 * done once per window (or more loosely, per RTT).
13464 	 */
13465 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13466 		tcp->tcp_cwr = B_FALSE;
13467 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13468 		if (!tcp->tcp_cwr) {
13469 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13470 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13471 			tcp->tcp_cwnd = npkt * mss;
13472 			/*
13473 			 * If the cwnd is 0, use the timer to clock out
13474 			 * new segments.  This is required by the ECN spec.
13475 			 */
13476 			if (npkt == 0) {
13477 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13478 				/*
13479 				 * This makes sure that when the ACK comes
13480 				 * back, we will increase tcp_cwnd by 1 MSS.
13481 				 */
13482 				tcp->tcp_cwnd_cnt = 0;
13483 			}
13484 			tcp->tcp_cwr = B_TRUE;
13485 			/*
13486 			 * This marks the end of the current window of in
13487 			 * flight data.  That is why we don't use
13488 			 * tcp_suna + tcp_swnd.  Only data in flight can
13489 			 * provide ECN info.
13490 			 */
13491 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13492 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13493 		}
13494 	}
13495 
13496 	mp1 = tcp->tcp_xmit_head;
13497 	if (bytes_acked == 0) {
13498 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13499 			int dupack_cnt;
13500 
13501 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13502 			/*
13503 			 * Fast retransmit.  When we have seen exactly three
13504 			 * identical ACKs while we have unacked data
13505 			 * outstanding we take it as a hint that our peer
13506 			 * dropped something.
13507 			 *
13508 			 * If TCP is retransmitting, don't do fast retransmit.
13509 			 */
13510 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13511 			    ! tcp->tcp_rexmit) {
13512 				/* Do Limited Transmit */
13513 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13514 				    tcp_dupack_fast_retransmit) {
13515 					/*
13516 					 * RFC 3042
13517 					 *
13518 					 * What we need to do is temporarily
13519 					 * increase tcp_cwnd so that new
13520 					 * data can be sent if it is allowed
13521 					 * by the receive window (tcp_rwnd).
13522 					 * tcp_wput_data() will take care of
13523 					 * the rest.
13524 					 *
13525 					 * If the connection is SACK capable,
13526 					 * only do limited xmit when there
13527 					 * is SACK info.
13528 					 *
13529 					 * Note how tcp_cwnd is incremented.
13530 					 * The first dup ACK will increase
13531 					 * it by 1 MSS.  The second dup ACK
13532 					 * will increase it by 2 MSS.  This
13533 					 * means that only 1 new segment will
13534 					 * be sent for each dup ACK.
13535 					 */
13536 					if (tcp->tcp_unsent > 0 &&
13537 					    (!tcp->tcp_snd_sack_ok ||
13538 					    (tcp->tcp_snd_sack_ok &&
13539 					    tcp->tcp_notsack_list != NULL))) {
13540 						tcp->tcp_cwnd += mss <<
13541 						    (tcp->tcp_dupack_cnt - 1);
13542 						flags |= TH_LIMIT_XMIT;
13543 					}
13544 				} else if (dupack_cnt ==
13545 				    tcp_dupack_fast_retransmit) {
13546 
13547 				/*
13548 				 * If we have reduced tcp_ssthresh
13549 				 * because of ECN, do not reduce it again
13550 				 * unless it is already one window of data
13551 				 * away.  After one window of data, tcp_cwr
13552 				 * should then be cleared.  Note that
13553 				 * for non ECN capable connection, tcp_cwr
13554 				 * should always be false.
13555 				 *
13556 				 * Adjust cwnd since the duplicate
13557 				 * ack indicates that a packet was
13558 				 * dropped (due to congestion.)
13559 				 */
13560 				if (!tcp->tcp_cwr) {
13561 					npkt = ((tcp->tcp_snxt -
13562 					    tcp->tcp_suna) >> 1) / mss;
13563 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13564 					    mss;
13565 					tcp->tcp_cwnd = (npkt +
13566 					    tcp->tcp_dupack_cnt) * mss;
13567 				}
13568 				if (tcp->tcp_ecn_ok) {
13569 					tcp->tcp_cwr = B_TRUE;
13570 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13571 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13572 				}
13573 
13574 				/*
13575 				 * We do Hoe's algorithm.  Refer to her
13576 				 * paper "Improving the Start-up Behavior
13577 				 * of a Congestion Control Scheme for TCP,"
13578 				 * appeared in SIGCOMM'96.
13579 				 *
13580 				 * Save highest seq no we have sent so far.
13581 				 * Be careful about the invisible FIN byte.
13582 				 */
13583 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13584 				    (tcp->tcp_unsent == 0)) {
13585 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13586 				} else {
13587 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13588 				}
13589 
13590 				/*
13591 				 * Do not allow bursty traffic during.
13592 				 * fast recovery.  Refer to Fall and Floyd's
13593 				 * paper "Simulation-based Comparisons of
13594 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13595 				 * This is a best current practise.
13596 				 */
13597 				tcp->tcp_snd_burst = TCP_CWND_SS;
13598 
13599 				/*
13600 				 * For SACK:
13601 				 * Calculate tcp_pipe, which is the
13602 				 * estimated number of bytes in
13603 				 * network.
13604 				 *
13605 				 * tcp_fack is the highest sack'ed seq num
13606 				 * TCP has received.
13607 				 *
13608 				 * tcp_pipe is explained in the above quoted
13609 				 * Fall and Floyd's paper.  tcp_fack is
13610 				 * explained in Mathis and Mahdavi's
13611 				 * "Forward Acknowledgment: Refining TCP
13612 				 * Congestion Control" in SIGCOMM '96.
13613 				 */
13614 				if (tcp->tcp_snd_sack_ok) {
13615 					ASSERT(tcp->tcp_sack_info != NULL);
13616 					if (tcp->tcp_notsack_list != NULL) {
13617 						tcp->tcp_pipe = tcp->tcp_snxt -
13618 						    tcp->tcp_fack;
13619 						tcp->tcp_sack_snxt = seg_ack;
13620 						flags |= TH_NEED_SACK_REXMIT;
13621 					} else {
13622 						/*
13623 						 * Always initialize tcp_pipe
13624 						 * even though we don't have
13625 						 * any SACK info.  If later
13626 						 * we get SACK info and
13627 						 * tcp_pipe is not initialized,
13628 						 * funny things will happen.
13629 						 */
13630 						tcp->tcp_pipe =
13631 						    tcp->tcp_cwnd_ssthresh;
13632 					}
13633 				} else {
13634 					flags |= TH_REXMIT_NEEDED;
13635 				} /* tcp_snd_sack_ok */
13636 
13637 				} else {
13638 					/*
13639 					 * Here we perform congestion
13640 					 * avoidance, but NOT slow start.
13641 					 * This is known as the Fast
13642 					 * Recovery Algorithm.
13643 					 */
13644 					if (tcp->tcp_snd_sack_ok &&
13645 					    tcp->tcp_notsack_list != NULL) {
13646 						flags |= TH_NEED_SACK_REXMIT;
13647 						tcp->tcp_pipe -= mss;
13648 						if (tcp->tcp_pipe < 0)
13649 							tcp->tcp_pipe = 0;
13650 					} else {
13651 					/*
13652 					 * We know that one more packet has
13653 					 * left the pipe thus we can update
13654 					 * cwnd.
13655 					 */
13656 					cwnd = tcp->tcp_cwnd + mss;
13657 					if (cwnd > tcp->tcp_cwnd_max)
13658 						cwnd = tcp->tcp_cwnd_max;
13659 					tcp->tcp_cwnd = cwnd;
13660 					if (tcp->tcp_unsent > 0)
13661 						flags |= TH_XMIT_NEEDED;
13662 					}
13663 				}
13664 			}
13665 		} else if (tcp->tcp_zero_win_probe) {
13666 			/*
13667 			 * If the window has opened, need to arrange
13668 			 * to send additional data.
13669 			 */
13670 			if (new_swnd != 0) {
13671 				/* tcp_suna != tcp_snxt */
13672 				/* Packet contains a window update */
13673 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13674 				tcp->tcp_zero_win_probe = 0;
13675 				tcp->tcp_timer_backoff = 0;
13676 				tcp->tcp_ms_we_have_waited = 0;
13677 
13678 				/*
13679 				 * Transmit starting with tcp_suna since
13680 				 * the one byte probe is not ack'ed.
13681 				 * If TCP has sent more than one identical
13682 				 * probe, tcp_rexmit will be set.  That means
13683 				 * tcp_ss_rexmit() will send out the one
13684 				 * byte along with new data.  Otherwise,
13685 				 * fake the retransmission.
13686 				 */
13687 				flags |= TH_XMIT_NEEDED;
13688 				if (!tcp->tcp_rexmit) {
13689 					tcp->tcp_rexmit = B_TRUE;
13690 					tcp->tcp_dupack_cnt = 0;
13691 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13692 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13693 				}
13694 			}
13695 		}
13696 		goto swnd_update;
13697 	}
13698 
13699 	/*
13700 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13701 	 * If the ACK value acks something that we have not yet sent, it might
13702 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13703 	 * other side.
13704 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13705 	 * state is handled above, so we can always just drop the segment and
13706 	 * send an ACK here.
13707 	 *
13708 	 * Should we send ACKs in response to ACK only segments?
13709 	 */
13710 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13711 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13712 		/* drop the received segment */
13713 		freemsg(mp);
13714 
13715 		/*
13716 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13717 		 * greater than 0, check if the number of such
13718 		 * bogus ACks is greater than that count.  If yes,
13719 		 * don't send back any ACK.  This prevents TCP from
13720 		 * getting into an ACK storm if somehow an attacker
13721 		 * successfully spoofs an acceptable segment to our
13722 		 * peer.
13723 		 */
13724 		if (tcp_drop_ack_unsent_cnt > 0 &&
13725 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13726 			TCP_STAT(tcp_in_ack_unsent_drop);
13727 			return;
13728 		}
13729 		mp = tcp_ack_mp(tcp);
13730 		if (mp != NULL) {
13731 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13732 			BUMP_LOCAL(tcp->tcp_obsegs);
13733 			BUMP_MIB(&tcp_mib, tcpOutAck);
13734 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13735 		}
13736 		return;
13737 	}
13738 
13739 	/*
13740 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13741 	 * blocks that are covered by this ACK.
13742 	 */
13743 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13744 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13745 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13746 	}
13747 
13748 	/*
13749 	 * If we got an ACK after fast retransmit, check to see
13750 	 * if it is a partial ACK.  If it is not and the congestion
13751 	 * window was inflated to account for the other side's
13752 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13753 	 */
13754 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13755 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13756 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13757 			tcp->tcp_dupack_cnt = 0;
13758 			/*
13759 			 * Restore the orig tcp_cwnd_ssthresh after
13760 			 * fast retransmit phase.
13761 			 */
13762 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13763 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13764 			}
13765 			tcp->tcp_rexmit_max = seg_ack;
13766 			tcp->tcp_cwnd_cnt = 0;
13767 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13768 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13769 
13770 			/*
13771 			 * Remove all notsack info to avoid confusion with
13772 			 * the next fast retrasnmit/recovery phase.
13773 			 */
13774 			if (tcp->tcp_snd_sack_ok &&
13775 			    tcp->tcp_notsack_list != NULL) {
13776 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13777 			}
13778 		} else {
13779 			if (tcp->tcp_snd_sack_ok &&
13780 			    tcp->tcp_notsack_list != NULL) {
13781 				flags |= TH_NEED_SACK_REXMIT;
13782 				tcp->tcp_pipe -= mss;
13783 				if (tcp->tcp_pipe < 0)
13784 					tcp->tcp_pipe = 0;
13785 			} else {
13786 				/*
13787 				 * Hoe's algorithm:
13788 				 *
13789 				 * Retransmit the unack'ed segment and
13790 				 * restart fast recovery.  Note that we
13791 				 * need to scale back tcp_cwnd to the
13792 				 * original value when we started fast
13793 				 * recovery.  This is to prevent overly
13794 				 * aggressive behaviour in sending new
13795 				 * segments.
13796 				 */
13797 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
13798 					tcp_dupack_fast_retransmit * mss;
13799 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
13800 				flags |= TH_REXMIT_NEEDED;
13801 			}
13802 		}
13803 	} else {
13804 		tcp->tcp_dupack_cnt = 0;
13805 		if (tcp->tcp_rexmit) {
13806 			/*
13807 			 * TCP is retranmitting.  If the ACK ack's all
13808 			 * outstanding data, update tcp_rexmit_max and
13809 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
13810 			 * to the correct value.
13811 			 *
13812 			 * Note that SEQ_LEQ() is used.  This is to avoid
13813 			 * unnecessary fast retransmit caused by dup ACKs
13814 			 * received when TCP does slow start retransmission
13815 			 * after a time out.  During this phase, TCP may
13816 			 * send out segments which are already received.
13817 			 * This causes dup ACKs to be sent back.
13818 			 */
13819 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
13820 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
13821 					tcp->tcp_rexmit_nxt = seg_ack;
13822 				}
13823 				if (seg_ack != tcp->tcp_rexmit_max) {
13824 					flags |= TH_XMIT_NEEDED;
13825 				}
13826 			} else {
13827 				tcp->tcp_rexmit = B_FALSE;
13828 				tcp->tcp_xmit_zc_clean = B_FALSE;
13829 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13830 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13831 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13832 			}
13833 			tcp->tcp_ms_we_have_waited = 0;
13834 		}
13835 	}
13836 
13837 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
13838 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
13839 	tcp->tcp_suna = seg_ack;
13840 	if (tcp->tcp_zero_win_probe != 0) {
13841 		tcp->tcp_zero_win_probe = 0;
13842 		tcp->tcp_timer_backoff = 0;
13843 	}
13844 
13845 	/*
13846 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
13847 	 * Note that it cannot be the SYN being ack'ed.  The code flow
13848 	 * will not reach here.
13849 	 */
13850 	if (mp1 == NULL) {
13851 		goto fin_acked;
13852 	}
13853 
13854 	/*
13855 	 * Update the congestion window.
13856 	 *
13857 	 * If TCP is not ECN capable or TCP is ECN capable but the
13858 	 * congestion experience bit is not set, increase the tcp_cwnd as
13859 	 * usual.
13860 	 */
13861 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
13862 		cwnd = tcp->tcp_cwnd;
13863 		add = mss;
13864 
13865 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
13866 			/*
13867 			 * This is to prevent an increase of less than 1 MSS of
13868 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
13869 			 * may send out tinygrams in order to preserve mblk
13870 			 * boundaries.
13871 			 *
13872 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
13873 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
13874 			 * increased by 1 MSS for every RTTs.
13875 			 */
13876 			if (tcp->tcp_cwnd_cnt <= 0) {
13877 				tcp->tcp_cwnd_cnt = cwnd + add;
13878 			} else {
13879 				tcp->tcp_cwnd_cnt -= add;
13880 				add = 0;
13881 			}
13882 		}
13883 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
13884 	}
13885 
13886 	/* See if the latest urgent data has been acknowledged */
13887 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
13888 	    SEQ_GT(seg_ack, tcp->tcp_urg))
13889 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
13890 
13891 	/* Can we update the RTT estimates? */
13892 	if (tcp->tcp_snd_ts_ok) {
13893 		/* Ignore zero timestamp echo-reply. */
13894 		if (tcpopt.tcp_opt_ts_ecr != 0) {
13895 			tcp_set_rto(tcp, (int32_t)lbolt -
13896 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
13897 		}
13898 
13899 		/* If needed, restart the timer. */
13900 		if (tcp->tcp_set_timer == 1) {
13901 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13902 			tcp->tcp_set_timer = 0;
13903 		}
13904 		/*
13905 		 * Update tcp_csuna in case the other side stops sending
13906 		 * us timestamps.
13907 		 */
13908 		tcp->tcp_csuna = tcp->tcp_snxt;
13909 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
13910 		/*
13911 		 * An ACK sequence we haven't seen before, so get the RTT
13912 		 * and update the RTO. But first check if the timestamp is
13913 		 * valid to use.
13914 		 */
13915 		if ((mp1->b_next != NULL) &&
13916 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
13917 			tcp_set_rto(tcp, (int32_t)lbolt -
13918 			    (int32_t)(intptr_t)mp1->b_prev);
13919 		else
13920 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13921 
13922 		/* Remeber the last sequence to be ACKed */
13923 		tcp->tcp_csuna = seg_ack;
13924 		if (tcp->tcp_set_timer == 1) {
13925 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13926 			tcp->tcp_set_timer = 0;
13927 		}
13928 	} else {
13929 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13930 	}
13931 
13932 	/* Eat acknowledged bytes off the xmit queue. */
13933 	for (;;) {
13934 		mblk_t	*mp2;
13935 		uchar_t	*wptr;
13936 
13937 		wptr = mp1->b_wptr;
13938 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
13939 		bytes_acked -= (int)(wptr - mp1->b_rptr);
13940 		if (bytes_acked < 0) {
13941 			mp1->b_rptr = wptr + bytes_acked;
13942 			/*
13943 			 * Set a new timestamp if all the bytes timed by the
13944 			 * old timestamp have been ack'ed.
13945 			 */
13946 			if (SEQ_GT(seg_ack,
13947 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
13948 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
13949 				mp1->b_next = NULL;
13950 			}
13951 			break;
13952 		}
13953 		mp1->b_next = NULL;
13954 		mp1->b_prev = NULL;
13955 		mp2 = mp1;
13956 		mp1 = mp1->b_cont;
13957 
13958 		/*
13959 		 * This notification is required for some zero-copy
13960 		 * clients to maintain a copy semantic. After the data
13961 		 * is ack'ed, client is safe to modify or reuse the buffer.
13962 		 */
13963 		if (tcp->tcp_snd_zcopy_aware &&
13964 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
13965 			tcp_zcopy_notify(tcp);
13966 		freeb(mp2);
13967 		if (bytes_acked == 0) {
13968 			if (mp1 == NULL) {
13969 				/* Everything is ack'ed, clear the tail. */
13970 				tcp->tcp_xmit_tail = NULL;
13971 				/*
13972 				 * Cancel the timer unless we are still
13973 				 * waiting for an ACK for the FIN packet.
13974 				 */
13975 				if (tcp->tcp_timer_tid != 0 &&
13976 				    tcp->tcp_snxt == tcp->tcp_suna) {
13977 					(void) TCP_TIMER_CANCEL(tcp,
13978 					    tcp->tcp_timer_tid);
13979 					tcp->tcp_timer_tid = 0;
13980 				}
13981 				goto pre_swnd_update;
13982 			}
13983 			if (mp2 != tcp->tcp_xmit_tail)
13984 				break;
13985 			tcp->tcp_xmit_tail = mp1;
13986 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13987 			    (uintptr_t)INT_MAX);
13988 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
13989 			    mp1->b_rptr);
13990 			break;
13991 		}
13992 		if (mp1 == NULL) {
13993 			/*
13994 			 * More was acked but there is nothing more
13995 			 * outstanding.  This means that the FIN was
13996 			 * just acked or that we're talking to a clown.
13997 			 */
13998 fin_acked:
13999 			ASSERT(tcp->tcp_fin_sent);
14000 			tcp->tcp_xmit_tail = NULL;
14001 			if (tcp->tcp_fin_sent) {
14002 				/* FIN was acked - making progress */
14003 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14004 				    !tcp->tcp_fin_acked)
14005 					tcp->tcp_ip_forward_progress = B_TRUE;
14006 				tcp->tcp_fin_acked = B_TRUE;
14007 				if (tcp->tcp_linger_tid != 0 &&
14008 				    TCP_TIMER_CANCEL(tcp,
14009 					tcp->tcp_linger_tid) >= 0) {
14010 					tcp_stop_lingering(tcp);
14011 				}
14012 			} else {
14013 				/*
14014 				 * We should never get here because
14015 				 * we have already checked that the
14016 				 * number of bytes ack'ed should be
14017 				 * smaller than or equal to what we
14018 				 * have sent so far (it is the
14019 				 * acceptability check of the ACK).
14020 				 * We can only get here if the send
14021 				 * queue is corrupted.
14022 				 *
14023 				 * Terminate the connection and
14024 				 * panic the system.  It is better
14025 				 * for us to panic instead of
14026 				 * continuing to avoid other disaster.
14027 				 */
14028 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14029 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14030 				panic("Memory corruption "
14031 				    "detected for connection %s.",
14032 				    tcp_display(tcp, NULL,
14033 					DISP_ADDR_AND_PORT));
14034 				/*NOTREACHED*/
14035 			}
14036 			goto pre_swnd_update;
14037 		}
14038 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14039 	}
14040 	if (tcp->tcp_unsent) {
14041 		flags |= TH_XMIT_NEEDED;
14042 	}
14043 pre_swnd_update:
14044 	tcp->tcp_xmit_head = mp1;
14045 swnd_update:
14046 	/*
14047 	 * The following check is different from most other implementations.
14048 	 * For bi-directional transfer, when segments are dropped, the
14049 	 * "normal" check will not accept a window update in those
14050 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14051 	 * segments which are outside receiver's window.  As TCP accepts
14052 	 * the ack in those retransmitted segments, if the window update in
14053 	 * the same segment is not accepted, TCP will incorrectly calculates
14054 	 * that it can send more segments.  This can create a deadlock
14055 	 * with the receiver if its window becomes zero.
14056 	 */
14057 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14058 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14059 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14060 		/*
14061 		 * The criteria for update is:
14062 		 *
14063 		 * 1. the segment acknowledges some data.  Or
14064 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14065 		 * 3. the segment is not old and the advertised window is
14066 		 * larger than the previous advertised window.
14067 		 */
14068 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14069 			flags |= TH_XMIT_NEEDED;
14070 		tcp->tcp_swnd = new_swnd;
14071 		if (new_swnd > tcp->tcp_max_swnd)
14072 			tcp->tcp_max_swnd = new_swnd;
14073 		tcp->tcp_swl1 = seg_seq;
14074 		tcp->tcp_swl2 = seg_ack;
14075 	}
14076 est:
14077 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14078 
14079 		switch (tcp->tcp_state) {
14080 		case TCPS_FIN_WAIT_1:
14081 			if (tcp->tcp_fin_acked) {
14082 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14083 				/*
14084 				 * We implement the non-standard BSD/SunOS
14085 				 * FIN_WAIT_2 flushing algorithm.
14086 				 * If there is no user attached to this
14087 				 * TCP endpoint, then this TCP struct
14088 				 * could hang around forever in FIN_WAIT_2
14089 				 * state if the peer forgets to send us
14090 				 * a FIN.  To prevent this, we wait only
14091 				 * 2*MSL (a convenient time value) for
14092 				 * the FIN to arrive.  If it doesn't show up,
14093 				 * we flush the TCP endpoint.  This algorithm,
14094 				 * though a violation of RFC-793, has worked
14095 				 * for over 10 years in BSD systems.
14096 				 * Note: SunOS 4.x waits 675 seconds before
14097 				 * flushing the FIN_WAIT_2 connection.
14098 				 */
14099 				TCP_TIMER_RESTART(tcp,
14100 				    tcp_fin_wait_2_flush_interval);
14101 			}
14102 			break;
14103 		case TCPS_FIN_WAIT_2:
14104 			break;	/* Shutdown hook? */
14105 		case TCPS_LAST_ACK:
14106 			freemsg(mp);
14107 			if (tcp->tcp_fin_acked) {
14108 				(void) tcp_clean_death(tcp, 0, 19);
14109 				return;
14110 			}
14111 			goto xmit_check;
14112 		case TCPS_CLOSING:
14113 			if (tcp->tcp_fin_acked) {
14114 				tcp->tcp_state = TCPS_TIME_WAIT;
14115 				if (!TCP_IS_DETACHED(tcp)) {
14116 					TCP_TIMER_RESTART(tcp,
14117 					    tcp_time_wait_interval);
14118 				} else {
14119 					tcp_time_wait_append(tcp);
14120 					TCP_DBGSTAT(tcp_rput_time_wait);
14121 				}
14122 			}
14123 			/*FALLTHRU*/
14124 		case TCPS_CLOSE_WAIT:
14125 			freemsg(mp);
14126 			goto xmit_check;
14127 		default:
14128 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14129 			break;
14130 		}
14131 	}
14132 	if (flags & TH_FIN) {
14133 		/* Make sure we ack the fin */
14134 		flags |= TH_ACK_NEEDED;
14135 		if (!tcp->tcp_fin_rcvd) {
14136 			tcp->tcp_fin_rcvd = B_TRUE;
14137 			tcp->tcp_rnxt++;
14138 			tcph = tcp->tcp_tcph;
14139 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14140 
14141 			/*
14142 			 * Generate the ordrel_ind at the end unless we
14143 			 * are an eager guy.
14144 			 * In the eager case tcp_rsrv will do this when run
14145 			 * after tcp_accept is done.
14146 			 */
14147 			if (tcp->tcp_listener == NULL &&
14148 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14149 				flags |= TH_ORDREL_NEEDED;
14150 			switch (tcp->tcp_state) {
14151 			case TCPS_SYN_RCVD:
14152 			case TCPS_ESTABLISHED:
14153 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14154 				/* Keepalive? */
14155 				break;
14156 			case TCPS_FIN_WAIT_1:
14157 				if (!tcp->tcp_fin_acked) {
14158 					tcp->tcp_state = TCPS_CLOSING;
14159 					break;
14160 				}
14161 				/* FALLTHRU */
14162 			case TCPS_FIN_WAIT_2:
14163 				tcp->tcp_state = TCPS_TIME_WAIT;
14164 				if (!TCP_IS_DETACHED(tcp)) {
14165 					TCP_TIMER_RESTART(tcp,
14166 					    tcp_time_wait_interval);
14167 				} else {
14168 					tcp_time_wait_append(tcp);
14169 					TCP_DBGSTAT(tcp_rput_time_wait);
14170 				}
14171 				if (seg_len) {
14172 					/*
14173 					 * implies data piggybacked on FIN.
14174 					 * break to handle data.
14175 					 */
14176 					break;
14177 				}
14178 				freemsg(mp);
14179 				goto ack_check;
14180 			}
14181 		}
14182 	}
14183 	if (mp == NULL)
14184 		goto xmit_check;
14185 	if (seg_len == 0) {
14186 		freemsg(mp);
14187 		goto xmit_check;
14188 	}
14189 	if (mp->b_rptr == mp->b_wptr) {
14190 		/*
14191 		 * The header has been consumed, so we remove the
14192 		 * zero-length mblk here.
14193 		 */
14194 		mp1 = mp;
14195 		mp = mp->b_cont;
14196 		freeb(mp1);
14197 	}
14198 	tcph = tcp->tcp_tcph;
14199 	tcp->tcp_rack_cnt++;
14200 	{
14201 		uint32_t cur_max;
14202 
14203 		cur_max = tcp->tcp_rack_cur_max;
14204 		if (tcp->tcp_rack_cnt >= cur_max) {
14205 			/*
14206 			 * We have more unacked data than we should - send
14207 			 * an ACK now.
14208 			 */
14209 			flags |= TH_ACK_NEEDED;
14210 			cur_max++;
14211 			if (cur_max > tcp->tcp_rack_abs_max)
14212 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14213 			else
14214 				tcp->tcp_rack_cur_max = cur_max;
14215 		} else if (TCP_IS_DETACHED(tcp)) {
14216 			/* We don't have an ACK timer for detached TCP. */
14217 			flags |= TH_ACK_NEEDED;
14218 		} else if (seg_len < mss) {
14219 			/*
14220 			 * If we get a segment that is less than an mss, and we
14221 			 * already have unacknowledged data, and the amount
14222 			 * unacknowledged is not a multiple of mss, then we
14223 			 * better generate an ACK now.  Otherwise, this may be
14224 			 * the tail piece of a transaction, and we would rather
14225 			 * wait for the response.
14226 			 */
14227 			uint32_t udif;
14228 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14229 			    (uintptr_t)INT_MAX);
14230 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14231 			if (udif && (udif % mss))
14232 				flags |= TH_ACK_NEEDED;
14233 			else
14234 				flags |= TH_ACK_TIMER_NEEDED;
14235 		} else {
14236 			/* Start delayed ack timer */
14237 			flags |= TH_ACK_TIMER_NEEDED;
14238 		}
14239 	}
14240 	tcp->tcp_rnxt += seg_len;
14241 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14242 
14243 	/* Update SACK list */
14244 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14245 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14246 		    &(tcp->tcp_num_sack_blk));
14247 	}
14248 
14249 	if (tcp->tcp_urp_mp) {
14250 		tcp->tcp_urp_mp->b_cont = mp;
14251 		mp = tcp->tcp_urp_mp;
14252 		tcp->tcp_urp_mp = NULL;
14253 		/* Ready for a new signal. */
14254 		tcp->tcp_urp_last_valid = B_FALSE;
14255 #ifdef DEBUG
14256 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14257 		    "tcp_rput: sending exdata_ind %s",
14258 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14259 #endif /* DEBUG */
14260 	}
14261 
14262 	/*
14263 	 * Check for ancillary data changes compared to last segment.
14264 	 */
14265 	if (tcp->tcp_ipv6_recvancillary != 0) {
14266 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14267 		if (mp == NULL)
14268 			return;
14269 	}
14270 
14271 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14272 		/*
14273 		 * Side queue inbound data until the accept happens.
14274 		 * tcp_accept/tcp_rput drains this when the accept happens.
14275 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14276 		 * T_EXDATA_IND) it is queued on b_next.
14277 		 * XXX Make urgent data use this. Requires:
14278 		 *	Removing tcp_listener check for TH_URG
14279 		 *	Making M_PCPROTO and MARK messages skip the eager case
14280 		 */
14281 
14282 		if (tcp->tcp_kssl_pending) {
14283 			tcp_kssl_input(tcp, mp);
14284 		} else {
14285 			tcp_rcv_enqueue(tcp, mp, seg_len);
14286 		}
14287 	} else {
14288 		if (mp->b_datap->db_type != M_DATA ||
14289 		    (flags & TH_MARKNEXT_NEEDED)) {
14290 			if (tcp->tcp_rcv_list != NULL) {
14291 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14292 			}
14293 			ASSERT(tcp->tcp_rcv_list == NULL ||
14294 			    tcp->tcp_fused_sigurg);
14295 			if (flags & TH_MARKNEXT_NEEDED) {
14296 #ifdef DEBUG
14297 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14298 				    "tcp_rput: sending MSGMARKNEXT %s",
14299 				    tcp_display(tcp, NULL,
14300 				    DISP_PORT_ONLY));
14301 #endif /* DEBUG */
14302 				mp->b_flag |= MSGMARKNEXT;
14303 				flags &= ~TH_MARKNEXT_NEEDED;
14304 			}
14305 
14306 			/* Does this need SSL processing first? */
14307 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14308 			    (DB_TYPE(mp) == M_DATA)) {
14309 				tcp_kssl_input(tcp, mp);
14310 			} else {
14311 				putnext(tcp->tcp_rq, mp);
14312 				if (!canputnext(tcp->tcp_rq))
14313 					tcp->tcp_rwnd -= seg_len;
14314 			}
14315 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
14316 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
14317 		    (sqp != NULL)) {
14318 			if (tcp->tcp_rcv_list != NULL) {
14319 				/*
14320 				 * Enqueue the new segment first and then
14321 				 * call tcp_rcv_drain() to send all data
14322 				 * up.  The other way to do this is to
14323 				 * send all queued data up and then call
14324 				 * putnext() to send the new segment up.
14325 				 * This way can remove the else part later
14326 				 * on.
14327 				 *
14328 				 * We don't this to avoid one more call to
14329 				 * canputnext() as tcp_rcv_drain() needs to
14330 				 * call canputnext().
14331 				 */
14332 				tcp_rcv_enqueue(tcp, mp, seg_len);
14333 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14334 			} else {
14335 				/* Does this need SSL processing first? */
14336 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14337 				    (DB_TYPE(mp) == M_DATA)) {
14338 					tcp_kssl_input(tcp, mp);
14339 				} else {
14340 					putnext(tcp->tcp_rq, mp);
14341 					if (!canputnext(tcp->tcp_rq))
14342 						tcp->tcp_rwnd -= seg_len;
14343 				}
14344 			}
14345 		} else {
14346 			/*
14347 			 * Enqueue all packets when processing an mblk
14348 			 * from the co queue and also enqueue normal packets.
14349 			 */
14350 			tcp_rcv_enqueue(tcp, mp, seg_len);
14351 		}
14352 		/*
14353 		 * Make sure the timer is running if we have data waiting
14354 		 * for a push bit. This provides resiliency against
14355 		 * implementations that do not correctly generate push bits.
14356 		 */
14357 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
14358 		    tcp->tcp_push_tid == 0) {
14359 			/*
14360 			 * The connection may be closed at this point, so don't
14361 			 * do anything for a detached tcp.
14362 			 */
14363 			if (!TCP_IS_DETACHED(tcp))
14364 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14365 				    tcp_push_timer,
14366 				    MSEC_TO_TICK(tcp_push_timer_interval));
14367 		}
14368 	}
14369 xmit_check:
14370 	/* Is there anything left to do? */
14371 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14372 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14373 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14374 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14375 		goto done;
14376 
14377 	/* Any transmit work to do and a non-zero window? */
14378 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14379 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14380 		if (flags & TH_REXMIT_NEEDED) {
14381 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14382 
14383 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14384 			if (snd_size > mss)
14385 				snd_size = mss;
14386 			if (snd_size > tcp->tcp_swnd)
14387 				snd_size = tcp->tcp_swnd;
14388 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14389 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14390 			    B_TRUE);
14391 
14392 			if (mp1 != NULL) {
14393 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14394 				tcp->tcp_csuna = tcp->tcp_snxt;
14395 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14396 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14397 				TCP_RECORD_TRACE(tcp, mp1,
14398 				    TCP_TRACE_SEND_PKT);
14399 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14400 			}
14401 		}
14402 		if (flags & TH_NEED_SACK_REXMIT) {
14403 			tcp_sack_rxmit(tcp, &flags);
14404 		}
14405 		/*
14406 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14407 		 * out new segment.  Note that tcp_rexmit should not be
14408 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14409 		 */
14410 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14411 			if (!tcp->tcp_rexmit) {
14412 				tcp_wput_data(tcp, NULL, B_FALSE);
14413 			} else {
14414 				tcp_ss_rexmit(tcp);
14415 			}
14416 		}
14417 		/*
14418 		 * Adjust tcp_cwnd back to normal value after sending
14419 		 * new data segments.
14420 		 */
14421 		if (flags & TH_LIMIT_XMIT) {
14422 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14423 			/*
14424 			 * This will restart the timer.  Restarting the
14425 			 * timer is used to avoid a timeout before the
14426 			 * limited transmitted segment's ACK gets back.
14427 			 */
14428 			if (tcp->tcp_xmit_head != NULL)
14429 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14430 		}
14431 
14432 		/* Anything more to do? */
14433 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14434 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14435 			goto done;
14436 	}
14437 ack_check:
14438 	if (flags & TH_SEND_URP_MARK) {
14439 		ASSERT(tcp->tcp_urp_mark_mp);
14440 		/*
14441 		 * Send up any queued data and then send the mark message
14442 		 */
14443 		if (tcp->tcp_rcv_list != NULL) {
14444 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14445 		}
14446 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14447 
14448 		mp1 = tcp->tcp_urp_mark_mp;
14449 		tcp->tcp_urp_mark_mp = NULL;
14450 #ifdef DEBUG
14451 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14452 		    "tcp_rput: sending zero-length %s %s",
14453 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14454 		    "MSGNOTMARKNEXT"),
14455 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14456 #endif /* DEBUG */
14457 		putnext(tcp->tcp_rq, mp1);
14458 		flags &= ~TH_SEND_URP_MARK;
14459 	}
14460 	if (flags & TH_ACK_NEEDED) {
14461 		/*
14462 		 * Time to send an ack for some reason.
14463 		 */
14464 		mp1 = tcp_ack_mp(tcp);
14465 
14466 		if (mp1 != NULL) {
14467 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14468 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14469 			BUMP_LOCAL(tcp->tcp_obsegs);
14470 			BUMP_MIB(&tcp_mib, tcpOutAck);
14471 		}
14472 		if (tcp->tcp_ack_tid != 0) {
14473 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14474 			tcp->tcp_ack_tid = 0;
14475 		}
14476 	}
14477 	if (flags & TH_ACK_TIMER_NEEDED) {
14478 		/*
14479 		 * Arrange for deferred ACK or push wait timeout.
14480 		 * Start timer if it is not already running.
14481 		 */
14482 		if (tcp->tcp_ack_tid == 0) {
14483 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14484 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14485 			    (clock_t)tcp_local_dack_interval :
14486 			    (clock_t)tcp_deferred_ack_interval));
14487 		}
14488 	}
14489 	if (flags & TH_ORDREL_NEEDED) {
14490 		/*
14491 		 * Send up the ordrel_ind unless we are an eager guy.
14492 		 * In the eager case tcp_rsrv will do this when run
14493 		 * after tcp_accept is done.
14494 		 */
14495 		ASSERT(tcp->tcp_listener == NULL);
14496 		if (tcp->tcp_rcv_list != NULL) {
14497 			/*
14498 			 * Push any mblk(s) enqueued from co processing.
14499 			 */
14500 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14501 		}
14502 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14503 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14504 			tcp->tcp_ordrel_done = B_TRUE;
14505 			putnext(tcp->tcp_rq, mp1);
14506 			if (tcp->tcp_deferred_clean_death) {
14507 				/*
14508 				 * tcp_clean_death was deferred
14509 				 * for T_ORDREL_IND - do it now
14510 				 */
14511 				(void) tcp_clean_death(tcp,
14512 				    tcp->tcp_client_errno, 20);
14513 				tcp->tcp_deferred_clean_death =	B_FALSE;
14514 			}
14515 		} else {
14516 			/*
14517 			 * Run the orderly release in the
14518 			 * service routine.
14519 			 */
14520 			qenable(tcp->tcp_rq);
14521 			/*
14522 			 * Caveat(XXX): The machine may be so
14523 			 * overloaded that tcp_rsrv() is not scheduled
14524 			 * until after the endpoint has transitioned
14525 			 * to TCPS_TIME_WAIT
14526 			 * and tcp_time_wait_interval expires. Then
14527 			 * tcp_timer() will blow away state in tcp_t
14528 			 * and T_ORDREL_IND will never be delivered
14529 			 * upstream. Unlikely but potentially
14530 			 * a problem.
14531 			 */
14532 		}
14533 	}
14534 done:
14535 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14536 }
14537 
14538 /*
14539  * This function does PAWS protection check. Returns B_TRUE if the
14540  * segment passes the PAWS test, else returns B_FALSE.
14541  */
14542 boolean_t
14543 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14544 {
14545 	uint8_t	flags;
14546 	int	options;
14547 	uint8_t *up;
14548 
14549 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14550 	/*
14551 	 * If timestamp option is aligned nicely, get values inline,
14552 	 * otherwise call general routine to parse.  Only do that
14553 	 * if timestamp is the only option.
14554 	 */
14555 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14556 	    TCPOPT_REAL_TS_LEN &&
14557 	    OK_32PTR((up = ((uint8_t *)tcph) +
14558 	    TCP_MIN_HEADER_LENGTH)) &&
14559 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14560 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14561 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14562 
14563 		options = TCP_OPT_TSTAMP_PRESENT;
14564 	} else {
14565 		if (tcp->tcp_snd_sack_ok) {
14566 			tcpoptp->tcp = tcp;
14567 		} else {
14568 			tcpoptp->tcp = NULL;
14569 		}
14570 		options = tcp_parse_options(tcph, tcpoptp);
14571 	}
14572 
14573 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14574 		/*
14575 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14576 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14577 		 */
14578 		if ((flags & TH_RST) == 0 &&
14579 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14580 		    tcp->tcp_ts_recent)) {
14581 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14582 			    PAWS_TIMEOUT)) {
14583 				/* This segment is not acceptable. */
14584 				return (B_FALSE);
14585 			} else {
14586 				/*
14587 				 * Connection has been idle for
14588 				 * too long.  Reset the timestamp
14589 				 * and assume the segment is valid.
14590 				 */
14591 				tcp->tcp_ts_recent =
14592 				    tcpoptp->tcp_opt_ts_val;
14593 			}
14594 		}
14595 	} else {
14596 		/*
14597 		 * If we don't get a timestamp on every packet, we
14598 		 * figure we can't really trust 'em, so we stop sending
14599 		 * and parsing them.
14600 		 */
14601 		tcp->tcp_snd_ts_ok = B_FALSE;
14602 
14603 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14604 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14605 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14606 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14607 		if (tcp->tcp_snd_sack_ok) {
14608 			ASSERT(tcp->tcp_sack_info != NULL);
14609 			tcp->tcp_max_sack_blk = 4;
14610 		}
14611 	}
14612 	return (B_TRUE);
14613 }
14614 
14615 /*
14616  * Attach ancillary data to a received TCP segments for the
14617  * ancillary pieces requested by the application that are
14618  * different than they were in the previous data segment.
14619  *
14620  * Save the "current" values once memory allocation is ok so that
14621  * when memory allocation fails we can just wait for the next data segment.
14622  */
14623 static mblk_t *
14624 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14625 {
14626 	struct T_optdata_ind *todi;
14627 	int optlen;
14628 	uchar_t *optptr;
14629 	struct T_opthdr *toh;
14630 	uint_t addflag;	/* Which pieces to add */
14631 	mblk_t *mp1;
14632 
14633 	optlen = 0;
14634 	addflag = 0;
14635 	/* If app asked for pktinfo and the index has changed ... */
14636 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14637 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14638 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14639 		optlen += sizeof (struct T_opthdr) +
14640 		    sizeof (struct in6_pktinfo);
14641 		addflag |= TCP_IPV6_RECVPKTINFO;
14642 	}
14643 	/* If app asked for hoplimit and it has changed ... */
14644 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14645 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14646 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14647 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14648 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14649 	}
14650 	/* If app asked for tclass and it has changed ... */
14651 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14652 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14653 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14654 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14655 		addflag |= TCP_IPV6_RECVTCLASS;
14656 	}
14657 	/* If app asked for hopbyhop headers and it has changed ... */
14658 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14659 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14660 		(ipp->ipp_fields & IPPF_HOPOPTS),
14661 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14662 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
14663 		addflag |= TCP_IPV6_RECVHOPOPTS;
14664 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
14665 		    &tcp->tcp_hopoptslen,
14666 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14667 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14668 			return (mp);
14669 	}
14670 	/* If app asked for dst headers before routing headers ... */
14671 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14672 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14673 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14674 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14675 		optlen += sizeof (struct T_opthdr) +
14676 		    ipp->ipp_rtdstoptslen;
14677 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14678 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
14679 		    &tcp->tcp_rtdstoptslen,
14680 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14681 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14682 			return (mp);
14683 	}
14684 	/* If app asked for routing headers and it has changed ... */
14685 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14686 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14687 		(ipp->ipp_fields & IPPF_RTHDR),
14688 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14689 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14690 		addflag |= TCP_IPV6_RECVRTHDR;
14691 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
14692 		    &tcp->tcp_rthdrlen,
14693 		    (ipp->ipp_fields & IPPF_RTHDR),
14694 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14695 			return (mp);
14696 	}
14697 	/* If app asked for dest headers and it has changed ... */
14698 	if ((tcp->tcp_ipv6_recvancillary &
14699 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14700 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14701 		(ipp->ipp_fields & IPPF_DSTOPTS),
14702 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14703 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14704 		addflag |= TCP_IPV6_RECVDSTOPTS;
14705 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
14706 		    &tcp->tcp_dstoptslen,
14707 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14708 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14709 			return (mp);
14710 	}
14711 
14712 	if (optlen == 0) {
14713 		/* Nothing to add */
14714 		return (mp);
14715 	}
14716 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14717 	if (mp1 == NULL) {
14718 		/*
14719 		 * Defer sending ancillary data until the next TCP segment
14720 		 * arrives.
14721 		 */
14722 		return (mp);
14723 	}
14724 	mp1->b_cont = mp;
14725 	mp = mp1;
14726 	mp->b_wptr += sizeof (*todi) + optlen;
14727 	mp->b_datap->db_type = M_PROTO;
14728 	todi = (struct T_optdata_ind *)mp->b_rptr;
14729 	todi->PRIM_type = T_OPTDATA_IND;
14730 	todi->DATA_flag = 1;	/* MORE data */
14731 	todi->OPT_length = optlen;
14732 	todi->OPT_offset = sizeof (*todi);
14733 	optptr = (uchar_t *)&todi[1];
14734 	/*
14735 	 * If app asked for pktinfo and the index has changed ...
14736 	 * Note that the local address never changes for the connection.
14737 	 */
14738 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14739 		struct in6_pktinfo *pkti;
14740 
14741 		toh = (struct T_opthdr *)optptr;
14742 		toh->level = IPPROTO_IPV6;
14743 		toh->name = IPV6_PKTINFO;
14744 		toh->len = sizeof (*toh) + sizeof (*pkti);
14745 		toh->status = 0;
14746 		optptr += sizeof (*toh);
14747 		pkti = (struct in6_pktinfo *)optptr;
14748 		if (tcp->tcp_ipversion == IPV6_VERSION)
14749 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14750 		else
14751 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14752 			    &pkti->ipi6_addr);
14753 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14754 		optptr += sizeof (*pkti);
14755 		ASSERT(OK_32PTR(optptr));
14756 		/* Save as "last" value */
14757 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14758 	}
14759 	/* If app asked for hoplimit and it has changed ... */
14760 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14761 		toh = (struct T_opthdr *)optptr;
14762 		toh->level = IPPROTO_IPV6;
14763 		toh->name = IPV6_HOPLIMIT;
14764 		toh->len = sizeof (*toh) + sizeof (uint_t);
14765 		toh->status = 0;
14766 		optptr += sizeof (*toh);
14767 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14768 		optptr += sizeof (uint_t);
14769 		ASSERT(OK_32PTR(optptr));
14770 		/* Save as "last" value */
14771 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14772 	}
14773 	/* If app asked for tclass and it has changed ... */
14774 	if (addflag & TCP_IPV6_RECVTCLASS) {
14775 		toh = (struct T_opthdr *)optptr;
14776 		toh->level = IPPROTO_IPV6;
14777 		toh->name = IPV6_TCLASS;
14778 		toh->len = sizeof (*toh) + sizeof (uint_t);
14779 		toh->status = 0;
14780 		optptr += sizeof (*toh);
14781 		*(uint_t *)optptr = ipp->ipp_tclass;
14782 		optptr += sizeof (uint_t);
14783 		ASSERT(OK_32PTR(optptr));
14784 		/* Save as "last" value */
14785 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14786 	}
14787 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14788 		toh = (struct T_opthdr *)optptr;
14789 		toh->level = IPPROTO_IPV6;
14790 		toh->name = IPV6_HOPOPTS;
14791 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
14792 		toh->status = 0;
14793 		optptr += sizeof (*toh);
14794 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
14795 		optptr += ipp->ipp_hopoptslen;
14796 		ASSERT(OK_32PTR(optptr));
14797 		/* Save as last value */
14798 		tcp_savebuf((void **)&tcp->tcp_hopopts,
14799 		    &tcp->tcp_hopoptslen,
14800 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14801 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14802 	}
14803 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
14804 		toh = (struct T_opthdr *)optptr;
14805 		toh->level = IPPROTO_IPV6;
14806 		toh->name = IPV6_RTHDRDSTOPTS;
14807 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
14808 		toh->status = 0;
14809 		optptr += sizeof (*toh);
14810 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
14811 		optptr += ipp->ipp_rtdstoptslen;
14812 		ASSERT(OK_32PTR(optptr));
14813 		/* Save as last value */
14814 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
14815 		    &tcp->tcp_rtdstoptslen,
14816 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14817 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
14818 	}
14819 	if (addflag & TCP_IPV6_RECVRTHDR) {
14820 		toh = (struct T_opthdr *)optptr;
14821 		toh->level = IPPROTO_IPV6;
14822 		toh->name = IPV6_RTHDR;
14823 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
14824 		toh->status = 0;
14825 		optptr += sizeof (*toh);
14826 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
14827 		optptr += ipp->ipp_rthdrlen;
14828 		ASSERT(OK_32PTR(optptr));
14829 		/* Save as last value */
14830 		tcp_savebuf((void **)&tcp->tcp_rthdr,
14831 		    &tcp->tcp_rthdrlen,
14832 		    (ipp->ipp_fields & IPPF_RTHDR),
14833 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14834 	}
14835 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
14836 		toh = (struct T_opthdr *)optptr;
14837 		toh->level = IPPROTO_IPV6;
14838 		toh->name = IPV6_DSTOPTS;
14839 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
14840 		toh->status = 0;
14841 		optptr += sizeof (*toh);
14842 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
14843 		optptr += ipp->ipp_dstoptslen;
14844 		ASSERT(OK_32PTR(optptr));
14845 		/* Save as last value */
14846 		tcp_savebuf((void **)&tcp->tcp_dstopts,
14847 		    &tcp->tcp_dstoptslen,
14848 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14849 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14850 	}
14851 	ASSERT(optptr == mp->b_wptr);
14852 	return (mp);
14853 }
14854 
14855 
14856 /*
14857  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
14858  * or a "bad" IRE detected by tcp_adapt_ire.
14859  * We can't tell if the failure was due to the laddr or the faddr
14860  * thus we clear out all addresses and ports.
14861  */
14862 static void
14863 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
14864 {
14865 	queue_t	*q = tcp->tcp_rq;
14866 	tcph_t	*tcph;
14867 	struct T_error_ack *tea;
14868 	conn_t	*connp = tcp->tcp_connp;
14869 
14870 
14871 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
14872 
14873 	if (mp->b_cont) {
14874 		freemsg(mp->b_cont);
14875 		mp->b_cont = NULL;
14876 	}
14877 	tea = (struct T_error_ack *)mp->b_rptr;
14878 	switch (tea->PRIM_type) {
14879 	case T_BIND_ACK:
14880 		/*
14881 		 * Need to unbind with classifier since we were just told that
14882 		 * our bind succeeded.
14883 		 */
14884 		tcp->tcp_hard_bound = B_FALSE;
14885 		tcp->tcp_hard_binding = B_FALSE;
14886 
14887 		ipcl_hash_remove(connp);
14888 		/* Reuse the mblk if possible */
14889 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
14890 			sizeof (*tea));
14891 		mp->b_rptr = mp->b_datap->db_base;
14892 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
14893 		tea = (struct T_error_ack *)mp->b_rptr;
14894 		tea->PRIM_type = T_ERROR_ACK;
14895 		tea->TLI_error = TSYSERR;
14896 		tea->UNIX_error = error;
14897 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
14898 			tea->ERROR_prim = T_CONN_REQ;
14899 		} else {
14900 			tea->ERROR_prim = O_T_BIND_REQ;
14901 		}
14902 		break;
14903 
14904 	case T_ERROR_ACK:
14905 		if (tcp->tcp_state >= TCPS_SYN_SENT)
14906 			tea->ERROR_prim = T_CONN_REQ;
14907 		break;
14908 	default:
14909 		panic("tcp_bind_failed: unexpected TPI type");
14910 		/*NOTREACHED*/
14911 	}
14912 
14913 	tcp->tcp_state = TCPS_IDLE;
14914 	if (tcp->tcp_ipversion == IPV4_VERSION)
14915 		tcp->tcp_ipha->ipha_src = 0;
14916 	else
14917 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
14918 	/*
14919 	 * Copy of the src addr. in tcp_t is needed since
14920 	 * the lookup funcs. can only look at tcp_t
14921 	 */
14922 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
14923 
14924 	tcph = tcp->tcp_tcph;
14925 	tcph->th_lport[0] = 0;
14926 	tcph->th_lport[1] = 0;
14927 	tcp_bind_hash_remove(tcp);
14928 	bzero(&connp->u_port, sizeof (connp->u_port));
14929 	/* blow away saved option results if any */
14930 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
14931 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
14932 
14933 	conn_delete_ire(tcp->tcp_connp, NULL);
14934 	putnext(q, mp);
14935 }
14936 
14937 /*
14938  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
14939  * messages.
14940  */
14941 void
14942 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
14943 {
14944 	mblk_t	*mp1;
14945 	uchar_t	*rptr = mp->b_rptr;
14946 	queue_t	*q = tcp->tcp_rq;
14947 	struct T_error_ack *tea;
14948 	uint32_t mss;
14949 	mblk_t *syn_mp;
14950 	mblk_t *mdti;
14951 	int	retval;
14952 	mblk_t *ire_mp;
14953 
14954 	switch (mp->b_datap->db_type) {
14955 	case M_PROTO:
14956 	case M_PCPROTO:
14957 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
14958 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
14959 			break;
14960 		tea = (struct T_error_ack *)rptr;
14961 		switch (tea->PRIM_type) {
14962 		case T_BIND_ACK:
14963 			/*
14964 			 * Adapt Multidata information, if any.  The
14965 			 * following tcp_mdt_update routine will free
14966 			 * the message.
14967 			 */
14968 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
14969 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
14970 				    b_rptr)->mdt_capab, B_TRUE);
14971 				freemsg(mdti);
14972 			}
14973 
14974 			/* Get the IRE, if we had requested for it */
14975 			ire_mp = tcp_ire_mp(mp);
14976 
14977 			if (tcp->tcp_hard_binding) {
14978 				tcp->tcp_hard_binding = B_FALSE;
14979 				tcp->tcp_hard_bound = B_TRUE;
14980 				CL_INET_CONNECT(tcp);
14981 			} else {
14982 				if (ire_mp != NULL)
14983 					freeb(ire_mp);
14984 				goto after_syn_sent;
14985 			}
14986 
14987 			retval = tcp_adapt_ire(tcp, ire_mp);
14988 			if (ire_mp != NULL)
14989 				freeb(ire_mp);
14990 			if (retval == 0) {
14991 				tcp_bind_failed(tcp, mp,
14992 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
14993 				    ENETUNREACH : EADDRNOTAVAIL));
14994 				return;
14995 			}
14996 			/*
14997 			 * Don't let an endpoint connect to itself.
14998 			 * Also checked in tcp_connect() but that
14999 			 * check can't handle the case when the
15000 			 * local IP address is INADDR_ANY.
15001 			 */
15002 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15003 				if ((tcp->tcp_ipha->ipha_dst ==
15004 				    tcp->tcp_ipha->ipha_src) &&
15005 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15006 				    tcp->tcp_tcph->th_fport))) {
15007 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15008 					return;
15009 				}
15010 			} else {
15011 				if (IN6_ARE_ADDR_EQUAL(
15012 				    &tcp->tcp_ip6h->ip6_dst,
15013 				    &tcp->tcp_ip6h->ip6_src) &&
15014 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15015 				    tcp->tcp_tcph->th_fport))) {
15016 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15017 					return;
15018 				}
15019 			}
15020 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15021 			/*
15022 			 * This should not be possible!  Just for
15023 			 * defensive coding...
15024 			 */
15025 			if (tcp->tcp_state != TCPS_SYN_SENT)
15026 				goto after_syn_sent;
15027 
15028 			ASSERT(q == tcp->tcp_rq);
15029 			/*
15030 			 * tcp_adapt_ire() does not adjust
15031 			 * for TCP/IP header length.
15032 			 */
15033 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15034 
15035 			/*
15036 			 * Just make sure our rwnd is at
15037 			 * least tcp_recv_hiwat_mss * MSS
15038 			 * large, and round up to the nearest
15039 			 * MSS.
15040 			 *
15041 			 * We do the round up here because
15042 			 * we need to get the interface
15043 			 * MTU first before we can do the
15044 			 * round up.
15045 			 */
15046 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15047 			    tcp_recv_hiwat_minmss * mss);
15048 			q->q_hiwat = tcp->tcp_rwnd;
15049 			tcp_set_ws_value(tcp);
15050 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15051 			    tcp->tcp_tcph->th_win);
15052 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15053 				tcp->tcp_snd_ws_ok = B_TRUE;
15054 
15055 			/*
15056 			 * Set tcp_snd_ts_ok to true
15057 			 * so that tcp_xmit_mp will
15058 			 * include the timestamp
15059 			 * option in the SYN segment.
15060 			 */
15061 			if (tcp_tstamp_always ||
15062 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15063 				tcp->tcp_snd_ts_ok = B_TRUE;
15064 			}
15065 
15066 			/*
15067 			 * tcp_snd_sack_ok can be set in
15068 			 * tcp_adapt_ire() if the sack metric
15069 			 * is set.  So check it here also.
15070 			 */
15071 			if (tcp_sack_permitted == 2 ||
15072 			    tcp->tcp_snd_sack_ok) {
15073 				if (tcp->tcp_sack_info == NULL) {
15074 					tcp->tcp_sack_info =
15075 					kmem_cache_alloc(tcp_sack_info_cache,
15076 					    KM_SLEEP);
15077 				}
15078 				tcp->tcp_snd_sack_ok = B_TRUE;
15079 			}
15080 
15081 			/*
15082 			 * Should we use ECN?  Note that the current
15083 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15084 			 * is 1.  The reason for doing this is that there
15085 			 * are equipments out there that will drop ECN
15086 			 * enabled IP packets.  Setting it to 1 avoids
15087 			 * compatibility problems.
15088 			 */
15089 			if (tcp_ecn_permitted == 2)
15090 				tcp->tcp_ecn_ok = B_TRUE;
15091 
15092 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15093 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15094 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15095 			if (syn_mp) {
15096 				cred_t *cr;
15097 				pid_t pid;
15098 
15099 				/*
15100 				 * Obtain the credential from the
15101 				 * thread calling connect(); the credential
15102 				 * lives on in the second mblk which
15103 				 * originated from T_CONN_REQ and is echoed
15104 				 * with the T_BIND_ACK from ip.  If none
15105 				 * can be found, default to the creator
15106 				 * of the socket.
15107 				 */
15108 				if (mp->b_cont == NULL ||
15109 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15110 					cr = tcp->tcp_cred;
15111 					pid = tcp->tcp_cpid;
15112 				} else {
15113 					pid = DB_CPID(mp->b_cont);
15114 				}
15115 
15116 				TCP_RECORD_TRACE(tcp, syn_mp,
15117 				    TCP_TRACE_SEND_PKT);
15118 				mblk_setcred(syn_mp, cr);
15119 				DB_CPID(syn_mp) = pid;
15120 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15121 			}
15122 		after_syn_sent:
15123 			/*
15124 			 * A trailer mblk indicates a waiting client upstream.
15125 			 * We complete here the processing begun in
15126 			 * either tcp_bind() or tcp_connect() by passing
15127 			 * upstream the reply message they supplied.
15128 			 */
15129 			mp1 = mp;
15130 			mp = mp->b_cont;
15131 			freeb(mp1);
15132 			if (mp)
15133 				break;
15134 			return;
15135 		case T_ERROR_ACK:
15136 			if (tcp->tcp_debug) {
15137 				(void) strlog(TCP_MOD_ID, 0, 1,
15138 				    SL_TRACE|SL_ERROR,
15139 				    "tcp_rput_other: case T_ERROR_ACK, "
15140 				    "ERROR_prim == %d",
15141 				    tea->ERROR_prim);
15142 			}
15143 			switch (tea->ERROR_prim) {
15144 			case O_T_BIND_REQ:
15145 			case T_BIND_REQ:
15146 				tcp_bind_failed(tcp, mp,
15147 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15148 				    ENETUNREACH : EADDRNOTAVAIL));
15149 				return;
15150 			case T_UNBIND_REQ:
15151 				tcp->tcp_hard_binding = B_FALSE;
15152 				tcp->tcp_hard_bound = B_FALSE;
15153 				if (mp->b_cont) {
15154 					freemsg(mp->b_cont);
15155 					mp->b_cont = NULL;
15156 				}
15157 				if (tcp->tcp_unbind_pending)
15158 					tcp->tcp_unbind_pending = 0;
15159 				else {
15160 					/* From tcp_ip_unbind() - free */
15161 					freemsg(mp);
15162 					return;
15163 				}
15164 				break;
15165 			case T_SVR4_OPTMGMT_REQ:
15166 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15167 					/* T_OPTMGMT_REQ generated by TCP */
15168 					printf("T_SVR4_OPTMGMT_REQ failed "
15169 					    "%d/%d - dropped (cnt %d)\n",
15170 					    tea->TLI_error, tea->UNIX_error,
15171 					    tcp->tcp_drop_opt_ack_cnt);
15172 					freemsg(mp);
15173 					tcp->tcp_drop_opt_ack_cnt--;
15174 					return;
15175 				}
15176 				break;
15177 			}
15178 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15179 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15180 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15181 				    "- dropped (cnt %d)\n",
15182 				    tea->TLI_error, tea->UNIX_error,
15183 				    tcp->tcp_drop_opt_ack_cnt);
15184 				freemsg(mp);
15185 				tcp->tcp_drop_opt_ack_cnt--;
15186 				return;
15187 			}
15188 			break;
15189 		case T_OPTMGMT_ACK:
15190 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15191 				/* T_OPTMGMT_REQ generated by TCP */
15192 				freemsg(mp);
15193 				tcp->tcp_drop_opt_ack_cnt--;
15194 				return;
15195 			}
15196 			break;
15197 		default:
15198 			break;
15199 		}
15200 		break;
15201 	case M_CTL:
15202 		/*
15203 		 * ICMP messages.
15204 		 */
15205 		tcp_icmp_error(tcp, mp);
15206 		return;
15207 	case M_FLUSH:
15208 		if (*rptr & FLUSHR)
15209 			flushq(q, FLUSHDATA);
15210 		break;
15211 	default:
15212 		break;
15213 	}
15214 	/*
15215 	 * Make sure we set this bit before sending the ACK for
15216 	 * bind. Otherwise accept could possibly run and free
15217 	 * this tcp struct.
15218 	 */
15219 	putnext(q, mp);
15220 }
15221 
15222 /*
15223  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15224  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15225  * tcp_rsrv() try again.
15226  */
15227 static void
15228 tcp_ordrel_kick(void *arg)
15229 {
15230 	conn_t 	*connp = (conn_t *)arg;
15231 	tcp_t	*tcp = connp->conn_tcp;
15232 
15233 	tcp->tcp_ordrelid = 0;
15234 	tcp->tcp_timeout = B_FALSE;
15235 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15236 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15237 		qenable(tcp->tcp_rq);
15238 	}
15239 }
15240 
15241 /* ARGSUSED */
15242 static void
15243 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15244 {
15245 	conn_t	*connp = (conn_t *)arg;
15246 	tcp_t	*tcp = connp->conn_tcp;
15247 	queue_t	*q = tcp->tcp_rq;
15248 	uint_t	thwin;
15249 
15250 	freeb(mp);
15251 
15252 	TCP_STAT(tcp_rsrv_calls);
15253 
15254 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15255 		return;
15256 	}
15257 
15258 	if (tcp->tcp_fused) {
15259 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15260 
15261 		ASSERT(tcp->tcp_fused);
15262 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15263 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15264 		ASSERT(!TCP_IS_DETACHED(tcp));
15265 		ASSERT(tcp->tcp_connp->conn_sqp ==
15266 		    peer_tcp->tcp_connp->conn_sqp);
15267 
15268 		/*
15269 		 * Normally we would not get backenabled in synchronous
15270 		 * streams mode, but in case this happens, we need to stop
15271 		 * synchronous streams temporarily to prevent a race with
15272 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15273 		 * tcp_rcv_list here because those entry points will return
15274 		 * right away when synchronous streams is stopped.
15275 		 */
15276 		TCP_FUSE_SYNCSTR_STOP(tcp);
15277 		if (tcp->tcp_rcv_list != NULL)
15278 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15279 
15280 		tcp_clrqfull(peer_tcp);
15281 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15282 		TCP_STAT(tcp_fusion_backenabled);
15283 		return;
15284 	}
15285 
15286 	if (canputnext(q)) {
15287 		tcp->tcp_rwnd = q->q_hiwat;
15288 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15289 		    << tcp->tcp_rcv_ws;
15290 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15291 		/*
15292 		 * Send back a window update immediately if TCP is above
15293 		 * ESTABLISHED state and the increase of the rcv window
15294 		 * that the other side knows is at least 1 MSS after flow
15295 		 * control is lifted.
15296 		 */
15297 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15298 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15299 			tcp_xmit_ctl(NULL, tcp,
15300 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15301 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15302 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15303 		}
15304 	}
15305 	/* Handle a failure to allocate a T_ORDREL_IND here */
15306 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15307 		ASSERT(tcp->tcp_listener == NULL);
15308 		if (tcp->tcp_rcv_list != NULL) {
15309 			(void) tcp_rcv_drain(q, tcp);
15310 		}
15311 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15312 		mp = mi_tpi_ordrel_ind();
15313 		if (mp) {
15314 			tcp->tcp_ordrel_done = B_TRUE;
15315 			putnext(q, mp);
15316 			if (tcp->tcp_deferred_clean_death) {
15317 				/*
15318 				 * tcp_clean_death was deferred for
15319 				 * T_ORDREL_IND - do it now
15320 				 */
15321 				tcp->tcp_deferred_clean_death = B_FALSE;
15322 				(void) tcp_clean_death(tcp,
15323 				    tcp->tcp_client_errno, 22);
15324 			}
15325 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15326 			/*
15327 			 * If there isn't already a timer running
15328 			 * start one.  Use a 4 second
15329 			 * timer as a fallback since it can't fail.
15330 			 */
15331 			tcp->tcp_timeout = B_TRUE;
15332 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15333 			    MSEC_TO_TICK(4000));
15334 		}
15335 	}
15336 }
15337 
15338 /*
15339  * The read side service routine is called mostly when we get back-enabled as a
15340  * result of flow control relief.  Since we don't actually queue anything in
15341  * TCP, we have no data to send out of here.  What we do is clear the receive
15342  * window, and send out a window update.
15343  * This routine is also called to drive an orderly release message upstream
15344  * if the attempt in tcp_rput failed.
15345  */
15346 static void
15347 tcp_rsrv(queue_t *q)
15348 {
15349 	conn_t *connp = Q_TO_CONN(q);
15350 	tcp_t	*tcp = connp->conn_tcp;
15351 	mblk_t	*mp;
15352 
15353 	/* No code does a putq on the read side */
15354 	ASSERT(q->q_first == NULL);
15355 
15356 	/* Nothing to do for the default queue */
15357 	if (q == tcp_g_q) {
15358 		return;
15359 	}
15360 
15361 	mp = allocb(0, BPRI_HI);
15362 	if (mp == NULL) {
15363 		/*
15364 		 * We are under memory pressure. Return for now and we
15365 		 * we will be called again later.
15366 		 */
15367 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15368 			/*
15369 			 * If there isn't already a timer running
15370 			 * start one.  Use a 4 second
15371 			 * timer as a fallback since it can't fail.
15372 			 */
15373 			tcp->tcp_timeout = B_TRUE;
15374 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15375 			    MSEC_TO_TICK(4000));
15376 		}
15377 		return;
15378 	}
15379 	CONN_INC_REF(connp);
15380 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15381 	    SQTAG_TCP_RSRV);
15382 }
15383 
15384 /*
15385  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15386  * We do not allow the receive window to shrink.  After setting rwnd,
15387  * set the flow control hiwat of the stream.
15388  *
15389  * This function is called in 2 cases:
15390  *
15391  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15392  *    connection (passive open) and in tcp_rput_data() for active connect.
15393  *    This is called after tcp_mss_set() when the desired MSS value is known.
15394  *    This makes sure that our window size is a mutiple of the other side's
15395  *    MSS.
15396  * 2) Handling SO_RCVBUF option.
15397  *
15398  * It is ASSUMED that the requested size is a multiple of the current MSS.
15399  *
15400  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15401  * user requests so.
15402  */
15403 static int
15404 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15405 {
15406 	uint32_t	mss = tcp->tcp_mss;
15407 	uint32_t	old_max_rwnd;
15408 	uint32_t	max_transmittable_rwnd;
15409 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15410 
15411 	if (tcp->tcp_fused) {
15412 		size_t sth_hiwat;
15413 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15414 
15415 		ASSERT(peer_tcp != NULL);
15416 		/*
15417 		 * Record the stream head's high water mark for
15418 		 * this endpoint; this is used for flow-control
15419 		 * purposes in tcp_fuse_output().
15420 		 */
15421 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15422 		if (!tcp_detached)
15423 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15424 
15425 		/*
15426 		 * In the fusion case, the maxpsz stream head value of
15427 		 * our peer is set according to its send buffer size
15428 		 * and our receive buffer size; since the latter may
15429 		 * have changed we need to update the peer's maxpsz.
15430 		 */
15431 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15432 		return (rwnd);
15433 	}
15434 
15435 	if (tcp_detached)
15436 		old_max_rwnd = tcp->tcp_rwnd;
15437 	else
15438 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15439 
15440 	/*
15441 	 * Insist on a receive window that is at least
15442 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15443 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15444 	 * and delayed acknowledgement.
15445 	 */
15446 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15447 
15448 	/*
15449 	 * If window size info has already been exchanged, TCP should not
15450 	 * shrink the window.  Shrinking window is doable if done carefully.
15451 	 * We may add that support later.  But so far there is not a real
15452 	 * need to do that.
15453 	 */
15454 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15455 		/* MSS may have changed, do a round up again. */
15456 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15457 	}
15458 
15459 	/*
15460 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15461 	 * can be applied even before the window scale option is decided.
15462 	 */
15463 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15464 	if (rwnd > max_transmittable_rwnd) {
15465 		rwnd = max_transmittable_rwnd -
15466 		    (max_transmittable_rwnd % mss);
15467 		if (rwnd < mss)
15468 			rwnd = max_transmittable_rwnd;
15469 		/*
15470 		 * If we're over the limit we may have to back down tcp_rwnd.
15471 		 * The increment below won't work for us. So we set all three
15472 		 * here and the increment below will have no effect.
15473 		 */
15474 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15475 	}
15476 	if (tcp->tcp_localnet) {
15477 		tcp->tcp_rack_abs_max =
15478 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15479 	} else {
15480 		/*
15481 		 * For a remote host on a different subnet (through a router),
15482 		 * we ack every other packet to be conforming to RFC1122.
15483 		 * tcp_deferred_acks_max is default to 2.
15484 		 */
15485 		tcp->tcp_rack_abs_max =
15486 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15487 	}
15488 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15489 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15490 	else
15491 		tcp->tcp_rack_cur_max = 0;
15492 	/*
15493 	 * Increment the current rwnd by the amount the maximum grew (we
15494 	 * can not overwrite it since we might be in the middle of a
15495 	 * connection.)
15496 	 */
15497 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15498 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15499 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15500 		tcp->tcp_cwnd_max = rwnd;
15501 
15502 	if (tcp_detached)
15503 		return (rwnd);
15504 	/*
15505 	 * We set the maximum receive window into rq->q_hiwat.
15506 	 * This is not actually used for flow control.
15507 	 */
15508 	tcp->tcp_rq->q_hiwat = rwnd;
15509 	/*
15510 	 * Set the Stream head high water mark. This doesn't have to be
15511 	 * here, since we are simply using default values, but we would
15512 	 * prefer to choose these values algorithmically, with a likely
15513 	 * relationship to rwnd.
15514 	 */
15515 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15516 	return (rwnd);
15517 }
15518 
15519 /*
15520  * Return SNMP stuff in buffer in mpdata.
15521  */
15522 int
15523 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15524 {
15525 	mblk_t			*mpdata;
15526 	mblk_t			*mp_conn_ctl = NULL;
15527 	mblk_t			*mp_conn_data;
15528 	mblk_t			*mp6_conn_ctl = NULL;
15529 	mblk_t			*mp6_conn_data;
15530 	mblk_t			*mp_conn_tail = NULL;
15531 	mblk_t			*mp6_conn_tail = NULL;
15532 	struct opthdr		*optp;
15533 	mib2_tcpConnEntry_t	tce;
15534 	mib2_tcp6ConnEntry_t	tce6;
15535 	connf_t			*connfp;
15536 	conn_t			*connp;
15537 	int			i;
15538 	boolean_t 		ispriv;
15539 	zoneid_t 		zoneid;
15540 
15541 	if (mpctl == NULL ||
15542 	    (mpdata = mpctl->b_cont) == NULL ||
15543 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15544 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
15545 		if (mp_conn_ctl != NULL)
15546 			freemsg(mp_conn_ctl);
15547 		if (mp6_conn_ctl != NULL)
15548 			freemsg(mp6_conn_ctl);
15549 		return (0);
15550 	}
15551 
15552 	/* build table of connections -- need count in fixed part */
15553 	mp_conn_data = mp_conn_ctl->b_cont;
15554 	mp6_conn_data = mp6_conn_ctl->b_cont;
15555 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15556 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15557 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15558 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15559 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15560 
15561 	ispriv =
15562 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15563 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15564 
15565 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15566 
15567 		connfp = &ipcl_globalhash_fanout[i];
15568 
15569 		connp = NULL;
15570 
15571 		while ((connp =
15572 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15573 			tcp_t *tcp;
15574 
15575 			if (connp->conn_zoneid != zoneid)
15576 				continue;	/* not in this zone */
15577 
15578 			tcp = connp->conn_tcp;
15579 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15580 			tcp->tcp_ibsegs = 0;
15581 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15582 			tcp->tcp_obsegs = 0;
15583 
15584 			tce6.tcp6ConnState = tce.tcpConnState =
15585 			    tcp_snmp_state(tcp);
15586 			if (tce.tcpConnState == MIB2_TCP_established ||
15587 			    tce.tcpConnState == MIB2_TCP_closeWait)
15588 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15589 
15590 			/* Create a message to report on IPv6 entries */
15591 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15592 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15593 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15594 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15595 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15596 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15597 			/* Don't want just anybody seeing these... */
15598 			if (ispriv) {
15599 				tce6.tcp6ConnEntryInfo.ce_snxt =
15600 				    tcp->tcp_snxt;
15601 				tce6.tcp6ConnEntryInfo.ce_suna =
15602 				    tcp->tcp_suna;
15603 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15604 				    tcp->tcp_rnxt;
15605 				tce6.tcp6ConnEntryInfo.ce_rack =
15606 				    tcp->tcp_rack;
15607 			} else {
15608 				/*
15609 				 * Netstat, unfortunately, uses this to
15610 				 * get send/receive queue sizes.  How to fix?
15611 				 * Why not compute the difference only?
15612 				 */
15613 				tce6.tcp6ConnEntryInfo.ce_snxt =
15614 				    tcp->tcp_snxt - tcp->tcp_suna;
15615 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15616 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15617 				    tcp->tcp_rnxt - tcp->tcp_rack;
15618 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15619 			}
15620 
15621 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15622 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15623 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15624 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15625 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15626 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
15627 			    (char *)&tce6, sizeof (tce6));
15628 			}
15629 			/*
15630 			 * Create an IPv4 table entry for IPv4 entries and also
15631 			 * for IPv6 entries which are bound to in6addr_any
15632 			 * but don't have IPV6_V6ONLY set.
15633 			 * (i.e. anything an IPv4 peer could connect to)
15634 			 */
15635 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15636 			    (tcp->tcp_state <= TCPS_LISTEN &&
15637 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15638 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15639 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15640 					tce.tcpConnRemAddress = INADDR_ANY;
15641 					tce.tcpConnLocalAddress = INADDR_ANY;
15642 				} else {
15643 					tce.tcpConnRemAddress =
15644 					    tcp->tcp_remote;
15645 					tce.tcpConnLocalAddress =
15646 					    tcp->tcp_ip_src;
15647 				}
15648 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15649 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15650 				/* Don't want just anybody seeing these... */
15651 				if (ispriv) {
15652 					tce.tcpConnEntryInfo.ce_snxt =
15653 					    tcp->tcp_snxt;
15654 					tce.tcpConnEntryInfo.ce_suna =
15655 					    tcp->tcp_suna;
15656 					tce.tcpConnEntryInfo.ce_rnxt =
15657 					    tcp->tcp_rnxt;
15658 					tce.tcpConnEntryInfo.ce_rack =
15659 					    tcp->tcp_rack;
15660 				} else {
15661 					/*
15662 					 * Netstat, unfortunately, uses this to
15663 					 * get send/receive queue sizes.  How
15664 					 * to fix?
15665 					 * Why not compute the difference only?
15666 					 */
15667 					tce.tcpConnEntryInfo.ce_snxt =
15668 					    tcp->tcp_snxt - tcp->tcp_suna;
15669 					tce.tcpConnEntryInfo.ce_suna = 0;
15670 					tce.tcpConnEntryInfo.ce_rnxt =
15671 					    tcp->tcp_rnxt - tcp->tcp_rack;
15672 					tce.tcpConnEntryInfo.ce_rack = 0;
15673 				}
15674 
15675 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15676 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15677 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15678 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15679 				tce.tcpConnEntryInfo.ce_state =
15680 				    tcp->tcp_state;
15681 				(void) snmp_append_data2(mp_conn_data,
15682 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15683 			}
15684 		}
15685 	}
15686 
15687 	/* fixed length structure for IPv4 and IPv6 counters */
15688 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15689 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15690 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15691 	optp->level = MIB2_TCP;
15692 	optp->name = 0;
15693 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15694 	optp->len = msgdsize(mpdata);
15695 	qreply(q, mpctl);
15696 
15697 	/* table of connections... */
15698 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15699 	    sizeof (struct T_optmgmt_ack)];
15700 	optp->level = MIB2_TCP;
15701 	optp->name = MIB2_TCP_CONN;
15702 	optp->len = msgdsize(mp_conn_data);
15703 	qreply(q, mp_conn_ctl);
15704 
15705 	/* table of IPv6 connections... */
15706 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15707 	    sizeof (struct T_optmgmt_ack)];
15708 	optp->level = MIB2_TCP6;
15709 	optp->name = MIB2_TCP6_CONN;
15710 	optp->len = msgdsize(mp6_conn_data);
15711 	qreply(q, mp6_conn_ctl);
15712 	return (1);
15713 }
15714 
15715 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15716 /* ARGSUSED */
15717 int
15718 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
15719 {
15720 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
15721 
15722 	switch (level) {
15723 	case MIB2_TCP:
15724 		switch (name) {
15725 		case 13:
15726 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
15727 				return (0);
15728 			/* TODO: delete entry defined by tce */
15729 			return (1);
15730 		default:
15731 			return (0);
15732 		}
15733 	default:
15734 		return (1);
15735 	}
15736 }
15737 
15738 /* Translate TCP state to MIB2 TCP state. */
15739 static int
15740 tcp_snmp_state(tcp_t *tcp)
15741 {
15742 	if (tcp == NULL)
15743 		return (0);
15744 
15745 	switch (tcp->tcp_state) {
15746 	case TCPS_CLOSED:
15747 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
15748 	case TCPS_BOUND:
15749 		return (MIB2_TCP_closed);
15750 	case TCPS_LISTEN:
15751 		return (MIB2_TCP_listen);
15752 	case TCPS_SYN_SENT:
15753 		return (MIB2_TCP_synSent);
15754 	case TCPS_SYN_RCVD:
15755 		return (MIB2_TCP_synReceived);
15756 	case TCPS_ESTABLISHED:
15757 		return (MIB2_TCP_established);
15758 	case TCPS_CLOSE_WAIT:
15759 		return (MIB2_TCP_closeWait);
15760 	case TCPS_FIN_WAIT_1:
15761 		return (MIB2_TCP_finWait1);
15762 	case TCPS_CLOSING:
15763 		return (MIB2_TCP_closing);
15764 	case TCPS_LAST_ACK:
15765 		return (MIB2_TCP_lastAck);
15766 	case TCPS_FIN_WAIT_2:
15767 		return (MIB2_TCP_finWait2);
15768 	case TCPS_TIME_WAIT:
15769 		return (MIB2_TCP_timeWait);
15770 	default:
15771 		return (0);
15772 	}
15773 }
15774 
15775 static char tcp_report_header[] =
15776 	"TCP     " MI_COL_HDRPAD_STR
15777 	"zone dest            snxt     suna     "
15778 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
15779 	"recent   [lport,fport] state";
15780 
15781 /*
15782  * TCP status report triggered via the Named Dispatch mechanism.
15783  */
15784 /* ARGSUSED */
15785 static void
15786 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
15787     cred_t *cr)
15788 {
15789 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
15790 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
15791 	char cflag;
15792 	in6_addr_t	v6dst;
15793 	char buf[80];
15794 	uint_t print_len, buf_len;
15795 
15796 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15797 	if (buf_len <= 0)
15798 		return;
15799 
15800 	if (hashval >= 0)
15801 		(void) sprintf(hash, "%03d ", hashval);
15802 	else
15803 		hash[0] = '\0';
15804 
15805 	/*
15806 	 * Note that we use the remote address in the tcp_b  structure.
15807 	 * This means that it will print out the real destination address,
15808 	 * not the next hop's address if source routing is used.  This
15809 	 * avoid the confusion on the output because user may not
15810 	 * know that source routing is used for a connection.
15811 	 */
15812 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15813 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
15814 	} else {
15815 		v6dst = tcp->tcp_remote_v6;
15816 	}
15817 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15818 	/*
15819 	 * the ispriv checks are so that normal users cannot determine
15820 	 * sequence number information using NDD.
15821 	 */
15822 
15823 	if (TCP_IS_DETACHED(tcp))
15824 		cflag = '*';
15825 	else
15826 		cflag = ' ';
15827 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15828 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
15829 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
15830 	    hash,
15831 	    (void *)tcp,
15832 	    tcp->tcp_connp->conn_zoneid,
15833 	    addrbuf,
15834 	    (ispriv) ? tcp->tcp_snxt : 0,
15835 	    (ispriv) ? tcp->tcp_suna : 0,
15836 	    tcp->tcp_swnd,
15837 	    (ispriv) ? tcp->tcp_rnxt : 0,
15838 	    (ispriv) ? tcp->tcp_rack : 0,
15839 	    tcp->tcp_rwnd,
15840 	    tcp->tcp_rto,
15841 	    tcp->tcp_mss,
15842 	    tcp->tcp_snd_ws_ok,
15843 	    tcp->tcp_snd_ws,
15844 	    tcp->tcp_rcv_ws,
15845 	    tcp->tcp_snd_ts_ok,
15846 	    tcp->tcp_ts_recent,
15847 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
15848 	if (print_len < buf_len) {
15849 		((mblk_t *)mp)->b_wptr += print_len;
15850 	} else {
15851 		((mblk_t *)mp)->b_wptr += buf_len;
15852 	}
15853 }
15854 
15855 /*
15856  * TCP status report (for listeners only) triggered via the Named Dispatch
15857  * mechanism.
15858  */
15859 /* ARGSUSED */
15860 static void
15861 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
15862 {
15863 	char addrbuf[INET6_ADDRSTRLEN];
15864 	in6_addr_t	v6dst;
15865 	uint_t print_len, buf_len;
15866 
15867 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15868 	if (buf_len <= 0)
15869 		return;
15870 
15871 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15872 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
15873 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15874 	} else {
15875 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
15876 		    addrbuf, sizeof (addrbuf));
15877 	}
15878 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15879 	    "%03d "
15880 	    MI_COL_PTRFMT_STR
15881 	    "%d %s %05u %08u %d/%d/%d%c\n",
15882 	    hashval, (void *)tcp,
15883 	    tcp->tcp_connp->conn_zoneid,
15884 	    addrbuf,
15885 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
15886 	    tcp->tcp_conn_req_seqnum,
15887 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
15888 	    tcp->tcp_conn_req_max,
15889 	    tcp->tcp_syn_defense ? '*' : ' ');
15890 	if (print_len < buf_len) {
15891 		((mblk_t *)mp)->b_wptr += print_len;
15892 	} else {
15893 		((mblk_t *)mp)->b_wptr += buf_len;
15894 	}
15895 }
15896 
15897 /* TCP status report triggered via the Named Dispatch mechanism. */
15898 /* ARGSUSED */
15899 static int
15900 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15901 {
15902 	tcp_t	*tcp;
15903 	int	i;
15904 	conn_t	*connp;
15905 	connf_t	*connfp;
15906 	zoneid_t zoneid;
15907 
15908 	/*
15909 	 * Because of the ndd constraint, at most we can have 64K buffer
15910 	 * to put in all TCP info.  So to be more efficient, just
15911 	 * allocate a 64K buffer here, assuming we need that large buffer.
15912 	 * This may be a problem as any user can read tcp_status.  Therefore
15913 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
15914 	 * This should be OK as normal users should not do this too often.
15915 	 */
15916 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15917 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15918 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15919 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15920 			return (0);
15921 		}
15922 	}
15923 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15924 		/* The following may work even if we cannot get a large buf. */
15925 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15926 		return (0);
15927 	}
15928 
15929 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
15930 
15931 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15932 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15933 
15934 		connfp = &ipcl_globalhash_fanout[i];
15935 
15936 		connp = NULL;
15937 
15938 		while ((connp =
15939 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15940 			tcp = connp->conn_tcp;
15941 			if (zoneid != GLOBAL_ZONEID &&
15942 			    zoneid != connp->conn_zoneid)
15943 				continue;
15944 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
15945 			    cr);
15946 		}
15947 
15948 	}
15949 
15950 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15951 	return (0);
15952 }
15953 
15954 /* TCP status report triggered via the Named Dispatch mechanism. */
15955 /* ARGSUSED */
15956 static int
15957 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15958 {
15959 	tf_t	*tbf;
15960 	tcp_t	*tcp;
15961 	int	i;
15962 	zoneid_t zoneid;
15963 
15964 	/* Refer to comments in tcp_status_report(). */
15965 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15966 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15967 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15968 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15969 			return (0);
15970 		}
15971 	}
15972 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15973 		/* The following may work even if we cannot get a large buf. */
15974 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15975 		return (0);
15976 	}
15977 
15978 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
15979 
15980 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15981 
15982 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
15983 		tbf = &tcp_bind_fanout[i];
15984 		mutex_enter(&tbf->tf_lock);
15985 		for (tcp = tbf->tf_tcp; tcp != NULL;
15986 		    tcp = tcp->tcp_bind_hash) {
15987 			if (zoneid != GLOBAL_ZONEID &&
15988 			    zoneid != tcp->tcp_connp->conn_zoneid)
15989 				continue;
15990 			CONN_INC_REF(tcp->tcp_connp);
15991 			tcp_report_item(mp->b_cont, tcp, i,
15992 			    Q_TO_TCP(q), cr);
15993 			CONN_DEC_REF(tcp->tcp_connp);
15994 		}
15995 		mutex_exit(&tbf->tf_lock);
15996 	}
15997 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
15998 	return (0);
15999 }
16000 
16001 /* TCP status report triggered via the Named Dispatch mechanism. */
16002 /* ARGSUSED */
16003 static int
16004 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16005 {
16006 	connf_t	*connfp;
16007 	conn_t	*connp;
16008 	tcp_t	*tcp;
16009 	int	i;
16010 	zoneid_t zoneid;
16011 
16012 	/* Refer to comments in tcp_status_report(). */
16013 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16014 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16015 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16016 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16017 			return (0);
16018 		}
16019 	}
16020 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16021 		/* The following may work even if we cannot get a large buf. */
16022 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16023 		return (0);
16024 	}
16025 
16026 	(void) mi_mpprintf(mp,
16027 	    "    TCP    " MI_COL_HDRPAD_STR
16028 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16029 
16030 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16031 
16032 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16033 		connfp =  &ipcl_bind_fanout[i];
16034 		connp = NULL;
16035 		while ((connp =
16036 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16037 			tcp = connp->conn_tcp;
16038 			if (zoneid != GLOBAL_ZONEID &&
16039 			    zoneid != connp->conn_zoneid)
16040 				continue;
16041 			tcp_report_listener(mp->b_cont, tcp, i);
16042 		}
16043 	}
16044 
16045 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16046 	return (0);
16047 }
16048 
16049 /* TCP status report triggered via the Named Dispatch mechanism. */
16050 /* ARGSUSED */
16051 static int
16052 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16053 {
16054 	connf_t	*connfp;
16055 	conn_t	*connp;
16056 	tcp_t	*tcp;
16057 	int	i;
16058 	zoneid_t zoneid;
16059 
16060 	/* Refer to comments in tcp_status_report(). */
16061 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16062 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16063 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16064 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16065 			return (0);
16066 		}
16067 	}
16068 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16069 		/* The following may work even if we cannot get a large buf. */
16070 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16071 		return (0);
16072 	}
16073 
16074 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16075 	    ipcl_conn_fanout_size);
16076 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16077 
16078 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16079 
16080 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16081 		connfp =  &ipcl_conn_fanout[i];
16082 		connp = NULL;
16083 		while ((connp =
16084 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16085 			tcp = connp->conn_tcp;
16086 			if (zoneid != GLOBAL_ZONEID &&
16087 			    zoneid != connp->conn_zoneid)
16088 				continue;
16089 			tcp_report_item(mp->b_cont, tcp, i,
16090 			    Q_TO_TCP(q), cr);
16091 		}
16092 	}
16093 
16094 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16095 	return (0);
16096 }
16097 
16098 /* TCP status report triggered via the Named Dispatch mechanism. */
16099 /* ARGSUSED */
16100 static int
16101 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16102 {
16103 	tf_t	*tf;
16104 	tcp_t	*tcp;
16105 	int	i;
16106 	zoneid_t zoneid;
16107 
16108 	/* Refer to comments in tcp_status_report(). */
16109 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16110 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16111 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16112 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16113 			return (0);
16114 		}
16115 	}
16116 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16117 		/* The following may work even if we cannot get a large buf. */
16118 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16119 		return (0);
16120 	}
16121 
16122 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16123 
16124 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16125 
16126 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16127 		tf = &tcp_acceptor_fanout[i];
16128 		mutex_enter(&tf->tf_lock);
16129 		for (tcp = tf->tf_tcp; tcp != NULL;
16130 		    tcp = tcp->tcp_acceptor_hash) {
16131 			if (zoneid != GLOBAL_ZONEID &&
16132 			    zoneid != tcp->tcp_connp->conn_zoneid)
16133 				continue;
16134 			tcp_report_item(mp->b_cont, tcp, i,
16135 			    Q_TO_TCP(q), cr);
16136 		}
16137 		mutex_exit(&tf->tf_lock);
16138 	}
16139 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16140 	return (0);
16141 }
16142 
16143 /*
16144  * tcp_timer is the timer service routine.  It handles the retransmission,
16145  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16146  * from the state of the tcp instance what kind of action needs to be done
16147  * at the time it is called.
16148  */
16149 static void
16150 tcp_timer(void *arg)
16151 {
16152 	mblk_t		*mp;
16153 	clock_t		first_threshold;
16154 	clock_t		second_threshold;
16155 	clock_t		ms;
16156 	uint32_t	mss;
16157 	conn_t		*connp = (conn_t *)arg;
16158 	tcp_t		*tcp = connp->conn_tcp;
16159 
16160 	tcp->tcp_timer_tid = 0;
16161 
16162 	if (tcp->tcp_fused)
16163 		return;
16164 
16165 	first_threshold =  tcp->tcp_first_timer_threshold;
16166 	second_threshold = tcp->tcp_second_timer_threshold;
16167 	switch (tcp->tcp_state) {
16168 	case TCPS_IDLE:
16169 	case TCPS_BOUND:
16170 	case TCPS_LISTEN:
16171 		return;
16172 	case TCPS_SYN_RCVD: {
16173 		tcp_t	*listener = tcp->tcp_listener;
16174 
16175 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16176 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16177 			/* it's our first timeout */
16178 			tcp->tcp_syn_rcvd_timeout = 1;
16179 			mutex_enter(&listener->tcp_eager_lock);
16180 			listener->tcp_syn_rcvd_timeout++;
16181 			if (!listener->tcp_syn_defense &&
16182 			    (listener->tcp_syn_rcvd_timeout >
16183 			    (tcp_conn_req_max_q0 >> 2)) &&
16184 			    (tcp_conn_req_max_q0 > 200)) {
16185 				/* We may be under attack. Put on a defense. */
16186 				listener->tcp_syn_defense = B_TRUE;
16187 				cmn_err(CE_WARN, "High TCP connect timeout "
16188 				    "rate! System (port %d) may be under a "
16189 				    "SYN flood attack!",
16190 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16191 
16192 				listener->tcp_ip_addr_cache = kmem_zalloc(
16193 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16194 				    KM_NOSLEEP);
16195 			}
16196 			mutex_exit(&listener->tcp_eager_lock);
16197 		}
16198 	}
16199 		/* FALLTHRU */
16200 	case TCPS_SYN_SENT:
16201 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16202 		second_threshold = tcp->tcp_second_ctimer_threshold;
16203 		break;
16204 	case TCPS_ESTABLISHED:
16205 	case TCPS_FIN_WAIT_1:
16206 	case TCPS_CLOSING:
16207 	case TCPS_CLOSE_WAIT:
16208 	case TCPS_LAST_ACK:
16209 		/* If we have data to rexmit */
16210 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16211 			clock_t	time_to_wait;
16212 
16213 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16214 			if (!tcp->tcp_xmit_head)
16215 				break;
16216 			time_to_wait = lbolt -
16217 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16218 			time_to_wait = tcp->tcp_rto -
16219 			    TICK_TO_MSEC(time_to_wait);
16220 			/*
16221 			 * If the timer fires too early, 1 clock tick earlier,
16222 			 * restart the timer.
16223 			 */
16224 			if (time_to_wait > msec_per_tick) {
16225 				TCP_STAT(tcp_timer_fire_early);
16226 				TCP_TIMER_RESTART(tcp, time_to_wait);
16227 				return;
16228 			}
16229 			/*
16230 			 * When we probe zero windows, we force the swnd open.
16231 			 * If our peer acks with a closed window swnd will be
16232 			 * set to zero by tcp_rput(). As long as we are
16233 			 * receiving acks tcp_rput will
16234 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16235 			 * first and second interval actions.  NOTE: the timer
16236 			 * interval is allowed to continue its exponential
16237 			 * backoff.
16238 			 */
16239 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16240 				if (tcp->tcp_debug) {
16241 					(void) strlog(TCP_MOD_ID, 0, 1,
16242 					    SL_TRACE, "tcp_timer: zero win");
16243 				}
16244 			} else {
16245 				/*
16246 				 * After retransmission, we need to do
16247 				 * slow start.  Set the ssthresh to one
16248 				 * half of current effective window and
16249 				 * cwnd to one MSS.  Also reset
16250 				 * tcp_cwnd_cnt.
16251 				 *
16252 				 * Note that if tcp_ssthresh is reduced because
16253 				 * of ECN, do not reduce it again unless it is
16254 				 * already one window of data away (tcp_cwr
16255 				 * should then be cleared) or this is a
16256 				 * timeout for a retransmitted segment.
16257 				 */
16258 				uint32_t npkt;
16259 
16260 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16261 					npkt = ((tcp->tcp_timer_backoff ?
16262 					    tcp->tcp_cwnd_ssthresh :
16263 					    tcp->tcp_snxt -
16264 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16265 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16266 					    tcp->tcp_mss;
16267 				}
16268 				tcp->tcp_cwnd = tcp->tcp_mss;
16269 				tcp->tcp_cwnd_cnt = 0;
16270 				if (tcp->tcp_ecn_ok) {
16271 					tcp->tcp_cwr = B_TRUE;
16272 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16273 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16274 				}
16275 			}
16276 			break;
16277 		}
16278 		/*
16279 		 * We have something to send yet we cannot send.  The
16280 		 * reason can be:
16281 		 *
16282 		 * 1. Zero send window: we need to do zero window probe.
16283 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16284 		 * segments.
16285 		 * 3. SWS avoidance: receiver may have shrunk window,
16286 		 * reset our knowledge.
16287 		 *
16288 		 * Note that condition 2 can happen with either 1 or
16289 		 * 3.  But 1 and 3 are exclusive.
16290 		 */
16291 		if (tcp->tcp_unsent != 0) {
16292 			if (tcp->tcp_cwnd == 0) {
16293 				/*
16294 				 * Set tcp_cwnd to 1 MSS so that a
16295 				 * new segment can be sent out.  We
16296 				 * are "clocking out" new data when
16297 				 * the network is really congested.
16298 				 */
16299 				ASSERT(tcp->tcp_ecn_ok);
16300 				tcp->tcp_cwnd = tcp->tcp_mss;
16301 			}
16302 			if (tcp->tcp_swnd == 0) {
16303 				/* Extend window for zero window probe */
16304 				tcp->tcp_swnd++;
16305 				tcp->tcp_zero_win_probe = B_TRUE;
16306 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16307 			} else {
16308 				/*
16309 				 * Handle timeout from sender SWS avoidance.
16310 				 * Reset our knowledge of the max send window
16311 				 * since the receiver might have reduced its
16312 				 * receive buffer.  Avoid setting tcp_max_swnd
16313 				 * to one since that will essentially disable
16314 				 * the SWS checks.
16315 				 *
16316 				 * Note that since we don't have a SWS
16317 				 * state variable, if the timeout is set
16318 				 * for ECN but not for SWS, this
16319 				 * code will also be executed.  This is
16320 				 * fine as tcp_max_swnd is updated
16321 				 * constantly and it will not affect
16322 				 * anything.
16323 				 */
16324 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16325 			}
16326 			tcp_wput_data(tcp, NULL, B_FALSE);
16327 			return;
16328 		}
16329 		/* Is there a FIN that needs to be to re retransmitted? */
16330 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16331 		    !tcp->tcp_fin_acked)
16332 			break;
16333 		/* Nothing to do, return without restarting timer. */
16334 		TCP_STAT(tcp_timer_fire_miss);
16335 		return;
16336 	case TCPS_FIN_WAIT_2:
16337 		/*
16338 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16339 		 * We waited some time for for peer's FIN, but it hasn't
16340 		 * arrived.  We flush the connection now to avoid
16341 		 * case where the peer has rebooted.
16342 		 */
16343 		if (TCP_IS_DETACHED(tcp)) {
16344 			(void) tcp_clean_death(tcp, 0, 23);
16345 		} else {
16346 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16347 		}
16348 		return;
16349 	case TCPS_TIME_WAIT:
16350 		(void) tcp_clean_death(tcp, 0, 24);
16351 		return;
16352 	default:
16353 		if (tcp->tcp_debug) {
16354 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16355 			    "tcp_timer: strange state (%d) %s",
16356 			    tcp->tcp_state, tcp_display(tcp, NULL,
16357 			    DISP_PORT_ONLY));
16358 		}
16359 		return;
16360 	}
16361 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16362 		/*
16363 		 * For zero window probe, we need to send indefinitely,
16364 		 * unless we have not heard from the other side for some
16365 		 * time...
16366 		 */
16367 		if ((tcp->tcp_zero_win_probe == 0) ||
16368 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16369 		    second_threshold)) {
16370 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16371 			/*
16372 			 * If TCP is in SYN_RCVD state, send back a
16373 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16374 			 * should be zero in TCPS_SYN_RCVD state.
16375 			 */
16376 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16377 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16378 				    "in SYN_RCVD",
16379 				    tcp, tcp->tcp_snxt,
16380 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16381 			}
16382 			(void) tcp_clean_death(tcp,
16383 			    tcp->tcp_client_errno ?
16384 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16385 			return;
16386 		} else {
16387 			/*
16388 			 * Set tcp_ms_we_have_waited to second_threshold
16389 			 * so that in next timeout, we will do the above
16390 			 * check (lbolt - tcp_last_recv_time).  This is
16391 			 * also to avoid overflow.
16392 			 *
16393 			 * We don't need to decrement tcp_timer_backoff
16394 			 * to avoid overflow because it will be decremented
16395 			 * later if new timeout value is greater than
16396 			 * tcp_rexmit_interval_max.  In the case when
16397 			 * tcp_rexmit_interval_max is greater than
16398 			 * second_threshold, it means that we will wait
16399 			 * longer than second_threshold to send the next
16400 			 * window probe.
16401 			 */
16402 			tcp->tcp_ms_we_have_waited = second_threshold;
16403 		}
16404 	} else if (ms > first_threshold) {
16405 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16406 		    tcp->tcp_xmit_head != NULL) {
16407 			tcp->tcp_xmit_head =
16408 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16409 		}
16410 		/*
16411 		 * We have been retransmitting for too long...  The RTT
16412 		 * we calculated is probably incorrect.  Reinitialize it.
16413 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16414 		 * tcp_rtt_update so that we won't accidentally cache a
16415 		 * bad value.  But only do this if this is not a zero
16416 		 * window probe.
16417 		 */
16418 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16419 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16420 			    (tcp->tcp_rtt_sa >> 5);
16421 			tcp->tcp_rtt_sa = 0;
16422 			tcp_ip_notify(tcp);
16423 			tcp->tcp_rtt_update = 0;
16424 		}
16425 	}
16426 	tcp->tcp_timer_backoff++;
16427 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16428 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16429 	    tcp_rexmit_interval_min) {
16430 		/*
16431 		 * This means the original RTO is tcp_rexmit_interval_min.
16432 		 * So we will use tcp_rexmit_interval_min as the RTO value
16433 		 * and do the backoff.
16434 		 */
16435 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16436 	} else {
16437 		ms <<= tcp->tcp_timer_backoff;
16438 	}
16439 	if (ms > tcp_rexmit_interval_max) {
16440 		ms = tcp_rexmit_interval_max;
16441 		/*
16442 		 * ms is at max, decrement tcp_timer_backoff to avoid
16443 		 * overflow.
16444 		 */
16445 		tcp->tcp_timer_backoff--;
16446 	}
16447 	tcp->tcp_ms_we_have_waited += ms;
16448 	if (tcp->tcp_zero_win_probe == 0) {
16449 		tcp->tcp_rto = ms;
16450 	}
16451 	TCP_TIMER_RESTART(tcp, ms);
16452 	/*
16453 	 * This is after a timeout and tcp_rto is backed off.  Set
16454 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16455 	 * restart the timer with a correct value.
16456 	 */
16457 	tcp->tcp_set_timer = 1;
16458 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16459 	if (mss > tcp->tcp_mss)
16460 		mss = tcp->tcp_mss;
16461 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16462 		mss = tcp->tcp_swnd;
16463 
16464 	if ((mp = tcp->tcp_xmit_head) != NULL)
16465 		mp->b_prev = (mblk_t *)lbolt;
16466 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16467 	    B_TRUE);
16468 
16469 	/*
16470 	 * When slow start after retransmission begins, start with
16471 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16472 	 * start phase.  tcp_snd_burst controls how many segments
16473 	 * can be sent because of an ack.
16474 	 */
16475 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16476 	tcp->tcp_snd_burst = TCP_CWND_SS;
16477 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16478 	    (tcp->tcp_unsent == 0)) {
16479 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16480 	} else {
16481 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16482 	}
16483 	tcp->tcp_rexmit = B_TRUE;
16484 	tcp->tcp_dupack_cnt = 0;
16485 
16486 	/*
16487 	 * Remove all rexmit SACK blk to start from fresh.
16488 	 */
16489 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16490 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16491 		tcp->tcp_num_notsack_blk = 0;
16492 		tcp->tcp_cnt_notsack_list = 0;
16493 	}
16494 	if (mp == NULL) {
16495 		return;
16496 	}
16497 	/* Attach credentials to retransmitted initial SYNs. */
16498 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16499 		mblk_setcred(mp, tcp->tcp_cred);
16500 		DB_CPID(mp) = tcp->tcp_cpid;
16501 	}
16502 
16503 	tcp->tcp_csuna = tcp->tcp_snxt;
16504 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16505 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16506 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16507 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16508 
16509 }
16510 
16511 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16512 static void
16513 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16514 {
16515 	conn_t	*connp;
16516 
16517 	switch (tcp->tcp_state) {
16518 	case TCPS_BOUND:
16519 	case TCPS_LISTEN:
16520 		break;
16521 	default:
16522 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16523 		return;
16524 	}
16525 
16526 	/*
16527 	 * Need to clean up all the eagers since after the unbind, segments
16528 	 * will no longer be delivered to this listener stream.
16529 	 */
16530 	mutex_enter(&tcp->tcp_eager_lock);
16531 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16532 		tcp_eager_cleanup(tcp, 0);
16533 	}
16534 	mutex_exit(&tcp->tcp_eager_lock);
16535 
16536 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16537 		tcp->tcp_ipha->ipha_src = 0;
16538 	} else {
16539 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16540 	}
16541 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16542 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16543 	tcp_bind_hash_remove(tcp);
16544 	tcp->tcp_state = TCPS_IDLE;
16545 	tcp->tcp_mdt = B_FALSE;
16546 	/* Send M_FLUSH according to TPI */
16547 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16548 	connp = tcp->tcp_connp;
16549 	connp->conn_mdt_ok = B_FALSE;
16550 	ipcl_hash_remove(connp);
16551 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16552 	mp = mi_tpi_ok_ack_alloc(mp);
16553 	putnext(tcp->tcp_rq, mp);
16554 }
16555 
16556 /*
16557  * Don't let port fall into the privileged range.
16558  * Since the extra privileged ports can be arbitrary we also
16559  * ensure that we exclude those from consideration.
16560  * tcp_g_epriv_ports is not sorted thus we loop over it until
16561  * there are no changes.
16562  *
16563  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16564  * but instead the code relies on:
16565  * - the fact that the address of the array and its size never changes
16566  * - the atomic assignment of the elements of the array
16567  */
16568 static in_port_t
16569 tcp_update_next_port(in_port_t port, boolean_t random)
16570 {
16571 	int i;
16572 
16573 	if (random && tcp_random_anon_port != 0) {
16574 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16575 		    sizeof (in_port_t));
16576 		/*
16577 		 * Unless changed by a sys admin, the smallest anon port
16578 		 * is 32768 and the largest anon port is 65535.  It is
16579 		 * very likely (50%) for the random port to be smaller
16580 		 * than the smallest anon port.  When that happens,
16581 		 * add port % (anon port range) to the smallest anon
16582 		 * port to get the random port.  It should fall into the
16583 		 * valid anon port range.
16584 		 */
16585 		if (port < tcp_smallest_anon_port) {
16586 			port = tcp_smallest_anon_port +
16587 			    port % (tcp_largest_anon_port -
16588 				tcp_smallest_anon_port);
16589 		}
16590 	}
16591 
16592 retry:
16593 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
16594 		port = (in_port_t)tcp_smallest_anon_port;
16595 
16596 	if (port < tcp_smallest_nonpriv_port)
16597 		port = (in_port_t)tcp_smallest_nonpriv_port;
16598 
16599 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16600 		if (port == tcp_g_epriv_ports[i]) {
16601 			port++;
16602 			/*
16603 			 * Make sure whether the port is in the
16604 			 * valid range.
16605 			 *
16606 			 * XXX Note that if tcp_g_epriv_ports contains
16607 			 * all the anonymous ports this will be an
16608 			 * infinite loop.
16609 			 */
16610 			goto retry;
16611 		}
16612 	}
16613 	return (port);
16614 }
16615 
16616 /*
16617  * Return the next anonymous port in the priviledged port range for
16618  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16619  * downwards.  This is the same behavior as documented in the userland
16620  * library call rresvport(3N).
16621  */
16622 static in_port_t
16623 tcp_get_next_priv_port(void)
16624 {
16625 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16626 
16627 	if (next_priv_port < tcp_min_anonpriv_port) {
16628 		next_priv_port = IPPORT_RESERVED - 1;
16629 	}
16630 	return (next_priv_port--);
16631 }
16632 
16633 /* The write side r/w procedure. */
16634 
16635 #if CCS_STATS
16636 struct {
16637 	struct {
16638 		int64_t count, bytes;
16639 	} tot, hit;
16640 } wrw_stats;
16641 #endif
16642 
16643 /*
16644  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16645  * messages.
16646  */
16647 /* ARGSUSED */
16648 static void
16649 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16650 {
16651 	conn_t	*connp = (conn_t *)arg;
16652 	tcp_t	*tcp = connp->conn_tcp;
16653 	queue_t	*q = tcp->tcp_wq;
16654 
16655 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16656 	/*
16657 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16658 	 * Once the close starts, streamhead and sockfs will not let any data
16659 	 * packets come down (close ensures that there are no threads using the
16660 	 * queue and no new threads will come down) but since qprocsoff()
16661 	 * hasn't happened yet, a M_FLUSH or some non data message might
16662 	 * get reflected back (in response to our own FLUSHRW) and get
16663 	 * processed after tcp_close() is done. The conn would still be valid
16664 	 * because a ref would have added but we need to check the state
16665 	 * before actually processing the packet.
16666 	 */
16667 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16668 		freemsg(mp);
16669 		return;
16670 	}
16671 
16672 	switch (DB_TYPE(mp)) {
16673 	case M_IOCDATA:
16674 		tcp_wput_iocdata(tcp, mp);
16675 		break;
16676 	case M_FLUSH:
16677 		tcp_wput_flush(tcp, mp);
16678 		break;
16679 	default:
16680 		CALL_IP_WPUT(connp, q, mp);
16681 		break;
16682 	}
16683 }
16684 
16685 /*
16686  * The TCP fast path write put procedure.
16687  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16688  */
16689 /* ARGSUSED */
16690 void
16691 tcp_output(void *arg, mblk_t *mp, void *arg2)
16692 {
16693 	int		len;
16694 	int		hdrlen;
16695 	int		plen;
16696 	mblk_t		*mp1;
16697 	uchar_t		*rptr;
16698 	uint32_t	snxt;
16699 	tcph_t		*tcph;
16700 	struct datab	*db;
16701 	uint32_t	suna;
16702 	uint32_t	mss;
16703 	ipaddr_t	*dst;
16704 	ipaddr_t	*src;
16705 	uint32_t	sum;
16706 	int		usable;
16707 	conn_t		*connp = (conn_t *)arg;
16708 	tcp_t		*tcp = connp->conn_tcp;
16709 	uint32_t	msize;
16710 
16711 	/*
16712 	 * Try and ASSERT the minimum possible references on the
16713 	 * conn early enough. Since we are executing on write side,
16714 	 * the connection is obviously not detached and that means
16715 	 * there is a ref each for TCP and IP. Since we are behind
16716 	 * the squeue, the minimum references needed are 3. If the
16717 	 * conn is in classifier hash list, there should be an
16718 	 * extra ref for that (we check both the possibilities).
16719 	 */
16720 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16721 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16722 
16723 	/* Bypass tcp protocol for fused tcp loopback */
16724 	if (tcp->tcp_fused) {
16725 		msize = msgdsize(mp);
16726 		mutex_enter(&connp->conn_lock);
16727 		tcp->tcp_squeue_bytes -= msize;
16728 		mutex_exit(&connp->conn_lock);
16729 
16730 		if (tcp_fuse_output(tcp, mp, msize))
16731 			return;
16732 	}
16733 
16734 	mss = tcp->tcp_mss;
16735 	if (tcp->tcp_xmit_zc_clean)
16736 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16737 
16738 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16739 	len = (int)(mp->b_wptr - mp->b_rptr);
16740 
16741 	/*
16742 	 * Criteria for fast path:
16743 	 *
16744 	 *   1. no unsent data
16745 	 *   2. single mblk in request
16746 	 *   3. connection established
16747 	 *   4. data in mblk
16748 	 *   5. len <= mss
16749 	 *   6. no tcp_valid bits
16750 	 */
16751 	if ((tcp->tcp_unsent != 0) ||
16752 	    (tcp->tcp_cork) ||
16753 	    (mp->b_cont != NULL) ||
16754 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16755 	    (len == 0) ||
16756 	    (len > mss) ||
16757 	    (tcp->tcp_valid_bits != 0)) {
16758 		msize = msgdsize(mp);
16759 		mutex_enter(&connp->conn_lock);
16760 		tcp->tcp_squeue_bytes -= msize;
16761 		mutex_exit(&connp->conn_lock);
16762 
16763 		tcp_wput_data(tcp, mp, B_FALSE);
16764 		return;
16765 	}
16766 
16767 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16768 	ASSERT(tcp->tcp_fin_sent == 0);
16769 
16770 	mutex_enter(&connp->conn_lock);
16771 	tcp->tcp_squeue_bytes -= len;
16772 	mutex_exit(&connp->conn_lock);
16773 
16774 	/* queue new packet onto retransmission queue */
16775 	if (tcp->tcp_xmit_head == NULL) {
16776 		tcp->tcp_xmit_head = mp;
16777 	} else {
16778 		tcp->tcp_xmit_last->b_cont = mp;
16779 	}
16780 	tcp->tcp_xmit_last = mp;
16781 	tcp->tcp_xmit_tail = mp;
16782 
16783 	/* find out how much we can send */
16784 	/* BEGIN CSTYLED */
16785 	/*
16786 	 *    un-acked           usable
16787 	 *  |--------------|-----------------|
16788 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
16789 	 */
16790 	/* END CSTYLED */
16791 
16792 	/* start sending from tcp_snxt */
16793 	snxt = tcp->tcp_snxt;
16794 
16795 	/*
16796 	 * Check to see if this connection has been idled for some
16797 	 * time and no ACK is expected.  If it is, we need to slow
16798 	 * start again to get back the connection's "self-clock" as
16799 	 * described in VJ's paper.
16800 	 *
16801 	 * Refer to the comment in tcp_mss_set() for the calculation
16802 	 * of tcp_cwnd after idle.
16803 	 */
16804 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16805 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16806 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
16807 	}
16808 
16809 	usable = tcp->tcp_swnd;		/* tcp window size */
16810 	if (usable > tcp->tcp_cwnd)
16811 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16812 	usable -= snxt;		/* subtract stuff already sent */
16813 	suna = tcp->tcp_suna;
16814 	usable += suna;
16815 	/* usable can be < 0 if the congestion window is smaller */
16816 	if (len > usable) {
16817 		/* Can't send complete M_DATA in one shot */
16818 		goto slow;
16819 	}
16820 
16821 	if (tcp->tcp_flow_stopped &&
16822 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16823 		tcp_clrqfull(tcp);
16824 	}
16825 
16826 	/*
16827 	 * determine if anything to send (Nagle).
16828 	 *
16829 	 *   1. len < tcp_mss (i.e. small)
16830 	 *   2. unacknowledged data present
16831 	 *   3. len < nagle limit
16832 	 *   4. last packet sent < nagle limit (previous packet sent)
16833 	 */
16834 	if ((len < mss) && (snxt != suna) &&
16835 	    (len < (int)tcp->tcp_naglim) &&
16836 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16837 		/*
16838 		 * This was the first unsent packet and normally
16839 		 * mss < xmit_hiwater so there is no need to worry
16840 		 * about flow control. The next packet will go
16841 		 * through the flow control check in tcp_wput_data().
16842 		 */
16843 		/* leftover work from above */
16844 		tcp->tcp_unsent = len;
16845 		tcp->tcp_xmit_tail_unsent = len;
16846 
16847 		return;
16848 	}
16849 
16850 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16851 
16852 	if (snxt == suna) {
16853 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16854 	}
16855 
16856 	/* we have always sent something */
16857 	tcp->tcp_rack_cnt = 0;
16858 
16859 	tcp->tcp_snxt = snxt + len;
16860 	tcp->tcp_rack = tcp->tcp_rnxt;
16861 
16862 	if ((mp1 = dupb(mp)) == 0)
16863 		goto no_memory;
16864 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16865 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16866 
16867 	/* adjust tcp header information */
16868 	tcph = tcp->tcp_tcph;
16869 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16870 
16871 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16872 	sum = (sum >> 16) + (sum & 0xFFFF);
16873 	U16_TO_ABE16(sum, tcph->th_sum);
16874 
16875 	U32_TO_ABE32(snxt, tcph->th_seq);
16876 
16877 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
16878 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
16879 	BUMP_LOCAL(tcp->tcp_obsegs);
16880 
16881 	/* Update the latest receive window size in TCP header. */
16882 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16883 	    tcph->th_win);
16884 
16885 	tcp->tcp_last_sent_len = (ushort_t)len;
16886 
16887 	plen = len + tcp->tcp_hdr_len;
16888 
16889 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16890 		tcp->tcp_ipha->ipha_length = htons(plen);
16891 	} else {
16892 		tcp->tcp_ip6h->ip6_plen = htons(plen -
16893 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
16894 	}
16895 
16896 	/* see if we need to allocate a mblk for the headers */
16897 	hdrlen = tcp->tcp_hdr_len;
16898 	rptr = mp1->b_rptr - hdrlen;
16899 	db = mp1->b_datap;
16900 	if ((db->db_ref != 2) || rptr < db->db_base ||
16901 	    (!OK_32PTR(rptr))) {
16902 		/* NOTE: we assume allocb returns an OK_32PTR */
16903 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
16904 		    tcp_wroff_xtra, BPRI_MED);
16905 		if (!mp) {
16906 			freemsg(mp1);
16907 			goto no_memory;
16908 		}
16909 		mp->b_cont = mp1;
16910 		mp1 = mp;
16911 		/* Leave room for Link Level header */
16912 		/* hdrlen = tcp->tcp_hdr_len; */
16913 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
16914 		mp1->b_wptr = &rptr[hdrlen];
16915 	}
16916 	mp1->b_rptr = rptr;
16917 
16918 	/* Fill in the timestamp option. */
16919 	if (tcp->tcp_snd_ts_ok) {
16920 		U32_TO_BE32((uint32_t)lbolt,
16921 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
16922 		U32_TO_BE32(tcp->tcp_ts_recent,
16923 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
16924 	} else {
16925 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
16926 	}
16927 
16928 	/* copy header into outgoing packet */
16929 	dst = (ipaddr_t *)rptr;
16930 	src = (ipaddr_t *)tcp->tcp_iphc;
16931 	dst[0] = src[0];
16932 	dst[1] = src[1];
16933 	dst[2] = src[2];
16934 	dst[3] = src[3];
16935 	dst[4] = src[4];
16936 	dst[5] = src[5];
16937 	dst[6] = src[6];
16938 	dst[7] = src[7];
16939 	dst[8] = src[8];
16940 	dst[9] = src[9];
16941 	if (hdrlen -= 40) {
16942 		hdrlen >>= 2;
16943 		dst += 10;
16944 		src += 10;
16945 		do {
16946 			*dst++ = *src++;
16947 		} while (--hdrlen);
16948 	}
16949 
16950 	/*
16951 	 * Set the ECN info in the TCP header.  Note that this
16952 	 * is not the template header.
16953 	 */
16954 	if (tcp->tcp_ecn_ok) {
16955 		SET_ECT(tcp, rptr);
16956 
16957 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
16958 		if (tcp->tcp_ecn_echo_on)
16959 			tcph->th_flags[0] |= TH_ECE;
16960 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16961 			tcph->th_flags[0] |= TH_CWR;
16962 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16963 		}
16964 	}
16965 
16966 	if (tcp->tcp_ip_forward_progress) {
16967 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
16968 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
16969 		tcp->tcp_ip_forward_progress = B_FALSE;
16970 	}
16971 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
16972 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
16973 	return;
16974 
16975 	/*
16976 	 * If we ran out of memory, we pretend to have sent the packet
16977 	 * and that it was lost on the wire.
16978 	 */
16979 no_memory:
16980 	return;
16981 
16982 slow:
16983 	/* leftover work from above */
16984 	tcp->tcp_unsent = len;
16985 	tcp->tcp_xmit_tail_unsent = len;
16986 	tcp_wput_data(tcp, NULL, B_FALSE);
16987 }
16988 
16989 /*
16990  * The function called through squeue to get behind eager's perimeter to
16991  * finish the accept processing.
16992  */
16993 /* ARGSUSED */
16994 void
16995 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
16996 {
16997 	conn_t			*connp = (conn_t *)arg;
16998 	tcp_t			*tcp = connp->conn_tcp;
16999 	queue_t			*q = tcp->tcp_rq;
17000 	mblk_t			*mp1;
17001 	mblk_t			*stropt_mp = mp;
17002 	struct  stroptions	*stropt;
17003 	uint_t			thwin;
17004 
17005 	/*
17006 	 * Drop the eager's ref on the listener, that was placed when
17007 	 * this eager began life in tcp_conn_request.
17008 	 */
17009 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17010 
17011 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17012 		/*
17013 		 * Someone blewoff the eager before we could finish
17014 		 * the accept.
17015 		 *
17016 		 * The only reason eager exists it because we put in
17017 		 * a ref on it when conn ind went up. We need to send
17018 		 * a disconnect indication up while the last reference
17019 		 * on the eager will be dropped by the squeue when we
17020 		 * return.
17021 		 */
17022 		ASSERT(tcp->tcp_listener == NULL);
17023 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17024 			struct	T_discon_ind	*tdi;
17025 
17026 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17027 			/*
17028 			 * Let us reuse the incoming mblk to avoid memory
17029 			 * allocation failure problems. We know that the
17030 			 * size of the incoming mblk i.e. stroptions is greater
17031 			 * than sizeof T_discon_ind. So the reallocb below
17032 			 * can't fail.
17033 			 */
17034 			freemsg(mp->b_cont);
17035 			mp->b_cont = NULL;
17036 			ASSERT(DB_REF(mp) == 1);
17037 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17038 			    B_FALSE);
17039 			ASSERT(mp != NULL);
17040 			DB_TYPE(mp) = M_PROTO;
17041 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17042 			tdi = (struct T_discon_ind *)mp->b_rptr;
17043 			if (tcp->tcp_issocket) {
17044 				tdi->DISCON_reason = ECONNREFUSED;
17045 				tdi->SEQ_number = 0;
17046 			} else {
17047 				tdi->DISCON_reason = ENOPROTOOPT;
17048 				tdi->SEQ_number =
17049 				    tcp->tcp_conn_req_seqnum;
17050 			}
17051 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17052 			putnext(q, mp);
17053 		} else {
17054 			freemsg(mp);
17055 		}
17056 		if (tcp->tcp_hard_binding) {
17057 			tcp->tcp_hard_binding = B_FALSE;
17058 			tcp->tcp_hard_bound = B_TRUE;
17059 		}
17060 		tcp->tcp_detached = B_FALSE;
17061 		return;
17062 	}
17063 
17064 	mp1 = stropt_mp->b_cont;
17065 	stropt_mp->b_cont = NULL;
17066 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17067 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17068 
17069 	while (mp1 != NULL) {
17070 		mp = mp1;
17071 		mp1 = mp1->b_cont;
17072 		mp->b_cont = NULL;
17073 		tcp->tcp_drop_opt_ack_cnt++;
17074 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17075 	}
17076 	mp = NULL;
17077 
17078 	/*
17079 	 * For a loopback connection with tcp_direct_sockfs on, note that
17080 	 * we don't have to protect tcp_rcv_list yet because synchronous
17081 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17082 	 * possibly race with us.
17083 	 */
17084 
17085 	/*
17086 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17087 	 * properly.  This is the first time we know of the acceptor'
17088 	 * queue.  So we do it here.
17089 	 */
17090 	if (tcp->tcp_rcv_list == NULL) {
17091 		/*
17092 		 * Recv queue is empty, tcp_rwnd should not have changed.
17093 		 * That means it should be equal to the listener's tcp_rwnd.
17094 		 */
17095 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17096 	} else {
17097 #ifdef DEBUG
17098 		uint_t cnt = 0;
17099 
17100 		mp1 = tcp->tcp_rcv_list;
17101 		while ((mp = mp1) != NULL) {
17102 			mp1 = mp->b_next;
17103 			cnt += msgdsize(mp);
17104 		}
17105 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17106 #endif
17107 		/* There is some data, add them back to get the max. */
17108 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17109 	}
17110 
17111 	stropt->so_flags = SO_HIWAT;
17112 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17113 
17114 	stropt->so_flags |= SO_MAXBLK;
17115 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17116 
17117 	/*
17118 	 * This is the first time we run on the correct
17119 	 * queue after tcp_accept. So fix all the q parameters
17120 	 * here.
17121 	 */
17122 	/* Allocate room for SACK options if needed. */
17123 	stropt->so_flags |= SO_WROFF;
17124 	if (tcp->tcp_fused) {
17125 		ASSERT(tcp->tcp_loopback);
17126 		ASSERT(tcp->tcp_loopback_peer != NULL);
17127 		/*
17128 		 * For fused tcp loopback, set the stream head's write
17129 		 * offset value to zero since we won't be needing any room
17130 		 * for TCP/IP headers.  This would also improve performance
17131 		 * since it would reduce the amount of work done by kmem.
17132 		 * Non-fused tcp loopback case is handled separately below.
17133 		 */
17134 		stropt->so_wroff = 0;
17135 		/*
17136 		 * Record the stream head's high water mark for this endpoint;
17137 		 * this is used for flow-control purposes in tcp_fuse_output().
17138 		 */
17139 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17140 		/*
17141 		 * Update the peer's transmit parameters according to
17142 		 * our recently calculated high water mark value.
17143 		 */
17144 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17145 	} else if (tcp->tcp_snd_sack_ok) {
17146 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17147 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17148 	} else {
17149 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17150 		    tcp_wroff_xtra);
17151 	}
17152 
17153 	/*
17154 	 * If this is endpoint is handling SSL, then reserve extra
17155 	 * offset and space at the end.
17156 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17157 	 * overriding the previous setting. The extra cost of signing and
17158 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17159 	 * instead of a single contiguous one by the stream head
17160 	 * largely outweighs the statistical reduction of ACKs, when
17161 	 * applicable. The peer will also save on decyption and verification
17162 	 * costs.
17163 	 */
17164 	if (tcp->tcp_kssl_ctx != NULL) {
17165 		stropt->so_wroff += SSL3_WROFFSET;
17166 
17167 		stropt->so_flags |= SO_TAIL;
17168 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17169 
17170 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17171 	}
17172 
17173 	/* Send the options up */
17174 	putnext(q, stropt_mp);
17175 
17176 	/*
17177 	 * Pass up any data and/or a fin that has been received.
17178 	 *
17179 	 * Adjust receive window in case it had decreased
17180 	 * (because there is data <=> tcp_rcv_list != NULL)
17181 	 * while the connection was detached. Note that
17182 	 * in case the eager was flow-controlled, w/o this
17183 	 * code, the rwnd may never open up again!
17184 	 */
17185 	if (tcp->tcp_rcv_list != NULL) {
17186 		/* We drain directly in case of fused tcp loopback */
17187 		if (!tcp->tcp_fused && canputnext(q)) {
17188 			tcp->tcp_rwnd = q->q_hiwat;
17189 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17190 			    << tcp->tcp_rcv_ws;
17191 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17192 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17193 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17194 				tcp_xmit_ctl(NULL,
17195 				    tcp, (tcp->tcp_swnd == 0) ?
17196 				    tcp->tcp_suna : tcp->tcp_snxt,
17197 				    tcp->tcp_rnxt, TH_ACK);
17198 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17199 			}
17200 
17201 		}
17202 		(void) tcp_rcv_drain(q, tcp);
17203 
17204 		/*
17205 		 * For fused tcp loopback, back-enable peer endpoint
17206 		 * if it's currently flow-controlled.
17207 		 */
17208 		if (tcp->tcp_fused &&
17209 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17210 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17211 
17212 			ASSERT(peer_tcp != NULL);
17213 			ASSERT(peer_tcp->tcp_fused);
17214 
17215 			tcp_clrqfull(peer_tcp);
17216 			TCP_STAT(tcp_fusion_backenabled);
17217 		}
17218 	}
17219 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17220 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17221 		mp = mi_tpi_ordrel_ind();
17222 		if (mp) {
17223 			tcp->tcp_ordrel_done = B_TRUE;
17224 			putnext(q, mp);
17225 			if (tcp->tcp_deferred_clean_death) {
17226 				/*
17227 				 * tcp_clean_death was deferred
17228 				 * for T_ORDREL_IND - do it now
17229 				 */
17230 				(void) tcp_clean_death(tcp,
17231 				    tcp->tcp_client_errno, 21);
17232 				tcp->tcp_deferred_clean_death = B_FALSE;
17233 			}
17234 		} else {
17235 			/*
17236 			 * Run the orderly release in the
17237 			 * service routine.
17238 			 */
17239 			qenable(q);
17240 		}
17241 	}
17242 	if (tcp->tcp_hard_binding) {
17243 		tcp->tcp_hard_binding = B_FALSE;
17244 		tcp->tcp_hard_bound = B_TRUE;
17245 	}
17246 
17247 	tcp->tcp_detached = B_FALSE;
17248 
17249 	/* We can enable synchronous streams now */
17250 	if (tcp->tcp_fused) {
17251 		tcp_fuse_syncstr_enable_pair(tcp);
17252 	}
17253 
17254 	if (tcp->tcp_ka_enabled) {
17255 		tcp->tcp_ka_last_intrvl = 0;
17256 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17257 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17258 	}
17259 
17260 	/*
17261 	 * At this point, eager is fully established and will
17262 	 * have the following references -
17263 	 *
17264 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17265 	 * 1 reference for the squeue which will be dropped by the squeue as
17266 	 *	soon as this function returns.
17267 	 * There will be 1 additonal reference for being in classifier
17268 	 *	hash list provided something bad hasn't happened.
17269 	 */
17270 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17271 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17272 }
17273 
17274 /*
17275  * The function called through squeue to get behind listener's perimeter to
17276  * send a deffered conn_ind.
17277  */
17278 /* ARGSUSED */
17279 void
17280 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17281 {
17282 	conn_t	*connp = (conn_t *)arg;
17283 	tcp_t *listener = connp->conn_tcp;
17284 
17285 	if (listener->tcp_state == TCPS_CLOSED ||
17286 	    TCP_IS_DETACHED(listener)) {
17287 		/*
17288 		 * If listener has closed, it would have caused a
17289 		 * a cleanup/blowoff to happen for the eager.
17290 		 */
17291 		tcp_t *tcp;
17292 		struct T_conn_ind	*conn_ind;
17293 
17294 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17295 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17296 		    conn_ind->OPT_length);
17297 		/*
17298 		 * We need to drop the ref on eager that was put
17299 		 * tcp_rput_data() before trying to send the conn_ind
17300 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17301 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17302 		 * listener is closed so we drop the ref.
17303 		 */
17304 		CONN_DEC_REF(tcp->tcp_connp);
17305 		freemsg(mp);
17306 		return;
17307 	}
17308 	putnext(listener->tcp_rq, mp);
17309 }
17310 
17311 
17312 /*
17313  * This is the STREAMS entry point for T_CONN_RES coming down on
17314  * Acceptor STREAM when  sockfs listener does accept processing.
17315  * Read the block comment on top pf tcp_conn_request().
17316  */
17317 void
17318 tcp_wput_accept(queue_t *q, mblk_t *mp)
17319 {
17320 	queue_t *rq = RD(q);
17321 	struct T_conn_res *conn_res;
17322 	tcp_t *eager;
17323 	tcp_t *listener;
17324 	struct T_ok_ack *ok;
17325 	t_scalar_t PRIM_type;
17326 	mblk_t *opt_mp;
17327 	conn_t *econnp;
17328 
17329 	ASSERT(DB_TYPE(mp) == M_PROTO);
17330 
17331 	conn_res = (struct T_conn_res *)mp->b_rptr;
17332 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17333 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17334 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17335 		if (mp != NULL)
17336 			putnext(rq, mp);
17337 		return;
17338 	}
17339 	switch (conn_res->PRIM_type) {
17340 	case O_T_CONN_RES:
17341 	case T_CONN_RES:
17342 		/*
17343 		 * We pass up an err ack if allocb fails. This will
17344 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17345 		 * tcp_eager_blowoff to be called. sockfs will then call
17346 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17347 		 * we need to do the allocb up here because we have to
17348 		 * make sure rq->q_qinfo->qi_qclose still points to the
17349 		 * correct function (tcpclose_accept) in case allocb
17350 		 * fails.
17351 		 */
17352 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17353 		if (opt_mp == NULL) {
17354 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17355 			if (mp != NULL)
17356 				putnext(rq, mp);
17357 			return;
17358 		}
17359 
17360 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17361 		    &eager, conn_res->OPT_length);
17362 		PRIM_type = conn_res->PRIM_type;
17363 		mp->b_datap->db_type = M_PCPROTO;
17364 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17365 		ok = (struct T_ok_ack *)mp->b_rptr;
17366 		ok->PRIM_type = T_OK_ACK;
17367 		ok->CORRECT_prim = PRIM_type;
17368 		econnp = eager->tcp_connp;
17369 		econnp->conn_dev = (dev_t)q->q_ptr;
17370 		eager->tcp_rq = rq;
17371 		eager->tcp_wq = q;
17372 		rq->q_ptr = econnp;
17373 		rq->q_qinfo = &tcp_rinit;
17374 		q->q_ptr = econnp;
17375 		q->q_qinfo = &tcp_winit;
17376 		listener = eager->tcp_listener;
17377 		eager->tcp_issocket = B_TRUE;
17378 		eager->tcp_cred = econnp->conn_cred =
17379 		    listener->tcp_connp->conn_cred;
17380 		crhold(econnp->conn_cred);
17381 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17382 
17383 		/* Put the ref for IP */
17384 		CONN_INC_REF(econnp);
17385 
17386 		/*
17387 		 * We should have minimum of 3 references on the conn
17388 		 * at this point. One each for TCP and IP and one for
17389 		 * the T_conn_ind that was sent up when the 3-way handshake
17390 		 * completed. In the normal case we would also have another
17391 		 * reference (making a total of 4) for the conn being in the
17392 		 * classifier hash list. However the eager could have received
17393 		 * an RST subsequently and tcp_closei_local could have removed
17394 		 * the eager from the classifier hash list, hence we can't
17395 		 * assert that reference.
17396 		 */
17397 		ASSERT(econnp->conn_ref >= 3);
17398 
17399 		/*
17400 		 * Send the new local address also up to sockfs. There
17401 		 * should already be enough space in the mp that came
17402 		 * down from soaccept().
17403 		 */
17404 		if (eager->tcp_family == AF_INET) {
17405 			sin_t *sin;
17406 
17407 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17408 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17409 			sin = (sin_t *)mp->b_wptr;
17410 			mp->b_wptr += sizeof (sin_t);
17411 			sin->sin_family = AF_INET;
17412 			sin->sin_port = eager->tcp_lport;
17413 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17414 		} else {
17415 			sin6_t *sin6;
17416 
17417 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17418 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17419 			sin6 = (sin6_t *)mp->b_wptr;
17420 			mp->b_wptr += sizeof (sin6_t);
17421 			sin6->sin6_family = AF_INET6;
17422 			sin6->sin6_port = eager->tcp_lport;
17423 			if (eager->tcp_ipversion == IPV4_VERSION) {
17424 				sin6->sin6_flowinfo = 0;
17425 				IN6_IPADDR_TO_V4MAPPED(
17426 					eager->tcp_ipha->ipha_src,
17427 					    &sin6->sin6_addr);
17428 			} else {
17429 				ASSERT(eager->tcp_ip6h != NULL);
17430 				sin6->sin6_flowinfo =
17431 				    eager->tcp_ip6h->ip6_vcf &
17432 				    ~IPV6_VERS_AND_FLOW_MASK;
17433 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17434 			}
17435 			sin6->sin6_scope_id = 0;
17436 			sin6->__sin6_src_id = 0;
17437 		}
17438 
17439 		putnext(rq, mp);
17440 
17441 		opt_mp->b_datap->db_type = M_SETOPTS;
17442 		opt_mp->b_wptr += sizeof (struct stroptions);
17443 
17444 		/*
17445 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17446 		 * from listener to acceptor. The message is chained on the
17447 		 * bind_mp which tcp_rput_other will send down to IP.
17448 		 */
17449 		if (listener->tcp_bound_if != 0) {
17450 			/* allocate optmgmt req */
17451 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17452 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17453 			    sizeof (int));
17454 			if (mp != NULL)
17455 				linkb(opt_mp, mp);
17456 		}
17457 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17458 			uint_t on = 1;
17459 
17460 			/* allocate optmgmt req */
17461 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17462 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17463 			if (mp != NULL)
17464 				linkb(opt_mp, mp);
17465 		}
17466 
17467 
17468 		mutex_enter(&listener->tcp_eager_lock);
17469 
17470 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17471 
17472 			tcp_t *tail;
17473 			tcp_t *tcp;
17474 			mblk_t *mp1;
17475 
17476 			tcp = listener->tcp_eager_prev_q0;
17477 			/*
17478 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17479 			 * deferred T_conn_ind queue. We need to get to the head
17480 			 * of the queue in order to send up T_conn_ind the same
17481 			 * order as how the 3WHS is completed.
17482 			 */
17483 			while (tcp != listener) {
17484 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17485 				    !tcp->tcp_kssl_pending)
17486 					break;
17487 				else
17488 					tcp = tcp->tcp_eager_prev_q0;
17489 			}
17490 			/* None of the pending eagers can be sent up now */
17491 			if (tcp == listener)
17492 				goto no_more_eagers;
17493 
17494 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17495 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17496 			/* Move from q0 to q */
17497 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17498 			listener->tcp_conn_req_cnt_q0--;
17499 			listener->tcp_conn_req_cnt_q++;
17500 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17501 			    tcp->tcp_eager_prev_q0;
17502 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17503 			    tcp->tcp_eager_next_q0;
17504 			tcp->tcp_eager_prev_q0 = NULL;
17505 			tcp->tcp_eager_next_q0 = NULL;
17506 			tcp->tcp_conn_def_q0 = B_FALSE;
17507 
17508 			/*
17509 			 * Insert at end of the queue because sockfs sends
17510 			 * down T_CONN_RES in chronological order. Leaving
17511 			 * the older conn indications at front of the queue
17512 			 * helps reducing search time.
17513 			 */
17514 			tail = listener->tcp_eager_last_q;
17515 			if (tail != NULL) {
17516 				tail->tcp_eager_next_q = tcp;
17517 			} else {
17518 				listener->tcp_eager_next_q = tcp;
17519 			}
17520 			listener->tcp_eager_last_q = tcp;
17521 			tcp->tcp_eager_next_q = NULL;
17522 
17523 			/* Need to get inside the listener perimeter */
17524 			CONN_INC_REF(listener->tcp_connp);
17525 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17526 			    tcp_send_pending, listener->tcp_connp,
17527 			    SQTAG_TCP_SEND_PENDING);
17528 		}
17529 no_more_eagers:
17530 		tcp_eager_unlink(eager);
17531 		mutex_exit(&listener->tcp_eager_lock);
17532 
17533 		/*
17534 		 * At this point, the eager is detached from the listener
17535 		 * but we still have an extra refs on eager (apart from the
17536 		 * usual tcp references). The ref was placed in tcp_rput_data
17537 		 * before sending the conn_ind in tcp_send_conn_ind.
17538 		 * The ref will be dropped in tcp_accept_finish().
17539 		 */
17540 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17541 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17542 		return;
17543 	default:
17544 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17545 		if (mp != NULL)
17546 			putnext(rq, mp);
17547 		return;
17548 	}
17549 }
17550 
17551 void
17552 tcp_wput(queue_t *q, mblk_t *mp)
17553 {
17554 	conn_t	*connp = Q_TO_CONN(q);
17555 	tcp_t	*tcp;
17556 	void (*output_proc)();
17557 	t_scalar_t type;
17558 	uchar_t *rptr;
17559 	struct iocblk	*iocp;
17560 	uint32_t	msize;
17561 
17562 	ASSERT(connp->conn_ref >= 2);
17563 
17564 	switch (DB_TYPE(mp)) {
17565 	case M_DATA:
17566 		tcp = connp->conn_tcp;
17567 		ASSERT(tcp != NULL);
17568 
17569 		msize = msgdsize(mp);
17570 
17571 		mutex_enter(&connp->conn_lock);
17572 		CONN_INC_REF_LOCKED(connp);
17573 
17574 		tcp->tcp_squeue_bytes += msize;
17575 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17576 			mutex_exit(&connp->conn_lock);
17577 			tcp_setqfull(tcp);
17578 		} else
17579 			mutex_exit(&connp->conn_lock);
17580 
17581 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17582 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17583 		return;
17584 	case M_PROTO:
17585 	case M_PCPROTO:
17586 		/*
17587 		 * if it is a snmp message, don't get behind the squeue
17588 		 */
17589 		tcp = connp->conn_tcp;
17590 		rptr = mp->b_rptr;
17591 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17592 			type = ((union T_primitives *)rptr)->type;
17593 		} else {
17594 			if (tcp->tcp_debug) {
17595 				(void) strlog(TCP_MOD_ID, 0, 1,
17596 				    SL_ERROR|SL_TRACE,
17597 				    "tcp_wput_proto, dropping one...");
17598 			}
17599 			freemsg(mp);
17600 			return;
17601 		}
17602 		if (type == T_SVR4_OPTMGMT_REQ) {
17603 			cred_t	*cr = DB_CREDDEF(mp,
17604 			    tcp->tcp_cred);
17605 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17606 			    cr)) {
17607 				/*
17608 				 * This was a SNMP request
17609 				 */
17610 				return;
17611 			} else {
17612 				output_proc = tcp_wput_proto;
17613 			}
17614 		} else {
17615 			output_proc = tcp_wput_proto;
17616 		}
17617 		break;
17618 	case M_IOCTL:
17619 		/*
17620 		 * Most ioctls can be processed right away without going via
17621 		 * squeues - process them right here. Those that do require
17622 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17623 		 * are processed by tcp_wput_ioctl().
17624 		 */
17625 		iocp = (struct iocblk *)mp->b_rptr;
17626 		tcp = connp->conn_tcp;
17627 
17628 		switch (iocp->ioc_cmd) {
17629 		case TCP_IOC_ABORT_CONN:
17630 			tcp_ioctl_abort_conn(q, mp);
17631 			return;
17632 		case TI_GETPEERNAME:
17633 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17634 				iocp->ioc_error = ENOTCONN;
17635 				iocp->ioc_count = 0;
17636 				mp->b_datap->db_type = M_IOCACK;
17637 				qreply(q, mp);
17638 				return;
17639 			}
17640 			/* FALLTHRU */
17641 		case TI_GETMYNAME:
17642 			mi_copyin(q, mp, NULL,
17643 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17644 			return;
17645 		case ND_SET:
17646 			/* nd_getset does the necessary checks */
17647 		case ND_GET:
17648 			if (!nd_getset(q, tcp_g_nd, mp)) {
17649 				CALL_IP_WPUT(connp, q, mp);
17650 				return;
17651 			}
17652 			qreply(q, mp);
17653 			return;
17654 		case TCP_IOC_DEFAULT_Q:
17655 			/*
17656 			 * Wants to be the default wq. Check the credentials
17657 			 * first, the rest is executed via squeue.
17658 			 */
17659 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17660 				iocp->ioc_error = EPERM;
17661 				iocp->ioc_count = 0;
17662 				mp->b_datap->db_type = M_IOCACK;
17663 				qreply(q, mp);
17664 				return;
17665 			}
17666 			output_proc = tcp_wput_ioctl;
17667 			break;
17668 		default:
17669 			output_proc = tcp_wput_ioctl;
17670 			break;
17671 		}
17672 		break;
17673 	default:
17674 		output_proc = tcp_wput_nondata;
17675 		break;
17676 	}
17677 
17678 	CONN_INC_REF(connp);
17679 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17680 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17681 }
17682 
17683 /*
17684  * Initial STREAMS write side put() procedure for sockets. It tries to
17685  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17686  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17687  * are handled by tcp_wput() as usual.
17688  *
17689  * All further messages will also be handled by tcp_wput() because we cannot
17690  * be sure that the above short cut is safe later.
17691  */
17692 static void
17693 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17694 {
17695 	conn_t			*connp = Q_TO_CONN(wq);
17696 	tcp_t			*tcp = connp->conn_tcp;
17697 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17698 
17699 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17700 	wq->q_qinfo = &tcp_winit;
17701 
17702 	ASSERT(IPCL_IS_TCP(connp));
17703 	ASSERT(TCP_IS_SOCKET(tcp));
17704 
17705 	if (DB_TYPE(mp) == M_PCPROTO &&
17706 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
17707 	    car->PRIM_type == T_CAPABILITY_REQ) {
17708 		tcp_capability_req(tcp, mp);
17709 		return;
17710 	}
17711 
17712 	tcp_wput(wq, mp);
17713 }
17714 
17715 static boolean_t
17716 tcp_zcopy_check(tcp_t *tcp)
17717 {
17718 	conn_t	*connp = tcp->tcp_connp;
17719 	ire_t	*ire;
17720 	boolean_t	zc_enabled = B_FALSE;
17721 
17722 	if (do_tcpzcopy == 2)
17723 		zc_enabled = B_TRUE;
17724 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
17725 	    IPCL_IS_CONNECTED(connp) &&
17726 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
17727 	    connp->conn_dontroute == 0 &&
17728 	    connp->conn_xmit_if_ill == NULL &&
17729 	    connp->conn_nofailover_ill == NULL &&
17730 	    do_tcpzcopy == 1) {
17731 		/*
17732 		 * the checks above  closely resemble the fast path checks
17733 		 * in tcp_send_data().
17734 		 */
17735 		mutex_enter(&connp->conn_lock);
17736 		ire = connp->conn_ire_cache;
17737 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17738 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17739 			IRE_REFHOLD(ire);
17740 			if (ire->ire_stq != NULL) {
17741 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
17742 
17743 				zc_enabled = ill && (ill->ill_capabilities &
17744 				    ILL_CAPAB_ZEROCOPY) &&
17745 				    (ill->ill_zerocopy_capab->
17746 				    ill_zerocopy_flags != 0);
17747 			}
17748 			IRE_REFRELE(ire);
17749 		}
17750 		mutex_exit(&connp->conn_lock);
17751 	}
17752 	tcp->tcp_snd_zcopy_on = zc_enabled;
17753 	if (!TCP_IS_DETACHED(tcp)) {
17754 		if (zc_enabled) {
17755 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
17756 			TCP_STAT(tcp_zcopy_on);
17757 		} else {
17758 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17759 			TCP_STAT(tcp_zcopy_off);
17760 		}
17761 	}
17762 	return (zc_enabled);
17763 }
17764 
17765 static mblk_t *
17766 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
17767 {
17768 	if (do_tcpzcopy == 2)
17769 		return (bp);
17770 	else if (tcp->tcp_snd_zcopy_on) {
17771 		tcp->tcp_snd_zcopy_on = B_FALSE;
17772 		if (!TCP_IS_DETACHED(tcp)) {
17773 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17774 			TCP_STAT(tcp_zcopy_disable);
17775 		}
17776 	}
17777 	return (tcp_zcopy_backoff(tcp, bp, 0));
17778 }
17779 
17780 /*
17781  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
17782  * the original desballoca'ed segmapped mblk.
17783  */
17784 static mblk_t *
17785 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
17786 {
17787 	mblk_t *head, *tail, *nbp;
17788 	if (IS_VMLOANED_MBLK(bp)) {
17789 		TCP_STAT(tcp_zcopy_backoff);
17790 		if ((head = copyb(bp)) == NULL) {
17791 			/* fail to backoff; leave it for the next backoff */
17792 			tcp->tcp_xmit_zc_clean = B_FALSE;
17793 			return (bp);
17794 		}
17795 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17796 			if (fix_xmitlist)
17797 				tcp_zcopy_notify(tcp);
17798 			else
17799 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
17800 		}
17801 		nbp = bp->b_cont;
17802 		if (fix_xmitlist) {
17803 			head->b_prev = bp->b_prev;
17804 			head->b_next = bp->b_next;
17805 			if (tcp->tcp_xmit_tail == bp)
17806 				tcp->tcp_xmit_tail = head;
17807 		}
17808 		bp->b_next = NULL;
17809 		bp->b_prev = NULL;
17810 		freeb(bp);
17811 	} else {
17812 		head = bp;
17813 		nbp = bp->b_cont;
17814 	}
17815 	tail = head;
17816 	while (nbp) {
17817 		if (IS_VMLOANED_MBLK(nbp)) {
17818 			TCP_STAT(tcp_zcopy_backoff);
17819 			if ((tail->b_cont = copyb(nbp)) == NULL) {
17820 				tcp->tcp_xmit_zc_clean = B_FALSE;
17821 				tail->b_cont = nbp;
17822 				return (head);
17823 			}
17824 			tail = tail->b_cont;
17825 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17826 				if (fix_xmitlist)
17827 					tcp_zcopy_notify(tcp);
17828 				else
17829 					tail->b_datap->db_struioflag |=
17830 					    STRUIO_ZCNOTIFY;
17831 			}
17832 			bp = nbp;
17833 			nbp = nbp->b_cont;
17834 			if (fix_xmitlist) {
17835 				tail->b_prev = bp->b_prev;
17836 				tail->b_next = bp->b_next;
17837 				if (tcp->tcp_xmit_tail == bp)
17838 					tcp->tcp_xmit_tail = tail;
17839 			}
17840 			bp->b_next = NULL;
17841 			bp->b_prev = NULL;
17842 			freeb(bp);
17843 		} else {
17844 			tail->b_cont = nbp;
17845 			tail = nbp;
17846 			nbp = nbp->b_cont;
17847 		}
17848 	}
17849 	if (fix_xmitlist) {
17850 		tcp->tcp_xmit_last = tail;
17851 		tcp->tcp_xmit_zc_clean = B_TRUE;
17852 	}
17853 	return (head);
17854 }
17855 
17856 static void
17857 tcp_zcopy_notify(tcp_t *tcp)
17858 {
17859 	struct stdata	*stp;
17860 
17861 	if (tcp->tcp_detached)
17862 		return;
17863 	stp = STREAM(tcp->tcp_rq);
17864 	mutex_enter(&stp->sd_lock);
17865 	stp->sd_flag |= STZCNOTIFY;
17866 	cv_broadcast(&stp->sd_zcopy_wait);
17867 	mutex_exit(&stp->sd_lock);
17868 }
17869 
17870 static void
17871 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
17872 {
17873 	ipha_t		*ipha;
17874 	ipaddr_t	src;
17875 	ipaddr_t	dst;
17876 	uint32_t	cksum;
17877 	ire_t		*ire;
17878 	uint16_t	*up;
17879 	ill_t		*ill;
17880 	conn_t		*connp = tcp->tcp_connp;
17881 	uint32_t	hcksum_txflags = 0;
17882 	mblk_t		*ire_fp_mp;
17883 	uint_t		ire_fp_mp_len;
17884 
17885 	ASSERT(DB_TYPE(mp) == M_DATA);
17886 
17887 	ipha = (ipha_t *)mp->b_rptr;
17888 	src = ipha->ipha_src;
17889 	dst = ipha->ipha_dst;
17890 
17891 	/*
17892 	 * Drop off slow path for IPv6 and also if options are present.
17893 	 */
17894 	if (tcp->tcp_ipversion != IPV4_VERSION ||
17895 	    !IPCL_IS_CONNECTED(connp) ||
17896 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
17897 	    connp->conn_dontroute ||
17898 	    connp->conn_xmit_if_ill != NULL ||
17899 	    connp->conn_nofailover_ill != NULL ||
17900 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
17901 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
17902 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
17903 		if (tcp->tcp_snd_zcopy_aware)
17904 			mp = tcp_zcopy_disable(tcp, mp);
17905 		TCP_STAT(tcp_ip_send);
17906 		CALL_IP_WPUT(connp, q, mp);
17907 		return;
17908 	}
17909 
17910 	mutex_enter(&connp->conn_lock);
17911 	ire = connp->conn_ire_cache;
17912 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17913 	if (ire != NULL && ire->ire_addr == dst &&
17914 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17915 		IRE_REFHOLD(ire);
17916 		mutex_exit(&connp->conn_lock);
17917 	} else {
17918 		boolean_t cached = B_FALSE;
17919 
17920 		/* force a recheck later on */
17921 		tcp->tcp_ire_ill_check_done = B_FALSE;
17922 
17923 		TCP_DBGSTAT(tcp_ire_null1);
17924 		connp->conn_ire_cache = NULL;
17925 		mutex_exit(&connp->conn_lock);
17926 		if (ire != NULL)
17927 			IRE_REFRELE_NOTR(ire);
17928 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
17929 		if (ire == NULL) {
17930 			if (tcp->tcp_snd_zcopy_aware)
17931 				mp = tcp_zcopy_backoff(tcp, mp, 0);
17932 			TCP_STAT(tcp_ire_null);
17933 			CALL_IP_WPUT(connp, q, mp);
17934 			return;
17935 		}
17936 		IRE_REFHOLD_NOTR(ire);
17937 		/*
17938 		 * Since we are inside the squeue, there cannot be another
17939 		 * thread in TCP trying to set the conn_ire_cache now.  The
17940 		 * check for IRE_MARK_CONDEMNED ensures that an interface
17941 		 * unplumb thread has not yet started cleaning up the conns.
17942 		 * Hence we don't need to grab the conn lock.
17943 		 */
17944 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
17945 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
17946 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17947 				connp->conn_ire_cache = ire;
17948 				cached = B_TRUE;
17949 			}
17950 			rw_exit(&ire->ire_bucket->irb_lock);
17951 		}
17952 
17953 		/*
17954 		 * We can continue to use the ire but since it was
17955 		 * not cached, we should drop the extra reference.
17956 		 */
17957 		if (!cached)
17958 			IRE_REFRELE_NOTR(ire);
17959 	}
17960 
17961 	if (ire->ire_flags & RTF_MULTIRT ||
17962 	    ire->ire_stq == NULL ||
17963 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
17964 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
17965 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
17966 		if (tcp->tcp_snd_zcopy_aware)
17967 			mp = tcp_zcopy_disable(tcp, mp);
17968 		TCP_STAT(tcp_ip_ire_send);
17969 		IRE_REFRELE(ire);
17970 		CALL_IP_WPUT(connp, q, mp);
17971 		return;
17972 	}
17973 
17974 	ill = ire_to_ill(ire);
17975 	if (connp->conn_outgoing_ill != NULL) {
17976 		ill_t *conn_outgoing_ill = NULL;
17977 		/*
17978 		 * Choose a good ill in the group to send the packets on.
17979 		 */
17980 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
17981 		ill = ire_to_ill(ire);
17982 	}
17983 	ASSERT(ill != NULL);
17984 
17985 	if (!tcp->tcp_ire_ill_check_done) {
17986 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
17987 		tcp->tcp_ire_ill_check_done = B_TRUE;
17988 	}
17989 
17990 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
17991 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
17992 #ifndef _BIG_ENDIAN
17993 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
17994 #endif
17995 
17996 	/*
17997 	 * Check to see if we need to re-enable MDT for this connection
17998 	 * because it was previously disabled due to changes in the ill;
17999 	 * note that by doing it here, this re-enabling only applies when
18000 	 * the packet is not dispatched through CALL_IP_WPUT().
18001 	 *
18002 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18003 	 * case, since that's how we ended up here.  For IPv6, we do the
18004 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18005 	 */
18006 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18007 		/*
18008 		 * Restore MDT for this connection, so that next time around
18009 		 * it is eligible to go through tcp_multisend() path again.
18010 		 */
18011 		TCP_STAT(tcp_mdt_conn_resumed1);
18012 		tcp->tcp_mdt = B_TRUE;
18013 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18014 		    "interface %s\n", (void *)connp, ill->ill_name));
18015 	}
18016 
18017 	if (tcp->tcp_snd_zcopy_aware) {
18018 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18019 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18020 			mp = tcp_zcopy_disable(tcp, mp);
18021 		/*
18022 		 * we shouldn't need to reset ipha as the mp containing
18023 		 * ipha should never be a zero-copy mp.
18024 		 */
18025 	}
18026 
18027 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18028 		ASSERT(ill->ill_hcksum_capab != NULL);
18029 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18030 	}
18031 
18032 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18033 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18034 
18035 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18036 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18037 
18038 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18039 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18040 
18041 	/* Software checksum? */
18042 	if (DB_CKSUMFLAGS(mp) == 0) {
18043 		TCP_STAT(tcp_out_sw_cksum);
18044 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18045 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18046 	}
18047 
18048 	ipha->ipha_fragment_offset_and_flags |=
18049 	    (uint32_t)htons(ire->ire_frag_flag);
18050 
18051 	/* Calculate IP header checksum if hardware isn't capable */
18052 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18053 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18054 		    ((uint16_t *)ipha)[4]);
18055 	}
18056 
18057 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18058 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18059 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18060 
18061 	UPDATE_OB_PKT_COUNT(ire);
18062 	ire->ire_last_used_time = lbolt;
18063 	BUMP_MIB(&ip_mib, ipOutRequests);
18064 
18065 	if (ILL_POLL_CAPABLE(ill)) {
18066 		/*
18067 		 * Send the packet directly to DLD, where it may be queued
18068 		 * depending on the availability of transmit resources at
18069 		 * the media layer.
18070 		 */
18071 		IP_POLL_ILL_TX(ill, mp);
18072 	} else {
18073 		putnext(ire->ire_stq, mp);
18074 	}
18075 	IRE_REFRELE(ire);
18076 }
18077 
18078 /*
18079  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18080  * if the receiver shrinks the window, i.e. moves the right window to the
18081  * left, the we should not send new data, but should retransmit normally the
18082  * old unacked data between suna and suna + swnd. We might has sent data
18083  * that is now outside the new window, pretend that we didn't send  it.
18084  */
18085 static void
18086 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18087 {
18088 	uint32_t	snxt = tcp->tcp_snxt;
18089 	mblk_t		*xmit_tail;
18090 	int32_t		offset;
18091 
18092 	ASSERT(shrunk_count > 0);
18093 
18094 	/* Pretend we didn't send the data outside the window */
18095 	snxt -= shrunk_count;
18096 
18097 	/* Get the mblk and the offset in it per the shrunk window */
18098 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18099 
18100 	ASSERT(xmit_tail != NULL);
18101 
18102 	/* Reset all the values per the now shrunk window */
18103 	tcp->tcp_snxt = snxt;
18104 	tcp->tcp_xmit_tail = xmit_tail;
18105 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18106 	    offset;
18107 	tcp->tcp_unsent += shrunk_count;
18108 
18109 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18110 		/*
18111 		 * Make sure the timer is running so that we will probe a zero
18112 		 * window.
18113 		 */
18114 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18115 }
18116 
18117 
18118 /*
18119  * The TCP normal data output path.
18120  * NOTE: the logic of the fast path is duplicated from this function.
18121  */
18122 static void
18123 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18124 {
18125 	int		len;
18126 	mblk_t		*local_time;
18127 	mblk_t		*mp1;
18128 	uint32_t	snxt;
18129 	int		tail_unsent;
18130 	int		tcpstate;
18131 	int		usable = 0;
18132 	mblk_t		*xmit_tail;
18133 	queue_t		*q = tcp->tcp_wq;
18134 	int32_t		mss;
18135 	int32_t		num_sack_blk = 0;
18136 	int32_t		tcp_hdr_len;
18137 	int32_t		tcp_tcp_hdr_len;
18138 	int		mdt_thres;
18139 	int		rc;
18140 
18141 	tcpstate = tcp->tcp_state;
18142 	if (mp == NULL) {
18143 		/*
18144 		 * tcp_wput_data() with NULL mp should only be called when
18145 		 * there is unsent data.
18146 		 */
18147 		ASSERT(tcp->tcp_unsent > 0);
18148 		/* Really tacky... but we need this for detached closes. */
18149 		len = tcp->tcp_unsent;
18150 		goto data_null;
18151 	}
18152 
18153 #if CCS_STATS
18154 	wrw_stats.tot.count++;
18155 	wrw_stats.tot.bytes += msgdsize(mp);
18156 #endif
18157 	ASSERT(mp->b_datap->db_type == M_DATA);
18158 	/*
18159 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18160 	 * or before a connection attempt has begun.
18161 	 */
18162 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18163 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18164 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18165 #ifdef DEBUG
18166 			cmn_err(CE_WARN,
18167 			    "tcp_wput_data: data after ordrel, %s",
18168 			    tcp_display(tcp, NULL,
18169 			    DISP_ADDR_AND_PORT));
18170 #else
18171 			if (tcp->tcp_debug) {
18172 				(void) strlog(TCP_MOD_ID, 0, 1,
18173 				    SL_TRACE|SL_ERROR,
18174 				    "tcp_wput_data: data after ordrel, %s\n",
18175 				    tcp_display(tcp, NULL,
18176 				    DISP_ADDR_AND_PORT));
18177 			}
18178 #endif /* DEBUG */
18179 		}
18180 		if (tcp->tcp_snd_zcopy_aware &&
18181 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18182 			tcp_zcopy_notify(tcp);
18183 		freemsg(mp);
18184 		if (tcp->tcp_flow_stopped &&
18185 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18186 			tcp_clrqfull(tcp);
18187 		}
18188 		return;
18189 	}
18190 
18191 	/* Strip empties */
18192 	for (;;) {
18193 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18194 		    (uintptr_t)INT_MAX);
18195 		len = (int)(mp->b_wptr - mp->b_rptr);
18196 		if (len > 0)
18197 			break;
18198 		mp1 = mp;
18199 		mp = mp->b_cont;
18200 		freeb(mp1);
18201 		if (!mp) {
18202 			return;
18203 		}
18204 	}
18205 
18206 	/* If we are the first on the list ... */
18207 	if (tcp->tcp_xmit_head == NULL) {
18208 		tcp->tcp_xmit_head = mp;
18209 		tcp->tcp_xmit_tail = mp;
18210 		tcp->tcp_xmit_tail_unsent = len;
18211 	} else {
18212 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18213 		struct datab *dp;
18214 
18215 		mp1 = tcp->tcp_xmit_last;
18216 		if (len < tcp_tx_pull_len &&
18217 		    (dp = mp1->b_datap)->db_ref == 1 &&
18218 		    dp->db_lim - mp1->b_wptr >= len) {
18219 			ASSERT(len > 0);
18220 			ASSERT(!mp1->b_cont);
18221 			if (len == 1) {
18222 				*mp1->b_wptr++ = *mp->b_rptr;
18223 			} else {
18224 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18225 				mp1->b_wptr += len;
18226 			}
18227 			if (mp1 == tcp->tcp_xmit_tail)
18228 				tcp->tcp_xmit_tail_unsent += len;
18229 			mp1->b_cont = mp->b_cont;
18230 			if (tcp->tcp_snd_zcopy_aware &&
18231 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18232 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18233 			freeb(mp);
18234 			mp = mp1;
18235 		} else {
18236 			tcp->tcp_xmit_last->b_cont = mp;
18237 		}
18238 		len += tcp->tcp_unsent;
18239 	}
18240 
18241 	/* Tack on however many more positive length mblks we have */
18242 	if ((mp1 = mp->b_cont) != NULL) {
18243 		do {
18244 			int tlen;
18245 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18246 			    (uintptr_t)INT_MAX);
18247 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18248 			if (tlen <= 0) {
18249 				mp->b_cont = mp1->b_cont;
18250 				freeb(mp1);
18251 			} else {
18252 				len += tlen;
18253 				mp = mp1;
18254 			}
18255 		} while ((mp1 = mp->b_cont) != NULL);
18256 	}
18257 	tcp->tcp_xmit_last = mp;
18258 	tcp->tcp_unsent = len;
18259 
18260 	if (urgent)
18261 		usable = 1;
18262 
18263 data_null:
18264 	snxt = tcp->tcp_snxt;
18265 	xmit_tail = tcp->tcp_xmit_tail;
18266 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18267 
18268 	/*
18269 	 * Note that tcp_mss has been adjusted to take into account the
18270 	 * timestamp option if applicable.  Because SACK options do not
18271 	 * appear in every TCP segments and they are of variable lengths,
18272 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18273 	 * the actual segment length when we need to send a segment which
18274 	 * includes SACK options.
18275 	 */
18276 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18277 		int32_t	opt_len;
18278 
18279 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18280 		    tcp->tcp_num_sack_blk);
18281 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18282 		    2 + TCPOPT_HEADER_LEN;
18283 		mss = tcp->tcp_mss - opt_len;
18284 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18285 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18286 	} else {
18287 		mss = tcp->tcp_mss;
18288 		tcp_hdr_len = tcp->tcp_hdr_len;
18289 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18290 	}
18291 
18292 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18293 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18294 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18295 	}
18296 	if (tcpstate == TCPS_SYN_RCVD) {
18297 		/*
18298 		 * The three-way connection establishment handshake is not
18299 		 * complete yet. We want to queue the data for transmission
18300 		 * after entering ESTABLISHED state (RFC793). A jump to
18301 		 * "done" label effectively leaves data on the queue.
18302 		 */
18303 		goto done;
18304 	} else {
18305 		int usable_r = tcp->tcp_swnd;
18306 
18307 		/*
18308 		 * In the special case when cwnd is zero, which can only
18309 		 * happen if the connection is ECN capable, return now.
18310 		 * New segments is sent using tcp_timer().  The timer
18311 		 * is set in tcp_rput_data().
18312 		 */
18313 		if (tcp->tcp_cwnd == 0) {
18314 			/*
18315 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18316 			 * finished.
18317 			 */
18318 			ASSERT(tcp->tcp_ecn_ok ||
18319 			    tcp->tcp_state < TCPS_ESTABLISHED);
18320 			return;
18321 		}
18322 
18323 		/* NOTE: trouble if xmitting while SYN not acked? */
18324 		usable_r -= snxt;
18325 		usable_r += tcp->tcp_suna;
18326 
18327 		/*
18328 		 * Check if the receiver has shrunk the window.  If
18329 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18330 		 * cannot be set as there is unsent data, so FIN cannot
18331 		 * be sent out.  Otherwise, we need to take into account
18332 		 * of FIN as it consumes an "invisible" sequence number.
18333 		 */
18334 		ASSERT(tcp->tcp_fin_sent == 0);
18335 		if (usable_r < 0) {
18336 			/*
18337 			 * The receiver has shrunk the window and we have sent
18338 			 * -usable_r date beyond the window, re-adjust.
18339 			 *
18340 			 * If TCP window scaling is enabled, there can be
18341 			 * round down error as the advertised receive window
18342 			 * is actually right shifted n bits.  This means that
18343 			 * the lower n bits info is wiped out.  It will look
18344 			 * like the window is shrunk.  Do a check here to
18345 			 * see if the shrunk amount is actually within the
18346 			 * error in window calculation.  If it is, just
18347 			 * return.  Note that this check is inside the
18348 			 * shrunk window check.  This makes sure that even
18349 			 * though tcp_process_shrunk_swnd() is not called,
18350 			 * we will stop further processing.
18351 			 */
18352 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18353 				tcp_process_shrunk_swnd(tcp, -usable_r);
18354 			}
18355 			return;
18356 		}
18357 
18358 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18359 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18360 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18361 
18362 		/* usable = MIN(usable, unsent) */
18363 		if (usable_r > len)
18364 			usable_r = len;
18365 
18366 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18367 		if (usable_r > 0) {
18368 			usable = usable_r;
18369 		} else {
18370 			/* Bypass all other unnecessary processing. */
18371 			goto done;
18372 		}
18373 	}
18374 
18375 	local_time = (mblk_t *)lbolt;
18376 
18377 	/*
18378 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18379 	 * BSD.  This is more in line with the true intent of Nagle.
18380 	 *
18381 	 * The conditions are:
18382 	 * 1. The amount of unsent data (or amount of data which can be
18383 	 *    sent, whichever is smaller) is less than Nagle limit.
18384 	 * 2. The last sent size is also less than Nagle limit.
18385 	 * 3. There is unack'ed data.
18386 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18387 	 *    Nagle algorithm.  This reduces the probability that urgent
18388 	 *    bytes get "merged" together.
18389 	 * 5. The app has not closed the connection.  This eliminates the
18390 	 *    wait time of the receiving side waiting for the last piece of
18391 	 *    (small) data.
18392 	 *
18393 	 * If all are satisified, exit without sending anything.  Note
18394 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18395 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18396 	 * 4095).
18397 	 */
18398 	if (usable < (int)tcp->tcp_naglim &&
18399 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18400 	    snxt != tcp->tcp_suna &&
18401 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18402 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18403 		goto done;
18404 	}
18405 
18406 	if (tcp->tcp_cork) {
18407 		/*
18408 		 * if the tcp->tcp_cork option is set, then we have to force
18409 		 * TCP not to send partial segment (smaller than MSS bytes).
18410 		 * We are calculating the usable now based on full mss and
18411 		 * will save the rest of remaining data for later.
18412 		 */
18413 		if (usable < mss)
18414 			goto done;
18415 		usable = (usable / mss) * mss;
18416 	}
18417 
18418 	/* Update the latest receive window size in TCP header. */
18419 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18420 	    tcp->tcp_tcph->th_win);
18421 
18422 	/*
18423 	 * Determine if it's worthwhile to attempt MDT, based on:
18424 	 *
18425 	 * 1. Simple TCP/IP{v4,v6} (no options).
18426 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18427 	 * 3. If the TCP connection is in ESTABLISHED state.
18428 	 * 4. The TCP is not detached.
18429 	 *
18430 	 * If any of the above conditions have changed during the
18431 	 * connection, stop using MDT and restore the stream head
18432 	 * parameters accordingly.
18433 	 */
18434 	if (tcp->tcp_mdt &&
18435 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18436 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18437 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18438 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18439 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18440 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18441 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18442 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18443 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18444 		tcp->tcp_mdt = B_FALSE;
18445 
18446 		/* Anything other than detached is considered pathological */
18447 		if (!TCP_IS_DETACHED(tcp)) {
18448 			TCP_STAT(tcp_mdt_conn_halted1);
18449 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18450 		}
18451 	}
18452 
18453 	/* Use MDT if sendable amount is greater than the threshold */
18454 	if (tcp->tcp_mdt &&
18455 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18456 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18457 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18458 	    (tcp->tcp_valid_bits == 0 ||
18459 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18460 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18461 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18462 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18463 		    local_time, mdt_thres);
18464 	} else {
18465 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18466 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18467 		    local_time, INT_MAX);
18468 	}
18469 
18470 	/* Pretend that all we were trying to send really got sent */
18471 	if (rc < 0 && tail_unsent < 0) {
18472 		do {
18473 			xmit_tail = xmit_tail->b_cont;
18474 			xmit_tail->b_prev = local_time;
18475 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18476 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18477 			tail_unsent += (int)(xmit_tail->b_wptr -
18478 			    xmit_tail->b_rptr);
18479 		} while (tail_unsent < 0);
18480 	}
18481 done:;
18482 	tcp->tcp_xmit_tail = xmit_tail;
18483 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18484 	len = tcp->tcp_snxt - snxt;
18485 	if (len) {
18486 		/*
18487 		 * If new data was sent, need to update the notsack
18488 		 * list, which is, afterall, data blocks that have
18489 		 * not been sack'ed by the receiver.  New data is
18490 		 * not sack'ed.
18491 		 */
18492 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18493 			/* len is a negative value. */
18494 			tcp->tcp_pipe -= len;
18495 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18496 			    tcp->tcp_snxt, snxt,
18497 			    &(tcp->tcp_num_notsack_blk),
18498 			    &(tcp->tcp_cnt_notsack_list));
18499 		}
18500 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18501 		tcp->tcp_rack = tcp->tcp_rnxt;
18502 		tcp->tcp_rack_cnt = 0;
18503 		if ((snxt + len) == tcp->tcp_suna) {
18504 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18505 		}
18506 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18507 		/*
18508 		 * Didn't send anything. Make sure the timer is running
18509 		 * so that we will probe a zero window.
18510 		 */
18511 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18512 	}
18513 	/* Note that len is the amount we just sent but with a negative sign */
18514 	tcp->tcp_unsent += len;
18515 	if (tcp->tcp_flow_stopped) {
18516 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18517 			tcp_clrqfull(tcp);
18518 		}
18519 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18520 		tcp_setqfull(tcp);
18521 	}
18522 }
18523 
18524 /*
18525  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18526  * outgoing TCP header with the template header, as well as other
18527  * options such as time-stamp, ECN and/or SACK.
18528  */
18529 static void
18530 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18531 {
18532 	tcph_t *tcp_tmpl, *tcp_h;
18533 	uint32_t *dst, *src;
18534 	int hdrlen;
18535 
18536 	ASSERT(OK_32PTR(rptr));
18537 
18538 	/* Template header */
18539 	tcp_tmpl = tcp->tcp_tcph;
18540 
18541 	/* Header of outgoing packet */
18542 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18543 
18544 	/* dst and src are opaque 32-bit fields, used for copying */
18545 	dst = (uint32_t *)rptr;
18546 	src = (uint32_t *)tcp->tcp_iphc;
18547 	hdrlen = tcp->tcp_hdr_len;
18548 
18549 	/* Fill time-stamp option if needed */
18550 	if (tcp->tcp_snd_ts_ok) {
18551 		U32_TO_BE32((uint32_t)now,
18552 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18553 		U32_TO_BE32(tcp->tcp_ts_recent,
18554 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18555 	} else {
18556 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18557 	}
18558 
18559 	/*
18560 	 * Copy the template header; is this really more efficient than
18561 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18562 	 * but perhaps not for other scenarios.
18563 	 */
18564 	dst[0] = src[0];
18565 	dst[1] = src[1];
18566 	dst[2] = src[2];
18567 	dst[3] = src[3];
18568 	dst[4] = src[4];
18569 	dst[5] = src[5];
18570 	dst[6] = src[6];
18571 	dst[7] = src[7];
18572 	dst[8] = src[8];
18573 	dst[9] = src[9];
18574 	if (hdrlen -= 40) {
18575 		hdrlen >>= 2;
18576 		dst += 10;
18577 		src += 10;
18578 		do {
18579 			*dst++ = *src++;
18580 		} while (--hdrlen);
18581 	}
18582 
18583 	/*
18584 	 * Set the ECN info in the TCP header if it is not a zero
18585 	 * window probe.  Zero window probe is only sent in
18586 	 * tcp_wput_data() and tcp_timer().
18587 	 */
18588 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18589 		SET_ECT(tcp, rptr);
18590 
18591 		if (tcp->tcp_ecn_echo_on)
18592 			tcp_h->th_flags[0] |= TH_ECE;
18593 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18594 			tcp_h->th_flags[0] |= TH_CWR;
18595 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18596 		}
18597 	}
18598 
18599 	/* Fill in SACK options */
18600 	if (num_sack_blk > 0) {
18601 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18602 		sack_blk_t *tmp;
18603 		int32_t	i;
18604 
18605 		wptr[0] = TCPOPT_NOP;
18606 		wptr[1] = TCPOPT_NOP;
18607 		wptr[2] = TCPOPT_SACK;
18608 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18609 		    sizeof (sack_blk_t);
18610 		wptr += TCPOPT_REAL_SACK_LEN;
18611 
18612 		tmp = tcp->tcp_sack_list;
18613 		for (i = 0; i < num_sack_blk; i++) {
18614 			U32_TO_BE32(tmp[i].begin, wptr);
18615 			wptr += sizeof (tcp_seq);
18616 			U32_TO_BE32(tmp[i].end, wptr);
18617 			wptr += sizeof (tcp_seq);
18618 		}
18619 		tcp_h->th_offset_and_rsrvd[0] +=
18620 		    ((num_sack_blk * 2 + 1) << 4);
18621 	}
18622 }
18623 
18624 /*
18625  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18626  * the destination address and SAP attribute, and if necessary, the
18627  * hardware checksum offload attribute to a Multidata message.
18628  */
18629 static int
18630 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18631     const uint32_t start, const uint32_t stuff, const uint32_t end,
18632     const uint32_t flags)
18633 {
18634 	/* Add global destination address & SAP attribute */
18635 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18636 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18637 		    "destination address+SAP\n"));
18638 
18639 		if (dlmp != NULL)
18640 			TCP_STAT(tcp_mdt_allocfail);
18641 		return (-1);
18642 	}
18643 
18644 	/* Add global hwcksum attribute */
18645 	if (hwcksum &&
18646 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18647 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18648 		    "checksum attribute\n"));
18649 
18650 		TCP_STAT(tcp_mdt_allocfail);
18651 		return (-1);
18652 	}
18653 
18654 	return (0);
18655 }
18656 
18657 /*
18658  * Smaller and private version of pdescinfo_t used specifically for TCP,
18659  * which allows for only two payload spans per packet.
18660  */
18661 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18662 
18663 /*
18664  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18665  * scheme, and returns one the following:
18666  *
18667  * -1 = failed allocation.
18668  *  0 = success; burst count reached, or usable send window is too small,
18669  *      and that we'd rather wait until later before sending again.
18670  */
18671 static int
18672 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18673     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18674     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18675     const int mdt_thres)
18676 {
18677 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18678 	multidata_t	*mmd;
18679 	uint_t		obsegs, obbytes, hdr_frag_sz;
18680 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18681 	int		num_burst_seg, max_pld;
18682 	pdesc_t		*pkt;
18683 	tcp_pdescinfo_t	tcp_pkt_info;
18684 	pdescinfo_t	*pkt_info;
18685 	int		pbuf_idx, pbuf_idx_nxt;
18686 	int		seg_len, len, spill, af;
18687 	boolean_t	add_buffer, zcopy, clusterwide;
18688 	boolean_t	rconfirm = B_FALSE;
18689 	boolean_t	done = B_FALSE;
18690 	uint32_t	cksum;
18691 	uint32_t	hwcksum_flags;
18692 	ire_t		*ire;
18693 	ill_t		*ill;
18694 	ipha_t		*ipha;
18695 	ip6_t		*ip6h;
18696 	ipaddr_t	src, dst;
18697 	ill_zerocopy_capab_t *zc_cap = NULL;
18698 	uint16_t	*up;
18699 	int		err;
18700 
18701 #ifdef	_BIG_ENDIAN
18702 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
18703 #else
18704 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
18705 #endif
18706 
18707 #define	PREP_NEW_MULTIDATA() {			\
18708 	mmd = NULL;				\
18709 	md_mp = md_hbuf = NULL;			\
18710 	cur_hdr_off = 0;			\
18711 	max_pld = tcp->tcp_mdt_max_pld;		\
18712 	pbuf_idx = pbuf_idx_nxt = -1;		\
18713 	add_buffer = B_TRUE;			\
18714 	zcopy = B_FALSE;			\
18715 }
18716 
18717 #define	PREP_NEW_PBUF() {			\
18718 	md_pbuf = md_pbuf_nxt = NULL;		\
18719 	pbuf_idx = pbuf_idx_nxt = -1;		\
18720 	cur_pld_off = 0;			\
18721 	first_snxt = *snxt;			\
18722 	ASSERT(*tail_unsent > 0);		\
18723 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
18724 }
18725 
18726 	ASSERT(mdt_thres >= mss);
18727 	ASSERT(*usable > 0 && *usable > mdt_thres);
18728 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
18729 	ASSERT(!TCP_IS_DETACHED(tcp));
18730 	ASSERT(tcp->tcp_valid_bits == 0 ||
18731 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
18732 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
18733 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
18734 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18735 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
18736 	ASSERT(tcp->tcp_connp != NULL);
18737 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
18738 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
18739 
18740 	/*
18741 	 * Note that tcp will only declare at most 2 payload spans per
18742 	 * packet, which is much lower than the maximum allowable number
18743 	 * of packet spans per Multidata.  For this reason, we use the
18744 	 * privately declared and smaller descriptor info structure, in
18745 	 * order to save some stack space.
18746 	 */
18747 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
18748 
18749 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
18750 	if (af == AF_INET) {
18751 		dst = tcp->tcp_ipha->ipha_dst;
18752 		src = tcp->tcp_ipha->ipha_src;
18753 		ASSERT(!CLASSD(dst));
18754 	}
18755 	ASSERT(af == AF_INET ||
18756 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
18757 
18758 	obsegs = obbytes = 0;
18759 	num_burst_seg = tcp->tcp_snd_burst;
18760 	md_mp_head = NULL;
18761 	PREP_NEW_MULTIDATA();
18762 
18763 	/*
18764 	 * Before we go on further, make sure there is an IRE that we can
18765 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
18766 	 * in proceeding any further, and we should just hand everything
18767 	 * off to the legacy path.
18768 	 */
18769 	mutex_enter(&tcp->tcp_connp->conn_lock);
18770 	ire = tcp->tcp_connp->conn_ire_cache;
18771 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
18772 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
18773 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
18774 	    &tcp->tcp_ip6h->ip6_dst))) &&
18775 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18776 		IRE_REFHOLD(ire);
18777 		mutex_exit(&tcp->tcp_connp->conn_lock);
18778 	} else {
18779 		boolean_t cached = B_FALSE;
18780 
18781 		/* force a recheck later on */
18782 		tcp->tcp_ire_ill_check_done = B_FALSE;
18783 
18784 		TCP_DBGSTAT(tcp_ire_null1);
18785 		tcp->tcp_connp->conn_ire_cache = NULL;
18786 		mutex_exit(&tcp->tcp_connp->conn_lock);
18787 
18788 		/* Release the old ire */
18789 		if (ire != NULL)
18790 			IRE_REFRELE_NOTR(ire);
18791 
18792 		ire = (af == AF_INET) ?
18793 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
18794 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18795 		    tcp->tcp_connp->conn_zoneid);
18796 
18797 		if (ire == NULL) {
18798 			TCP_STAT(tcp_ire_null);
18799 			goto legacy_send_no_md;
18800 		}
18801 
18802 		IRE_REFHOLD_NOTR(ire);
18803 		/*
18804 		 * Since we are inside the squeue, there cannot be another
18805 		 * thread in TCP trying to set the conn_ire_cache now. The
18806 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18807 		 * unplumb thread has not yet started cleaning up the conns.
18808 		 * Hence we don't need to grab the conn lock.
18809 		 */
18810 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
18811 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18812 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18813 				tcp->tcp_connp->conn_ire_cache = ire;
18814 				cached = B_TRUE;
18815 			}
18816 			rw_exit(&ire->ire_bucket->irb_lock);
18817 		}
18818 
18819 		/*
18820 		 * We can continue to use the ire but since it was not
18821 		 * cached, we should drop the extra reference.
18822 		 */
18823 		if (!cached)
18824 			IRE_REFRELE_NOTR(ire);
18825 	}
18826 
18827 	ASSERT(ire != NULL);
18828 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
18829 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
18830 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
18831 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18832 	/*
18833 	 * If we do support loopback for MDT (which requires modifications
18834 	 * to the receiving paths), the following assertions should go away,
18835 	 * and we would be sending the Multidata to loopback conn later on.
18836 	 */
18837 	ASSERT(!IRE_IS_LOCAL(ire));
18838 	ASSERT(ire->ire_stq != NULL);
18839 
18840 	ill = ire_to_ill(ire);
18841 	ASSERT(ill != NULL);
18842 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
18843 
18844 	if (!tcp->tcp_ire_ill_check_done) {
18845 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18846 		tcp->tcp_ire_ill_check_done = B_TRUE;
18847 	}
18848 
18849 	/*
18850 	 * If the underlying interface conditions have changed, or if the
18851 	 * new interface does not support MDT, go back to legacy path.
18852 	 */
18853 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
18854 		/* don't go through this path anymore for this connection */
18855 		TCP_STAT(tcp_mdt_conn_halted2);
18856 		tcp->tcp_mdt = B_FALSE;
18857 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
18858 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
18859 		/* IRE will be released prior to returning */
18860 		goto legacy_send_no_md;
18861 	}
18862 
18863 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
18864 		zc_cap = ill->ill_zerocopy_capab;
18865 
18866 	/* go to legacy path if interface doesn't support zerocopy */
18867 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
18868 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
18869 		/* IRE will be released prior to returning */
18870 		goto legacy_send_no_md;
18871 	}
18872 
18873 	/* does the interface support hardware checksum offload? */
18874 	hwcksum_flags = 0;
18875 	if (ILL_HCKSUM_CAPABLE(ill) &&
18876 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
18877 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
18878 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
18879 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18880 		    HCKSUM_IPHDRCKSUM)
18881 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
18882 
18883 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18884 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
18885 			hwcksum_flags |= HCK_FULLCKSUM;
18886 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18887 		    HCKSUM_INET_PARTIAL)
18888 			hwcksum_flags |= HCK_PARTIALCKSUM;
18889 	}
18890 
18891 	/*
18892 	 * Each header fragment consists of the leading extra space,
18893 	 * followed by the TCP/IP header, and the trailing extra space.
18894 	 * We make sure that each header fragment begins on a 32-bit
18895 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
18896 	 * aligned in tcp_mdt_update).
18897 	 */
18898 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
18899 	    tcp->tcp_mdt_hdr_tail), 4);
18900 
18901 	/* are we starting from the beginning of data block? */
18902 	if (*tail_unsent == 0) {
18903 		*xmit_tail = (*xmit_tail)->b_cont;
18904 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
18905 		*tail_unsent = (int)MBLKL(*xmit_tail);
18906 	}
18907 
18908 	/*
18909 	 * Here we create one or more Multidata messages, each made up of
18910 	 * one header buffer and up to N payload buffers.  This entire
18911 	 * operation is done within two loops:
18912 	 *
18913 	 * The outer loop mostly deals with creating the Multidata message,
18914 	 * as well as the header buffer that gets added to it.  It also
18915 	 * links the Multidata messages together such that all of them can
18916 	 * be sent down to the lower layer in a single putnext call; this
18917 	 * linking behavior depends on the tcp_mdt_chain tunable.
18918 	 *
18919 	 * The inner loop takes an existing Multidata message, and adds
18920 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
18921 	 * packetizes those buffers by filling up the corresponding header
18922 	 * buffer fragments with the proper IP and TCP headers, and by
18923 	 * describing the layout of each packet in the packet descriptors
18924 	 * that get added to the Multidata.
18925 	 */
18926 	do {
18927 		/*
18928 		 * If usable send window is too small, or data blocks in
18929 		 * transmit list are smaller than our threshold (i.e. app
18930 		 * performs large writes followed by small ones), we hand
18931 		 * off the control over to the legacy path.  Note that we'll
18932 		 * get back the control once it encounters a large block.
18933 		 */
18934 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
18935 		    (*xmit_tail)->b_cont != NULL &&
18936 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
18937 			/* send down what we've got so far */
18938 			if (md_mp_head != NULL) {
18939 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
18940 				    obsegs, obbytes, &rconfirm);
18941 			}
18942 			/*
18943 			 * Pass control over to tcp_send(), but tell it to
18944 			 * return to us once a large-size transmission is
18945 			 * possible.
18946 			 */
18947 			TCP_STAT(tcp_mdt_legacy_small);
18948 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
18949 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
18950 			    tail_unsent, xmit_tail, local_time,
18951 			    mdt_thres)) <= 0) {
18952 				/* burst count reached, or alloc failed */
18953 				IRE_REFRELE(ire);
18954 				return (err);
18955 			}
18956 
18957 			/* tcp_send() may have sent everything, so check */
18958 			if (*usable <= 0) {
18959 				IRE_REFRELE(ire);
18960 				return (0);
18961 			}
18962 
18963 			TCP_STAT(tcp_mdt_legacy_ret);
18964 			/*
18965 			 * We may have delivered the Multidata, so make sure
18966 			 * to re-initialize before the next round.
18967 			 */
18968 			md_mp_head = NULL;
18969 			obsegs = obbytes = 0;
18970 			num_burst_seg = tcp->tcp_snd_burst;
18971 			PREP_NEW_MULTIDATA();
18972 
18973 			/* are we starting from the beginning of data block? */
18974 			if (*tail_unsent == 0) {
18975 				*xmit_tail = (*xmit_tail)->b_cont;
18976 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
18977 				    (uintptr_t)INT_MAX);
18978 				*tail_unsent = (int)MBLKL(*xmit_tail);
18979 			}
18980 		}
18981 
18982 		/*
18983 		 * max_pld limits the number of mblks in tcp's transmit
18984 		 * queue that can be added to a Multidata message.  Once
18985 		 * this counter reaches zero, no more additional mblks
18986 		 * can be added to it.  What happens afterwards depends
18987 		 * on whether or not we are set to chain the Multidata
18988 		 * messages.  If we are to link them together, reset
18989 		 * max_pld to its original value (tcp_mdt_max_pld) and
18990 		 * prepare to create a new Multidata message which will
18991 		 * get linked to md_mp_head.  Else, leave it alone and
18992 		 * let the inner loop break on its own.
18993 		 */
18994 		if (tcp_mdt_chain && max_pld == 0)
18995 			PREP_NEW_MULTIDATA();
18996 
18997 		/* adding a payload buffer; re-initialize values */
18998 		if (add_buffer)
18999 			PREP_NEW_PBUF();
19000 
19001 		/*
19002 		 * If we don't have a Multidata, either because we just
19003 		 * (re)entered this outer loop, or after we branched off
19004 		 * to tcp_send above, setup the Multidata and header
19005 		 * buffer to be used.
19006 		 */
19007 		if (md_mp == NULL) {
19008 			int md_hbuflen;
19009 			uint32_t start, stuff;
19010 
19011 			/*
19012 			 * Calculate Multidata header buffer size large enough
19013 			 * to hold all of the headers that can possibly be
19014 			 * sent at this moment.  We'd rather over-estimate
19015 			 * the size than running out of space; this is okay
19016 			 * since this buffer is small anyway.
19017 			 */
19018 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19019 
19020 			/*
19021 			 * Start and stuff offset for partial hardware
19022 			 * checksum offload; these are currently for IPv4.
19023 			 * For full checksum offload, they are set to zero.
19024 			 */
19025 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19026 				if (af == AF_INET) {
19027 					start = IP_SIMPLE_HDR_LENGTH;
19028 					stuff = IP_SIMPLE_HDR_LENGTH +
19029 					    TCP_CHECKSUM_OFFSET;
19030 				} else {
19031 					start = IPV6_HDR_LEN;
19032 					stuff = IPV6_HDR_LEN +
19033 					    TCP_CHECKSUM_OFFSET;
19034 				}
19035 			} else {
19036 				start = stuff = 0;
19037 			}
19038 
19039 			/*
19040 			 * Create the header buffer, Multidata, as well as
19041 			 * any necessary attributes (destination address,
19042 			 * SAP and hardware checksum offload) that should
19043 			 * be associated with the Multidata message.
19044 			 */
19045 			ASSERT(cur_hdr_off == 0);
19046 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19047 			    ((md_hbuf->b_wptr += md_hbuflen),
19048 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19049 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19050 			    /* fastpath mblk */
19051 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19052 			    ire->ire_nce->nce_res_mp,
19053 			    /* hardware checksum enabled */
19054 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19055 			    /* hardware checksum offsets */
19056 			    start, stuff, 0,
19057 			    /* hardware checksum flag */
19058 			    hwcksum_flags) != 0)) {
19059 legacy_send:
19060 				if (md_mp != NULL) {
19061 					/* Unlink message from the chain */
19062 					if (md_mp_head != NULL) {
19063 						err = (intptr_t)rmvb(md_mp_head,
19064 						    md_mp);
19065 						/*
19066 						 * We can't assert that rmvb
19067 						 * did not return -1, since we
19068 						 * may get here before linkb
19069 						 * happens.  We do, however,
19070 						 * check if we just removed the
19071 						 * only element in the list.
19072 						 */
19073 						if (err == 0)
19074 							md_mp_head = NULL;
19075 					}
19076 					/* md_hbuf gets freed automatically */
19077 					TCP_STAT(tcp_mdt_discarded);
19078 					freeb(md_mp);
19079 				} else {
19080 					/* Either allocb or mmd_alloc failed */
19081 					TCP_STAT(tcp_mdt_allocfail);
19082 					if (md_hbuf != NULL)
19083 						freeb(md_hbuf);
19084 				}
19085 
19086 				/* send down what we've got so far */
19087 				if (md_mp_head != NULL) {
19088 					tcp_multisend_data(tcp, ire, ill,
19089 					    md_mp_head, obsegs, obbytes,
19090 					    &rconfirm);
19091 				}
19092 legacy_send_no_md:
19093 				if (ire != NULL)
19094 					IRE_REFRELE(ire);
19095 				/*
19096 				 * Too bad; let the legacy path handle this.
19097 				 * We specify INT_MAX for the threshold, since
19098 				 * we gave up with the Multidata processings
19099 				 * and let the old path have it all.
19100 				 */
19101 				TCP_STAT(tcp_mdt_legacy_all);
19102 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19103 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19104 				    snxt, tail_unsent, xmit_tail, local_time,
19105 				    INT_MAX));
19106 			}
19107 
19108 			/* link to any existing ones, if applicable */
19109 			TCP_STAT(tcp_mdt_allocd);
19110 			if (md_mp_head == NULL) {
19111 				md_mp_head = md_mp;
19112 			} else if (tcp_mdt_chain) {
19113 				TCP_STAT(tcp_mdt_linked);
19114 				linkb(md_mp_head, md_mp);
19115 			}
19116 		}
19117 
19118 		ASSERT(md_mp_head != NULL);
19119 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19120 		ASSERT(md_mp != NULL && mmd != NULL);
19121 		ASSERT(md_hbuf != NULL);
19122 
19123 		/*
19124 		 * Packetize the transmittable portion of the data block;
19125 		 * each data block is essentially added to the Multidata
19126 		 * as a payload buffer.  We also deal with adding more
19127 		 * than one payload buffers, which happens when the remaining
19128 		 * packetized portion of the current payload buffer is less
19129 		 * than MSS, while the next data block in transmit queue
19130 		 * has enough data to make up for one.  This "spillover"
19131 		 * case essentially creates a split-packet, where portions
19132 		 * of the packet's payload fragments may span across two
19133 		 * virtually discontiguous address blocks.
19134 		 */
19135 		seg_len = mss;
19136 		do {
19137 			len = seg_len;
19138 
19139 			ASSERT(len > 0);
19140 			ASSERT(max_pld >= 0);
19141 			ASSERT(!add_buffer || cur_pld_off == 0);
19142 
19143 			/*
19144 			 * First time around for this payload buffer; note
19145 			 * in the case of a spillover, the following has
19146 			 * been done prior to adding the split-packet
19147 			 * descriptor to Multidata, and we don't want to
19148 			 * repeat the process.
19149 			 */
19150 			if (add_buffer) {
19151 				ASSERT(mmd != NULL);
19152 				ASSERT(md_pbuf == NULL);
19153 				ASSERT(md_pbuf_nxt == NULL);
19154 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19155 
19156 				/*
19157 				 * Have we reached the limit?  We'd get to
19158 				 * this case when we're not chaining the
19159 				 * Multidata messages together, and since
19160 				 * we're done, terminate this loop.
19161 				 */
19162 				if (max_pld == 0)
19163 					break; /* done */
19164 
19165 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19166 					TCP_STAT(tcp_mdt_allocfail);
19167 					goto legacy_send; /* out_of_mem */
19168 				}
19169 
19170 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19171 				    zc_cap != NULL) {
19172 					if (!ip_md_zcopy_attr(mmd, NULL,
19173 					    zc_cap->ill_zerocopy_flags)) {
19174 						freeb(md_pbuf);
19175 						TCP_STAT(tcp_mdt_allocfail);
19176 						/* out_of_mem */
19177 						goto legacy_send;
19178 					}
19179 					zcopy = B_TRUE;
19180 				}
19181 
19182 				md_pbuf->b_rptr += base_pld_off;
19183 
19184 				/*
19185 				 * Add a payload buffer to the Multidata; this
19186 				 * operation must not fail, or otherwise our
19187 				 * logic in this routine is broken.  There
19188 				 * is no memory allocation done by the
19189 				 * routine, so any returned failure simply
19190 				 * tells us that we've done something wrong.
19191 				 *
19192 				 * A failure tells us that either we're adding
19193 				 * the same payload buffer more than once, or
19194 				 * we're trying to add more buffers than
19195 				 * allowed (max_pld calculation is wrong).
19196 				 * None of the above cases should happen, and
19197 				 * we panic because either there's horrible
19198 				 * heap corruption, and/or programming mistake.
19199 				 */
19200 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19201 				if (pbuf_idx < 0) {
19202 					cmn_err(CE_PANIC, "tcp_multisend: "
19203 					    "payload buffer logic error "
19204 					    "detected for tcp %p mmd %p "
19205 					    "pbuf %p (%d)\n",
19206 					    (void *)tcp, (void *)mmd,
19207 					    (void *)md_pbuf, pbuf_idx);
19208 				}
19209 
19210 				ASSERT(max_pld > 0);
19211 				--max_pld;
19212 				add_buffer = B_FALSE;
19213 			}
19214 
19215 			ASSERT(md_mp_head != NULL);
19216 			ASSERT(md_pbuf != NULL);
19217 			ASSERT(md_pbuf_nxt == NULL);
19218 			ASSERT(pbuf_idx != -1);
19219 			ASSERT(pbuf_idx_nxt == -1);
19220 			ASSERT(*usable > 0);
19221 
19222 			/*
19223 			 * We spillover to the next payload buffer only
19224 			 * if all of the following is true:
19225 			 *
19226 			 *   1. There is not enough data on the current
19227 			 *	payload buffer to make up `len',
19228 			 *   2. We are allowed to send `len',
19229 			 *   3. The next payload buffer length is large
19230 			 *	enough to accomodate `spill'.
19231 			 */
19232 			if ((spill = len - *tail_unsent) > 0 &&
19233 			    *usable >= len &&
19234 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19235 			    max_pld > 0) {
19236 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19237 				if (md_pbuf_nxt == NULL) {
19238 					TCP_STAT(tcp_mdt_allocfail);
19239 					goto legacy_send; /* out_of_mem */
19240 				}
19241 
19242 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19243 				    zc_cap != NULL) {
19244 					if (!ip_md_zcopy_attr(mmd, NULL,
19245 					    zc_cap->ill_zerocopy_flags)) {
19246 						freeb(md_pbuf_nxt);
19247 						TCP_STAT(tcp_mdt_allocfail);
19248 						/* out_of_mem */
19249 						goto legacy_send;
19250 					}
19251 					zcopy = B_TRUE;
19252 				}
19253 
19254 				/*
19255 				 * See comments above on the first call to
19256 				 * mmd_addpldbuf for explanation on the panic.
19257 				 */
19258 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19259 				if (pbuf_idx_nxt < 0) {
19260 					panic("tcp_multisend: "
19261 					    "next payload buffer logic error "
19262 					    "detected for tcp %p mmd %p "
19263 					    "pbuf %p (%d)\n",
19264 					    (void *)tcp, (void *)mmd,
19265 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19266 				}
19267 
19268 				ASSERT(max_pld > 0);
19269 				--max_pld;
19270 			} else if (spill > 0) {
19271 				/*
19272 				 * If there's a spillover, but the following
19273 				 * xmit_tail couldn't give us enough octets
19274 				 * to reach "len", then stop the current
19275 				 * Multidata creation and let the legacy
19276 				 * tcp_send() path take over.  We don't want
19277 				 * to send the tiny segment as part of this
19278 				 * Multidata for performance reasons; instead,
19279 				 * we let the legacy path deal with grouping
19280 				 * it with the subsequent small mblks.
19281 				 */
19282 				if (*usable >= len &&
19283 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19284 					max_pld = 0;
19285 					break;	/* done */
19286 				}
19287 
19288 				/*
19289 				 * We can't spillover, and we are near
19290 				 * the end of the current payload buffer,
19291 				 * so send what's left.
19292 				 */
19293 				ASSERT(*tail_unsent > 0);
19294 				len = *tail_unsent;
19295 			}
19296 
19297 			/* tail_unsent is negated if there is a spillover */
19298 			*tail_unsent -= len;
19299 			*usable -= len;
19300 			ASSERT(*usable >= 0);
19301 
19302 			if (*usable < mss)
19303 				seg_len = *usable;
19304 			/*
19305 			 * Sender SWS avoidance; see comments in tcp_send();
19306 			 * everything else is the same, except that we only
19307 			 * do this here if there is no more data to be sent
19308 			 * following the current xmit_tail.  We don't check
19309 			 * for 1-byte urgent data because we shouldn't get
19310 			 * here if TCP_URG_VALID is set.
19311 			 */
19312 			if (*usable > 0 && *usable < mss &&
19313 			    ((md_pbuf_nxt == NULL &&
19314 			    (*xmit_tail)->b_cont == NULL) ||
19315 			    (md_pbuf_nxt != NULL &&
19316 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19317 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19318 			    (tcp->tcp_unsent -
19319 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19320 			    !tcp->tcp_zero_win_probe) {
19321 				if ((*snxt + len) == tcp->tcp_snxt &&
19322 				    (*snxt + len) == tcp->tcp_suna) {
19323 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19324 				}
19325 				done = B_TRUE;
19326 			}
19327 
19328 			/*
19329 			 * Prime pump for IP's checksumming on our behalf;
19330 			 * include the adjustment for a source route if any.
19331 			 * Do this only for software/partial hardware checksum
19332 			 * offload, as this field gets zeroed out later for
19333 			 * the full hardware checksum offload case.
19334 			 */
19335 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19336 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19337 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19338 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19339 			}
19340 
19341 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19342 			*snxt += len;
19343 
19344 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19345 			/*
19346 			 * We set the PUSH bit only if TCP has no more buffered
19347 			 * data to be transmitted (or if sender SWS avoidance
19348 			 * takes place), as opposed to setting it for every
19349 			 * last packet in the burst.
19350 			 */
19351 			if (done ||
19352 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19353 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19354 
19355 			/*
19356 			 * Set FIN bit if this is our last segment; snxt
19357 			 * already includes its length, and it will not
19358 			 * be adjusted after this point.
19359 			 */
19360 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19361 			    *snxt == tcp->tcp_fss) {
19362 				if (!tcp->tcp_fin_acked) {
19363 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19364 					BUMP_MIB(&tcp_mib, tcpOutControl);
19365 				}
19366 				if (!tcp->tcp_fin_sent) {
19367 					tcp->tcp_fin_sent = B_TRUE;
19368 					/*
19369 					 * tcp state must be ESTABLISHED
19370 					 * in order for us to get here in
19371 					 * the first place.
19372 					 */
19373 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19374 
19375 					/*
19376 					 * Upon returning from this routine,
19377 					 * tcp_wput_data() will set tcp_snxt
19378 					 * to be equal to snxt + tcp_fin_sent.
19379 					 * This is essentially the same as
19380 					 * setting it to tcp_fss + 1.
19381 					 */
19382 				}
19383 			}
19384 
19385 			tcp->tcp_last_sent_len = (ushort_t)len;
19386 
19387 			len += tcp_hdr_len;
19388 			if (tcp->tcp_ipversion == IPV4_VERSION)
19389 				tcp->tcp_ipha->ipha_length = htons(len);
19390 			else
19391 				tcp->tcp_ip6h->ip6_plen = htons(len -
19392 				    ((char *)&tcp->tcp_ip6h[1] -
19393 				    tcp->tcp_iphc));
19394 
19395 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19396 
19397 			/* setup header fragment */
19398 			PDESC_HDR_ADD(pkt_info,
19399 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19400 			    tcp->tcp_mdt_hdr_head,		/* head room */
19401 			    tcp_hdr_len,			/* len */
19402 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19403 
19404 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19405 			    hdr_frag_sz);
19406 			ASSERT(MBLKIN(md_hbuf,
19407 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19408 			    PDESC_HDRSIZE(pkt_info)));
19409 
19410 			/* setup first payload fragment */
19411 			PDESC_PLD_INIT(pkt_info);
19412 			PDESC_PLD_SPAN_ADD(pkt_info,
19413 			    pbuf_idx,				/* index */
19414 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19415 			    tcp->tcp_last_sent_len);		/* len */
19416 
19417 			/* create a split-packet in case of a spillover */
19418 			if (md_pbuf_nxt != NULL) {
19419 				ASSERT(spill > 0);
19420 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19421 				ASSERT(!add_buffer);
19422 
19423 				md_pbuf = md_pbuf_nxt;
19424 				md_pbuf_nxt = NULL;
19425 				pbuf_idx = pbuf_idx_nxt;
19426 				pbuf_idx_nxt = -1;
19427 				cur_pld_off = spill;
19428 
19429 				/* trim out first payload fragment */
19430 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19431 
19432 				/* setup second payload fragment */
19433 				PDESC_PLD_SPAN_ADD(pkt_info,
19434 				    pbuf_idx,			/* index */
19435 				    md_pbuf->b_rptr,		/* start */
19436 				    spill);			/* len */
19437 
19438 				if ((*xmit_tail)->b_next == NULL) {
19439 					/*
19440 					 * Store the lbolt used for RTT
19441 					 * estimation. We can only record one
19442 					 * timestamp per mblk so we do it when
19443 					 * we reach the end of the payload
19444 					 * buffer.  Also we only take a new
19445 					 * timestamp sample when the previous
19446 					 * timed data from the same mblk has
19447 					 * been ack'ed.
19448 					 */
19449 					(*xmit_tail)->b_prev = local_time;
19450 					(*xmit_tail)->b_next =
19451 					    (mblk_t *)(uintptr_t)first_snxt;
19452 				}
19453 
19454 				first_snxt = *snxt - spill;
19455 
19456 				/*
19457 				 * Advance xmit_tail; usable could be 0 by
19458 				 * the time we got here, but we made sure
19459 				 * above that we would only spillover to
19460 				 * the next data block if usable includes
19461 				 * the spilled-over amount prior to the
19462 				 * subtraction.  Therefore, we are sure
19463 				 * that xmit_tail->b_cont can't be NULL.
19464 				 */
19465 				ASSERT((*xmit_tail)->b_cont != NULL);
19466 				*xmit_tail = (*xmit_tail)->b_cont;
19467 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19468 				    (uintptr_t)INT_MAX);
19469 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19470 			} else {
19471 				cur_pld_off += tcp->tcp_last_sent_len;
19472 			}
19473 
19474 			/*
19475 			 * Fill in the header using the template header, and
19476 			 * add options such as time-stamp, ECN and/or SACK,
19477 			 * as needed.
19478 			 */
19479 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19480 			    (clock_t)local_time, num_sack_blk);
19481 
19482 			/* take care of some IP header businesses */
19483 			if (af == AF_INET) {
19484 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19485 
19486 				ASSERT(OK_32PTR((uchar_t *)ipha));
19487 				ASSERT(PDESC_HDRL(pkt_info) >=
19488 				    IP_SIMPLE_HDR_LENGTH);
19489 				ASSERT(ipha->ipha_version_and_hdr_length ==
19490 				    IP_SIMPLE_HDR_VERSION);
19491 
19492 				/*
19493 				 * Assign ident value for current packet; see
19494 				 * related comments in ip_wput_ire() about the
19495 				 * contract private interface with clustering
19496 				 * group.
19497 				 */
19498 				clusterwide = B_FALSE;
19499 				if (cl_inet_ipident != NULL) {
19500 					ASSERT(cl_inet_isclusterwide != NULL);
19501 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19502 					    AF_INET,
19503 					    (uint8_t *)(uintptr_t)src)) {
19504 						ipha->ipha_ident =
19505 						    (*cl_inet_ipident)
19506 						    (IPPROTO_IP, AF_INET,
19507 						    (uint8_t *)(uintptr_t)src,
19508 						    (uint8_t *)(uintptr_t)dst);
19509 						clusterwide = B_TRUE;
19510 					}
19511 				}
19512 
19513 				if (!clusterwide) {
19514 					ipha->ipha_ident = (uint16_t)
19515 					    atomic_add_32_nv(
19516 						&ire->ire_ident, 1);
19517 				}
19518 #ifndef _BIG_ENDIAN
19519 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19520 				    (ipha->ipha_ident >> 8);
19521 #endif
19522 			} else {
19523 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19524 
19525 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19526 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19527 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19528 				ASSERT(PDESC_HDRL(pkt_info) >=
19529 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19530 				    TCP_CHECKSUM_SIZE));
19531 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19532 
19533 				if (tcp->tcp_ip_forward_progress) {
19534 					rconfirm = B_TRUE;
19535 					tcp->tcp_ip_forward_progress = B_FALSE;
19536 				}
19537 			}
19538 
19539 			/* at least one payload span, and at most two */
19540 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19541 
19542 			/* add the packet descriptor to Multidata */
19543 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19544 			    KM_NOSLEEP)) == NULL) {
19545 				/*
19546 				 * Any failure other than ENOMEM indicates
19547 				 * that we have passed in invalid pkt_info
19548 				 * or parameters to mmd_addpdesc, which must
19549 				 * not happen.
19550 				 *
19551 				 * EINVAL is a result of failure on boundary
19552 				 * checks against the pkt_info contents.  It
19553 				 * should not happen, and we panic because
19554 				 * either there's horrible heap corruption,
19555 				 * and/or programming mistake.
19556 				 */
19557 				if (err != ENOMEM) {
19558 					cmn_err(CE_PANIC, "tcp_multisend: "
19559 					    "pdesc logic error detected for "
19560 					    "tcp %p mmd %p pinfo %p (%d)\n",
19561 					    (void *)tcp, (void *)mmd,
19562 					    (void *)pkt_info, err);
19563 				}
19564 				TCP_STAT(tcp_mdt_addpdescfail);
19565 				goto legacy_send; /* out_of_mem */
19566 			}
19567 			ASSERT(pkt != NULL);
19568 
19569 			/* calculate IP header and TCP checksums */
19570 			if (af == AF_INET) {
19571 				/* calculate pseudo-header checksum */
19572 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19573 				    (src >> 16) + (src & 0xFFFF);
19574 
19575 				/* offset for TCP header checksum */
19576 				up = IPH_TCPH_CHECKSUMP(ipha,
19577 				    IP_SIMPLE_HDR_LENGTH);
19578 			} else {
19579 				up = (uint16_t *)&ip6h->ip6_src;
19580 
19581 				/* calculate pseudo-header checksum */
19582 				cksum = up[0] + up[1] + up[2] + up[3] +
19583 				    up[4] + up[5] + up[6] + up[7] +
19584 				    up[8] + up[9] + up[10] + up[11] +
19585 				    up[12] + up[13] + up[14] + up[15];
19586 
19587 				/* Fold the initial sum */
19588 				cksum = (cksum & 0xffff) + (cksum >> 16);
19589 
19590 				up = (uint16_t *)(((uchar_t *)ip6h) +
19591 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19592 			}
19593 
19594 			if (hwcksum_flags & HCK_FULLCKSUM) {
19595 				/* clear checksum field for hardware */
19596 				*up = 0;
19597 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19598 				uint32_t sum;
19599 
19600 				/* pseudo-header checksumming */
19601 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19602 				sum = (sum & 0xFFFF) + (sum >> 16);
19603 				*up = (sum & 0xFFFF) + (sum >> 16);
19604 			} else {
19605 				/* software checksumming */
19606 				TCP_STAT(tcp_out_sw_cksum);
19607 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19608 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19609 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19610 				    cksum + IP_TCP_CSUM_COMP);
19611 				if (*up == 0)
19612 					*up = 0xFFFF;
19613 			}
19614 
19615 			/* IPv4 header checksum */
19616 			if (af == AF_INET) {
19617 				ipha->ipha_fragment_offset_and_flags |=
19618 				    (uint32_t)htons(ire->ire_frag_flag);
19619 
19620 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19621 					ipha->ipha_hdr_checksum = 0;
19622 				} else {
19623 					IP_HDR_CKSUM(ipha, cksum,
19624 					    ((uint32_t *)ipha)[0],
19625 					    ((uint16_t *)ipha)[4]);
19626 				}
19627 			}
19628 
19629 			/* advance header offset */
19630 			cur_hdr_off += hdr_frag_sz;
19631 
19632 			obbytes += tcp->tcp_last_sent_len;
19633 			++obsegs;
19634 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19635 		    *tail_unsent > 0);
19636 
19637 		if ((*xmit_tail)->b_next == NULL) {
19638 			/*
19639 			 * Store the lbolt used for RTT estimation. We can only
19640 			 * record one timestamp per mblk so we do it when we
19641 			 * reach the end of the payload buffer. Also we only
19642 			 * take a new timestamp sample when the previous timed
19643 			 * data from the same mblk has been ack'ed.
19644 			 */
19645 			(*xmit_tail)->b_prev = local_time;
19646 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19647 		}
19648 
19649 		ASSERT(*tail_unsent >= 0);
19650 		if (*tail_unsent > 0) {
19651 			/*
19652 			 * We got here because we broke out of the above
19653 			 * loop due to of one of the following cases:
19654 			 *
19655 			 *   1. len < adjusted MSS (i.e. small),
19656 			 *   2. Sender SWS avoidance,
19657 			 *   3. max_pld is zero.
19658 			 *
19659 			 * We are done for this Multidata, so trim our
19660 			 * last payload buffer (if any) accordingly.
19661 			 */
19662 			if (md_pbuf != NULL)
19663 				md_pbuf->b_wptr -= *tail_unsent;
19664 		} else if (*usable > 0) {
19665 			*xmit_tail = (*xmit_tail)->b_cont;
19666 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19667 			    (uintptr_t)INT_MAX);
19668 			*tail_unsent = (int)MBLKL(*xmit_tail);
19669 			add_buffer = B_TRUE;
19670 		}
19671 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19672 	    (tcp_mdt_chain || max_pld > 0));
19673 
19674 	/* send everything down */
19675 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19676 	    &rconfirm);
19677 
19678 #undef PREP_NEW_MULTIDATA
19679 #undef PREP_NEW_PBUF
19680 #undef IPVER
19681 
19682 	IRE_REFRELE(ire);
19683 	return (0);
19684 }
19685 
19686 /*
19687  * A wrapper function for sending one or more Multidata messages down to
19688  * the module below ip; this routine does not release the reference of the
19689  * IRE (caller does that).  This routine is analogous to tcp_send_data().
19690  */
19691 static void
19692 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
19693     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
19694 {
19695 	uint64_t delta;
19696 	nce_t *nce;
19697 
19698 	ASSERT(ire != NULL && ill != NULL);
19699 	ASSERT(ire->ire_stq != NULL);
19700 	ASSERT(md_mp_head != NULL);
19701 	ASSERT(rconfirm != NULL);
19702 
19703 	/* adjust MIBs and IRE timestamp */
19704 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
19705 	tcp->tcp_obsegs += obsegs;
19706 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
19707 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
19708 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
19709 
19710 	if (tcp->tcp_ipversion == IPV4_VERSION) {
19711 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
19712 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
19713 	} else {
19714 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
19715 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
19716 	}
19717 
19718 	ire->ire_ob_pkt_count += obsegs;
19719 	if (ire->ire_ipif != NULL)
19720 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
19721 	ire->ire_last_used_time = lbolt;
19722 
19723 	/* send it down */
19724 	putnext(ire->ire_stq, md_mp_head);
19725 
19726 	/* we're done for TCP/IPv4 */
19727 	if (tcp->tcp_ipversion == IPV4_VERSION)
19728 		return;
19729 
19730 	nce = ire->ire_nce;
19731 
19732 	ASSERT(nce != NULL);
19733 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
19734 	ASSERT(nce->nce_state != ND_INCOMPLETE);
19735 
19736 	/* reachability confirmation? */
19737 	if (*rconfirm) {
19738 		nce->nce_last = TICK_TO_MSEC(lbolt64);
19739 		if (nce->nce_state != ND_REACHABLE) {
19740 			mutex_enter(&nce->nce_lock);
19741 			nce->nce_state = ND_REACHABLE;
19742 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
19743 			mutex_exit(&nce->nce_lock);
19744 			(void) untimeout(nce->nce_timeout_id);
19745 			if (ip_debug > 2) {
19746 				/* ip1dbg */
19747 				pr_addr_dbg("tcp_multisend_data: state "
19748 				    "for %s changed to REACHABLE\n",
19749 				    AF_INET6, &ire->ire_addr_v6);
19750 			}
19751 		}
19752 		/* reset transport reachability confirmation */
19753 		*rconfirm = B_FALSE;
19754 	}
19755 
19756 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
19757 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
19758 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
19759 
19760 	if (delta > (uint64_t)ill->ill_reachable_time) {
19761 		mutex_enter(&nce->nce_lock);
19762 		switch (nce->nce_state) {
19763 		case ND_REACHABLE:
19764 		case ND_STALE:
19765 			/*
19766 			 * ND_REACHABLE is identical to ND_STALE in this
19767 			 * specific case. If reachable time has expired for
19768 			 * this neighbor (delta is greater than reachable
19769 			 * time), conceptually, the neighbor cache is no
19770 			 * longer in REACHABLE state, but already in STALE
19771 			 * state.  So the correct transition here is to
19772 			 * ND_DELAY.
19773 			 */
19774 			nce->nce_state = ND_DELAY;
19775 			mutex_exit(&nce->nce_lock);
19776 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
19777 			if (ip_debug > 3) {
19778 				/* ip2dbg */
19779 				pr_addr_dbg("tcp_multisend_data: state "
19780 				    "for %s changed to DELAY\n",
19781 				    AF_INET6, &ire->ire_addr_v6);
19782 			}
19783 			break;
19784 		case ND_DELAY:
19785 		case ND_PROBE:
19786 			mutex_exit(&nce->nce_lock);
19787 			/* Timers have already started */
19788 			break;
19789 		case ND_UNREACHABLE:
19790 			/*
19791 			 * ndp timer has detected that this nce is
19792 			 * unreachable and initiated deleting this nce
19793 			 * and all its associated IREs. This is a race
19794 			 * where we found the ire before it was deleted
19795 			 * and have just sent out a packet using this
19796 			 * unreachable nce.
19797 			 */
19798 			mutex_exit(&nce->nce_lock);
19799 			break;
19800 		default:
19801 			ASSERT(0);
19802 		}
19803 	}
19804 }
19805 
19806 /*
19807  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
19808  * scheme, and returns one of the following:
19809  *
19810  * -1 = failed allocation.
19811  *  0 = success; burst count reached, or usable send window is too small,
19812  *      and that we'd rather wait until later before sending again.
19813  *  1 = success; we are called from tcp_multisend(), and both usable send
19814  *      window and tail_unsent are greater than the MDT threshold, and thus
19815  *      Multidata Transmit should be used instead.
19816  */
19817 static int
19818 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19819     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19820     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19821     const int mdt_thres)
19822 {
19823 	int num_burst_seg = tcp->tcp_snd_burst;
19824 
19825 	for (;;) {
19826 		struct datab	*db;
19827 		tcph_t		*tcph;
19828 		uint32_t	sum;
19829 		mblk_t		*mp, *mp1;
19830 		uchar_t		*rptr;
19831 		int		len;
19832 
19833 		/*
19834 		 * If we're called by tcp_multisend(), and the amount of
19835 		 * sendable data as well as the size of current xmit_tail
19836 		 * is beyond the MDT threshold, return to the caller and
19837 		 * let the large data transmit be done using MDT.
19838 		 */
19839 		if (*usable > 0 && *usable > mdt_thres &&
19840 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
19841 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
19842 			ASSERT(tcp->tcp_mdt);
19843 			return (1);	/* success; do large send */
19844 		}
19845 
19846 		if (num_burst_seg-- == 0)
19847 			break;		/* success; burst count reached */
19848 
19849 		len = mss;
19850 		if (len > *usable) {
19851 			len = *usable;
19852 			if (len <= 0) {
19853 				/* Terminate the loop */
19854 				break;	/* success; too small */
19855 			}
19856 			/*
19857 			 * Sender silly-window avoidance.
19858 			 * Ignore this if we are going to send a
19859 			 * zero window probe out.
19860 			 *
19861 			 * TODO: force data into microscopic window?
19862 			 *	==> (!pushed || (unsent > usable))
19863 			 */
19864 			if (len < (tcp->tcp_max_swnd >> 1) &&
19865 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
19866 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
19867 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
19868 				/*
19869 				 * If the retransmit timer is not running
19870 				 * we start it so that we will retransmit
19871 				 * in the case when the the receiver has
19872 				 * decremented the window.
19873 				 */
19874 				if (*snxt == tcp->tcp_snxt &&
19875 				    *snxt == tcp->tcp_suna) {
19876 					/*
19877 					 * We are not supposed to send
19878 					 * anything.  So let's wait a little
19879 					 * bit longer before breaking SWS
19880 					 * avoidance.
19881 					 *
19882 					 * What should the value be?
19883 					 * Suggestion: MAX(init rexmit time,
19884 					 * tcp->tcp_rto)
19885 					 */
19886 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19887 				}
19888 				break;	/* success; too small */
19889 			}
19890 		}
19891 
19892 		tcph = tcp->tcp_tcph;
19893 
19894 		*usable -= len; /* Approximate - can be adjusted later */
19895 		if (*usable > 0)
19896 			tcph->th_flags[0] = TH_ACK;
19897 		else
19898 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
19899 
19900 		/*
19901 		 * Prime pump for IP's checksumming on our behalf
19902 		 * Include the adjustment for a source route if any.
19903 		 */
19904 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19905 		sum = (sum >> 16) + (sum & 0xFFFF);
19906 		U16_TO_ABE16(sum, tcph->th_sum);
19907 
19908 		U32_TO_ABE32(*snxt, tcph->th_seq);
19909 
19910 		/*
19911 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
19912 		 * set.  For the case when TCP_FSS_VALID is the only valid
19913 		 * bit (normal active close), branch off only when we think
19914 		 * that the FIN flag needs to be set.  Note for this case,
19915 		 * that (snxt + len) may not reflect the actual seg_len,
19916 		 * as len may be further reduced in tcp_xmit_mp().  If len
19917 		 * gets modified, we will end up here again.
19918 		 */
19919 		if (tcp->tcp_valid_bits != 0 &&
19920 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
19921 		    ((*snxt + len) == tcp->tcp_fss))) {
19922 			uchar_t		*prev_rptr;
19923 			uint32_t	prev_snxt = tcp->tcp_snxt;
19924 
19925 			if (*tail_unsent == 0) {
19926 				ASSERT((*xmit_tail)->b_cont != NULL);
19927 				*xmit_tail = (*xmit_tail)->b_cont;
19928 				prev_rptr = (*xmit_tail)->b_rptr;
19929 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
19930 				    (*xmit_tail)->b_rptr);
19931 			} else {
19932 				prev_rptr = (*xmit_tail)->b_rptr;
19933 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
19934 				    *tail_unsent;
19935 			}
19936 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
19937 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
19938 			/* Restore tcp_snxt so we get amount sent right. */
19939 			tcp->tcp_snxt = prev_snxt;
19940 			if (prev_rptr == (*xmit_tail)->b_rptr) {
19941 				/*
19942 				 * If the previous timestamp is still in use,
19943 				 * don't stomp on it.
19944 				 */
19945 				if ((*xmit_tail)->b_next == NULL) {
19946 					(*xmit_tail)->b_prev = local_time;
19947 					(*xmit_tail)->b_next =
19948 					    (mblk_t *)(uintptr_t)(*snxt);
19949 				}
19950 			} else
19951 				(*xmit_tail)->b_rptr = prev_rptr;
19952 
19953 			if (mp == NULL)
19954 				return (-1);
19955 			mp1 = mp->b_cont;
19956 
19957 			tcp->tcp_last_sent_len = (ushort_t)len;
19958 			while (mp1->b_cont) {
19959 				*xmit_tail = (*xmit_tail)->b_cont;
19960 				(*xmit_tail)->b_prev = local_time;
19961 				(*xmit_tail)->b_next =
19962 				    (mblk_t *)(uintptr_t)(*snxt);
19963 				mp1 = mp1->b_cont;
19964 			}
19965 			*snxt += len;
19966 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
19967 			BUMP_LOCAL(tcp->tcp_obsegs);
19968 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19969 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19970 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
19971 			tcp_send_data(tcp, q, mp);
19972 			continue;
19973 		}
19974 
19975 		*snxt += len;	/* Adjust later if we don't send all of len */
19976 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
19977 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
19978 
19979 		if (*tail_unsent) {
19980 			/* Are the bytes above us in flight? */
19981 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
19982 			if (rptr != (*xmit_tail)->b_rptr) {
19983 				*tail_unsent -= len;
19984 				tcp->tcp_last_sent_len = (ushort_t)len;
19985 				len += tcp_hdr_len;
19986 				if (tcp->tcp_ipversion == IPV4_VERSION)
19987 					tcp->tcp_ipha->ipha_length = htons(len);
19988 				else
19989 					tcp->tcp_ip6h->ip6_plen =
19990 					    htons(len -
19991 					    ((char *)&tcp->tcp_ip6h[1] -
19992 					    tcp->tcp_iphc));
19993 				mp = dupb(*xmit_tail);
19994 				if (!mp)
19995 					return (-1);	/* out_of_mem */
19996 				mp->b_rptr = rptr;
19997 				/*
19998 				 * If the old timestamp is no longer in use,
19999 				 * sample a new timestamp now.
20000 				 */
20001 				if ((*xmit_tail)->b_next == NULL) {
20002 					(*xmit_tail)->b_prev = local_time;
20003 					(*xmit_tail)->b_next =
20004 					    (mblk_t *)(uintptr_t)(*snxt-len);
20005 				}
20006 				goto must_alloc;
20007 			}
20008 		} else {
20009 			*xmit_tail = (*xmit_tail)->b_cont;
20010 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20011 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20012 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20013 			    (*xmit_tail)->b_rptr);
20014 		}
20015 
20016 		(*xmit_tail)->b_prev = local_time;
20017 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20018 
20019 		*tail_unsent -= len;
20020 		tcp->tcp_last_sent_len = (ushort_t)len;
20021 
20022 		len += tcp_hdr_len;
20023 		if (tcp->tcp_ipversion == IPV4_VERSION)
20024 			tcp->tcp_ipha->ipha_length = htons(len);
20025 		else
20026 			tcp->tcp_ip6h->ip6_plen = htons(len -
20027 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20028 
20029 		mp = dupb(*xmit_tail);
20030 		if (!mp)
20031 			return (-1);	/* out_of_mem */
20032 
20033 		len = tcp_hdr_len;
20034 		/*
20035 		 * There are four reasons to allocate a new hdr mblk:
20036 		 *  1) The bytes above us are in use by another packet
20037 		 *  2) We don't have good alignment
20038 		 *  3) The mblk is being shared
20039 		 *  4) We don't have enough room for a header
20040 		 */
20041 		rptr = mp->b_rptr - len;
20042 		if (!OK_32PTR(rptr) ||
20043 		    ((db = mp->b_datap), db->db_ref != 2) ||
20044 		    rptr < db->db_base) {
20045 			/* NOTE: we assume allocb returns an OK_32PTR */
20046 
20047 		must_alloc:;
20048 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20049 			    tcp_wroff_xtra, BPRI_MED);
20050 			if (!mp1) {
20051 				freemsg(mp);
20052 				return (-1);	/* out_of_mem */
20053 			}
20054 			mp1->b_cont = mp;
20055 			mp = mp1;
20056 			/* Leave room for Link Level header */
20057 			len = tcp_hdr_len;
20058 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20059 			mp->b_wptr = &rptr[len];
20060 		}
20061 
20062 		/*
20063 		 * Fill in the header using the template header, and add
20064 		 * options such as time-stamp, ECN and/or SACK, as needed.
20065 		 */
20066 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20067 
20068 		mp->b_rptr = rptr;
20069 
20070 		if (*tail_unsent) {
20071 			int spill = *tail_unsent;
20072 
20073 			mp1 = mp->b_cont;
20074 			if (!mp1)
20075 				mp1 = mp;
20076 
20077 			/*
20078 			 * If we're a little short, tack on more mblks until
20079 			 * there is no more spillover.
20080 			 */
20081 			while (spill < 0) {
20082 				mblk_t *nmp;
20083 				int nmpsz;
20084 
20085 				nmp = (*xmit_tail)->b_cont;
20086 				nmpsz = MBLKL(nmp);
20087 
20088 				/*
20089 				 * Excess data in mblk; can we split it?
20090 				 * If MDT is enabled for the connection,
20091 				 * keep on splitting as this is a transient
20092 				 * send path.
20093 				 */
20094 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20095 					/*
20096 					 * Don't split if stream head was
20097 					 * told to break up larger writes
20098 					 * into smaller ones.
20099 					 */
20100 					if (tcp->tcp_maxpsz > 0)
20101 						break;
20102 
20103 					/*
20104 					 * Next mblk is less than SMSS/2
20105 					 * rounded up to nearest 64-byte;
20106 					 * let it get sent as part of the
20107 					 * next segment.
20108 					 */
20109 					if (tcp->tcp_localnet &&
20110 					    !tcp->tcp_cork &&
20111 					    (nmpsz < roundup((mss >> 1), 64)))
20112 						break;
20113 				}
20114 
20115 				*xmit_tail = nmp;
20116 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20117 				/* Stash for rtt use later */
20118 				(*xmit_tail)->b_prev = local_time;
20119 				(*xmit_tail)->b_next =
20120 				    (mblk_t *)(uintptr_t)(*snxt - len);
20121 				mp1->b_cont = dupb(*xmit_tail);
20122 				mp1 = mp1->b_cont;
20123 
20124 				spill += nmpsz;
20125 				if (mp1 == NULL) {
20126 					*tail_unsent = spill;
20127 					freemsg(mp);
20128 					return (-1);	/* out_of_mem */
20129 				}
20130 			}
20131 
20132 			/* Trim back any surplus on the last mblk */
20133 			if (spill >= 0) {
20134 				mp1->b_wptr -= spill;
20135 				*tail_unsent = spill;
20136 			} else {
20137 				/*
20138 				 * We did not send everything we could in
20139 				 * order to remain within the b_cont limit.
20140 				 */
20141 				*usable -= spill;
20142 				*snxt += spill;
20143 				tcp->tcp_last_sent_len += spill;
20144 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20145 				/*
20146 				 * Adjust the checksum
20147 				 */
20148 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20149 				sum += spill;
20150 				sum = (sum >> 16) + (sum & 0xFFFF);
20151 				U16_TO_ABE16(sum, tcph->th_sum);
20152 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20153 					sum = ntohs(
20154 					    ((ipha_t *)rptr)->ipha_length) +
20155 					    spill;
20156 					((ipha_t *)rptr)->ipha_length =
20157 					    htons(sum);
20158 				} else {
20159 					sum = ntohs(
20160 					    ((ip6_t *)rptr)->ip6_plen) +
20161 					    spill;
20162 					((ip6_t *)rptr)->ip6_plen =
20163 					    htons(sum);
20164 				}
20165 				*tail_unsent = 0;
20166 			}
20167 		}
20168 		if (tcp->tcp_ip_forward_progress) {
20169 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20170 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20171 			tcp->tcp_ip_forward_progress = B_FALSE;
20172 		}
20173 
20174 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20175 		tcp_send_data(tcp, q, mp);
20176 		BUMP_LOCAL(tcp->tcp_obsegs);
20177 	}
20178 
20179 	return (0);
20180 }
20181 
20182 /* Unlink and return any mblk that looks like it contains a MDT info */
20183 static mblk_t *
20184 tcp_mdt_info_mp(mblk_t *mp)
20185 {
20186 	mblk_t	*prev_mp;
20187 
20188 	for (;;) {
20189 		prev_mp = mp;
20190 		/* no more to process? */
20191 		if ((mp = mp->b_cont) == NULL)
20192 			break;
20193 
20194 		switch (DB_TYPE(mp)) {
20195 		case M_CTL:
20196 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20197 				continue;
20198 			ASSERT(prev_mp != NULL);
20199 			prev_mp->b_cont = mp->b_cont;
20200 			mp->b_cont = NULL;
20201 			return (mp);
20202 		default:
20203 			break;
20204 		}
20205 	}
20206 	return (mp);
20207 }
20208 
20209 /* MDT info update routine, called when IP notifies us about MDT */
20210 static void
20211 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20212 {
20213 	boolean_t prev_state;
20214 
20215 	/*
20216 	 * IP is telling us to abort MDT on this connection?  We know
20217 	 * this because the capability is only turned off when IP
20218 	 * encounters some pathological cases, e.g. link-layer change
20219 	 * where the new driver doesn't support MDT, or in situation
20220 	 * where MDT usage on the link-layer has been switched off.
20221 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20222 	 * if the link-layer doesn't support MDT, and if it does, it
20223 	 * will indicate that the feature is to be turned on.
20224 	 */
20225 	prev_state = tcp->tcp_mdt;
20226 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20227 	if (!tcp->tcp_mdt && !first) {
20228 		TCP_STAT(tcp_mdt_conn_halted3);
20229 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20230 		    (void *)tcp->tcp_connp));
20231 	}
20232 
20233 	/*
20234 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20235 	 * so disable MDT otherwise.  The checks are done here
20236 	 * and in tcp_wput_data().
20237 	 */
20238 	if (tcp->tcp_mdt &&
20239 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20240 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20241 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20242 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20243 		tcp->tcp_mdt = B_FALSE;
20244 
20245 	if (tcp->tcp_mdt) {
20246 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20247 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20248 			    "version (%d), expected version is %d",
20249 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20250 			tcp->tcp_mdt = B_FALSE;
20251 			return;
20252 		}
20253 
20254 		/*
20255 		 * We need the driver to be able to handle at least three
20256 		 * spans per packet in order for tcp MDT to be utilized.
20257 		 * The first is for the header portion, while the rest are
20258 		 * needed to handle a packet that straddles across two
20259 		 * virtually non-contiguous buffers; a typical tcp packet
20260 		 * therefore consists of only two spans.  Note that we take
20261 		 * a zero as "don't care".
20262 		 */
20263 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20264 		    mdt_capab->ill_mdt_span_limit < 3) {
20265 			tcp->tcp_mdt = B_FALSE;
20266 			return;
20267 		}
20268 
20269 		/* a zero means driver wants default value */
20270 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20271 		    tcp_mdt_max_pbufs);
20272 		if (tcp->tcp_mdt_max_pld == 0)
20273 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20274 
20275 		/* ensure 32-bit alignment */
20276 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20277 		    mdt_capab->ill_mdt_hdr_head), 4);
20278 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20279 		    mdt_capab->ill_mdt_hdr_tail), 4);
20280 
20281 		if (!first && !prev_state) {
20282 			TCP_STAT(tcp_mdt_conn_resumed2);
20283 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20284 			    (void *)tcp->tcp_connp));
20285 		}
20286 	}
20287 }
20288 
20289 static void
20290 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20291 {
20292 	conn_t *connp = tcp->tcp_connp;
20293 
20294 	ASSERT(ire != NULL);
20295 
20296 	/*
20297 	 * We may be in the fastpath here, and although we essentially do
20298 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20299 	 * we try to keep things as brief as possible.  After all, these
20300 	 * are only best-effort checks, and we do more thorough ones prior
20301 	 * to calling tcp_multisend().
20302 	 */
20303 	if (ip_multidata_outbound && check_mdt &&
20304 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20305 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20306 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20307 	    !(ire->ire_flags & RTF_MULTIRT) &&
20308 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20309 	    CONN_IS_MD_FASTPATH(connp)) {
20310 		/* Remember the result */
20311 		connp->conn_mdt_ok = B_TRUE;
20312 
20313 		ASSERT(ill->ill_mdt_capab != NULL);
20314 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20315 			/*
20316 			 * If MDT has been previously turned off in the past,
20317 			 * and we currently can do MDT (due to IPQoS policy
20318 			 * removal, etc.) then enable it for this interface.
20319 			 */
20320 			ill->ill_mdt_capab->ill_mdt_on = 1;
20321 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20322 			    "interface %s\n", (void *)connp, ill->ill_name));
20323 		}
20324 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20325 	}
20326 
20327 	/*
20328 	 * The goal is to reduce the number of generated tcp segments by
20329 	 * setting the maxpsz multiplier to 0; this will have an affect on
20330 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20331 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20332 	 * of outbound segments and incoming ACKs, thus allowing for better
20333 	 * network and system performance.  In contrast the legacy behavior
20334 	 * may result in sending less than SMSS size, because the last mblk
20335 	 * for some packets may have more data than needed to make up SMSS,
20336 	 * and the legacy code refused to "split" it.
20337 	 *
20338 	 * We apply the new behavior on following situations:
20339 	 *
20340 	 *   1) Loopback connections,
20341 	 *   2) Connections in which the remote peer is not on local subnet,
20342 	 *   3) Local subnet connections over the bge interface (see below).
20343 	 *
20344 	 * Ideally, we would like this behavior to apply for interfaces other
20345 	 * than bge.  However, doing so would negatively impact drivers which
20346 	 * perform dynamic mapping and unmapping of DMA resources, which are
20347 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20348 	 * packet will be generated by tcp).  The bge driver does not suffer
20349 	 * from this, as it copies the mblks into pre-mapped buffers, and
20350 	 * therefore does not require more I/O resources than before.
20351 	 *
20352 	 * Otherwise, this behavior is present on all network interfaces when
20353 	 * the destination endpoint is non-local, since reducing the number
20354 	 * of packets in general is good for the network.
20355 	 *
20356 	 * TODO We need to remove this hard-coded conditional for bge once
20357 	 *	a better "self-tuning" mechanism, or a way to comprehend
20358 	 *	the driver transmit strategy is devised.  Until the solution
20359 	 *	is found and well understood, we live with this hack.
20360 	 */
20361 	if (!tcp_static_maxpsz &&
20362 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20363 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20364 		/* override the default value */
20365 		tcp->tcp_maxpsz = 0;
20366 
20367 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20368 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20369 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20370 	}
20371 
20372 	/* set the stream head parameters accordingly */
20373 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20374 }
20375 
20376 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20377 static void
20378 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20379 {
20380 	uchar_t	fval = *mp->b_rptr;
20381 	mblk_t	*tail;
20382 	queue_t	*q = tcp->tcp_wq;
20383 
20384 	/* TODO: How should flush interact with urgent data? */
20385 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20386 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20387 		/*
20388 		 * Flush only data that has not yet been put on the wire.  If
20389 		 * we flush data that we have already transmitted, life, as we
20390 		 * know it, may come to an end.
20391 		 */
20392 		tail = tcp->tcp_xmit_tail;
20393 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20394 		tcp->tcp_xmit_tail_unsent = 0;
20395 		tcp->tcp_unsent = 0;
20396 		if (tail->b_wptr != tail->b_rptr)
20397 			tail = tail->b_cont;
20398 		if (tail) {
20399 			mblk_t **excess = &tcp->tcp_xmit_head;
20400 			for (;;) {
20401 				mblk_t *mp1 = *excess;
20402 				if (mp1 == tail)
20403 					break;
20404 				tcp->tcp_xmit_tail = mp1;
20405 				tcp->tcp_xmit_last = mp1;
20406 				excess = &mp1->b_cont;
20407 			}
20408 			*excess = NULL;
20409 			tcp_close_mpp(&tail);
20410 			if (tcp->tcp_snd_zcopy_aware)
20411 				tcp_zcopy_notify(tcp);
20412 		}
20413 		/*
20414 		 * We have no unsent data, so unsent must be less than
20415 		 * tcp_xmit_lowater, so re-enable flow.
20416 		 */
20417 		if (tcp->tcp_flow_stopped) {
20418 			tcp_clrqfull(tcp);
20419 		}
20420 	}
20421 	/*
20422 	 * TODO: you can't just flush these, you have to increase rwnd for one
20423 	 * thing.  For another, how should urgent data interact?
20424 	 */
20425 	if (fval & FLUSHR) {
20426 		*mp->b_rptr = fval & ~FLUSHW;
20427 		/* XXX */
20428 		qreply(q, mp);
20429 		return;
20430 	}
20431 	freemsg(mp);
20432 }
20433 
20434 /*
20435  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20436  * messages.
20437  */
20438 static void
20439 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20440 {
20441 	mblk_t	*mp1;
20442 	STRUCT_HANDLE(strbuf, sb);
20443 	uint16_t port;
20444 	queue_t 	*q = tcp->tcp_wq;
20445 	in6_addr_t	v6addr;
20446 	ipaddr_t	v4addr;
20447 	uint32_t	flowinfo = 0;
20448 	int		addrlen;
20449 
20450 	/* Make sure it is one of ours. */
20451 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20452 	case TI_GETMYNAME:
20453 	case TI_GETPEERNAME:
20454 		break;
20455 	default:
20456 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20457 		return;
20458 	}
20459 	switch (mi_copy_state(q, mp, &mp1)) {
20460 	case -1:
20461 		return;
20462 	case MI_COPY_CASE(MI_COPY_IN, 1):
20463 		break;
20464 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20465 		/* Copy out the strbuf. */
20466 		mi_copyout(q, mp);
20467 		return;
20468 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20469 		/* All done. */
20470 		mi_copy_done(q, mp, 0);
20471 		return;
20472 	default:
20473 		mi_copy_done(q, mp, EPROTO);
20474 		return;
20475 	}
20476 	/* Check alignment of the strbuf */
20477 	if (!OK_32PTR(mp1->b_rptr)) {
20478 		mi_copy_done(q, mp, EINVAL);
20479 		return;
20480 	}
20481 
20482 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20483 	    (void *)mp1->b_rptr);
20484 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20485 
20486 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20487 		mi_copy_done(q, mp, EINVAL);
20488 		return;
20489 	}
20490 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20491 	case TI_GETMYNAME:
20492 		if (tcp->tcp_family == AF_INET) {
20493 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20494 				v4addr = tcp->tcp_ipha->ipha_src;
20495 			} else {
20496 				/* can't return an address in this case */
20497 				v4addr = 0;
20498 			}
20499 		} else {
20500 			/* tcp->tcp_family == AF_INET6 */
20501 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20502 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20503 				    &v6addr);
20504 			} else {
20505 				v6addr = tcp->tcp_ip6h->ip6_src;
20506 			}
20507 		}
20508 		port = tcp->tcp_lport;
20509 		break;
20510 	case TI_GETPEERNAME:
20511 		if (tcp->tcp_family == AF_INET) {
20512 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20513 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20514 				    v4addr);
20515 			} else {
20516 				/* can't return an address in this case */
20517 				v4addr = 0;
20518 			}
20519 		} else {
20520 			/* tcp->tcp_family == AF_INET6) */
20521 			v6addr = tcp->tcp_remote_v6;
20522 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20523 				/*
20524 				 * No flowinfo if tcp->tcp_ipversion is v4.
20525 				 *
20526 				 * flowinfo was already initialized to zero
20527 				 * where it was declared above, so only
20528 				 * set it if ipversion is v6.
20529 				 */
20530 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20531 				    ~IPV6_VERS_AND_FLOW_MASK;
20532 			}
20533 		}
20534 		port = tcp->tcp_fport;
20535 		break;
20536 	default:
20537 		mi_copy_done(q, mp, EPROTO);
20538 		return;
20539 	}
20540 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20541 	if (!mp1)
20542 		return;
20543 
20544 	if (tcp->tcp_family == AF_INET) {
20545 		sin_t *sin;
20546 
20547 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20548 		sin = (sin_t *)mp1->b_rptr;
20549 		mp1->b_wptr = (uchar_t *)&sin[1];
20550 		*sin = sin_null;
20551 		sin->sin_family = AF_INET;
20552 		sin->sin_addr.s_addr = v4addr;
20553 		sin->sin_port = port;
20554 	} else {
20555 		/* tcp->tcp_family == AF_INET6 */
20556 		sin6_t *sin6;
20557 
20558 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20559 		sin6 = (sin6_t *)mp1->b_rptr;
20560 		mp1->b_wptr = (uchar_t *)&sin6[1];
20561 		*sin6 = sin6_null;
20562 		sin6->sin6_family = AF_INET6;
20563 		sin6->sin6_flowinfo = flowinfo;
20564 		sin6->sin6_addr = v6addr;
20565 		sin6->sin6_port = port;
20566 	}
20567 	/* Copy out the address */
20568 	mi_copyout(q, mp);
20569 }
20570 
20571 /*
20572  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20573  * messages.
20574  */
20575 /* ARGSUSED */
20576 static void
20577 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20578 {
20579 	conn_t 	*connp = (conn_t *)arg;
20580 	tcp_t	*tcp = connp->conn_tcp;
20581 	queue_t	*q = tcp->tcp_wq;
20582 	struct iocblk	*iocp;
20583 
20584 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20585 	/*
20586 	 * Try and ASSERT the minimum possible references on the
20587 	 * conn early enough. Since we are executing on write side,
20588 	 * the connection is obviously not detached and that means
20589 	 * there is a ref each for TCP and IP. Since we are behind
20590 	 * the squeue, the minimum references needed are 3. If the
20591 	 * conn is in classifier hash list, there should be an
20592 	 * extra ref for that (we check both the possibilities).
20593 	 */
20594 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20595 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20596 
20597 	iocp = (struct iocblk *)mp->b_rptr;
20598 	switch (iocp->ioc_cmd) {
20599 	case TCP_IOC_DEFAULT_Q:
20600 		/* Wants to be the default wq. */
20601 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20602 			iocp->ioc_error = EPERM;
20603 			iocp->ioc_count = 0;
20604 			mp->b_datap->db_type = M_IOCACK;
20605 			qreply(q, mp);
20606 			return;
20607 		}
20608 		tcp_def_q_set(tcp, mp);
20609 		return;
20610 	case _SIOCSOCKFALLBACK:
20611 		/*
20612 		 * Either sockmod is about to be popped and the socket
20613 		 * would now be treated as a plain stream, or a module
20614 		 * is about to be pushed so we could no longer use read-
20615 		 * side synchronous streams for fused loopback tcp.
20616 		 * Drain any queued data and disable direct sockfs
20617 		 * interface from now on.
20618 		 */
20619 		if (!tcp->tcp_issocket) {
20620 			DB_TYPE(mp) = M_IOCNAK;
20621 			iocp->ioc_error = EINVAL;
20622 		} else {
20623 #ifdef	_ILP32
20624 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20625 #else
20626 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20627 #endif
20628 			/*
20629 			 * Insert this socket into the acceptor hash.
20630 			 * We might need it for T_CONN_RES message
20631 			 */
20632 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20633 
20634 			if (tcp->tcp_fused) {
20635 				/*
20636 				 * This is a fused loopback tcp; disable
20637 				 * read-side synchronous streams interface
20638 				 * and drain any queued data.  It is okay
20639 				 * to do this for non-synchronous streams
20640 				 * fused tcp as well.
20641 				 */
20642 				tcp_fuse_disable_pair(tcp, B_FALSE);
20643 			}
20644 			tcp->tcp_issocket = B_FALSE;
20645 			TCP_STAT(tcp_sock_fallback);
20646 
20647 			DB_TYPE(mp) = M_IOCACK;
20648 			iocp->ioc_error = 0;
20649 		}
20650 		iocp->ioc_count = 0;
20651 		iocp->ioc_rval = 0;
20652 		qreply(q, mp);
20653 		return;
20654 	}
20655 	CALL_IP_WPUT(connp, q, mp);
20656 }
20657 
20658 /*
20659  * This routine is called by tcp_wput() to handle all TPI requests.
20660  */
20661 /* ARGSUSED */
20662 static void
20663 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20664 {
20665 	conn_t 	*connp = (conn_t *)arg;
20666 	tcp_t	*tcp = connp->conn_tcp;
20667 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20668 	uchar_t *rptr;
20669 	t_scalar_t type;
20670 	int len;
20671 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20672 
20673 	/*
20674 	 * Try and ASSERT the minimum possible references on the
20675 	 * conn early enough. Since we are executing on write side,
20676 	 * the connection is obviously not detached and that means
20677 	 * there is a ref each for TCP and IP. Since we are behind
20678 	 * the squeue, the minimum references needed are 3. If the
20679 	 * conn is in classifier hash list, there should be an
20680 	 * extra ref for that (we check both the possibilities).
20681 	 */
20682 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20683 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20684 
20685 	rptr = mp->b_rptr;
20686 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
20687 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
20688 		type = ((union T_primitives *)rptr)->type;
20689 		if (type == T_EXDATA_REQ) {
20690 			uint32_t msize = msgdsize(mp->b_cont);
20691 
20692 			len = msize - 1;
20693 			if (len < 0) {
20694 				freemsg(mp);
20695 				return;
20696 			}
20697 			/*
20698 			 * Try to force urgent data out on the wire.
20699 			 * Even if we have unsent data this will
20700 			 * at least send the urgent flag.
20701 			 * XXX does not handle more flag correctly.
20702 			 */
20703 			len += tcp->tcp_unsent;
20704 			len += tcp->tcp_snxt;
20705 			tcp->tcp_urg = len;
20706 			tcp->tcp_valid_bits |= TCP_URG_VALID;
20707 
20708 			/* Bypass tcp protocol for fused tcp loopback */
20709 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20710 				return;
20711 		} else if (type != T_DATA_REQ) {
20712 			goto non_urgent_data;
20713 		}
20714 		/* TODO: options, flags, ... from user */
20715 		/* Set length to zero for reclamation below */
20716 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
20717 		freeb(mp);
20718 		return;
20719 	} else {
20720 		if (tcp->tcp_debug) {
20721 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20722 			    "tcp_wput_proto, dropping one...");
20723 		}
20724 		freemsg(mp);
20725 		return;
20726 	}
20727 
20728 non_urgent_data:
20729 
20730 	switch ((int)tprim->type) {
20731 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
20732 		/*
20733 		 * save the kssl_ent_t from the next block, and convert this
20734 		 * back to a normal bind_req.
20735 		 */
20736 		if (mp->b_cont != NULL) {
20737 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
20738 
20739 			if (tcp->tcp_kssl_ent != NULL) {
20740 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
20741 				    KSSL_NO_PROXY);
20742 				tcp->tcp_kssl_ent = NULL;
20743 			}
20744 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
20745 			    sizeof (kssl_ent_t));
20746 			kssl_hold_ent(tcp->tcp_kssl_ent);
20747 			freemsg(mp->b_cont);
20748 			mp->b_cont = NULL;
20749 		}
20750 		tprim->type = T_BIND_REQ;
20751 
20752 	/* FALLTHROUGH */
20753 	case O_T_BIND_REQ:	/* bind request */
20754 	case T_BIND_REQ:	/* new semantics bind request */
20755 		tcp_bind(tcp, mp);
20756 		break;
20757 	case T_UNBIND_REQ:	/* unbind request */
20758 		tcp_unbind(tcp, mp);
20759 		break;
20760 	case O_T_CONN_RES:	/* old connection response XXX */
20761 	case T_CONN_RES:	/* connection response */
20762 		tcp_accept(tcp, mp);
20763 		break;
20764 	case T_CONN_REQ:	/* connection request */
20765 		tcp_connect(tcp, mp);
20766 		break;
20767 	case T_DISCON_REQ:	/* disconnect request */
20768 		tcp_disconnect(tcp, mp);
20769 		break;
20770 	case T_CAPABILITY_REQ:
20771 		tcp_capability_req(tcp, mp);	/* capability request */
20772 		break;
20773 	case T_INFO_REQ:	/* information request */
20774 		tcp_info_req(tcp, mp);
20775 		break;
20776 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
20777 		/* Only IP is allowed to return meaningful value */
20778 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20779 		break;
20780 	case T_OPTMGMT_REQ:
20781 		/*
20782 		 * Note:  no support for snmpcom_req() through new
20783 		 * T_OPTMGMT_REQ. See comments in ip.c
20784 		 */
20785 		/* Only IP is allowed to return meaningful value */
20786 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20787 		break;
20788 
20789 	case T_UNITDATA_REQ:	/* unitdata request */
20790 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20791 		break;
20792 	case T_ORDREL_REQ:	/* orderly release req */
20793 		freemsg(mp);
20794 
20795 		if (tcp->tcp_fused)
20796 			tcp_unfuse(tcp);
20797 
20798 		if (tcp_xmit_end(tcp) != 0) {
20799 			/*
20800 			 * We were crossing FINs and got a reset from
20801 			 * the other side. Just ignore it.
20802 			 */
20803 			if (tcp->tcp_debug) {
20804 				(void) strlog(TCP_MOD_ID, 0, 1,
20805 				    SL_ERROR|SL_TRACE,
20806 				    "tcp_wput_proto, T_ORDREL_REQ out of "
20807 				    "state %s",
20808 				    tcp_display(tcp, NULL,
20809 				    DISP_ADDR_AND_PORT));
20810 			}
20811 		}
20812 		break;
20813 	case T_ADDR_REQ:
20814 		tcp_addr_req(tcp, mp);
20815 		break;
20816 	default:
20817 		if (tcp->tcp_debug) {
20818 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20819 			    "tcp_wput_proto, bogus TPI msg, type %d",
20820 			    tprim->type);
20821 		}
20822 		/*
20823 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
20824 		 * to recover.
20825 		 */
20826 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20827 		break;
20828 	}
20829 }
20830 
20831 /*
20832  * The TCP write service routine should never be called...
20833  */
20834 /* ARGSUSED */
20835 static void
20836 tcp_wsrv(queue_t *q)
20837 {
20838 	TCP_STAT(tcp_wsrv_called);
20839 }
20840 
20841 /* Non overlapping byte exchanger */
20842 static void
20843 tcp_xchg(uchar_t *a, uchar_t *b, int len)
20844 {
20845 	uchar_t	uch;
20846 
20847 	while (len-- > 0) {
20848 		uch = a[len];
20849 		a[len] = b[len];
20850 		b[len] = uch;
20851 	}
20852 }
20853 
20854 /*
20855  * Send out a control packet on the tcp connection specified.  This routine
20856  * is typically called where we need a simple ACK or RST generated.
20857  */
20858 static void
20859 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
20860 {
20861 	uchar_t		*rptr;
20862 	tcph_t		*tcph;
20863 	ipha_t		*ipha = NULL;
20864 	ip6_t		*ip6h = NULL;
20865 	uint32_t	sum;
20866 	int		tcp_hdr_len;
20867 	int		tcp_ip_hdr_len;
20868 	mblk_t		*mp;
20869 
20870 	/*
20871 	 * Save sum for use in source route later.
20872 	 */
20873 	ASSERT(tcp != NULL);
20874 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
20875 	tcp_hdr_len = tcp->tcp_hdr_len;
20876 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
20877 
20878 	/* If a text string is passed in with the request, pass it to strlog. */
20879 	if (str != NULL && tcp->tcp_debug) {
20880 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20881 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
20882 		    str, seq, ack, ctl);
20883 	}
20884 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
20885 	    BPRI_MED);
20886 	if (mp == NULL) {
20887 		return;
20888 	}
20889 	rptr = &mp->b_rptr[tcp_wroff_xtra];
20890 	mp->b_rptr = rptr;
20891 	mp->b_wptr = &rptr[tcp_hdr_len];
20892 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
20893 
20894 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20895 		ipha = (ipha_t *)rptr;
20896 		ipha->ipha_length = htons(tcp_hdr_len);
20897 	} else {
20898 		ip6h = (ip6_t *)rptr;
20899 		ASSERT(tcp != NULL);
20900 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
20901 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20902 	}
20903 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
20904 	tcph->th_flags[0] = (uint8_t)ctl;
20905 	if (ctl & TH_RST) {
20906 		BUMP_MIB(&tcp_mib, tcpOutRsts);
20907 		BUMP_MIB(&tcp_mib, tcpOutControl);
20908 		/*
20909 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
20910 		 */
20911 		if (tcp->tcp_snd_ts_ok &&
20912 		    tcp->tcp_state > TCPS_SYN_SENT) {
20913 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
20914 			*(mp->b_wptr) = TCPOPT_EOL;
20915 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20916 				ipha->ipha_length = htons(tcp_hdr_len -
20917 				    TCPOPT_REAL_TS_LEN);
20918 			} else {
20919 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
20920 				    TCPOPT_REAL_TS_LEN);
20921 			}
20922 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
20923 			sum -= TCPOPT_REAL_TS_LEN;
20924 		}
20925 	}
20926 	if (ctl & TH_ACK) {
20927 		if (tcp->tcp_snd_ts_ok) {
20928 			U32_TO_BE32(lbolt,
20929 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
20930 			U32_TO_BE32(tcp->tcp_ts_recent,
20931 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
20932 		}
20933 
20934 		/* Update the latest receive window size in TCP header. */
20935 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
20936 		    tcph->th_win);
20937 		tcp->tcp_rack = ack;
20938 		tcp->tcp_rack_cnt = 0;
20939 		BUMP_MIB(&tcp_mib, tcpOutAck);
20940 	}
20941 	BUMP_LOCAL(tcp->tcp_obsegs);
20942 	U32_TO_BE32(seq, tcph->th_seq);
20943 	U32_TO_BE32(ack, tcph->th_ack);
20944 	/*
20945 	 * Include the adjustment for a source route if any.
20946 	 */
20947 	sum = (sum >> 16) + (sum & 0xFFFF);
20948 	U16_TO_BE16(sum, tcph->th_sum);
20949 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20950 	tcp_send_data(tcp, tcp->tcp_wq, mp);
20951 }
20952 
20953 /*
20954  * If this routine returns B_TRUE, TCP can generate a RST in response
20955  * to a segment.  If it returns B_FALSE, TCP should not respond.
20956  */
20957 static boolean_t
20958 tcp_send_rst_chk(void)
20959 {
20960 	clock_t	now;
20961 
20962 	/*
20963 	 * TCP needs to protect itself from generating too many RSTs.
20964 	 * This can be a DoS attack by sending us random segments
20965 	 * soliciting RSTs.
20966 	 *
20967 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
20968 	 * in each 1 second interval.  In this way, TCP still generate
20969 	 * RSTs in normal cases but when under attack, the impact is
20970 	 * limited.
20971 	 */
20972 	if (tcp_rst_sent_rate_enabled != 0) {
20973 		now = lbolt;
20974 		/* lbolt can wrap around. */
20975 		if ((tcp_last_rst_intrvl > now) ||
20976 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
20977 			tcp_last_rst_intrvl = now;
20978 			tcp_rst_cnt = 1;
20979 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
20980 			return (B_FALSE);
20981 		}
20982 	}
20983 	return (B_TRUE);
20984 }
20985 
20986 /*
20987  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
20988  */
20989 static void
20990 tcp_ip_ire_mark_advice(tcp_t *tcp)
20991 {
20992 	mblk_t *mp;
20993 	ipic_t *ipic;
20994 
20995 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20996 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
20997 		    &ipic);
20998 	} else {
20999 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21000 		    &ipic);
21001 	}
21002 	if (mp == NULL)
21003 		return;
21004 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21005 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21006 }
21007 
21008 /*
21009  * Return an IP advice ioctl mblk and set ipic to be the pointer
21010  * to the advice structure.
21011  */
21012 static mblk_t *
21013 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21014 {
21015 	struct iocblk *ioc;
21016 	mblk_t *mp, *mp1;
21017 
21018 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21019 	if (mp == NULL)
21020 		return (NULL);
21021 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21022 	*ipic = (ipic_t *)mp->b_rptr;
21023 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21024 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21025 
21026 	bcopy(addr, *ipic + 1, addr_len);
21027 
21028 	(*ipic)->ipic_addr_length = addr_len;
21029 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21030 
21031 	mp1 = mkiocb(IP_IOCTL);
21032 	if (mp1 == NULL) {
21033 		freemsg(mp);
21034 		return (NULL);
21035 	}
21036 	mp1->b_cont = mp;
21037 	ioc = (struct iocblk *)mp1->b_rptr;
21038 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21039 
21040 	return (mp1);
21041 }
21042 
21043 /*
21044  * Generate a reset based on an inbound packet for which there is no active
21045  * tcp state that we can find.
21046  *
21047  * IPSEC NOTE : Try to send the reply with the same protection as it came
21048  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21049  * the packet will go out at the same level of protection as it came in by
21050  * converting the IPSEC_IN to IPSEC_OUT.
21051  */
21052 static void
21053 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21054     uint32_t ack, int ctl, uint_t ip_hdr_len)
21055 {
21056 	ipha_t		*ipha = NULL;
21057 	ip6_t		*ip6h = NULL;
21058 	ushort_t	len;
21059 	tcph_t		*tcph;
21060 	int		i;
21061 	mblk_t		*ipsec_mp;
21062 	boolean_t	mctl_present;
21063 	ipic_t		*ipic;
21064 	ipaddr_t	v4addr;
21065 	in6_addr_t	v6addr;
21066 	int		addr_len;
21067 	void		*addr;
21068 	queue_t		*q = tcp_g_q;
21069 	tcp_t		*tcp = Q_TO_TCP(q);
21070 
21071 	if (!tcp_send_rst_chk()) {
21072 		tcp_rst_unsent++;
21073 		freemsg(mp);
21074 		return;
21075 	}
21076 
21077 	if (mp->b_datap->db_type == M_CTL) {
21078 		ipsec_mp = mp;
21079 		mp = mp->b_cont;
21080 		mctl_present = B_TRUE;
21081 	} else {
21082 		ipsec_mp = mp;
21083 		mctl_present = B_FALSE;
21084 	}
21085 
21086 	if (str && q && tcp_dbg) {
21087 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21088 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21089 		    "flags 0x%x",
21090 		    str, seq, ack, ctl);
21091 	}
21092 	if (mp->b_datap->db_ref != 1) {
21093 		mblk_t *mp1 = copyb(mp);
21094 		freemsg(mp);
21095 		mp = mp1;
21096 		if (!mp) {
21097 			if (mctl_present)
21098 				freeb(ipsec_mp);
21099 			return;
21100 		} else {
21101 			if (mctl_present) {
21102 				ipsec_mp->b_cont = mp;
21103 			} else {
21104 				ipsec_mp = mp;
21105 			}
21106 		}
21107 	} else if (mp->b_cont) {
21108 		freemsg(mp->b_cont);
21109 		mp->b_cont = NULL;
21110 	}
21111 	/*
21112 	 * We skip reversing source route here.
21113 	 * (for now we replace all IP options with EOL)
21114 	 */
21115 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21116 		ipha = (ipha_t *)mp->b_rptr;
21117 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21118 			mp->b_rptr[i] = IPOPT_EOL;
21119 		/*
21120 		 * Make sure that src address isn't flagrantly invalid.
21121 		 * Not all broadcast address checking for the src address
21122 		 * is possible, since we don't know the netmask of the src
21123 		 * addr.  No check for destination address is done, since
21124 		 * IP will not pass up a packet with a broadcast dest
21125 		 * address to TCP.  Similar checks are done below for IPv6.
21126 		 */
21127 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21128 		    CLASSD(ipha->ipha_src)) {
21129 			freemsg(ipsec_mp);
21130 			BUMP_MIB(&ip_mib, ipInDiscards);
21131 			return;
21132 		}
21133 	} else {
21134 		ip6h = (ip6_t *)mp->b_rptr;
21135 
21136 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21137 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21138 			freemsg(ipsec_mp);
21139 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21140 			return;
21141 		}
21142 
21143 		/* Remove any extension headers assuming partial overlay */
21144 		if (ip_hdr_len > IPV6_HDR_LEN) {
21145 			uint8_t *to;
21146 
21147 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21148 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21149 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21150 			ip_hdr_len = IPV6_HDR_LEN;
21151 			ip6h = (ip6_t *)mp->b_rptr;
21152 			ip6h->ip6_nxt = IPPROTO_TCP;
21153 		}
21154 	}
21155 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21156 	if (tcph->th_flags[0] & TH_RST) {
21157 		freemsg(ipsec_mp);
21158 		return;
21159 	}
21160 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21161 	len = ip_hdr_len + sizeof (tcph_t);
21162 	mp->b_wptr = &mp->b_rptr[len];
21163 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21164 		ipha->ipha_length = htons(len);
21165 		/* Swap addresses */
21166 		v4addr = ipha->ipha_src;
21167 		ipha->ipha_src = ipha->ipha_dst;
21168 		ipha->ipha_dst = v4addr;
21169 		ipha->ipha_ident = 0;
21170 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21171 		addr_len = IP_ADDR_LEN;
21172 		addr = &v4addr;
21173 	} else {
21174 		/* No ip6i_t in this case */
21175 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21176 		/* Swap addresses */
21177 		v6addr = ip6h->ip6_src;
21178 		ip6h->ip6_src = ip6h->ip6_dst;
21179 		ip6h->ip6_dst = v6addr;
21180 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21181 		addr_len = IPV6_ADDR_LEN;
21182 		addr = &v6addr;
21183 	}
21184 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21185 	U32_TO_BE32(ack, tcph->th_ack);
21186 	U32_TO_BE32(seq, tcph->th_seq);
21187 	U16_TO_BE16(0, tcph->th_win);
21188 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21189 	tcph->th_flags[0] = (uint8_t)ctl;
21190 	if (ctl & TH_RST) {
21191 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21192 		BUMP_MIB(&tcp_mib, tcpOutControl);
21193 	}
21194 	if (mctl_present) {
21195 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21196 
21197 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21198 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21199 			return;
21200 		}
21201 	}
21202 	/*
21203 	 * NOTE:  one might consider tracing a TCP packet here, but
21204 	 * this function has no active TCP state nd no tcp structure
21205 	 * which has trace buffer.  If we traced here, we would have
21206 	 * to keep a local trace buffer in tcp_record_trace().
21207 	 */
21208 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21209 
21210 	/*
21211 	 * Tell IP to mark the IRE used for this destination temporary.
21212 	 * This way, we can limit our exposure to DoS attack because IP
21213 	 * creates an IRE for each destination.  If there are too many,
21214 	 * the time to do any routing lookup will be extremely long.  And
21215 	 * the lookup can be in interrupt context.
21216 	 *
21217 	 * Note that in normal circumstances, this marking should not
21218 	 * affect anything.  It would be nice if only 1 message is
21219 	 * needed to inform IP that the IRE created for this RST should
21220 	 * not be added to the cache table.  But there is currently
21221 	 * not such communication mechanism between TCP and IP.  So
21222 	 * the best we can do now is to send the advice ioctl to IP
21223 	 * to mark the IRE temporary.
21224 	 */
21225 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21226 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21227 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21228 	}
21229 }
21230 
21231 /*
21232  * Initiate closedown sequence on an active connection.  (May be called as
21233  * writer.)  Return value zero for OK return, non-zero for error return.
21234  */
21235 static int
21236 tcp_xmit_end(tcp_t *tcp)
21237 {
21238 	ipic_t	*ipic;
21239 	mblk_t	*mp;
21240 
21241 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21242 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21243 		/*
21244 		 * Invalid state, only states TCPS_SYN_RCVD,
21245 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21246 		 */
21247 		return (-1);
21248 	}
21249 
21250 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21251 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21252 	/*
21253 	 * If there is nothing more unsent, send the FIN now.
21254 	 * Otherwise, it will go out with the last segment.
21255 	 */
21256 	if (tcp->tcp_unsent == 0) {
21257 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21258 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21259 
21260 		if (mp) {
21261 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21262 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21263 		} else {
21264 			/*
21265 			 * Couldn't allocate msg.  Pretend we got it out.
21266 			 * Wait for rexmit timeout.
21267 			 */
21268 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21269 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21270 		}
21271 
21272 		/*
21273 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21274 		 * changed.
21275 		 */
21276 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21277 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21278 		}
21279 	} else {
21280 		/*
21281 		 * If tcp->tcp_cork is set, then the data will not get sent,
21282 		 * so we have to check that and unset it first.
21283 		 */
21284 		if (tcp->tcp_cork)
21285 			tcp->tcp_cork = B_FALSE;
21286 		tcp_wput_data(tcp, NULL, B_FALSE);
21287 	}
21288 
21289 	/*
21290 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21291 	 * is 0, don't update the cache.
21292 	 */
21293 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21294 		return (0);
21295 
21296 	/*
21297 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21298 	 * different from the destination.
21299 	 */
21300 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21301 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21302 			return (0);
21303 		}
21304 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21305 		    &ipic);
21306 	} else {
21307 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21308 		    &tcp->tcp_ip6h->ip6_dst))) {
21309 			return (0);
21310 		}
21311 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21312 		    &ipic);
21313 	}
21314 
21315 	/* Record route attributes in the IRE for use by future connections. */
21316 	if (mp == NULL)
21317 		return (0);
21318 
21319 	/*
21320 	 * We do not have a good algorithm to update ssthresh at this time.
21321 	 * So don't do any update.
21322 	 */
21323 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21324 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21325 
21326 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21327 	return (0);
21328 }
21329 
21330 /*
21331  * Generate a "no listener here" RST in response to an "unknown" segment.
21332  * Note that we are reusing the incoming mp to construct the outgoing
21333  * RST.
21334  */
21335 void
21336 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21337 {
21338 	uchar_t		*rptr;
21339 	uint32_t	seg_len;
21340 	tcph_t		*tcph;
21341 	uint32_t	seg_seq;
21342 	uint32_t	seg_ack;
21343 	uint_t		flags;
21344 	mblk_t		*ipsec_mp;
21345 	ipha_t 		*ipha;
21346 	ip6_t 		*ip6h;
21347 	boolean_t	mctl_present = B_FALSE;
21348 	boolean_t	check = B_TRUE;
21349 	boolean_t	policy_present;
21350 
21351 	TCP_STAT(tcp_no_listener);
21352 
21353 	ipsec_mp = mp;
21354 
21355 	if (mp->b_datap->db_type == M_CTL) {
21356 		ipsec_in_t *ii;
21357 
21358 		mctl_present = B_TRUE;
21359 		mp = mp->b_cont;
21360 
21361 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21362 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21363 		if (ii->ipsec_in_dont_check) {
21364 			check = B_FALSE;
21365 			if (!ii->ipsec_in_secure) {
21366 				freeb(ipsec_mp);
21367 				mctl_present = B_FALSE;
21368 				ipsec_mp = mp;
21369 			}
21370 		}
21371 	}
21372 
21373 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21374 		policy_present = ipsec_inbound_v4_policy_present;
21375 		ipha = (ipha_t *)mp->b_rptr;
21376 		ip6h = NULL;
21377 	} else {
21378 		policy_present = ipsec_inbound_v6_policy_present;
21379 		ipha = NULL;
21380 		ip6h = (ip6_t *)mp->b_rptr;
21381 	}
21382 
21383 	if (check && policy_present) {
21384 		/*
21385 		 * The conn_t parameter is NULL because we already know
21386 		 * nobody's home.
21387 		 */
21388 		ipsec_mp = ipsec_check_global_policy(
21389 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21390 		if (ipsec_mp == NULL)
21391 			return;
21392 	}
21393 
21394 
21395 	rptr = mp->b_rptr;
21396 
21397 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21398 	seg_seq = BE32_TO_U32(tcph->th_seq);
21399 	seg_ack = BE32_TO_U32(tcph->th_ack);
21400 	flags = tcph->th_flags[0];
21401 
21402 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21403 	if (flags & TH_RST) {
21404 		freemsg(ipsec_mp);
21405 	} else if (flags & TH_ACK) {
21406 		tcp_xmit_early_reset("no tcp, reset",
21407 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21408 	} else {
21409 		if (flags & TH_SYN) {
21410 			seg_len++;
21411 		} else {
21412 			/*
21413 			 * Here we violate the RFC.  Note that a normal
21414 			 * TCP will never send a segment without the ACK
21415 			 * flag, except for RST or SYN segment.  This
21416 			 * segment is neither.  Just drop it on the
21417 			 * floor.
21418 			 */
21419 			freemsg(ipsec_mp);
21420 			tcp_rst_unsent++;
21421 			return;
21422 		}
21423 
21424 		tcp_xmit_early_reset("no tcp, reset/ack",
21425 		    ipsec_mp, 0, seg_seq + seg_len,
21426 		    TH_RST | TH_ACK, ip_hdr_len);
21427 	}
21428 }
21429 
21430 /*
21431  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21432  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21433  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21434  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21435  * otherwise it will dup partial mblks.)
21436  * Otherwise, an appropriate ACK packet will be generated.  This
21437  * routine is not usually called to send new data for the first time.  It
21438  * is mostly called out of the timer for retransmits, and to generate ACKs.
21439  *
21440  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21441  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21442  * of the original mblk chain will be returned in *offset and *end_mp.
21443  */
21444 static mblk_t *
21445 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21446     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21447     boolean_t rexmit)
21448 {
21449 	int	data_length;
21450 	int32_t	off = 0;
21451 	uint_t	flags;
21452 	mblk_t	*mp1;
21453 	mblk_t	*mp2;
21454 	uchar_t	*rptr;
21455 	tcph_t	*tcph;
21456 	int32_t	num_sack_blk = 0;
21457 	int32_t	sack_opt_len = 0;
21458 
21459 	/* Allocate for our maximum TCP header + link-level */
21460 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21461 	    BPRI_MED);
21462 	if (!mp1)
21463 		return (NULL);
21464 	data_length = 0;
21465 
21466 	/*
21467 	 * Note that tcp_mss has been adjusted to take into account the
21468 	 * timestamp option if applicable.  Because SACK options do not
21469 	 * appear in every TCP segments and they are of variable lengths,
21470 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21471 	 * the actual segment length when we need to send a segment which
21472 	 * includes SACK options.
21473 	 */
21474 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21475 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21476 		    tcp->tcp_num_sack_blk);
21477 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21478 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21479 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21480 			max_to_send -= sack_opt_len;
21481 	}
21482 
21483 	if (offset != NULL) {
21484 		off = *offset;
21485 		/* We use offset as an indicator that end_mp is not NULL. */
21486 		*end_mp = NULL;
21487 	}
21488 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21489 		/* This could be faster with cooperation from downstream */
21490 		if (mp2 != mp1 && !sendall &&
21491 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21492 		    max_to_send)
21493 			/*
21494 			 * Don't send the next mblk since the whole mblk
21495 			 * does not fit.
21496 			 */
21497 			break;
21498 		mp2->b_cont = dupb(mp);
21499 		mp2 = mp2->b_cont;
21500 		if (!mp2) {
21501 			freemsg(mp1);
21502 			return (NULL);
21503 		}
21504 		mp2->b_rptr += off;
21505 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21506 		    (uintptr_t)INT_MAX);
21507 
21508 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21509 		if (data_length > max_to_send) {
21510 			mp2->b_wptr -= data_length - max_to_send;
21511 			data_length = max_to_send;
21512 			off = mp2->b_wptr - mp->b_rptr;
21513 			break;
21514 		} else {
21515 			off = 0;
21516 		}
21517 	}
21518 	if (offset != NULL) {
21519 		*offset = off;
21520 		*end_mp = mp;
21521 	}
21522 	if (seg_len != NULL) {
21523 		*seg_len = data_length;
21524 	}
21525 
21526 	/* Update the latest receive window size in TCP header. */
21527 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21528 	    tcp->tcp_tcph->th_win);
21529 
21530 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21531 	mp1->b_rptr = rptr;
21532 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21533 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21534 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21535 	U32_TO_ABE32(seq, tcph->th_seq);
21536 
21537 	/*
21538 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21539 	 * that this function was called from tcp_wput_data. Thus, when called
21540 	 * to retransmit data the setting of the PUSH bit may appear some
21541 	 * what random in that it might get set when it should not. This
21542 	 * should not pose any performance issues.
21543 	 */
21544 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21545 	    tcp->tcp_unsent == data_length)) {
21546 		flags = TH_ACK | TH_PUSH;
21547 	} else {
21548 		flags = TH_ACK;
21549 	}
21550 
21551 	if (tcp->tcp_ecn_ok) {
21552 		if (tcp->tcp_ecn_echo_on)
21553 			flags |= TH_ECE;
21554 
21555 		/*
21556 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21557 		 * There is no TCP flow control for non-data segments, and
21558 		 * only data segment is transmitted reliably.
21559 		 */
21560 		if (data_length > 0 && !rexmit) {
21561 			SET_ECT(tcp, rptr);
21562 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21563 				flags |= TH_CWR;
21564 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21565 			}
21566 		}
21567 	}
21568 
21569 	if (tcp->tcp_valid_bits) {
21570 		uint32_t u1;
21571 
21572 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21573 		    seq == tcp->tcp_iss) {
21574 			uchar_t	*wptr;
21575 
21576 			/*
21577 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21578 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21579 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21580 			 * our SYN is not ack'ed but the app closes this
21581 			 * TCP connection.
21582 			 */
21583 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21584 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21585 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21586 
21587 			/*
21588 			 * Tack on the MSS option.  It is always needed
21589 			 * for both active and passive open.
21590 			 *
21591 			 * MSS option value should be interface MTU - MIN
21592 			 * TCP/IP header according to RFC 793 as it means
21593 			 * the maximum segment size TCP can receive.  But
21594 			 * to get around some broken middle boxes/end hosts
21595 			 * out there, we allow the option value to be the
21596 			 * same as the MSS option size on the peer side.
21597 			 * In this way, the other side will not send
21598 			 * anything larger than they can receive.
21599 			 *
21600 			 * Note that for SYN_SENT state, the ndd param
21601 			 * tcp_use_smss_as_mss_opt has no effect as we
21602 			 * don't know the peer's MSS option value. So
21603 			 * the only case we need to take care of is in
21604 			 * SYN_RCVD state, which is done later.
21605 			 */
21606 			wptr = mp1->b_wptr;
21607 			wptr[0] = TCPOPT_MAXSEG;
21608 			wptr[1] = TCPOPT_MAXSEG_LEN;
21609 			wptr += 2;
21610 			u1 = tcp->tcp_if_mtu -
21611 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21612 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21613 			    TCP_MIN_HEADER_LENGTH;
21614 			U16_TO_BE16(u1, wptr);
21615 			mp1->b_wptr = wptr + 2;
21616 			/* Update the offset to cover the additional word */
21617 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21618 
21619 			/*
21620 			 * Note that the following way of filling in
21621 			 * TCP options are not optimal.  Some NOPs can
21622 			 * be saved.  But there is no need at this time
21623 			 * to optimize it.  When it is needed, we will
21624 			 * do it.
21625 			 */
21626 			switch (tcp->tcp_state) {
21627 			case TCPS_SYN_SENT:
21628 				flags = TH_SYN;
21629 
21630 				if (tcp->tcp_snd_ts_ok) {
21631 					uint32_t llbolt = (uint32_t)lbolt;
21632 
21633 					wptr = mp1->b_wptr;
21634 					wptr[0] = TCPOPT_NOP;
21635 					wptr[1] = TCPOPT_NOP;
21636 					wptr[2] = TCPOPT_TSTAMP;
21637 					wptr[3] = TCPOPT_TSTAMP_LEN;
21638 					wptr += 4;
21639 					U32_TO_BE32(llbolt, wptr);
21640 					wptr += 4;
21641 					ASSERT(tcp->tcp_ts_recent == 0);
21642 					U32_TO_BE32(0L, wptr);
21643 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
21644 					tcph->th_offset_and_rsrvd[0] +=
21645 					    (3 << 4);
21646 				}
21647 
21648 				/*
21649 				 * Set up all the bits to tell other side
21650 				 * we are ECN capable.
21651 				 */
21652 				if (tcp->tcp_ecn_ok) {
21653 					flags |= (TH_ECE | TH_CWR);
21654 				}
21655 				break;
21656 			case TCPS_SYN_RCVD:
21657 				flags |= TH_SYN;
21658 
21659 				/*
21660 				 * Reset the MSS option value to be SMSS
21661 				 * We should probably add back the bytes
21662 				 * for timestamp option and IPsec.  We
21663 				 * don't do that as this is a workaround
21664 				 * for broken middle boxes/end hosts, it
21665 				 * is better for us to be more cautious.
21666 				 * They may not take these things into
21667 				 * account in their SMSS calculation.  Thus
21668 				 * the peer's calculated SMSS may be smaller
21669 				 * than what it can be.  This should be OK.
21670 				 */
21671 				if (tcp_use_smss_as_mss_opt) {
21672 					u1 = tcp->tcp_mss;
21673 					U16_TO_BE16(u1, wptr);
21674 				}
21675 
21676 				/*
21677 				 * If the other side is ECN capable, reply
21678 				 * that we are also ECN capable.
21679 				 */
21680 				if (tcp->tcp_ecn_ok)
21681 					flags |= TH_ECE;
21682 				break;
21683 			default:
21684 				/*
21685 				 * The above ASSERT() makes sure that this
21686 				 * must be FIN-WAIT-1 state.  Our SYN has
21687 				 * not been ack'ed so retransmit it.
21688 				 */
21689 				flags |= TH_SYN;
21690 				break;
21691 			}
21692 
21693 			if (tcp->tcp_snd_ws_ok) {
21694 				wptr = mp1->b_wptr;
21695 				wptr[0] =  TCPOPT_NOP;
21696 				wptr[1] =  TCPOPT_WSCALE;
21697 				wptr[2] =  TCPOPT_WS_LEN;
21698 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
21699 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
21700 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21701 			}
21702 
21703 			if (tcp->tcp_snd_sack_ok) {
21704 				wptr = mp1->b_wptr;
21705 				wptr[0] = TCPOPT_NOP;
21706 				wptr[1] = TCPOPT_NOP;
21707 				wptr[2] = TCPOPT_SACK_PERMITTED;
21708 				wptr[3] = TCPOPT_SACK_OK_LEN;
21709 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
21710 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21711 			}
21712 
21713 			/* allocb() of adequate mblk assures space */
21714 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
21715 			    (uintptr_t)INT_MAX);
21716 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
21717 			/*
21718 			 * Get IP set to checksum on our behalf
21719 			 * Include the adjustment for a source route if any.
21720 			 */
21721 			u1 += tcp->tcp_sum;
21722 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
21723 			U16_TO_BE16(u1, tcph->th_sum);
21724 			BUMP_MIB(&tcp_mib, tcpOutControl);
21725 		}
21726 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
21727 		    (seq + data_length) == tcp->tcp_fss) {
21728 			if (!tcp->tcp_fin_acked) {
21729 				flags |= TH_FIN;
21730 				BUMP_MIB(&tcp_mib, tcpOutControl);
21731 			}
21732 			if (!tcp->tcp_fin_sent) {
21733 				tcp->tcp_fin_sent = B_TRUE;
21734 				switch (tcp->tcp_state) {
21735 				case TCPS_SYN_RCVD:
21736 				case TCPS_ESTABLISHED:
21737 					tcp->tcp_state = TCPS_FIN_WAIT_1;
21738 					break;
21739 				case TCPS_CLOSE_WAIT:
21740 					tcp->tcp_state = TCPS_LAST_ACK;
21741 					break;
21742 				}
21743 				if (tcp->tcp_suna == tcp->tcp_snxt)
21744 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21745 				tcp->tcp_snxt = tcp->tcp_fss + 1;
21746 			}
21747 		}
21748 		/*
21749 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
21750 		 * is smaller than seq, u1 will become a very huge value.
21751 		 * So the comparison will fail.  Also note that tcp_urp
21752 		 * should be positive, see RFC 793 page 17.
21753 		 */
21754 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
21755 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
21756 		    u1 < (uint32_t)(64 * 1024)) {
21757 			flags |= TH_URG;
21758 			BUMP_MIB(&tcp_mib, tcpOutUrg);
21759 			U32_TO_ABE16(u1, tcph->th_urp);
21760 		}
21761 	}
21762 	tcph->th_flags[0] = (uchar_t)flags;
21763 	tcp->tcp_rack = tcp->tcp_rnxt;
21764 	tcp->tcp_rack_cnt = 0;
21765 
21766 	if (tcp->tcp_snd_ts_ok) {
21767 		if (tcp->tcp_state != TCPS_SYN_SENT) {
21768 			uint32_t llbolt = (uint32_t)lbolt;
21769 
21770 			U32_TO_BE32(llbolt,
21771 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21772 			U32_TO_BE32(tcp->tcp_ts_recent,
21773 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21774 		}
21775 	}
21776 
21777 	if (num_sack_blk > 0) {
21778 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21779 		sack_blk_t *tmp;
21780 		int32_t	i;
21781 
21782 		wptr[0] = TCPOPT_NOP;
21783 		wptr[1] = TCPOPT_NOP;
21784 		wptr[2] = TCPOPT_SACK;
21785 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21786 		    sizeof (sack_blk_t);
21787 		wptr += TCPOPT_REAL_SACK_LEN;
21788 
21789 		tmp = tcp->tcp_sack_list;
21790 		for (i = 0; i < num_sack_blk; i++) {
21791 			U32_TO_BE32(tmp[i].begin, wptr);
21792 			wptr += sizeof (tcp_seq);
21793 			U32_TO_BE32(tmp[i].end, wptr);
21794 			wptr += sizeof (tcp_seq);
21795 		}
21796 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
21797 	}
21798 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21799 	data_length += (int)(mp1->b_wptr - rptr);
21800 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21801 		((ipha_t *)rptr)->ipha_length = htons(data_length);
21802 	} else {
21803 		ip6_t *ip6 = (ip6_t *)(rptr +
21804 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21805 		    sizeof (ip6i_t) : 0));
21806 
21807 		ip6->ip6_plen = htons(data_length -
21808 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21809 	}
21810 
21811 	/*
21812 	 * Prime pump for IP
21813 	 * Include the adjustment for a source route if any.
21814 	 */
21815 	data_length -= tcp->tcp_ip_hdr_len;
21816 	data_length += tcp->tcp_sum;
21817 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
21818 	U16_TO_ABE16(data_length, tcph->th_sum);
21819 	if (tcp->tcp_ip_forward_progress) {
21820 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21821 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21822 		tcp->tcp_ip_forward_progress = B_FALSE;
21823 	}
21824 	return (mp1);
21825 }
21826 
21827 /* This function handles the push timeout. */
21828 void
21829 tcp_push_timer(void *arg)
21830 {
21831 	conn_t	*connp = (conn_t *)arg;
21832 	tcp_t *tcp = connp->conn_tcp;
21833 
21834 	TCP_DBGSTAT(tcp_push_timer_cnt);
21835 
21836 	ASSERT(tcp->tcp_listener == NULL);
21837 
21838 	/*
21839 	 * We need to stop synchronous streams temporarily to prevent a race
21840 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
21841 	 * tcp_rcv_list here because those entry points will return right
21842 	 * away when synchronous streams is stopped.
21843 	 */
21844 	TCP_FUSE_SYNCSTR_STOP(tcp);
21845 	tcp->tcp_push_tid = 0;
21846 	if ((tcp->tcp_rcv_list != NULL) &&
21847 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
21848 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21849 	TCP_FUSE_SYNCSTR_RESUME(tcp);
21850 }
21851 
21852 /*
21853  * This function handles delayed ACK timeout.
21854  */
21855 static void
21856 tcp_ack_timer(void *arg)
21857 {
21858 	conn_t	*connp = (conn_t *)arg;
21859 	tcp_t *tcp = connp->conn_tcp;
21860 	mblk_t *mp;
21861 
21862 	TCP_DBGSTAT(tcp_ack_timer_cnt);
21863 
21864 	tcp->tcp_ack_tid = 0;
21865 
21866 	if (tcp->tcp_fused)
21867 		return;
21868 
21869 	/*
21870 	 * Do not send ACK if there is no outstanding unack'ed data.
21871 	 */
21872 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
21873 		return;
21874 	}
21875 
21876 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
21877 		/*
21878 		 * Make sure we don't allow deferred ACKs to result in
21879 		 * timer-based ACKing.  If we have held off an ACK
21880 		 * when there was more than an mss here, and the timer
21881 		 * goes off, we have to worry about the possibility
21882 		 * that the sender isn't doing slow-start, or is out
21883 		 * of step with us for some other reason.  We fall
21884 		 * permanently back in the direction of
21885 		 * ACK-every-other-packet as suggested in RFC 1122.
21886 		 */
21887 		if (tcp->tcp_rack_abs_max > 2)
21888 			tcp->tcp_rack_abs_max--;
21889 		tcp->tcp_rack_cur_max = 2;
21890 	}
21891 	mp = tcp_ack_mp(tcp);
21892 
21893 	if (mp != NULL) {
21894 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21895 		BUMP_LOCAL(tcp->tcp_obsegs);
21896 		BUMP_MIB(&tcp_mib, tcpOutAck);
21897 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
21898 		tcp_send_data(tcp, tcp->tcp_wq, mp);
21899 	}
21900 }
21901 
21902 
21903 /* Generate an ACK-only (no data) segment for a TCP endpoint */
21904 static mblk_t *
21905 tcp_ack_mp(tcp_t *tcp)
21906 {
21907 	uint32_t	seq_no;
21908 
21909 	/*
21910 	 * There are a few cases to be considered while setting the sequence no.
21911 	 * Essentially, we can come here while processing an unacceptable pkt
21912 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
21913 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
21914 	 * If we are here for a zero window probe, stick with suna. In all
21915 	 * other cases, we check if suna + swnd encompasses snxt and set
21916 	 * the sequence number to snxt, if so. If snxt falls outside the
21917 	 * window (the receiver probably shrunk its window), we will go with
21918 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
21919 	 * receiver.
21920 	 */
21921 	if (tcp->tcp_zero_win_probe) {
21922 		seq_no = tcp->tcp_suna;
21923 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
21924 		ASSERT(tcp->tcp_swnd == 0);
21925 		seq_no = tcp->tcp_snxt;
21926 	} else {
21927 		seq_no = SEQ_GT(tcp->tcp_snxt,
21928 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
21929 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
21930 	}
21931 
21932 	if (tcp->tcp_valid_bits) {
21933 		/*
21934 		 * For the complex case where we have to send some
21935 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
21936 		 */
21937 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
21938 		    NULL, B_FALSE));
21939 	} else {
21940 		/* Generate a simple ACK */
21941 		int	data_length;
21942 		uchar_t	*rptr;
21943 		tcph_t	*tcph;
21944 		mblk_t	*mp1;
21945 		int32_t	tcp_hdr_len;
21946 		int32_t	tcp_tcp_hdr_len;
21947 		int32_t	num_sack_blk = 0;
21948 		int32_t sack_opt_len;
21949 
21950 		/*
21951 		 * Allocate space for TCP + IP headers
21952 		 * and link-level header
21953 		 */
21954 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21955 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21956 			    tcp->tcp_num_sack_blk);
21957 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21958 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21959 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
21960 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
21961 		} else {
21962 			tcp_hdr_len = tcp->tcp_hdr_len;
21963 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
21964 		}
21965 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
21966 		if (!mp1)
21967 			return (NULL);
21968 
21969 		/* Update the latest receive window size in TCP header. */
21970 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21971 		    tcp->tcp_tcph->th_win);
21972 		/* copy in prototype TCP + IP header */
21973 		rptr = mp1->b_rptr + tcp_wroff_xtra;
21974 		mp1->b_rptr = rptr;
21975 		mp1->b_wptr = rptr + tcp_hdr_len;
21976 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21977 
21978 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21979 
21980 		/* Set the TCP sequence number. */
21981 		U32_TO_ABE32(seq_no, tcph->th_seq);
21982 
21983 		/* Set up the TCP flag field. */
21984 		tcph->th_flags[0] = (uchar_t)TH_ACK;
21985 		if (tcp->tcp_ecn_echo_on)
21986 			tcph->th_flags[0] |= TH_ECE;
21987 
21988 		tcp->tcp_rack = tcp->tcp_rnxt;
21989 		tcp->tcp_rack_cnt = 0;
21990 
21991 		/* fill in timestamp option if in use */
21992 		if (tcp->tcp_snd_ts_ok) {
21993 			uint32_t llbolt = (uint32_t)lbolt;
21994 
21995 			U32_TO_BE32(llbolt,
21996 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21997 			U32_TO_BE32(tcp->tcp_ts_recent,
21998 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21999 		}
22000 
22001 		/* Fill in SACK options */
22002 		if (num_sack_blk > 0) {
22003 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22004 			sack_blk_t *tmp;
22005 			int32_t	i;
22006 
22007 			wptr[0] = TCPOPT_NOP;
22008 			wptr[1] = TCPOPT_NOP;
22009 			wptr[2] = TCPOPT_SACK;
22010 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22011 			    sizeof (sack_blk_t);
22012 			wptr += TCPOPT_REAL_SACK_LEN;
22013 
22014 			tmp = tcp->tcp_sack_list;
22015 			for (i = 0; i < num_sack_blk; i++) {
22016 				U32_TO_BE32(tmp[i].begin, wptr);
22017 				wptr += sizeof (tcp_seq);
22018 				U32_TO_BE32(tmp[i].end, wptr);
22019 				wptr += sizeof (tcp_seq);
22020 			}
22021 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22022 			    << 4);
22023 		}
22024 
22025 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22026 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22027 		} else {
22028 			/* Check for ip6i_t header in sticky hdrs */
22029 			ip6_t *ip6 = (ip6_t *)(rptr +
22030 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22031 			    sizeof (ip6i_t) : 0));
22032 
22033 			ip6->ip6_plen = htons(tcp_hdr_len -
22034 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22035 		}
22036 
22037 		/*
22038 		 * Prime pump for checksum calculation in IP.  Include the
22039 		 * adjustment for a source route if any.
22040 		 */
22041 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22042 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22043 		U16_TO_ABE16(data_length, tcph->th_sum);
22044 
22045 		if (tcp->tcp_ip_forward_progress) {
22046 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22047 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22048 			tcp->tcp_ip_forward_progress = B_FALSE;
22049 		}
22050 		return (mp1);
22051 	}
22052 }
22053 
22054 /*
22055  * To create a temporary tcp structure for inserting into bind hash list.
22056  * The parameter is assumed to be in network byte order, ready for use.
22057  */
22058 /* ARGSUSED */
22059 static tcp_t *
22060 tcp_alloc_temp_tcp(in_port_t port)
22061 {
22062 	conn_t	*connp;
22063 	tcp_t	*tcp;
22064 
22065 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22066 	if (connp == NULL)
22067 		return (NULL);
22068 
22069 	tcp = connp->conn_tcp;
22070 
22071 	/*
22072 	 * Only initialize the necessary info in those structures.  Note
22073 	 * that since INADDR_ANY is all 0, we do not need to set
22074 	 * tcp_bound_source to INADDR_ANY here.
22075 	 */
22076 	tcp->tcp_state = TCPS_BOUND;
22077 	tcp->tcp_lport = port;
22078 	tcp->tcp_exclbind = 1;
22079 	tcp->tcp_reserved_port = 1;
22080 
22081 	/* Just for place holding... */
22082 	tcp->tcp_ipversion = IPV4_VERSION;
22083 
22084 	return (tcp);
22085 }
22086 
22087 /*
22088  * To remove a port range specified by lo_port and hi_port from the
22089  * reserved port ranges.  This is one of the three public functions of
22090  * the reserved port interface.  Note that a port range has to be removed
22091  * as a whole.  Ports in a range cannot be removed individually.
22092  *
22093  * Params:
22094  *	in_port_t lo_port: the beginning port of the reserved port range to
22095  *		be deleted.
22096  *	in_port_t hi_port: the ending port of the reserved port range to
22097  *		be deleted.
22098  *
22099  * Return:
22100  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22101  */
22102 boolean_t
22103 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22104 {
22105 	int	i, j;
22106 	int	size;
22107 	tcp_t	**temp_tcp_array;
22108 	tcp_t	*tcp;
22109 
22110 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22111 
22112 	/* First make sure that the port ranage is indeed reserved. */
22113 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22114 		if (tcp_reserved_port[i].lo_port == lo_port) {
22115 			hi_port = tcp_reserved_port[i].hi_port;
22116 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22117 			break;
22118 		}
22119 	}
22120 	if (i == tcp_reserved_port_array_size) {
22121 		rw_exit(&tcp_reserved_port_lock);
22122 		return (B_FALSE);
22123 	}
22124 
22125 	/*
22126 	 * Remove the range from the array.  This simple loop is possible
22127 	 * because port ranges are inserted in ascending order.
22128 	 */
22129 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22130 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22131 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22132 		tcp_reserved_port[j].temp_tcp_array =
22133 		    tcp_reserved_port[j+1].temp_tcp_array;
22134 	}
22135 
22136 	/* Remove all the temporary tcp structures. */
22137 	size = hi_port - lo_port + 1;
22138 	while (size > 0) {
22139 		tcp = temp_tcp_array[size - 1];
22140 		ASSERT(tcp != NULL);
22141 		tcp_bind_hash_remove(tcp);
22142 		CONN_DEC_REF(tcp->tcp_connp);
22143 		size--;
22144 	}
22145 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22146 	tcp_reserved_port_array_size--;
22147 	rw_exit(&tcp_reserved_port_lock);
22148 	return (B_TRUE);
22149 }
22150 
22151 /*
22152  * Macro to remove temporary tcp structure from the bind hash list.  The
22153  * first parameter is the list of tcp to be removed.  The second parameter
22154  * is the number of tcps in the array.
22155  */
22156 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22157 { \
22158 	while ((num) > 0) { \
22159 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22160 		tf_t *tbf; \
22161 		tcp_t *tcpnext; \
22162 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22163 		mutex_enter(&tbf->tf_lock); \
22164 		tcpnext = tcp->tcp_bind_hash; \
22165 		if (tcpnext) { \
22166 			tcpnext->tcp_ptpbhn = \
22167 				tcp->tcp_ptpbhn; \
22168 		} \
22169 		*tcp->tcp_ptpbhn = tcpnext; \
22170 		mutex_exit(&tbf->tf_lock); \
22171 		kmem_free(tcp, sizeof (tcp_t)); \
22172 		(tcp_array)[(num) - 1] = NULL; \
22173 		(num)--; \
22174 	} \
22175 }
22176 
22177 /*
22178  * The public interface for other modules to call to reserve a port range
22179  * in TCP.  The caller passes in how large a port range it wants.  TCP
22180  * will try to find a range and return it via lo_port and hi_port.  This is
22181  * used by NCA's nca_conn_init.
22182  * NCA can only be used in the global zone so this only affects the global
22183  * zone's ports.
22184  *
22185  * Params:
22186  *	int size: the size of the port range to be reserved.
22187  *	in_port_t *lo_port (referenced): returns the beginning port of the
22188  *		reserved port range added.
22189  *	in_port_t *hi_port (referenced): returns the ending port of the
22190  *		reserved port range added.
22191  *
22192  * Return:
22193  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22194  */
22195 boolean_t
22196 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22197 {
22198 	tcp_t		*tcp;
22199 	tcp_t		*tmp_tcp;
22200 	tcp_t		**temp_tcp_array;
22201 	tf_t		*tbf;
22202 	in_port_t	net_port;
22203 	in_port_t	port;
22204 	int32_t		cur_size;
22205 	int		i, j;
22206 	boolean_t	used;
22207 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22208 	zoneid_t	zoneid = GLOBAL_ZONEID;
22209 
22210 	/* Sanity check. */
22211 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22212 		return (B_FALSE);
22213 	}
22214 
22215 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22216 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22217 		rw_exit(&tcp_reserved_port_lock);
22218 		return (B_FALSE);
22219 	}
22220 
22221 	/*
22222 	 * Find the starting port to try.  Since the port ranges are ordered
22223 	 * in the reserved port array, we can do a simple search here.
22224 	 */
22225 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22226 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22227 	for (i = 0; i < tcp_reserved_port_array_size;
22228 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22229 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22230 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22231 			break;
22232 		}
22233 	}
22234 	/* No available port range. */
22235 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22236 		rw_exit(&tcp_reserved_port_lock);
22237 		return (B_FALSE);
22238 	}
22239 
22240 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22241 	if (temp_tcp_array == NULL) {
22242 		rw_exit(&tcp_reserved_port_lock);
22243 		return (B_FALSE);
22244 	}
22245 
22246 	/* Go thru the port range to see if some ports are already bound. */
22247 	for (port = *lo_port, cur_size = 0;
22248 	    cur_size < size && port <= *hi_port;
22249 	    cur_size++, port++) {
22250 		used = B_FALSE;
22251 		net_port = htons(port);
22252 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22253 		mutex_enter(&tbf->tf_lock);
22254 		for (tcp = tbf->tf_tcp; tcp != NULL;
22255 		    tcp = tcp->tcp_bind_hash) {
22256 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22257 			    net_port == tcp->tcp_lport) {
22258 				/*
22259 				 * A port is already bound.  Search again
22260 				 * starting from port + 1.  Release all
22261 				 * temporary tcps.
22262 				 */
22263 				mutex_exit(&tbf->tf_lock);
22264 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22265 				*lo_port = port + 1;
22266 				cur_size = -1;
22267 				used = B_TRUE;
22268 				break;
22269 			}
22270 		}
22271 		if (!used) {
22272 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22273 				/*
22274 				 * Allocation failure.  Just fail the request.
22275 				 * Need to remove all those temporary tcp
22276 				 * structures.
22277 				 */
22278 				mutex_exit(&tbf->tf_lock);
22279 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22280 				rw_exit(&tcp_reserved_port_lock);
22281 				kmem_free(temp_tcp_array,
22282 				    (hi_port - lo_port + 1) *
22283 				    sizeof (tcp_t *));
22284 				return (B_FALSE);
22285 			}
22286 			temp_tcp_array[cur_size] = tmp_tcp;
22287 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22288 			mutex_exit(&tbf->tf_lock);
22289 		}
22290 	}
22291 
22292 	/*
22293 	 * The current range is not large enough.  We can actually do another
22294 	 * search if this search is done between 2 reserved port ranges.  But
22295 	 * for first release, we just stop here and return saying that no port
22296 	 * range is available.
22297 	 */
22298 	if (cur_size < size) {
22299 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22300 		rw_exit(&tcp_reserved_port_lock);
22301 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22302 		return (B_FALSE);
22303 	}
22304 	*hi_port = port - 1;
22305 
22306 	/*
22307 	 * Insert range into array in ascending order.  Since this function
22308 	 * must not be called often, we choose to use the simplest method.
22309 	 * The above array should not consume excessive stack space as
22310 	 * the size must be very small.  If in future releases, we find
22311 	 * that we should provide more reserved port ranges, this function
22312 	 * has to be modified to be more efficient.
22313 	 */
22314 	if (tcp_reserved_port_array_size == 0) {
22315 		tcp_reserved_port[0].lo_port = *lo_port;
22316 		tcp_reserved_port[0].hi_port = *hi_port;
22317 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22318 	} else {
22319 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22320 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22321 				tmp_ports[j].lo_port = *lo_port;
22322 				tmp_ports[j].hi_port = *hi_port;
22323 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22324 				j++;
22325 			}
22326 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22327 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22328 			tmp_ports[j].temp_tcp_array =
22329 			    tcp_reserved_port[i].temp_tcp_array;
22330 		}
22331 		if (j == i) {
22332 			tmp_ports[j].lo_port = *lo_port;
22333 			tmp_ports[j].hi_port = *hi_port;
22334 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22335 		}
22336 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22337 	}
22338 	tcp_reserved_port_array_size++;
22339 	rw_exit(&tcp_reserved_port_lock);
22340 	return (B_TRUE);
22341 }
22342 
22343 /*
22344  * Check to see if a port is in any reserved port range.
22345  *
22346  * Params:
22347  *	in_port_t port: the port to be verified.
22348  *
22349  * Return:
22350  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22351  */
22352 boolean_t
22353 tcp_reserved_port_check(in_port_t port)
22354 {
22355 	int i;
22356 
22357 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22358 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22359 		if (port >= tcp_reserved_port[i].lo_port ||
22360 		    port <= tcp_reserved_port[i].hi_port) {
22361 			rw_exit(&tcp_reserved_port_lock);
22362 			return (B_TRUE);
22363 		}
22364 	}
22365 	rw_exit(&tcp_reserved_port_lock);
22366 	return (B_FALSE);
22367 }
22368 
22369 /*
22370  * To list all reserved port ranges.  This is the function to handle
22371  * ndd tcp_reserved_port_list.
22372  */
22373 /* ARGSUSED */
22374 static int
22375 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22376 {
22377 	int i;
22378 
22379 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22380 	if (tcp_reserved_port_array_size > 0)
22381 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22382 	else
22383 		(void) mi_mpprintf(mp, "No port is reserved.");
22384 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22385 		(void) mi_mpprintf(mp, "%d-%d",
22386 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22387 	}
22388 	rw_exit(&tcp_reserved_port_lock);
22389 	return (0);
22390 }
22391 
22392 /*
22393  * Hash list insertion routine for tcp_t structures.
22394  * Inserts entries with the ones bound to a specific IP address first
22395  * followed by those bound to INADDR_ANY.
22396  */
22397 static void
22398 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22399 {
22400 	tcp_t	**tcpp;
22401 	tcp_t	*tcpnext;
22402 
22403 	if (tcp->tcp_ptpbhn != NULL) {
22404 		ASSERT(!caller_holds_lock);
22405 		tcp_bind_hash_remove(tcp);
22406 	}
22407 	tcpp = &tbf->tf_tcp;
22408 	if (!caller_holds_lock) {
22409 		mutex_enter(&tbf->tf_lock);
22410 	} else {
22411 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22412 	}
22413 	tcpnext = tcpp[0];
22414 	if (tcpnext) {
22415 		/*
22416 		 * If the new tcp bound to the INADDR_ANY address
22417 		 * and the first one in the list is not bound to
22418 		 * INADDR_ANY we skip all entries until we find the
22419 		 * first one bound to INADDR_ANY.
22420 		 * This makes sure that applications binding to a
22421 		 * specific address get preference over those binding to
22422 		 * INADDR_ANY.
22423 		 */
22424 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22425 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22426 			while ((tcpnext = tcpp[0]) != NULL &&
22427 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22428 				tcpp = &(tcpnext->tcp_bind_hash);
22429 			if (tcpnext)
22430 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22431 		} else
22432 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22433 	}
22434 	tcp->tcp_bind_hash = tcpnext;
22435 	tcp->tcp_ptpbhn = tcpp;
22436 	tcpp[0] = tcp;
22437 	if (!caller_holds_lock)
22438 		mutex_exit(&tbf->tf_lock);
22439 }
22440 
22441 /*
22442  * Hash list removal routine for tcp_t structures.
22443  */
22444 static void
22445 tcp_bind_hash_remove(tcp_t *tcp)
22446 {
22447 	tcp_t	*tcpnext;
22448 	kmutex_t *lockp;
22449 
22450 	if (tcp->tcp_ptpbhn == NULL)
22451 		return;
22452 
22453 	/*
22454 	 * Extract the lock pointer in case there are concurrent
22455 	 * hash_remove's for this instance.
22456 	 */
22457 	ASSERT(tcp->tcp_lport != 0);
22458 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22459 
22460 	ASSERT(lockp != NULL);
22461 	mutex_enter(lockp);
22462 	if (tcp->tcp_ptpbhn) {
22463 		tcpnext = tcp->tcp_bind_hash;
22464 		if (tcpnext) {
22465 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22466 			tcp->tcp_bind_hash = NULL;
22467 		}
22468 		*tcp->tcp_ptpbhn = tcpnext;
22469 		tcp->tcp_ptpbhn = NULL;
22470 	}
22471 	mutex_exit(lockp);
22472 }
22473 
22474 
22475 /*
22476  * Hash list lookup routine for tcp_t structures.
22477  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22478  */
22479 static tcp_t *
22480 tcp_acceptor_hash_lookup(t_uscalar_t id)
22481 {
22482 	tf_t	*tf;
22483 	tcp_t	*tcp;
22484 
22485 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22486 	mutex_enter(&tf->tf_lock);
22487 	for (tcp = tf->tf_tcp; tcp != NULL;
22488 	    tcp = tcp->tcp_acceptor_hash) {
22489 		if (tcp->tcp_acceptor_id == id) {
22490 			CONN_INC_REF(tcp->tcp_connp);
22491 			mutex_exit(&tf->tf_lock);
22492 			return (tcp);
22493 		}
22494 	}
22495 	mutex_exit(&tf->tf_lock);
22496 	return (NULL);
22497 }
22498 
22499 
22500 /*
22501  * Hash list insertion routine for tcp_t structures.
22502  */
22503 void
22504 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22505 {
22506 	tf_t	*tf;
22507 	tcp_t	**tcpp;
22508 	tcp_t	*tcpnext;
22509 
22510 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22511 
22512 	if (tcp->tcp_ptpahn != NULL)
22513 		tcp_acceptor_hash_remove(tcp);
22514 	tcpp = &tf->tf_tcp;
22515 	mutex_enter(&tf->tf_lock);
22516 	tcpnext = tcpp[0];
22517 	if (tcpnext)
22518 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22519 	tcp->tcp_acceptor_hash = tcpnext;
22520 	tcp->tcp_ptpahn = tcpp;
22521 	tcpp[0] = tcp;
22522 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22523 	mutex_exit(&tf->tf_lock);
22524 }
22525 
22526 /*
22527  * Hash list removal routine for tcp_t structures.
22528  */
22529 static void
22530 tcp_acceptor_hash_remove(tcp_t *tcp)
22531 {
22532 	tcp_t	*tcpnext;
22533 	kmutex_t *lockp;
22534 
22535 	/*
22536 	 * Extract the lock pointer in case there are concurrent
22537 	 * hash_remove's for this instance.
22538 	 */
22539 	lockp = tcp->tcp_acceptor_lockp;
22540 
22541 	if (tcp->tcp_ptpahn == NULL)
22542 		return;
22543 
22544 	ASSERT(lockp != NULL);
22545 	mutex_enter(lockp);
22546 	if (tcp->tcp_ptpahn) {
22547 		tcpnext = tcp->tcp_acceptor_hash;
22548 		if (tcpnext) {
22549 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22550 			tcp->tcp_acceptor_hash = NULL;
22551 		}
22552 		*tcp->tcp_ptpahn = tcpnext;
22553 		tcp->tcp_ptpahn = NULL;
22554 	}
22555 	mutex_exit(lockp);
22556 	tcp->tcp_acceptor_lockp = NULL;
22557 }
22558 
22559 /* ARGSUSED */
22560 static int
22561 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22562 {
22563 	int error = 0;
22564 	int retval;
22565 	char *end;
22566 
22567 	tcp_hsp_t *hsp;
22568 	tcp_hsp_t *hspprev;
22569 
22570 	ipaddr_t addr = 0;		/* Address we're looking for */
22571 	in6_addr_t v6addr;		/* Address we're looking for */
22572 	uint32_t hash;			/* Hash of that address */
22573 
22574 	/*
22575 	 * If the following variables are still zero after parsing the input
22576 	 * string, the user didn't specify them and we don't change them in
22577 	 * the HSP.
22578 	 */
22579 
22580 	ipaddr_t mask = 0;		/* Subnet mask */
22581 	in6_addr_t v6mask;
22582 	long sendspace = 0;		/* Send buffer size */
22583 	long recvspace = 0;		/* Receive buffer size */
22584 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22585 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22586 
22587 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22588 
22589 	/* Parse and validate address */
22590 	if (af == AF_INET) {
22591 		retval = inet_pton(af, value, &addr);
22592 		if (retval == 1)
22593 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22594 	} else if (af == AF_INET6) {
22595 		retval = inet_pton(af, value, &v6addr);
22596 	} else {
22597 		error = EINVAL;
22598 		goto done;
22599 	}
22600 	if (retval == 0) {
22601 		error = EINVAL;
22602 		goto done;
22603 	}
22604 
22605 	while ((*value) && *value != ' ')
22606 		value++;
22607 
22608 	/* Parse individual keywords, set variables if found */
22609 	while (*value) {
22610 		/* Skip leading blanks */
22611 
22612 		while (*value == ' ' || *value == '\t')
22613 			value++;
22614 
22615 		/* If at end of string, we're done */
22616 
22617 		if (!*value)
22618 			break;
22619 
22620 		/* We have a word, figure out what it is */
22621 
22622 		if (strncmp("mask", value, 4) == 0) {
22623 			value += 4;
22624 			while (*value == ' ' || *value == '\t')
22625 				value++;
22626 			/* Parse subnet mask */
22627 			if (af == AF_INET) {
22628 				retval = inet_pton(af, value, &mask);
22629 				if (retval == 1) {
22630 					V4MASK_TO_V6(mask, v6mask);
22631 				}
22632 			} else if (af == AF_INET6) {
22633 				retval = inet_pton(af, value, &v6mask);
22634 			}
22635 			if (retval != 1) {
22636 				error = EINVAL;
22637 				goto done;
22638 			}
22639 			while ((*value) && *value != ' ')
22640 				value++;
22641 		} else if (strncmp("sendspace", value, 9) == 0) {
22642 			value += 9;
22643 
22644 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
22645 			    sendspace < TCP_XMIT_HIWATER ||
22646 			    sendspace >= (1L<<30)) {
22647 				error = EINVAL;
22648 				goto done;
22649 			}
22650 			value = end;
22651 		} else if (strncmp("recvspace", value, 9) == 0) {
22652 			value += 9;
22653 
22654 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
22655 			    recvspace < TCP_RECV_HIWATER ||
22656 			    recvspace >= (1L<<30)) {
22657 				error = EINVAL;
22658 				goto done;
22659 			}
22660 			value = end;
22661 		} else if (strncmp("timestamp", value, 9) == 0) {
22662 			value += 9;
22663 
22664 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
22665 			    timestamp < 0 || timestamp > 1) {
22666 				error = EINVAL;
22667 				goto done;
22668 			}
22669 
22670 			/*
22671 			 * We increment timestamp so we know it's been set;
22672 			 * this is undone when we put it in the HSP
22673 			 */
22674 			timestamp++;
22675 			value = end;
22676 		} else if (strncmp("delete", value, 6) == 0) {
22677 			value += 6;
22678 			delete = B_TRUE;
22679 		} else {
22680 			error = EINVAL;
22681 			goto done;
22682 		}
22683 	}
22684 
22685 	/* Hash address for lookup */
22686 
22687 	hash = TCP_HSP_HASH(addr);
22688 
22689 	if (delete) {
22690 		/*
22691 		 * Note that deletes don't return an error if the thing
22692 		 * we're trying to delete isn't there.
22693 		 */
22694 		if (tcp_hsp_hash == NULL)
22695 			goto done;
22696 		hsp = tcp_hsp_hash[hash];
22697 
22698 		if (hsp) {
22699 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22700 			    &v6addr)) {
22701 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
22702 				mi_free((char *)hsp);
22703 			} else {
22704 				hspprev = hsp;
22705 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
22706 					if (IN6_ARE_ADDR_EQUAL(
22707 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
22708 						hspprev->tcp_hsp_next =
22709 						    hsp->tcp_hsp_next;
22710 						mi_free((char *)hsp);
22711 						break;
22712 					}
22713 					hspprev = hsp;
22714 				}
22715 			}
22716 		}
22717 	} else {
22718 		/*
22719 		 * We're adding/modifying an HSP.  If we haven't already done
22720 		 * so, allocate the hash table.
22721 		 */
22722 
22723 		if (!tcp_hsp_hash) {
22724 			tcp_hsp_hash = (tcp_hsp_t **)
22725 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
22726 			if (!tcp_hsp_hash) {
22727 				error = EINVAL;
22728 				goto done;
22729 			}
22730 		}
22731 
22732 		/* Get head of hash chain */
22733 
22734 		hsp = tcp_hsp_hash[hash];
22735 
22736 		/* Try to find pre-existing hsp on hash chain */
22737 		/* Doesn't handle CIDR prefixes. */
22738 		while (hsp) {
22739 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
22740 				break;
22741 			hsp = hsp->tcp_hsp_next;
22742 		}
22743 
22744 		/*
22745 		 * If we didn't, create one with default values and put it
22746 		 * at head of hash chain
22747 		 */
22748 
22749 		if (!hsp) {
22750 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
22751 			if (!hsp) {
22752 				error = EINVAL;
22753 				goto done;
22754 			}
22755 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
22756 			tcp_hsp_hash[hash] = hsp;
22757 		}
22758 
22759 		/* Set values that the user asked us to change */
22760 
22761 		hsp->tcp_hsp_addr_v6 = v6addr;
22762 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
22763 			hsp->tcp_hsp_vers = IPV4_VERSION;
22764 		else
22765 			hsp->tcp_hsp_vers = IPV6_VERSION;
22766 		hsp->tcp_hsp_subnet_v6 = v6mask;
22767 		if (sendspace > 0)
22768 			hsp->tcp_hsp_sendspace = sendspace;
22769 		if (recvspace > 0)
22770 			hsp->tcp_hsp_recvspace = recvspace;
22771 		if (timestamp > 0)
22772 			hsp->tcp_hsp_tstamp = timestamp - 1;
22773 	}
22774 
22775 done:
22776 	rw_exit(&tcp_hsp_lock);
22777 	return (error);
22778 }
22779 
22780 /* Set callback routine passed to nd_load by tcp_param_register. */
22781 /* ARGSUSED */
22782 static int
22783 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
22784 {
22785 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
22786 }
22787 /* ARGSUSED */
22788 static int
22789 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22790     cred_t *cr)
22791 {
22792 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
22793 }
22794 
22795 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
22796 /* ARGSUSED */
22797 static int
22798 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22799 {
22800 	tcp_hsp_t *hsp;
22801 	int i;
22802 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
22803 
22804 	rw_enter(&tcp_hsp_lock, RW_READER);
22805 	(void) mi_mpprintf(mp,
22806 	    "Hash HSP     " MI_COL_HDRPAD_STR
22807 	    "Address         Subnet Mask     Send       Receive    TStamp");
22808 	if (tcp_hsp_hash) {
22809 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
22810 			hsp = tcp_hsp_hash[i];
22811 			while (hsp) {
22812 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
22813 					(void) inet_ntop(AF_INET,
22814 					    &hsp->tcp_hsp_addr,
22815 					    addrbuf, sizeof (addrbuf));
22816 					(void) inet_ntop(AF_INET,
22817 					    &hsp->tcp_hsp_subnet,
22818 					    subnetbuf, sizeof (subnetbuf));
22819 				} else {
22820 					(void) inet_ntop(AF_INET6,
22821 					    &hsp->tcp_hsp_addr_v6,
22822 					    addrbuf, sizeof (addrbuf));
22823 					(void) inet_ntop(AF_INET6,
22824 					    &hsp->tcp_hsp_subnet_v6,
22825 					    subnetbuf, sizeof (subnetbuf));
22826 				}
22827 				(void) mi_mpprintf(mp,
22828 				    " %03d " MI_COL_PTRFMT_STR
22829 				    "%s %s %010d %010d      %d",
22830 				    i,
22831 				    (void *)hsp,
22832 				    addrbuf,
22833 				    subnetbuf,
22834 				    hsp->tcp_hsp_sendspace,
22835 				    hsp->tcp_hsp_recvspace,
22836 				    hsp->tcp_hsp_tstamp);
22837 
22838 				hsp = hsp->tcp_hsp_next;
22839 			}
22840 		}
22841 	}
22842 	rw_exit(&tcp_hsp_lock);
22843 	return (0);
22844 }
22845 
22846 
22847 /* Data for fast netmask macro used by tcp_hsp_lookup */
22848 
22849 static ipaddr_t netmasks[] = {
22850 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
22851 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
22852 };
22853 
22854 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
22855 
22856 /*
22857  * XXX This routine should go away and instead we should use the metrics
22858  * associated with the routes to determine the default sndspace and rcvspace.
22859  */
22860 static tcp_hsp_t *
22861 tcp_hsp_lookup(ipaddr_t addr)
22862 {
22863 	tcp_hsp_t *hsp = NULL;
22864 
22865 	/* Quick check without acquiring the lock. */
22866 	if (tcp_hsp_hash == NULL)
22867 		return (NULL);
22868 
22869 	rw_enter(&tcp_hsp_lock, RW_READER);
22870 
22871 	/* This routine finds the best-matching HSP for address addr. */
22872 
22873 	if (tcp_hsp_hash) {
22874 		int i;
22875 		ipaddr_t srchaddr;
22876 		tcp_hsp_t *hsp_net;
22877 
22878 		/* We do three passes: host, network, and subnet. */
22879 
22880 		srchaddr = addr;
22881 
22882 		for (i = 1; i <= 3; i++) {
22883 			/* Look for exact match on srchaddr */
22884 
22885 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
22886 			while (hsp) {
22887 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
22888 				    hsp->tcp_hsp_addr == srchaddr)
22889 					break;
22890 				hsp = hsp->tcp_hsp_next;
22891 			}
22892 			ASSERT(hsp == NULL ||
22893 			    hsp->tcp_hsp_vers == IPV4_VERSION);
22894 
22895 			/*
22896 			 * If this is the first pass:
22897 			 *   If we found a match, great, return it.
22898 			 *   If not, search for the network on the second pass.
22899 			 */
22900 
22901 			if (i == 1)
22902 				if (hsp)
22903 					break;
22904 				else
22905 				{
22906 					srchaddr = addr & netmask(addr);
22907 					continue;
22908 				}
22909 
22910 			/*
22911 			 * If this is the second pass:
22912 			 *   If we found a match, but there's a subnet mask,
22913 			 *    save the match but try again using the subnet
22914 			 *    mask on the third pass.
22915 			 *   Otherwise, return whatever we found.
22916 			 */
22917 
22918 			if (i == 2) {
22919 				if (hsp && hsp->tcp_hsp_subnet) {
22920 					hsp_net = hsp;
22921 					srchaddr = addr & hsp->tcp_hsp_subnet;
22922 					continue;
22923 				} else {
22924 					break;
22925 				}
22926 			}
22927 
22928 			/*
22929 			 * This must be the third pass.  If we didn't find
22930 			 * anything, return the saved network HSP instead.
22931 			 */
22932 
22933 			if (!hsp)
22934 				hsp = hsp_net;
22935 		}
22936 	}
22937 
22938 	rw_exit(&tcp_hsp_lock);
22939 	return (hsp);
22940 }
22941 
22942 /*
22943  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
22944  * match lookup.
22945  */
22946 static tcp_hsp_t *
22947 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
22948 {
22949 	tcp_hsp_t *hsp = NULL;
22950 
22951 	/* Quick check without acquiring the lock. */
22952 	if (tcp_hsp_hash == NULL)
22953 		return (NULL);
22954 
22955 	rw_enter(&tcp_hsp_lock, RW_READER);
22956 
22957 	/* This routine finds the best-matching HSP for address addr. */
22958 
22959 	if (tcp_hsp_hash) {
22960 		int i;
22961 		in6_addr_t v6srchaddr;
22962 		tcp_hsp_t *hsp_net;
22963 
22964 		/* We do three passes: host, network, and subnet. */
22965 
22966 		v6srchaddr = *v6addr;
22967 
22968 		for (i = 1; i <= 3; i++) {
22969 			/* Look for exact match on srchaddr */
22970 
22971 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
22972 			    V4_PART_OF_V6(v6srchaddr))];
22973 			while (hsp) {
22974 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
22975 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22976 				    &v6srchaddr))
22977 					break;
22978 				hsp = hsp->tcp_hsp_next;
22979 			}
22980 
22981 			/*
22982 			 * If this is the first pass:
22983 			 *   If we found a match, great, return it.
22984 			 *   If not, search for the network on the second pass.
22985 			 */
22986 
22987 			if (i == 1)
22988 				if (hsp)
22989 					break;
22990 				else {
22991 					/* Assume a 64 bit mask */
22992 					v6srchaddr.s6_addr32[0] =
22993 					    v6addr->s6_addr32[0];
22994 					v6srchaddr.s6_addr32[1] =
22995 					    v6addr->s6_addr32[1];
22996 					v6srchaddr.s6_addr32[2] = 0;
22997 					v6srchaddr.s6_addr32[3] = 0;
22998 					continue;
22999 				}
23000 
23001 			/*
23002 			 * If this is the second pass:
23003 			 *   If we found a match, but there's a subnet mask,
23004 			 *    save the match but try again using the subnet
23005 			 *    mask on the third pass.
23006 			 *   Otherwise, return whatever we found.
23007 			 */
23008 
23009 			if (i == 2) {
23010 				ASSERT(hsp == NULL ||
23011 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23012 				if (hsp &&
23013 				    !IN6_IS_ADDR_UNSPECIFIED(
23014 				    &hsp->tcp_hsp_subnet_v6)) {
23015 					hsp_net = hsp;
23016 					V6_MASK_COPY(*v6addr,
23017 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23018 					continue;
23019 				} else {
23020 					break;
23021 				}
23022 			}
23023 
23024 			/*
23025 			 * This must be the third pass.  If we didn't find
23026 			 * anything, return the saved network HSP instead.
23027 			 */
23028 
23029 			if (!hsp)
23030 				hsp = hsp_net;
23031 		}
23032 	}
23033 
23034 	rw_exit(&tcp_hsp_lock);
23035 	return (hsp);
23036 }
23037 
23038 /*
23039  * Type three generator adapted from the random() function in 4.4 BSD:
23040  */
23041 
23042 /*
23043  * Copyright (c) 1983, 1993
23044  *	The Regents of the University of California.  All rights reserved.
23045  *
23046  * Redistribution and use in source and binary forms, with or without
23047  * modification, are permitted provided that the following conditions
23048  * are met:
23049  * 1. Redistributions of source code must retain the above copyright
23050  *    notice, this list of conditions and the following disclaimer.
23051  * 2. Redistributions in binary form must reproduce the above copyright
23052  *    notice, this list of conditions and the following disclaimer in the
23053  *    documentation and/or other materials provided with the distribution.
23054  * 3. All advertising materials mentioning features or use of this software
23055  *    must display the following acknowledgement:
23056  *	This product includes software developed by the University of
23057  *	California, Berkeley and its contributors.
23058  * 4. Neither the name of the University nor the names of its contributors
23059  *    may be used to endorse or promote products derived from this software
23060  *    without specific prior written permission.
23061  *
23062  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23063  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23064  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23065  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23066  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23067  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23068  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23069  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23070  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23071  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23072  * SUCH DAMAGE.
23073  */
23074 
23075 /* Type 3 -- x**31 + x**3 + 1 */
23076 #define	DEG_3		31
23077 #define	SEP_3		3
23078 
23079 
23080 /* Protected by tcp_random_lock */
23081 static int tcp_randtbl[DEG_3 + 1];
23082 
23083 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23084 static int *tcp_random_rptr = &tcp_randtbl[1];
23085 
23086 static int *tcp_random_state = &tcp_randtbl[1];
23087 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23088 
23089 kmutex_t tcp_random_lock;
23090 
23091 void
23092 tcp_random_init(void)
23093 {
23094 	int i;
23095 	hrtime_t hrt;
23096 	time_t wallclock;
23097 	uint64_t result;
23098 
23099 	/*
23100 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23101 	 * a longlong, which may contain resolution down to nanoseconds.
23102 	 * The current time will either be a 32-bit or a 64-bit quantity.
23103 	 * XOR the two together in a 64-bit result variable.
23104 	 * Convert the result to a 32-bit value by multiplying the high-order
23105 	 * 32-bits by the low-order 32-bits.
23106 	 */
23107 
23108 	hrt = gethrtime();
23109 	(void) drv_getparm(TIME, &wallclock);
23110 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23111 	mutex_enter(&tcp_random_lock);
23112 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23113 	    (result & 0xffffffff);
23114 
23115 	for (i = 1; i < DEG_3; i++)
23116 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23117 			+ 12345;
23118 	tcp_random_fptr = &tcp_random_state[SEP_3];
23119 	tcp_random_rptr = &tcp_random_state[0];
23120 	mutex_exit(&tcp_random_lock);
23121 	for (i = 0; i < 10 * DEG_3; i++)
23122 		(void) tcp_random();
23123 }
23124 
23125 /*
23126  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23127  * This range is selected to be approximately centered on TCP_ISS / 2,
23128  * and easy to compute. We get this value by generating a 32-bit random
23129  * number, selecting out the high-order 17 bits, and then adding one so
23130  * that we never return zero.
23131  */
23132 int
23133 tcp_random(void)
23134 {
23135 	int i;
23136 
23137 	mutex_enter(&tcp_random_lock);
23138 	*tcp_random_fptr += *tcp_random_rptr;
23139 
23140 	/*
23141 	 * The high-order bits are more random than the low-order bits,
23142 	 * so we select out the high-order 17 bits and add one so that
23143 	 * we never return zero.
23144 	 */
23145 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23146 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23147 		tcp_random_fptr = tcp_random_state;
23148 		++tcp_random_rptr;
23149 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23150 		tcp_random_rptr = tcp_random_state;
23151 
23152 	mutex_exit(&tcp_random_lock);
23153 	return (i);
23154 }
23155 
23156 /*
23157  * XXX This will go away when TPI is extended to send
23158  * info reqs to sockfs/timod .....
23159  * Given a queue, set the max packet size for the write
23160  * side of the queue below stream head.  This value is
23161  * cached on the stream head.
23162  * Returns 1 on success, 0 otherwise.
23163  */
23164 static int
23165 setmaxps(queue_t *q, int maxpsz)
23166 {
23167 	struct stdata	*stp;
23168 	queue_t		*wq;
23169 	stp = STREAM(q);
23170 
23171 	/*
23172 	 * At this point change of a queue parameter is not allowed
23173 	 * when a multiplexor is sitting on top.
23174 	 */
23175 	if (stp->sd_flag & STPLEX)
23176 		return (0);
23177 
23178 	claimstr(stp->sd_wrq);
23179 	wq = stp->sd_wrq->q_next;
23180 	ASSERT(wq != NULL);
23181 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23182 	releasestr(stp->sd_wrq);
23183 	return (1);
23184 }
23185 
23186 static int
23187 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23188     int *t_errorp, int *sys_errorp)
23189 {
23190 	int error;
23191 	int is_absreq_failure;
23192 	t_scalar_t *opt_lenp;
23193 	t_scalar_t opt_offset;
23194 	int prim_type;
23195 	struct T_conn_req *tcreqp;
23196 	struct T_conn_res *tcresp;
23197 	cred_t *cr;
23198 
23199 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23200 
23201 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23202 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23203 	    prim_type == T_CONN_RES);
23204 
23205 	switch (prim_type) {
23206 	case T_CONN_REQ:
23207 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23208 		opt_offset = tcreqp->OPT_offset;
23209 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23210 		break;
23211 	case O_T_CONN_RES:
23212 	case T_CONN_RES:
23213 		tcresp = (struct T_conn_res *)mp->b_rptr;
23214 		opt_offset = tcresp->OPT_offset;
23215 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23216 		break;
23217 	}
23218 
23219 	*t_errorp = 0;
23220 	*sys_errorp = 0;
23221 	*do_disconnectp = 0;
23222 
23223 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23224 	    opt_offset, cr, &tcp_opt_obj,
23225 	    NULL, &is_absreq_failure);
23226 
23227 	switch (error) {
23228 	case  0:		/* no error */
23229 		ASSERT(is_absreq_failure == 0);
23230 		return (0);
23231 	case ENOPROTOOPT:
23232 		*t_errorp = TBADOPT;
23233 		break;
23234 	case EACCES:
23235 		*t_errorp = TACCES;
23236 		break;
23237 	default:
23238 		*t_errorp = TSYSERR; *sys_errorp = error;
23239 		break;
23240 	}
23241 	if (is_absreq_failure != 0) {
23242 		/*
23243 		 * The connection request should get the local ack
23244 		 * T_OK_ACK and then a T_DISCON_IND.
23245 		 */
23246 		*do_disconnectp = 1;
23247 	}
23248 	return (-1);
23249 }
23250 
23251 /*
23252  * Split this function out so that if the secret changes, I'm okay.
23253  *
23254  * Initialize the tcp_iss_cookie and tcp_iss_key.
23255  */
23256 
23257 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23258 
23259 static void
23260 tcp_iss_key_init(uint8_t *phrase, int len)
23261 {
23262 	struct {
23263 		int32_t current_time;
23264 		uint32_t randnum;
23265 		uint16_t pad;
23266 		uint8_t ether[6];
23267 		uint8_t passwd[PASSWD_SIZE];
23268 	} tcp_iss_cookie;
23269 	time_t t;
23270 
23271 	/*
23272 	 * Start with the current absolute time.
23273 	 */
23274 	(void) drv_getparm(TIME, &t);
23275 	tcp_iss_cookie.current_time = t;
23276 
23277 	/*
23278 	 * XXX - Need a more random number per RFC 1750, not this crap.
23279 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23280 	 */
23281 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23282 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23283 
23284 	/*
23285 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23286 	 * as a good template.
23287 	 */
23288 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23289 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23290 
23291 	/*
23292 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23293 	 */
23294 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23295 
23296 	/*
23297 	 * See 4010593 if this section becomes a problem again,
23298 	 * but the local ethernet address is useful here.
23299 	 */
23300 	(void) localetheraddr(NULL,
23301 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23302 
23303 	/*
23304 	 * Hash 'em all together.  The MD5Final is called per-connection.
23305 	 */
23306 	mutex_enter(&tcp_iss_key_lock);
23307 	MD5Init(&tcp_iss_key);
23308 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23309 	    sizeof (tcp_iss_cookie));
23310 	mutex_exit(&tcp_iss_key_lock);
23311 }
23312 
23313 /*
23314  * Set the RFC 1948 pass phrase
23315  */
23316 /* ARGSUSED */
23317 static int
23318 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23319     cred_t *cr)
23320 {
23321 	/*
23322 	 * Basically, value contains a new pass phrase.  Pass it along!
23323 	 */
23324 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23325 	return (0);
23326 }
23327 
23328 /* ARGSUSED */
23329 static int
23330 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23331 {
23332 	bzero(buf, sizeof (tcp_sack_info_t));
23333 	return (0);
23334 }
23335 
23336 /* ARGSUSED */
23337 static int
23338 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23339 {
23340 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23341 	return (0);
23342 }
23343 
23344 void
23345 tcp_ddi_init(void)
23346 {
23347 	int i;
23348 
23349 	/* Initialize locks */
23350 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23351 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23352 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23353 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23354 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23355 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23356 
23357 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23358 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23359 		    MUTEX_DEFAULT, NULL);
23360 	}
23361 
23362 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23363 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23364 		    MUTEX_DEFAULT, NULL);
23365 	}
23366 
23367 	/* TCP's IPsec code calls the packet dropper. */
23368 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23369 
23370 	if (!tcp_g_nd) {
23371 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23372 			nd_free(&tcp_g_nd);
23373 		}
23374 	}
23375 
23376 	/*
23377 	 * Note: To really walk the device tree you need the devinfo
23378 	 * pointer to your device which is only available after probe/attach.
23379 	 * The following is safe only because it uses ddi_root_node()
23380 	 */
23381 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23382 	    tcp_opt_obj.odb_opt_arr_cnt);
23383 
23384 	tcp_timercache = kmem_cache_create("tcp_timercache",
23385 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23386 	    NULL, NULL, NULL, NULL, NULL, 0);
23387 
23388 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23389 	    sizeof (tcp_sack_info_t), 0,
23390 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23391 
23392 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23393 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23394 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23395 
23396 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23397 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23398 
23399 	ip_squeue_init(tcp_squeue_add);
23400 
23401 	/* Initialize the random number generator */
23402 	tcp_random_init();
23403 
23404 	/*
23405 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23406 	 * by the boot scripts.
23407 	 *
23408 	 * Use NULL name, as the name is caught by the new lockstats.
23409 	 *
23410 	 * Initialize with some random, non-guessable string, like the global
23411 	 * T_INFO_ACK.
23412 	 */
23413 
23414 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23415 	    sizeof (tcp_g_t_info_ack));
23416 
23417 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23418 		"net", KSTAT_TYPE_NAMED,
23419 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23420 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23421 		tcp_kstat->ks_data = &tcp_statistics;
23422 		kstat_install(tcp_kstat);
23423 	}
23424 
23425 	tcp_kstat_init();
23426 }
23427 
23428 void
23429 tcp_ddi_destroy(void)
23430 {
23431 	int i;
23432 
23433 	nd_free(&tcp_g_nd);
23434 
23435 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23436 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23437 	}
23438 
23439 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23440 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23441 	}
23442 
23443 	mutex_destroy(&tcp_iss_key_lock);
23444 	rw_destroy(&tcp_hsp_lock);
23445 	mutex_destroy(&tcp_g_q_lock);
23446 	mutex_destroy(&tcp_random_lock);
23447 	mutex_destroy(&tcp_epriv_port_lock);
23448 	rw_destroy(&tcp_reserved_port_lock);
23449 
23450 	ip_drop_unregister(&tcp_dropper);
23451 
23452 	kmem_cache_destroy(tcp_timercache);
23453 	kmem_cache_destroy(tcp_sack_info_cache);
23454 	kmem_cache_destroy(tcp_iphc_cache);
23455 
23456 	tcp_kstat_fini();
23457 }
23458 
23459 /*
23460  * Generate ISS, taking into account NDD changes may happen halfway through.
23461  * (If the iss is not zero, set it.)
23462  */
23463 
23464 static void
23465 tcp_iss_init(tcp_t *tcp)
23466 {
23467 	MD5_CTX context;
23468 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23469 	uint32_t answer[4];
23470 
23471 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23472 	tcp->tcp_iss = tcp_iss_incr_extra;
23473 	switch (tcp_strong_iss) {
23474 	case 2:
23475 		mutex_enter(&tcp_iss_key_lock);
23476 		context = tcp_iss_key;
23477 		mutex_exit(&tcp_iss_key_lock);
23478 		arg.ports = tcp->tcp_ports;
23479 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23480 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23481 			    &arg.src);
23482 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23483 			    &arg.dst);
23484 		} else {
23485 			arg.src = tcp->tcp_ip6h->ip6_src;
23486 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23487 		}
23488 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23489 		MD5Final((uchar_t *)answer, &context);
23490 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23491 		/*
23492 		 * Now that we've hashed into a unique per-connection sequence
23493 		 * space, add a random increment per strong_iss == 1.  So I
23494 		 * guess we'll have to...
23495 		 */
23496 		/* FALLTHRU */
23497 	case 1:
23498 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23499 		break;
23500 	default:
23501 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23502 		break;
23503 	}
23504 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23505 	tcp->tcp_fss = tcp->tcp_iss - 1;
23506 	tcp->tcp_suna = tcp->tcp_iss;
23507 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23508 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23509 	tcp->tcp_csuna = tcp->tcp_snxt;
23510 }
23511 
23512 /*
23513  * Exported routine for extracting active tcp connection status.
23514  *
23515  * This is used by the Solaris Cluster Networking software to
23516  * gather a list of connections that need to be forwarded to
23517  * specific nodes in the cluster when configuration changes occur.
23518  *
23519  * The callback is invoked for each tcp_t structure. Returning
23520  * non-zero from the callback routine terminates the search.
23521  */
23522 int
23523 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23524 {
23525 	tcp_t *tcp;
23526 	cl_tcp_info_t	cl_tcpi;
23527 	connf_t	*connfp;
23528 	conn_t	*connp;
23529 	int	i;
23530 
23531 	ASSERT(callback != NULL);
23532 
23533 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23534 
23535 		connfp = &ipcl_globalhash_fanout[i];
23536 		connp = NULL;
23537 
23538 		while ((connp =
23539 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23540 
23541 			tcp = connp->conn_tcp;
23542 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23543 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23544 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23545 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23546 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23547 			/*
23548 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23549 			 * addresses. They are copied implicitly below as
23550 			 * mapped addresses.
23551 			 */
23552 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23553 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23554 				cl_tcpi.cl_tcpi_faddr =
23555 				    tcp->tcp_ipha->ipha_dst;
23556 			} else {
23557 				cl_tcpi.cl_tcpi_faddr_v6 =
23558 				    tcp->tcp_ip6h->ip6_dst;
23559 			}
23560 
23561 			/*
23562 			 * If the callback returns non-zero
23563 			 * we terminate the traversal.
23564 			 */
23565 			if ((*callback)(&cl_tcpi, arg) != 0) {
23566 				CONN_DEC_REF(tcp->tcp_connp);
23567 				return (1);
23568 			}
23569 		}
23570 	}
23571 
23572 	return (0);
23573 }
23574 
23575 /*
23576  * Macros used for accessing the different types of sockaddr
23577  * structures inside a tcp_ioc_abort_conn_t.
23578  */
23579 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23580 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23581 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23582 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23583 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23584 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23585 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23586 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23587 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23588 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23589 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23590 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23591 
23592 /*
23593  * Return the correct error code to mimic the behavior
23594  * of a connection reset.
23595  */
23596 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23597 		switch ((state)) {		\
23598 		case TCPS_SYN_SENT:		\
23599 		case TCPS_SYN_RCVD:		\
23600 			(err) = ECONNREFUSED;	\
23601 			break;			\
23602 		case TCPS_ESTABLISHED:		\
23603 		case TCPS_FIN_WAIT_1:		\
23604 		case TCPS_FIN_WAIT_2:		\
23605 		case TCPS_CLOSE_WAIT:		\
23606 			(err) = ECONNRESET;	\
23607 			break;			\
23608 		case TCPS_CLOSING:		\
23609 		case TCPS_LAST_ACK:		\
23610 		case TCPS_TIME_WAIT:		\
23611 			(err) = 0;		\
23612 			break;			\
23613 		default:			\
23614 			(err) = ENXIO;		\
23615 		}				\
23616 	}
23617 
23618 /*
23619  * Check if a tcp structure matches the info in acp.
23620  */
23621 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23622 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23623 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23624 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23625 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23626 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23627 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23628 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23629 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23630 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23631 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23632 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23633 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23634 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23635 	&(tcp)->tcp_ip_src_v6)) &&				\
23636 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23637 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23638 	&(tcp)->tcp_remote_v6)) &&				\
23639 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
23640 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
23641 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
23642 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
23643 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23644 	(acp)->ac_end >= (tcp)->tcp_state))
23645 
23646 #define	TCP_AC_MATCH(acp, tcp)					\
23647 	(((acp)->ac_zoneid == ALL_ZONES ||			\
23648 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
23649 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
23650 
23651 /*
23652  * Build a message containing a tcp_ioc_abort_conn_t structure
23653  * which is filled in with information from acp and tp.
23654  */
23655 static mblk_t *
23656 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
23657 {
23658 	mblk_t *mp;
23659 	tcp_ioc_abort_conn_t *tacp;
23660 
23661 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
23662 	if (mp == NULL)
23663 		return (NULL);
23664 
23665 	mp->b_datap->db_type = M_CTL;
23666 
23667 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
23668 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
23669 		sizeof (uint32_t));
23670 
23671 	tacp->ac_start = acp->ac_start;
23672 	tacp->ac_end = acp->ac_end;
23673 	tacp->ac_zoneid = acp->ac_zoneid;
23674 
23675 	if (acp->ac_local.ss_family == AF_INET) {
23676 		tacp->ac_local.ss_family = AF_INET;
23677 		tacp->ac_remote.ss_family = AF_INET;
23678 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
23679 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
23680 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
23681 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
23682 	} else {
23683 		tacp->ac_local.ss_family = AF_INET6;
23684 		tacp->ac_remote.ss_family = AF_INET6;
23685 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
23686 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
23687 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
23688 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
23689 	}
23690 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
23691 	return (mp);
23692 }
23693 
23694 /*
23695  * Print a tcp_ioc_abort_conn_t structure.
23696  */
23697 static void
23698 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
23699 {
23700 	char lbuf[128];
23701 	char rbuf[128];
23702 	sa_family_t af;
23703 	in_port_t lport, rport;
23704 	ushort_t logflags;
23705 
23706 	af = acp->ac_local.ss_family;
23707 
23708 	if (af == AF_INET) {
23709 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
23710 				lbuf, 128);
23711 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
23712 				rbuf, 128);
23713 		lport = ntohs(TCP_AC_V4LPORT(acp));
23714 		rport = ntohs(TCP_AC_V4RPORT(acp));
23715 	} else {
23716 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
23717 				lbuf, 128);
23718 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
23719 				rbuf, 128);
23720 		lport = ntohs(TCP_AC_V6LPORT(acp));
23721 		rport = ntohs(TCP_AC_V6RPORT(acp));
23722 	}
23723 
23724 	logflags = SL_TRACE | SL_NOTE;
23725 	/*
23726 	 * Don't print this message to the console if the operation was done
23727 	 * to a non-global zone.
23728 	 */
23729 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23730 		logflags |= SL_CONSOLE;
23731 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
23732 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
23733 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
23734 		acp->ac_start, acp->ac_end);
23735 }
23736 
23737 /*
23738  * Called inside tcp_rput when a message built using
23739  * tcp_ioctl_abort_build_msg is put into a queue.
23740  * Note that when we get here there is no wildcard in acp any more.
23741  */
23742 static void
23743 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
23744 {
23745 	tcp_ioc_abort_conn_t *acp;
23746 
23747 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
23748 	if (tcp->tcp_state <= acp->ac_end) {
23749 		/*
23750 		 * If we get here, we are already on the correct
23751 		 * squeue. This ioctl follows the following path
23752 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
23753 		 * ->tcp_ioctl_abort->squeue_fill (if on a
23754 		 * different squeue)
23755 		 */
23756 		int errcode;
23757 
23758 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
23759 		(void) tcp_clean_death(tcp, errcode, 26);
23760 	}
23761 	freemsg(mp);
23762 }
23763 
23764 /*
23765  * Abort all matching connections on a hash chain.
23766  */
23767 static int
23768 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
23769     boolean_t exact)
23770 {
23771 	int nmatch, err = 0;
23772 	tcp_t *tcp;
23773 	MBLKP mp, last, listhead = NULL;
23774 	conn_t	*tconnp;
23775 	connf_t	*connfp = &ipcl_conn_fanout[index];
23776 
23777 startover:
23778 	nmatch = 0;
23779 
23780 	mutex_enter(&connfp->connf_lock);
23781 	for (tconnp = connfp->connf_head; tconnp != NULL;
23782 	    tconnp = tconnp->conn_next) {
23783 		tcp = tconnp->conn_tcp;
23784 		if (TCP_AC_MATCH(acp, tcp)) {
23785 			CONN_INC_REF(tcp->tcp_connp);
23786 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
23787 			if (mp == NULL) {
23788 				err = ENOMEM;
23789 				CONN_DEC_REF(tcp->tcp_connp);
23790 				break;
23791 			}
23792 			mp->b_prev = (mblk_t *)tcp;
23793 
23794 			if (listhead == NULL) {
23795 				listhead = mp;
23796 				last = mp;
23797 			} else {
23798 				last->b_next = mp;
23799 				last = mp;
23800 			}
23801 			nmatch++;
23802 			if (exact)
23803 				break;
23804 		}
23805 
23806 		/* Avoid holding lock for too long. */
23807 		if (nmatch >= 500)
23808 			break;
23809 	}
23810 	mutex_exit(&connfp->connf_lock);
23811 
23812 	/* Pass mp into the correct tcp */
23813 	while ((mp = listhead) != NULL) {
23814 		listhead = listhead->b_next;
23815 		tcp = (tcp_t *)mp->b_prev;
23816 		mp->b_next = mp->b_prev = NULL;
23817 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
23818 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
23819 	}
23820 
23821 	*count += nmatch;
23822 	if (nmatch >= 500 && err == 0)
23823 		goto startover;
23824 	return (err);
23825 }
23826 
23827 /*
23828  * Abort all connections that matches the attributes specified in acp.
23829  */
23830 static int
23831 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
23832 {
23833 	sa_family_t af;
23834 	uint32_t  ports;
23835 	uint16_t *pports;
23836 	int err = 0, count = 0;
23837 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
23838 	int index = -1;
23839 	ushort_t logflags;
23840 
23841 	af = acp->ac_local.ss_family;
23842 
23843 	if (af == AF_INET) {
23844 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
23845 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
23846 			pports = (uint16_t *)&ports;
23847 			pports[1] = TCP_AC_V4LPORT(acp);
23848 			pports[0] = TCP_AC_V4RPORT(acp);
23849 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
23850 		}
23851 	} else {
23852 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
23853 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
23854 			pports = (uint16_t *)&ports;
23855 			pports[1] = TCP_AC_V6LPORT(acp);
23856 			pports[0] = TCP_AC_V6RPORT(acp);
23857 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
23858 		}
23859 	}
23860 
23861 	/*
23862 	 * For cases where remote addr, local port, and remote port are non-
23863 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
23864 	 */
23865 	if (index != -1) {
23866 		err = tcp_ioctl_abort_bucket(acp, index,
23867 			    &count, exact);
23868 	} else {
23869 		/*
23870 		 * loop through all entries for wildcard case
23871 		 */
23872 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
23873 			err = tcp_ioctl_abort_bucket(acp, index,
23874 			    &count, exact);
23875 			if (err != 0)
23876 				break;
23877 		}
23878 	}
23879 
23880 	logflags = SL_TRACE | SL_NOTE;
23881 	/*
23882 	 * Don't print this message to the console if the operation was done
23883 	 * to a non-global zone.
23884 	 */
23885 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23886 		logflags |= SL_CONSOLE;
23887 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
23888 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
23889 	if (err == 0 && count == 0)
23890 		err = ENOENT;
23891 	return (err);
23892 }
23893 
23894 /*
23895  * Process the TCP_IOC_ABORT_CONN ioctl request.
23896  */
23897 static void
23898 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
23899 {
23900 	int	err;
23901 	IOCP    iocp;
23902 	MBLKP   mp1;
23903 	sa_family_t laf, raf;
23904 	tcp_ioc_abort_conn_t *acp;
23905 	zone_t *zptr;
23906 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
23907 
23908 	iocp = (IOCP)mp->b_rptr;
23909 
23910 	if ((mp1 = mp->b_cont) == NULL ||
23911 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
23912 		err = EINVAL;
23913 		goto out;
23914 	}
23915 
23916 	/* check permissions */
23917 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
23918 		err = EPERM;
23919 		goto out;
23920 	}
23921 
23922 	if (mp1->b_cont != NULL) {
23923 		freemsg(mp1->b_cont);
23924 		mp1->b_cont = NULL;
23925 	}
23926 
23927 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
23928 	laf = acp->ac_local.ss_family;
23929 	raf = acp->ac_remote.ss_family;
23930 
23931 	/* check that a zone with the supplied zoneid exists */
23932 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
23933 		zptr = zone_find_by_id(zoneid);
23934 		if (zptr != NULL) {
23935 			zone_rele(zptr);
23936 		} else {
23937 			err = EINVAL;
23938 			goto out;
23939 		}
23940 	}
23941 
23942 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
23943 	    acp->ac_start > acp->ac_end || laf != raf ||
23944 	    (laf != AF_INET && laf != AF_INET6)) {
23945 		err = EINVAL;
23946 		goto out;
23947 	}
23948 
23949 	tcp_ioctl_abort_dump(acp);
23950 	err = tcp_ioctl_abort(acp);
23951 
23952 out:
23953 	if (mp1 != NULL) {
23954 		freemsg(mp1);
23955 		mp->b_cont = NULL;
23956 	}
23957 
23958 	if (err != 0)
23959 		miocnak(q, mp, 0, err);
23960 	else
23961 		miocack(q, mp, 0, 0);
23962 }
23963 
23964 /*
23965  * tcp_time_wait_processing() handles processing of incoming packets when
23966  * the tcp is in the TIME_WAIT state.
23967  * A TIME_WAIT tcp that has an associated open TCP stream is never put
23968  * on the time wait list.
23969  */
23970 void
23971 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
23972     uint32_t seg_ack, int seg_len, tcph_t *tcph)
23973 {
23974 	int32_t		bytes_acked;
23975 	int32_t		gap;
23976 	int32_t		rgap;
23977 	tcp_opt_t	tcpopt;
23978 	uint_t		flags;
23979 	uint32_t	new_swnd = 0;
23980 	conn_t		*connp;
23981 
23982 	BUMP_LOCAL(tcp->tcp_ibsegs);
23983 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
23984 
23985 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
23986 	new_swnd = BE16_TO_U16(tcph->th_win) <<
23987 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
23988 	if (tcp->tcp_snd_ts_ok) {
23989 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
23990 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
23991 			    tcp->tcp_rnxt, TH_ACK);
23992 			goto done;
23993 		}
23994 	}
23995 	gap = seg_seq - tcp->tcp_rnxt;
23996 	rgap = tcp->tcp_rwnd - (gap + seg_len);
23997 	if (gap < 0) {
23998 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
23999 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24000 		    (seg_len > -gap ? -gap : seg_len));
24001 		seg_len += gap;
24002 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24003 			if (flags & TH_RST) {
24004 				goto done;
24005 			}
24006 			if ((flags & TH_FIN) && seg_len == -1) {
24007 				/*
24008 				 * When TCP receives a duplicate FIN in
24009 				 * TIME_WAIT state, restart the 2 MSL timer.
24010 				 * See page 73 in RFC 793. Make sure this TCP
24011 				 * is already on the TIME_WAIT list. If not,
24012 				 * just restart the timer.
24013 				 */
24014 				if (TCP_IS_DETACHED(tcp)) {
24015 					tcp_time_wait_remove(tcp, NULL);
24016 					tcp_time_wait_append(tcp);
24017 					TCP_DBGSTAT(tcp_rput_time_wait);
24018 				} else {
24019 					ASSERT(tcp != NULL);
24020 					TCP_TIMER_RESTART(tcp,
24021 					    tcp_time_wait_interval);
24022 				}
24023 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24024 				    tcp->tcp_rnxt, TH_ACK);
24025 				goto done;
24026 			}
24027 			flags |=  TH_ACK_NEEDED;
24028 			seg_len = 0;
24029 			goto process_ack;
24030 		}
24031 
24032 		/* Fix seg_seq, and chew the gap off the front. */
24033 		seg_seq = tcp->tcp_rnxt;
24034 	}
24035 
24036 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24037 		/*
24038 		 * Make sure that when we accept the connection, pick
24039 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24040 		 * old connection.
24041 		 *
24042 		 * The next ISS generated is equal to tcp_iss_incr_extra
24043 		 * + ISS_INCR/2 + other components depending on the
24044 		 * value of tcp_strong_iss.  We pre-calculate the new
24045 		 * ISS here and compare with tcp_snxt to determine if
24046 		 * we need to make adjustment to tcp_iss_incr_extra.
24047 		 *
24048 		 * The above calculation is ugly and is a
24049 		 * waste of CPU cycles...
24050 		 */
24051 		uint32_t new_iss = tcp_iss_incr_extra;
24052 		int32_t adj;
24053 
24054 		switch (tcp_strong_iss) {
24055 		case 2: {
24056 			/* Add time and MD5 components. */
24057 			uint32_t answer[4];
24058 			struct {
24059 				uint32_t ports;
24060 				in6_addr_t src;
24061 				in6_addr_t dst;
24062 			} arg;
24063 			MD5_CTX context;
24064 
24065 			mutex_enter(&tcp_iss_key_lock);
24066 			context = tcp_iss_key;
24067 			mutex_exit(&tcp_iss_key_lock);
24068 			arg.ports = tcp->tcp_ports;
24069 			/* We use MAPPED addresses in tcp_iss_init */
24070 			arg.src = tcp->tcp_ip_src_v6;
24071 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24072 				IN6_IPADDR_TO_V4MAPPED(
24073 					tcp->tcp_ipha->ipha_dst,
24074 					    &arg.dst);
24075 			} else {
24076 				arg.dst =
24077 				    tcp->tcp_ip6h->ip6_dst;
24078 			}
24079 			MD5Update(&context, (uchar_t *)&arg,
24080 			    sizeof (arg));
24081 			MD5Final((uchar_t *)answer, &context);
24082 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24083 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24084 			break;
24085 		}
24086 		case 1:
24087 			/* Add time component and min random (i.e. 1). */
24088 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24089 			break;
24090 		default:
24091 			/* Add only time component. */
24092 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24093 			break;
24094 		}
24095 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24096 			/*
24097 			 * New ISS not guaranteed to be ISS_INCR/2
24098 			 * ahead of the current tcp_snxt, so add the
24099 			 * difference to tcp_iss_incr_extra.
24100 			 */
24101 			tcp_iss_incr_extra += adj;
24102 		}
24103 		/*
24104 		 * If tcp_clean_death() can not perform the task now,
24105 		 * drop the SYN packet and let the other side re-xmit.
24106 		 * Otherwise pass the SYN packet back in, since the
24107 		 * old tcp state has been cleaned up or freed.
24108 		 */
24109 		if (tcp_clean_death(tcp, 0, 27) == -1)
24110 			goto done;
24111 		/*
24112 		 * We will come back to tcp_rput_data
24113 		 * on the global queue. Packets destined
24114 		 * for the global queue will be checked
24115 		 * with global policy. But the policy for
24116 		 * this packet has already been checked as
24117 		 * this was destined for the detached
24118 		 * connection. We need to bypass policy
24119 		 * check this time by attaching a dummy
24120 		 * ipsec_in with ipsec_in_dont_check set.
24121 		 */
24122 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24123 		    NULL) {
24124 			TCP_STAT(tcp_time_wait_syn_success);
24125 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24126 			return;
24127 		}
24128 		goto done;
24129 	}
24130 
24131 	/*
24132 	 * rgap is the amount of stuff received out of window.  A negative
24133 	 * value is the amount out of window.
24134 	 */
24135 	if (rgap < 0) {
24136 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24137 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24138 		/* Fix seg_len and make sure there is something left. */
24139 		seg_len += rgap;
24140 		if (seg_len <= 0) {
24141 			if (flags & TH_RST) {
24142 				goto done;
24143 			}
24144 			flags |=  TH_ACK_NEEDED;
24145 			seg_len = 0;
24146 			goto process_ack;
24147 		}
24148 	}
24149 	/*
24150 	 * Check whether we can update tcp_ts_recent.  This test is
24151 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24152 	 * Extensions for High Performance: An Update", Internet Draft.
24153 	 */
24154 	if (tcp->tcp_snd_ts_ok &&
24155 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24156 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24157 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24158 		tcp->tcp_last_rcv_lbolt = lbolt64;
24159 	}
24160 
24161 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24162 		/* Always ack out of order packets */
24163 		flags |= TH_ACK_NEEDED;
24164 		seg_len = 0;
24165 	} else if (seg_len > 0) {
24166 		BUMP_MIB(&tcp_mib, tcpInClosed);
24167 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24168 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24169 	}
24170 	if (flags & TH_RST) {
24171 		(void) tcp_clean_death(tcp, 0, 28);
24172 		goto done;
24173 	}
24174 	if (flags & TH_SYN) {
24175 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24176 		    TH_RST|TH_ACK);
24177 		/*
24178 		 * Do not delete the TCP structure if it is in
24179 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24180 		 */
24181 		goto done;
24182 	}
24183 process_ack:
24184 	if (flags & TH_ACK) {
24185 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24186 		if (bytes_acked <= 0) {
24187 			if (bytes_acked == 0 && seg_len == 0 &&
24188 			    new_swnd == tcp->tcp_swnd)
24189 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24190 		} else {
24191 			/* Acks something not sent */
24192 			flags |= TH_ACK_NEEDED;
24193 		}
24194 	}
24195 	if (flags & TH_ACK_NEEDED) {
24196 		/*
24197 		 * Time to send an ack for some reason.
24198 		 */
24199 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24200 		    tcp->tcp_rnxt, TH_ACK);
24201 	}
24202 done:
24203 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24204 		DB_CKSUMSTART(mp) = 0;
24205 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24206 		TCP_STAT(tcp_time_wait_syn_fail);
24207 	}
24208 	freemsg(mp);
24209 }
24210 
24211 /*
24212  * Return zero if the buffers are identical in length and content.
24213  * This is used for comparing extension header buffers.
24214  * Note that an extension header would be declared different
24215  * even if all that changed was the next header value in that header i.e.
24216  * what really changed is the next extension header.
24217  */
24218 static boolean_t
24219 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24220 {
24221 	if (!b_valid)
24222 		blen = 0;
24223 
24224 	if (alen != blen)
24225 		return (B_TRUE);
24226 	if (alen == 0)
24227 		return (B_FALSE);	/* Both zero length */
24228 	return (bcmp(a, b, alen));
24229 }
24230 
24231 /*
24232  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24233  * Return B_FALSE if memory allocation fails - don't change any state!
24234  */
24235 static boolean_t
24236 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24237     void *src, uint_t srclen)
24238 {
24239 	void *dst;
24240 
24241 	if (!src_valid)
24242 		srclen = 0;
24243 
24244 	ASSERT(*dstlenp == 0);
24245 	if (src != NULL && srclen != 0) {
24246 		dst = mi_alloc(srclen, BPRI_MED);
24247 		if (dst == NULL)
24248 			return (B_FALSE);
24249 	} else {
24250 		dst = NULL;
24251 	}
24252 	if (*dstp != NULL) {
24253 		mi_free(*dstp);
24254 		*dstp = NULL;
24255 		*dstlenp = 0;
24256 	}
24257 	*dstp = dst;
24258 	if (dst != NULL)
24259 		*dstlenp = srclen;
24260 	else
24261 		*dstlenp = 0;
24262 	return (B_TRUE);
24263 }
24264 
24265 /*
24266  * Replace what is in *dst, *dstlen with the source.
24267  * Assumes tcp_allocbuf has already been called.
24268  */
24269 static void
24270 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24271     void *src, uint_t srclen)
24272 {
24273 	if (!src_valid)
24274 		srclen = 0;
24275 
24276 	ASSERT(*dstlenp == srclen);
24277 	if (src != NULL && srclen != 0) {
24278 		bcopy(src, *dstp, srclen);
24279 	}
24280 }
24281 
24282 /*
24283  * Allocate a T_SVR4_OPTMGMT_REQ.
24284  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24285  * that tcp_rput_other can drop the acks.
24286  */
24287 static mblk_t *
24288 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24289 {
24290 	mblk_t *mp;
24291 	struct T_optmgmt_req *tor;
24292 	struct opthdr *oh;
24293 	uint_t size;
24294 	char *optptr;
24295 
24296 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24297 	mp = allocb(size, BPRI_MED);
24298 	if (mp == NULL)
24299 		return (NULL);
24300 
24301 	mp->b_wptr += size;
24302 	mp->b_datap->db_type = M_PROTO;
24303 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24304 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24305 	tor->MGMT_flags = T_NEGOTIATE;
24306 	tor->OPT_length = sizeof (*oh) + optlen;
24307 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24308 
24309 	oh = (struct opthdr *)&tor[1];
24310 	oh->level = level;
24311 	oh->name = cmd;
24312 	oh->len = optlen;
24313 	if (optlen != 0) {
24314 		optptr = (char *)&oh[1];
24315 		bcopy(opt, optptr, optlen);
24316 	}
24317 	return (mp);
24318 }
24319 
24320 /*
24321  * TCP Timers Implementation.
24322  */
24323 timeout_id_t
24324 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24325 {
24326 	mblk_t *mp;
24327 	tcp_timer_t *tcpt;
24328 	tcp_t *tcp = connp->conn_tcp;
24329 
24330 	ASSERT(connp->conn_sqp != NULL);
24331 
24332 	TCP_DBGSTAT(tcp_timeout_calls);
24333 
24334 	if (tcp->tcp_timercache == NULL) {
24335 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24336 	} else {
24337 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24338 		mp = tcp->tcp_timercache;
24339 		tcp->tcp_timercache = mp->b_next;
24340 		mp->b_next = NULL;
24341 		ASSERT(mp->b_wptr == NULL);
24342 	}
24343 
24344 	CONN_INC_REF(connp);
24345 	tcpt = (tcp_timer_t *)mp->b_rptr;
24346 	tcpt->connp = connp;
24347 	tcpt->tcpt_proc = f;
24348 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24349 	return ((timeout_id_t)mp);
24350 }
24351 
24352 static void
24353 tcp_timer_callback(void *arg)
24354 {
24355 	mblk_t *mp = (mblk_t *)arg;
24356 	tcp_timer_t *tcpt;
24357 	conn_t	*connp;
24358 
24359 	tcpt = (tcp_timer_t *)mp->b_rptr;
24360 	connp = tcpt->connp;
24361 	squeue_fill(connp->conn_sqp, mp,
24362 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24363 }
24364 
24365 static void
24366 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24367 {
24368 	tcp_timer_t *tcpt;
24369 	conn_t *connp = (conn_t *)arg;
24370 	tcp_t *tcp = connp->conn_tcp;
24371 
24372 	tcpt = (tcp_timer_t *)mp->b_rptr;
24373 	ASSERT(connp == tcpt->connp);
24374 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24375 
24376 	/*
24377 	 * If the TCP has reached the closed state, don't proceed any
24378 	 * further. This TCP logically does not exist on the system.
24379 	 * tcpt_proc could for example access queues, that have already
24380 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24381 	 */
24382 	if (tcp->tcp_state != TCPS_CLOSED) {
24383 		(*tcpt->tcpt_proc)(connp);
24384 	} else {
24385 		tcp->tcp_timer_tid = 0;
24386 	}
24387 	tcp_timer_free(connp->conn_tcp, mp);
24388 }
24389 
24390 /*
24391  * There is potential race with untimeout and the handler firing at the same
24392  * time. The mblock may be freed by the handler while we are trying to use
24393  * it. But since both should execute on the same squeue, this race should not
24394  * occur.
24395  */
24396 clock_t
24397 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24398 {
24399 	mblk_t	*mp = (mblk_t *)id;
24400 	tcp_timer_t *tcpt;
24401 	clock_t delta;
24402 
24403 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24404 
24405 	if (mp == NULL)
24406 		return (-1);
24407 
24408 	tcpt = (tcp_timer_t *)mp->b_rptr;
24409 	ASSERT(tcpt->connp == connp);
24410 
24411 	delta = untimeout(tcpt->tcpt_tid);
24412 
24413 	if (delta >= 0) {
24414 		TCP_DBGSTAT(tcp_timeout_canceled);
24415 		tcp_timer_free(connp->conn_tcp, mp);
24416 		CONN_DEC_REF(connp);
24417 	}
24418 
24419 	return (delta);
24420 }
24421 
24422 /*
24423  * Allocate space for the timer event. The allocation looks like mblk, but it is
24424  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24425  *
24426  * Dealing with failures: If we can't allocate from the timer cache we try
24427  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24428  * points to b_rptr.
24429  * If we can't allocate anything using allocb_tryhard(), we perform a last
24430  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24431  * save the actual allocation size in b_datap.
24432  */
24433 mblk_t *
24434 tcp_timermp_alloc(int kmflags)
24435 {
24436 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24437 	    kmflags & ~KM_PANIC);
24438 
24439 	if (mp != NULL) {
24440 		mp->b_next = mp->b_prev = NULL;
24441 		mp->b_rptr = (uchar_t *)(&mp[1]);
24442 		mp->b_wptr = NULL;
24443 		mp->b_datap = NULL;
24444 		mp->b_queue = NULL;
24445 	} else if (kmflags & KM_PANIC) {
24446 		/*
24447 		 * Failed to allocate memory for the timer. Try allocating from
24448 		 * dblock caches.
24449 		 */
24450 		TCP_STAT(tcp_timermp_allocfail);
24451 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24452 		if (mp == NULL) {
24453 			size_t size = 0;
24454 			/*
24455 			 * Memory is really low. Try tryhard allocation.
24456 			 */
24457 			TCP_STAT(tcp_timermp_allocdblfail);
24458 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24459 			    sizeof (tcp_timer_t), &size, kmflags);
24460 			mp->b_rptr = (uchar_t *)(&mp[1]);
24461 			mp->b_next = mp->b_prev = NULL;
24462 			mp->b_wptr = (uchar_t *)-1;
24463 			mp->b_datap = (dblk_t *)size;
24464 			mp->b_queue = NULL;
24465 		}
24466 		ASSERT(mp->b_wptr != NULL);
24467 	}
24468 	TCP_DBGSTAT(tcp_timermp_alloced);
24469 
24470 	return (mp);
24471 }
24472 
24473 /*
24474  * Free per-tcp timer cache.
24475  * It can only contain entries from tcp_timercache.
24476  */
24477 void
24478 tcp_timermp_free(tcp_t *tcp)
24479 {
24480 	mblk_t *mp;
24481 
24482 	while ((mp = tcp->tcp_timercache) != NULL) {
24483 		ASSERT(mp->b_wptr == NULL);
24484 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24485 		kmem_cache_free(tcp_timercache, mp);
24486 	}
24487 }
24488 
24489 /*
24490  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24491  * events there already (currently at most two events are cached).
24492  * If the event is not allocated from the timer cache, free it right away.
24493  */
24494 static void
24495 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24496 {
24497 	mblk_t *mp1 = tcp->tcp_timercache;
24498 
24499 	if (mp->b_wptr != NULL) {
24500 		/*
24501 		 * This allocation is not from a timer cache, free it right
24502 		 * away.
24503 		 */
24504 		if (mp->b_wptr != (uchar_t *)-1)
24505 			freeb(mp);
24506 		else
24507 			kmem_free(mp, (size_t)mp->b_datap);
24508 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24509 		/* Cache this timer block for future allocations */
24510 		mp->b_rptr = (uchar_t *)(&mp[1]);
24511 		mp->b_next = mp1;
24512 		tcp->tcp_timercache = mp;
24513 	} else {
24514 		kmem_cache_free(tcp_timercache, mp);
24515 		TCP_DBGSTAT(tcp_timermp_freed);
24516 	}
24517 }
24518 
24519 /*
24520  * End of TCP Timers implementation.
24521  */
24522 
24523 /*
24524  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24525  * on the specified backing STREAMS q. Note, the caller may make the
24526  * decision to call based on the tcp_t.tcp_flow_stopped value which
24527  * when check outside the q's lock is only an advisory check ...
24528  */
24529 
24530 void
24531 tcp_setqfull(tcp_t *tcp)
24532 {
24533 	queue_t *q = tcp->tcp_wq;
24534 
24535 	if (!(q->q_flag & QFULL)) {
24536 		mutex_enter(QLOCK(q));
24537 		if (!(q->q_flag & QFULL)) {
24538 			/* still need to set QFULL */
24539 			q->q_flag |= QFULL;
24540 			tcp->tcp_flow_stopped = B_TRUE;
24541 			mutex_exit(QLOCK(q));
24542 			TCP_STAT(tcp_flwctl_on);
24543 		} else {
24544 			mutex_exit(QLOCK(q));
24545 		}
24546 	}
24547 }
24548 
24549 void
24550 tcp_clrqfull(tcp_t *tcp)
24551 {
24552 	queue_t *q = tcp->tcp_wq;
24553 
24554 	if (q->q_flag & QFULL) {
24555 		mutex_enter(QLOCK(q));
24556 		if (q->q_flag & QFULL) {
24557 			q->q_flag &= ~QFULL;
24558 			tcp->tcp_flow_stopped = B_FALSE;
24559 			mutex_exit(QLOCK(q));
24560 			if (q->q_flag & QWANTW)
24561 				qbackenable(q, 0);
24562 		} else {
24563 			mutex_exit(QLOCK(q));
24564 		}
24565 	}
24566 }
24567 
24568 /*
24569  * TCP Kstats implementation
24570  */
24571 static void
24572 tcp_kstat_init(void)
24573 {
24574 	tcp_named_kstat_t template = {
24575 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24576 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24577 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24578 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24579 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24580 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24581 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24582 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24583 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24584 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24585 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24586 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24587 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24588 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24589 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24590 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24591 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24592 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24593 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24594 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24595 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24596 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24597 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24598 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24599 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24600 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24601 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24602 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24603 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24604 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24605 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24606 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24607 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24608 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24609 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24610 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24611 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24612 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24613 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24614 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24615 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24616 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24617 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24618 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24619 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24620 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24621 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24622 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24623 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24624 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24625 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24626 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24627 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24628 	};
24629 
24630 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24631 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24632 
24633 	if (tcp_mibkp == NULL)
24634 		return;
24635 
24636 	template.rtoAlgorithm.value.ui32 = 4;
24637 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24638 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24639 	template.maxConn.value.i32 = -1;
24640 
24641 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24642 
24643 	tcp_mibkp->ks_update = tcp_kstat_update;
24644 
24645 	kstat_install(tcp_mibkp);
24646 }
24647 
24648 static void
24649 tcp_kstat_fini(void)
24650 {
24651 
24652 	if (tcp_mibkp != NULL) {
24653 		kstat_delete(tcp_mibkp);
24654 		tcp_mibkp = NULL;
24655 	}
24656 }
24657 
24658 static int
24659 tcp_kstat_update(kstat_t *kp, int rw)
24660 {
24661 	tcp_named_kstat_t	*tcpkp;
24662 	tcp_t			*tcp;
24663 	connf_t			*connfp;
24664 	conn_t			*connp;
24665 	int 			i;
24666 
24667 	if (!kp || !kp->ks_data)
24668 		return (EIO);
24669 
24670 	if (rw == KSTAT_WRITE)
24671 		return (EACCES);
24672 
24673 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24674 
24675 	tcpkp->currEstab.value.ui32 = 0;
24676 
24677 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24678 		connfp = &ipcl_globalhash_fanout[i];
24679 		connp = NULL;
24680 		while ((connp =
24681 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24682 			tcp = connp->conn_tcp;
24683 			switch (tcp_snmp_state(tcp)) {
24684 			case MIB2_TCP_established:
24685 			case MIB2_TCP_closeWait:
24686 				tcpkp->currEstab.value.ui32++;
24687 				break;
24688 			}
24689 		}
24690 	}
24691 
24692 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24693 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24694 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24695 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24696 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24697 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24698 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24699 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24700 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24701 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24702 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24703 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24704 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24705 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24706 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24707 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24708 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24709 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24710 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
24711 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
24712 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
24713 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
24714 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
24715 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
24716 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
24717 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
24718 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
24719 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
24720 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
24721 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
24722 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
24723 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
24724 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
24725 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
24726 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
24727 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
24728 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
24729 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
24730 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
24731 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
24732 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
24733 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
24734 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
24735 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
24736 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
24737 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
24738 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
24739 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
24740 
24741 	return (0);
24742 }
24743 
24744 void
24745 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
24746 {
24747 	uint16_t	hdr_len;
24748 	ipha_t		*ipha;
24749 	uint8_t		*nexthdrp;
24750 	tcph_t		*tcph;
24751 
24752 	/* Already has an eager */
24753 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24754 		TCP_STAT(tcp_reinput_syn);
24755 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
24756 		    connp, SQTAG_TCP_REINPUT_EAGER);
24757 		return;
24758 	}
24759 
24760 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
24761 	case IPV4_VERSION:
24762 		ipha = (ipha_t *)mp->b_rptr;
24763 		hdr_len = IPH_HDR_LENGTH(ipha);
24764 		break;
24765 	case IPV6_VERSION:
24766 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
24767 		    &hdr_len, &nexthdrp)) {
24768 			CONN_DEC_REF(connp);
24769 			freemsg(mp);
24770 			return;
24771 		}
24772 		break;
24773 	}
24774 
24775 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
24776 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
24777 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
24778 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
24779 	}
24780 
24781 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
24782 	    SQTAG_TCP_REINPUT);
24783 }
24784 
24785 static squeue_func_t
24786 tcp_squeue_switch(int val)
24787 {
24788 	squeue_func_t rval = squeue_fill;
24789 
24790 	switch (val) {
24791 	case 1:
24792 		rval = squeue_enter_nodrain;
24793 		break;
24794 	case 2:
24795 		rval = squeue_enter;
24796 		break;
24797 	default:
24798 		break;
24799 	}
24800 	return (rval);
24801 }
24802 
24803 static void
24804 tcp_squeue_add(squeue_t *sqp)
24805 {
24806 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
24807 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
24808 
24809 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
24810 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
24811 	    sqp, TCP_TIME_WAIT_DELAY);
24812 	if (tcp_free_list_max_cnt == 0) {
24813 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
24814 			max_ncpus : boot_max_ncpus);
24815 
24816 		/*
24817 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
24818 		 */
24819 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
24820 			(tcp_ncpus * sizeof (tcp_t) * 100);
24821 	}
24822 	tcp_time_wait->tcp_free_list_cnt = 0;
24823 }
24824