xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision 06e46062ef4f5f4b687cbafb4518fb123fe23920)
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[] = "@(#)tcp.c	1.490	05/11/29 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 = NULL;
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 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2491 		 * for the destination with the nexthop as gateway.
2492 		 * ire_ctable_lookup() is used because this particular
2493 		 * ire, if it exists, will be marked private.
2494 		 * If that is not available, use the interface ire
2495 		 * for the nexthop.
2496 		 */
2497 		if (tcp->tcp_connp->conn_nexthop_set) {
2498 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2499 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2500 			    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2501 			if (ire == NULL) {
2502 				ire = ire_ftable_lookup(
2503 				    tcp->tcp_connp->conn_nexthop_v4,
2504 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2505 				    MATCH_IRE_TYPE);
2506 				if (ire == NULL)
2507 					return (0);
2508 			} else {
2509 				ire_uinfo = &ire->ire_uinfo;
2510 			}
2511 		} else {
2512 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2513 			    zoneid);
2514 			if (ire != NULL) {
2515 				ire_cacheable = B_TRUE;
2516 				ire_uinfo = (ire_mp != NULL) ?
2517 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2518 				    &ire->ire_uinfo;
2519 
2520 			} else {
2521 				if (ire_mp == NULL) {
2522 					ire = ire_ftable_lookup(
2523 					    tcp->tcp_connp->conn_rem,
2524 					    0, 0, 0, NULL, &sire, zoneid, 0,
2525 					    (MATCH_IRE_RECURSIVE |
2526 					    MATCH_IRE_DEFAULT));
2527 					if (ire == NULL)
2528 						return (0);
2529 					ire_uinfo = (sire != NULL) ?
2530 					    &sire->ire_uinfo :
2531 					    &ire->ire_uinfo;
2532 				} else {
2533 					ire = (ire_t *)ire_mp->b_rptr;
2534 					ire_uinfo =
2535 					    &((ire_t *)
2536 					    ire_mp->b_rptr)->ire_uinfo;
2537 				}
2538 			}
2539 		}
2540 		ASSERT(ire != NULL);
2541 
2542 		if ((ire->ire_src_addr == INADDR_ANY) ||
2543 		    (ire->ire_type & IRE_BROADCAST)) {
2544 			/*
2545 			 * ire->ire_mp is non null when ire_mp passed in is used
2546 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2547 			 */
2548 			if (ire->ire_mp == NULL)
2549 				ire_refrele(ire);
2550 			if (sire != NULL)
2551 				ire_refrele(sire);
2552 			return (0);
2553 		}
2554 
2555 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2556 			ipaddr_t src_addr;
2557 
2558 			/*
2559 			 * ip_bind_connected() has stored the correct source
2560 			 * address in conn_src.
2561 			 */
2562 			src_addr = tcp->tcp_connp->conn_src;
2563 			tcp->tcp_ipha->ipha_src = src_addr;
2564 			/*
2565 			 * Copy of the src addr. in tcp_t is needed
2566 			 * for the lookup funcs.
2567 			 */
2568 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2569 		}
2570 		/*
2571 		 * Set the fragment bit so that IP will tell us if the MTU
2572 		 * should change. IP tells us the latest setting of
2573 		 * ip_path_mtu_discovery through ire_frag_flag.
2574 		 */
2575 		if (ip_path_mtu_discovery) {
2576 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2577 			    htons(IPH_DF);
2578 		}
2579 		/*
2580 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2581 		 * for IP_NEXTHOP. No cache ire has been found for the
2582 		 * destination and we are working with the nexthop's
2583 		 * interface ire. Since we need to forward all packets
2584 		 * to the nexthop first, we "blindly" set tcp_localnet
2585 		 * to false, eventhough the destination may also be
2586 		 * onlink.
2587 		 */
2588 		if (ire_uinfo == NULL)
2589 			tcp->tcp_localnet = 0;
2590 		else
2591 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2592 	} else {
2593 		/*
2594 		 * For incoming connection ire_mp = NULL
2595 		 * For outgoing connection ire_mp != NULL
2596 		 * Technically we should check conn_incoming_ill
2597 		 * when ire_mp is NULL and conn_outgoing_ill when
2598 		 * ire_mp is non-NULL. But this is performance
2599 		 * critical path and for IPV*_BOUND_IF, outgoing
2600 		 * and incoming ill are always set to the same value.
2601 		 */
2602 		ill_t	*dst_ill = NULL;
2603 		ipif_t  *dst_ipif = NULL;
2604 		int match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT;
2605 
2606 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2607 
2608 		if (connp->conn_outgoing_ill != NULL) {
2609 			/* Outgoing or incoming path */
2610 			int   err;
2611 
2612 			dst_ill = conn_get_held_ill(connp,
2613 			    &connp->conn_outgoing_ill, &err);
2614 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2615 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2616 				return (0);
2617 			}
2618 			match_flags |= MATCH_IRE_ILL;
2619 			dst_ipif = dst_ill->ill_ipif;
2620 		}
2621 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2622 		    0, 0, dst_ipif, zoneid, match_flags);
2623 
2624 		if (ire != NULL) {
2625 			ire_cacheable = B_TRUE;
2626 			ire_uinfo = (ire_mp != NULL) ?
2627 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2628 			    &ire->ire_uinfo;
2629 		} else {
2630 			if (ire_mp == NULL) {
2631 				ire = ire_ftable_lookup_v6(
2632 				    &tcp->tcp_connp->conn_remv6,
2633 				    0, 0, 0, dst_ipif, &sire, zoneid,
2634 				    0, match_flags);
2635 				if (ire == NULL) {
2636 					if (dst_ill != NULL)
2637 						ill_refrele(dst_ill);
2638 					return (0);
2639 				}
2640 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2641 				    &ire->ire_uinfo;
2642 			} else {
2643 				ire = (ire_t *)ire_mp->b_rptr;
2644 				ire_uinfo =
2645 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2646 			}
2647 		}
2648 		if (dst_ill != NULL)
2649 			ill_refrele(dst_ill);
2650 
2651 		ASSERT(ire != NULL);
2652 		ASSERT(ire_uinfo != NULL);
2653 
2654 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2655 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2656 			/*
2657 			 * ire->ire_mp is non null when ire_mp passed in is used
2658 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2659 			 */
2660 			if (ire->ire_mp == NULL)
2661 				ire_refrele(ire);
2662 			if (sire != NULL)
2663 				ire_refrele(sire);
2664 			return (0);
2665 		}
2666 
2667 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2668 			in6_addr_t	src_addr;
2669 
2670 			/*
2671 			 * ip_bind_connected_v6() has stored the correct source
2672 			 * address per IPv6 addr. selection policy in
2673 			 * conn_src_v6.
2674 			 */
2675 			src_addr = tcp->tcp_connp->conn_srcv6;
2676 
2677 			tcp->tcp_ip6h->ip6_src = src_addr;
2678 			/*
2679 			 * Copy of the src addr. in tcp_t is needed
2680 			 * for the lookup funcs.
2681 			 */
2682 			tcp->tcp_ip_src_v6 = src_addr;
2683 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2684 			    &connp->conn_srcv6));
2685 		}
2686 		tcp->tcp_localnet =
2687 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2688 	}
2689 
2690 	/*
2691 	 * This allows applications to fail quickly when connections are made
2692 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2693 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2694 	 */
2695 	if ((ire->ire_flags & RTF_REJECT) &&
2696 	    (ire->ire_flags & RTF_PRIVATE))
2697 		goto error;
2698 
2699 	/*
2700 	 * Make use of the cached rtt and rtt_sd values to calculate the
2701 	 * initial RTO.  Note that they are already initialized in
2702 	 * tcp_init_values().
2703 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2704 	 * IP_NEXTHOP, but instead are using the interface ire for the
2705 	 * nexthop, then we do not use the ire_uinfo from that ire to
2706 	 * do any initializations.
2707 	 */
2708 	if (ire_uinfo != NULL) {
2709 		if (ire_uinfo->iulp_rtt != 0) {
2710 			clock_t	rto;
2711 
2712 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2713 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2714 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2715 			    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5);
2716 
2717 			if (rto > tcp_rexmit_interval_max) {
2718 				tcp->tcp_rto = tcp_rexmit_interval_max;
2719 			} else if (rto < tcp_rexmit_interval_min) {
2720 				tcp->tcp_rto = tcp_rexmit_interval_min;
2721 			} else {
2722 				tcp->tcp_rto = rto;
2723 			}
2724 		}
2725 		if (ire_uinfo->iulp_ssthresh != 0)
2726 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2727 		else
2728 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2729 		if (ire_uinfo->iulp_spipe > 0) {
2730 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2731 			    tcp_max_buf);
2732 			if (tcp_snd_lowat_fraction != 0)
2733 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2734 				    tcp_snd_lowat_fraction;
2735 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2736 		}
2737 		/*
2738 		 * Note that up till now, acceptor always inherits receive
2739 		 * window from the listener.  But if there is a metrics
2740 		 * associated with a host, we should use that instead of
2741 		 * inheriting it from listener. Thus we need to pass this
2742 		 * info back to the caller.
2743 		 */
2744 		if (ire_uinfo->iulp_rpipe > 0) {
2745 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe, tcp_max_buf);
2746 		}
2747 
2748 		if (ire_uinfo->iulp_rtomax > 0) {
2749 			tcp->tcp_second_timer_threshold =
2750 			    ire_uinfo->iulp_rtomax;
2751 		}
2752 
2753 		/*
2754 		 * Use the metric option settings, iulp_tstamp_ok and
2755 		 * iulp_wscale_ok, only for active open. What this means
2756 		 * is that if the other side uses timestamp or window
2757 		 * scale option, TCP will also use those options. That
2758 		 * is for passive open.  If the application sets a
2759 		 * large window, window scale is enabled regardless of
2760 		 * the value in iulp_wscale_ok.  This is the behavior
2761 		 * since 2.6.  So we keep it.
2762 		 * The only case left in passive open processing is the
2763 		 * check for SACK.
2764 		 * For ECN, it should probably be like SACK.  But the
2765 		 * current value is binary, so we treat it like the other
2766 		 * cases.  The metric only controls active open.For passive
2767 		 * open, the ndd param, tcp_ecn_permitted, controls the
2768 		 * behavior.
2769 		 */
2770 		if (!tcp_detached) {
2771 			/*
2772 			 * The if check means that the following can only
2773 			 * be turned on by the metrics only IRE, but not off.
2774 			 */
2775 			if (ire_uinfo->iulp_tstamp_ok)
2776 				tcp->tcp_snd_ts_ok = B_TRUE;
2777 			if (ire_uinfo->iulp_wscale_ok)
2778 				tcp->tcp_snd_ws_ok = B_TRUE;
2779 			if (ire_uinfo->iulp_sack == 2)
2780 				tcp->tcp_snd_sack_ok = B_TRUE;
2781 			if (ire_uinfo->iulp_ecn_ok)
2782 				tcp->tcp_ecn_ok = B_TRUE;
2783 		} else {
2784 			/*
2785 			 * Passive open.
2786 			 *
2787 			 * As above, the if check means that SACK can only be
2788 			 * turned on by the metric only IRE.
2789 			 */
2790 			if (ire_uinfo->iulp_sack > 0) {
2791 				tcp->tcp_snd_sack_ok = B_TRUE;
2792 			}
2793 		}
2794 	}
2795 
2796 
2797 	/*
2798 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2799 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2800 	 * length of all those options exceeds 28 bytes.  But because
2801 	 * of the tcp_mss_min check below, we may not have a problem if
2802 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2803 	 * the negative problem still exists.  And the check defeats PMTUd.
2804 	 * In fact, if PMTUd finds that the MSS should be smaller than
2805 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2806 	 * value.
2807 	 *
2808 	 * We do not deal with that now.  All those problems related to
2809 	 * PMTUd will be fixed later.
2810 	 */
2811 	ASSERT(ire->ire_max_frag != 0);
2812 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2813 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2814 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2815 			mss = MIN(mss, IPV6_MIN_MTU);
2816 		}
2817 	}
2818 
2819 	/* Sanity check for MSS value. */
2820 	if (tcp->tcp_ipversion == IPV4_VERSION)
2821 		mss_max = tcp_mss_max_ipv4;
2822 	else
2823 		mss_max = tcp_mss_max_ipv6;
2824 
2825 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2826 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2827 		/*
2828 		 * After receiving an ICMPv6 "packet too big" message with a
2829 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2830 		 * will insert a 8-byte fragment header in every packet; we
2831 		 * reduce the MSS by that amount here.
2832 		 */
2833 		mss -= sizeof (ip6_frag_t);
2834 	}
2835 
2836 	if (tcp->tcp_ipsec_overhead == 0)
2837 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2838 
2839 	mss -= tcp->tcp_ipsec_overhead;
2840 
2841 	if (mss < tcp_mss_min)
2842 		mss = tcp_mss_min;
2843 	if (mss > mss_max)
2844 		mss = mss_max;
2845 
2846 	/* Note that this is the maximum MSS, excluding all options. */
2847 	tcp->tcp_mss = mss;
2848 
2849 	/*
2850 	 * Initialize the ISS here now that we have the full connection ID.
2851 	 * The RFC 1948 method of initial sequence number generation requires
2852 	 * knowledge of the full connection ID before setting the ISS.
2853 	 */
2854 
2855 	tcp_iss_init(tcp);
2856 
2857 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2858 		tcp->tcp_loopback = B_TRUE;
2859 
2860 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2861 		hsp = tcp_hsp_lookup(tcp->tcp_remote);
2862 	} else {
2863 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6);
2864 	}
2865 
2866 	if (hsp != NULL) {
2867 		/* Only modify if we're going to make them bigger */
2868 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2869 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2870 			if (tcp_snd_lowat_fraction != 0)
2871 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2872 					tcp_snd_lowat_fraction;
2873 		}
2874 
2875 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2876 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2877 		}
2878 
2879 		/* Copy timestamp flag only for active open */
2880 		if (!tcp_detached)
2881 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2882 	}
2883 
2884 	if (sire != NULL)
2885 		IRE_REFRELE(sire);
2886 
2887 	/*
2888 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2889 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2890 	 */
2891 	if (tcp->tcp_loopback ||
2892 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2893 		/*
2894 		 * For incoming, see if this tcp may be MDT-capable.  For
2895 		 * outgoing, this process has been taken care of through
2896 		 * tcp_rput_other.
2897 		 */
2898 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2899 		tcp->tcp_ire_ill_check_done = B_TRUE;
2900 	}
2901 
2902 	mutex_enter(&connp->conn_lock);
2903 	/*
2904 	 * Make sure that conn is not marked incipient
2905 	 * for incoming connections. A blind
2906 	 * removal of incipient flag is cheaper than
2907 	 * check and removal.
2908 	 */
2909 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2910 
2911 	/* Must not cache forwarding table routes. */
2912 	if (ire_cacheable) {
2913 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2914 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2915 			connp->conn_ire_cache = ire;
2916 			IRE_UNTRACE_REF(ire);
2917 			rw_exit(&ire->ire_bucket->irb_lock);
2918 			mutex_exit(&connp->conn_lock);
2919 			return (1);
2920 		}
2921 		rw_exit(&ire->ire_bucket->irb_lock);
2922 	}
2923 	mutex_exit(&connp->conn_lock);
2924 
2925 	if (ire->ire_mp == NULL)
2926 		ire_refrele(ire);
2927 	return (1);
2928 
2929 error:
2930 	if (ire->ire_mp == NULL)
2931 		ire_refrele(ire);
2932 	if (sire != NULL)
2933 		ire_refrele(sire);
2934 	return (0);
2935 }
2936 
2937 /*
2938  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2939  * O_T_BIND_REQ/T_BIND_REQ message.
2940  */
2941 static void
2942 tcp_bind(tcp_t *tcp, mblk_t *mp)
2943 {
2944 	sin_t	*sin;
2945 	sin6_t	*sin6;
2946 	mblk_t	*mp1;
2947 	in_port_t requested_port;
2948 	in_port_t allocated_port;
2949 	struct T_bind_req *tbr;
2950 	boolean_t	bind_to_req_port_only;
2951 	boolean_t	backlog_update = B_FALSE;
2952 	boolean_t	user_specified;
2953 	in6_addr_t	v6addr;
2954 	ipaddr_t	v4addr;
2955 	uint_t	origipversion;
2956 	int	err;
2957 	queue_t *q = tcp->tcp_wq;
2958 
2959 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2960 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2961 		if (tcp->tcp_debug) {
2962 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2963 			    "tcp_bind: bad req, len %u",
2964 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2965 		}
2966 		tcp_err_ack(tcp, mp, TPROTO, 0);
2967 		return;
2968 	}
2969 	/* Make sure the largest address fits */
2970 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
2971 	if (mp1 == NULL) {
2972 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2973 		return;
2974 	}
2975 	mp = mp1;
2976 	tbr = (struct T_bind_req *)mp->b_rptr;
2977 	if (tcp->tcp_state >= TCPS_BOUND) {
2978 		if ((tcp->tcp_state == TCPS_BOUND ||
2979 		    tcp->tcp_state == TCPS_LISTEN) &&
2980 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
2981 		    tbr->CONIND_number > 0) {
2982 			/*
2983 			 * Handle listen() increasing CONIND_number.
2984 			 * This is more "liberal" then what the TPI spec
2985 			 * requires but is needed to avoid a t_unbind
2986 			 * when handling listen() since the port number
2987 			 * might be "stolen" between the unbind and bind.
2988 			 */
2989 			backlog_update = B_TRUE;
2990 			goto do_bind;
2991 		}
2992 		if (tcp->tcp_debug) {
2993 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2994 			    "tcp_bind: bad state, %d", tcp->tcp_state);
2995 		}
2996 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
2997 		return;
2998 	}
2999 	origipversion = tcp->tcp_ipversion;
3000 
3001 	switch (tbr->ADDR_length) {
3002 	case 0:			/* request for a generic port */
3003 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3004 		if (tcp->tcp_family == AF_INET) {
3005 			tbr->ADDR_length = sizeof (sin_t);
3006 			sin = (sin_t *)&tbr[1];
3007 			*sin = sin_null;
3008 			sin->sin_family = AF_INET;
3009 			mp->b_wptr = (uchar_t *)&sin[1];
3010 			tcp->tcp_ipversion = IPV4_VERSION;
3011 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3012 		} else {
3013 			ASSERT(tcp->tcp_family == AF_INET6);
3014 			tbr->ADDR_length = sizeof (sin6_t);
3015 			sin6 = (sin6_t *)&tbr[1];
3016 			*sin6 = sin6_null;
3017 			sin6->sin6_family = AF_INET6;
3018 			mp->b_wptr = (uchar_t *)&sin6[1];
3019 			tcp->tcp_ipversion = IPV6_VERSION;
3020 			V6_SET_ZERO(v6addr);
3021 		}
3022 		requested_port = 0;
3023 		break;
3024 
3025 	case sizeof (sin_t):	/* Complete IPv4 address */
3026 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3027 		    sizeof (sin_t));
3028 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3029 			if (tcp->tcp_debug) {
3030 				(void) strlog(TCP_MOD_ID, 0, 1,
3031 				    SL_ERROR|SL_TRACE,
3032 				    "tcp_bind: bad address parameter, "
3033 				    "offset %d, len %d",
3034 				    tbr->ADDR_offset, tbr->ADDR_length);
3035 			}
3036 			tcp_err_ack(tcp, mp, TPROTO, 0);
3037 			return;
3038 		}
3039 		/*
3040 		 * With sockets sockfs will accept bogus sin_family in
3041 		 * bind() and replace it with the family used in the socket
3042 		 * call.
3043 		 */
3044 		if (sin->sin_family != AF_INET ||
3045 		    tcp->tcp_family != AF_INET) {
3046 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3047 			return;
3048 		}
3049 		requested_port = ntohs(sin->sin_port);
3050 		tcp->tcp_ipversion = IPV4_VERSION;
3051 		v4addr = sin->sin_addr.s_addr;
3052 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3053 		break;
3054 
3055 	case sizeof (sin6_t): /* Complete IPv6 address */
3056 		sin6 = (sin6_t *)mi_offset_param(mp,
3057 		    tbr->ADDR_offset, sizeof (sin6_t));
3058 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3059 			if (tcp->tcp_debug) {
3060 				(void) strlog(TCP_MOD_ID, 0, 1,
3061 				    SL_ERROR|SL_TRACE,
3062 				    "tcp_bind: bad IPv6 address parameter, "
3063 				    "offset %d, len %d", tbr->ADDR_offset,
3064 				    tbr->ADDR_length);
3065 			}
3066 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3067 			return;
3068 		}
3069 		if (sin6->sin6_family != AF_INET6 ||
3070 		    tcp->tcp_family != AF_INET6) {
3071 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3072 			return;
3073 		}
3074 		requested_port = ntohs(sin6->sin6_port);
3075 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3076 		    IPV4_VERSION : IPV6_VERSION;
3077 		v6addr = sin6->sin6_addr;
3078 		break;
3079 
3080 	default:
3081 		if (tcp->tcp_debug) {
3082 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3083 			    "tcp_bind: bad address length, %d",
3084 			    tbr->ADDR_length);
3085 		}
3086 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3087 		return;
3088 	}
3089 	tcp->tcp_bound_source_v6 = v6addr;
3090 
3091 	/* Check for change in ipversion */
3092 	if (origipversion != tcp->tcp_ipversion) {
3093 		ASSERT(tcp->tcp_family == AF_INET6);
3094 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3095 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3096 		if (err) {
3097 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3098 			return;
3099 		}
3100 	}
3101 
3102 	/*
3103 	 * Initialize family specific fields. Copy of the src addr.
3104 	 * in tcp_t is needed for the lookup funcs.
3105 	 */
3106 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3107 		tcp->tcp_ip6h->ip6_src = v6addr;
3108 	} else {
3109 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3110 	}
3111 	tcp->tcp_ip_src_v6 = v6addr;
3112 
3113 	/*
3114 	 * For O_T_BIND_REQ:
3115 	 * Verify that the target port/addr is available, or choose
3116 	 * another.
3117 	 * For  T_BIND_REQ:
3118 	 * Verify that the target port/addr is available or fail.
3119 	 * In both cases when it succeeds the tcp is inserted in the
3120 	 * bind hash table. This ensures that the operation is atomic
3121 	 * under the lock on the hash bucket.
3122 	 */
3123 	bind_to_req_port_only = requested_port != 0 &&
3124 	    tbr->PRIM_type != O_T_BIND_REQ;
3125 	/*
3126 	 * Get a valid port (within the anonymous range and should not
3127 	 * be a privileged one) to use if the user has not given a port.
3128 	 * If multiple threads are here, they may all start with
3129 	 * with the same initial port. But, it should be fine as long as
3130 	 * tcp_bindi will ensure that no two threads will be assigned
3131 	 * the same port.
3132 	 *
3133 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3134 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3135 	 * unless TCP_ANONPRIVBIND option is set.
3136 	 */
3137 	if (requested_port == 0) {
3138 		requested_port = tcp->tcp_anon_priv_bind ?
3139 		    tcp_get_next_priv_port() :
3140 		    tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
3141 		user_specified = B_FALSE;
3142 	} else {
3143 		int i;
3144 		boolean_t priv = B_FALSE;
3145 		/*
3146 		 * If the requested_port is in the well-known privileged range,
3147 		 * verify that the stream was opened by a privileged user.
3148 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3149 		 * but instead the code relies on:
3150 		 * - the fact that the address of the array and its size never
3151 		 *   changes
3152 		 * - the atomic assignment of the elements of the array
3153 		 */
3154 		if (requested_port < tcp_smallest_nonpriv_port) {
3155 			priv = B_TRUE;
3156 		} else {
3157 			for (i = 0; i < tcp_g_num_epriv_ports; i++) {
3158 				if (requested_port ==
3159 				    tcp_g_epriv_ports[i]) {
3160 					priv = B_TRUE;
3161 					break;
3162 				}
3163 			}
3164 		}
3165 		if (priv) {
3166 			cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
3167 
3168 			if (secpolicy_net_privaddr(cr, requested_port) != 0) {
3169 				if (tcp->tcp_debug) {
3170 					(void) strlog(TCP_MOD_ID, 0, 1,
3171 					    SL_ERROR|SL_TRACE,
3172 					    "tcp_bind: no priv for port %d",
3173 					    requested_port);
3174 				}
3175 				tcp_err_ack(tcp, mp, TACCES, 0);
3176 				return;
3177 			}
3178 		}
3179 		user_specified = B_TRUE;
3180 	}
3181 
3182 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3183 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3184 
3185 	if (allocated_port == 0) {
3186 		if (bind_to_req_port_only) {
3187 			if (tcp->tcp_debug) {
3188 				(void) strlog(TCP_MOD_ID, 0, 1,
3189 				    SL_ERROR|SL_TRACE,
3190 				    "tcp_bind: requested addr busy");
3191 			}
3192 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3193 		} else {
3194 			/* If we are out of ports, fail the bind. */
3195 			if (tcp->tcp_debug) {
3196 				(void) strlog(TCP_MOD_ID, 0, 1,
3197 				    SL_ERROR|SL_TRACE,
3198 				    "tcp_bind: out of ports?");
3199 			}
3200 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3201 		}
3202 		return;
3203 	}
3204 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3205 do_bind:
3206 	if (!backlog_update) {
3207 		if (tcp->tcp_family == AF_INET)
3208 			sin->sin_port = htons(allocated_port);
3209 		else
3210 			sin6->sin6_port = htons(allocated_port);
3211 	}
3212 	if (tcp->tcp_family == AF_INET) {
3213 		if (tbr->CONIND_number != 0) {
3214 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3215 			    sizeof (sin_t));
3216 		} else {
3217 			/* Just verify the local IP address */
3218 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3219 		}
3220 	} else {
3221 		if (tbr->CONIND_number != 0) {
3222 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3223 			    sizeof (sin6_t));
3224 		} else {
3225 			/* Just verify the local IP address */
3226 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3227 			    IPV6_ADDR_LEN);
3228 		}
3229 	}
3230 	if (!mp1) {
3231 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3232 		return;
3233 	}
3234 
3235 	tbr->PRIM_type = T_BIND_ACK;
3236 	mp->b_datap->db_type = M_PCPROTO;
3237 
3238 	/* Chain in the reply mp for tcp_rput() */
3239 	mp1->b_cont = mp;
3240 	mp = mp1;
3241 
3242 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3243 	if (tcp->tcp_conn_req_max) {
3244 		if (tcp->tcp_conn_req_max < tcp_conn_req_min)
3245 			tcp->tcp_conn_req_max = tcp_conn_req_min;
3246 		if (tcp->tcp_conn_req_max > tcp_conn_req_max_q)
3247 			tcp->tcp_conn_req_max = tcp_conn_req_max_q;
3248 		/*
3249 		 * If this is a listener, do not reset the eager list
3250 		 * and other stuffs.  Note that we don't check if the
3251 		 * existing eager list meets the new tcp_conn_req_max
3252 		 * requirement.
3253 		 */
3254 		if (tcp->tcp_state != TCPS_LISTEN) {
3255 			tcp->tcp_state = TCPS_LISTEN;
3256 			/* Initialize the chain. Don't need the eager_lock */
3257 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3258 			tcp->tcp_second_ctimer_threshold =
3259 			    tcp_ip_abort_linterval;
3260 		}
3261 	}
3262 
3263 	/*
3264 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3265 	 * processing continues in tcp_rput_other().
3266 	 */
3267 	if (tcp->tcp_family == AF_INET6) {
3268 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3269 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3270 	} else {
3271 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3272 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3273 	}
3274 	/*
3275 	 * If the bind cannot complete immediately
3276 	 * IP will arrange to call tcp_rput_other
3277 	 * when the bind completes.
3278 	 */
3279 	if (mp != NULL) {
3280 		tcp_rput_other(tcp, mp);
3281 	} else {
3282 		/*
3283 		 * Bind will be resumed later. Need to ensure
3284 		 * that conn doesn't disappear when that happens.
3285 		 * This will be decremented in ip_resume_tcp_bind().
3286 		 */
3287 		CONN_INC_REF(tcp->tcp_connp);
3288 	}
3289 }
3290 
3291 
3292 /*
3293  * If the "bind_to_req_port_only" parameter is set, if the requested port
3294  * number is available, return it, If not return 0
3295  *
3296  * If "bind_to_req_port_only" parameter is not set and
3297  * If the requested port number is available, return it.  If not, return
3298  * the first anonymous port we happen across.  If no anonymous ports are
3299  * available, return 0. addr is the requested local address, if any.
3300  *
3301  * In either case, when succeeding update the tcp_t to record the port number
3302  * and insert it in the bind hash table.
3303  *
3304  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3305  * without setting SO_REUSEADDR. This is needed so that they
3306  * can be viewed as two independent transport protocols.
3307  */
3308 static in_port_t
3309 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3310     int reuseaddr, boolean_t quick_connect,
3311     boolean_t bind_to_req_port_only, boolean_t user_specified)
3312 {
3313 	/* number of times we have run around the loop */
3314 	int count = 0;
3315 	/* maximum number of times to run around the loop */
3316 	int loopmax;
3317 	zoneid_t zoneid = tcp->tcp_connp->conn_zoneid;
3318 
3319 	/*
3320 	 * Lookup for free addresses is done in a loop and "loopmax"
3321 	 * influences how long we spin in the loop
3322 	 */
3323 	if (bind_to_req_port_only) {
3324 		/*
3325 		 * If the requested port is busy, don't bother to look
3326 		 * for a new one. Setting loop maximum count to 1 has
3327 		 * that effect.
3328 		 */
3329 		loopmax = 1;
3330 	} else {
3331 		/*
3332 		 * If the requested port is busy, look for a free one
3333 		 * in the anonymous port range.
3334 		 * Set loopmax appropriately so that one does not look
3335 		 * forever in the case all of the anonymous ports are in use.
3336 		 */
3337 		if (tcp->tcp_anon_priv_bind) {
3338 			/*
3339 			 * loopmax =
3340 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3341 			 */
3342 			loopmax = IPPORT_RESERVED - tcp_min_anonpriv_port;
3343 		} else {
3344 			loopmax = (tcp_largest_anon_port -
3345 			    tcp_smallest_anon_port + 1);
3346 		}
3347 	}
3348 	do {
3349 		uint16_t	lport;
3350 		tf_t		*tbf;
3351 		tcp_t		*ltcp;
3352 
3353 		lport = htons(port);
3354 
3355 		/*
3356 		 * Ensure that the tcp_t is not currently in the bind hash.
3357 		 * Hold the lock on the hash bucket to ensure that
3358 		 * the duplicate check plus the insertion is an atomic
3359 		 * operation.
3360 		 *
3361 		 * This function does an inline lookup on the bind hash list
3362 		 * Make sure that we access only members of tcp_t
3363 		 * and that we don't look at tcp_tcp, since we are not
3364 		 * doing a CONN_INC_REF.
3365 		 */
3366 		tcp_bind_hash_remove(tcp);
3367 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(lport)];
3368 		mutex_enter(&tbf->tf_lock);
3369 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3370 		    ltcp = ltcp->tcp_bind_hash) {
3371 			if (lport != ltcp->tcp_lport ||
3372 			    ltcp->tcp_connp->conn_zoneid != zoneid) {
3373 				continue;
3374 			}
3375 
3376 			/*
3377 			 * If TCP_EXCLBIND is set for either the bound or
3378 			 * binding endpoint, the semantics of bind
3379 			 * is changed according to the following.
3380 			 *
3381 			 * spec = specified address (v4 or v6)
3382 			 * unspec = unspecified address (v4 or v6)
3383 			 * A = specified addresses are different for endpoints
3384 			 *
3385 			 * bound	bind to		allowed
3386 			 * -------------------------------------
3387 			 * unspec	unspec		no
3388 			 * unspec	spec		no
3389 			 * spec		unspec		no
3390 			 * spec		spec		yes if A
3391 			 *
3392 			 * Note:
3393 			 *
3394 			 * 1. Because of TLI semantics, an endpoint can go
3395 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3396 			 * TCPS_BOUND, depending on whether it is originally
3397 			 * a listener or not.  That is why we need to check
3398 			 * for states greater than or equal to TCPS_BOUND
3399 			 * here.
3400 			 *
3401 			 * 2. Ideally, we should only check for state equals
3402 			 * to TCPS_LISTEN. And the following check should be
3403 			 * added.
3404 			 *
3405 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3406 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3407 			 *		...
3408 			 * }
3409 			 *
3410 			 * The semantics will be changed to this.  If the
3411 			 * endpoint on the list is in state not equal to
3412 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3413 			 * set, let the bind succeed.
3414 			 *
3415 			 * But because of (1), we cannot do that now.  If
3416 			 * in future, we can change this going back semantics,
3417 			 * we can add the above check.
3418 			 */
3419 			if (ltcp->tcp_exclbind || tcp->tcp_exclbind) {
3420 				if (V6_OR_V4_INADDR_ANY(
3421 				    ltcp->tcp_bound_source_v6) ||
3422 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3423 				    IN6_ARE_ADDR_EQUAL(laddr,
3424 				    &ltcp->tcp_bound_source_v6)) {
3425 					break;
3426 				}
3427 				continue;
3428 			}
3429 
3430 			/*
3431 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3432 			 * have disjoint port number spaces, if *_EXCLBIND
3433 			 * is not set and only if the application binds to a
3434 			 * specific port. We use the same autoassigned port
3435 			 * number space for IPv4 and IPv6 sockets.
3436 			 */
3437 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3438 			    bind_to_req_port_only)
3439 				continue;
3440 
3441 			/*
3442 			 * Ideally, we should make sure that the source
3443 			 * address, remote address, and remote port in the
3444 			 * four tuple for this tcp-connection is unique.
3445 			 * However, trying to find out the local source
3446 			 * address would require too much code duplication
3447 			 * with IP, since IP needs needs to have that code
3448 			 * to support userland TCP implementations.
3449 			 */
3450 			if (quick_connect &&
3451 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3452 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3453 				!IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3454 				    &ltcp->tcp_remote_v6)))
3455 				continue;
3456 
3457 			if (!reuseaddr) {
3458 				/*
3459 				 * No socket option SO_REUSEADDR.
3460 				 * If existing port is bound to
3461 				 * a non-wildcard IP address
3462 				 * and the requesting stream is
3463 				 * bound to a distinct
3464 				 * different IP addresses
3465 				 * (non-wildcard, also), keep
3466 				 * going.
3467 				 */
3468 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3469 				    !V6_OR_V4_INADDR_ANY(
3470 				    ltcp->tcp_bound_source_v6) &&
3471 				    !IN6_ARE_ADDR_EQUAL(laddr,
3472 					&ltcp->tcp_bound_source_v6))
3473 					continue;
3474 				if (ltcp->tcp_state >= TCPS_BOUND) {
3475 					/*
3476 					 * This port is being used and
3477 					 * its state is >= TCPS_BOUND,
3478 					 * so we can't bind to it.
3479 					 */
3480 					break;
3481 				}
3482 			} else {
3483 				/*
3484 				 * socket option SO_REUSEADDR is set on the
3485 				 * binding tcp_t.
3486 				 *
3487 				 * If two streams are bound to
3488 				 * same IP address or both addr
3489 				 * and bound source are wildcards
3490 				 * (INADDR_ANY), we want to stop
3491 				 * searching.
3492 				 * We have found a match of IP source
3493 				 * address and source port, which is
3494 				 * refused regardless of the
3495 				 * SO_REUSEADDR setting, so we break.
3496 				 */
3497 				if (IN6_ARE_ADDR_EQUAL(laddr,
3498 				    &ltcp->tcp_bound_source_v6) &&
3499 				    (ltcp->tcp_state == TCPS_LISTEN ||
3500 					ltcp->tcp_state == TCPS_BOUND))
3501 					break;
3502 			}
3503 		}
3504 		if (ltcp != NULL) {
3505 			/* The port number is busy */
3506 			mutex_exit(&tbf->tf_lock);
3507 		} else {
3508 			/*
3509 			 * This port is ours. Insert in fanout and mark as
3510 			 * bound to prevent others from getting the port
3511 			 * number.
3512 			 */
3513 			tcp->tcp_state = TCPS_BOUND;
3514 			tcp->tcp_lport = htons(port);
3515 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3516 
3517 			ASSERT(&tcp_bind_fanout[TCP_BIND_HASH(
3518 			    tcp->tcp_lport)] == tbf);
3519 			tcp_bind_hash_insert(tbf, tcp, 1);
3520 
3521 			mutex_exit(&tbf->tf_lock);
3522 
3523 			/*
3524 			 * We don't want tcp_next_port_to_try to "inherit"
3525 			 * a port number supplied by the user in a bind.
3526 			 */
3527 			if (user_specified)
3528 				return (port);
3529 
3530 			/*
3531 			 * This is the only place where tcp_next_port_to_try
3532 			 * is updated. After the update, it may or may not
3533 			 * be in the valid range.
3534 			 */
3535 			if (!tcp->tcp_anon_priv_bind)
3536 				tcp_next_port_to_try = port + 1;
3537 			return (port);
3538 		}
3539 
3540 		if (tcp->tcp_anon_priv_bind) {
3541 			port = tcp_get_next_priv_port();
3542 		} else {
3543 			if (count == 0 && user_specified) {
3544 				/*
3545 				 * We may have to return an anonymous port. So
3546 				 * get one to start with.
3547 				 */
3548 				port =
3549 				    tcp_update_next_port(tcp_next_port_to_try,
3550 					B_TRUE);
3551 				user_specified = B_FALSE;
3552 			} else {
3553 				port = tcp_update_next_port(port + 1, B_FALSE);
3554 			}
3555 		}
3556 
3557 		/*
3558 		 * Don't let this loop run forever in the case where
3559 		 * all of the anonymous ports are in use.
3560 		 */
3561 	} while (++count < loopmax);
3562 	return (0);
3563 }
3564 
3565 /*
3566  * We are dying for some reason.  Try to do it gracefully.  (May be called
3567  * as writer.)
3568  *
3569  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3570  * done by a service procedure).
3571  * TBD - Should the return value distinguish between the tcp_t being
3572  * freed and it being reinitialized?
3573  */
3574 static int
3575 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3576 {
3577 	mblk_t	*mp;
3578 	queue_t	*q;
3579 
3580 	TCP_CLD_STAT(tag);
3581 
3582 #if TCP_TAG_CLEAN_DEATH
3583 	tcp->tcp_cleandeathtag = tag;
3584 #endif
3585 
3586 	if (tcp->tcp_linger_tid != 0 &&
3587 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3588 		tcp_stop_lingering(tcp);
3589 	}
3590 
3591 	ASSERT(tcp != NULL);
3592 	ASSERT((tcp->tcp_family == AF_INET &&
3593 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3594 	    (tcp->tcp_family == AF_INET6 &&
3595 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3596 	    tcp->tcp_ipversion == IPV6_VERSION)));
3597 
3598 	if (TCP_IS_DETACHED(tcp)) {
3599 		if (tcp->tcp_hard_binding) {
3600 			/*
3601 			 * Its an eager that we are dealing with. We close the
3602 			 * eager but in case a conn_ind has already gone to the
3603 			 * listener, let tcp_accept_finish() send a discon_ind
3604 			 * to the listener and drop the last reference. If the
3605 			 * listener doesn't even know about the eager i.e. the
3606 			 * conn_ind hasn't gone up, blow away the eager and drop
3607 			 * the last reference as well. If the conn_ind has gone
3608 			 * up, state should be BOUND. tcp_accept_finish
3609 			 * will figure out that the connection has received a
3610 			 * RST and will send a DISCON_IND to the application.
3611 			 */
3612 			tcp_closei_local(tcp);
3613 			if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
3614 				CONN_DEC_REF(tcp->tcp_connp);
3615 			} else {
3616 				tcp->tcp_state = TCPS_BOUND;
3617 			}
3618 		} else {
3619 			tcp_close_detached(tcp);
3620 		}
3621 		return (0);
3622 	}
3623 
3624 	TCP_STAT(tcp_clean_death_nondetached);
3625 
3626 	/*
3627 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3628 	 * is run) postpone cleaning up the endpoint until service routine
3629 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3630 	 * client_errno since tcp_close uses the client_errno field.
3631 	 */
3632 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3633 		if (err != 0)
3634 			tcp->tcp_client_errno = err;
3635 
3636 		tcp->tcp_deferred_clean_death = B_TRUE;
3637 		return (-1);
3638 	}
3639 
3640 	q = tcp->tcp_rq;
3641 
3642 	/* Trash all inbound data */
3643 	flushq(q, FLUSHALL);
3644 
3645 	/*
3646 	 * If we are at least part way open and there is error
3647 	 * (err==0 implies no error)
3648 	 * notify our client by a T_DISCON_IND.
3649 	 */
3650 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3651 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3652 		    !TCP_IS_SOCKET(tcp)) {
3653 			/*
3654 			 * Send M_FLUSH according to TPI. Because sockets will
3655 			 * (and must) ignore FLUSHR we do that only for TPI
3656 			 * endpoints and sockets in STREAMS mode.
3657 			 */
3658 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3659 		}
3660 		if (tcp->tcp_debug) {
3661 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3662 			    "tcp_clean_death: discon err %d", err);
3663 		}
3664 		mp = mi_tpi_discon_ind(NULL, err, 0);
3665 		if (mp != NULL) {
3666 			putnext(q, mp);
3667 		} else {
3668 			if (tcp->tcp_debug) {
3669 				(void) strlog(TCP_MOD_ID, 0, 1,
3670 				    SL_ERROR|SL_TRACE,
3671 				    "tcp_clean_death, sending M_ERROR");
3672 			}
3673 			(void) putnextctl1(q, M_ERROR, EPROTO);
3674 		}
3675 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3676 			/* SYN_SENT or SYN_RCVD */
3677 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
3678 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3679 			/* ESTABLISHED or CLOSE_WAIT */
3680 			BUMP_MIB(&tcp_mib, tcpEstabResets);
3681 		}
3682 	}
3683 
3684 	tcp_reinit(tcp);
3685 	return (-1);
3686 }
3687 
3688 /*
3689  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3690  * to expire, stop the wait and finish the close.
3691  */
3692 static void
3693 tcp_stop_lingering(tcp_t *tcp)
3694 {
3695 	clock_t	delta = 0;
3696 
3697 	tcp->tcp_linger_tid = 0;
3698 	if (tcp->tcp_state > TCPS_LISTEN) {
3699 		tcp_acceptor_hash_remove(tcp);
3700 		if (tcp->tcp_flow_stopped) {
3701 			tcp_clrqfull(tcp);
3702 		}
3703 
3704 		if (tcp->tcp_timer_tid != 0) {
3705 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3706 			tcp->tcp_timer_tid = 0;
3707 		}
3708 		/*
3709 		 * Need to cancel those timers which will not be used when
3710 		 * TCP is detached.  This has to be done before the tcp_wq
3711 		 * is set to the global queue.
3712 		 */
3713 		tcp_timers_stop(tcp);
3714 
3715 
3716 		tcp->tcp_detached = B_TRUE;
3717 		tcp->tcp_rq = tcp_g_q;
3718 		tcp->tcp_wq = WR(tcp_g_q);
3719 
3720 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3721 			tcp_time_wait_append(tcp);
3722 			TCP_DBGSTAT(tcp_detach_time_wait);
3723 			goto finish;
3724 		}
3725 
3726 		/*
3727 		 * If delta is zero the timer event wasn't executed and was
3728 		 * successfully canceled. In this case we need to restart it
3729 		 * with the minimal delta possible.
3730 		 */
3731 		if (delta >= 0) {
3732 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3733 			    delta ? delta : 1);
3734 		}
3735 	} else {
3736 		tcp_closei_local(tcp);
3737 		CONN_DEC_REF(tcp->tcp_connp);
3738 	}
3739 finish:
3740 	/* Signal closing thread that it can complete close */
3741 	mutex_enter(&tcp->tcp_closelock);
3742 	tcp->tcp_detached = B_TRUE;
3743 	tcp->tcp_rq = tcp_g_q;
3744 	tcp->tcp_wq = WR(tcp_g_q);
3745 	tcp->tcp_closed = 1;
3746 	cv_signal(&tcp->tcp_closecv);
3747 	mutex_exit(&tcp->tcp_closelock);
3748 }
3749 
3750 /*
3751  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3752  * expires.
3753  */
3754 static void
3755 tcp_close_linger_timeout(void *arg)
3756 {
3757 	conn_t	*connp = (conn_t *)arg;
3758 	tcp_t 	*tcp = connp->conn_tcp;
3759 
3760 	tcp->tcp_client_errno = ETIMEDOUT;
3761 	tcp_stop_lingering(tcp);
3762 }
3763 
3764 static int
3765 tcp_close(queue_t *q, int flags)
3766 {
3767 	conn_t		*connp = Q_TO_CONN(q);
3768 	tcp_t		*tcp = connp->conn_tcp;
3769 	mblk_t 		*mp = &tcp->tcp_closemp;
3770 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3771 
3772 	ASSERT(WR(q)->q_next == NULL);
3773 	ASSERT(connp->conn_ref >= 2);
3774 	ASSERT((connp->conn_flags & IPCL_TCPMOD) == 0);
3775 
3776 	/*
3777 	 * We are being closed as /dev/tcp or /dev/tcp6.
3778 	 *
3779 	 * Mark the conn as closing. ill_pending_mp_add will not
3780 	 * add any mp to the pending mp list, after this conn has
3781 	 * started closing. Same for sq_pending_mp_add
3782 	 */
3783 	mutex_enter(&connp->conn_lock);
3784 	connp->conn_state_flags |= CONN_CLOSING;
3785 	if (connp->conn_oper_pending_ill != NULL)
3786 		conn_ioctl_cleanup_reqd = B_TRUE;
3787 	CONN_INC_REF_LOCKED(connp);
3788 	mutex_exit(&connp->conn_lock);
3789 	tcp->tcp_closeflags = (uint8_t)flags;
3790 	ASSERT(connp->conn_ref >= 3);
3791 
3792 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
3793 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
3794 
3795 	mutex_enter(&tcp->tcp_closelock);
3796 
3797 	while (!tcp->tcp_closed)
3798 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3799 	mutex_exit(&tcp->tcp_closelock);
3800 	/*
3801 	 * In the case of listener streams that have eagers in the q or q0
3802 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3803 	 * tcp_wq of the eagers point to our queues. By waiting for the
3804 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3805 	 * up their queue pointers and also dropped their references to us.
3806 	 */
3807 	if (tcp->tcp_wait_for_eagers) {
3808 		mutex_enter(&connp->conn_lock);
3809 		while (connp->conn_ref != 1) {
3810 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3811 		}
3812 		mutex_exit(&connp->conn_lock);
3813 	}
3814 	/*
3815 	 * ioctl cleanup. The mp is queued in the
3816 	 * ill_pending_mp or in the sq_pending_mp.
3817 	 */
3818 	if (conn_ioctl_cleanup_reqd)
3819 		conn_ioctl_cleanup(connp);
3820 
3821 	qprocsoff(q);
3822 	inet_minor_free(ip_minor_arena, connp->conn_dev);
3823 
3824 	ASSERT(connp->conn_cred != NULL);
3825 	crfree(connp->conn_cred);
3826 	tcp->tcp_cred = connp->conn_cred = NULL;
3827 	tcp->tcp_cpid = -1;
3828 
3829 	/*
3830 	 * Drop IP's reference on the conn. This is the last reference
3831 	 * on the connp if the state was less than established. If the
3832 	 * connection has gone into timewait state, then we will have
3833 	 * one ref for the TCP and one more ref (total of two) for the
3834 	 * classifier connected hash list (a timewait connections stays
3835 	 * in connected hash till closed).
3836 	 *
3837 	 * We can't assert the references because there might be other
3838 	 * transient reference places because of some walkers or queued
3839 	 * packets in squeue for the timewait state.
3840 	 */
3841 	CONN_DEC_REF(connp);
3842 	q->q_ptr = WR(q)->q_ptr = NULL;
3843 	return (0);
3844 }
3845 
3846 static int
3847 tcpclose_accept(queue_t *q)
3848 {
3849 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3850 
3851 	/*
3852 	 * We had opened an acceptor STREAM for sockfs which is
3853 	 * now being closed due to some error.
3854 	 */
3855 	qprocsoff(q);
3856 	inet_minor_free(ip_minor_arena, (dev_t)q->q_ptr);
3857 	q->q_ptr = WR(q)->q_ptr = NULL;
3858 	return (0);
3859 }
3860 
3861 
3862 /*
3863  * Called by streams close routine via squeues when our client blows off her
3864  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3865  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3866  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3867  * acked.
3868  *
3869  * NOTE: tcp_close potentially returns error when lingering.
3870  * However, the stream head currently does not pass these errors
3871  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3872  * errors to the application (from tsleep()) and not errors
3873  * like ECONNRESET caused by receiving a reset packet.
3874  */
3875 
3876 /* ARGSUSED */
3877 static void
3878 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3879 {
3880 	char	*msg;
3881 	conn_t	*connp = (conn_t *)arg;
3882 	tcp_t	*tcp = connp->conn_tcp;
3883 	clock_t	delta = 0;
3884 
3885 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3886 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3887 
3888 	/* Cancel any pending timeout */
3889 	if (tcp->tcp_ordrelid != 0) {
3890 		if (tcp->tcp_timeout) {
3891 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
3892 		}
3893 		tcp->tcp_ordrelid = 0;
3894 		tcp->tcp_timeout = B_FALSE;
3895 	}
3896 
3897 	mutex_enter(&tcp->tcp_eager_lock);
3898 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3899 		/* Cleanup for listener */
3900 		tcp_eager_cleanup(tcp, 0);
3901 		tcp->tcp_wait_for_eagers = 1;
3902 	}
3903 	mutex_exit(&tcp->tcp_eager_lock);
3904 
3905 	connp->conn_mdt_ok = B_FALSE;
3906 	tcp->tcp_mdt = B_FALSE;
3907 
3908 	msg = NULL;
3909 	switch (tcp->tcp_state) {
3910 	case TCPS_CLOSED:
3911 	case TCPS_IDLE:
3912 	case TCPS_BOUND:
3913 	case TCPS_LISTEN:
3914 		break;
3915 	case TCPS_SYN_SENT:
3916 		msg = "tcp_close, during connect";
3917 		break;
3918 	case TCPS_SYN_RCVD:
3919 		/*
3920 		 * Close during the connect 3-way handshake
3921 		 * but here there may or may not be pending data
3922 		 * already on queue. Process almost same as in
3923 		 * the ESTABLISHED state.
3924 		 */
3925 		/* FALLTHRU */
3926 	default:
3927 		if (tcp->tcp_fused)
3928 			tcp_unfuse(tcp);
3929 
3930 		/*
3931 		 * If SO_LINGER has set a zero linger time, abort the
3932 		 * connection with a reset.
3933 		 */
3934 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3935 			msg = "tcp_close, zero lingertime";
3936 			break;
3937 		}
3938 
3939 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3940 		/*
3941 		 * Abort connection if there is unread data queued.
3942 		 */
3943 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3944 			msg = "tcp_close, unread data";
3945 			break;
3946 		}
3947 		/*
3948 		 * tcp_hard_bound is now cleared thus all packets go through
3949 		 * tcp_lookup. This fact is used by tcp_detach below.
3950 		 *
3951 		 * We have done a qwait() above which could have possibly
3952 		 * drained more messages in turn causing transition to a
3953 		 * different state. Check whether we have to do the rest
3954 		 * of the processing or not.
3955 		 */
3956 		if (tcp->tcp_state <= TCPS_LISTEN)
3957 			break;
3958 
3959 		/*
3960 		 * Transmit the FIN before detaching the tcp_t.
3961 		 * After tcp_detach returns this queue/perimeter
3962 		 * no longer owns the tcp_t thus others can modify it.
3963 		 */
3964 		(void) tcp_xmit_end(tcp);
3965 
3966 		/*
3967 		 * If lingering on close then wait until the fin is acked,
3968 		 * the SO_LINGER time passes, or a reset is sent/received.
3969 		 */
3970 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3971 		    !(tcp->tcp_fin_acked) &&
3972 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3973 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3974 				tcp->tcp_client_errno = EWOULDBLOCK;
3975 			} else if (tcp->tcp_client_errno == 0) {
3976 
3977 				ASSERT(tcp->tcp_linger_tid == 0);
3978 
3979 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3980 				    tcp_close_linger_timeout,
3981 				    tcp->tcp_lingertime * hz);
3982 
3983 				/* tcp_close_linger_timeout will finish close */
3984 				if (tcp->tcp_linger_tid == 0)
3985 					tcp->tcp_client_errno = ENOSR;
3986 				else
3987 					return;
3988 			}
3989 
3990 			/*
3991 			 * Check if we need to detach or just close
3992 			 * the instance.
3993 			 */
3994 			if (tcp->tcp_state <= TCPS_LISTEN)
3995 				break;
3996 		}
3997 
3998 		/*
3999 		 * Make sure that no other thread will access the tcp_rq of
4000 		 * this instance (through lookups etc.) as tcp_rq will go
4001 		 * away shortly.
4002 		 */
4003 		tcp_acceptor_hash_remove(tcp);
4004 
4005 		if (tcp->tcp_flow_stopped) {
4006 			tcp_clrqfull(tcp);
4007 		}
4008 
4009 		if (tcp->tcp_timer_tid != 0) {
4010 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4011 			tcp->tcp_timer_tid = 0;
4012 		}
4013 		/*
4014 		 * Need to cancel those timers which will not be used when
4015 		 * TCP is detached.  This has to be done before the tcp_wq
4016 		 * is set to the global queue.
4017 		 */
4018 		tcp_timers_stop(tcp);
4019 
4020 		tcp->tcp_detached = B_TRUE;
4021 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4022 			tcp_time_wait_append(tcp);
4023 			TCP_DBGSTAT(tcp_detach_time_wait);
4024 			ASSERT(connp->conn_ref >= 3);
4025 			goto finish;
4026 		}
4027 
4028 		/*
4029 		 * If delta is zero the timer event wasn't executed and was
4030 		 * successfully canceled. In this case we need to restart it
4031 		 * with the minimal delta possible.
4032 		 */
4033 		if (delta >= 0)
4034 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4035 			    delta ? delta : 1);
4036 
4037 		ASSERT(connp->conn_ref >= 3);
4038 		goto finish;
4039 	}
4040 
4041 	/* Detach did not complete. Still need to remove q from stream. */
4042 	if (msg) {
4043 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4044 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4045 			BUMP_MIB(&tcp_mib, tcpEstabResets);
4046 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4047 		    tcp->tcp_state == TCPS_SYN_RCVD)
4048 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
4049 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4050 	}
4051 
4052 	tcp_closei_local(tcp);
4053 	CONN_DEC_REF(connp);
4054 	ASSERT(connp->conn_ref >= 2);
4055 
4056 finish:
4057 	/*
4058 	 * Although packets are always processed on the correct
4059 	 * tcp's perimeter and access is serialized via squeue's,
4060 	 * IP still needs a queue when sending packets in time_wait
4061 	 * state so use WR(tcp_g_q) till ip_output() can be
4062 	 * changed to deal with just connp. For read side, we
4063 	 * could have set tcp_rq to NULL but there are some cases
4064 	 * in tcp_rput_data() from early days of this code which
4065 	 * do a putnext without checking if tcp is closed. Those
4066 	 * need to be identified before both tcp_rq and tcp_wq
4067 	 * can be set to NULL and tcp_q_q can disappear forever.
4068 	 */
4069 	mutex_enter(&tcp->tcp_closelock);
4070 	/*
4071 	 * Don't change the queues in the case of a listener that has
4072 	 * eagers in its q or q0. It could surprise the eagers.
4073 	 * Instead wait for the eagers outside the squeue.
4074 	 */
4075 	if (!tcp->tcp_wait_for_eagers) {
4076 		tcp->tcp_detached = B_TRUE;
4077 		tcp->tcp_rq = tcp_g_q;
4078 		tcp->tcp_wq = WR(tcp_g_q);
4079 	}
4080 
4081 	/* Signal tcp_close() to finish closing. */
4082 	tcp->tcp_closed = 1;
4083 	cv_signal(&tcp->tcp_closecv);
4084 	mutex_exit(&tcp->tcp_closelock);
4085 }
4086 
4087 
4088 /*
4089  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4090  * Some stream heads get upset if they see these later on as anything but NULL.
4091  */
4092 static void
4093 tcp_close_mpp(mblk_t **mpp)
4094 {
4095 	mblk_t	*mp;
4096 
4097 	if ((mp = *mpp) != NULL) {
4098 		do {
4099 			mp->b_next = NULL;
4100 			mp->b_prev = NULL;
4101 		} while ((mp = mp->b_cont) != NULL);
4102 
4103 		mp = *mpp;
4104 		*mpp = NULL;
4105 		freemsg(mp);
4106 	}
4107 }
4108 
4109 /* Do detached close. */
4110 static void
4111 tcp_close_detached(tcp_t *tcp)
4112 {
4113 	if (tcp->tcp_fused)
4114 		tcp_unfuse(tcp);
4115 
4116 	/*
4117 	 * Clustering code serializes TCP disconnect callbacks and
4118 	 * cluster tcp list walks by blocking a TCP disconnect callback
4119 	 * if a cluster tcp list walk is in progress. This ensures
4120 	 * accurate accounting of TCPs in the cluster code even though
4121 	 * the TCP list walk itself is not atomic.
4122 	 */
4123 	tcp_closei_local(tcp);
4124 	CONN_DEC_REF(tcp->tcp_connp);
4125 }
4126 
4127 /*
4128  * Stop all TCP timers, and free the timer mblks if requested.
4129  */
4130 void
4131 tcp_timers_stop(tcp_t *tcp)
4132 {
4133 	if (tcp->tcp_timer_tid != 0) {
4134 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4135 		tcp->tcp_timer_tid = 0;
4136 	}
4137 	if (tcp->tcp_ka_tid != 0) {
4138 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4139 		tcp->tcp_ka_tid = 0;
4140 	}
4141 	if (tcp->tcp_ack_tid != 0) {
4142 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4143 		tcp->tcp_ack_tid = 0;
4144 	}
4145 	if (tcp->tcp_push_tid != 0) {
4146 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4147 		tcp->tcp_push_tid = 0;
4148 	}
4149 }
4150 
4151 /*
4152  * The tcp_t is going away. Remove it from all lists and set it
4153  * to TCPS_CLOSED. The freeing up of memory is deferred until
4154  * tcp_inactive. This is needed since a thread in tcp_rput might have
4155  * done a CONN_INC_REF on this structure before it was removed from the
4156  * hashes.
4157  */
4158 static void
4159 tcp_closei_local(tcp_t *tcp)
4160 {
4161 	ire_t 	*ire;
4162 	conn_t	*connp = tcp->tcp_connp;
4163 
4164 	if (!TCP_IS_SOCKET(tcp))
4165 		tcp_acceptor_hash_remove(tcp);
4166 
4167 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
4168 	tcp->tcp_ibsegs = 0;
4169 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
4170 	tcp->tcp_obsegs = 0;
4171 
4172 	/*
4173 	 * If we are an eager connection hanging off a listener that
4174 	 * hasn't formally accepted the connection yet, get off his
4175 	 * list and blow off any data that we have accumulated.
4176 	 */
4177 	if (tcp->tcp_listener != NULL) {
4178 		tcp_t	*listener = tcp->tcp_listener;
4179 		mutex_enter(&listener->tcp_eager_lock);
4180 		/*
4181 		 * tcp_eager_conn_ind == NULL means that the
4182 		 * conn_ind has already gone to listener. At
4183 		 * this point, eager will be closed but we
4184 		 * leave it in listeners eager list so that
4185 		 * if listener decides to close without doing
4186 		 * accept, we can clean this up. In tcp_wput_accept
4187 		 * we take case of the case of accept on closed
4188 		 * eager.
4189 		 */
4190 		if (tcp->tcp_conn.tcp_eager_conn_ind != NULL) {
4191 			tcp_eager_unlink(tcp);
4192 			mutex_exit(&listener->tcp_eager_lock);
4193 			/*
4194 			 * We don't want to have any pointers to the
4195 			 * listener queue, after we have released our
4196 			 * reference on the listener
4197 			 */
4198 			tcp->tcp_rq = tcp_g_q;
4199 			tcp->tcp_wq = WR(tcp_g_q);
4200 			CONN_DEC_REF(listener->tcp_connp);
4201 		} else {
4202 			mutex_exit(&listener->tcp_eager_lock);
4203 		}
4204 	}
4205 
4206 	/* Stop all the timers */
4207 	tcp_timers_stop(tcp);
4208 
4209 	if (tcp->tcp_state == TCPS_LISTEN) {
4210 		if (tcp->tcp_ip_addr_cache) {
4211 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4212 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4213 			tcp->tcp_ip_addr_cache = NULL;
4214 		}
4215 	}
4216 	if (tcp->tcp_flow_stopped)
4217 		tcp_clrqfull(tcp);
4218 
4219 	tcp_bind_hash_remove(tcp);
4220 	/*
4221 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4222 	 * is trying to remove this tcp from the time wait list, we will
4223 	 * block in tcp_time_wait_remove while trying to acquire the
4224 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4225 	 * requires the ipcl_hash_remove to be ordered after the
4226 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4227 	 */
4228 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4229 		tcp_time_wait_remove(tcp, NULL);
4230 	CL_INET_DISCONNECT(tcp);
4231 	ipcl_hash_remove(connp);
4232 
4233 	/*
4234 	 * Delete the cached ire in conn_ire_cache and also mark
4235 	 * the conn as CONDEMNED
4236 	 */
4237 	mutex_enter(&connp->conn_lock);
4238 	connp->conn_state_flags |= CONN_CONDEMNED;
4239 	ire = connp->conn_ire_cache;
4240 	connp->conn_ire_cache = NULL;
4241 	mutex_exit(&connp->conn_lock);
4242 	if (ire != NULL)
4243 		IRE_REFRELE_NOTR(ire);
4244 
4245 	/* Need to cleanup any pending ioctls */
4246 	ASSERT(tcp->tcp_time_wait_next == NULL);
4247 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4248 	ASSERT(tcp->tcp_time_wait_expire == 0);
4249 	tcp->tcp_state = TCPS_CLOSED;
4250 
4251 	/* Release any SSL context */
4252 	if (tcp->tcp_kssl_ent != NULL) {
4253 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4254 		tcp->tcp_kssl_ent = NULL;
4255 	}
4256 	if (tcp->tcp_kssl_ctx != NULL) {
4257 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4258 		tcp->tcp_kssl_ctx = NULL;
4259 	}
4260 	tcp->tcp_kssl_pending = B_FALSE;
4261 }
4262 
4263 /*
4264  * tcp is dying (called from ipcl_conn_destroy and error cases).
4265  * Free the tcp_t in either case.
4266  */
4267 void
4268 tcp_free(tcp_t *tcp)
4269 {
4270 	mblk_t	*mp;
4271 	ip6_pkt_t	*ipp;
4272 
4273 	ASSERT(tcp != NULL);
4274 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4275 
4276 	tcp->tcp_rq = NULL;
4277 	tcp->tcp_wq = NULL;
4278 
4279 	tcp_close_mpp(&tcp->tcp_xmit_head);
4280 	tcp_close_mpp(&tcp->tcp_reass_head);
4281 	if (tcp->tcp_rcv_list != NULL) {
4282 		/* Free b_next chain */
4283 		tcp_close_mpp(&tcp->tcp_rcv_list);
4284 	}
4285 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4286 		freemsg(mp);
4287 	}
4288 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4289 		freemsg(mp);
4290 	}
4291 
4292 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4293 		freeb(tcp->tcp_fused_sigurg_mp);
4294 		tcp->tcp_fused_sigurg_mp = NULL;
4295 	}
4296 
4297 	if (tcp->tcp_sack_info != NULL) {
4298 		if (tcp->tcp_notsack_list != NULL) {
4299 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4300 		}
4301 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4302 	}
4303 
4304 	if (tcp->tcp_hopopts != NULL) {
4305 		mi_free(tcp->tcp_hopopts);
4306 		tcp->tcp_hopopts = NULL;
4307 		tcp->tcp_hopoptslen = 0;
4308 	}
4309 	ASSERT(tcp->tcp_hopoptslen == 0);
4310 	if (tcp->tcp_dstopts != NULL) {
4311 		mi_free(tcp->tcp_dstopts);
4312 		tcp->tcp_dstopts = NULL;
4313 		tcp->tcp_dstoptslen = 0;
4314 	}
4315 	ASSERT(tcp->tcp_dstoptslen == 0);
4316 	if (tcp->tcp_rtdstopts != NULL) {
4317 		mi_free(tcp->tcp_rtdstopts);
4318 		tcp->tcp_rtdstopts = NULL;
4319 		tcp->tcp_rtdstoptslen = 0;
4320 	}
4321 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4322 	if (tcp->tcp_rthdr != NULL) {
4323 		mi_free(tcp->tcp_rthdr);
4324 		tcp->tcp_rthdr = NULL;
4325 		tcp->tcp_rthdrlen = 0;
4326 	}
4327 	ASSERT(tcp->tcp_rthdrlen == 0);
4328 
4329 	ipp = &tcp->tcp_sticky_ipp;
4330 	if ((ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4331 	    IPPF_DSTOPTS | IPPF_RTHDR)) != 0) {
4332 		if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
4333 			kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
4334 			ipp->ipp_hopopts = NULL;
4335 			ipp->ipp_hopoptslen = 0;
4336 		}
4337 		if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4338 			kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
4339 			ipp->ipp_rtdstopts = NULL;
4340 			ipp->ipp_rtdstoptslen = 0;
4341 		}
4342 		if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4343 			kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
4344 			ipp->ipp_dstopts = NULL;
4345 			ipp->ipp_dstoptslen = 0;
4346 		}
4347 		if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
4348 			kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
4349 			ipp->ipp_rthdr = NULL;
4350 			ipp->ipp_rthdrlen = 0;
4351 		}
4352 		ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS |
4353 		    IPPF_DSTOPTS | IPPF_RTHDR);
4354 	}
4355 
4356 	/*
4357 	 * Free memory associated with the tcp/ip header template.
4358 	 */
4359 
4360 	if (tcp->tcp_iphc != NULL)
4361 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4362 
4363 	/*
4364 	 * Following is really a blowing away a union.
4365 	 * It happens to have exactly two members of identical size
4366 	 * the following code is enough.
4367 	 */
4368 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4369 
4370 	if (tcp->tcp_tracebuf != NULL) {
4371 		kmem_free(tcp->tcp_tracebuf, sizeof (tcptrch_t));
4372 		tcp->tcp_tracebuf = NULL;
4373 	}
4374 }
4375 
4376 
4377 /*
4378  * Put a connection confirmation message upstream built from the
4379  * address information within 'iph' and 'tcph'.  Report our success or failure.
4380  */
4381 static boolean_t
4382 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4383     mblk_t **defermp)
4384 {
4385 	sin_t	sin;
4386 	sin6_t	sin6;
4387 	mblk_t	*mp;
4388 	char	*optp = NULL;
4389 	int	optlen = 0;
4390 	cred_t	*cr;
4391 
4392 	if (defermp != NULL)
4393 		*defermp = NULL;
4394 
4395 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4396 		/*
4397 		 * Return in T_CONN_CON results of option negotiation through
4398 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4399 		 * negotiation, then what is received from remote end needs
4400 		 * to be taken into account but there is no such thing (yet?)
4401 		 * in our TCP/IP.
4402 		 * Note: We do not use mi_offset_param() here as
4403 		 * tcp_opts_conn_req contents do not directly come from
4404 		 * an application and are either generated in kernel or
4405 		 * from user input that was already verified.
4406 		 */
4407 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4408 		optp = (char *)(mp->b_rptr +
4409 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4410 		optlen = (int)
4411 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4412 	}
4413 
4414 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4415 		ipha_t *ipha = (ipha_t *)iphdr;
4416 
4417 		/* packet is IPv4 */
4418 		if (tcp->tcp_family == AF_INET) {
4419 			sin = sin_null;
4420 			sin.sin_addr.s_addr = ipha->ipha_src;
4421 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4422 			sin.sin_family = AF_INET;
4423 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4424 			    (int)sizeof (sin_t), optp, optlen);
4425 		} else {
4426 			sin6 = sin6_null;
4427 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4428 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4429 			sin6.sin6_family = AF_INET6;
4430 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4431 			    (int)sizeof (sin6_t), optp, optlen);
4432 
4433 		}
4434 	} else {
4435 		ip6_t	*ip6h = (ip6_t *)iphdr;
4436 
4437 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4438 		ASSERT(tcp->tcp_family == AF_INET6);
4439 		sin6 = sin6_null;
4440 		sin6.sin6_addr = ip6h->ip6_src;
4441 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4442 		sin6.sin6_family = AF_INET6;
4443 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4444 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4445 		    (int)sizeof (sin6_t), optp, optlen);
4446 	}
4447 
4448 	if (!mp)
4449 		return (B_FALSE);
4450 
4451 	if ((cr = DB_CRED(idmp)) != NULL) {
4452 		mblk_setcred(mp, cr);
4453 		DB_CPID(mp) = DB_CPID(idmp);
4454 	}
4455 
4456 	if (defermp == NULL)
4457 		putnext(tcp->tcp_rq, mp);
4458 	else
4459 		*defermp = mp;
4460 
4461 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4462 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4463 	return (B_TRUE);
4464 }
4465 
4466 /*
4467  * Defense for the SYN attack -
4468  * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest
4469  *    one that doesn't have the dontdrop bit set.
4470  * 2. Don't drop a SYN request before its first timeout. This gives every
4471  *    request at least til the first timeout to complete its 3-way handshake.
4472  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4473  *    requests currently on the queue that has timed out. This will be used
4474  *    as an indicator of whether an attack is under way, so that appropriate
4475  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4476  *    either when eager goes into ESTABLISHED, or gets freed up.)
4477  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4478  *    # of timeout drops back to <= q0len/32 => SYN alert off
4479  */
4480 static boolean_t
4481 tcp_drop_q0(tcp_t *tcp)
4482 {
4483 	tcp_t	*eager;
4484 
4485 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4486 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4487 	/*
4488 	 * New one is added after next_q0 so prev_q0 points to the oldest
4489 	 * Also do not drop any established connections that are deferred on
4490 	 * q0 due to q being full
4491 	 */
4492 
4493 	eager = tcp->tcp_eager_prev_q0;
4494 	while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) {
4495 		eager = eager->tcp_eager_prev_q0;
4496 		if (eager == tcp) {
4497 			eager = tcp->tcp_eager_prev_q0;
4498 			break;
4499 		}
4500 	}
4501 	if (eager->tcp_syn_rcvd_timeout == 0)
4502 		return (B_FALSE);
4503 
4504 	if (tcp->tcp_debug) {
4505 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4506 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4507 		    " (%d pending) on %s, drop one", tcp_conn_req_max_q0,
4508 		    tcp->tcp_conn_req_cnt_q0,
4509 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4510 	}
4511 
4512 	BUMP_MIB(&tcp_mib, tcpHalfOpenDrop);
4513 
4514 	/*
4515 	 * need to do refhold here because the selected eager could
4516 	 * be removed by someone else if we release the eager lock.
4517 	 */
4518 	CONN_INC_REF(eager->tcp_connp);
4519 	mutex_exit(&tcp->tcp_eager_lock);
4520 
4521 	/* Mark the IRE created for this SYN request temporary */
4522 	tcp_ip_ire_mark_advice(eager);
4523 	(void) tcp_clean_death(eager, ETIMEDOUT, 5);
4524 	CONN_DEC_REF(eager->tcp_connp);
4525 
4526 	mutex_enter(&tcp->tcp_eager_lock);
4527 	return (B_TRUE);
4528 }
4529 
4530 int
4531 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4532     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4533 {
4534 	tcp_t 		*ltcp = lconnp->conn_tcp;
4535 	tcp_t		*tcp = connp->conn_tcp;
4536 	mblk_t		*tpi_mp;
4537 	ipha_t		*ipha;
4538 	ip6_t		*ip6h;
4539 	sin6_t 		sin6;
4540 	in6_addr_t 	v6dst;
4541 	int		err;
4542 	int		ifindex = 0;
4543 	cred_t		*cr;
4544 
4545 	if (ipvers == IPV4_VERSION) {
4546 		ipha = (ipha_t *)mp->b_rptr;
4547 
4548 		connp->conn_send = ip_output;
4549 		connp->conn_recv = tcp_input;
4550 
4551 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4552 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4553 
4554 		sin6 = sin6_null;
4555 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4556 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4557 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4558 		sin6.sin6_family = AF_INET6;
4559 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4560 		    lconnp->conn_zoneid);
4561 		if (tcp->tcp_recvdstaddr) {
4562 			sin6_t	sin6d;
4563 
4564 			sin6d = sin6_null;
4565 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4566 			    &sin6d.sin6_addr);
4567 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4568 			sin6d.sin6_family = AF_INET;
4569 			tpi_mp = mi_tpi_extconn_ind(NULL,
4570 			    (char *)&sin6d, sizeof (sin6_t),
4571 			    (char *)&tcp,
4572 			    (t_scalar_t)sizeof (intptr_t),
4573 			    (char *)&sin6d, sizeof (sin6_t),
4574 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4575 		} else {
4576 			tpi_mp = mi_tpi_conn_ind(NULL,
4577 			    (char *)&sin6, sizeof (sin6_t),
4578 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4579 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4580 		}
4581 	} else {
4582 		ip6h = (ip6_t *)mp->b_rptr;
4583 
4584 		connp->conn_send = ip_output_v6;
4585 		connp->conn_recv = tcp_input;
4586 
4587 		connp->conn_srcv6 = ip6h->ip6_dst;
4588 		connp->conn_remv6 = ip6h->ip6_src;
4589 
4590 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4591 		ifindex = (int)DB_CKSUMSTUFF(mp);
4592 		DB_CKSUMSTUFF(mp) = 0;
4593 
4594 		sin6 = sin6_null;
4595 		sin6.sin6_addr = ip6h->ip6_src;
4596 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4597 		sin6.sin6_family = AF_INET6;
4598 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4599 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4600 		    lconnp->conn_zoneid);
4601 
4602 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4603 			/* Pass up the scope_id of remote addr */
4604 			sin6.sin6_scope_id = ifindex;
4605 		} else {
4606 			sin6.sin6_scope_id = 0;
4607 		}
4608 		if (tcp->tcp_recvdstaddr) {
4609 			sin6_t	sin6d;
4610 
4611 			sin6d = sin6_null;
4612 			sin6.sin6_addr = ip6h->ip6_dst;
4613 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4614 			sin6d.sin6_family = AF_INET;
4615 			tpi_mp = mi_tpi_extconn_ind(NULL,
4616 			    (char *)&sin6d, sizeof (sin6_t),
4617 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4618 			    (char *)&sin6d, sizeof (sin6_t),
4619 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4620 		} else {
4621 			tpi_mp = mi_tpi_conn_ind(NULL,
4622 			    (char *)&sin6, sizeof (sin6_t),
4623 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4624 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4625 		}
4626 	}
4627 
4628 	if (tpi_mp == NULL)
4629 		return (ENOMEM);
4630 
4631 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4632 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4633 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4634 	connp->conn_fully_bound = B_FALSE;
4635 
4636 	if (tcp_trace)
4637 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4638 
4639 	/* Inherit information from the "parent" */
4640 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4641 	tcp->tcp_family = ltcp->tcp_family;
4642 	tcp->tcp_wq = ltcp->tcp_wq;
4643 	tcp->tcp_rq = ltcp->tcp_rq;
4644 	tcp->tcp_mss = tcp_mss_def_ipv6;
4645 	tcp->tcp_detached = B_TRUE;
4646 	if ((err = tcp_init_values(tcp)) != 0) {
4647 		freemsg(tpi_mp);
4648 		return (err);
4649 	}
4650 
4651 	if (ipvers == IPV4_VERSION) {
4652 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4653 			freemsg(tpi_mp);
4654 			return (err);
4655 		}
4656 		ASSERT(tcp->tcp_ipha != NULL);
4657 	} else {
4658 		/* ifindex must be already set */
4659 		ASSERT(ifindex != 0);
4660 
4661 		if (ltcp->tcp_bound_if != 0) {
4662 			/*
4663 			 * Set newtcp's bound_if equal to
4664 			 * listener's value. If ifindex is
4665 			 * not the same as ltcp->tcp_bound_if,
4666 			 * it must be a packet for the ipmp group
4667 			 * of interfaces
4668 			 */
4669 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4670 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4671 			tcp->tcp_bound_if = ifindex;
4672 		}
4673 
4674 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4675 		tcp->tcp_recvifindex = 0;
4676 		tcp->tcp_recvhops = 0xffffffffU;
4677 		ASSERT(tcp->tcp_ip6h != NULL);
4678 	}
4679 
4680 	tcp->tcp_lport = ltcp->tcp_lport;
4681 
4682 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4683 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4684 			/*
4685 			 * Listener had options of some sort; eager inherits.
4686 			 * Free up the eager template and allocate one
4687 			 * of the right size.
4688 			 */
4689 			if (tcp->tcp_hdr_grown) {
4690 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4691 			} else {
4692 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4693 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4694 			}
4695 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4696 			    KM_NOSLEEP);
4697 			if (tcp->tcp_iphc == NULL) {
4698 				tcp->tcp_iphc_len = 0;
4699 				freemsg(tpi_mp);
4700 				return (ENOMEM);
4701 			}
4702 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4703 			tcp->tcp_hdr_grown = B_TRUE;
4704 		}
4705 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4706 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4707 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4708 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4709 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4710 
4711 		/*
4712 		 * Copy the IP+TCP header template from listener to eager
4713 		 */
4714 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4715 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4716 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4717 			    IPPROTO_RAW) {
4718 				tcp->tcp_ip6h =
4719 				    (ip6_t *)(tcp->tcp_iphc +
4720 					sizeof (ip6i_t));
4721 			} else {
4722 				tcp->tcp_ip6h =
4723 				    (ip6_t *)(tcp->tcp_iphc);
4724 			}
4725 			tcp->tcp_ipha = NULL;
4726 		} else {
4727 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4728 			tcp->tcp_ip6h = NULL;
4729 		}
4730 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4731 		    tcp->tcp_ip_hdr_len);
4732 	} else {
4733 		/*
4734 		 * only valid case when ipversion of listener and
4735 		 * eager differ is when listener is IPv6 and
4736 		 * eager is IPv4.
4737 		 * Eager header template has been initialized to the
4738 		 * maximum v4 header sizes, which includes space for
4739 		 * TCP and IP options.
4740 		 */
4741 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4742 		    (tcp->tcp_ipversion == IPV4_VERSION));
4743 		ASSERT(tcp->tcp_iphc_len >=
4744 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4745 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4746 		/* copy IP header fields individually */
4747 		tcp->tcp_ipha->ipha_ttl =
4748 		    ltcp->tcp_ip6h->ip6_hops;
4749 		bcopy(ltcp->tcp_tcph->th_lport,
4750 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4751 	}
4752 
4753 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4754 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4755 	    sizeof (in_port_t));
4756 
4757 	if (ltcp->tcp_lport == 0) {
4758 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4759 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4760 		    sizeof (in_port_t));
4761 	}
4762 
4763 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4764 		ASSERT(ipha != NULL);
4765 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4766 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4767 
4768 		/* Source routing option copyover (reverse it) */
4769 		if (tcp_rev_src_routes)
4770 			tcp_opt_reverse(tcp, ipha);
4771 	} else {
4772 		ASSERT(ip6h != NULL);
4773 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4774 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4775 	}
4776 
4777 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4778 	/*
4779 	 * If the SYN contains a credential, it's a loopback packet; attach
4780 	 * the credential to the TPI message.
4781 	 */
4782 	if ((cr = DB_CRED(idmp)) != NULL) {
4783 		mblk_setcred(tpi_mp, cr);
4784 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4785 	}
4786 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4787 
4788 	/* Inherit the listener's SSL protection state */
4789 
4790 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4791 		kssl_hold_ent(tcp->tcp_kssl_ent);
4792 		tcp->tcp_kssl_pending = B_TRUE;
4793 	}
4794 
4795 	return (0);
4796 }
4797 
4798 
4799 int
4800 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4801     tcph_t *tcph, mblk_t *idmp)
4802 {
4803 	tcp_t 		*ltcp = lconnp->conn_tcp;
4804 	tcp_t		*tcp = connp->conn_tcp;
4805 	sin_t		sin;
4806 	mblk_t		*tpi_mp = NULL;
4807 	int		err;
4808 	cred_t		*cr;
4809 
4810 	sin = sin_null;
4811 	sin.sin_addr.s_addr = ipha->ipha_src;
4812 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4813 	sin.sin_family = AF_INET;
4814 	if (ltcp->tcp_recvdstaddr) {
4815 		sin_t	sind;
4816 
4817 		sind = sin_null;
4818 		sind.sin_addr.s_addr = ipha->ipha_dst;
4819 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4820 		sind.sin_family = AF_INET;
4821 		tpi_mp = mi_tpi_extconn_ind(NULL,
4822 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4823 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4824 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4825 	} else {
4826 		tpi_mp = mi_tpi_conn_ind(NULL,
4827 		    (char *)&sin, sizeof (sin_t),
4828 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4829 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4830 	}
4831 
4832 	if (tpi_mp == NULL) {
4833 		return (ENOMEM);
4834 	}
4835 
4836 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4837 	connp->conn_send = ip_output;
4838 	connp->conn_recv = tcp_input;
4839 	connp->conn_fully_bound = B_FALSE;
4840 
4841 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4842 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4843 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4844 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4845 
4846 	if (tcp_trace) {
4847 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_NOSLEEP);
4848 	}
4849 
4850 	/* Inherit information from the "parent" */
4851 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4852 	tcp->tcp_family = ltcp->tcp_family;
4853 	tcp->tcp_wq = ltcp->tcp_wq;
4854 	tcp->tcp_rq = ltcp->tcp_rq;
4855 	tcp->tcp_mss = tcp_mss_def_ipv4;
4856 	tcp->tcp_detached = B_TRUE;
4857 	if ((err = tcp_init_values(tcp)) != 0) {
4858 		freemsg(tpi_mp);
4859 		return (err);
4860 	}
4861 
4862 	/*
4863 	 * Let's make sure that eager tcp template has enough space to
4864 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4865 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4866 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4867 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4868 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4869 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4870 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4871 	 */
4872 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4873 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4874 
4875 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4876 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4877 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4878 	tcp->tcp_ttl = ltcp->tcp_ttl;
4879 	tcp->tcp_tos = ltcp->tcp_tos;
4880 
4881 	/* Copy the IP+TCP header template from listener to eager */
4882 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4883 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4884 	tcp->tcp_ip6h = NULL;
4885 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4886 	    tcp->tcp_ip_hdr_len);
4887 
4888 	/* Initialize the IP addresses and Ports */
4889 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4890 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4891 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4892 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4893 
4894 	/* Source routing option copyover (reverse it) */
4895 	if (tcp_rev_src_routes)
4896 		tcp_opt_reverse(tcp, ipha);
4897 
4898 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4899 
4900 	/*
4901 	 * If the SYN contains a credential, it's a loopback packet; attach
4902 	 * the credential to the TPI message.
4903 	 */
4904 	if ((cr = DB_CRED(idmp)) != NULL) {
4905 		mblk_setcred(tpi_mp, cr);
4906 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4907 	}
4908 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4909 
4910 	/* Inherit the listener's SSL protection state */
4911 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4912 		kssl_hold_ent(tcp->tcp_kssl_ent);
4913 		tcp->tcp_kssl_pending = B_TRUE;
4914 	}
4915 
4916 	return (0);
4917 }
4918 
4919 /*
4920  * sets up conn for ipsec.
4921  * if the first mblk is M_CTL it is consumed and mpp is updated.
4922  * in case of error mpp is freed.
4923  */
4924 conn_t *
4925 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4926 {
4927 	conn_t 		*connp = tcp->tcp_connp;
4928 	conn_t 		*econnp;
4929 	squeue_t 	*new_sqp;
4930 	mblk_t 		*first_mp = *mpp;
4931 	mblk_t		*mp = *mpp;
4932 	boolean_t	mctl_present = B_FALSE;
4933 	uint_t		ipvers;
4934 
4935 	econnp = tcp_get_conn(sqp);
4936 	if (econnp == NULL) {
4937 		freemsg(first_mp);
4938 		return (NULL);
4939 	}
4940 	if (DB_TYPE(mp) == M_CTL) {
4941 		if (mp->b_cont == NULL ||
4942 		    mp->b_cont->b_datap->db_type != M_DATA) {
4943 			freemsg(first_mp);
4944 			return (NULL);
4945 		}
4946 		mp = mp->b_cont;
4947 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4948 			freemsg(first_mp);
4949 			return (NULL);
4950 		}
4951 
4952 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4953 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4954 		mctl_present = B_TRUE;
4955 	} else {
4956 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4957 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4958 	}
4959 
4960 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4961 	DB_CKSUMSTART(mp) = 0;
4962 
4963 	ASSERT(OK_32PTR(mp->b_rptr));
4964 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4965 	if (ipvers == IPV4_VERSION) {
4966 		uint16_t  	*up;
4967 		uint32_t	ports;
4968 		ipha_t		*ipha;
4969 
4970 		ipha = (ipha_t *)mp->b_rptr;
4971 		up = (uint16_t *)((uchar_t *)ipha +
4972 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4973 		ports = *(uint32_t *)up;
4974 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4975 		    ipha->ipha_dst, ipha->ipha_src, ports);
4976 	} else {
4977 		uint16_t  	*up;
4978 		uint32_t	ports;
4979 		uint16_t	ip_hdr_len;
4980 		uint8_t		*nexthdrp;
4981 		ip6_t 		*ip6h;
4982 		tcph_t		*tcph;
4983 
4984 		ip6h = (ip6_t *)mp->b_rptr;
4985 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
4986 			ip_hdr_len = IPV6_HDR_LEN;
4987 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
4988 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
4989 			CONN_DEC_REF(econnp);
4990 			freemsg(first_mp);
4991 			return (NULL);
4992 		}
4993 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
4994 		up = (uint16_t *)tcph->th_lport;
4995 		ports = *(uint32_t *)up;
4996 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
4997 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
4998 	}
4999 
5000 	/*
5001 	 * The caller already ensured that there is a sqp present.
5002 	 */
5003 	econnp->conn_sqp = new_sqp;
5004 
5005 	if (connp->conn_policy != NULL) {
5006 		ipsec_in_t *ii;
5007 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5008 		ASSERT(ii->ipsec_in_policy == NULL);
5009 		IPPH_REFHOLD(connp->conn_policy);
5010 		ii->ipsec_in_policy = connp->conn_policy;
5011 
5012 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5013 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5014 			CONN_DEC_REF(econnp);
5015 			freemsg(first_mp);
5016 			return (NULL);
5017 		}
5018 	}
5019 
5020 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5021 		CONN_DEC_REF(econnp);
5022 		freemsg(first_mp);
5023 		return (NULL);
5024 	}
5025 
5026 	/*
5027 	 * If we know we have some policy, pass the "IPSEC"
5028 	 * options size TCP uses this adjust the MSS.
5029 	 */
5030 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5031 	if (mctl_present) {
5032 		freeb(first_mp);
5033 		*mpp = mp;
5034 	}
5035 
5036 	return (econnp);
5037 }
5038 
5039 /*
5040  * tcp_get_conn/tcp_free_conn
5041  *
5042  * tcp_get_conn is used to get a clean tcp connection structure.
5043  * It tries to reuse the connections put on the freelist by the
5044  * time_wait_collector failing which it goes to kmem_cache. This
5045  * way has two benefits compared to just allocating from and
5046  * freeing to kmem_cache.
5047  * 1) The time_wait_collector can free (which includes the cleanup)
5048  * outside the squeue. So when the interrupt comes, we have a clean
5049  * connection sitting in the freelist. Obviously, this buys us
5050  * performance.
5051  *
5052  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5053  * has multiple disadvantages - tying up the squeue during alloc, and the
5054  * fact that IPSec policy initialization has to happen here which
5055  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5056  * But allocating the conn/tcp in IP land is also not the best since
5057  * we can't check the 'q' and 'q0' which are protected by squeue and
5058  * blindly allocate memory which might have to be freed here if we are
5059  * not allowed to accept the connection. By using the freelist and
5060  * putting the conn/tcp back in freelist, we don't pay a penalty for
5061  * allocating memory without checking 'q/q0' and freeing it if we can't
5062  * accept the connection.
5063  *
5064  * Care should be taken to put the conn back in the same squeue's freelist
5065  * from which it was allocated. Best results are obtained if conn is
5066  * allocated from listener's squeue and freed to the same. Time wait
5067  * collector will free up the freelist is the connection ends up sitting
5068  * there for too long.
5069  */
5070 void *
5071 tcp_get_conn(void *arg)
5072 {
5073 	tcp_t			*tcp = NULL;
5074 	conn_t			*connp = NULL;
5075 	squeue_t		*sqp = (squeue_t *)arg;
5076 	tcp_squeue_priv_t 	*tcp_time_wait;
5077 
5078 	tcp_time_wait =
5079 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5080 
5081 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5082 	tcp = tcp_time_wait->tcp_free_list;
5083 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5084 	if (tcp != NULL) {
5085 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5086 		tcp_time_wait->tcp_free_list_cnt--;
5087 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5088 		tcp->tcp_time_wait_next = NULL;
5089 		connp = tcp->tcp_connp;
5090 		connp->conn_flags |= IPCL_REUSED;
5091 		return ((void *)connp);
5092 	}
5093 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5094 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP)) == NULL)
5095 		return (NULL);
5096 	return ((void *)connp);
5097 }
5098 
5099 /* BEGIN CSTYLED */
5100 /*
5101  *
5102  * The sockfs ACCEPT path:
5103  * =======================
5104  *
5105  * The eager is now established in its own perimeter as soon as SYN is
5106  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5107  * completes the accept processing on the acceptor STREAM. The sending
5108  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5109  * listener but a TLI/XTI listener completes the accept processing
5110  * on the listener perimeter.
5111  *
5112  * Common control flow for 3 way handshake:
5113  * ----------------------------------------
5114  *
5115  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5116  *					-> tcp_conn_request()
5117  *
5118  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5119  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5120  *
5121  * Sockfs ACCEPT Path:
5122  * -------------------
5123  *
5124  * open acceptor stream (ip_tcpopen allocates tcp_wput_accept()
5125  * as STREAM entry point)
5126  *
5127  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5128  *
5129  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5130  * association (we are not behind eager's squeue but sockfs is protecting us
5131  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5132  * is changed to point at tcp_wput().
5133  *
5134  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5135  * listener (done on listener's perimeter).
5136  *
5137  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5138  * accept.
5139  *
5140  * TLI/XTI client ACCEPT path:
5141  * ---------------------------
5142  *
5143  * soaccept() sends T_CONN_RES on the listener STREAM.
5144  *
5145  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5146  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5147  *
5148  * Locks:
5149  * ======
5150  *
5151  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5152  * and listeners->tcp_eager_next_q.
5153  *
5154  * Referencing:
5155  * ============
5156  *
5157  * 1) We start out in tcp_conn_request by eager placing a ref on
5158  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5159  *
5160  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5161  * doing so we place a ref on the eager. This ref is finally dropped at the
5162  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5163  * reference is dropped by the squeue framework.
5164  *
5165  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5166  *
5167  * The reference must be released by the same entity that added the reference
5168  * In the above scheme, the eager is the entity that adds and releases the
5169  * references. Note that tcp_accept_finish executes in the squeue of the eager
5170  * (albeit after it is attached to the acceptor stream). Though 1. executes
5171  * in the listener's squeue, the eager is nascent at this point and the
5172  * reference can be considered to have been added on behalf of the eager.
5173  *
5174  * Eager getting a Reset or listener closing:
5175  * ==========================================
5176  *
5177  * Once the listener and eager are linked, the listener never does the unlink.
5178  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5179  * a message on all eager perimeter. The eager then does the unlink, clears
5180  * any pointers to the listener's queue and drops the reference to the
5181  * listener. The listener waits in tcp_close outside the squeue until its
5182  * refcount has dropped to 1. This ensures that the listener has waited for
5183  * all eagers to clear their association with the listener.
5184  *
5185  * Similarly, if eager decides to go away, it can unlink itself and close.
5186  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5187  * the reference to eager is still valid because of the extra ref we put
5188  * in tcp_send_conn_ind.
5189  *
5190  * Listener can always locate the eager under the protection
5191  * of the listener->tcp_eager_lock, and then do a refhold
5192  * on the eager during the accept processing.
5193  *
5194  * The acceptor stream accesses the eager in the accept processing
5195  * based on the ref placed on eager before sending T_conn_ind.
5196  * The only entity that can negate this refhold is a listener close
5197  * which is mutually exclusive with an active acceptor stream.
5198  *
5199  * Eager's reference on the listener
5200  * ===================================
5201  *
5202  * If the accept happens (even on a closed eager) the eager drops its
5203  * reference on the listener at the start of tcp_accept_finish. If the
5204  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5205  * the reference is dropped in tcp_closei_local. If the listener closes,
5206  * the reference is dropped in tcp_eager_kill. In all cases the reference
5207  * is dropped while executing in the eager's context (squeue).
5208  */
5209 /* END CSTYLED */
5210 
5211 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5212 
5213 /*
5214  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5215  * tcp_rput_data will not see any SYN packets.
5216  */
5217 /* ARGSUSED */
5218 void
5219 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5220 {
5221 	tcph_t		*tcph;
5222 	uint32_t	seg_seq;
5223 	tcp_t		*eager;
5224 	uint_t		ipvers;
5225 	ipha_t		*ipha;
5226 	ip6_t		*ip6h;
5227 	int		err;
5228 	conn_t		*econnp = NULL;
5229 	squeue_t	*new_sqp;
5230 	mblk_t		*mp1;
5231 	uint_t 		ip_hdr_len;
5232 	conn_t		*connp = (conn_t *)arg;
5233 	tcp_t		*tcp = connp->conn_tcp;
5234 	ire_t		*ire;
5235 
5236 	if (tcp->tcp_state != TCPS_LISTEN)
5237 		goto error2;
5238 
5239 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5240 
5241 	mutex_enter(&tcp->tcp_eager_lock);
5242 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5243 		mutex_exit(&tcp->tcp_eager_lock);
5244 		TCP_STAT(tcp_listendrop);
5245 		BUMP_MIB(&tcp_mib, tcpListenDrop);
5246 		if (tcp->tcp_debug) {
5247 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5248 			    "tcp_conn_request: listen backlog (max=%d) "
5249 			    "overflow (%d pending) on %s",
5250 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5251 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5252 		}
5253 		goto error2;
5254 	}
5255 
5256 	if (tcp->tcp_conn_req_cnt_q0 >=
5257 	    tcp->tcp_conn_req_max + tcp_conn_req_max_q0) {
5258 		/*
5259 		 * Q0 is full. Drop a pending half-open req from the queue
5260 		 * to make room for the new SYN req. Also mark the time we
5261 		 * drop a SYN.
5262 		 *
5263 		 * A more aggressive defense against SYN attack will
5264 		 * be to set the "tcp_syn_defense" flag now.
5265 		 */
5266 		TCP_STAT(tcp_listendropq0);
5267 		tcp->tcp_last_rcv_lbolt = lbolt64;
5268 		if (!tcp_drop_q0(tcp)) {
5269 			mutex_exit(&tcp->tcp_eager_lock);
5270 			BUMP_MIB(&tcp_mib, tcpListenDropQ0);
5271 			if (tcp->tcp_debug) {
5272 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5273 				    "tcp_conn_request: listen half-open queue "
5274 				    "(max=%d) full (%d pending) on %s",
5275 				    tcp_conn_req_max_q0,
5276 				    tcp->tcp_conn_req_cnt_q0,
5277 				    tcp_display(tcp, NULL,
5278 				    DISP_PORT_ONLY));
5279 			}
5280 			goto error2;
5281 		}
5282 	}
5283 	mutex_exit(&tcp->tcp_eager_lock);
5284 
5285 	/*
5286 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5287 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5288 	 * link local address.  If IPSec is enabled, db_struioflag has
5289 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5290 	 * otherwise an error case if neither of them is set.
5291 	 */
5292 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5293 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5294 		DB_CKSUMSTART(mp) = 0;
5295 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5296 		econnp = (conn_t *)tcp_get_conn(arg2);
5297 		if (econnp == NULL)
5298 			goto error2;
5299 		econnp->conn_sqp = new_sqp;
5300 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5301 		/*
5302 		 * mp is updated in tcp_get_ipsec_conn().
5303 		 */
5304 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5305 		if (econnp == NULL) {
5306 			/*
5307 			 * mp freed by tcp_get_ipsec_conn.
5308 			 */
5309 			return;
5310 		}
5311 	} else {
5312 		goto error2;
5313 	}
5314 
5315 	ASSERT(DB_TYPE(mp) == M_DATA);
5316 
5317 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5318 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5319 	ASSERT(OK_32PTR(mp->b_rptr));
5320 	if (ipvers == IPV4_VERSION) {
5321 		ipha = (ipha_t *)mp->b_rptr;
5322 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5323 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5324 	} else {
5325 		ip6h = (ip6_t *)mp->b_rptr;
5326 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5327 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5328 	}
5329 
5330 	if (tcp->tcp_family == AF_INET) {
5331 		ASSERT(ipvers == IPV4_VERSION);
5332 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5333 	} else {
5334 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5335 	}
5336 
5337 	if (err)
5338 		goto error3;
5339 
5340 	eager = econnp->conn_tcp;
5341 
5342 	/* Inherit various TCP parameters from the listener */
5343 	eager->tcp_naglim = tcp->tcp_naglim;
5344 	eager->tcp_first_timer_threshold =
5345 	    tcp->tcp_first_timer_threshold;
5346 	eager->tcp_second_timer_threshold =
5347 	    tcp->tcp_second_timer_threshold;
5348 
5349 	eager->tcp_first_ctimer_threshold =
5350 	    tcp->tcp_first_ctimer_threshold;
5351 	eager->tcp_second_ctimer_threshold =
5352 	    tcp->tcp_second_ctimer_threshold;
5353 
5354 	/*
5355 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5356 	 * If it does not, the eager's receive window will be set to the
5357 	 * listener's receive window later in this function.
5358 	 */
5359 	eager->tcp_rwnd = 0;
5360 
5361 	/*
5362 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5363 	 * zone id before the accept is completed in tcp_wput_accept().
5364 	 */
5365 	econnp->conn_zoneid = connp->conn_zoneid;
5366 
5367 	/* Copy nexthop information from listener to eager */
5368 	if (connp->conn_nexthop_set) {
5369 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5370 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5371 	}
5372 
5373 	eager->tcp_hard_binding = B_TRUE;
5374 
5375 	tcp_bind_hash_insert(&tcp_bind_fanout[
5376 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5377 
5378 	CL_INET_CONNECT(eager);
5379 
5380 	/*
5381 	 * No need to check for multicast destination since ip will only pass
5382 	 * up multicasts to those that have expressed interest
5383 	 * TODO: what about rejecting broadcasts?
5384 	 * Also check that source is not a multicast or broadcast address.
5385 	 */
5386 	eager->tcp_state = TCPS_SYN_RCVD;
5387 
5388 
5389 	/*
5390 	 * There should be no ire in the mp as we are being called after
5391 	 * receiving the SYN.
5392 	 */
5393 	ASSERT(tcp_ire_mp(mp) == NULL);
5394 
5395 	/*
5396 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5397 	 */
5398 
5399 	if (tcp_adapt_ire(eager, NULL) == 0) {
5400 		/* Undo the bind_hash_insert */
5401 		tcp_bind_hash_remove(eager);
5402 		goto error3;
5403 	}
5404 
5405 	/* Process all TCP options. */
5406 	tcp_process_options(eager, tcph);
5407 
5408 	/* Is the other end ECN capable? */
5409 	if (tcp_ecn_permitted >= 1 &&
5410 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5411 		eager->tcp_ecn_ok = B_TRUE;
5412 	}
5413 
5414 	/*
5415 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5416 	 * window size changed via SO_RCVBUF option.  First round up the
5417 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5418 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5419 	 * setting.
5420 	 *
5421 	 * Note if there is a rpipe metric associated with the remote host,
5422 	 * we should not inherit receive window size from listener.
5423 	 */
5424 	eager->tcp_rwnd = MSS_ROUNDUP(
5425 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5426 	    eager->tcp_rwnd), eager->tcp_mss);
5427 	if (eager->tcp_snd_ws_ok)
5428 		tcp_set_ws_value(eager);
5429 	/*
5430 	 * Note that this is the only place tcp_rwnd_set() is called for
5431 	 * accepting a connection.  We need to call it here instead of
5432 	 * after the 3-way handshake because we need to tell the other
5433 	 * side our rwnd in the SYN-ACK segment.
5434 	 */
5435 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5436 
5437 	/*
5438 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5439 	 * via soaccept()->soinheritoptions() which essentially applies
5440 	 * all the listener options to the new STREAM. The options that we
5441 	 * need to take care of are:
5442 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5443 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5444 	 * SO_SNDBUF, SO_RCVBUF.
5445 	 *
5446 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5447 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5448 	 *		tcp_maxpsz_set() gets called later from
5449 	 *		tcp_accept_finish(), the option takes effect.
5450 	 *
5451 	 */
5452 	/* Set the TCP options */
5453 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5454 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5455 	eager->tcp_oobinline = tcp->tcp_oobinline;
5456 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5457 	eager->tcp_broadcast = tcp->tcp_broadcast;
5458 	eager->tcp_useloopback = tcp->tcp_useloopback;
5459 	eager->tcp_dontroute = tcp->tcp_dontroute;
5460 	eager->tcp_linger = tcp->tcp_linger;
5461 	eager->tcp_lingertime = tcp->tcp_lingertime;
5462 	if (tcp->tcp_ka_enabled)
5463 		eager->tcp_ka_enabled = 1;
5464 
5465 	/* Set the IP options */
5466 	econnp->conn_broadcast = connp->conn_broadcast;
5467 	econnp->conn_loopback = connp->conn_loopback;
5468 	econnp->conn_dontroute = connp->conn_dontroute;
5469 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5470 
5471 	/* Put a ref on the listener for the eager. */
5472 	CONN_INC_REF(connp);
5473 	mutex_enter(&tcp->tcp_eager_lock);
5474 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5475 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5476 	tcp->tcp_eager_next_q0 = eager;
5477 	eager->tcp_eager_prev_q0 = tcp;
5478 
5479 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5480 	eager->tcp_listener = tcp;
5481 	eager->tcp_saved_listener = tcp;
5482 
5483 	/*
5484 	 * Tag this detached tcp vector for later retrieval
5485 	 * by our listener client in tcp_accept().
5486 	 */
5487 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5488 	tcp->tcp_conn_req_cnt_q0++;
5489 	if (++tcp->tcp_conn_req_seqnum == -1) {
5490 		/*
5491 		 * -1 is "special" and defined in TPI as something
5492 		 * that should never be used in T_CONN_IND
5493 		 */
5494 		++tcp->tcp_conn_req_seqnum;
5495 	}
5496 	mutex_exit(&tcp->tcp_eager_lock);
5497 
5498 	if (tcp->tcp_syn_defense) {
5499 		/* Don't drop the SYN that comes from a good IP source */
5500 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5501 		if (addr_cache != NULL && eager->tcp_remote ==
5502 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5503 			eager->tcp_dontdrop = B_TRUE;
5504 		}
5505 	}
5506 
5507 	/*
5508 	 * We need to insert the eager in its own perimeter but as soon
5509 	 * as we do that, we expose the eager to the classifier and
5510 	 * should not touch any field outside the eager's perimeter.
5511 	 * So do all the work necessary before inserting the eager
5512 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5513 	 * will succeed but undo everything if it fails.
5514 	 */
5515 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5516 	eager->tcp_irs = seg_seq;
5517 	eager->tcp_rack = seg_seq;
5518 	eager->tcp_rnxt = seg_seq + 1;
5519 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5520 	BUMP_MIB(&tcp_mib, tcpPassiveOpens);
5521 	eager->tcp_state = TCPS_SYN_RCVD;
5522 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5523 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5524 	if (mp1 == NULL)
5525 		goto error1;
5526 	mblk_setcred(mp1, tcp->tcp_cred);
5527 	DB_CPID(mp1) = tcp->tcp_cpid;
5528 
5529 	/*
5530 	 * We need to start the rto timer. In normal case, we start
5531 	 * the timer after sending the packet on the wire (or at
5532 	 * least believing that packet was sent by waiting for
5533 	 * CALL_IP_WPUT() to return). Since this is the first packet
5534 	 * being sent on the wire for the eager, our initial tcp_rto
5535 	 * is at least tcp_rexmit_interval_min which is a fairly
5536 	 * large value to allow the algorithm to adjust slowly to large
5537 	 * fluctuations of RTT during first few transmissions.
5538 	 *
5539 	 * Starting the timer first and then sending the packet in this
5540 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5541 	 * is of the order of several 100ms and starting the timer
5542 	 * first and then sending the packet will result in difference
5543 	 * of few micro seconds.
5544 	 *
5545 	 * Without this optimization, we are forced to hold the fanout
5546 	 * lock across the ipcl_bind_insert() and sending the packet
5547 	 * so that we don't race against an incoming packet (maybe RST)
5548 	 * for this eager.
5549 	 */
5550 
5551 	TCP_RECORD_TRACE(eager, mp1, TCP_TRACE_SEND_PKT);
5552 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5553 
5554 
5555 	/*
5556 	 * Insert the eager in its own perimeter now. We are ready to deal
5557 	 * with any packets on eager.
5558 	 */
5559 	if (eager->tcp_ipversion == IPV4_VERSION) {
5560 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5561 			goto error;
5562 		}
5563 	} else {
5564 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5565 			goto error;
5566 		}
5567 	}
5568 
5569 	/* mark conn as fully-bound */
5570 	econnp->conn_fully_bound = B_TRUE;
5571 
5572 	/* Send the SYN-ACK */
5573 	tcp_send_data(eager, eager->tcp_wq, mp1);
5574 	freemsg(mp);
5575 
5576 	return;
5577 error:
5578 	(void) TCP_TIMER_CANCEL(eager, eager->tcp_timer_tid);
5579 	freemsg(mp1);
5580 error1:
5581 	/* Undo what we did above */
5582 	mutex_enter(&tcp->tcp_eager_lock);
5583 	tcp_eager_unlink(eager);
5584 	mutex_exit(&tcp->tcp_eager_lock);
5585 	/* Drop eager's reference on the listener */
5586 	CONN_DEC_REF(connp);
5587 
5588 	/*
5589 	 * Delete the cached ire in conn_ire_cache and also mark
5590 	 * the conn as CONDEMNED
5591 	 */
5592 	mutex_enter(&econnp->conn_lock);
5593 	econnp->conn_state_flags |= CONN_CONDEMNED;
5594 	ire = econnp->conn_ire_cache;
5595 	econnp->conn_ire_cache = NULL;
5596 	mutex_exit(&econnp->conn_lock);
5597 	if (ire != NULL)
5598 		IRE_REFRELE_NOTR(ire);
5599 
5600 	/*
5601 	 * tcp_accept_comm inserts the eager to the bind_hash
5602 	 * we need to remove it from the hash if ipcl_conn_insert
5603 	 * fails.
5604 	 */
5605 	tcp_bind_hash_remove(eager);
5606 	/* Drop the eager ref placed in tcp_open_detached */
5607 	CONN_DEC_REF(econnp);
5608 
5609 	/*
5610 	 * If a connection already exists, send the mp to that connections so
5611 	 * that it can be appropriately dealt with.
5612 	 */
5613 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid)) != NULL) {
5614 		if (!IPCL_IS_CONNECTED(econnp)) {
5615 			/*
5616 			 * Something bad happened. ipcl_conn_insert()
5617 			 * failed because a connection already existed
5618 			 * in connected hash but we can't find it
5619 			 * anymore (someone blew it away). Just
5620 			 * free this message and hopefully remote
5621 			 * will retransmit at which time the SYN can be
5622 			 * treated as a new connection or dealth with
5623 			 * a TH_RST if a connection already exists.
5624 			 */
5625 			freemsg(mp);
5626 		} else {
5627 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
5628 			    econnp, SQTAG_TCP_CONN_REQ);
5629 		}
5630 	} else {
5631 		/* Nobody wants this packet */
5632 		freemsg(mp);
5633 	}
5634 	return;
5635 error2:
5636 	freemsg(mp);
5637 	return;
5638 error3:
5639 	CONN_DEC_REF(econnp);
5640 	freemsg(mp);
5641 }
5642 
5643 /*
5644  * In an ideal case of vertical partition in NUMA architecture, its
5645  * beneficial to have the listener and all the incoming connections
5646  * tied to the same squeue. The other constraint is that incoming
5647  * connections should be tied to the squeue attached to interrupted
5648  * CPU for obvious locality reason so this leaves the listener to
5649  * be tied to the same squeue. Our only problem is that when listener
5650  * is binding, the CPU that will get interrupted by the NIC whose
5651  * IP address the listener is binding to is not even known. So
5652  * the code below allows us to change that binding at the time the
5653  * CPU is interrupted by virtue of incoming connection's squeue.
5654  *
5655  * This is usefull only in case of a listener bound to a specific IP
5656  * address. For other kind of listeners, they get bound the
5657  * very first time and there is no attempt to rebind them.
5658  */
5659 void
5660 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5661 {
5662 	conn_t		*connp = (conn_t *)arg;
5663 	squeue_t	*sqp = (squeue_t *)arg2;
5664 	squeue_t	*new_sqp;
5665 	uint32_t	conn_flags;
5666 
5667 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5668 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5669 	} else {
5670 		goto done;
5671 	}
5672 
5673 	if (connp->conn_fanout == NULL)
5674 		goto done;
5675 
5676 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5677 		mutex_enter(&connp->conn_fanout->connf_lock);
5678 		mutex_enter(&connp->conn_lock);
5679 		/*
5680 		 * No one from read or write side can access us now
5681 		 * except for already queued packets on this squeue.
5682 		 * But since we haven't changed the squeue yet, they
5683 		 * can't execute. If they are processed after we have
5684 		 * changed the squeue, they are sent back to the
5685 		 * correct squeue down below.
5686 		 */
5687 		if (connp->conn_sqp != new_sqp) {
5688 			while (connp->conn_sqp != new_sqp)
5689 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5690 		}
5691 
5692 		do {
5693 			conn_flags = connp->conn_flags;
5694 			conn_flags |= IPCL_FULLY_BOUND;
5695 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5696 			    conn_flags);
5697 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5698 
5699 		mutex_exit(&connp->conn_fanout->connf_lock);
5700 		mutex_exit(&connp->conn_lock);
5701 	}
5702 
5703 done:
5704 	if (connp->conn_sqp != sqp) {
5705 		CONN_INC_REF(connp);
5706 		squeue_fill(connp->conn_sqp, mp,
5707 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
5708 	} else {
5709 		tcp_conn_request(connp, mp, sqp);
5710 	}
5711 }
5712 
5713 /*
5714  * Successful connect request processing begins when our client passes
5715  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5716  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5717  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
5718  *   upstream <- tcp_rput()                <- IP
5719  * After various error checks are completed, tcp_connect() lays
5720  * the target address and port into the composite header template,
5721  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5722  * request followed by an IRE request, and passes the three mblk message
5723  * down to IP looking like this:
5724  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5725  * Processing continues in tcp_rput() when we receive the following message:
5726  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5727  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5728  * to fire off the connection request, and then passes the T_OK_ACK mblk
5729  * upstream that we filled in below.  There are, of course, numerous
5730  * error conditions along the way which truncate the processing described
5731  * above.
5732  */
5733 static void
5734 tcp_connect(tcp_t *tcp, mblk_t *mp)
5735 {
5736 	sin_t		*sin;
5737 	sin6_t		*sin6;
5738 	queue_t		*q = tcp->tcp_wq;
5739 	struct T_conn_req	*tcr;
5740 	ipaddr_t	*dstaddrp;
5741 	in_port_t	dstport;
5742 	uint_t		srcid;
5743 
5744 	tcr = (struct T_conn_req *)mp->b_rptr;
5745 
5746 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5747 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5748 		tcp_err_ack(tcp, mp, TPROTO, 0);
5749 		return;
5750 	}
5751 
5752 	/*
5753 	 * Determine packet type based on type of address passed in
5754 	 * the request should contain an IPv4 or IPv6 address.
5755 	 * Make sure that address family matches the type of
5756 	 * family of the the address passed down
5757 	 */
5758 	switch (tcr->DEST_length) {
5759 	default:
5760 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5761 		return;
5762 
5763 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5764 		/*
5765 		 * XXX: The check for valid DEST_length was not there
5766 		 * in earlier releases and some buggy
5767 		 * TLI apps (e.g Sybase) got away with not feeding
5768 		 * in sin_zero part of address.
5769 		 * We allow that bug to keep those buggy apps humming.
5770 		 * Test suites require the check on DEST_length.
5771 		 * We construct a new mblk with valid DEST_length
5772 		 * free the original so the rest of the code does
5773 		 * not have to keep track of this special shorter
5774 		 * length address case.
5775 		 */
5776 		mblk_t *nmp;
5777 		struct T_conn_req *ntcr;
5778 		sin_t *nsin;
5779 
5780 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5781 		    tcr->OPT_length, BPRI_HI);
5782 		if (nmp == NULL) {
5783 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5784 			return;
5785 		}
5786 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5787 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5788 		ntcr->PRIM_type = T_CONN_REQ;
5789 		ntcr->DEST_length = sizeof (sin_t);
5790 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5791 
5792 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5793 		*nsin = sin_null;
5794 		/* Get pointer to shorter address to copy from original mp */
5795 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5796 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5797 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5798 			freemsg(nmp);
5799 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5800 			return;
5801 		}
5802 		nsin->sin_family = sin->sin_family;
5803 		nsin->sin_port = sin->sin_port;
5804 		nsin->sin_addr = sin->sin_addr;
5805 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5806 		nmp->b_wptr = (uchar_t *)&nsin[1];
5807 		if (tcr->OPT_length != 0) {
5808 			ntcr->OPT_length = tcr->OPT_length;
5809 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5810 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5811 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5812 			    tcr->OPT_length);
5813 			nmp->b_wptr += tcr->OPT_length;
5814 		}
5815 		freemsg(mp);	/* original mp freed */
5816 		mp = nmp;	/* re-initialize original variables */
5817 		tcr = ntcr;
5818 	}
5819 	/* FALLTHRU */
5820 
5821 	case sizeof (sin_t):
5822 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5823 		    sizeof (sin_t));
5824 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5825 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5826 			return;
5827 		}
5828 		if (tcp->tcp_family != AF_INET ||
5829 		    sin->sin_family != AF_INET) {
5830 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5831 			return;
5832 		}
5833 		if (sin->sin_port == 0) {
5834 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5835 			return;
5836 		}
5837 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
5838 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5839 			return;
5840 		}
5841 
5842 		break;
5843 
5844 	case sizeof (sin6_t):
5845 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
5846 		    sizeof (sin6_t));
5847 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
5848 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5849 			return;
5850 		}
5851 		if (tcp->tcp_family != AF_INET6 ||
5852 		    sin6->sin6_family != AF_INET6) {
5853 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
5854 			return;
5855 		}
5856 		if (sin6->sin6_port == 0) {
5857 			tcp_err_ack(tcp, mp, TBADADDR, 0);
5858 			return;
5859 		}
5860 		break;
5861 	}
5862 	/*
5863 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5864 	 * should key on their sequence number and cut them loose.
5865 	 */
5866 
5867 	/*
5868 	 * If options passed in, feed it for verification and handling
5869 	 */
5870 	if (tcr->OPT_length != 0) {
5871 		mblk_t	*ok_mp;
5872 		mblk_t	*discon_mp;
5873 		mblk_t  *conn_opts_mp;
5874 		int t_error, sys_error, do_disconnect;
5875 
5876 		conn_opts_mp = NULL;
5877 
5878 		if (tcp_conprim_opt_process(tcp, mp,
5879 			&do_disconnect, &t_error, &sys_error) < 0) {
5880 			if (do_disconnect) {
5881 				ASSERT(t_error == 0 && sys_error == 0);
5882 				discon_mp = mi_tpi_discon_ind(NULL,
5883 				    ECONNREFUSED, 0);
5884 				if (!discon_mp) {
5885 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5886 					    TSYSERR, ENOMEM);
5887 					return;
5888 				}
5889 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5890 				if (!ok_mp) {
5891 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5892 					    TSYSERR, ENOMEM);
5893 					return;
5894 				}
5895 				qreply(q, ok_mp);
5896 				qreply(q, discon_mp); /* no flush! */
5897 			} else {
5898 				ASSERT(t_error != 0);
5899 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5900 				    sys_error);
5901 			}
5902 			return;
5903 		}
5904 		/*
5905 		 * Success in setting options, the mp option buffer represented
5906 		 * by OPT_length/offset has been potentially modified and
5907 		 * contains results of option processing. We copy it in
5908 		 * another mp to save it for potentially influencing returning
5909 		 * it in T_CONN_CONN.
5910 		 */
5911 		if (tcr->OPT_length != 0) { /* there are resulting options */
5912 			conn_opts_mp = copyb(mp);
5913 			if (!conn_opts_mp) {
5914 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5915 				    TSYSERR, ENOMEM);
5916 				return;
5917 			}
5918 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5919 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5920 			/*
5921 			 * Note:
5922 			 * These resulting option negotiation can include any
5923 			 * end-to-end negotiation options but there no such
5924 			 * thing (yet?) in our TCP/IP.
5925 			 */
5926 		}
5927 	}
5928 
5929 	/*
5930 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
5931 	 * make sure that the template IP header in the tcp structure is an
5932 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
5933 	 * need to this before we call tcp_bindi() so that the port lookup
5934 	 * code will look for ports in the correct port space (IPv4 and
5935 	 * IPv6 have separate port spaces).
5936 	 */
5937 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
5938 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5939 		int err = 0;
5940 
5941 		err = tcp_header_init_ipv4(tcp);
5942 		if (err != 0) {
5943 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
5944 			goto connect_failed;
5945 		}
5946 		if (tcp->tcp_lport != 0)
5947 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
5948 	}
5949 
5950 	switch (tcp->tcp_state) {
5951 	case TCPS_IDLE:
5952 		/*
5953 		 * We support quick connect, refer to comments in
5954 		 * tcp_connect_*()
5955 		 */
5956 		/* FALLTHRU */
5957 	case TCPS_BOUND:
5958 	case TCPS_LISTEN:
5959 		if (tcp->tcp_family == AF_INET6) {
5960 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
5961 				tcp_connect_ipv6(tcp, mp,
5962 				    &sin6->sin6_addr,
5963 				    sin6->sin6_port, sin6->sin6_flowinfo,
5964 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
5965 				return;
5966 			}
5967 			/*
5968 			 * Destination adress is mapped IPv6 address.
5969 			 * Source bound address should be unspecified or
5970 			 * IPv6 mapped address as well.
5971 			 */
5972 			if (!IN6_IS_ADDR_UNSPECIFIED(
5973 			    &tcp->tcp_bound_source_v6) &&
5974 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
5975 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
5976 				    EADDRNOTAVAIL);
5977 				break;
5978 			}
5979 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
5980 			dstport = sin6->sin6_port;
5981 			srcid = sin6->__sin6_src_id;
5982 		} else {
5983 			dstaddrp = &sin->sin_addr.s_addr;
5984 			dstport = sin->sin_port;
5985 			srcid = 0;
5986 		}
5987 
5988 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
5989 		return;
5990 	default:
5991 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
5992 		break;
5993 	}
5994 	/*
5995 	 * Note: Code below is the "failure" case
5996 	 */
5997 	/* return error ack and blow away saved option results if any */
5998 connect_failed:
5999 	if (mp != NULL)
6000 		putnext(tcp->tcp_rq, mp);
6001 	else {
6002 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6003 		    TSYSERR, ENOMEM);
6004 	}
6005 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6006 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6007 }
6008 
6009 /*
6010  * Handle connect to IPv4 destinations, including connections for AF_INET6
6011  * sockets connecting to IPv4 mapped IPv6 destinations.
6012  */
6013 static void
6014 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6015     uint_t srcid)
6016 {
6017 	tcph_t	*tcph;
6018 	mblk_t	*mp1;
6019 	ipaddr_t dstaddr = *dstaddrp;
6020 	int32_t	oldstate;
6021 	uint16_t lport;
6022 
6023 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6024 
6025 	/* Check for attempt to connect to INADDR_ANY */
6026 	if (dstaddr == INADDR_ANY)  {
6027 		/*
6028 		 * SunOS 4.x and 4.3 BSD allow an application
6029 		 * to connect a TCP socket to INADDR_ANY.
6030 		 * When they do this, the kernel picks the
6031 		 * address of one interface and uses it
6032 		 * instead.  The kernel usually ends up
6033 		 * picking the address of the loopback
6034 		 * interface.  This is an undocumented feature.
6035 		 * However, we provide the same thing here
6036 		 * in order to have source and binary
6037 		 * compatibility with SunOS 4.x.
6038 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6039 		 * generate the T_CONN_CON.
6040 		 */
6041 		dstaddr = htonl(INADDR_LOOPBACK);
6042 		*dstaddrp = dstaddr;
6043 	}
6044 
6045 	/* Handle __sin6_src_id if socket not bound to an IP address */
6046 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6047 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6048 		    tcp->tcp_connp->conn_zoneid);
6049 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6050 		    tcp->tcp_ipha->ipha_src);
6051 	}
6052 
6053 	/*
6054 	 * Don't let an endpoint connect to itself.  Note that
6055 	 * the test here does not catch the case where the
6056 	 * source IP addr was left unspecified by the user. In
6057 	 * this case, the source addr is set in tcp_adapt_ire()
6058 	 * using the reply to the T_BIND message that we send
6059 	 * down to IP here and the check is repeated in tcp_rput_other.
6060 	 */
6061 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6062 	    dstport == tcp->tcp_lport) {
6063 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6064 		goto failed;
6065 	}
6066 
6067 	tcp->tcp_ipha->ipha_dst = dstaddr;
6068 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6069 
6070 	/*
6071 	 * Massage a source route if any putting the first hop
6072 	 * in iph_dst. Compute a starting value for the checksum which
6073 	 * takes into account that the original iph_dst should be
6074 	 * included in the checksum but that ip will include the
6075 	 * first hop in the source route in the tcp checksum.
6076 	 */
6077 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha);
6078 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6079 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6080 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6081 	if ((int)tcp->tcp_sum < 0)
6082 		tcp->tcp_sum--;
6083 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6084 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6085 	    (tcp->tcp_sum >> 16));
6086 	tcph = tcp->tcp_tcph;
6087 	*(uint16_t *)tcph->th_fport = dstport;
6088 	tcp->tcp_fport = dstport;
6089 
6090 	oldstate = tcp->tcp_state;
6091 	/*
6092 	 * At this point the remote destination address and remote port fields
6093 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6094 	 * have to see which state tcp was in so we can take apropriate action.
6095 	 */
6096 	if (oldstate == TCPS_IDLE) {
6097 		/*
6098 		 * We support a quick connect capability here, allowing
6099 		 * clients to transition directly from IDLE to SYN_SENT
6100 		 * tcp_bindi will pick an unused port, insert the connection
6101 		 * in the bind hash and transition to BOUND state.
6102 		 */
6103 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6104 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6105 		    B_FALSE, B_FALSE);
6106 		if (lport == 0) {
6107 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6108 			goto failed;
6109 		}
6110 	}
6111 	tcp->tcp_state = TCPS_SYN_SENT;
6112 
6113 	/*
6114 	 * TODO: allow data with connect requests
6115 	 * by unlinking M_DATA trailers here and
6116 	 * linking them in behind the T_OK_ACK mblk.
6117 	 * The tcp_rput() bind ack handler would then
6118 	 * feed them to tcp_wput_data() rather than call
6119 	 * tcp_timer().
6120 	 */
6121 	mp = mi_tpi_ok_ack_alloc(mp);
6122 	if (!mp) {
6123 		tcp->tcp_state = oldstate;
6124 		goto failed;
6125 	}
6126 	if (tcp->tcp_family == AF_INET) {
6127 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6128 		    sizeof (ipa_conn_t));
6129 	} else {
6130 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6131 		    sizeof (ipa6_conn_t));
6132 	}
6133 	if (mp1) {
6134 		/* Hang onto the T_OK_ACK for later. */
6135 		linkb(mp1, mp);
6136 		if (tcp->tcp_family == AF_INET)
6137 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6138 		else {
6139 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6140 			    &tcp->tcp_sticky_ipp);
6141 		}
6142 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6143 		tcp->tcp_active_open = 1;
6144 		/*
6145 		 * If the bind cannot complete immediately
6146 		 * IP will arrange to call tcp_rput_other
6147 		 * when the bind completes.
6148 		 */
6149 		if (mp1 != NULL)
6150 			tcp_rput_other(tcp, mp1);
6151 		return;
6152 	}
6153 	/* Error case */
6154 	tcp->tcp_state = oldstate;
6155 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6156 
6157 failed:
6158 	/* return error ack and blow away saved option results if any */
6159 	if (mp != NULL)
6160 		putnext(tcp->tcp_rq, mp);
6161 	else {
6162 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6163 		    TSYSERR, ENOMEM);
6164 	}
6165 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6166 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6167 
6168 }
6169 
6170 /*
6171  * Handle connect to IPv6 destinations.
6172  */
6173 static void
6174 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6175     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6176 {
6177 	tcph_t	*tcph;
6178 	mblk_t	*mp1;
6179 	ip6_rthdr_t *rth;
6180 	int32_t  oldstate;
6181 	uint16_t lport;
6182 
6183 	ASSERT(tcp->tcp_family == AF_INET6);
6184 
6185 	/*
6186 	 * If we're here, it means that the destination address is a native
6187 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6188 	 * reason why it might not be IPv6 is if the socket was bound to an
6189 	 * IPv4-mapped IPv6 address.
6190 	 */
6191 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6192 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6193 		goto failed;
6194 	}
6195 
6196 	/*
6197 	 * Interpret a zero destination to mean loopback.
6198 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6199 	 * generate the T_CONN_CON.
6200 	 */
6201 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6202 		*dstaddrp = ipv6_loopback;
6203 	}
6204 
6205 	/* Handle __sin6_src_id if socket not bound to an IP address */
6206 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6207 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6208 		    tcp->tcp_connp->conn_zoneid);
6209 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6210 	}
6211 
6212 	/*
6213 	 * Take care of the scope_id now and add ip6i_t
6214 	 * if ip6i_t is not already allocated through TCP
6215 	 * sticky options. At this point tcp_ip6h does not
6216 	 * have dst info, thus use dstaddrp.
6217 	 */
6218 	if (scope_id != 0 &&
6219 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6220 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6221 		ip6i_t  *ip6i;
6222 
6223 		ipp->ipp_ifindex = scope_id;
6224 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6225 
6226 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6227 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6228 			/* Already allocated */
6229 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6230 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6231 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6232 		} else {
6233 			int reterr;
6234 
6235 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6236 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6237 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6238 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6239 			if (reterr != 0)
6240 				goto failed;
6241 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6242 		}
6243 	}
6244 
6245 	/*
6246 	 * Don't let an endpoint connect to itself.  Note that
6247 	 * the test here does not catch the case where the
6248 	 * source IP addr was left unspecified by the user. In
6249 	 * this case, the source addr is set in tcp_adapt_ire()
6250 	 * using the reply to the T_BIND message that we send
6251 	 * down to IP here and the check is repeated in tcp_rput_other.
6252 	 */
6253 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6254 	    (dstport == tcp->tcp_lport)) {
6255 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6256 		goto failed;
6257 	}
6258 
6259 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6260 	tcp->tcp_remote_v6 = *dstaddrp;
6261 	tcp->tcp_ip6h->ip6_vcf =
6262 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6263 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6264 
6265 
6266 	/*
6267 	 * Massage a routing header (if present) putting the first hop
6268 	 * in ip6_dst. Compute a starting value for the checksum which
6269 	 * takes into account that the original ip6_dst should be
6270 	 * included in the checksum but that ip will include the
6271 	 * first hop in the source route in the tcp checksum.
6272 	 */
6273 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6274 	if (rth != NULL) {
6275 
6276 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth);
6277 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6278 		    (tcp->tcp_sum >> 16));
6279 	} else {
6280 		tcp->tcp_sum = 0;
6281 	}
6282 
6283 	tcph = tcp->tcp_tcph;
6284 	*(uint16_t *)tcph->th_fport = dstport;
6285 	tcp->tcp_fport = dstport;
6286 
6287 	oldstate = tcp->tcp_state;
6288 	/*
6289 	 * At this point the remote destination address and remote port fields
6290 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6291 	 * have to see which state tcp was in so we can take apropriate action.
6292 	 */
6293 	if (oldstate == TCPS_IDLE) {
6294 		/*
6295 		 * We support a quick connect capability here, allowing
6296 		 * clients to transition directly from IDLE to SYN_SENT
6297 		 * tcp_bindi will pick an unused port, insert the connection
6298 		 * in the bind hash and transition to BOUND state.
6299 		 */
6300 		lport = tcp_update_next_port(tcp_next_port_to_try, B_TRUE);
6301 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6302 		    B_FALSE, B_FALSE);
6303 		if (lport == 0) {
6304 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6305 			goto failed;
6306 		}
6307 	}
6308 	tcp->tcp_state = TCPS_SYN_SENT;
6309 	/*
6310 	 * TODO: allow data with connect requests
6311 	 * by unlinking M_DATA trailers here and
6312 	 * linking them in behind the T_OK_ACK mblk.
6313 	 * The tcp_rput() bind ack handler would then
6314 	 * feed them to tcp_wput_data() rather than call
6315 	 * tcp_timer().
6316 	 */
6317 	mp = mi_tpi_ok_ack_alloc(mp);
6318 	if (!mp) {
6319 		tcp->tcp_state = oldstate;
6320 		goto failed;
6321 	}
6322 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6323 	if (mp1) {
6324 		/* Hang onto the T_OK_ACK for later. */
6325 		linkb(mp1, mp);
6326 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6327 		    &tcp->tcp_sticky_ipp);
6328 		BUMP_MIB(&tcp_mib, tcpActiveOpens);
6329 		tcp->tcp_active_open = 1;
6330 		/* ip_bind_v6() may return ACK or ERROR */
6331 		if (mp1 != NULL)
6332 			tcp_rput_other(tcp, mp1);
6333 		return;
6334 	}
6335 	/* Error case */
6336 	tcp->tcp_state = oldstate;
6337 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6338 
6339 failed:
6340 	/* return error ack and blow away saved option results if any */
6341 	if (mp != NULL)
6342 		putnext(tcp->tcp_rq, mp);
6343 	else {
6344 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6345 		    TSYSERR, ENOMEM);
6346 	}
6347 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6348 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6349 }
6350 
6351 /*
6352  * We need a stream q for detached closing tcp connections
6353  * to use.  Our client hereby indicates that this q is the
6354  * one to use.
6355  */
6356 static void
6357 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6358 {
6359 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6360 	queue_t	*q = tcp->tcp_wq;
6361 
6362 	mp->b_datap->db_type = M_IOCACK;
6363 	iocp->ioc_count = 0;
6364 	mutex_enter(&tcp_g_q_lock);
6365 	if (tcp_g_q != NULL) {
6366 		mutex_exit(&tcp_g_q_lock);
6367 		iocp->ioc_error = EALREADY;
6368 	} else {
6369 		mblk_t *mp1;
6370 
6371 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6372 		if (mp1 == NULL) {
6373 			mutex_exit(&tcp_g_q_lock);
6374 			iocp->ioc_error = ENOMEM;
6375 		} else {
6376 			tcp_g_q = tcp->tcp_rq;
6377 			mutex_exit(&tcp_g_q_lock);
6378 			iocp->ioc_error = 0;
6379 			iocp->ioc_rval = 0;
6380 			/*
6381 			 * We are passing tcp_sticky_ipp as NULL
6382 			 * as it is not useful for tcp_default queue
6383 			 */
6384 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6385 			if (mp1 != NULL)
6386 				tcp_rput_other(tcp, mp1);
6387 		}
6388 	}
6389 	qreply(q, mp);
6390 }
6391 
6392 /*
6393  * Our client hereby directs us to reject the connection request
6394  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6395  * of sending the appropriate RST, not an ICMP error.
6396  */
6397 static void
6398 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6399 {
6400 	tcp_t	*ltcp = NULL;
6401 	t_scalar_t seqnum;
6402 	conn_t	*connp;
6403 
6404 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6405 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6406 		tcp_err_ack(tcp, mp, TPROTO, 0);
6407 		return;
6408 	}
6409 
6410 	/*
6411 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6412 	 * when the stream is in BOUND state. Do not send a reset,
6413 	 * since the destination IP address is not valid, and it can
6414 	 * be the initialized value of all zeros (broadcast address).
6415 	 *
6416 	 * If TCP has sent down a bind request to IP and has not
6417 	 * received the reply, reject the request.  Otherwise, TCP
6418 	 * will be confused.
6419 	 */
6420 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6421 		if (tcp->tcp_debug) {
6422 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6423 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6424 		}
6425 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6426 		return;
6427 	}
6428 
6429 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6430 
6431 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6432 
6433 		/*
6434 		 * According to TPI, for non-listeners, ignore seqnum
6435 		 * and disconnect.
6436 		 * Following interpretation of -1 seqnum is historical
6437 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6438 		 * a valid seqnum should not be -1).
6439 		 *
6440 		 *	-1 means disconnect everything
6441 		 *	regardless even on a listener.
6442 		 */
6443 
6444 		int old_state = tcp->tcp_state;
6445 
6446 		/*
6447 		 * The connection can't be on the tcp_time_wait_head list
6448 		 * since it is not detached.
6449 		 */
6450 		ASSERT(tcp->tcp_time_wait_next == NULL);
6451 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6452 		ASSERT(tcp->tcp_time_wait_expire == 0);
6453 		ltcp = NULL;
6454 		/*
6455 		 * If it used to be a listener, check to make sure no one else
6456 		 * has taken the port before switching back to LISTEN state.
6457 		 */
6458 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6459 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6460 			    tcp->tcp_ipha->ipha_src,
6461 			    tcp->tcp_connp->conn_zoneid);
6462 			if (connp != NULL)
6463 				ltcp = connp->conn_tcp;
6464 		} else {
6465 			/* Allow tcp_bound_if listeners? */
6466 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6467 			    &tcp->tcp_ip6h->ip6_src, 0,
6468 			    tcp->tcp_connp->conn_zoneid);
6469 			if (connp != NULL)
6470 				ltcp = connp->conn_tcp;
6471 		}
6472 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6473 			tcp->tcp_state = TCPS_LISTEN;
6474 		} else if (old_state > TCPS_BOUND) {
6475 			tcp->tcp_conn_req_max = 0;
6476 			tcp->tcp_state = TCPS_BOUND;
6477 		}
6478 		if (ltcp != NULL)
6479 			CONN_DEC_REF(ltcp->tcp_connp);
6480 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6481 			BUMP_MIB(&tcp_mib, tcpAttemptFails);
6482 		} else if (old_state == TCPS_ESTABLISHED ||
6483 		    old_state == TCPS_CLOSE_WAIT) {
6484 			BUMP_MIB(&tcp_mib, tcpEstabResets);
6485 		}
6486 
6487 		if (tcp->tcp_fused)
6488 			tcp_unfuse(tcp);
6489 
6490 		mutex_enter(&tcp->tcp_eager_lock);
6491 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6492 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6493 			tcp_eager_cleanup(tcp, 0);
6494 		}
6495 		mutex_exit(&tcp->tcp_eager_lock);
6496 
6497 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6498 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6499 
6500 		tcp_reinit(tcp);
6501 
6502 		if (old_state >= TCPS_ESTABLISHED) {
6503 			/* Send M_FLUSH according to TPI */
6504 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6505 		}
6506 		mp = mi_tpi_ok_ack_alloc(mp);
6507 		if (mp)
6508 			putnext(tcp->tcp_rq, mp);
6509 		return;
6510 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6511 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6512 		return;
6513 	}
6514 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6515 		/* Send M_FLUSH according to TPI */
6516 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6517 	}
6518 	mp = mi_tpi_ok_ack_alloc(mp);
6519 	if (mp)
6520 		putnext(tcp->tcp_rq, mp);
6521 }
6522 
6523 /*
6524  * Diagnostic routine used to return a string associated with the tcp state.
6525  * Note that if the caller does not supply a buffer, it will use an internal
6526  * static string.  This means that if multiple threads call this function at
6527  * the same time, output can be corrupted...  Note also that this function
6528  * does not check the size of the supplied buffer.  The caller has to make
6529  * sure that it is big enough.
6530  */
6531 static char *
6532 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6533 {
6534 	char		buf1[30];
6535 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6536 	char		*buf;
6537 	char		*cp;
6538 	in6_addr_t	local, remote;
6539 	char		local_addrbuf[INET6_ADDRSTRLEN];
6540 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6541 
6542 	if (sup_buf != NULL)
6543 		buf = sup_buf;
6544 	else
6545 		buf = priv_buf;
6546 
6547 	if (tcp == NULL)
6548 		return ("NULL_TCP");
6549 	switch (tcp->tcp_state) {
6550 	case TCPS_CLOSED:
6551 		cp = "TCP_CLOSED";
6552 		break;
6553 	case TCPS_IDLE:
6554 		cp = "TCP_IDLE";
6555 		break;
6556 	case TCPS_BOUND:
6557 		cp = "TCP_BOUND";
6558 		break;
6559 	case TCPS_LISTEN:
6560 		cp = "TCP_LISTEN";
6561 		break;
6562 	case TCPS_SYN_SENT:
6563 		cp = "TCP_SYN_SENT";
6564 		break;
6565 	case TCPS_SYN_RCVD:
6566 		cp = "TCP_SYN_RCVD";
6567 		break;
6568 	case TCPS_ESTABLISHED:
6569 		cp = "TCP_ESTABLISHED";
6570 		break;
6571 	case TCPS_CLOSE_WAIT:
6572 		cp = "TCP_CLOSE_WAIT";
6573 		break;
6574 	case TCPS_FIN_WAIT_1:
6575 		cp = "TCP_FIN_WAIT_1";
6576 		break;
6577 	case TCPS_CLOSING:
6578 		cp = "TCP_CLOSING";
6579 		break;
6580 	case TCPS_LAST_ACK:
6581 		cp = "TCP_LAST_ACK";
6582 		break;
6583 	case TCPS_FIN_WAIT_2:
6584 		cp = "TCP_FIN_WAIT_2";
6585 		break;
6586 	case TCPS_TIME_WAIT:
6587 		cp = "TCP_TIME_WAIT";
6588 		break;
6589 	default:
6590 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6591 		cp = buf1;
6592 		break;
6593 	}
6594 	switch (format) {
6595 	case DISP_ADDR_AND_PORT:
6596 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6597 			/*
6598 			 * Note that we use the remote address in the tcp_b
6599 			 * structure.  This means that it will print out
6600 			 * the real destination address, not the next hop's
6601 			 * address if source routing is used.
6602 			 */
6603 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6604 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6605 
6606 		} else {
6607 			local = tcp->tcp_ip_src_v6;
6608 			remote = tcp->tcp_remote_v6;
6609 		}
6610 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6611 		    sizeof (local_addrbuf));
6612 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6613 		    sizeof (remote_addrbuf));
6614 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6615 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6616 		    ntohs(tcp->tcp_fport), cp);
6617 		break;
6618 	case DISP_PORT_ONLY:
6619 	default:
6620 		(void) mi_sprintf(buf, "[%u, %u] %s",
6621 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6622 		break;
6623 	}
6624 
6625 	return (buf);
6626 }
6627 
6628 /*
6629  * Called via squeue to get on to eager's perimeter to send a
6630  * TH_RST. The listener wants the eager to disappear either
6631  * by means of tcp_eager_blowoff() or tcp_eager_cleanup()
6632  * being called.
6633  */
6634 /* ARGSUSED */
6635 void
6636 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6637 {
6638 	conn_t	*econnp = (conn_t *)arg;
6639 	tcp_t	*eager = econnp->conn_tcp;
6640 	tcp_t	*listener = eager->tcp_listener;
6641 
6642 	/*
6643 	 * We could be called because listener is closing. Since
6644 	 * the eager is using listener's queue's, its not safe.
6645 	 * Better use the default queue just to send the TH_RST
6646 	 * out.
6647 	 */
6648 	eager->tcp_rq = tcp_g_q;
6649 	eager->tcp_wq = WR(tcp_g_q);
6650 
6651 	if (eager->tcp_state > TCPS_LISTEN) {
6652 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6653 		    eager, eager->tcp_snxt, 0, TH_RST);
6654 	}
6655 
6656 	/* We are here because listener wants this eager gone */
6657 	if (listener != NULL) {
6658 		mutex_enter(&listener->tcp_eager_lock);
6659 		tcp_eager_unlink(eager);
6660 		if (eager->tcp_conn.tcp_eager_conn_ind == NULL) {
6661 			/*
6662 			 * The eager has sent a conn_ind up to the
6663 			 * listener but listener decides to close
6664 			 * instead. We need to drop the extra ref
6665 			 * placed on eager in tcp_rput_data() before
6666 			 * sending the conn_ind to listener.
6667 			 */
6668 			CONN_DEC_REF(econnp);
6669 		}
6670 		mutex_exit(&listener->tcp_eager_lock);
6671 		CONN_DEC_REF(listener->tcp_connp);
6672 	}
6673 
6674 	if (eager->tcp_state > TCPS_BOUND)
6675 		tcp_close_detached(eager);
6676 }
6677 
6678 /*
6679  * Reset any eager connection hanging off this listener marked
6680  * with 'seqnum' and then reclaim it's resources.
6681  */
6682 static boolean_t
6683 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6684 {
6685 	tcp_t	*eager;
6686 	mblk_t 	*mp;
6687 
6688 	TCP_STAT(tcp_eager_blowoff_calls);
6689 	eager = listener;
6690 	mutex_enter(&listener->tcp_eager_lock);
6691 	do {
6692 		eager = eager->tcp_eager_next_q;
6693 		if (eager == NULL) {
6694 			mutex_exit(&listener->tcp_eager_lock);
6695 			return (B_FALSE);
6696 		}
6697 	} while (eager->tcp_conn_req_seqnum != seqnum);
6698 	CONN_INC_REF(eager->tcp_connp);
6699 	mutex_exit(&listener->tcp_eager_lock);
6700 	mp = &eager->tcp_closemp;
6701 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6702 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
6703 	return (B_TRUE);
6704 }
6705 
6706 /*
6707  * Reset any eager connection hanging off this listener
6708  * and then reclaim it's resources.
6709  */
6710 static void
6711 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6712 {
6713 	tcp_t	*eager;
6714 	mblk_t	*mp;
6715 
6716 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6717 
6718 	if (!q0_only) {
6719 		/* First cleanup q */
6720 		TCP_STAT(tcp_eager_blowoff_q);
6721 		eager = listener->tcp_eager_next_q;
6722 		while (eager != NULL) {
6723 			CONN_INC_REF(eager->tcp_connp);
6724 			mp = &eager->tcp_closemp;
6725 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
6726 			    tcp_eager_kill, eager->tcp_connp,
6727 			    SQTAG_TCP_EAGER_CLEANUP);
6728 			eager = eager->tcp_eager_next_q;
6729 		}
6730 	}
6731 	/* Then cleanup q0 */
6732 	TCP_STAT(tcp_eager_blowoff_q0);
6733 	eager = listener->tcp_eager_next_q0;
6734 	while (eager != listener) {
6735 		CONN_INC_REF(eager->tcp_connp);
6736 		mp = &eager->tcp_closemp;
6737 		squeue_fill(eager->tcp_connp->conn_sqp, mp,
6738 		    tcp_eager_kill, eager->tcp_connp,
6739 		    SQTAG_TCP_EAGER_CLEANUP_Q0);
6740 		eager = eager->tcp_eager_next_q0;
6741 	}
6742 }
6743 
6744 /*
6745  * If we are an eager connection hanging off a listener that hasn't
6746  * formally accepted the connection yet, get off his list and blow off
6747  * any data that we have accumulated.
6748  */
6749 static void
6750 tcp_eager_unlink(tcp_t *tcp)
6751 {
6752 	tcp_t	*listener = tcp->tcp_listener;
6753 
6754 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6755 	ASSERT(listener != NULL);
6756 	if (tcp->tcp_eager_next_q0 != NULL) {
6757 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6758 
6759 		/* Remove the eager tcp from q0 */
6760 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6761 		    tcp->tcp_eager_prev_q0;
6762 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6763 		    tcp->tcp_eager_next_q0;
6764 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6765 		listener->tcp_conn_req_cnt_q0--;
6766 
6767 		tcp->tcp_eager_next_q0 = NULL;
6768 		tcp->tcp_eager_prev_q0 = NULL;
6769 
6770 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6771 			/* we have timed out before */
6772 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6773 			listener->tcp_syn_rcvd_timeout--;
6774 		}
6775 	} else {
6776 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6777 		tcp_t	*prev = NULL;
6778 
6779 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6780 			if (tcpp[0] == tcp) {
6781 				if (listener->tcp_eager_last_q == tcp) {
6782 					/*
6783 					 * If we are unlinking the last
6784 					 * element on the list, adjust
6785 					 * tail pointer. Set tail pointer
6786 					 * to nil when list is empty.
6787 					 */
6788 					ASSERT(tcp->tcp_eager_next_q == NULL);
6789 					if (listener->tcp_eager_last_q ==
6790 					    listener->tcp_eager_next_q) {
6791 						listener->tcp_eager_last_q =
6792 						NULL;
6793 					} else {
6794 						/*
6795 						 * We won't get here if there
6796 						 * is only one eager in the
6797 						 * list.
6798 						 */
6799 						ASSERT(prev != NULL);
6800 						listener->tcp_eager_last_q =
6801 						    prev;
6802 					}
6803 				}
6804 				tcpp[0] = tcp->tcp_eager_next_q;
6805 				tcp->tcp_eager_next_q = NULL;
6806 				tcp->tcp_eager_last_q = NULL;
6807 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6808 				listener->tcp_conn_req_cnt_q--;
6809 				break;
6810 			}
6811 			prev = tcpp[0];
6812 		}
6813 	}
6814 	tcp->tcp_listener = NULL;
6815 }
6816 
6817 /* Shorthand to generate and send TPI error acks to our client */
6818 static void
6819 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6820 {
6821 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6822 		putnext(tcp->tcp_rq, mp);
6823 }
6824 
6825 /* Shorthand to generate and send TPI error acks to our client */
6826 static void
6827 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6828     int t_error, int sys_error)
6829 {
6830 	struct T_error_ack	*teackp;
6831 
6832 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6833 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6834 		teackp = (struct T_error_ack *)mp->b_rptr;
6835 		teackp->ERROR_prim = primitive;
6836 		teackp->TLI_error = t_error;
6837 		teackp->UNIX_error = sys_error;
6838 		putnext(tcp->tcp_rq, mp);
6839 	}
6840 }
6841 
6842 /*
6843  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6844  * but instead the code relies on:
6845  * - the fact that the address of the array and its size never changes
6846  * - the atomic assignment of the elements of the array
6847  */
6848 /* ARGSUSED */
6849 static int
6850 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6851 {
6852 	int i;
6853 
6854 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6855 		if (tcp_g_epriv_ports[i] != 0)
6856 			(void) mi_mpprintf(mp, "%d ", tcp_g_epriv_ports[i]);
6857 	}
6858 	return (0);
6859 }
6860 
6861 /*
6862  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6863  * threads from changing it at the same time.
6864  */
6865 /* ARGSUSED */
6866 static int
6867 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6868     cred_t *cr)
6869 {
6870 	long	new_value;
6871 	int	i;
6872 
6873 	/*
6874 	 * Fail the request if the new value does not lie within the
6875 	 * port number limits.
6876 	 */
6877 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6878 	    new_value <= 0 || new_value >= 65536) {
6879 		return (EINVAL);
6880 	}
6881 
6882 	mutex_enter(&tcp_epriv_port_lock);
6883 	/* Check if the value is already in the list */
6884 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6885 		if (new_value == tcp_g_epriv_ports[i]) {
6886 			mutex_exit(&tcp_epriv_port_lock);
6887 			return (EEXIST);
6888 		}
6889 	}
6890 	/* Find an empty slot */
6891 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6892 		if (tcp_g_epriv_ports[i] == 0)
6893 			break;
6894 	}
6895 	if (i == tcp_g_num_epriv_ports) {
6896 		mutex_exit(&tcp_epriv_port_lock);
6897 		return (EOVERFLOW);
6898 	}
6899 	/* Set the new value */
6900 	tcp_g_epriv_ports[i] = (uint16_t)new_value;
6901 	mutex_exit(&tcp_epriv_port_lock);
6902 	return (0);
6903 }
6904 
6905 /*
6906  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6907  * threads from changing it at the same time.
6908  */
6909 /* ARGSUSED */
6910 static int
6911 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6912     cred_t *cr)
6913 {
6914 	long	new_value;
6915 	int	i;
6916 
6917 	/*
6918 	 * Fail the request if the new value does not lie within the
6919 	 * port number limits.
6920 	 */
6921 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6922 	    new_value >= 65536) {
6923 		return (EINVAL);
6924 	}
6925 
6926 	mutex_enter(&tcp_epriv_port_lock);
6927 	/* Check that the value is already in the list */
6928 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
6929 		if (tcp_g_epriv_ports[i] == new_value)
6930 			break;
6931 	}
6932 	if (i == tcp_g_num_epriv_ports) {
6933 		mutex_exit(&tcp_epriv_port_lock);
6934 		return (ESRCH);
6935 	}
6936 	/* Clear the value */
6937 	tcp_g_epriv_ports[i] = 0;
6938 	mutex_exit(&tcp_epriv_port_lock);
6939 	return (0);
6940 }
6941 
6942 /* Return the TPI/TLI equivalent of our current tcp_state */
6943 static int
6944 tcp_tpistate(tcp_t *tcp)
6945 {
6946 	switch (tcp->tcp_state) {
6947 	case TCPS_IDLE:
6948 		return (TS_UNBND);
6949 	case TCPS_LISTEN:
6950 		/*
6951 		 * Return whether there are outstanding T_CONN_IND waiting
6952 		 * for the matching T_CONN_RES. Therefore don't count q0.
6953 		 */
6954 		if (tcp->tcp_conn_req_cnt_q > 0)
6955 			return (TS_WRES_CIND);
6956 		else
6957 			return (TS_IDLE);
6958 	case TCPS_BOUND:
6959 		return (TS_IDLE);
6960 	case TCPS_SYN_SENT:
6961 		return (TS_WCON_CREQ);
6962 	case TCPS_SYN_RCVD:
6963 		/*
6964 		 * Note: assumption: this has to the active open SYN_RCVD.
6965 		 * The passive instance is detached in SYN_RCVD stage of
6966 		 * incoming connection processing so we cannot get request
6967 		 * for T_info_ack on it.
6968 		 */
6969 		return (TS_WACK_CRES);
6970 	case TCPS_ESTABLISHED:
6971 		return (TS_DATA_XFER);
6972 	case TCPS_CLOSE_WAIT:
6973 		return (TS_WREQ_ORDREL);
6974 	case TCPS_FIN_WAIT_1:
6975 		return (TS_WIND_ORDREL);
6976 	case TCPS_FIN_WAIT_2:
6977 		return (TS_WIND_ORDREL);
6978 
6979 	case TCPS_CLOSING:
6980 	case TCPS_LAST_ACK:
6981 	case TCPS_TIME_WAIT:
6982 	case TCPS_CLOSED:
6983 		/*
6984 		 * Following TS_WACK_DREQ7 is a rendition of "not
6985 		 * yet TS_IDLE" TPI state. There is no best match to any
6986 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6987 		 * choose a value chosen that will map to TLI/XTI level
6988 		 * state of TSTATECHNG (state is process of changing) which
6989 		 * captures what this dummy state represents.
6990 		 */
6991 		return (TS_WACK_DREQ7);
6992 	default:
6993 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6994 		    tcp->tcp_state, tcp_display(tcp, NULL,
6995 		    DISP_PORT_ONLY));
6996 		return (TS_UNBND);
6997 	}
6998 }
6999 
7000 static void
7001 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7002 {
7003 	if (tcp->tcp_family == AF_INET6)
7004 		*tia = tcp_g_t_info_ack_v6;
7005 	else
7006 		*tia = tcp_g_t_info_ack;
7007 	tia->CURRENT_state = tcp_tpistate(tcp);
7008 	tia->OPT_size = tcp_max_optsize;
7009 	if (tcp->tcp_mss == 0) {
7010 		/* Not yet set - tcp_open does not set mss */
7011 		if (tcp->tcp_ipversion == IPV4_VERSION)
7012 			tia->TIDU_size = tcp_mss_def_ipv4;
7013 		else
7014 			tia->TIDU_size = tcp_mss_def_ipv6;
7015 	} else {
7016 		tia->TIDU_size = tcp->tcp_mss;
7017 	}
7018 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7019 }
7020 
7021 /*
7022  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7023  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7024  * tcp_g_t_info_ack.  The current state of the stream is copied from
7025  * tcp_state.
7026  */
7027 static void
7028 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7029 {
7030 	t_uscalar_t		cap_bits1;
7031 	struct T_capability_ack	*tcap;
7032 
7033 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7034 		freemsg(mp);
7035 		return;
7036 	}
7037 
7038 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7039 
7040 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7041 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7042 	if (mp == NULL)
7043 		return;
7044 
7045 	tcap = (struct T_capability_ack *)mp->b_rptr;
7046 	tcap->CAP_bits1 = 0;
7047 
7048 	if (cap_bits1 & TC1_INFO) {
7049 		tcp_copy_info(&tcap->INFO_ack, tcp);
7050 		tcap->CAP_bits1 |= TC1_INFO;
7051 	}
7052 
7053 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7054 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7055 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7056 	}
7057 
7058 	putnext(tcp->tcp_rq, mp);
7059 }
7060 
7061 /*
7062  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7063  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7064  * The current state of the stream is copied from tcp_state.
7065  */
7066 static void
7067 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7068 {
7069 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7070 	    T_INFO_ACK);
7071 	if (!mp) {
7072 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7073 		return;
7074 	}
7075 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7076 	putnext(tcp->tcp_rq, mp);
7077 }
7078 
7079 /* Respond to the TPI addr request */
7080 static void
7081 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7082 {
7083 	sin_t	*sin;
7084 	mblk_t	*ackmp;
7085 	struct T_addr_ack *taa;
7086 
7087 	/* Make it large enough for worst case */
7088 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7089 	    2 * sizeof (sin6_t), 1);
7090 	if (ackmp == NULL) {
7091 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7092 		return;
7093 	}
7094 
7095 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7096 		tcp_addr_req_ipv6(tcp, ackmp);
7097 		return;
7098 	}
7099 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7100 
7101 	bzero(taa, sizeof (struct T_addr_ack));
7102 	ackmp->b_wptr = (uchar_t *)&taa[1];
7103 
7104 	taa->PRIM_type = T_ADDR_ACK;
7105 	ackmp->b_datap->db_type = M_PCPROTO;
7106 
7107 	/*
7108 	 * Note: Following code assumes 32 bit alignment of basic
7109 	 * data structures like sin_t and struct T_addr_ack.
7110 	 */
7111 	if (tcp->tcp_state >= TCPS_BOUND) {
7112 		/*
7113 		 * Fill in local address
7114 		 */
7115 		taa->LOCADDR_length = sizeof (sin_t);
7116 		taa->LOCADDR_offset = sizeof (*taa);
7117 
7118 		sin = (sin_t *)&taa[1];
7119 
7120 		/* Fill zeroes and then intialize non-zero fields */
7121 		*sin = sin_null;
7122 
7123 		sin->sin_family = AF_INET;
7124 
7125 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7126 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7127 
7128 		ackmp->b_wptr = (uchar_t *)&sin[1];
7129 
7130 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7131 			/*
7132 			 * Fill in Remote address
7133 			 */
7134 			taa->REMADDR_length = sizeof (sin_t);
7135 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7136 						taa->LOCADDR_length);
7137 
7138 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7139 			*sin = sin_null;
7140 			sin->sin_family = AF_INET;
7141 			sin->sin_addr.s_addr = tcp->tcp_remote;
7142 			sin->sin_port = tcp->tcp_fport;
7143 
7144 			ackmp->b_wptr = (uchar_t *)&sin[1];
7145 		}
7146 	}
7147 	putnext(tcp->tcp_rq, ackmp);
7148 }
7149 
7150 /* Assumes that tcp_addr_req gets enough space and alignment */
7151 static void
7152 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7153 {
7154 	sin6_t	*sin6;
7155 	struct T_addr_ack *taa;
7156 
7157 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7158 	ASSERT(OK_32PTR(ackmp->b_rptr));
7159 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7160 	    2 * sizeof (sin6_t));
7161 
7162 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7163 
7164 	bzero(taa, sizeof (struct T_addr_ack));
7165 	ackmp->b_wptr = (uchar_t *)&taa[1];
7166 
7167 	taa->PRIM_type = T_ADDR_ACK;
7168 	ackmp->b_datap->db_type = M_PCPROTO;
7169 
7170 	/*
7171 	 * Note: Following code assumes 32 bit alignment of basic
7172 	 * data structures like sin6_t and struct T_addr_ack.
7173 	 */
7174 	if (tcp->tcp_state >= TCPS_BOUND) {
7175 		/*
7176 		 * Fill in local address
7177 		 */
7178 		taa->LOCADDR_length = sizeof (sin6_t);
7179 		taa->LOCADDR_offset = sizeof (*taa);
7180 
7181 		sin6 = (sin6_t *)&taa[1];
7182 		*sin6 = sin6_null;
7183 
7184 		sin6->sin6_family = AF_INET6;
7185 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7186 		sin6->sin6_port = tcp->tcp_lport;
7187 
7188 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7189 
7190 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7191 			/*
7192 			 * Fill in Remote address
7193 			 */
7194 			taa->REMADDR_length = sizeof (sin6_t);
7195 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7196 						taa->LOCADDR_length);
7197 
7198 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7199 			*sin6 = sin6_null;
7200 			sin6->sin6_family = AF_INET6;
7201 			sin6->sin6_flowinfo =
7202 			    tcp->tcp_ip6h->ip6_vcf &
7203 			    ~IPV6_VERS_AND_FLOW_MASK;
7204 			sin6->sin6_addr = tcp->tcp_remote_v6;
7205 			sin6->sin6_port = tcp->tcp_fport;
7206 
7207 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7208 		}
7209 	}
7210 	putnext(tcp->tcp_rq, ackmp);
7211 }
7212 
7213 /*
7214  * Handle reinitialization of a tcp structure.
7215  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7216  */
7217 static void
7218 tcp_reinit(tcp_t *tcp)
7219 {
7220 	mblk_t	*mp;
7221 	int 	err;
7222 
7223 	TCP_STAT(tcp_reinit_calls);
7224 
7225 	/* tcp_reinit should never be called for detached tcp_t's */
7226 	ASSERT(tcp->tcp_listener == NULL);
7227 	ASSERT((tcp->tcp_family == AF_INET &&
7228 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7229 	    (tcp->tcp_family == AF_INET6 &&
7230 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7231 	    tcp->tcp_ipversion == IPV6_VERSION)));
7232 
7233 	/* Cancel outstanding timers */
7234 	tcp_timers_stop(tcp);
7235 
7236 	/*
7237 	 * Reset everything in the state vector, after updating global
7238 	 * MIB data from instance counters.
7239 	 */
7240 	UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
7241 	tcp->tcp_ibsegs = 0;
7242 	UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
7243 	tcp->tcp_obsegs = 0;
7244 
7245 	tcp_close_mpp(&tcp->tcp_xmit_head);
7246 	if (tcp->tcp_snd_zcopy_aware)
7247 		tcp_zcopy_notify(tcp);
7248 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7249 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7250 	if (tcp->tcp_flow_stopped &&
7251 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7252 		tcp_clrqfull(tcp);
7253 	}
7254 	tcp_close_mpp(&tcp->tcp_reass_head);
7255 	tcp->tcp_reass_tail = NULL;
7256 	if (tcp->tcp_rcv_list != NULL) {
7257 		/* Free b_next chain */
7258 		tcp_close_mpp(&tcp->tcp_rcv_list);
7259 		tcp->tcp_rcv_last_head = NULL;
7260 		tcp->tcp_rcv_last_tail = NULL;
7261 		tcp->tcp_rcv_cnt = 0;
7262 	}
7263 	tcp->tcp_rcv_last_tail = NULL;
7264 
7265 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7266 		freemsg(mp);
7267 		tcp->tcp_urp_mp = NULL;
7268 	}
7269 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7270 		freemsg(mp);
7271 		tcp->tcp_urp_mark_mp = NULL;
7272 	}
7273 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7274 		freeb(tcp->tcp_fused_sigurg_mp);
7275 		tcp->tcp_fused_sigurg_mp = NULL;
7276 	}
7277 
7278 	/*
7279 	 * Following is a union with two members which are
7280 	 * identical types and size so the following cleanup
7281 	 * is enough.
7282 	 */
7283 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7284 
7285 	CL_INET_DISCONNECT(tcp);
7286 
7287 	/*
7288 	 * The connection can't be on the tcp_time_wait_head list
7289 	 * since it is not detached.
7290 	 */
7291 	ASSERT(tcp->tcp_time_wait_next == NULL);
7292 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7293 	ASSERT(tcp->tcp_time_wait_expire == 0);
7294 
7295 	if (tcp->tcp_kssl_pending) {
7296 		tcp->tcp_kssl_pending = B_FALSE;
7297 
7298 		/* Don't reset if the initialized by bind. */
7299 		if (tcp->tcp_kssl_ent != NULL) {
7300 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7301 			    KSSL_NO_PROXY);
7302 		}
7303 	}
7304 	if (tcp->tcp_kssl_ctx != NULL) {
7305 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7306 		tcp->tcp_kssl_ctx = NULL;
7307 	}
7308 
7309 	/*
7310 	 * Reset/preserve other values
7311 	 */
7312 	tcp_reinit_values(tcp);
7313 	ipcl_hash_remove(tcp->tcp_connp);
7314 	conn_delete_ire(tcp->tcp_connp, NULL);
7315 
7316 	if (tcp->tcp_conn_req_max != 0) {
7317 		/*
7318 		 * This is the case when a TLI program uses the same
7319 		 * transport end point to accept a connection.  This
7320 		 * makes the TCP both a listener and acceptor.  When
7321 		 * this connection is closed, we need to set the state
7322 		 * back to TCPS_LISTEN.  Make sure that the eager list
7323 		 * is reinitialized.
7324 		 *
7325 		 * Note that this stream is still bound to the four
7326 		 * tuples of the previous connection in IP.  If a new
7327 		 * SYN with different foreign address comes in, IP will
7328 		 * not find it and will send it to the global queue.  In
7329 		 * the global queue, TCP will do a tcp_lookup_listener()
7330 		 * to find this stream.  This works because this stream
7331 		 * is only removed from connected hash.
7332 		 *
7333 		 */
7334 		tcp->tcp_state = TCPS_LISTEN;
7335 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7336 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7337 		if (tcp->tcp_family == AF_INET6) {
7338 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7339 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7340 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7341 		} else {
7342 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7343 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7344 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7345 		}
7346 	} else {
7347 		tcp->tcp_state = TCPS_BOUND;
7348 	}
7349 
7350 	/*
7351 	 * Initialize to default values
7352 	 * Can't fail since enough header template space already allocated
7353 	 * at open().
7354 	 */
7355 	err = tcp_init_values(tcp);
7356 	ASSERT(err == 0);
7357 	/* Restore state in tcp_tcph */
7358 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7359 	if (tcp->tcp_ipversion == IPV4_VERSION)
7360 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7361 	else
7362 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7363 	/*
7364 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7365 	 * since the lookup funcs can only lookup on tcp_t
7366 	 */
7367 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7368 
7369 	ASSERT(tcp->tcp_ptpbhn != NULL);
7370 	tcp->tcp_rq->q_hiwat = tcp_recv_hiwat;
7371 	tcp->tcp_rwnd = tcp_recv_hiwat;
7372 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7373 	    tcp_mss_def_ipv6 : tcp_mss_def_ipv4;
7374 }
7375 
7376 /*
7377  * Force values to zero that need be zero.
7378  * Do not touch values asociated with the BOUND or LISTEN state
7379  * since the connection will end up in that state after the reinit.
7380  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7381  * structure!
7382  */
7383 static void
7384 tcp_reinit_values(tcp)
7385 	tcp_t *tcp;
7386 {
7387 #ifndef	lint
7388 #define	DONTCARE(x)
7389 #define	PRESERVE(x)
7390 #else
7391 #define	DONTCARE(x)	((x) = (x))
7392 #define	PRESERVE(x)	((x) = (x))
7393 #endif	/* lint */
7394 
7395 	PRESERVE(tcp->tcp_bind_hash);
7396 	PRESERVE(tcp->tcp_ptpbhn);
7397 	PRESERVE(tcp->tcp_acceptor_hash);
7398 	PRESERVE(tcp->tcp_ptpahn);
7399 
7400 	/* Should be ASSERT NULL on these with new code! */
7401 	ASSERT(tcp->tcp_time_wait_next == NULL);
7402 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7403 	ASSERT(tcp->tcp_time_wait_expire == 0);
7404 	PRESERVE(tcp->tcp_state);
7405 	PRESERVE(tcp->tcp_rq);
7406 	PRESERVE(tcp->tcp_wq);
7407 
7408 	ASSERT(tcp->tcp_xmit_head == NULL);
7409 	ASSERT(tcp->tcp_xmit_last == NULL);
7410 	ASSERT(tcp->tcp_unsent == 0);
7411 	ASSERT(tcp->tcp_xmit_tail == NULL);
7412 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7413 
7414 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7415 	tcp->tcp_suna = 0;			/* Displayed in mib */
7416 	tcp->tcp_swnd = 0;
7417 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7418 
7419 	ASSERT(tcp->tcp_ibsegs == 0);
7420 	ASSERT(tcp->tcp_obsegs == 0);
7421 
7422 	if (tcp->tcp_iphc != NULL) {
7423 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7424 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7425 	}
7426 
7427 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7428 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7429 	DONTCARE(tcp->tcp_ipha);
7430 	DONTCARE(tcp->tcp_ip6h);
7431 	DONTCARE(tcp->tcp_ip_hdr_len);
7432 	DONTCARE(tcp->tcp_tcph);
7433 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7434 	tcp->tcp_valid_bits = 0;
7435 
7436 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7437 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7438 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7439 	tcp->tcp_last_rcv_lbolt = 0;
7440 
7441 	tcp->tcp_init_cwnd = 0;
7442 
7443 	tcp->tcp_urp_last_valid = 0;
7444 	tcp->tcp_hard_binding = 0;
7445 	tcp->tcp_hard_bound = 0;
7446 	PRESERVE(tcp->tcp_cred);
7447 	PRESERVE(tcp->tcp_cpid);
7448 	PRESERVE(tcp->tcp_exclbind);
7449 
7450 	tcp->tcp_fin_acked = 0;
7451 	tcp->tcp_fin_rcvd = 0;
7452 	tcp->tcp_fin_sent = 0;
7453 	tcp->tcp_ordrel_done = 0;
7454 
7455 	tcp->tcp_debug = 0;
7456 	tcp->tcp_dontroute = 0;
7457 	tcp->tcp_broadcast = 0;
7458 
7459 	tcp->tcp_useloopback = 0;
7460 	tcp->tcp_reuseaddr = 0;
7461 	tcp->tcp_oobinline = 0;
7462 	tcp->tcp_dgram_errind = 0;
7463 
7464 	tcp->tcp_detached = 0;
7465 	tcp->tcp_bind_pending = 0;
7466 	tcp->tcp_unbind_pending = 0;
7467 	tcp->tcp_deferred_clean_death = 0;
7468 
7469 	tcp->tcp_snd_ws_ok = B_FALSE;
7470 	tcp->tcp_snd_ts_ok = B_FALSE;
7471 	tcp->tcp_linger = 0;
7472 	tcp->tcp_ka_enabled = 0;
7473 	tcp->tcp_zero_win_probe = 0;
7474 
7475 	tcp->tcp_loopback = 0;
7476 	tcp->tcp_localnet = 0;
7477 	tcp->tcp_syn_defense = 0;
7478 	tcp->tcp_set_timer = 0;
7479 
7480 	tcp->tcp_active_open = 0;
7481 	ASSERT(tcp->tcp_timeout == B_FALSE);
7482 	tcp->tcp_rexmit = B_FALSE;
7483 	tcp->tcp_xmit_zc_clean = B_FALSE;
7484 
7485 	tcp->tcp_snd_sack_ok = B_FALSE;
7486 	PRESERVE(tcp->tcp_recvdstaddr);
7487 	tcp->tcp_hwcksum = B_FALSE;
7488 
7489 	tcp->tcp_ire_ill_check_done = B_FALSE;
7490 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7491 
7492 	tcp->tcp_mdt = B_FALSE;
7493 	tcp->tcp_mdt_hdr_head = 0;
7494 	tcp->tcp_mdt_hdr_tail = 0;
7495 
7496 	tcp->tcp_conn_def_q0 = 0;
7497 	tcp->tcp_ip_forward_progress = B_FALSE;
7498 	tcp->tcp_anon_priv_bind = 0;
7499 	tcp->tcp_ecn_ok = B_FALSE;
7500 
7501 	tcp->tcp_cwr = B_FALSE;
7502 	tcp->tcp_ecn_echo_on = B_FALSE;
7503 
7504 	if (tcp->tcp_sack_info != NULL) {
7505 		if (tcp->tcp_notsack_list != NULL) {
7506 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7507 		}
7508 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7509 		tcp->tcp_sack_info = NULL;
7510 	}
7511 
7512 	tcp->tcp_rcv_ws = 0;
7513 	tcp->tcp_snd_ws = 0;
7514 	tcp->tcp_ts_recent = 0;
7515 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7516 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7517 	tcp->tcp_if_mtu = 0;
7518 
7519 	ASSERT(tcp->tcp_reass_head == NULL);
7520 	ASSERT(tcp->tcp_reass_tail == NULL);
7521 
7522 	tcp->tcp_cwnd_cnt = 0;
7523 
7524 	ASSERT(tcp->tcp_rcv_list == NULL);
7525 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7526 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7527 	ASSERT(tcp->tcp_rcv_cnt == 0);
7528 
7529 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7530 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7531 	tcp->tcp_csuna = 0;
7532 
7533 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7534 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7535 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7536 	tcp->tcp_rtt_update = 0;
7537 
7538 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7539 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7540 
7541 	tcp->tcp_rack = 0;			/* Displayed in mib */
7542 	tcp->tcp_rack_cnt = 0;
7543 	tcp->tcp_rack_cur_max = 0;
7544 	tcp->tcp_rack_abs_max = 0;
7545 
7546 	tcp->tcp_max_swnd = 0;
7547 
7548 	ASSERT(tcp->tcp_listener == NULL);
7549 
7550 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7551 
7552 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7553 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7554 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7555 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7556 
7557 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7558 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7559 	PRESERVE(tcp->tcp_conn_req_max);
7560 	PRESERVE(tcp->tcp_conn_req_seqnum);
7561 
7562 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7563 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7564 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7565 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7566 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7567 
7568 	tcp->tcp_lingertime = 0;
7569 
7570 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7571 	ASSERT(tcp->tcp_urp_mp == NULL);
7572 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7573 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7574 
7575 	ASSERT(tcp->tcp_eager_next_q == NULL);
7576 	ASSERT(tcp->tcp_eager_last_q == NULL);
7577 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7578 	    tcp->tcp_eager_prev_q0 == NULL) ||
7579 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7580 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7581 
7582 	tcp->tcp_client_errno = 0;
7583 
7584 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7585 
7586 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7587 
7588 	PRESERVE(tcp->tcp_bound_source_v6);
7589 	tcp->tcp_last_sent_len = 0;
7590 	tcp->tcp_dupack_cnt = 0;
7591 
7592 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7593 	PRESERVE(tcp->tcp_lport);
7594 
7595 	PRESERVE(tcp->tcp_acceptor_lockp);
7596 
7597 	ASSERT(tcp->tcp_ordrelid == 0);
7598 	PRESERVE(tcp->tcp_acceptor_id);
7599 	DONTCARE(tcp->tcp_ipsec_overhead);
7600 
7601 	/*
7602 	 * If tcp_tracing flag is ON (i.e. We have a trace buffer
7603 	 * in tcp structure and now tracing), Re-initialize all
7604 	 * members of tcp_traceinfo.
7605 	 */
7606 	if (tcp->tcp_tracebuf != NULL) {
7607 		bzero(tcp->tcp_tracebuf, sizeof (tcptrch_t));
7608 	}
7609 
7610 	PRESERVE(tcp->tcp_family);
7611 	if (tcp->tcp_family == AF_INET6) {
7612 		tcp->tcp_ipversion = IPV6_VERSION;
7613 		tcp->tcp_mss = tcp_mss_def_ipv6;
7614 	} else {
7615 		tcp->tcp_ipversion = IPV4_VERSION;
7616 		tcp->tcp_mss = tcp_mss_def_ipv4;
7617 	}
7618 
7619 	tcp->tcp_bound_if = 0;
7620 	tcp->tcp_ipv6_recvancillary = 0;
7621 	tcp->tcp_recvifindex = 0;
7622 	tcp->tcp_recvhops = 0;
7623 	tcp->tcp_closed = 0;
7624 	tcp->tcp_cleandeathtag = 0;
7625 	if (tcp->tcp_hopopts != NULL) {
7626 		mi_free(tcp->tcp_hopopts);
7627 		tcp->tcp_hopopts = NULL;
7628 		tcp->tcp_hopoptslen = 0;
7629 	}
7630 	ASSERT(tcp->tcp_hopoptslen == 0);
7631 	if (tcp->tcp_dstopts != NULL) {
7632 		mi_free(tcp->tcp_dstopts);
7633 		tcp->tcp_dstopts = NULL;
7634 		tcp->tcp_dstoptslen = 0;
7635 	}
7636 	ASSERT(tcp->tcp_dstoptslen == 0);
7637 	if (tcp->tcp_rtdstopts != NULL) {
7638 		mi_free(tcp->tcp_rtdstopts);
7639 		tcp->tcp_rtdstopts = NULL;
7640 		tcp->tcp_rtdstoptslen = 0;
7641 	}
7642 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7643 	if (tcp->tcp_rthdr != NULL) {
7644 		mi_free(tcp->tcp_rthdr);
7645 		tcp->tcp_rthdr = NULL;
7646 		tcp->tcp_rthdrlen = 0;
7647 	}
7648 	ASSERT(tcp->tcp_rthdrlen == 0);
7649 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7650 
7651 	/* Reset fusion-related fields */
7652 	tcp->tcp_fused = B_FALSE;
7653 	tcp->tcp_unfusable = B_FALSE;
7654 	tcp->tcp_fused_sigurg = B_FALSE;
7655 	tcp->tcp_direct_sockfs = B_FALSE;
7656 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7657 	tcp->tcp_loopback_peer = NULL;
7658 	tcp->tcp_fuse_rcv_hiwater = 0;
7659 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7660 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7661 
7662 	tcp->tcp_in_ack_unsent = 0;
7663 	tcp->tcp_cork = B_FALSE;
7664 
7665 	PRESERVE(tcp->tcp_squeue_bytes);
7666 
7667 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7668 	ASSERT(!tcp->tcp_kssl_pending);
7669 	PRESERVE(tcp->tcp_kssl_ent);
7670 
7671 #undef	DONTCARE
7672 #undef	PRESERVE
7673 }
7674 
7675 /*
7676  * Allocate necessary resources and initialize state vector.
7677  * Guaranteed not to fail so that when an error is returned,
7678  * the caller doesn't need to do any additional cleanup.
7679  */
7680 int
7681 tcp_init(tcp_t *tcp, queue_t *q)
7682 {
7683 	int	err;
7684 
7685 	tcp->tcp_rq = q;
7686 	tcp->tcp_wq = WR(q);
7687 	tcp->tcp_state = TCPS_IDLE;
7688 	if ((err = tcp_init_values(tcp)) != 0)
7689 		tcp_timers_stop(tcp);
7690 	return (err);
7691 }
7692 
7693 static int
7694 tcp_init_values(tcp_t *tcp)
7695 {
7696 	int	err;
7697 
7698 	ASSERT((tcp->tcp_family == AF_INET &&
7699 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7700 	    (tcp->tcp_family == AF_INET6 &&
7701 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7702 	    tcp->tcp_ipversion == IPV6_VERSION)));
7703 
7704 	/*
7705 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7706 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7707 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7708 	 * during first few transmissions of a connection as seen in slow
7709 	 * links.
7710 	 */
7711 	tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2;
7712 	tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1;
7713 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7714 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7715 	    tcp_conn_grace_period;
7716 	if (tcp->tcp_rto < tcp_rexmit_interval_min)
7717 		tcp->tcp_rto = tcp_rexmit_interval_min;
7718 	tcp->tcp_timer_backoff = 0;
7719 	tcp->tcp_ms_we_have_waited = 0;
7720 	tcp->tcp_last_recv_time = lbolt;
7721 	tcp->tcp_cwnd_max = tcp_cwnd_max_;
7722 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7723 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7724 
7725 	tcp->tcp_maxpsz = tcp_maxpsz_multiplier;
7726 
7727 	tcp->tcp_first_timer_threshold = tcp_ip_notify_interval;
7728 	tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval;
7729 	tcp->tcp_second_timer_threshold = tcp_ip_abort_interval;
7730 	/*
7731 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7732 	 * passive open.
7733 	 */
7734 	tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval;
7735 
7736 	tcp->tcp_naglim = tcp_naglim_def;
7737 
7738 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7739 
7740 	tcp->tcp_mdt_hdr_head = 0;
7741 	tcp->tcp_mdt_hdr_tail = 0;
7742 
7743 	/* Reset fusion-related fields */
7744 	tcp->tcp_fused = B_FALSE;
7745 	tcp->tcp_unfusable = B_FALSE;
7746 	tcp->tcp_fused_sigurg = B_FALSE;
7747 	tcp->tcp_direct_sockfs = B_FALSE;
7748 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7749 	tcp->tcp_loopback_peer = NULL;
7750 	tcp->tcp_fuse_rcv_hiwater = 0;
7751 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7752 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7753 
7754 	/* Initialize the header template */
7755 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7756 		err = tcp_header_init_ipv4(tcp);
7757 	} else {
7758 		err = tcp_header_init_ipv6(tcp);
7759 	}
7760 	if (err)
7761 		return (err);
7762 
7763 	/*
7764 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7765 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7766 	 */
7767 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7768 	tcp->tcp_xmit_lowater = tcp_xmit_lowat;
7769 	tcp->tcp_xmit_hiwater = tcp_xmit_hiwat;
7770 
7771 	tcp->tcp_cork = B_FALSE;
7772 	/*
7773 	 * Init the tcp_debug option.  This value determines whether TCP
7774 	 * calls strlog() to print out debug messages.  Doing this
7775 	 * initialization here means that this value is not inherited thru
7776 	 * tcp_reinit().
7777 	 */
7778 	tcp->tcp_debug = tcp_dbg;
7779 
7780 	tcp->tcp_ka_interval = tcp_keepalive_interval;
7781 	tcp->tcp_ka_abort_thres = tcp_keepalive_abort_interval;
7782 
7783 	return (0);
7784 }
7785 
7786 /*
7787  * Initialize the IPv4 header. Loses any record of any IP options.
7788  */
7789 static int
7790 tcp_header_init_ipv4(tcp_t *tcp)
7791 {
7792 	tcph_t		*tcph;
7793 	uint32_t	sum;
7794 
7795 	/*
7796 	 * This is a simple initialization. If there's
7797 	 * already a template, it should never be too small,
7798 	 * so reuse it.  Otherwise, allocate space for the new one.
7799 	 */
7800 	if (tcp->tcp_iphc == NULL) {
7801 		ASSERT(tcp->tcp_iphc_len == 0);
7802 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7803 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7804 		if (tcp->tcp_iphc == NULL) {
7805 			tcp->tcp_iphc_len = 0;
7806 			return (ENOMEM);
7807 		}
7808 	}
7809 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7810 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
7811 	tcp->tcp_ip6h = NULL;
7812 	tcp->tcp_ipversion = IPV4_VERSION;
7813 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
7814 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7815 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
7816 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
7817 	tcp->tcp_ipha->ipha_version_and_hdr_length
7818 		= (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
7819 	tcp->tcp_ipha->ipha_ident = 0;
7820 
7821 	tcp->tcp_ttl = (uchar_t)tcp_ipv4_ttl;
7822 	tcp->tcp_tos = 0;
7823 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7824 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
7825 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
7826 
7827 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
7828 	tcp->tcp_tcph = tcph;
7829 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7830 	/*
7831 	 * IP wants our header length in the checksum field to
7832 	 * allow it to perform a single pseudo-header+checksum
7833 	 * calculation on behalf of TCP.
7834 	 * Include the adjustment for a source route once IP_OPTIONS is set.
7835 	 */
7836 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7837 	sum = (sum >> 16) + (sum & 0xFFFF);
7838 	U16_TO_ABE16(sum, tcph->th_sum);
7839 	return (0);
7840 }
7841 
7842 /*
7843  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
7844  */
7845 static int
7846 tcp_header_init_ipv6(tcp_t *tcp)
7847 {
7848 	tcph_t	*tcph;
7849 	uint32_t	sum;
7850 
7851 	/*
7852 	 * This is a simple initialization. If there's
7853 	 * already a template, it should never be too small,
7854 	 * so reuse it. Otherwise, allocate space for the new one.
7855 	 * Ensure that there is enough space to "downgrade" the tcp_t
7856 	 * to an IPv4 tcp_t. This requires having space for a full load
7857 	 * of IPv4 options, as well as a full load of TCP options
7858 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
7859 	 * than a v6 header and a TCP header with a full load of TCP options
7860 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
7861 	 * We want to avoid reallocation in the "downgraded" case when
7862 	 * processing outbound IPv4 options.
7863 	 */
7864 	if (tcp->tcp_iphc == NULL) {
7865 		ASSERT(tcp->tcp_iphc_len == 0);
7866 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
7867 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
7868 		if (tcp->tcp_iphc == NULL) {
7869 			tcp->tcp_iphc_len = 0;
7870 			return (ENOMEM);
7871 		}
7872 	}
7873 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7874 	tcp->tcp_ipversion = IPV6_VERSION;
7875 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
7876 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
7877 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
7878 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
7879 	tcp->tcp_ipha = NULL;
7880 
7881 	/* Initialize the header template */
7882 
7883 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7884 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
7885 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
7886 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcp_ipv6_hoplimit;
7887 
7888 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
7889 	tcp->tcp_tcph = tcph;
7890 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
7891 	/*
7892 	 * IP wants our header length in the checksum field to
7893 	 * allow it to perform a single psuedo-header+checksum
7894 	 * calculation on behalf of TCP.
7895 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
7896 	 */
7897 	sum = sizeof (tcph_t) + tcp->tcp_sum;
7898 	sum = (sum >> 16) + (sum & 0xFFFF);
7899 	U16_TO_ABE16(sum, tcph->th_sum);
7900 	return (0);
7901 }
7902 
7903 /* At minimum we need 4 bytes in the TCP header for the lookup */
7904 #define	ICMP_MIN_TCP_HDR	12
7905 
7906 /*
7907  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
7908  * passed up by IP. The message is always received on the correct tcp_t.
7909  * Assumes that IP has pulled up everything up to and including the ICMP header.
7910  */
7911 void
7912 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
7913 {
7914 	icmph_t *icmph;
7915 	ipha_t	*ipha;
7916 	int	iph_hdr_length;
7917 	tcph_t	*tcph;
7918 	boolean_t ipsec_mctl = B_FALSE;
7919 	boolean_t secure;
7920 	mblk_t *first_mp = mp;
7921 	uint32_t new_mss;
7922 	uint32_t ratio;
7923 	size_t mp_size = MBLKL(mp);
7924 	uint32_t seg_ack;
7925 	uint32_t seg_seq;
7926 
7927 	/* Assume IP provides aligned packets - otherwise toss */
7928 	if (!OK_32PTR(mp->b_rptr)) {
7929 		freemsg(mp);
7930 		return;
7931 	}
7932 
7933 	/*
7934 	 * Since ICMP errors are normal data marked with M_CTL when sent
7935 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
7936 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
7937 	 */
7938 	if ((mp_size == sizeof (ipsec_info_t)) &&
7939 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
7940 		ASSERT(mp->b_cont != NULL);
7941 		mp = mp->b_cont;
7942 		/* IP should have done this */
7943 		ASSERT(OK_32PTR(mp->b_rptr));
7944 		mp_size = MBLKL(mp);
7945 		ipsec_mctl = B_TRUE;
7946 	}
7947 
7948 	/*
7949 	 * Verify that we have a complete outer IP header. If not, drop it.
7950 	 */
7951 	if (mp_size < sizeof (ipha_t)) {
7952 noticmpv4:
7953 		freemsg(first_mp);
7954 		return;
7955 	}
7956 
7957 	ipha = (ipha_t *)mp->b_rptr;
7958 	/*
7959 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
7960 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
7961 	 */
7962 	switch (IPH_HDR_VERSION(ipha)) {
7963 	case IPV6_VERSION:
7964 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
7965 		return;
7966 	case IPV4_VERSION:
7967 		break;
7968 	default:
7969 		goto noticmpv4;
7970 	}
7971 
7972 	/* Skip past the outer IP and ICMP headers */
7973 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7974 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7975 	/*
7976 	 * If we don't have the correct outer IP header length or if the ULP
7977 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
7978 	 * send it upstream.
7979 	 */
7980 	if (iph_hdr_length < sizeof (ipha_t) ||
7981 	    ipha->ipha_protocol != IPPROTO_ICMP ||
7982 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7983 		goto noticmpv4;
7984 	}
7985 	ipha = (ipha_t *)&icmph[1];
7986 
7987 	/* Skip past the inner IP and find the ULP header */
7988 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7989 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
7990 	/*
7991 	 * If we don't have the correct inner IP header length or if the ULP
7992 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7993 	 * bytes of TCP header, drop it.
7994 	 */
7995 	if (iph_hdr_length < sizeof (ipha_t) ||
7996 	    ipha->ipha_protocol != IPPROTO_TCP ||
7997 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7998 		goto noticmpv4;
7999 	}
8000 
8001 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8002 		if (ipsec_mctl) {
8003 			secure = ipsec_in_is_secure(first_mp);
8004 		} else {
8005 			secure = B_FALSE;
8006 		}
8007 		if (secure) {
8008 			/*
8009 			 * If we are willing to accept this in clear
8010 			 * we don't have to verify policy.
8011 			 */
8012 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8013 				if (!tcp_check_policy(tcp, first_mp,
8014 				    ipha, NULL, secure, ipsec_mctl)) {
8015 					/*
8016 					 * tcp_check_policy called
8017 					 * ip_drop_packet() on failure.
8018 					 */
8019 					return;
8020 				}
8021 			}
8022 		}
8023 	} else if (ipsec_mctl) {
8024 		/*
8025 		 * This is a hard_bound connection. IP has already
8026 		 * verified policy. We don't have to do it again.
8027 		 */
8028 		freeb(first_mp);
8029 		first_mp = mp;
8030 		ipsec_mctl = B_FALSE;
8031 	}
8032 
8033 	seg_ack = ABE32_TO_U32(tcph->th_ack);
8034 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8035 	/*
8036 	 * TCP SHOULD check that the TCP sequence number contained in
8037 	 * payload of the ICMP error message is within the range
8038 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8039 	 */
8040 	if (SEQ_LT(seg_seq, tcp->tcp_suna) ||
8041 		SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8042 		SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8043 		/*
8044 		 * If the ICMP message is bogus, should we kill the
8045 		 * connection, or should we just drop the bogus ICMP
8046 		 * message? It would probably make more sense to just
8047 		 * drop the message so that if this one managed to get
8048 		 * in, the real connection should not suffer.
8049 		 */
8050 		goto noticmpv4;
8051 	}
8052 
8053 	switch (icmph->icmph_type) {
8054 	case ICMP_DEST_UNREACHABLE:
8055 		switch (icmph->icmph_code) {
8056 		case ICMP_FRAGMENTATION_NEEDED:
8057 			/*
8058 			 * Reduce the MSS based on the new MTU.  This will
8059 			 * eliminate any fragmentation locally.
8060 			 * N.B.  There may well be some funny side-effects on
8061 			 * the local send policy and the remote receive policy.
8062 			 * Pending further research, we provide
8063 			 * tcp_ignore_path_mtu just in case this proves
8064 			 * disastrous somewhere.
8065 			 *
8066 			 * After updating the MSS, retransmit part of the
8067 			 * dropped segment using the new mss by calling
8068 			 * tcp_wput_data().  Need to adjust all those
8069 			 * params to make sure tcp_wput_data() work properly.
8070 			 */
8071 			if (tcp_ignore_path_mtu)
8072 				break;
8073 
8074 			/*
8075 			 * Decrease the MSS by time stamp options
8076 			 * IP options and IPSEC options. tcp_hdr_len
8077 			 * includes time stamp option and IP option
8078 			 * length.
8079 			 */
8080 
8081 			new_mss = ntohs(icmph->icmph_du_mtu) -
8082 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8083 
8084 			/*
8085 			 * Only update the MSS if the new one is
8086 			 * smaller than the previous one.  This is
8087 			 * to avoid problems when getting multiple
8088 			 * ICMP errors for the same MTU.
8089 			 */
8090 			if (new_mss >= tcp->tcp_mss)
8091 				break;
8092 
8093 			/*
8094 			 * Stop doing PMTU if new_mss is less than 68
8095 			 * or less than tcp_mss_min.
8096 			 * The value 68 comes from rfc 1191.
8097 			 */
8098 			if (new_mss < MAX(68, tcp_mss_min))
8099 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8100 				    0;
8101 
8102 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8103 			ASSERT(ratio >= 1);
8104 			tcp_mss_set(tcp, new_mss);
8105 
8106 			/*
8107 			 * Make sure we have something to
8108 			 * send.
8109 			 */
8110 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8111 			    (tcp->tcp_xmit_head != NULL)) {
8112 				/*
8113 				 * Shrink tcp_cwnd in
8114 				 * proportion to the old MSS/new MSS.
8115 				 */
8116 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8117 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8118 				    (tcp->tcp_unsent == 0)) {
8119 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8120 				} else {
8121 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8122 				}
8123 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8124 				tcp->tcp_rexmit = B_TRUE;
8125 				tcp->tcp_dupack_cnt = 0;
8126 				tcp->tcp_snd_burst = TCP_CWND_SS;
8127 				tcp_ss_rexmit(tcp);
8128 			}
8129 			break;
8130 		case ICMP_PORT_UNREACHABLE:
8131 		case ICMP_PROTOCOL_UNREACHABLE:
8132 			switch (tcp->tcp_state) {
8133 			case TCPS_SYN_SENT:
8134 			case TCPS_SYN_RCVD:
8135 				/*
8136 				 * ICMP can snipe away incipient
8137 				 * TCP connections as long as
8138 				 * seq number is same as initial
8139 				 * send seq number.
8140 				 */
8141 				if (seg_seq == tcp->tcp_iss) {
8142 					(void) tcp_clean_death(tcp,
8143 					    ECONNREFUSED, 6);
8144 				}
8145 				break;
8146 			}
8147 			break;
8148 		case ICMP_HOST_UNREACHABLE:
8149 		case ICMP_NET_UNREACHABLE:
8150 			/* Record the error in case we finally time out. */
8151 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8152 				tcp->tcp_client_errno = EHOSTUNREACH;
8153 			else
8154 				tcp->tcp_client_errno = ENETUNREACH;
8155 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8156 				if (tcp->tcp_listener != NULL &&
8157 				    tcp->tcp_listener->tcp_syn_defense) {
8158 					/*
8159 					 * Ditch the half-open connection if we
8160 					 * suspect a SYN attack is under way.
8161 					 */
8162 					tcp_ip_ire_mark_advice(tcp);
8163 					(void) tcp_clean_death(tcp,
8164 					    tcp->tcp_client_errno, 7);
8165 				}
8166 			}
8167 			break;
8168 		default:
8169 			break;
8170 		}
8171 		break;
8172 	case ICMP_SOURCE_QUENCH: {
8173 		/*
8174 		 * use a global boolean to control
8175 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8176 		 * The default is false.
8177 		 */
8178 		if (tcp_icmp_source_quench) {
8179 			/*
8180 			 * Reduce the sending rate as if we got a
8181 			 * retransmit timeout
8182 			 */
8183 			uint32_t npkt;
8184 
8185 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8186 			    tcp->tcp_mss;
8187 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8188 			tcp->tcp_cwnd = tcp->tcp_mss;
8189 			tcp->tcp_cwnd_cnt = 0;
8190 		}
8191 		break;
8192 	}
8193 	}
8194 	freemsg(first_mp);
8195 }
8196 
8197 /*
8198  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8199  * error messages passed up by IP.
8200  * Assumes that IP has pulled up all the extension headers as well
8201  * as the ICMPv6 header.
8202  */
8203 static void
8204 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8205 {
8206 	icmp6_t *icmp6;
8207 	ip6_t	*ip6h;
8208 	uint16_t	iph_hdr_length;
8209 	tcpha_t	*tcpha;
8210 	uint8_t	*nexthdrp;
8211 	uint32_t new_mss;
8212 	uint32_t ratio;
8213 	boolean_t secure;
8214 	mblk_t *first_mp = mp;
8215 	size_t mp_size;
8216 	uint32_t seg_ack;
8217 	uint32_t seg_seq;
8218 
8219 	/*
8220 	 * The caller has determined if this is an IPSEC_IN packet and
8221 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8222 	 */
8223 	if (ipsec_mctl)
8224 		mp = mp->b_cont;
8225 
8226 	mp_size = MBLKL(mp);
8227 
8228 	/*
8229 	 * Verify that we have a complete IP header. If not, send it upstream.
8230 	 */
8231 	if (mp_size < sizeof (ip6_t)) {
8232 noticmpv6:
8233 		freemsg(first_mp);
8234 		return;
8235 	}
8236 
8237 	/*
8238 	 * Verify this is an ICMPV6 packet, else send it upstream.
8239 	 */
8240 	ip6h = (ip6_t *)mp->b_rptr;
8241 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8242 		iph_hdr_length = IPV6_HDR_LEN;
8243 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8244 	    &nexthdrp) ||
8245 	    *nexthdrp != IPPROTO_ICMPV6) {
8246 		goto noticmpv6;
8247 	}
8248 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8249 	ip6h = (ip6_t *)&icmp6[1];
8250 	/*
8251 	 * Verify if we have a complete ICMP and inner IP header.
8252 	 */
8253 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8254 		goto noticmpv6;
8255 
8256 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8257 		goto noticmpv6;
8258 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8259 	/*
8260 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8261 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8262 	 * packet.
8263 	 */
8264 	if ((*nexthdrp != IPPROTO_TCP) ||
8265 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8266 		goto noticmpv6;
8267 	}
8268 
8269 	/*
8270 	 * ICMP errors come on the right queue or come on
8271 	 * listener/global queue for detached connections and
8272 	 * get switched to the right queue. If it comes on the
8273 	 * right queue, policy check has already been done by IP
8274 	 * and thus free the first_mp without verifying the policy.
8275 	 * If it has come for a non-hard bound connection, we need
8276 	 * to verify policy as IP may not have done it.
8277 	 */
8278 	if (!tcp->tcp_hard_bound) {
8279 		if (ipsec_mctl) {
8280 			secure = ipsec_in_is_secure(first_mp);
8281 		} else {
8282 			secure = B_FALSE;
8283 		}
8284 		if (secure) {
8285 			/*
8286 			 * If we are willing to accept this in clear
8287 			 * we don't have to verify policy.
8288 			 */
8289 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8290 				if (!tcp_check_policy(tcp, first_mp,
8291 				    NULL, ip6h, secure, ipsec_mctl)) {
8292 					/*
8293 					 * tcp_check_policy called
8294 					 * ip_drop_packet() on failure.
8295 					 */
8296 					return;
8297 				}
8298 			}
8299 		}
8300 	} else if (ipsec_mctl) {
8301 		/*
8302 		 * This is a hard_bound connection. IP has already
8303 		 * verified policy. We don't have to do it again.
8304 		 */
8305 		freeb(first_mp);
8306 		first_mp = mp;
8307 		ipsec_mctl = B_FALSE;
8308 	}
8309 
8310 	seg_ack = ntohl(tcpha->tha_ack);
8311 	seg_seq = ntohl(tcpha->tha_seq);
8312 	/*
8313 	 * TCP SHOULD check that the TCP sequence number contained in
8314 	 * payload of the ICMP error message is within the range
8315 	 * SND.UNA <= SEG.SEQ < SND.NXT. and also SEG.ACK <= RECV.NXT
8316 	 */
8317 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt) ||
8318 	    SEQ_GT(seg_ack, tcp->tcp_rnxt)) {
8319 		/*
8320 		 * If the ICMP message is bogus, should we kill the
8321 		 * connection, or should we just drop the bogus ICMP
8322 		 * message? It would probably make more sense to just
8323 		 * drop the message so that if this one managed to get
8324 		 * in, the real connection should not suffer.
8325 		 */
8326 		goto noticmpv6;
8327 	}
8328 
8329 	switch (icmp6->icmp6_type) {
8330 	case ICMP6_PACKET_TOO_BIG:
8331 		/*
8332 		 * Reduce the MSS based on the new MTU.  This will
8333 		 * eliminate any fragmentation locally.
8334 		 * N.B.  There may well be some funny side-effects on
8335 		 * the local send policy and the remote receive policy.
8336 		 * Pending further research, we provide
8337 		 * tcp_ignore_path_mtu just in case this proves
8338 		 * disastrous somewhere.
8339 		 *
8340 		 * After updating the MSS, retransmit part of the
8341 		 * dropped segment using the new mss by calling
8342 		 * tcp_wput_data().  Need to adjust all those
8343 		 * params to make sure tcp_wput_data() work properly.
8344 		 */
8345 		if (tcp_ignore_path_mtu)
8346 			break;
8347 
8348 		/*
8349 		 * Decrease the MSS by time stamp options
8350 		 * IP options and IPSEC options. tcp_hdr_len
8351 		 * includes time stamp option and IP option
8352 		 * length.
8353 		 */
8354 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8355 			    tcp->tcp_ipsec_overhead;
8356 
8357 		/*
8358 		 * Only update the MSS if the new one is
8359 		 * smaller than the previous one.  This is
8360 		 * to avoid problems when getting multiple
8361 		 * ICMP errors for the same MTU.
8362 		 */
8363 		if (new_mss >= tcp->tcp_mss)
8364 			break;
8365 
8366 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8367 		ASSERT(ratio >= 1);
8368 		tcp_mss_set(tcp, new_mss);
8369 
8370 		/*
8371 		 * Make sure we have something to
8372 		 * send.
8373 		 */
8374 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8375 		    (tcp->tcp_xmit_head != NULL)) {
8376 			/*
8377 			 * Shrink tcp_cwnd in
8378 			 * proportion to the old MSS/new MSS.
8379 			 */
8380 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8381 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8382 			    (tcp->tcp_unsent == 0)) {
8383 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8384 			} else {
8385 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8386 			}
8387 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8388 			tcp->tcp_rexmit = B_TRUE;
8389 			tcp->tcp_dupack_cnt = 0;
8390 			tcp->tcp_snd_burst = TCP_CWND_SS;
8391 			tcp_ss_rexmit(tcp);
8392 		}
8393 		break;
8394 
8395 	case ICMP6_DST_UNREACH:
8396 		switch (icmp6->icmp6_code) {
8397 		case ICMP6_DST_UNREACH_NOPORT:
8398 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8399 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8400 			    (seg_seq == tcp->tcp_iss)) {
8401 				(void) tcp_clean_death(tcp,
8402 				    ECONNREFUSED, 8);
8403 			}
8404 			break;
8405 
8406 		case ICMP6_DST_UNREACH_ADMIN:
8407 		case ICMP6_DST_UNREACH_NOROUTE:
8408 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8409 		case ICMP6_DST_UNREACH_ADDR:
8410 			/* Record the error in case we finally time out. */
8411 			tcp->tcp_client_errno = EHOSTUNREACH;
8412 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8413 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8414 			    (seg_seq == tcp->tcp_iss)) {
8415 				if (tcp->tcp_listener != NULL &&
8416 				    tcp->tcp_listener->tcp_syn_defense) {
8417 					/*
8418 					 * Ditch the half-open connection if we
8419 					 * suspect a SYN attack is under way.
8420 					 */
8421 					tcp_ip_ire_mark_advice(tcp);
8422 					(void) tcp_clean_death(tcp,
8423 					    tcp->tcp_client_errno, 9);
8424 				}
8425 			}
8426 
8427 
8428 			break;
8429 		default:
8430 			break;
8431 		}
8432 		break;
8433 
8434 	case ICMP6_PARAM_PROB:
8435 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8436 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8437 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8438 		    (uchar_t *)nexthdrp) {
8439 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8440 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8441 				(void) tcp_clean_death(tcp,
8442 				    ECONNREFUSED, 10);
8443 			}
8444 			break;
8445 		}
8446 		break;
8447 
8448 	case ICMP6_TIME_EXCEEDED:
8449 	default:
8450 		break;
8451 	}
8452 	freemsg(first_mp);
8453 }
8454 
8455 /*
8456  * IP recognizes seven kinds of bind requests:
8457  *
8458  * - A zero-length address binds only to the protocol number.
8459  *
8460  * - A 4-byte address is treated as a request to
8461  * validate that the address is a valid local IPv4
8462  * address, appropriate for an application to bind to.
8463  * IP does the verification, but does not make any note
8464  * of the address at this time.
8465  *
8466  * - A 16-byte address contains is treated as a request
8467  * to validate a local IPv6 address, as the 4-byte
8468  * address case above.
8469  *
8470  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
8471  * use it for the inbound fanout of packets.
8472  *
8473  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
8474  * use it for the inbound fanout of packets.
8475  *
8476  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
8477  * information consisting of local and remote addresses
8478  * and ports.  In this case, the addresses are both
8479  * validated as appropriate for this operation, and, if
8480  * so, the information is retained for use in the
8481  * inbound fanout.
8482  *
8483  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
8484  * fanout information, like the 12-byte case above.
8485  *
8486  * IP will also fill in the IRE request mblk with information
8487  * regarding our peer.  In all cases, we notify IP of our protocol
8488  * type by appending a single protocol byte to the bind request.
8489  */
8490 static mblk_t *
8491 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
8492 {
8493 	char	*cp;
8494 	mblk_t	*mp;
8495 	struct T_bind_req *tbr;
8496 	ipa_conn_t	*ac;
8497 	ipa6_conn_t	*ac6;
8498 	sin_t		*sin;
8499 	sin6_t		*sin6;
8500 
8501 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
8502 	ASSERT((tcp->tcp_family == AF_INET &&
8503 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8504 	    (tcp->tcp_family == AF_INET6 &&
8505 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8506 	    tcp->tcp_ipversion == IPV6_VERSION)));
8507 
8508 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
8509 	if (!mp)
8510 		return (mp);
8511 	mp->b_datap->db_type = M_PROTO;
8512 	tbr = (struct T_bind_req *)mp->b_rptr;
8513 	tbr->PRIM_type = bind_prim;
8514 	tbr->ADDR_offset = sizeof (*tbr);
8515 	tbr->CONIND_number = 0;
8516 	tbr->ADDR_length = addr_length;
8517 	cp = (char *)&tbr[1];
8518 	switch (addr_length) {
8519 	case sizeof (ipa_conn_t):
8520 		ASSERT(tcp->tcp_family == AF_INET);
8521 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8522 
8523 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8524 		if (mp->b_cont == NULL) {
8525 			freemsg(mp);
8526 			return (NULL);
8527 		}
8528 		mp->b_cont->b_wptr += sizeof (ire_t);
8529 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8530 
8531 		/* cp known to be 32 bit aligned */
8532 		ac = (ipa_conn_t *)cp;
8533 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
8534 		ac->ac_faddr = tcp->tcp_remote;
8535 		ac->ac_fport = tcp->tcp_fport;
8536 		ac->ac_lport = tcp->tcp_lport;
8537 		tcp->tcp_hard_binding = 1;
8538 		break;
8539 
8540 	case sizeof (ipa6_conn_t):
8541 		ASSERT(tcp->tcp_family == AF_INET6);
8542 
8543 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
8544 		if (mp->b_cont == NULL) {
8545 			freemsg(mp);
8546 			return (NULL);
8547 		}
8548 		mp->b_cont->b_wptr += sizeof (ire_t);
8549 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
8550 
8551 		/* cp known to be 32 bit aligned */
8552 		ac6 = (ipa6_conn_t *)cp;
8553 		if (tcp->tcp_ipversion == IPV4_VERSION) {
8554 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
8555 			    &ac6->ac6_laddr);
8556 		} else {
8557 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
8558 		}
8559 		ac6->ac6_faddr = tcp->tcp_remote_v6;
8560 		ac6->ac6_fport = tcp->tcp_fport;
8561 		ac6->ac6_lport = tcp->tcp_lport;
8562 		tcp->tcp_hard_binding = 1;
8563 		break;
8564 
8565 	case sizeof (sin_t):
8566 		/*
8567 		 * NOTE: IPV6_ADDR_LEN also has same size.
8568 		 * Use family to discriminate.
8569 		 */
8570 		if (tcp->tcp_family == AF_INET) {
8571 			sin = (sin_t *)cp;
8572 
8573 			*sin = sin_null;
8574 			sin->sin_family = AF_INET;
8575 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
8576 			sin->sin_port = tcp->tcp_lport;
8577 			break;
8578 		} else {
8579 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
8580 		}
8581 		break;
8582 
8583 	case sizeof (sin6_t):
8584 		ASSERT(tcp->tcp_family == AF_INET6);
8585 		sin6 = (sin6_t *)cp;
8586 
8587 		*sin6 = sin6_null;
8588 		sin6->sin6_family = AF_INET6;
8589 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
8590 		sin6->sin6_port = tcp->tcp_lport;
8591 		break;
8592 
8593 	case IP_ADDR_LEN:
8594 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
8595 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
8596 		break;
8597 
8598 	}
8599 	/* Add protocol number to end */
8600 	cp[addr_length] = (char)IPPROTO_TCP;
8601 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
8602 	return (mp);
8603 }
8604 
8605 /*
8606  * Notify IP that we are having trouble with this connection.  IP should
8607  * blow the IRE away and start over.
8608  */
8609 static void
8610 tcp_ip_notify(tcp_t *tcp)
8611 {
8612 	struct iocblk	*iocp;
8613 	ipid_t	*ipid;
8614 	mblk_t	*mp;
8615 
8616 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8617 	if (tcp->tcp_ipversion == IPV6_VERSION)
8618 		return;
8619 
8620 	mp = mkiocb(IP_IOCTL);
8621 	if (mp == NULL)
8622 		return;
8623 
8624 	iocp = (struct iocblk *)mp->b_rptr;
8625 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8626 
8627 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8628 	if (!mp->b_cont) {
8629 		freeb(mp);
8630 		return;
8631 	}
8632 
8633 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8634 	mp->b_cont->b_wptr += iocp->ioc_count;
8635 	bzero(ipid, sizeof (*ipid));
8636 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8637 	ipid->ipid_ire_type = IRE_CACHE;
8638 	ipid->ipid_addr_offset = sizeof (ipid_t);
8639 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8640 	/*
8641 	 * Note: in the case of source routing we want to blow away the
8642 	 * route to the first source route hop.
8643 	 */
8644 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8645 	    sizeof (tcp->tcp_ipha->ipha_dst));
8646 
8647 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8648 }
8649 
8650 /* Unlink and return any mblk that looks like it contains an ire */
8651 static mblk_t *
8652 tcp_ire_mp(mblk_t *mp)
8653 {
8654 	mblk_t	*prev_mp;
8655 
8656 	for (;;) {
8657 		prev_mp = mp;
8658 		mp = mp->b_cont;
8659 		if (mp == NULL)
8660 			break;
8661 		switch (DB_TYPE(mp)) {
8662 		case IRE_DB_TYPE:
8663 		case IRE_DB_REQ_TYPE:
8664 			if (prev_mp != NULL)
8665 				prev_mp->b_cont = mp->b_cont;
8666 			mp->b_cont = NULL;
8667 			return (mp);
8668 		default:
8669 			break;
8670 		}
8671 	}
8672 	return (mp);
8673 }
8674 
8675 /*
8676  * Timer callback routine for keepalive probe.  We do a fake resend of
8677  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8678  * check to see if we have heard anything from the other end for the last
8679  * RTO period.  If we have, set the timer to expire for another
8680  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8681  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8682  * the timeout if we have not heard from the other side.  If for more than
8683  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8684  * kill the connection unless the keepalive abort threshold is 0.  In
8685  * that case, we will probe "forever."
8686  */
8687 static void
8688 tcp_keepalive_killer(void *arg)
8689 {
8690 	mblk_t	*mp;
8691 	conn_t	*connp = (conn_t *)arg;
8692 	tcp_t  	*tcp = connp->conn_tcp;
8693 	int32_t	firetime;
8694 	int32_t	idletime;
8695 	int32_t	ka_intrvl;
8696 
8697 	tcp->tcp_ka_tid = 0;
8698 
8699 	if (tcp->tcp_fused)
8700 		return;
8701 
8702 	BUMP_MIB(&tcp_mib, tcpTimKeepalive);
8703 	ka_intrvl = tcp->tcp_ka_interval;
8704 
8705 	/*
8706 	 * Keepalive probe should only be sent if the application has not
8707 	 * done a close on the connection.
8708 	 */
8709 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8710 		return;
8711 	}
8712 	/* Timer fired too early, restart it. */
8713 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8714 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8715 		    MSEC_TO_TICK(ka_intrvl));
8716 		return;
8717 	}
8718 
8719 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8720 	/*
8721 	 * If we have not heard from the other side for a long
8722 	 * time, kill the connection unless the keepalive abort
8723 	 * threshold is 0.  In that case, we will probe "forever."
8724 	 */
8725 	if (tcp->tcp_ka_abort_thres != 0 &&
8726 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8727 		BUMP_MIB(&tcp_mib, tcpTimKeepaliveDrop);
8728 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8729 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8730 		return;
8731 	}
8732 
8733 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8734 	    idletime >= ka_intrvl) {
8735 		/* Fake resend of last ACKed byte. */
8736 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8737 
8738 		if (mp1 != NULL) {
8739 			*mp1->b_wptr++ = '\0';
8740 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8741 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8742 			freeb(mp1);
8743 			/*
8744 			 * if allocation failed, fall through to start the
8745 			 * timer back.
8746 			 */
8747 			if (mp != NULL) {
8748 				TCP_RECORD_TRACE(tcp, mp,
8749 				    TCP_TRACE_SEND_PKT);
8750 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8751 				BUMP_MIB(&tcp_mib, tcpTimKeepaliveProbe);
8752 				if (tcp->tcp_ka_last_intrvl != 0) {
8753 					/*
8754 					 * We should probe again at least
8755 					 * in ka_intrvl, but not more than
8756 					 * tcp_rexmit_interval_max.
8757 					 */
8758 					firetime = MIN(ka_intrvl - 1,
8759 					    tcp->tcp_ka_last_intrvl << 1);
8760 					if (firetime > tcp_rexmit_interval_max)
8761 						firetime =
8762 						    tcp_rexmit_interval_max;
8763 				} else {
8764 					firetime = tcp->tcp_rto;
8765 				}
8766 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8767 				    tcp_keepalive_killer,
8768 				    MSEC_TO_TICK(firetime));
8769 				tcp->tcp_ka_last_intrvl = firetime;
8770 				return;
8771 			}
8772 		}
8773 	} else {
8774 		tcp->tcp_ka_last_intrvl = 0;
8775 	}
8776 
8777 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8778 	if ((firetime = ka_intrvl - idletime) < 0) {
8779 		firetime = ka_intrvl;
8780 	}
8781 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8782 	    MSEC_TO_TICK(firetime));
8783 }
8784 
8785 int
8786 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8787 {
8788 	queue_t	*q = tcp->tcp_rq;
8789 	int32_t	mss = tcp->tcp_mss;
8790 	int	maxpsz;
8791 
8792 	if (TCP_IS_DETACHED(tcp))
8793 		return (mss);
8794 
8795 	if (tcp->tcp_fused) {
8796 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8797 		mss = INFPSZ;
8798 	} else if (tcp->tcp_mdt || tcp->tcp_maxpsz == 0) {
8799 		/*
8800 		 * Set the sd_qn_maxpsz according to the socket send buffer
8801 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8802 		 * instruct the stream head to copyin user data into contiguous
8803 		 * kernel-allocated buffers without breaking it up into smaller
8804 		 * chunks.  We round up the buffer size to the nearest SMSS.
8805 		 */
8806 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8807 		if (tcp->tcp_kssl_ctx == NULL)
8808 			mss = INFPSZ;
8809 		else
8810 			mss = SSL3_MAX_RECORD_LEN;
8811 	} else {
8812 		/*
8813 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8814 		 * (and a multiple of the mss).  This instructs the stream
8815 		 * head to break down larger than SMSS writes into SMSS-
8816 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8817 		 */
8818 		maxpsz = tcp->tcp_maxpsz * mss;
8819 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8820 			maxpsz = tcp->tcp_xmit_hiwater/2;
8821 			/* Round up to nearest mss */
8822 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8823 		}
8824 	}
8825 	(void) setmaxps(q, maxpsz);
8826 	tcp->tcp_wq->q_maxpsz = maxpsz;
8827 
8828 	if (set_maxblk)
8829 		(void) mi_set_sth_maxblk(q, mss);
8830 
8831 	return (mss);
8832 }
8833 
8834 /*
8835  * Extract option values from a tcp header.  We put any found values into the
8836  * tcpopt struct and return a bitmask saying which options were found.
8837  */
8838 static int
8839 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8840 {
8841 	uchar_t		*endp;
8842 	int		len;
8843 	uint32_t	mss;
8844 	uchar_t		*up = (uchar_t *)tcph;
8845 	int		found = 0;
8846 	int32_t		sack_len;
8847 	tcp_seq		sack_begin, sack_end;
8848 	tcp_t		*tcp;
8849 
8850 	endp = up + TCP_HDR_LENGTH(tcph);
8851 	up += TCP_MIN_HEADER_LENGTH;
8852 	while (up < endp) {
8853 		len = endp - up;
8854 		switch (*up) {
8855 		case TCPOPT_EOL:
8856 			break;
8857 
8858 		case TCPOPT_NOP:
8859 			up++;
8860 			continue;
8861 
8862 		case TCPOPT_MAXSEG:
8863 			if (len < TCPOPT_MAXSEG_LEN ||
8864 			    up[1] != TCPOPT_MAXSEG_LEN)
8865 				break;
8866 
8867 			mss = BE16_TO_U16(up+2);
8868 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8869 			tcpopt->tcp_opt_mss = mss;
8870 			found |= TCP_OPT_MSS_PRESENT;
8871 
8872 			up += TCPOPT_MAXSEG_LEN;
8873 			continue;
8874 
8875 		case TCPOPT_WSCALE:
8876 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8877 				break;
8878 
8879 			if (up[2] > TCP_MAX_WINSHIFT)
8880 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8881 			else
8882 				tcpopt->tcp_opt_wscale = up[2];
8883 			found |= TCP_OPT_WSCALE_PRESENT;
8884 
8885 			up += TCPOPT_WS_LEN;
8886 			continue;
8887 
8888 		case TCPOPT_SACK_PERMITTED:
8889 			if (len < TCPOPT_SACK_OK_LEN ||
8890 			    up[1] != TCPOPT_SACK_OK_LEN)
8891 				break;
8892 			found |= TCP_OPT_SACK_OK_PRESENT;
8893 			up += TCPOPT_SACK_OK_LEN;
8894 			continue;
8895 
8896 		case TCPOPT_SACK:
8897 			if (len <= 2 || up[1] <= 2 || len < up[1])
8898 				break;
8899 
8900 			/* If TCP is not interested in SACK blks... */
8901 			if ((tcp = tcpopt->tcp) == NULL) {
8902 				up += up[1];
8903 				continue;
8904 			}
8905 			sack_len = up[1] - TCPOPT_HEADER_LEN;
8906 			up += TCPOPT_HEADER_LEN;
8907 
8908 			/*
8909 			 * If the list is empty, allocate one and assume
8910 			 * nothing is sack'ed.
8911 			 */
8912 			ASSERT(tcp->tcp_sack_info != NULL);
8913 			if (tcp->tcp_notsack_list == NULL) {
8914 				tcp_notsack_update(&(tcp->tcp_notsack_list),
8915 				    tcp->tcp_suna, tcp->tcp_snxt,
8916 				    &(tcp->tcp_num_notsack_blk),
8917 				    &(tcp->tcp_cnt_notsack_list));
8918 
8919 				/*
8920 				 * Make sure tcp_notsack_list is not NULL.
8921 				 * This happens when kmem_alloc(KM_NOSLEEP)
8922 				 * returns NULL.
8923 				 */
8924 				if (tcp->tcp_notsack_list == NULL) {
8925 					up += sack_len;
8926 					continue;
8927 				}
8928 				tcp->tcp_fack = tcp->tcp_suna;
8929 			}
8930 
8931 			while (sack_len > 0) {
8932 				if (up + 8 > endp) {
8933 					up = endp;
8934 					break;
8935 				}
8936 				sack_begin = BE32_TO_U32(up);
8937 				up += 4;
8938 				sack_end = BE32_TO_U32(up);
8939 				up += 4;
8940 				sack_len -= 8;
8941 				/*
8942 				 * Bounds checking.  Make sure the SACK
8943 				 * info is within tcp_suna and tcp_snxt.
8944 				 * If this SACK blk is out of bound, ignore
8945 				 * it but continue to parse the following
8946 				 * blks.
8947 				 */
8948 				if (SEQ_LEQ(sack_end, sack_begin) ||
8949 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
8950 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
8951 					continue;
8952 				}
8953 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
8954 				    sack_begin, sack_end,
8955 				    &(tcp->tcp_num_notsack_blk),
8956 				    &(tcp->tcp_cnt_notsack_list));
8957 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
8958 					tcp->tcp_fack = sack_end;
8959 				}
8960 			}
8961 			found |= TCP_OPT_SACK_PRESENT;
8962 			continue;
8963 
8964 		case TCPOPT_TSTAMP:
8965 			if (len < TCPOPT_TSTAMP_LEN ||
8966 			    up[1] != TCPOPT_TSTAMP_LEN)
8967 				break;
8968 
8969 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
8970 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
8971 
8972 			found |= TCP_OPT_TSTAMP_PRESENT;
8973 
8974 			up += TCPOPT_TSTAMP_LEN;
8975 			continue;
8976 
8977 		default:
8978 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
8979 				break;
8980 			up += up[1];
8981 			continue;
8982 		}
8983 		break;
8984 	}
8985 	return (found);
8986 }
8987 
8988 /*
8989  * Set the mss associated with a particular tcp based on its current value,
8990  * and a new one passed in. Observe minimums and maximums, and reset
8991  * other state variables that we want to view as multiples of mss.
8992  *
8993  * This function is called in various places mainly because
8994  * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the
8995  *    other side's SYN/SYN-ACK packet arrives.
8996  * 2) PMTUd may get us a new MSS.
8997  * 3) If the other side stops sending us timestamp option, we need to
8998  *    increase the MSS size to use the extra bytes available.
8999  */
9000 static void
9001 tcp_mss_set(tcp_t *tcp, uint32_t mss)
9002 {
9003 	uint32_t	mss_max;
9004 
9005 	if (tcp->tcp_ipversion == IPV4_VERSION)
9006 		mss_max = tcp_mss_max_ipv4;
9007 	else
9008 		mss_max = tcp_mss_max_ipv6;
9009 
9010 	if (mss < tcp_mss_min)
9011 		mss = tcp_mss_min;
9012 	if (mss > mss_max)
9013 		mss = mss_max;
9014 	/*
9015 	 * Unless naglim has been set by our client to
9016 	 * a non-mss value, force naglim to track mss.
9017 	 * This can help to aggregate small writes.
9018 	 */
9019 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9020 		tcp->tcp_naglim = mss;
9021 	/*
9022 	 * TCP should be able to buffer at least 4 MSS data for obvious
9023 	 * performance reason.
9024 	 */
9025 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9026 		tcp->tcp_xmit_hiwater = mss << 2;
9027 
9028 	/*
9029 	 * Check if we need to apply the tcp_init_cwnd here.  If
9030 	 * it is set and the MSS gets bigger (should not happen
9031 	 * normally), we need to adjust the resulting tcp_cwnd properly.
9032 	 * The new tcp_cwnd should not get bigger.
9033 	 */
9034 	if (tcp->tcp_init_cwnd == 0) {
9035 		tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss,
9036 		    MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss)));
9037 	} else {
9038 		if (tcp->tcp_mss < mss) {
9039 			tcp->tcp_cwnd = MAX(1,
9040 			    (tcp->tcp_init_cwnd * tcp->tcp_mss / mss)) * mss;
9041 		} else {
9042 			tcp->tcp_cwnd = tcp->tcp_init_cwnd * mss;
9043 		}
9044 	}
9045 	tcp->tcp_mss = mss;
9046 	tcp->tcp_cwnd_cnt = 0;
9047 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9048 }
9049 
9050 static int
9051 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9052 {
9053 	tcp_t		*tcp = NULL;
9054 	conn_t		*connp;
9055 	int		err;
9056 	dev_t		conn_dev;
9057 	zoneid_t	zoneid = getzoneid();
9058 
9059 	/*
9060 	 * Special case for install: miniroot needs to be able to access files
9061 	 * via NFS as though it were always in the global zone.
9062 	 */
9063 	if (credp == kcred && nfs_global_client_only != 0)
9064 		zoneid = GLOBAL_ZONEID;
9065 
9066 	if (q->q_ptr != NULL)
9067 		return (0);
9068 
9069 	if (sflag == MODOPEN) {
9070 		/*
9071 		 * This is a special case. The purpose of a modopen
9072 		 * is to allow just the T_SVR4_OPTMGMT_REQ to pass
9073 		 * through for MIB browsers. Everything else is failed.
9074 		 */
9075 		connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9076 
9077 		if (connp == NULL)
9078 			return (ENOMEM);
9079 
9080 		connp->conn_flags |= IPCL_TCPMOD;
9081 		connp->conn_cred = credp;
9082 		connp->conn_zoneid = zoneid;
9083 		q->q_ptr = WR(q)->q_ptr = connp;
9084 		crhold(credp);
9085 		q->q_qinfo = &tcp_mod_rinit;
9086 		WR(q)->q_qinfo = &tcp_mod_winit;
9087 		qprocson(q);
9088 		return (0);
9089 	}
9090 
9091 	if ((conn_dev = inet_minor_alloc(ip_minor_arena)) == 0)
9092 		return (EBUSY);
9093 
9094 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9095 
9096 	if (flag & SO_ACCEPTOR) {
9097 		q->q_qinfo = &tcp_acceptor_rinit;
9098 		q->q_ptr = (void *)conn_dev;
9099 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9100 		WR(q)->q_ptr = (void *)conn_dev;
9101 		qprocson(q);
9102 		return (0);
9103 	}
9104 
9105 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt));
9106 	if (connp == NULL) {
9107 		inet_minor_free(ip_minor_arena, conn_dev);
9108 		q->q_ptr = NULL;
9109 		return (ENOSR);
9110 	}
9111 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9112 	tcp = connp->conn_tcp;
9113 
9114 	q->q_ptr = WR(q)->q_ptr = connp;
9115 	if (getmajor(*devp) == TCP6_MAJ) {
9116 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9117 		connp->conn_send = ip_output_v6;
9118 		connp->conn_af_isv6 = B_TRUE;
9119 		connp->conn_pkt_isv6 = B_TRUE;
9120 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9121 		tcp->tcp_ipversion = IPV6_VERSION;
9122 		tcp->tcp_family = AF_INET6;
9123 		tcp->tcp_mss = tcp_mss_def_ipv6;
9124 	} else {
9125 		connp->conn_flags |= IPCL_TCP4;
9126 		connp->conn_send = ip_output;
9127 		connp->conn_af_isv6 = B_FALSE;
9128 		connp->conn_pkt_isv6 = B_FALSE;
9129 		tcp->tcp_ipversion = IPV4_VERSION;
9130 		tcp->tcp_family = AF_INET;
9131 		tcp->tcp_mss = tcp_mss_def_ipv4;
9132 	}
9133 
9134 	/*
9135 	 * TCP keeps a copy of cred for cache locality reasons but
9136 	 * we put a reference only once. If connp->conn_cred
9137 	 * becomes invalid, tcp_cred should also be set to NULL.
9138 	 */
9139 	tcp->tcp_cred = connp->conn_cred = credp;
9140 	crhold(connp->conn_cred);
9141 	tcp->tcp_cpid = curproc->p_pid;
9142 	connp->conn_zoneid = zoneid;
9143 
9144 	connp->conn_dev = conn_dev;
9145 
9146 	ASSERT(q->q_qinfo == &tcp_rinit);
9147 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9148 
9149 	if (flag & SO_SOCKSTR) {
9150 		/*
9151 		 * No need to insert a socket in tcp acceptor hash.
9152 		 * If it was a socket acceptor stream, we dealt with
9153 		 * it above. A socket listener can never accept a
9154 		 * connection and doesn't need acceptor_id.
9155 		 */
9156 		connp->conn_flags |= IPCL_SOCKET;
9157 		tcp->tcp_issocket = 1;
9158 		WR(q)->q_qinfo = &tcp_sock_winit;
9159 	} else {
9160 #ifdef	_ILP32
9161 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9162 #else
9163 		tcp->tcp_acceptor_id = conn_dev;
9164 #endif	/* _ILP32 */
9165 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9166 	}
9167 
9168 	if (tcp_trace)
9169 		tcp->tcp_tracebuf = kmem_zalloc(sizeof (tcptrch_t), KM_SLEEP);
9170 
9171 	err = tcp_init(tcp, q);
9172 	if (err != 0) {
9173 		inet_minor_free(ip_minor_arena, connp->conn_dev);
9174 		tcp_acceptor_hash_remove(tcp);
9175 		CONN_DEC_REF(connp);
9176 		q->q_ptr = WR(q)->q_ptr = NULL;
9177 		return (err);
9178 	}
9179 
9180 	RD(q)->q_hiwat = tcp_recv_hiwat;
9181 	tcp->tcp_rwnd = tcp_recv_hiwat;
9182 
9183 	/* Non-zero default values */
9184 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9185 	/*
9186 	 * Put the ref for TCP. Ref for IP was already put
9187 	 * by ipcl_conn_create. Also Make the conn_t globally
9188 	 * visible to walkers
9189 	 */
9190 	mutex_enter(&connp->conn_lock);
9191 	CONN_INC_REF_LOCKED(connp);
9192 	ASSERT(connp->conn_ref == 2);
9193 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9194 	mutex_exit(&connp->conn_lock);
9195 
9196 	qprocson(q);
9197 	return (0);
9198 }
9199 
9200 /*
9201  * Some TCP options can be "set" by requesting them in the option
9202  * buffer. This is needed for XTI feature test though we do not
9203  * allow it in general. We interpret that this mechanism is more
9204  * applicable to OSI protocols and need not be allowed in general.
9205  * This routine filters out options for which it is not allowed (most)
9206  * and lets through those (few) for which it is. [ The XTI interface
9207  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9208  * ever implemented will have to be allowed here ].
9209  */
9210 static boolean_t
9211 tcp_allow_connopt_set(int level, int name)
9212 {
9213 
9214 	switch (level) {
9215 	case IPPROTO_TCP:
9216 		switch (name) {
9217 		case TCP_NODELAY:
9218 			return (B_TRUE);
9219 		default:
9220 			return (B_FALSE);
9221 		}
9222 		/*NOTREACHED*/
9223 	default:
9224 		return (B_FALSE);
9225 	}
9226 	/*NOTREACHED*/
9227 }
9228 
9229 /*
9230  * This routine gets default values of certain options whose default
9231  * values are maintained by protocol specific code
9232  */
9233 /* ARGSUSED */
9234 int
9235 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9236 {
9237 	int32_t	*i1 = (int32_t *)ptr;
9238 
9239 	switch (level) {
9240 	case IPPROTO_TCP:
9241 		switch (name) {
9242 		case TCP_NOTIFY_THRESHOLD:
9243 			*i1 = tcp_ip_notify_interval;
9244 			break;
9245 		case TCP_ABORT_THRESHOLD:
9246 			*i1 = tcp_ip_abort_interval;
9247 			break;
9248 		case TCP_CONN_NOTIFY_THRESHOLD:
9249 			*i1 = tcp_ip_notify_cinterval;
9250 			break;
9251 		case TCP_CONN_ABORT_THRESHOLD:
9252 			*i1 = tcp_ip_abort_cinterval;
9253 			break;
9254 		default:
9255 			return (-1);
9256 		}
9257 		break;
9258 	case IPPROTO_IP:
9259 		switch (name) {
9260 		case IP_TTL:
9261 			*i1 = tcp_ipv4_ttl;
9262 			break;
9263 		default:
9264 			return (-1);
9265 		}
9266 		break;
9267 	case IPPROTO_IPV6:
9268 		switch (name) {
9269 		case IPV6_UNICAST_HOPS:
9270 			*i1 = tcp_ipv6_hoplimit;
9271 			break;
9272 		default:
9273 			return (-1);
9274 		}
9275 		break;
9276 	default:
9277 		return (-1);
9278 	}
9279 	return (sizeof (int));
9280 }
9281 
9282 
9283 /*
9284  * TCP routine to get the values of options.
9285  */
9286 int
9287 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9288 {
9289 	int		*i1 = (int *)ptr;
9290 	conn_t		*connp = Q_TO_CONN(q);
9291 	tcp_t		*tcp = connp->conn_tcp;
9292 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9293 
9294 	switch (level) {
9295 	case SOL_SOCKET:
9296 		switch (name) {
9297 		case SO_LINGER:	{
9298 			struct linger *lgr = (struct linger *)ptr;
9299 
9300 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9301 			lgr->l_linger = tcp->tcp_lingertime;
9302 			}
9303 			return (sizeof (struct linger));
9304 		case SO_DEBUG:
9305 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9306 			break;
9307 		case SO_KEEPALIVE:
9308 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9309 			break;
9310 		case SO_DONTROUTE:
9311 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9312 			break;
9313 		case SO_USELOOPBACK:
9314 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9315 			break;
9316 		case SO_BROADCAST:
9317 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9318 			break;
9319 		case SO_REUSEADDR:
9320 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9321 			break;
9322 		case SO_OOBINLINE:
9323 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9324 			break;
9325 		case SO_DGRAM_ERRIND:
9326 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9327 			break;
9328 		case SO_TYPE:
9329 			*i1 = SOCK_STREAM;
9330 			break;
9331 		case SO_SNDBUF:
9332 			*i1 = tcp->tcp_xmit_hiwater;
9333 			break;
9334 		case SO_RCVBUF:
9335 			*i1 = RD(q)->q_hiwat;
9336 			break;
9337 		case SO_SND_COPYAVOID:
9338 			*i1 = tcp->tcp_snd_zcopy_on ?
9339 			    SO_SND_COPYAVOID : 0;
9340 			break;
9341 		default:
9342 			return (-1);
9343 		}
9344 		break;
9345 	case IPPROTO_TCP:
9346 		switch (name) {
9347 		case TCP_NODELAY:
9348 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9349 			break;
9350 		case TCP_MAXSEG:
9351 			*i1 = tcp->tcp_mss;
9352 			break;
9353 		case TCP_NOTIFY_THRESHOLD:
9354 			*i1 = (int)tcp->tcp_first_timer_threshold;
9355 			break;
9356 		case TCP_ABORT_THRESHOLD:
9357 			*i1 = tcp->tcp_second_timer_threshold;
9358 			break;
9359 		case TCP_CONN_NOTIFY_THRESHOLD:
9360 			*i1 = tcp->tcp_first_ctimer_threshold;
9361 			break;
9362 		case TCP_CONN_ABORT_THRESHOLD:
9363 			*i1 = tcp->tcp_second_ctimer_threshold;
9364 			break;
9365 		case TCP_RECVDSTADDR:
9366 			*i1 = tcp->tcp_recvdstaddr;
9367 			break;
9368 		case TCP_ANONPRIVBIND:
9369 			*i1 = tcp->tcp_anon_priv_bind;
9370 			break;
9371 		case TCP_EXCLBIND:
9372 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9373 			break;
9374 		case TCP_INIT_CWND:
9375 			*i1 = tcp->tcp_init_cwnd;
9376 			break;
9377 		case TCP_KEEPALIVE_THRESHOLD:
9378 			*i1 = tcp->tcp_ka_interval;
9379 			break;
9380 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9381 			*i1 = tcp->tcp_ka_abort_thres;
9382 			break;
9383 		case TCP_CORK:
9384 			*i1 = tcp->tcp_cork;
9385 			break;
9386 		default:
9387 			return (-1);
9388 		}
9389 		break;
9390 	case IPPROTO_IP:
9391 		if (tcp->tcp_family != AF_INET)
9392 			return (-1);
9393 		switch (name) {
9394 		case IP_OPTIONS:
9395 		case T_IP_OPTIONS: {
9396 			/*
9397 			 * This is compatible with BSD in that in only return
9398 			 * the reverse source route with the final destination
9399 			 * as the last entry. The first 4 bytes of the option
9400 			 * will contain the final destination.
9401 			 */
9402 			char	*opt_ptr;
9403 			int	opt_len;
9404 			opt_ptr = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
9405 			opt_len = (char *)tcp->tcp_tcph - opt_ptr;
9406 			/* Caller ensures enough space */
9407 			if (opt_len > 0) {
9408 				/*
9409 				 * TODO: Do we have to handle getsockopt on an
9410 				 * initiator as well?
9411 				 */
9412 				return (tcp_opt_get_user(tcp->tcp_ipha, ptr));
9413 			}
9414 			return (0);
9415 			}
9416 		case IP_TOS:
9417 		case T_IP_TOS:
9418 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9419 			break;
9420 		case IP_TTL:
9421 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9422 			break;
9423 		case IP_NEXTHOP:
9424 			/* Handled at IP level */
9425 			return (-EINVAL);
9426 		default:
9427 			return (-1);
9428 		}
9429 		break;
9430 	case IPPROTO_IPV6:
9431 		/*
9432 		 * IPPROTO_IPV6 options are only supported for sockets
9433 		 * that are using IPv6 on the wire.
9434 		 */
9435 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9436 			return (-1);
9437 		}
9438 		switch (name) {
9439 		case IPV6_UNICAST_HOPS:
9440 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9441 			break;	/* goto sizeof (int) option return */
9442 		case IPV6_BOUND_IF:
9443 			/* Zero if not set */
9444 			*i1 = tcp->tcp_bound_if;
9445 			break;	/* goto sizeof (int) option return */
9446 		case IPV6_RECVPKTINFO:
9447 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9448 				*i1 = 1;
9449 			else
9450 				*i1 = 0;
9451 			break;	/* goto sizeof (int) option return */
9452 		case IPV6_RECVTCLASS:
9453 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9454 				*i1 = 1;
9455 			else
9456 				*i1 = 0;
9457 			break;	/* goto sizeof (int) option return */
9458 		case IPV6_RECVHOPLIMIT:
9459 			if (tcp->tcp_ipv6_recvancillary &
9460 			    TCP_IPV6_RECVHOPLIMIT)
9461 				*i1 = 1;
9462 			else
9463 				*i1 = 0;
9464 			break;	/* goto sizeof (int) option return */
9465 		case IPV6_RECVHOPOPTS:
9466 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9467 				*i1 = 1;
9468 			else
9469 				*i1 = 0;
9470 			break;	/* goto sizeof (int) option return */
9471 		case IPV6_RECVDSTOPTS:
9472 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9473 				*i1 = 1;
9474 			else
9475 				*i1 = 0;
9476 			break;	/* goto sizeof (int) option return */
9477 		case _OLD_IPV6_RECVDSTOPTS:
9478 			if (tcp->tcp_ipv6_recvancillary &
9479 			    TCP_OLD_IPV6_RECVDSTOPTS)
9480 				*i1 = 1;
9481 			else
9482 				*i1 = 0;
9483 			break;	/* goto sizeof (int) option return */
9484 		case IPV6_RECVRTHDR:
9485 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9486 				*i1 = 1;
9487 			else
9488 				*i1 = 0;
9489 			break;	/* goto sizeof (int) option return */
9490 		case IPV6_RECVRTHDRDSTOPTS:
9491 			if (tcp->tcp_ipv6_recvancillary &
9492 			    TCP_IPV6_RECVRTDSTOPTS)
9493 				*i1 = 1;
9494 			else
9495 				*i1 = 0;
9496 			break;	/* goto sizeof (int) option return */
9497 		case IPV6_PKTINFO: {
9498 			/* XXX assumes that caller has room for max size! */
9499 			struct in6_pktinfo *pkti;
9500 
9501 			pkti = (struct in6_pktinfo *)ptr;
9502 			if (ipp->ipp_fields & IPPF_IFINDEX)
9503 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9504 			else
9505 				pkti->ipi6_ifindex = 0;
9506 			if (ipp->ipp_fields & IPPF_ADDR)
9507 				pkti->ipi6_addr = ipp->ipp_addr;
9508 			else
9509 				pkti->ipi6_addr = ipv6_all_zeros;
9510 			return (sizeof (struct in6_pktinfo));
9511 		}
9512 		case IPV6_TCLASS:
9513 			if (ipp->ipp_fields & IPPF_TCLASS)
9514 				*i1 = ipp->ipp_tclass;
9515 			else
9516 				*i1 = IPV6_FLOW_TCLASS(
9517 				    IPV6_DEFAULT_VERS_AND_FLOW);
9518 			break;	/* goto sizeof (int) option return */
9519 		case IPV6_NEXTHOP: {
9520 			sin6_t *sin6 = (sin6_t *)ptr;
9521 
9522 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9523 				return (0);
9524 			*sin6 = sin6_null;
9525 			sin6->sin6_family = AF_INET6;
9526 			sin6->sin6_addr = ipp->ipp_nexthop;
9527 			return (sizeof (sin6_t));
9528 		}
9529 		case IPV6_HOPOPTS:
9530 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9531 				return (0);
9532 			bcopy(ipp->ipp_hopopts, ptr, ipp->ipp_hopoptslen);
9533 			return (ipp->ipp_hopoptslen);
9534 		case IPV6_RTHDRDSTOPTS:
9535 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9536 				return (0);
9537 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9538 			return (ipp->ipp_rtdstoptslen);
9539 		case IPV6_RTHDR:
9540 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9541 				return (0);
9542 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9543 			return (ipp->ipp_rthdrlen);
9544 		case IPV6_DSTOPTS:
9545 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9546 				return (0);
9547 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9548 			return (ipp->ipp_dstoptslen);
9549 		case IPV6_SRC_PREFERENCES:
9550 			return (ip6_get_src_preferences(connp,
9551 			    (uint32_t *)ptr));
9552 		case IPV6_PATHMTU: {
9553 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9554 
9555 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9556 				return (-1);
9557 
9558 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9559 				connp->conn_fport, mtuinfo));
9560 		}
9561 		default:
9562 			return (-1);
9563 		}
9564 		break;
9565 	default:
9566 		return (-1);
9567 	}
9568 	return (sizeof (int));
9569 }
9570 
9571 /*
9572  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9573  * Parameters are assumed to be verified by the caller.
9574  */
9575 /* ARGSUSED */
9576 int
9577 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9578     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9579     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9580 {
9581 	tcp_t	*tcp = Q_TO_TCP(q);
9582 	int	*i1 = (int *)invalp;
9583 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9584 	boolean_t checkonly;
9585 	int	reterr;
9586 
9587 	switch (optset_context) {
9588 	case SETFN_OPTCOM_CHECKONLY:
9589 		checkonly = B_TRUE;
9590 		/*
9591 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9592 		 * inlen != 0 implies value supplied and
9593 		 * 	we have to "pretend" to set it.
9594 		 * inlen == 0 implies that there is no
9595 		 * 	value part in T_CHECK request and just validation
9596 		 * done elsewhere should be enough, we just return here.
9597 		 */
9598 		if (inlen == 0) {
9599 			*outlenp = 0;
9600 			return (0);
9601 		}
9602 		break;
9603 	case SETFN_OPTCOM_NEGOTIATE:
9604 		checkonly = B_FALSE;
9605 		break;
9606 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9607 	case SETFN_CONN_NEGOTIATE:
9608 		checkonly = B_FALSE;
9609 		/*
9610 		 * Negotiating local and "association-related" options
9611 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9612 		 * primitives is allowed by XTI, but we choose
9613 		 * to not implement this style negotiation for Internet
9614 		 * protocols (We interpret it is a must for OSI world but
9615 		 * optional for Internet protocols) for all options.
9616 		 * [ Will do only for the few options that enable test
9617 		 * suites that our XTI implementation of this feature
9618 		 * works for transports that do allow it ]
9619 		 */
9620 		if (!tcp_allow_connopt_set(level, name)) {
9621 			*outlenp = 0;
9622 			return (EINVAL);
9623 		}
9624 		break;
9625 	default:
9626 		/*
9627 		 * We should never get here
9628 		 */
9629 		*outlenp = 0;
9630 		return (EINVAL);
9631 	}
9632 
9633 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9634 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9635 
9636 	/*
9637 	 * For TCP, we should have no ancillary data sent down
9638 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9639 	 * has to be zero.
9640 	 */
9641 	ASSERT(thisdg_attrs == NULL);
9642 
9643 	/*
9644 	 * For fixed length options, no sanity check
9645 	 * of passed in length is done. It is assumed *_optcom_req()
9646 	 * routines do the right thing.
9647 	 */
9648 
9649 	switch (level) {
9650 	case SOL_SOCKET:
9651 		switch (name) {
9652 		case SO_LINGER: {
9653 			struct linger *lgr = (struct linger *)invalp;
9654 
9655 			if (!checkonly) {
9656 				if (lgr->l_onoff) {
9657 					tcp->tcp_linger = 1;
9658 					tcp->tcp_lingertime = lgr->l_linger;
9659 				} else {
9660 					tcp->tcp_linger = 0;
9661 					tcp->tcp_lingertime = 0;
9662 				}
9663 				/* struct copy */
9664 				*(struct linger *)outvalp = *lgr;
9665 			} else {
9666 				if (!lgr->l_onoff) {
9667 				    ((struct linger *)outvalp)->l_onoff = 0;
9668 				    ((struct linger *)outvalp)->l_linger = 0;
9669 				} else {
9670 				    /* struct copy */
9671 				    *(struct linger *)outvalp = *lgr;
9672 				}
9673 			}
9674 			*outlenp = sizeof (struct linger);
9675 			return (0);
9676 		}
9677 		case SO_DEBUG:
9678 			if (!checkonly)
9679 				tcp->tcp_debug = onoff;
9680 			break;
9681 		case SO_KEEPALIVE:
9682 			if (checkonly) {
9683 				/* T_CHECK case */
9684 				break;
9685 			}
9686 
9687 			if (!onoff) {
9688 				if (tcp->tcp_ka_enabled) {
9689 					if (tcp->tcp_ka_tid != 0) {
9690 						(void) TCP_TIMER_CANCEL(tcp,
9691 						    tcp->tcp_ka_tid);
9692 						tcp->tcp_ka_tid = 0;
9693 					}
9694 					tcp->tcp_ka_enabled = 0;
9695 				}
9696 				break;
9697 			}
9698 			if (!tcp->tcp_ka_enabled) {
9699 				/* Crank up the keepalive timer */
9700 				tcp->tcp_ka_last_intrvl = 0;
9701 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9702 				    tcp_keepalive_killer,
9703 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
9704 				tcp->tcp_ka_enabled = 1;
9705 			}
9706 			break;
9707 		case SO_DONTROUTE:
9708 			/*
9709 			 * SO_DONTROUTE, SO_USELOOPBACK and SO_BROADCAST are
9710 			 * only of interest to IP.  We track them here only so
9711 			 * that we can report their current value.
9712 			 */
9713 			if (!checkonly) {
9714 				tcp->tcp_dontroute = onoff;
9715 				tcp->tcp_connp->conn_dontroute = onoff;
9716 			}
9717 			break;
9718 		case SO_USELOOPBACK:
9719 			if (!checkonly) {
9720 				tcp->tcp_useloopback = onoff;
9721 				tcp->tcp_connp->conn_loopback = onoff;
9722 			}
9723 			break;
9724 		case SO_BROADCAST:
9725 			if (!checkonly) {
9726 				tcp->tcp_broadcast = onoff;
9727 				tcp->tcp_connp->conn_broadcast = onoff;
9728 			}
9729 			break;
9730 		case SO_REUSEADDR:
9731 			if (!checkonly) {
9732 				tcp->tcp_reuseaddr = onoff;
9733 				tcp->tcp_connp->conn_reuseaddr = onoff;
9734 			}
9735 			break;
9736 		case SO_OOBINLINE:
9737 			if (!checkonly)
9738 				tcp->tcp_oobinline = onoff;
9739 			break;
9740 		case SO_DGRAM_ERRIND:
9741 			if (!checkonly)
9742 				tcp->tcp_dgram_errind = onoff;
9743 			break;
9744 		case SO_SNDBUF: {
9745 			tcp_t *peer_tcp;
9746 
9747 			if (*i1 > tcp_max_buf) {
9748 				*outlenp = 0;
9749 				return (ENOBUFS);
9750 			}
9751 			if (checkonly)
9752 				break;
9753 
9754 			tcp->tcp_xmit_hiwater = *i1;
9755 			if (tcp_snd_lowat_fraction != 0)
9756 				tcp->tcp_xmit_lowater =
9757 				    tcp->tcp_xmit_hiwater /
9758 				    tcp_snd_lowat_fraction;
9759 			(void) tcp_maxpsz_set(tcp, B_TRUE);
9760 			/*
9761 			 * If we are flow-controlled, recheck the condition.
9762 			 * There are apps that increase SO_SNDBUF size when
9763 			 * flow-controlled (EWOULDBLOCK), and expect the flow
9764 			 * control condition to be lifted right away.
9765 			 *
9766 			 * For the fused tcp loopback case, in order to avoid
9767 			 * a race with the peer's tcp_fuse_rrw() we need to
9768 			 * hold its fuse_lock while accessing tcp_flow_stopped.
9769 			 */
9770 			peer_tcp = tcp->tcp_loopback_peer;
9771 			ASSERT(!tcp->tcp_fused || peer_tcp != NULL);
9772 			if (tcp->tcp_fused)
9773 				mutex_enter(&peer_tcp->tcp_fuse_lock);
9774 
9775 			if (tcp->tcp_flow_stopped &&
9776 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
9777 				tcp_clrqfull(tcp);
9778 			}
9779 			if (tcp->tcp_fused)
9780 				mutex_exit(&peer_tcp->tcp_fuse_lock);
9781 			break;
9782 		}
9783 		case SO_RCVBUF:
9784 			if (*i1 > tcp_max_buf) {
9785 				*outlenp = 0;
9786 				return (ENOBUFS);
9787 			}
9788 			/* Silently ignore zero */
9789 			if (!checkonly && *i1 != 0) {
9790 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
9791 				(void) tcp_rwnd_set(tcp, *i1);
9792 			}
9793 			/*
9794 			 * XXX should we return the rwnd here
9795 			 * and tcp_opt_get ?
9796 			 */
9797 			break;
9798 		case SO_SND_COPYAVOID:
9799 			if (!checkonly) {
9800 				/* we only allow enable at most once for now */
9801 				if (tcp->tcp_loopback ||
9802 				    (!tcp->tcp_snd_zcopy_aware &&
9803 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
9804 					*outlenp = 0;
9805 					return (EOPNOTSUPP);
9806 				}
9807 				tcp->tcp_snd_zcopy_aware = 1;
9808 			}
9809 			break;
9810 		default:
9811 			*outlenp = 0;
9812 			return (EINVAL);
9813 		}
9814 		break;
9815 	case IPPROTO_TCP:
9816 		switch (name) {
9817 		case TCP_NODELAY:
9818 			if (!checkonly)
9819 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
9820 			break;
9821 		case TCP_NOTIFY_THRESHOLD:
9822 			if (!checkonly)
9823 				tcp->tcp_first_timer_threshold = *i1;
9824 			break;
9825 		case TCP_ABORT_THRESHOLD:
9826 			if (!checkonly)
9827 				tcp->tcp_second_timer_threshold = *i1;
9828 			break;
9829 		case TCP_CONN_NOTIFY_THRESHOLD:
9830 			if (!checkonly)
9831 				tcp->tcp_first_ctimer_threshold = *i1;
9832 			break;
9833 		case TCP_CONN_ABORT_THRESHOLD:
9834 			if (!checkonly)
9835 				tcp->tcp_second_ctimer_threshold = *i1;
9836 			break;
9837 		case TCP_RECVDSTADDR:
9838 			if (tcp->tcp_state > TCPS_LISTEN)
9839 				return (EOPNOTSUPP);
9840 			if (!checkonly)
9841 				tcp->tcp_recvdstaddr = onoff;
9842 			break;
9843 		case TCP_ANONPRIVBIND:
9844 			if ((reterr = secpolicy_net_privaddr(cr, 0)) != 0) {
9845 				*outlenp = 0;
9846 				return (reterr);
9847 			}
9848 			if (!checkonly) {
9849 				tcp->tcp_anon_priv_bind = onoff;
9850 			}
9851 			break;
9852 		case TCP_EXCLBIND:
9853 			if (!checkonly)
9854 				tcp->tcp_exclbind = onoff;
9855 			break;	/* goto sizeof (int) option return */
9856 		case TCP_INIT_CWND: {
9857 			uint32_t init_cwnd = *((uint32_t *)invalp);
9858 
9859 			if (checkonly)
9860 				break;
9861 
9862 			/*
9863 			 * Only allow socket with network configuration
9864 			 * privilege to set the initial cwnd to be larger
9865 			 * than allowed by RFC 3390.
9866 			 */
9867 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
9868 				tcp->tcp_init_cwnd = init_cwnd;
9869 				break;
9870 			}
9871 			if ((reterr = secpolicy_net_config(cr, B_TRUE)) != 0) {
9872 				*outlenp = 0;
9873 				return (reterr);
9874 			}
9875 			if (init_cwnd > TCP_MAX_INIT_CWND) {
9876 				*outlenp = 0;
9877 				return (EINVAL);
9878 			}
9879 			tcp->tcp_init_cwnd = init_cwnd;
9880 			break;
9881 		}
9882 		case TCP_KEEPALIVE_THRESHOLD:
9883 			if (checkonly)
9884 				break;
9885 
9886 			if (*i1 < tcp_keepalive_interval_low ||
9887 			    *i1 > tcp_keepalive_interval_high) {
9888 				*outlenp = 0;
9889 				return (EINVAL);
9890 			}
9891 			if (*i1 != tcp->tcp_ka_interval) {
9892 				tcp->tcp_ka_interval = *i1;
9893 				/*
9894 				 * Check if we need to restart the
9895 				 * keepalive timer.
9896 				 */
9897 				if (tcp->tcp_ka_tid != 0) {
9898 					ASSERT(tcp->tcp_ka_enabled);
9899 					(void) TCP_TIMER_CANCEL(tcp,
9900 					    tcp->tcp_ka_tid);
9901 					tcp->tcp_ka_last_intrvl = 0;
9902 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
9903 					    tcp_keepalive_killer,
9904 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
9905 				}
9906 			}
9907 			break;
9908 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9909 			if (!checkonly) {
9910 				if (*i1 < tcp_keepalive_abort_interval_low ||
9911 				    *i1 > tcp_keepalive_abort_interval_high) {
9912 					*outlenp = 0;
9913 					return (EINVAL);
9914 				}
9915 				tcp->tcp_ka_abort_thres = *i1;
9916 			}
9917 			break;
9918 		case TCP_CORK:
9919 			if (!checkonly) {
9920 				/*
9921 				 * if tcp->tcp_cork was set and is now
9922 				 * being unset, we have to make sure that
9923 				 * the remaining data gets sent out. Also
9924 				 * unset tcp->tcp_cork so that tcp_wput_data()
9925 				 * can send data even if it is less than mss
9926 				 */
9927 				if (tcp->tcp_cork && onoff == 0 &&
9928 				    tcp->tcp_unsent > 0) {
9929 					tcp->tcp_cork = B_FALSE;
9930 					tcp_wput_data(tcp, NULL, B_FALSE);
9931 				}
9932 				tcp->tcp_cork = onoff;
9933 			}
9934 			break;
9935 		default:
9936 			*outlenp = 0;
9937 			return (EINVAL);
9938 		}
9939 		break;
9940 	case IPPROTO_IP:
9941 		if (tcp->tcp_family != AF_INET) {
9942 			*outlenp = 0;
9943 			return (ENOPROTOOPT);
9944 		}
9945 		switch (name) {
9946 		case IP_OPTIONS:
9947 		case T_IP_OPTIONS:
9948 			reterr = tcp_opt_set_header(tcp, checkonly,
9949 			    invalp, inlen);
9950 			if (reterr) {
9951 				*outlenp = 0;
9952 				return (reterr);
9953 			}
9954 			/* OK return - copy input buffer into output buffer */
9955 			if (invalp != outvalp) {
9956 				/* don't trust bcopy for identical src/dst */
9957 				bcopy(invalp, outvalp, inlen);
9958 			}
9959 			*outlenp = inlen;
9960 			return (0);
9961 		case IP_TOS:
9962 		case T_IP_TOS:
9963 			if (!checkonly) {
9964 				tcp->tcp_ipha->ipha_type_of_service =
9965 				    (uchar_t)*i1;
9966 				tcp->tcp_tos = (uchar_t)*i1;
9967 			}
9968 			break;
9969 		case IP_TTL:
9970 			if (!checkonly) {
9971 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
9972 				tcp->tcp_ttl = (uchar_t)*i1;
9973 			}
9974 			break;
9975 		case IP_BOUND_IF:
9976 		case IP_NEXTHOP:
9977 			/* Handled at the IP level */
9978 			return (-EINVAL);
9979 		case IP_SEC_OPT:
9980 			/*
9981 			 * We should not allow policy setting after
9982 			 * we start listening for connections.
9983 			 */
9984 			if (tcp->tcp_state == TCPS_LISTEN) {
9985 				return (EINVAL);
9986 			} else {
9987 				/* Handled at the IP level */
9988 				return (-EINVAL);
9989 			}
9990 		default:
9991 			*outlenp = 0;
9992 			return (EINVAL);
9993 		}
9994 		break;
9995 	case IPPROTO_IPV6: {
9996 		ip6_pkt_t		*ipp;
9997 
9998 		/*
9999 		 * IPPROTO_IPV6 options are only supported for sockets
10000 		 * that are using IPv6 on the wire.
10001 		 */
10002 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10003 			*outlenp = 0;
10004 			return (ENOPROTOOPT);
10005 		}
10006 		/*
10007 		 * Only sticky options; no ancillary data
10008 		 */
10009 		ASSERT(thisdg_attrs == NULL);
10010 		ipp = &tcp->tcp_sticky_ipp;
10011 
10012 		switch (name) {
10013 		case IPV6_UNICAST_HOPS:
10014 			/* -1 means use default */
10015 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10016 				*outlenp = 0;
10017 				return (EINVAL);
10018 			}
10019 			if (!checkonly) {
10020 				if (*i1 == -1) {
10021 					tcp->tcp_ip6h->ip6_hops =
10022 					    ipp->ipp_unicast_hops =
10023 					    (uint8_t)tcp_ipv6_hoplimit;
10024 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10025 					/* Pass modified value to IP. */
10026 					*i1 = tcp->tcp_ip6h->ip6_hops;
10027 				} else {
10028 					tcp->tcp_ip6h->ip6_hops =
10029 					    ipp->ipp_unicast_hops =
10030 					    (uint8_t)*i1;
10031 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10032 				}
10033 				reterr = tcp_build_hdrs(q, tcp);
10034 				if (reterr != 0)
10035 					return (reterr);
10036 			}
10037 			break;
10038 		case IPV6_BOUND_IF:
10039 			if (!checkonly) {
10040 				int error = 0;
10041 
10042 				tcp->tcp_bound_if = *i1;
10043 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10044 				    B_TRUE, checkonly, level, name, mblk);
10045 				if (error != 0) {
10046 					*outlenp = 0;
10047 					return (error);
10048 				}
10049 			}
10050 			break;
10051 		/*
10052 		 * Set boolean switches for ancillary data delivery
10053 		 */
10054 		case IPV6_RECVPKTINFO:
10055 			if (!checkonly) {
10056 				if (onoff)
10057 					tcp->tcp_ipv6_recvancillary |=
10058 					    TCP_IPV6_RECVPKTINFO;
10059 				else
10060 					tcp->tcp_ipv6_recvancillary &=
10061 					    ~TCP_IPV6_RECVPKTINFO;
10062 				/* Force it to be sent up with the next msg */
10063 				tcp->tcp_recvifindex = 0;
10064 			}
10065 			break;
10066 		case IPV6_RECVTCLASS:
10067 			if (!checkonly) {
10068 				if (onoff)
10069 					tcp->tcp_ipv6_recvancillary |=
10070 					    TCP_IPV6_RECVTCLASS;
10071 				else
10072 					tcp->tcp_ipv6_recvancillary &=
10073 					    ~TCP_IPV6_RECVTCLASS;
10074 			}
10075 			break;
10076 		case IPV6_RECVHOPLIMIT:
10077 			if (!checkonly) {
10078 				if (onoff)
10079 					tcp->tcp_ipv6_recvancillary |=
10080 					    TCP_IPV6_RECVHOPLIMIT;
10081 				else
10082 					tcp->tcp_ipv6_recvancillary &=
10083 					    ~TCP_IPV6_RECVHOPLIMIT;
10084 				/* Force it to be sent up with the next msg */
10085 				tcp->tcp_recvhops = 0xffffffffU;
10086 			}
10087 			break;
10088 		case IPV6_RECVHOPOPTS:
10089 			if (!checkonly) {
10090 				if (onoff)
10091 					tcp->tcp_ipv6_recvancillary |=
10092 					    TCP_IPV6_RECVHOPOPTS;
10093 				else
10094 					tcp->tcp_ipv6_recvancillary &=
10095 					    ~TCP_IPV6_RECVHOPOPTS;
10096 			}
10097 			break;
10098 		case IPV6_RECVDSTOPTS:
10099 			if (!checkonly) {
10100 				if (onoff)
10101 					tcp->tcp_ipv6_recvancillary |=
10102 					    TCP_IPV6_RECVDSTOPTS;
10103 				else
10104 					tcp->tcp_ipv6_recvancillary &=
10105 					    ~TCP_IPV6_RECVDSTOPTS;
10106 			}
10107 			break;
10108 		case _OLD_IPV6_RECVDSTOPTS:
10109 			if (!checkonly) {
10110 				if (onoff)
10111 					tcp->tcp_ipv6_recvancillary |=
10112 					    TCP_OLD_IPV6_RECVDSTOPTS;
10113 				else
10114 					tcp->tcp_ipv6_recvancillary &=
10115 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10116 			}
10117 			break;
10118 		case IPV6_RECVRTHDR:
10119 			if (!checkonly) {
10120 				if (onoff)
10121 					tcp->tcp_ipv6_recvancillary |=
10122 					    TCP_IPV6_RECVRTHDR;
10123 				else
10124 					tcp->tcp_ipv6_recvancillary &=
10125 					    ~TCP_IPV6_RECVRTHDR;
10126 			}
10127 			break;
10128 		case IPV6_RECVRTHDRDSTOPTS:
10129 			if (!checkonly) {
10130 				if (onoff)
10131 					tcp->tcp_ipv6_recvancillary |=
10132 					    TCP_IPV6_RECVRTDSTOPTS;
10133 				else
10134 					tcp->tcp_ipv6_recvancillary &=
10135 					    ~TCP_IPV6_RECVRTDSTOPTS;
10136 			}
10137 			break;
10138 		case IPV6_PKTINFO:
10139 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10140 				return (EINVAL);
10141 			if (checkonly)
10142 				break;
10143 
10144 			if (inlen == 0) {
10145 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10146 			} else {
10147 				struct in6_pktinfo *pkti;
10148 
10149 				pkti = (struct in6_pktinfo *)invalp;
10150 				/*
10151 				 * RFC 3542 states that ipi6_addr must be
10152 				 * the unspecified address when setting the
10153 				 * IPV6_PKTINFO sticky socket option on a
10154 				 * TCP socket.
10155 				 */
10156 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10157 					return (EINVAL);
10158 				/*
10159 				 * ip6_set_pktinfo() validates the source
10160 				 * address and interface index.
10161 				 */
10162 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10163 				    pkti, mblk);
10164 				if (reterr != 0)
10165 					return (reterr);
10166 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10167 				ipp->ipp_addr = pkti->ipi6_addr;
10168 				if (ipp->ipp_ifindex != 0)
10169 					ipp->ipp_fields |= IPPF_IFINDEX;
10170 				else
10171 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10172 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10173 					ipp->ipp_fields |= IPPF_ADDR;
10174 				else
10175 					ipp->ipp_fields &= ~IPPF_ADDR;
10176 			}
10177 			reterr = tcp_build_hdrs(q, tcp);
10178 			if (reterr != 0)
10179 				return (reterr);
10180 			break;
10181 		case IPV6_TCLASS:
10182 			if (inlen != 0 && inlen != sizeof (int))
10183 				return (EINVAL);
10184 			if (checkonly)
10185 				break;
10186 
10187 			if (inlen == 0) {
10188 				ipp->ipp_fields &= ~IPPF_TCLASS;
10189 			} else {
10190 				if (*i1 > 255 || *i1 < -1)
10191 					return (EINVAL);
10192 				if (*i1 == -1) {
10193 					ipp->ipp_tclass = 0;
10194 					*i1 = 0;
10195 				} else {
10196 					ipp->ipp_tclass = *i1;
10197 				}
10198 				ipp->ipp_fields |= IPPF_TCLASS;
10199 			}
10200 			reterr = tcp_build_hdrs(q, tcp);
10201 			if (reterr != 0)
10202 				return (reterr);
10203 			break;
10204 		case IPV6_NEXTHOP:
10205 			/*
10206 			 * IP will verify that the nexthop is reachable
10207 			 * and fail for sticky options.
10208 			 */
10209 			if (inlen != 0 && inlen != sizeof (sin6_t))
10210 				return (EINVAL);
10211 			if (checkonly)
10212 				break;
10213 
10214 			if (inlen == 0) {
10215 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10216 			} else {
10217 				sin6_t *sin6 = (sin6_t *)invalp;
10218 
10219 				if (sin6->sin6_family != AF_INET6)
10220 					return (EAFNOSUPPORT);
10221 				if (IN6_IS_ADDR_V4MAPPED(
10222 				    &sin6->sin6_addr))
10223 					return (EADDRNOTAVAIL);
10224 				ipp->ipp_nexthop = sin6->sin6_addr;
10225 				if (!IN6_IS_ADDR_UNSPECIFIED(
10226 				    &ipp->ipp_nexthop))
10227 					ipp->ipp_fields |= IPPF_NEXTHOP;
10228 				else
10229 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10230 			}
10231 			reterr = tcp_build_hdrs(q, tcp);
10232 			if (reterr != 0)
10233 				return (reterr);
10234 			break;
10235 		case IPV6_HOPOPTS: {
10236 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10237 			/*
10238 			 * Sanity checks - minimum size, size a multiple of
10239 			 * eight bytes, and matching size passed in.
10240 			 */
10241 			if (inlen != 0 &&
10242 			    inlen != (8 * (hopts->ip6h_len + 1)))
10243 				return (EINVAL);
10244 
10245 			if (checkonly)
10246 				break;
10247 
10248 			if (inlen == 0) {
10249 				if ((ipp->ipp_fields & IPPF_HOPOPTS) != 0) {
10250 					kmem_free(ipp->ipp_hopopts,
10251 					    ipp->ipp_hopoptslen);
10252 					ipp->ipp_hopopts = NULL;
10253 					ipp->ipp_hopoptslen = 0;
10254 				}
10255 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10256 			} else {
10257 				reterr = tcp_pkt_set(invalp, inlen,
10258 				    (uchar_t **)&ipp->ipp_hopopts,
10259 				    &ipp->ipp_hopoptslen);
10260 				if (reterr != 0)
10261 					return (reterr);
10262 				ipp->ipp_fields |= IPPF_HOPOPTS;
10263 			}
10264 			reterr = tcp_build_hdrs(q, tcp);
10265 			if (reterr != 0)
10266 				return (reterr);
10267 			break;
10268 		}
10269 		case IPV6_RTHDRDSTOPTS: {
10270 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10271 
10272 			/*
10273 			 * Sanity checks - minimum size, size a multiple of
10274 			 * eight bytes, and matching size passed in.
10275 			 */
10276 			if (inlen != 0 &&
10277 			    inlen != (8 * (dopts->ip6d_len + 1)))
10278 				return (EINVAL);
10279 
10280 			if (checkonly)
10281 				break;
10282 
10283 			if (inlen == 0) {
10284 				if ((ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
10285 					kmem_free(ipp->ipp_rtdstopts,
10286 					    ipp->ipp_rtdstoptslen);
10287 					ipp->ipp_rtdstopts = NULL;
10288 					ipp->ipp_rtdstoptslen = 0;
10289 				}
10290 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10291 			} else {
10292 				reterr = tcp_pkt_set(invalp, inlen,
10293 				    (uchar_t **)&ipp->ipp_rtdstopts,
10294 				    &ipp->ipp_rtdstoptslen);
10295 				if (reterr != 0)
10296 					return (reterr);
10297 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10298 			}
10299 			reterr = tcp_build_hdrs(q, tcp);
10300 			if (reterr != 0)
10301 				return (reterr);
10302 			break;
10303 		}
10304 		case IPV6_DSTOPTS: {
10305 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10306 
10307 			/*
10308 			 * Sanity checks - minimum size, size a multiple of
10309 			 * eight bytes, and matching size passed in.
10310 			 */
10311 			if (inlen != 0 &&
10312 			    inlen != (8 * (dopts->ip6d_len + 1)))
10313 				return (EINVAL);
10314 
10315 			if (checkonly)
10316 				break;
10317 
10318 			if (inlen == 0) {
10319 				if ((ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
10320 					kmem_free(ipp->ipp_dstopts,
10321 					    ipp->ipp_dstoptslen);
10322 					ipp->ipp_dstopts = NULL;
10323 					ipp->ipp_dstoptslen = 0;
10324 				}
10325 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10326 			} else {
10327 				reterr = tcp_pkt_set(invalp, inlen,
10328 				    (uchar_t **)&ipp->ipp_dstopts,
10329 				    &ipp->ipp_dstoptslen);
10330 				if (reterr != 0)
10331 					return (reterr);
10332 				ipp->ipp_fields |= IPPF_DSTOPTS;
10333 			}
10334 			reterr = tcp_build_hdrs(q, tcp);
10335 			if (reterr != 0)
10336 				return (reterr);
10337 			break;
10338 		}
10339 		case IPV6_RTHDR: {
10340 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10341 
10342 			/*
10343 			 * Sanity checks - minimum size, size a multiple of
10344 			 * eight bytes, and matching size passed in.
10345 			 */
10346 			if (inlen != 0 &&
10347 			    inlen != (8 * (rt->ip6r_len + 1)))
10348 				return (EINVAL);
10349 
10350 			if (checkonly)
10351 				break;
10352 
10353 			if (inlen == 0) {
10354 				if ((ipp->ipp_fields & IPPF_RTHDR) != 0) {
10355 					kmem_free(ipp->ipp_rthdr,
10356 					    ipp->ipp_rthdrlen);
10357 					ipp->ipp_rthdr = NULL;
10358 					ipp->ipp_rthdrlen = 0;
10359 				}
10360 				ipp->ipp_fields &= ~IPPF_RTHDR;
10361 			} else {
10362 				reterr = tcp_pkt_set(invalp, inlen,
10363 				    (uchar_t **)&ipp->ipp_rthdr,
10364 				    &ipp->ipp_rthdrlen);
10365 				if (reterr != 0)
10366 					return (reterr);
10367 				ipp->ipp_fields |= IPPF_RTHDR;
10368 			}
10369 			reterr = tcp_build_hdrs(q, tcp);
10370 			if (reterr != 0)
10371 				return (reterr);
10372 			break;
10373 		}
10374 		case IPV6_V6ONLY:
10375 			if (!checkonly)
10376 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10377 			break;
10378 		case IPV6_USE_MIN_MTU:
10379 			if (inlen != sizeof (int))
10380 				return (EINVAL);
10381 
10382 			if (*i1 < -1 || *i1 > 1)
10383 				return (EINVAL);
10384 
10385 			if (checkonly)
10386 				break;
10387 
10388 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10389 			ipp->ipp_use_min_mtu = *i1;
10390 			break;
10391 		case IPV6_BOUND_PIF:
10392 			/* Handled at the IP level */
10393 			return (-EINVAL);
10394 		case IPV6_SEC_OPT:
10395 			/*
10396 			 * We should not allow policy setting after
10397 			 * we start listening for connections.
10398 			 */
10399 			if (tcp->tcp_state == TCPS_LISTEN) {
10400 				return (EINVAL);
10401 			} else {
10402 				/* Handled at the IP level */
10403 				return (-EINVAL);
10404 			}
10405 		case IPV6_SRC_PREFERENCES:
10406 			if (inlen != sizeof (uint32_t))
10407 				return (EINVAL);
10408 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10409 			    *(uint32_t *)invalp);
10410 			if (reterr != 0) {
10411 				*outlenp = 0;
10412 				return (reterr);
10413 			}
10414 			break;
10415 		default:
10416 			*outlenp = 0;
10417 			return (EINVAL);
10418 		}
10419 		break;
10420 	}		/* end IPPROTO_IPV6 */
10421 	default:
10422 		*outlenp = 0;
10423 		return (EINVAL);
10424 	}
10425 	/*
10426 	 * Common case of OK return with outval same as inval
10427 	 */
10428 	if (invalp != outvalp) {
10429 		/* don't trust bcopy for identical src/dst */
10430 		(void) bcopy(invalp, outvalp, inlen);
10431 	}
10432 	*outlenp = inlen;
10433 	return (0);
10434 }
10435 
10436 /*
10437  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10438  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10439  * headers, and the maximum size tcp header (to avoid reallocation
10440  * on the fly for additional tcp options).
10441  * Returns failure if can't allocate memory.
10442  */
10443 static int
10444 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
10445 {
10446 	char	*hdrs;
10447 	uint_t	hdrs_len;
10448 	ip6i_t	*ip6i;
10449 	char	buf[TCP_MAX_HDR_LENGTH];
10450 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10451 	in6_addr_t src, dst;
10452 
10453 	/*
10454 	 * save the existing tcp header and source/dest IP addresses
10455 	 */
10456 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10457 	src = tcp->tcp_ip6h->ip6_src;
10458 	dst = tcp->tcp_ip6h->ip6_dst;
10459 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10460 	ASSERT(hdrs_len != 0);
10461 	if (hdrs_len > tcp->tcp_iphc_len) {
10462 		/* Need to reallocate */
10463 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10464 		if (hdrs == NULL)
10465 			return (ENOMEM);
10466 		if (tcp->tcp_iphc != NULL) {
10467 			if (tcp->tcp_hdr_grown) {
10468 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10469 			} else {
10470 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10471 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10472 			}
10473 			tcp->tcp_iphc_len = 0;
10474 		}
10475 		ASSERT(tcp->tcp_iphc_len == 0);
10476 		tcp->tcp_iphc = hdrs;
10477 		tcp->tcp_iphc_len = hdrs_len;
10478 		tcp->tcp_hdr_grown = B_TRUE;
10479 	}
10480 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10481 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10482 
10483 	/* Set header fields not in ipp */
10484 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10485 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10486 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10487 	} else {
10488 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10489 	}
10490 	/*
10491 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10492 	 *
10493 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10494 	 */
10495 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10496 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10497 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10498 
10499 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10500 
10501 	tcp->tcp_ip6h->ip6_src = src;
10502 	tcp->tcp_ip6h->ip6_dst = dst;
10503 
10504 	/*
10505 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10506 	 * the default value for TCP.
10507 	 */
10508 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10509 		tcp->tcp_ip6h->ip6_hops = tcp_ipv6_hoplimit;
10510 
10511 	/*
10512 	 * If we're setting extension headers after a connection
10513 	 * has been established, and if we have a routing header
10514 	 * among the extension headers, call ip_massage_options_v6 to
10515 	 * manipulate the routing header/ip6_dst set the checksum
10516 	 * difference in the tcp header template.
10517 	 * (This happens in tcp_connect_ipv6 if the routing header
10518 	 * is set prior to the connect.)
10519 	 * Set the tcp_sum to zero first in case we've cleared a
10520 	 * routing header or don't have one at all.
10521 	 */
10522 	tcp->tcp_sum = 0;
10523 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10524 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10525 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10526 		    (uint8_t *)tcp->tcp_tcph);
10527 		if (rth != NULL) {
10528 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10529 			    rth);
10530 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10531 			    (tcp->tcp_sum >> 16));
10532 		}
10533 	}
10534 
10535 	/* Try to get everything in a single mblk */
10536 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcp_wroff_xtra);
10537 	return (0);
10538 }
10539 
10540 /*
10541  * Set optbuf and optlen for the option.
10542  * Allocate memory (if not already present).
10543  * Otherwise just point optbuf and optlen at invalp and inlen.
10544  * Returns failure if memory can not be allocated.
10545  */
10546 static int
10547 tcp_pkt_set(uchar_t *invalp, uint_t inlen, uchar_t **optbufp, uint_t *optlenp)
10548 {
10549 	uchar_t *optbuf;
10550 
10551 	if (inlen == *optlenp) {
10552 		/* Unchanged length - no need to realocate */
10553 		bcopy(invalp, *optbufp, inlen);
10554 		return (0);
10555 	}
10556 	if (inlen != 0) {
10557 		/* Allocate new buffer before free */
10558 		optbuf = kmem_alloc(inlen, KM_NOSLEEP);
10559 		if (optbuf == NULL)
10560 			return (ENOMEM);
10561 	} else {
10562 		optbuf = NULL;
10563 	}
10564 	/* Free old buffer */
10565 	if (*optlenp != 0)
10566 		kmem_free(*optbufp, *optlenp);
10567 
10568 	bcopy(invalp, optbuf, inlen);
10569 	*optbufp = optbuf;
10570 	*optlenp = inlen;
10571 	return (0);
10572 }
10573 
10574 
10575 /*
10576  * Use the outgoing IP header to create an IP_OPTIONS option the way
10577  * it was passed down from the application.
10578  */
10579 static int
10580 tcp_opt_get_user(ipha_t *ipha, uchar_t *buf)
10581 {
10582 	ipoptp_t	opts;
10583 	uchar_t		*opt;
10584 	uint8_t		optval;
10585 	uint8_t		optlen;
10586 	uint32_t	len = 0;
10587 	uchar_t	*buf1 = buf;
10588 
10589 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
10590 	len += IP_ADDR_LEN;
10591 	bzero(buf1, IP_ADDR_LEN);
10592 
10593 	for (optval = ipoptp_first(&opts, ipha);
10594 	    optval != IPOPT_EOL;
10595 	    optval = ipoptp_next(&opts)) {
10596 		opt = opts.ipoptp_cur;
10597 		optlen = opts.ipoptp_len;
10598 		switch (optval) {
10599 			int	off;
10600 		case IPOPT_SSRR:
10601 		case IPOPT_LSRR:
10602 
10603 			/*
10604 			 * Insert ipha_dst as the first entry in the source
10605 			 * route and move down the entries on step.
10606 			 * The last entry gets placed at buf1.
10607 			 */
10608 			buf[IPOPT_OPTVAL] = optval;
10609 			buf[IPOPT_OLEN] = optlen;
10610 			buf[IPOPT_OFFSET] = optlen;
10611 
10612 			off = optlen - IP_ADDR_LEN;
10613 			if (off < 0) {
10614 				/* No entries in source route */
10615 				break;
10616 			}
10617 			/* Last entry in source route */
10618 			bcopy(opt + off, buf1, IP_ADDR_LEN);
10619 			off -= IP_ADDR_LEN;
10620 
10621 			while (off > 0) {
10622 				bcopy(opt + off,
10623 				    buf + off + IP_ADDR_LEN,
10624 				    IP_ADDR_LEN);
10625 				off -= IP_ADDR_LEN;
10626 			}
10627 			/* ipha_dst into first slot */
10628 			bcopy(&ipha->ipha_dst,
10629 			    buf + off + IP_ADDR_LEN,
10630 			    IP_ADDR_LEN);
10631 			buf += optlen;
10632 			len += optlen;
10633 			break;
10634 		default:
10635 			bcopy(opt, buf, optlen);
10636 			buf += optlen;
10637 			len += optlen;
10638 			break;
10639 		}
10640 	}
10641 done:
10642 	/* Pad the resulting options */
10643 	while (len & 0x3) {
10644 		*buf++ = IPOPT_EOL;
10645 		len++;
10646 	}
10647 	return (len);
10648 }
10649 
10650 /*
10651  * Transfer any source route option from ipha to buf/dst in reversed form.
10652  */
10653 static int
10654 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10655 {
10656 	ipoptp_t	opts;
10657 	uchar_t		*opt;
10658 	uint8_t		optval;
10659 	uint8_t		optlen;
10660 	uint32_t	len = 0;
10661 
10662 	for (optval = ipoptp_first(&opts, ipha);
10663 	    optval != IPOPT_EOL;
10664 	    optval = ipoptp_next(&opts)) {
10665 		opt = opts.ipoptp_cur;
10666 		optlen = opts.ipoptp_len;
10667 		switch (optval) {
10668 			int	off1, off2;
10669 		case IPOPT_SSRR:
10670 		case IPOPT_LSRR:
10671 
10672 			/* Reverse source route */
10673 			/*
10674 			 * First entry should be the next to last one in the
10675 			 * current source route (the last entry is our
10676 			 * address.)
10677 			 * The last entry should be the final destination.
10678 			 */
10679 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10680 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10681 			off1 = IPOPT_MINOFF_SR - 1;
10682 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10683 			if (off2 < 0) {
10684 				/* No entries in source route */
10685 				break;
10686 			}
10687 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10688 			/*
10689 			 * Note: use src since ipha has not had its src
10690 			 * and dst reversed (it is in the state it was
10691 			 * received.
10692 			 */
10693 			bcopy(&ipha->ipha_src, buf + off2,
10694 			    IP_ADDR_LEN);
10695 			off2 -= IP_ADDR_LEN;
10696 
10697 			while (off2 > 0) {
10698 				bcopy(opt + off2, buf + off1,
10699 				    IP_ADDR_LEN);
10700 				off1 += IP_ADDR_LEN;
10701 				off2 -= IP_ADDR_LEN;
10702 			}
10703 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10704 			buf += optlen;
10705 			len += optlen;
10706 			break;
10707 		}
10708 	}
10709 done:
10710 	/* Pad the resulting options */
10711 	while (len & 0x3) {
10712 		*buf++ = IPOPT_EOL;
10713 		len++;
10714 	}
10715 	return (len);
10716 }
10717 
10718 
10719 /*
10720  * Extract and revert a source route from ipha (if any)
10721  * and then update the relevant fields in both tcp_t and the standard header.
10722  */
10723 static void
10724 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
10725 {
10726 	char	buf[TCP_MAX_HDR_LENGTH];
10727 	uint_t	tcph_len;
10728 	int	len;
10729 
10730 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
10731 	len = IPH_HDR_LENGTH(ipha);
10732 	if (len == IP_SIMPLE_HDR_LENGTH)
10733 		/* Nothing to do */
10734 		return;
10735 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
10736 	    (len & 0x3))
10737 		return;
10738 
10739 	tcph_len = tcp->tcp_tcp_hdr_len;
10740 	bcopy(tcp->tcp_tcph, buf, tcph_len);
10741 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
10742 		(tcp->tcp_ipha->ipha_dst & 0xffff);
10743 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
10744 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
10745 	len += IP_SIMPLE_HDR_LENGTH;
10746 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
10747 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
10748 	if ((int)tcp->tcp_sum < 0)
10749 		tcp->tcp_sum--;
10750 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
10751 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
10752 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
10753 	bcopy(buf, tcp->tcp_tcph, tcph_len);
10754 	tcp->tcp_ip_hdr_len = len;
10755 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10756 	    (IP_VERSION << 4) | (len >> 2);
10757 	len += tcph_len;
10758 	tcp->tcp_hdr_len = len;
10759 }
10760 
10761 /*
10762  * Copy the standard header into its new location,
10763  * lay in the new options and then update the relevant
10764  * fields in both tcp_t and the standard header.
10765  */
10766 static int
10767 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
10768 {
10769 	uint_t	tcph_len;
10770 	char	*ip_optp;
10771 	tcph_t	*new_tcph;
10772 
10773 	if (checkonly) {
10774 		/*
10775 		 * do not really set, just pretend to - T_CHECK
10776 		 */
10777 		if (len != 0) {
10778 			/*
10779 			 * there is value supplied, validate it as if
10780 			 * for a real set operation.
10781 			 */
10782 			if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10783 				return (EINVAL);
10784 		}
10785 		return (0);
10786 	}
10787 
10788 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
10789 		return (EINVAL);
10790 
10791 	ip_optp = (char *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
10792 	tcph_len = tcp->tcp_tcp_hdr_len;
10793 	new_tcph = (tcph_t *)(ip_optp + len);
10794 	ovbcopy((char *)tcp->tcp_tcph, (char *)new_tcph, tcph_len);
10795 	tcp->tcp_tcph = new_tcph;
10796 	bcopy(ptr, ip_optp, len);
10797 
10798 	len += IP_SIMPLE_HDR_LENGTH;
10799 
10800 	tcp->tcp_ip_hdr_len = len;
10801 	tcp->tcp_ipha->ipha_version_and_hdr_length =
10802 		(IP_VERSION << 4) | (len >> 2);
10803 	len += tcph_len;
10804 	tcp->tcp_hdr_len = len;
10805 	if (!TCP_IS_DETACHED(tcp)) {
10806 		/* Always allocate room for all options. */
10807 		(void) mi_set_sth_wroff(tcp->tcp_rq,
10808 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcp_wroff_xtra);
10809 	}
10810 	return (0);
10811 }
10812 
10813 /* Get callback routine passed to nd_load by tcp_param_register */
10814 /* ARGSUSED */
10815 static int
10816 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
10817 {
10818 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10819 
10820 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
10821 	return (0);
10822 }
10823 
10824 /*
10825  * Walk through the param array specified registering each element with the
10826  * named dispatch handler.
10827  */
10828 static boolean_t
10829 tcp_param_register(tcpparam_t *tcppa, int cnt)
10830 {
10831 	for (; cnt-- > 0; tcppa++) {
10832 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
10833 			if (!nd_load(&tcp_g_nd, tcppa->tcp_param_name,
10834 			    tcp_param_get, tcp_param_set,
10835 			    (caddr_t)tcppa)) {
10836 				nd_free(&tcp_g_nd);
10837 				return (B_FALSE);
10838 			}
10839 		}
10840 	}
10841 	if (!nd_load(&tcp_g_nd, tcp_wroff_xtra_param.tcp_param_name,
10842 	    tcp_param_get, tcp_param_set_aligned,
10843 	    (caddr_t)&tcp_wroff_xtra_param)) {
10844 		nd_free(&tcp_g_nd);
10845 		return (B_FALSE);
10846 	}
10847 	if (!nd_load(&tcp_g_nd, tcp_mdt_head_param.tcp_param_name,
10848 	    tcp_param_get, tcp_param_set_aligned,
10849 	    (caddr_t)&tcp_mdt_head_param)) {
10850 		nd_free(&tcp_g_nd);
10851 		return (B_FALSE);
10852 	}
10853 	if (!nd_load(&tcp_g_nd, tcp_mdt_tail_param.tcp_param_name,
10854 	    tcp_param_get, tcp_param_set_aligned,
10855 	    (caddr_t)&tcp_mdt_tail_param)) {
10856 		nd_free(&tcp_g_nd);
10857 		return (B_FALSE);
10858 	}
10859 	if (!nd_load(&tcp_g_nd, tcp_mdt_max_pbufs_param.tcp_param_name,
10860 	    tcp_param_get, tcp_param_set,
10861 	    (caddr_t)&tcp_mdt_max_pbufs_param)) {
10862 		nd_free(&tcp_g_nd);
10863 		return (B_FALSE);
10864 	}
10865 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports",
10866 	    tcp_extra_priv_ports_get, NULL, NULL)) {
10867 		nd_free(&tcp_g_nd);
10868 		return (B_FALSE);
10869 	}
10870 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_add",
10871 	    NULL, tcp_extra_priv_ports_add, NULL)) {
10872 		nd_free(&tcp_g_nd);
10873 		return (B_FALSE);
10874 	}
10875 	if (!nd_load(&tcp_g_nd, "tcp_extra_priv_ports_del",
10876 	    NULL, tcp_extra_priv_ports_del, NULL)) {
10877 		nd_free(&tcp_g_nd);
10878 		return (B_FALSE);
10879 	}
10880 	if (!nd_load(&tcp_g_nd, "tcp_status", tcp_status_report, NULL,
10881 	    NULL)) {
10882 		nd_free(&tcp_g_nd);
10883 		return (B_FALSE);
10884 	}
10885 	if (!nd_load(&tcp_g_nd, "tcp_bind_hash", tcp_bind_hash_report,
10886 	    NULL, NULL)) {
10887 		nd_free(&tcp_g_nd);
10888 		return (B_FALSE);
10889 	}
10890 	if (!nd_load(&tcp_g_nd, "tcp_listen_hash", tcp_listen_hash_report,
10891 	    NULL, NULL)) {
10892 		nd_free(&tcp_g_nd);
10893 		return (B_FALSE);
10894 	}
10895 	if (!nd_load(&tcp_g_nd, "tcp_conn_hash", tcp_conn_hash_report,
10896 	    NULL, NULL)) {
10897 		nd_free(&tcp_g_nd);
10898 		return (B_FALSE);
10899 	}
10900 	if (!nd_load(&tcp_g_nd, "tcp_acceptor_hash", tcp_acceptor_hash_report,
10901 	    NULL, NULL)) {
10902 		nd_free(&tcp_g_nd);
10903 		return (B_FALSE);
10904 	}
10905 	if (!nd_load(&tcp_g_nd, "tcp_host_param", tcp_host_param_report,
10906 	    tcp_host_param_set, NULL)) {
10907 		nd_free(&tcp_g_nd);
10908 		return (B_FALSE);
10909 	}
10910 	if (!nd_load(&tcp_g_nd, "tcp_host_param_ipv6", tcp_host_param_report,
10911 	    tcp_host_param_set_ipv6, NULL)) {
10912 		nd_free(&tcp_g_nd);
10913 		return (B_FALSE);
10914 	}
10915 	if (!nd_load(&tcp_g_nd, "tcp_1948_phrase", NULL, tcp_1948_phrase_set,
10916 	    NULL)) {
10917 		nd_free(&tcp_g_nd);
10918 		return (B_FALSE);
10919 	}
10920 	if (!nd_load(&tcp_g_nd, "tcp_reserved_port_list",
10921 	    tcp_reserved_port_list, NULL, NULL)) {
10922 		nd_free(&tcp_g_nd);
10923 		return (B_FALSE);
10924 	}
10925 	/*
10926 	 * Dummy ndd variables - only to convey obsolescence information
10927 	 * through printing of their name (no get or set routines)
10928 	 * XXX Remove in future releases ?
10929 	 */
10930 	if (!nd_load(&tcp_g_nd,
10931 	    "tcp_close_wait_interval(obsoleted - "
10932 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
10933 		nd_free(&tcp_g_nd);
10934 		return (B_FALSE);
10935 	}
10936 	return (B_TRUE);
10937 }
10938 
10939 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
10940 /* ARGSUSED */
10941 static int
10942 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
10943     cred_t *cr)
10944 {
10945 	long new_value;
10946 	tcpparam_t *tcppa = (tcpparam_t *)cp;
10947 
10948 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10949 	    new_value < tcppa->tcp_param_min ||
10950 	    new_value > tcppa->tcp_param_max) {
10951 		return (EINVAL);
10952 	}
10953 	/*
10954 	 * Need to make sure new_value is a multiple of 4.  If it is not,
10955 	 * round it up.  For future 64 bit requirement, we actually make it
10956 	 * a multiple of 8.
10957 	 */
10958 	if (new_value & 0x7) {
10959 		new_value = (new_value & ~0x7) + 0x8;
10960 	}
10961 	tcppa->tcp_param_val = new_value;
10962 	return (0);
10963 }
10964 
10965 /* Set callback routine passed to nd_load by tcp_param_register */
10966 /* ARGSUSED */
10967 static int
10968 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
10969 {
10970 	long	new_value;
10971 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
10972 
10973 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10974 	    new_value < tcppa->tcp_param_min ||
10975 	    new_value > tcppa->tcp_param_max) {
10976 		return (EINVAL);
10977 	}
10978 	tcppa->tcp_param_val = new_value;
10979 	return (0);
10980 }
10981 
10982 /*
10983  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
10984  * is filled, return as much as we can.  The message passed in may be
10985  * multi-part, chained using b_cont.  "start" is the starting sequence
10986  * number for this piece.
10987  */
10988 static mblk_t *
10989 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
10990 {
10991 	uint32_t	end;
10992 	mblk_t		*mp1;
10993 	mblk_t		*mp2;
10994 	mblk_t		*next_mp;
10995 	uint32_t	u1;
10996 
10997 	/* Walk through all the new pieces. */
10998 	do {
10999 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11000 		    (uintptr_t)INT_MAX);
11001 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11002 		next_mp = mp->b_cont;
11003 		if (start == end) {
11004 			/* Empty.  Blast it. */
11005 			freeb(mp);
11006 			continue;
11007 		}
11008 		mp->b_cont = NULL;
11009 		TCP_REASS_SET_SEQ(mp, start);
11010 		TCP_REASS_SET_END(mp, end);
11011 		mp1 = tcp->tcp_reass_tail;
11012 		if (!mp1) {
11013 			tcp->tcp_reass_tail = mp;
11014 			tcp->tcp_reass_head = mp;
11015 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11016 			UPDATE_MIB(&tcp_mib,
11017 			    tcpInDataUnorderBytes, end - start);
11018 			continue;
11019 		}
11020 		/* New stuff completely beyond tail? */
11021 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11022 			/* Link it on end. */
11023 			mp1->b_cont = mp;
11024 			tcp->tcp_reass_tail = mp;
11025 			BUMP_MIB(&tcp_mib, tcpInDataUnorderSegs);
11026 			UPDATE_MIB(&tcp_mib,
11027 			    tcpInDataUnorderBytes, end - start);
11028 			continue;
11029 		}
11030 		mp1 = tcp->tcp_reass_head;
11031 		u1 = TCP_REASS_SEQ(mp1);
11032 		/* New stuff at the front? */
11033 		if (SEQ_LT(start, u1)) {
11034 			/* Yes... Check for overlap. */
11035 			mp->b_cont = mp1;
11036 			tcp->tcp_reass_head = mp;
11037 			tcp_reass_elim_overlap(tcp, mp);
11038 			continue;
11039 		}
11040 		/*
11041 		 * The new piece fits somewhere between the head and tail.
11042 		 * We find our slot, where mp1 precedes us and mp2 trails.
11043 		 */
11044 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11045 			u1 = TCP_REASS_SEQ(mp2);
11046 			if (SEQ_LEQ(start, u1))
11047 				break;
11048 		}
11049 		/* Link ourselves in */
11050 		mp->b_cont = mp2;
11051 		mp1->b_cont = mp;
11052 
11053 		/* Trim overlap with following mblk(s) first */
11054 		tcp_reass_elim_overlap(tcp, mp);
11055 
11056 		/* Trim overlap with preceding mblk */
11057 		tcp_reass_elim_overlap(tcp, mp1);
11058 
11059 	} while (start = end, mp = next_mp);
11060 	mp1 = tcp->tcp_reass_head;
11061 	/* Anything ready to go? */
11062 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11063 		return (NULL);
11064 	/* Eat what we can off the queue */
11065 	for (;;) {
11066 		mp = mp1->b_cont;
11067 		end = TCP_REASS_END(mp1);
11068 		TCP_REASS_SET_SEQ(mp1, 0);
11069 		TCP_REASS_SET_END(mp1, 0);
11070 		if (!mp) {
11071 			tcp->tcp_reass_tail = NULL;
11072 			break;
11073 		}
11074 		if (end != TCP_REASS_SEQ(mp)) {
11075 			mp1->b_cont = NULL;
11076 			break;
11077 		}
11078 		mp1 = mp;
11079 	}
11080 	mp1 = tcp->tcp_reass_head;
11081 	tcp->tcp_reass_head = mp;
11082 	return (mp1);
11083 }
11084 
11085 /* Eliminate any overlap that mp may have over later mblks */
11086 static void
11087 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11088 {
11089 	uint32_t	end;
11090 	mblk_t		*mp1;
11091 	uint32_t	u1;
11092 
11093 	end = TCP_REASS_END(mp);
11094 	while ((mp1 = mp->b_cont) != NULL) {
11095 		u1 = TCP_REASS_SEQ(mp1);
11096 		if (!SEQ_GT(end, u1))
11097 			break;
11098 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11099 			mp->b_wptr -= end - u1;
11100 			TCP_REASS_SET_END(mp, u1);
11101 			BUMP_MIB(&tcp_mib, tcpInDataPartDupSegs);
11102 			UPDATE_MIB(&tcp_mib, tcpInDataPartDupBytes, end - u1);
11103 			break;
11104 		}
11105 		mp->b_cont = mp1->b_cont;
11106 		TCP_REASS_SET_SEQ(mp1, 0);
11107 		TCP_REASS_SET_END(mp1, 0);
11108 		freeb(mp1);
11109 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
11110 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes, end - u1);
11111 	}
11112 	if (!mp1)
11113 		tcp->tcp_reass_tail = mp;
11114 }
11115 
11116 /*
11117  * Send up all messages queued on tcp_rcv_list.
11118  */
11119 static uint_t
11120 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11121 {
11122 	mblk_t *mp;
11123 	uint_t ret = 0;
11124 	uint_t thwin;
11125 #ifdef DEBUG
11126 	uint_t cnt = 0;
11127 #endif
11128 	/* Can't drain on an eager connection */
11129 	if (tcp->tcp_listener != NULL)
11130 		return (ret);
11131 
11132 	/*
11133 	 * Handle two cases here: we are currently fused or we were
11134 	 * previously fused and have some urgent data to be delivered
11135 	 * upstream.  The latter happens because we either ran out of
11136 	 * memory or were detached and therefore sending the SIGURG was
11137 	 * deferred until this point.  In either case we pass control
11138 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11139 	 * some work.
11140 	 */
11141 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11142 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11143 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11144 		    &tcp->tcp_fused_sigurg_mp))
11145 			return (ret);
11146 	}
11147 
11148 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11149 		tcp->tcp_rcv_list = mp->b_next;
11150 		mp->b_next = NULL;
11151 #ifdef DEBUG
11152 		cnt += msgdsize(mp);
11153 #endif
11154 		/* Does this need SSL processing first? */
11155 		if ((tcp->tcp_kssl_ctx  != NULL) && (DB_TYPE(mp) == M_DATA)) {
11156 			tcp_kssl_input(tcp, mp);
11157 			continue;
11158 		}
11159 		putnext(q, mp);
11160 	}
11161 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11162 	tcp->tcp_rcv_last_head = NULL;
11163 	tcp->tcp_rcv_last_tail = NULL;
11164 	tcp->tcp_rcv_cnt = 0;
11165 
11166 	/* Learn the latest rwnd information that we sent to the other side. */
11167 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11168 	    << tcp->tcp_rcv_ws;
11169 	/* This is peer's calculated send window (our receive window). */
11170 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11171 	/*
11172 	 * Increase the receive window to max.  But we need to do receiver
11173 	 * SWS avoidance.  This means that we need to check the increase of
11174 	 * of receive window is at least 1 MSS.
11175 	 */
11176 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11177 		/*
11178 		 * If the window that the other side knows is less than max
11179 		 * deferred acks segments, send an update immediately.
11180 		 */
11181 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11182 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
11183 			ret = TH_ACK_NEEDED;
11184 		}
11185 		tcp->tcp_rwnd = q->q_hiwat;
11186 	}
11187 	/* No need for the push timer now. */
11188 	if (tcp->tcp_push_tid != 0) {
11189 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11190 		tcp->tcp_push_tid = 0;
11191 	}
11192 	return (ret);
11193 }
11194 
11195 /*
11196  * Queue data on tcp_rcv_list which is a b_next chain.
11197  * tcp_rcv_last_head/tail is the last element of this chain.
11198  * Each element of the chain is a b_cont chain.
11199  *
11200  * M_DATA messages are added to the current element.
11201  * Other messages are added as new (b_next) elements.
11202  */
11203 void
11204 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11205 {
11206 	ASSERT(seg_len == msgdsize(mp));
11207 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11208 
11209 	if (tcp->tcp_rcv_list == NULL) {
11210 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11211 		tcp->tcp_rcv_list = mp;
11212 		tcp->tcp_rcv_last_head = mp;
11213 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11214 		tcp->tcp_rcv_last_tail->b_cont = mp;
11215 	} else {
11216 		tcp->tcp_rcv_last_head->b_next = mp;
11217 		tcp->tcp_rcv_last_head = mp;
11218 	}
11219 
11220 	while (mp->b_cont)
11221 		mp = mp->b_cont;
11222 
11223 	tcp->tcp_rcv_last_tail = mp;
11224 	tcp->tcp_rcv_cnt += seg_len;
11225 	tcp->tcp_rwnd -= seg_len;
11226 }
11227 
11228 /*
11229  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11230  *
11231  * This is the default entry function into TCP on the read side. TCP is
11232  * always entered via squeue i.e. using squeue's for mutual exclusion.
11233  * When classifier does a lookup to find the tcp, it also puts a reference
11234  * on the conn structure associated so the tcp is guaranteed to exist
11235  * when we come here. We still need to check the state because it might
11236  * as well has been closed. The squeue processing function i.e. squeue_enter,
11237  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
11238  * CONN_DEC_REF.
11239  *
11240  * Apart from the default entry point, IP also sends packets directly to
11241  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11242  * connections.
11243  */
11244 void
11245 tcp_input(void *arg, mblk_t *mp, void *arg2)
11246 {
11247 	conn_t	*connp = (conn_t *)arg;
11248 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11249 
11250 	/* arg2 is the sqp */
11251 	ASSERT(arg2 != NULL);
11252 	ASSERT(mp != NULL);
11253 
11254 	/*
11255 	 * Don't accept any input on a closed tcp as this TCP logically does
11256 	 * not exist on the system. Don't proceed further with this TCP.
11257 	 * For eg. this packet could trigger another close of this tcp
11258 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11259 	 * tcp_clean_death / tcp_closei_local must be called at most once
11260 	 * on a TCP. In this case we need to refeed the packet into the
11261 	 * classifier and figure out where the packet should go. Need to
11262 	 * preserve the recv_ill somehow. Until we figure that out, for
11263 	 * now just drop the packet if we can't classify the packet.
11264 	 */
11265 	if (tcp->tcp_state == TCPS_CLOSED ||
11266 	    tcp->tcp_state == TCPS_BOUND) {
11267 		conn_t	*new_connp;
11268 
11269 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
11270 		if (new_connp != NULL) {
11271 			tcp_reinput(new_connp, mp, arg2);
11272 			return;
11273 		}
11274 		/* We failed to classify. For now just drop the packet */
11275 		freemsg(mp);
11276 		return;
11277 	}
11278 
11279 	if (DB_TYPE(mp) == M_DATA)
11280 		tcp_rput_data(connp, mp, arg2);
11281 	else
11282 		tcp_rput_common(tcp, mp);
11283 }
11284 
11285 /*
11286  * The read side put procedure.
11287  * The packets passed up by ip are assume to be aligned according to
11288  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11289  */
11290 static void
11291 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11292 {
11293 	/*
11294 	 * tcp_rput_data() does not expect M_CTL except for the case
11295 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11296 	 * type. Need to make sure that any other M_CTLs don't make
11297 	 * it to tcp_rput_data since it is not expecting any and doesn't
11298 	 * check for it.
11299 	 */
11300 	if (DB_TYPE(mp) == M_CTL) {
11301 		switch (*(uint32_t *)(mp->b_rptr)) {
11302 		case TCP_IOC_ABORT_CONN:
11303 			/*
11304 			 * Handle connection abort request.
11305 			 */
11306 			tcp_ioctl_abort_handler(tcp, mp);
11307 			return;
11308 		case IPSEC_IN:
11309 			/*
11310 			 * Only secure icmp arrive in TCP and they
11311 			 * don't go through data path.
11312 			 */
11313 			tcp_icmp_error(tcp, mp);
11314 			return;
11315 		case IN_PKTINFO:
11316 			/*
11317 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11318 			 * sockets that are receiving IPv4 traffic. tcp
11319 			 */
11320 			ASSERT(tcp->tcp_family == AF_INET6);
11321 			ASSERT(tcp->tcp_ipv6_recvancillary &
11322 			    TCP_IPV6_RECVPKTINFO);
11323 			tcp_rput_data(tcp->tcp_connp, mp,
11324 			    tcp->tcp_connp->conn_sqp);
11325 			return;
11326 		case MDT_IOC_INFO_UPDATE:
11327 			/*
11328 			 * Handle Multidata information update; the
11329 			 * following routine will free the message.
11330 			 */
11331 			if (tcp->tcp_connp->conn_mdt_ok) {
11332 				tcp_mdt_update(tcp,
11333 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11334 				    B_FALSE);
11335 			}
11336 			freemsg(mp);
11337 			return;
11338 		default:
11339 			break;
11340 		}
11341 	}
11342 
11343 	/* No point processing the message if tcp is already closed */
11344 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11345 		freemsg(mp);
11346 		return;
11347 	}
11348 
11349 	tcp_rput_other(tcp, mp);
11350 }
11351 
11352 
11353 /* The minimum of smoothed mean deviation in RTO calculation. */
11354 #define	TCP_SD_MIN	400
11355 
11356 /*
11357  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11358  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11359  * are the same as those in Appendix A.2 of that paper.
11360  *
11361  * m = new measurement
11362  * sa = smoothed RTT average (8 * average estimates).
11363  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11364  */
11365 static void
11366 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11367 {
11368 	long m = TICK_TO_MSEC(rtt);
11369 	clock_t sa = tcp->tcp_rtt_sa;
11370 	clock_t sv = tcp->tcp_rtt_sd;
11371 	clock_t rto;
11372 
11373 	BUMP_MIB(&tcp_mib, tcpRttUpdate);
11374 	tcp->tcp_rtt_update++;
11375 
11376 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11377 	if (sa != 0) {
11378 		/*
11379 		 * Update average estimator:
11380 		 *	new rtt = 7/8 old rtt + 1/8 Error
11381 		 */
11382 
11383 		/* m is now Error in estimate. */
11384 		m -= sa >> 3;
11385 		if ((sa += m) <= 0) {
11386 			/*
11387 			 * Don't allow the smoothed average to be negative.
11388 			 * We use 0 to denote reinitialization of the
11389 			 * variables.
11390 			 */
11391 			sa = 1;
11392 		}
11393 
11394 		/*
11395 		 * Update deviation estimator:
11396 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11397 		 */
11398 		if (m < 0)
11399 			m = -m;
11400 		m -= sv >> 2;
11401 		sv += m;
11402 	} else {
11403 		/*
11404 		 * This follows BSD's implementation.  So the reinitialized
11405 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11406 		 * link is bandwidth dominated, doubling the window size
11407 		 * during slow start means doubling the RTT.  We want to be
11408 		 * more conservative when we reinitialize our estimates.  3
11409 		 * is just a convenient number.
11410 		 */
11411 		sa = m << 3;
11412 		sv = m << 1;
11413 	}
11414 	if (sv < TCP_SD_MIN) {
11415 		/*
11416 		 * We do not know that if sa captures the delay ACK
11417 		 * effect as in a long train of segments, a receiver
11418 		 * does not delay its ACKs.  So set the minimum of sv
11419 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11420 		 * of BSD DATO.  That means the minimum of mean
11421 		 * deviation is 100 ms.
11422 		 *
11423 		 */
11424 		sv = TCP_SD_MIN;
11425 	}
11426 	tcp->tcp_rtt_sa = sa;
11427 	tcp->tcp_rtt_sd = sv;
11428 	/*
11429 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
11430 	 *
11431 	 * Add tcp_rexmit_interval extra in case of extreme environment
11432 	 * where the algorithm fails to work.  The default value of
11433 	 * tcp_rexmit_interval_extra should be 0.
11434 	 *
11435 	 * As we use a finer grained clock than BSD and update
11436 	 * RTO for every ACKs, add in another .25 of RTT to the
11437 	 * deviation of RTO to accomodate burstiness of 1/4 of
11438 	 * window size.
11439 	 */
11440 	rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5);
11441 
11442 	if (rto > tcp_rexmit_interval_max) {
11443 		tcp->tcp_rto = tcp_rexmit_interval_max;
11444 	} else if (rto < tcp_rexmit_interval_min) {
11445 		tcp->tcp_rto = tcp_rexmit_interval_min;
11446 	} else {
11447 		tcp->tcp_rto = rto;
11448 	}
11449 
11450 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
11451 	tcp->tcp_timer_backoff = 0;
11452 }
11453 
11454 /*
11455  * tcp_get_seg_mp() is called to get the pointer to a segment in the
11456  * send queue which starts at the given seq. no.
11457  *
11458  * Parameters:
11459  *	tcp_t *tcp: the tcp instance pointer.
11460  *	uint32_t seq: the starting seq. no of the requested segment.
11461  *	int32_t *off: after the execution, *off will be the offset to
11462  *		the returned mblk which points to the requested seq no.
11463  *		It is the caller's responsibility to send in a non-null off.
11464  *
11465  * Return:
11466  *	A mblk_t pointer pointing to the requested segment in send queue.
11467  */
11468 static mblk_t *
11469 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
11470 {
11471 	int32_t	cnt;
11472 	mblk_t	*mp;
11473 
11474 	/* Defensive coding.  Make sure we don't send incorrect data. */
11475 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
11476 		return (NULL);
11477 
11478 	cnt = seq - tcp->tcp_suna;
11479 	mp = tcp->tcp_xmit_head;
11480 	while (cnt > 0 && mp != NULL) {
11481 		cnt -= mp->b_wptr - mp->b_rptr;
11482 		if (cnt < 0) {
11483 			cnt += mp->b_wptr - mp->b_rptr;
11484 			break;
11485 		}
11486 		mp = mp->b_cont;
11487 	}
11488 	ASSERT(mp != NULL);
11489 	*off = cnt;
11490 	return (mp);
11491 }
11492 
11493 /*
11494  * This function handles all retransmissions if SACK is enabled for this
11495  * connection.  First it calculates how many segments can be retransmitted
11496  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
11497  * segments.  A segment is eligible if sack_cnt for that segment is greater
11498  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
11499  * all eligible segments, it checks to see if TCP can send some new segments
11500  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
11501  *
11502  * Parameters:
11503  *	tcp_t *tcp: the tcp structure of the connection.
11504  *	uint_t *flags: in return, appropriate value will be set for
11505  *	tcp_rput_data().
11506  */
11507 static void
11508 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
11509 {
11510 	notsack_blk_t	*notsack_blk;
11511 	int32_t		usable_swnd;
11512 	int32_t		mss;
11513 	uint32_t	seg_len;
11514 	mblk_t		*xmit_mp;
11515 
11516 	ASSERT(tcp->tcp_sack_info != NULL);
11517 	ASSERT(tcp->tcp_notsack_list != NULL);
11518 	ASSERT(tcp->tcp_rexmit == B_FALSE);
11519 
11520 	/* Defensive coding in case there is a bug... */
11521 	if (tcp->tcp_notsack_list == NULL) {
11522 		return;
11523 	}
11524 	notsack_blk = tcp->tcp_notsack_list;
11525 	mss = tcp->tcp_mss;
11526 
11527 	/*
11528 	 * Limit the num of outstanding data in the network to be
11529 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
11530 	 */
11531 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11532 
11533 	/* At least retransmit 1 MSS of data. */
11534 	if (usable_swnd <= 0) {
11535 		usable_swnd = mss;
11536 	}
11537 
11538 	/* Make sure no new RTT samples will be taken. */
11539 	tcp->tcp_csuna = tcp->tcp_snxt;
11540 
11541 	notsack_blk = tcp->tcp_notsack_list;
11542 	while (usable_swnd > 0) {
11543 		mblk_t		*snxt_mp, *tmp_mp;
11544 		tcp_seq		begin = tcp->tcp_sack_snxt;
11545 		tcp_seq		end;
11546 		int32_t		off;
11547 
11548 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
11549 			if (SEQ_GT(notsack_blk->end, begin) &&
11550 			    (notsack_blk->sack_cnt >=
11551 			    tcp_dupack_fast_retransmit)) {
11552 				end = notsack_blk->end;
11553 				if (SEQ_LT(begin, notsack_blk->begin)) {
11554 					begin = notsack_blk->begin;
11555 				}
11556 				break;
11557 			}
11558 		}
11559 		/*
11560 		 * All holes are filled.  Manipulate tcp_cwnd to send more
11561 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
11562 		 * set to tcp_cwnd_ssthresh.
11563 		 */
11564 		if (notsack_blk == NULL) {
11565 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
11566 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
11567 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
11568 				ASSERT(tcp->tcp_cwnd > 0);
11569 				return;
11570 			} else {
11571 				usable_swnd = usable_swnd / mss;
11572 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
11573 				    MAX(usable_swnd * mss, mss);
11574 				*flags |= TH_XMIT_NEEDED;
11575 				return;
11576 			}
11577 		}
11578 
11579 		/*
11580 		 * Note that we may send more than usable_swnd allows here
11581 		 * because of round off, but no more than 1 MSS of data.
11582 		 */
11583 		seg_len = end - begin;
11584 		if (seg_len > mss)
11585 			seg_len = mss;
11586 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
11587 		ASSERT(snxt_mp != NULL);
11588 		/* This should not happen.  Defensive coding again... */
11589 		if (snxt_mp == NULL) {
11590 			return;
11591 		}
11592 
11593 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
11594 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
11595 		if (xmit_mp == NULL)
11596 			return;
11597 
11598 		usable_swnd -= seg_len;
11599 		tcp->tcp_pipe += seg_len;
11600 		tcp->tcp_sack_snxt = begin + seg_len;
11601 		TCP_RECORD_TRACE(tcp, xmit_mp, TCP_TRACE_SEND_PKT);
11602 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11603 
11604 		/*
11605 		 * Update the send timestamp to avoid false retransmission.
11606 		 */
11607 		snxt_mp->b_prev = (mblk_t *)lbolt;
11608 
11609 		BUMP_MIB(&tcp_mib, tcpRetransSegs);
11610 		UPDATE_MIB(&tcp_mib, tcpRetransBytes, seg_len);
11611 		BUMP_MIB(&tcp_mib, tcpOutSackRetransSegs);
11612 		/*
11613 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
11614 		 * This happens when new data sent during fast recovery is
11615 		 * also lost.  If TCP retransmits those new data, it needs
11616 		 * to extend SACK recover phase to avoid starting another
11617 		 * fast retransmit/recovery unnecessarily.
11618 		 */
11619 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
11620 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
11621 		}
11622 	}
11623 }
11624 
11625 /*
11626  * This function handles policy checking at TCP level for non-hard_bound/
11627  * detached connections.
11628  */
11629 static boolean_t
11630 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
11631     boolean_t secure, boolean_t mctl_present)
11632 {
11633 	ipsec_latch_t *ipl = NULL;
11634 	ipsec_action_t *act = NULL;
11635 	mblk_t *data_mp;
11636 	ipsec_in_t *ii;
11637 	const char *reason;
11638 	kstat_named_t *counter;
11639 
11640 	ASSERT(mctl_present || !secure);
11641 
11642 	ASSERT((ipha == NULL && ip6h != NULL) ||
11643 	    (ip6h == NULL && ipha != NULL));
11644 
11645 	/*
11646 	 * We don't necessarily have an ipsec_in_act action to verify
11647 	 * policy because of assymetrical policy where we have only
11648 	 * outbound policy and no inbound policy (possible with global
11649 	 * policy).
11650 	 */
11651 	if (!secure) {
11652 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
11653 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
11654 			return (B_TRUE);
11655 		ipsec_log_policy_failure(tcp->tcp_wq, IPSEC_POLICY_MISMATCH,
11656 		    "tcp_check_policy", ipha, ip6h, secure);
11657 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11658 		    &ipdrops_tcp_clear, &tcp_dropper);
11659 		return (B_FALSE);
11660 	}
11661 
11662 	/*
11663 	 * We have a secure packet.
11664 	 */
11665 	if (act == NULL) {
11666 		ipsec_log_policy_failure(tcp->tcp_wq,
11667 		    IPSEC_POLICY_NOT_NEEDED, "tcp_check_policy", ipha, ip6h,
11668 		    secure);
11669 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
11670 		    &ipdrops_tcp_secure, &tcp_dropper);
11671 		return (B_FALSE);
11672 	}
11673 
11674 	/*
11675 	 * XXX This whole routine is currently incorrect.  ipl should
11676 	 * be set to the latch pointer, but is currently not set, so
11677 	 * we initialize it to NULL to avoid picking up random garbage.
11678 	 */
11679 	if (ipl == NULL)
11680 		return (B_TRUE);
11681 
11682 	data_mp = first_mp->b_cont;
11683 
11684 	ii = (ipsec_in_t *)first_mp->b_rptr;
11685 
11686 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
11687 	    &counter)) {
11688 		BUMP_MIB(&ip_mib, ipsecInSucceeded);
11689 		return (B_TRUE);
11690 	}
11691 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
11692 	    "tcp inbound policy mismatch: %s, packet dropped\n",
11693 	    reason);
11694 	BUMP_MIB(&ip_mib, ipsecInFailed);
11695 
11696 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter, &tcp_dropper);
11697 	return (B_FALSE);
11698 }
11699 
11700 /*
11701  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
11702  * retransmission after a timeout.
11703  *
11704  * To limit the number of duplicate segments, we limit the number of segment
11705  * to be sent in one time to tcp_snd_burst, the burst variable.
11706  */
11707 static void
11708 tcp_ss_rexmit(tcp_t *tcp)
11709 {
11710 	uint32_t	snxt;
11711 	uint32_t	smax;
11712 	int32_t		win;
11713 	int32_t		mss;
11714 	int32_t		off;
11715 	int32_t		burst = tcp->tcp_snd_burst;
11716 	mblk_t		*snxt_mp;
11717 
11718 	/*
11719 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
11720 	 * all unack'ed segments.
11721 	 */
11722 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
11723 		smax = tcp->tcp_rexmit_max;
11724 		snxt = tcp->tcp_rexmit_nxt;
11725 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
11726 			snxt = tcp->tcp_suna;
11727 		}
11728 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
11729 		win -= snxt - tcp->tcp_suna;
11730 		mss = tcp->tcp_mss;
11731 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
11732 
11733 		while (SEQ_LT(snxt, smax) && (win > 0) &&
11734 		    (burst > 0) && (snxt_mp != NULL)) {
11735 			mblk_t	*xmit_mp;
11736 			mblk_t	*old_snxt_mp = snxt_mp;
11737 			uint32_t cnt = mss;
11738 
11739 			if (win < cnt) {
11740 				cnt = win;
11741 			}
11742 			if (SEQ_GT(snxt + cnt, smax)) {
11743 				cnt = smax - snxt;
11744 			}
11745 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
11746 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
11747 			if (xmit_mp == NULL)
11748 				return;
11749 
11750 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
11751 
11752 			snxt += cnt;
11753 			win -= cnt;
11754 			/*
11755 			 * Update the send timestamp to avoid false
11756 			 * retransmission.
11757 			 */
11758 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
11759 			BUMP_MIB(&tcp_mib, tcpRetransSegs);
11760 			UPDATE_MIB(&tcp_mib, tcpRetransBytes, cnt);
11761 
11762 			tcp->tcp_rexmit_nxt = snxt;
11763 			burst--;
11764 		}
11765 		/*
11766 		 * If we have transmitted all we have at the time
11767 		 * we started the retranmission, we can leave
11768 		 * the rest of the job to tcp_wput_data().  But we
11769 		 * need to check the send window first.  If the
11770 		 * win is not 0, go on with tcp_wput_data().
11771 		 */
11772 		if (SEQ_LT(snxt, smax) || win == 0) {
11773 			return;
11774 		}
11775 	}
11776 	/* Only call tcp_wput_data() if there is data to be sent. */
11777 	if (tcp->tcp_unsent) {
11778 		tcp_wput_data(tcp, NULL, B_FALSE);
11779 	}
11780 }
11781 
11782 /*
11783  * Process all TCP option in SYN segment.  Note that this function should
11784  * be called after tcp_adapt_ire() is called so that the necessary info
11785  * from IRE is already set in the tcp structure.
11786  *
11787  * This function sets up the correct tcp_mss value according to the
11788  * MSS option value and our header size.  It also sets up the window scale
11789  * and timestamp values, and initialize SACK info blocks.  But it does not
11790  * change receive window size after setting the tcp_mss value.  The caller
11791  * should do the appropriate change.
11792  */
11793 void
11794 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
11795 {
11796 	int options;
11797 	tcp_opt_t tcpopt;
11798 	uint32_t mss_max;
11799 	char *tmp_tcph;
11800 
11801 	tcpopt.tcp = NULL;
11802 	options = tcp_parse_options(tcph, &tcpopt);
11803 
11804 	/*
11805 	 * Process MSS option.  Note that MSS option value does not account
11806 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
11807 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
11808 	 * IPv6.
11809 	 */
11810 	if (!(options & TCP_OPT_MSS_PRESENT)) {
11811 		if (tcp->tcp_ipversion == IPV4_VERSION)
11812 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv4;
11813 		else
11814 			tcpopt.tcp_opt_mss = tcp_mss_def_ipv6;
11815 	} else {
11816 		if (tcp->tcp_ipversion == IPV4_VERSION)
11817 			mss_max = tcp_mss_max_ipv4;
11818 		else
11819 			mss_max = tcp_mss_max_ipv6;
11820 		if (tcpopt.tcp_opt_mss < tcp_mss_min)
11821 			tcpopt.tcp_opt_mss = tcp_mss_min;
11822 		else if (tcpopt.tcp_opt_mss > mss_max)
11823 			tcpopt.tcp_opt_mss = mss_max;
11824 	}
11825 
11826 	/* Process Window Scale option. */
11827 	if (options & TCP_OPT_WSCALE_PRESENT) {
11828 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
11829 		tcp->tcp_snd_ws_ok = B_TRUE;
11830 	} else {
11831 		tcp->tcp_snd_ws = B_FALSE;
11832 		tcp->tcp_snd_ws_ok = B_FALSE;
11833 		tcp->tcp_rcv_ws = B_FALSE;
11834 	}
11835 
11836 	/* Process Timestamp option. */
11837 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
11838 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
11839 		tmp_tcph = (char *)tcp->tcp_tcph;
11840 
11841 		tcp->tcp_snd_ts_ok = B_TRUE;
11842 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
11843 		tcp->tcp_last_rcv_lbolt = lbolt64;
11844 		ASSERT(OK_32PTR(tmp_tcph));
11845 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
11846 
11847 		/* Fill in our template header with basic timestamp option. */
11848 		tmp_tcph += tcp->tcp_tcp_hdr_len;
11849 		tmp_tcph[0] = TCPOPT_NOP;
11850 		tmp_tcph[1] = TCPOPT_NOP;
11851 		tmp_tcph[2] = TCPOPT_TSTAMP;
11852 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
11853 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11854 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
11855 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
11856 	} else {
11857 		tcp->tcp_snd_ts_ok = B_FALSE;
11858 	}
11859 
11860 	/*
11861 	 * Process SACK options.  If SACK is enabled for this connection,
11862 	 * then allocate the SACK info structure.  Note the following ways
11863 	 * when tcp_snd_sack_ok is set to true.
11864 	 *
11865 	 * For active connection: in tcp_adapt_ire() called in
11866 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
11867 	 * is checked.
11868 	 *
11869 	 * For passive connection: in tcp_adapt_ire() called in
11870 	 * tcp_accept_comm().
11871 	 *
11872 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
11873 	 * That check makes sure that if we did not send a SACK OK option,
11874 	 * we will not enable SACK for this connection even though the other
11875 	 * side sends us SACK OK option.  For active connection, the SACK
11876 	 * info structure has already been allocated.  So we need to free
11877 	 * it if SACK is disabled.
11878 	 */
11879 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
11880 	    (tcp->tcp_snd_sack_ok ||
11881 	    (tcp_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
11882 		/* This should be true only in the passive case. */
11883 		if (tcp->tcp_sack_info == NULL) {
11884 			ASSERT(TCP_IS_DETACHED(tcp));
11885 			tcp->tcp_sack_info =
11886 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
11887 		}
11888 		if (tcp->tcp_sack_info == NULL) {
11889 			tcp->tcp_snd_sack_ok = B_FALSE;
11890 		} else {
11891 			tcp->tcp_snd_sack_ok = B_TRUE;
11892 			if (tcp->tcp_snd_ts_ok) {
11893 				tcp->tcp_max_sack_blk = 3;
11894 			} else {
11895 				tcp->tcp_max_sack_blk = 4;
11896 			}
11897 		}
11898 	} else {
11899 		/*
11900 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
11901 		 * no SACK info will be used for this
11902 		 * connection.  This assumes that SACK usage
11903 		 * permission is negotiated.  This may need
11904 		 * to be changed once this is clarified.
11905 		 */
11906 		if (tcp->tcp_sack_info != NULL) {
11907 			ASSERT(tcp->tcp_notsack_list == NULL);
11908 			kmem_cache_free(tcp_sack_info_cache,
11909 			    tcp->tcp_sack_info);
11910 			tcp->tcp_sack_info = NULL;
11911 		}
11912 		tcp->tcp_snd_sack_ok = B_FALSE;
11913 	}
11914 
11915 	/*
11916 	 * Now we know the exact TCP/IP header length, subtract
11917 	 * that from tcp_mss to get our side's MSS.
11918 	 */
11919 	tcp->tcp_mss -= tcp->tcp_hdr_len;
11920 	/*
11921 	 * Here we assume that the other side's header size will be equal to
11922 	 * our header size.  We calculate the real MSS accordingly.  Need to
11923 	 * take into additional stuffs IPsec puts in.
11924 	 *
11925 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
11926 	 */
11927 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
11928 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
11929 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
11930 
11931 	/*
11932 	 * Set MSS to the smaller one of both ends of the connection.
11933 	 * We should not have called tcp_mss_set() before, but our
11934 	 * side of the MSS should have been set to a proper value
11935 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
11936 	 * STREAM head parameters properly.
11937 	 *
11938 	 * If we have a larger-than-16-bit window but the other side
11939 	 * didn't want to do window scale, tcp_rwnd_set() will take
11940 	 * care of that.
11941 	 */
11942 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
11943 }
11944 
11945 /*
11946  * Sends the T_CONN_IND to the listener. The caller calls this
11947  * functions via squeue to get inside the listener's perimeter
11948  * once the 3 way hand shake is done a T_CONN_IND needs to be
11949  * sent. As an optimization, the caller can call this directly
11950  * if listener's perimeter is same as eager's.
11951  */
11952 /* ARGSUSED */
11953 void
11954 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
11955 {
11956 	conn_t			*lconnp = (conn_t *)arg;
11957 	tcp_t			*listener = lconnp->conn_tcp;
11958 	tcp_t			*tcp;
11959 	struct T_conn_ind	*conn_ind;
11960 	ipaddr_t 		*addr_cache;
11961 	boolean_t		need_send_conn_ind = B_FALSE;
11962 
11963 	/* retrieve the eager */
11964 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
11965 	ASSERT(conn_ind->OPT_offset != 0 &&
11966 	    conn_ind->OPT_length == sizeof (intptr_t));
11967 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
11968 		conn_ind->OPT_length);
11969 
11970 	/*
11971 	 * TLI/XTI applications will get confused by
11972 	 * sending eager as an option since it violates
11973 	 * the option semantics. So remove the eager as
11974 	 * option since TLI/XTI app doesn't need it anyway.
11975 	 */
11976 	if (!TCP_IS_SOCKET(listener)) {
11977 		conn_ind->OPT_length = 0;
11978 		conn_ind->OPT_offset = 0;
11979 	}
11980 	if (listener->tcp_state == TCPS_CLOSED ||
11981 	    TCP_IS_DETACHED(listener)) {
11982 		/*
11983 		 * If listener has closed, it would have caused a
11984 		 * a cleanup/blowoff to happen for the eager. We
11985 		 * just need to return.
11986 		 */
11987 		freemsg(mp);
11988 		return;
11989 	}
11990 
11991 
11992 	/*
11993 	 * if the conn_req_q is full defer passing up the
11994 	 * T_CONN_IND until space is availabe after t_accept()
11995 	 * processing
11996 	 */
11997 	mutex_enter(&listener->tcp_eager_lock);
11998 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
11999 		tcp_t *tail;
12000 
12001 		/*
12002 		 * The eager already has an extra ref put in tcp_rput_data
12003 		 * so that it stays till accept comes back even though it
12004 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12005 		 */
12006 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12007 		listener->tcp_conn_req_cnt_q0--;
12008 		listener->tcp_conn_req_cnt_q++;
12009 
12010 		/* Move from SYN_RCVD to ESTABLISHED list  */
12011 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12012 		    tcp->tcp_eager_prev_q0;
12013 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12014 		    tcp->tcp_eager_next_q0;
12015 		tcp->tcp_eager_prev_q0 = NULL;
12016 		tcp->tcp_eager_next_q0 = NULL;
12017 
12018 		/*
12019 		 * Insert at end of the queue because sockfs
12020 		 * sends down T_CONN_RES in chronological
12021 		 * order. Leaving the older conn indications
12022 		 * at front of the queue helps reducing search
12023 		 * time.
12024 		 */
12025 		tail = listener->tcp_eager_last_q;
12026 		if (tail != NULL)
12027 			tail->tcp_eager_next_q = tcp;
12028 		else
12029 			listener->tcp_eager_next_q = tcp;
12030 		listener->tcp_eager_last_q = tcp;
12031 		tcp->tcp_eager_next_q = NULL;
12032 		/*
12033 		 * Delay sending up the T_conn_ind until we are
12034 		 * done with the eager. Once we have have sent up
12035 		 * the T_conn_ind, the accept can potentially complete
12036 		 * any time and release the refhold we have on the eager.
12037 		 */
12038 		need_send_conn_ind = B_TRUE;
12039 	} else {
12040 		/*
12041 		 * Defer connection on q0 and set deferred
12042 		 * connection bit true
12043 		 */
12044 		tcp->tcp_conn_def_q0 = B_TRUE;
12045 
12046 		/* take tcp out of q0 ... */
12047 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12048 		    tcp->tcp_eager_next_q0;
12049 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12050 		    tcp->tcp_eager_prev_q0;
12051 
12052 		/* ... and place it at the end of q0 */
12053 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12054 		tcp->tcp_eager_next_q0 = listener;
12055 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12056 		listener->tcp_eager_prev_q0 = tcp;
12057 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12058 	}
12059 
12060 	/* we have timed out before */
12061 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12062 		tcp->tcp_syn_rcvd_timeout = 0;
12063 		listener->tcp_syn_rcvd_timeout--;
12064 		if (listener->tcp_syn_defense &&
12065 		    listener->tcp_syn_rcvd_timeout <=
12066 		    (tcp_conn_req_max_q0 >> 5) &&
12067 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12068 			listener->tcp_last_rcv_lbolt)) {
12069 			/*
12070 			 * Turn off the defense mode if we
12071 			 * believe the SYN attack is over.
12072 			 */
12073 			listener->tcp_syn_defense = B_FALSE;
12074 			if (listener->tcp_ip_addr_cache) {
12075 				kmem_free((void *)listener->tcp_ip_addr_cache,
12076 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12077 				listener->tcp_ip_addr_cache = NULL;
12078 			}
12079 		}
12080 	}
12081 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12082 	if (addr_cache != NULL) {
12083 		/*
12084 		 * We have finished a 3-way handshake with this
12085 		 * remote host. This proves the IP addr is good.
12086 		 * Cache it!
12087 		 */
12088 		addr_cache[IP_ADDR_CACHE_HASH(
12089 			tcp->tcp_remote)] = tcp->tcp_remote;
12090 	}
12091 	mutex_exit(&listener->tcp_eager_lock);
12092 	if (need_send_conn_ind)
12093 		putnext(listener->tcp_rq, mp);
12094 }
12095 
12096 mblk_t *
12097 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12098     uint_t *ifindexp, ip6_pkt_t *ippp)
12099 {
12100 	in_pktinfo_t	*pinfo;
12101 	ip6_t		*ip6h;
12102 	uchar_t		*rptr;
12103 	mblk_t		*first_mp = mp;
12104 	boolean_t	mctl_present = B_FALSE;
12105 	uint_t 		ifindex = 0;
12106 	ip6_pkt_t	ipp;
12107 	uint_t		ipvers;
12108 	uint_t		ip_hdr_len;
12109 
12110 	rptr = mp->b_rptr;
12111 	ASSERT(OK_32PTR(rptr));
12112 	ASSERT(tcp != NULL);
12113 	ipp.ipp_fields = 0;
12114 
12115 	switch DB_TYPE(mp) {
12116 	case M_CTL:
12117 		mp = mp->b_cont;
12118 		if (mp == NULL) {
12119 			freemsg(first_mp);
12120 			return (NULL);
12121 		}
12122 		if (DB_TYPE(mp) != M_DATA) {
12123 			freemsg(first_mp);
12124 			return (NULL);
12125 		}
12126 		mctl_present = B_TRUE;
12127 		break;
12128 	case M_DATA:
12129 		break;
12130 	default:
12131 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12132 		freemsg(mp);
12133 		return (NULL);
12134 	}
12135 	ipvers = IPH_HDR_VERSION(rptr);
12136 	if (ipvers == IPV4_VERSION) {
12137 		if (tcp == NULL) {
12138 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12139 			goto done;
12140 		}
12141 
12142 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12143 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12144 
12145 		/*
12146 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12147 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12148 		 */
12149 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12150 		    mctl_present) {
12151 			pinfo = (in_pktinfo_t *)first_mp->b_rptr;
12152 			if ((MBLKL(first_mp) == sizeof (in_pktinfo_t)) &&
12153 			    (pinfo->in_pkt_ulp_type == IN_PKTINFO) &&
12154 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
12155 				ipp.ipp_fields |= IPPF_IFINDEX;
12156 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
12157 				ifindex = pinfo->in_pkt_ifindex;
12158 			}
12159 			freeb(first_mp);
12160 			mctl_present = B_FALSE;
12161 		}
12162 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12163 	} else {
12164 		ip6h = (ip6_t *)rptr;
12165 
12166 		ASSERT(ipvers == IPV6_VERSION);
12167 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12168 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12169 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12170 
12171 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12172 			uint8_t	nexthdrp;
12173 
12174 			/* Look for ifindex information */
12175 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12176 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12177 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12178 					BUMP_MIB(&ip_mib, tcpInErrs);
12179 					freemsg(first_mp);
12180 					return (NULL);
12181 				}
12182 
12183 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12184 					ASSERT(ip6i->ip6i_ifindex != 0);
12185 					ipp.ipp_fields |= IPPF_IFINDEX;
12186 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12187 					ifindex = ip6i->ip6i_ifindex;
12188 				}
12189 				rptr = (uchar_t *)&ip6i[1];
12190 				mp->b_rptr = rptr;
12191 				if (rptr == mp->b_wptr) {
12192 					mblk_t *mp1;
12193 					mp1 = mp->b_cont;
12194 					freeb(mp);
12195 					mp = mp1;
12196 					rptr = mp->b_rptr;
12197 				}
12198 				if (MBLKL(mp) < IPV6_HDR_LEN +
12199 				    sizeof (tcph_t)) {
12200 					BUMP_MIB(&ip_mib, tcpInErrs);
12201 					freemsg(first_mp);
12202 					return (NULL);
12203 				}
12204 				ip6h = (ip6_t *)rptr;
12205 			}
12206 
12207 			/*
12208 			 * Find any potentially interesting extension headers
12209 			 * as well as the length of the IPv6 + extension
12210 			 * headers.
12211 			 */
12212 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12213 			/* Verify if this is a TCP packet */
12214 			if (nexthdrp != IPPROTO_TCP) {
12215 				BUMP_MIB(&ip_mib, tcpInErrs);
12216 				freemsg(first_mp);
12217 				return (NULL);
12218 			}
12219 		} else {
12220 			ip_hdr_len = IPV6_HDR_LEN;
12221 		}
12222 	}
12223 
12224 done:
12225 	if (ipversp != NULL)
12226 		*ipversp = ipvers;
12227 	if (ip_hdr_lenp != NULL)
12228 		*ip_hdr_lenp = ip_hdr_len;
12229 	if (ippp != NULL)
12230 		*ippp = ipp;
12231 	if (ifindexp != NULL)
12232 		*ifindexp = ifindex;
12233 	if (mctl_present) {
12234 		freeb(first_mp);
12235 	}
12236 	return (mp);
12237 }
12238 
12239 /*
12240  * Handle M_DATA messages from IP. Its called directly from IP via
12241  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12242  * in this path.
12243  *
12244  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12245  * v4 and v6), we are called through tcp_input() and a M_CTL can
12246  * be present for options but tcp_find_pktinfo() deals with it. We
12247  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12248  *
12249  * The first argument is always the connp/tcp to which the mp belongs.
12250  * There are no exceptions to this rule. The caller has already put
12251  * a reference on this connp/tcp and once tcp_rput_data() returns,
12252  * the squeue will do the refrele.
12253  *
12254  * The TH_SYN for the listener directly go to tcp_conn_request via
12255  * squeue.
12256  *
12257  * sqp: NULL = recursive, sqp != NULL means called from squeue
12258  */
12259 void
12260 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12261 {
12262 	int32_t		bytes_acked;
12263 	int32_t		gap;
12264 	mblk_t		*mp1;
12265 	uint_t		flags;
12266 	uint32_t	new_swnd = 0;
12267 	uchar_t		*iphdr;
12268 	uchar_t		*rptr;
12269 	int32_t		rgap;
12270 	uint32_t	seg_ack;
12271 	int		seg_len;
12272 	uint_t		ip_hdr_len;
12273 	uint32_t	seg_seq;
12274 	tcph_t		*tcph;
12275 	int		urp;
12276 	tcp_opt_t	tcpopt;
12277 	uint_t		ipvers;
12278 	ip6_pkt_t	ipp;
12279 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12280 	uint32_t	cwnd;
12281 	uint32_t	add;
12282 	int		npkt;
12283 	int		mss;
12284 	conn_t		*connp = (conn_t *)arg;
12285 	squeue_t	*sqp = (squeue_t *)arg2;
12286 	tcp_t		*tcp = connp->conn_tcp;
12287 
12288 	/*
12289 	 * RST from fused tcp loopback peer should trigger an unfuse.
12290 	 */
12291 	if (tcp->tcp_fused) {
12292 		TCP_STAT(tcp_fusion_aborted);
12293 		tcp_unfuse(tcp);
12294 	}
12295 
12296 	iphdr = mp->b_rptr;
12297 	rptr = mp->b_rptr;
12298 	ASSERT(OK_32PTR(rptr));
12299 
12300 	/*
12301 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12302 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12303 	 * necessary information.
12304 	 */
12305 	if (IPCL_IS_TCP4(connp)) {
12306 		ipvers = IPV4_VERSION;
12307 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12308 	} else {
12309 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12310 		    NULL, &ipp);
12311 		if (mp == NULL) {
12312 			TCP_STAT(tcp_rput_v6_error);
12313 			return;
12314 		}
12315 		iphdr = mp->b_rptr;
12316 		rptr = mp->b_rptr;
12317 	}
12318 	ASSERT(DB_TYPE(mp) == M_DATA);
12319 
12320 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12321 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12322 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12323 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12324 	seg_len = (int)(mp->b_wptr - rptr) -
12325 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12326 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12327 		do {
12328 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12329 			    (uintptr_t)INT_MAX);
12330 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12331 		} while ((mp1 = mp1->b_cont) != NULL &&
12332 		    mp1->b_datap->db_type == M_DATA);
12333 	}
12334 
12335 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12336 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12337 		    seg_len, tcph);
12338 		return;
12339 	}
12340 
12341 	if (sqp != NULL) {
12342 		/*
12343 		 * This is the correct place to update tcp_last_recv_time. Note
12344 		 * that it is also updated for tcp structure that belongs to
12345 		 * global and listener queues which do not really need updating.
12346 		 * But that should not cause any harm.  And it is updated for
12347 		 * all kinds of incoming segments, not only for data segments.
12348 		 */
12349 		tcp->tcp_last_recv_time = lbolt;
12350 	}
12351 
12352 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12353 
12354 	BUMP_LOCAL(tcp->tcp_ibsegs);
12355 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
12356 
12357 	if ((flags & TH_URG) && sqp != NULL) {
12358 		/*
12359 		 * TCP can't handle urgent pointers that arrive before
12360 		 * the connection has been accept()ed since it can't
12361 		 * buffer OOB data.  Discard segment if this happens.
12362 		 *
12363 		 * Nor can it reassemble urgent pointers, so discard
12364 		 * if it's not the next segment expected.
12365 		 *
12366 		 * Otherwise, collapse chain into one mblk (discard if
12367 		 * that fails).  This makes sure the headers, retransmitted
12368 		 * data, and new data all are in the same mblk.
12369 		 */
12370 		ASSERT(mp != NULL);
12371 		if (tcp->tcp_listener || !pullupmsg(mp, -1)) {
12372 			freemsg(mp);
12373 			return;
12374 		}
12375 		/* Update pointers into message */
12376 		iphdr = rptr = mp->b_rptr;
12377 		tcph = (tcph_t *)&rptr[ip_hdr_len];
12378 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
12379 			/*
12380 			 * Since we can't handle any data with this urgent
12381 			 * pointer that is out of sequence, we expunge
12382 			 * the data.  This allows us to still register
12383 			 * the urgent mark and generate the M_PCSIG,
12384 			 * which we can do.
12385 			 */
12386 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12387 			seg_len = 0;
12388 		}
12389 	}
12390 
12391 	switch (tcp->tcp_state) {
12392 	case TCPS_SYN_SENT:
12393 		if (flags & TH_ACK) {
12394 			/*
12395 			 * Note that our stack cannot send data before a
12396 			 * connection is established, therefore the
12397 			 * following check is valid.  Otherwise, it has
12398 			 * to be changed.
12399 			 */
12400 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
12401 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12402 				freemsg(mp);
12403 				if (flags & TH_RST)
12404 					return;
12405 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
12406 				    tcp, seg_ack, 0, TH_RST);
12407 				return;
12408 			}
12409 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
12410 		}
12411 		if (flags & TH_RST) {
12412 			freemsg(mp);
12413 			if (flags & TH_ACK)
12414 				(void) tcp_clean_death(tcp,
12415 				    ECONNREFUSED, 13);
12416 			return;
12417 		}
12418 		if (!(flags & TH_SYN)) {
12419 			freemsg(mp);
12420 			return;
12421 		}
12422 
12423 		/* Process all TCP options. */
12424 		tcp_process_options(tcp, tcph);
12425 		/*
12426 		 * The following changes our rwnd to be a multiple of the
12427 		 * MIN(peer MSS, our MSS) for performance reason.
12428 		 */
12429 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
12430 		    tcp->tcp_mss));
12431 
12432 		/* Is the other end ECN capable? */
12433 		if (tcp->tcp_ecn_ok) {
12434 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
12435 				tcp->tcp_ecn_ok = B_FALSE;
12436 			}
12437 		}
12438 		/*
12439 		 * Clear ECN flags because it may interfere with later
12440 		 * processing.
12441 		 */
12442 		flags &= ~(TH_ECE|TH_CWR);
12443 
12444 		tcp->tcp_irs = seg_seq;
12445 		tcp->tcp_rack = seg_seq;
12446 		tcp->tcp_rnxt = seg_seq + 1;
12447 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12448 		if (!TCP_IS_DETACHED(tcp)) {
12449 			/* Allocate room for SACK options if needed. */
12450 			if (tcp->tcp_snd_sack_ok) {
12451 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12452 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
12453 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12454 			} else {
12455 				(void) mi_set_sth_wroff(tcp->tcp_rq,
12456 				    tcp->tcp_hdr_len +
12457 				    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra));
12458 			}
12459 		}
12460 		if (flags & TH_ACK) {
12461 			/*
12462 			 * If we can't get the confirmation upstream, pretend
12463 			 * we didn't even see this one.
12464 			 *
12465 			 * XXX: how can we pretend we didn't see it if we
12466 			 * have updated rnxt et. al.
12467 			 *
12468 			 * For loopback we defer sending up the T_CONN_CON
12469 			 * until after some checks below.
12470 			 */
12471 			mp1 = NULL;
12472 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
12473 			    tcp->tcp_loopback ? &mp1 : NULL)) {
12474 				freemsg(mp);
12475 				return;
12476 			}
12477 			/* SYN was acked - making progress */
12478 			if (tcp->tcp_ipversion == IPV6_VERSION)
12479 				tcp->tcp_ip_forward_progress = B_TRUE;
12480 
12481 			/* One for the SYN */
12482 			tcp->tcp_suna = tcp->tcp_iss + 1;
12483 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
12484 			tcp->tcp_state = TCPS_ESTABLISHED;
12485 
12486 			/*
12487 			 * If SYN was retransmitted, need to reset all
12488 			 * retransmission info.  This is because this
12489 			 * segment will be treated as a dup ACK.
12490 			 */
12491 			if (tcp->tcp_rexmit) {
12492 				tcp->tcp_rexmit = B_FALSE;
12493 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
12494 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
12495 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
12496 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
12497 				tcp->tcp_ms_we_have_waited = 0;
12498 
12499 				/*
12500 				 * Set tcp_cwnd back to 1 MSS, per
12501 				 * recommendation from
12502 				 * draft-floyd-incr-init-win-01.txt,
12503 				 * Increasing TCP's Initial Window.
12504 				 */
12505 				tcp->tcp_cwnd = tcp->tcp_mss;
12506 			}
12507 
12508 			tcp->tcp_swl1 = seg_seq;
12509 			tcp->tcp_swl2 = seg_ack;
12510 
12511 			new_swnd = BE16_TO_U16(tcph->th_win);
12512 			tcp->tcp_swnd = new_swnd;
12513 			if (new_swnd > tcp->tcp_max_swnd)
12514 				tcp->tcp_max_swnd = new_swnd;
12515 
12516 			/*
12517 			 * Always send the three-way handshake ack immediately
12518 			 * in order to make the connection complete as soon as
12519 			 * possible on the accepting host.
12520 			 */
12521 			flags |= TH_ACK_NEEDED;
12522 
12523 			/*
12524 			 * Special case for loopback.  At this point we have
12525 			 * received SYN-ACK from the remote endpoint.  In
12526 			 * order to ensure that both endpoints reach the
12527 			 * fused state prior to any data exchange, the final
12528 			 * ACK needs to be sent before we indicate T_CONN_CON
12529 			 * to the module upstream.
12530 			 */
12531 			if (tcp->tcp_loopback) {
12532 				mblk_t *ack_mp;
12533 
12534 				ASSERT(!tcp->tcp_unfusable);
12535 				ASSERT(mp1 != NULL);
12536 				/*
12537 				 * For loopback, we always get a pure SYN-ACK
12538 				 * and only need to send back the final ACK
12539 				 * with no data (this is because the other
12540 				 * tcp is ours and we don't do T/TCP).  This
12541 				 * final ACK triggers the passive side to
12542 				 * perform fusion in ESTABLISHED state.
12543 				 */
12544 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
12545 					if (tcp->tcp_ack_tid != 0) {
12546 						(void) TCP_TIMER_CANCEL(tcp,
12547 						    tcp->tcp_ack_tid);
12548 						tcp->tcp_ack_tid = 0;
12549 					}
12550 					TCP_RECORD_TRACE(tcp, ack_mp,
12551 					    TCP_TRACE_SEND_PKT);
12552 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
12553 					BUMP_LOCAL(tcp->tcp_obsegs);
12554 					BUMP_MIB(&tcp_mib, tcpOutAck);
12555 
12556 					/* Send up T_CONN_CON */
12557 					putnext(tcp->tcp_rq, mp1);
12558 
12559 					freemsg(mp);
12560 					return;
12561 				}
12562 				/*
12563 				 * Forget fusion; we need to handle more
12564 				 * complex cases below.  Send the deferred
12565 				 * T_CONN_CON message upstream and proceed
12566 				 * as usual.  Mark this tcp as not capable
12567 				 * of fusion.
12568 				 */
12569 				TCP_STAT(tcp_fusion_unfusable);
12570 				tcp->tcp_unfusable = B_TRUE;
12571 				putnext(tcp->tcp_rq, mp1);
12572 			}
12573 
12574 			/*
12575 			 * Check to see if there is data to be sent.  If
12576 			 * yes, set the transmit flag.  Then check to see
12577 			 * if received data processing needs to be done.
12578 			 * If not, go straight to xmit_check.  This short
12579 			 * cut is OK as we don't support T/TCP.
12580 			 */
12581 			if (tcp->tcp_unsent)
12582 				flags |= TH_XMIT_NEEDED;
12583 
12584 			if (seg_len == 0 && !(flags & TH_URG)) {
12585 				freemsg(mp);
12586 				goto xmit_check;
12587 			}
12588 
12589 			flags &= ~TH_SYN;
12590 			seg_seq++;
12591 			break;
12592 		}
12593 		tcp->tcp_state = TCPS_SYN_RCVD;
12594 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
12595 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
12596 		if (mp1) {
12597 			mblk_setcred(mp1, tcp->tcp_cred);
12598 			DB_CPID(mp1) = tcp->tcp_cpid;
12599 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
12600 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
12601 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12602 		}
12603 		freemsg(mp);
12604 		return;
12605 	case TCPS_SYN_RCVD:
12606 		if (flags & TH_ACK) {
12607 			/*
12608 			 * In this state, a SYN|ACK packet is either bogus
12609 			 * because the other side must be ACKing our SYN which
12610 			 * indicates it has seen the ACK for their SYN and
12611 			 * shouldn't retransmit it or we're crossing SYNs
12612 			 * on active open.
12613 			 */
12614 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
12615 				freemsg(mp);
12616 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
12617 				    tcp, seg_ack, 0, TH_RST);
12618 				return;
12619 			}
12620 			/*
12621 			 * NOTE: RFC 793 pg. 72 says this should be
12622 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
12623 			 * but that would mean we have an ack that ignored
12624 			 * our SYN.
12625 			 */
12626 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
12627 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
12628 				freemsg(mp);
12629 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
12630 				    tcp, seg_ack, 0, TH_RST);
12631 				return;
12632 			}
12633 		}
12634 		break;
12635 	case TCPS_LISTEN:
12636 		/*
12637 		 * Only a TLI listener can come through this path when a
12638 		 * acceptor is going back to be a listener and a packet
12639 		 * for the acceptor hits the classifier. For a socket
12640 		 * listener, this can never happen because a listener
12641 		 * can never accept connection on itself and hence a
12642 		 * socket acceptor can not go back to being a listener.
12643 		 */
12644 		ASSERT(!TCP_IS_SOCKET(tcp));
12645 		/*FALLTHRU*/
12646 	case TCPS_CLOSED:
12647 	case TCPS_BOUND: {
12648 		conn_t	*new_connp;
12649 
12650 		new_connp = ipcl_classify(mp, connp->conn_zoneid);
12651 		if (new_connp != NULL) {
12652 			tcp_reinput(new_connp, mp, connp->conn_sqp);
12653 			return;
12654 		}
12655 		/* We failed to classify. For now just drop the packet */
12656 		freemsg(mp);
12657 		return;
12658 	}
12659 	case TCPS_IDLE:
12660 		/*
12661 		 * Handle the case where the tcp_clean_death() has happened
12662 		 * on a connection (application hasn't closed yet) but a packet
12663 		 * was already queued on squeue before tcp_clean_death()
12664 		 * was processed. Calling tcp_clean_death() twice on same
12665 		 * connection can result in weird behaviour.
12666 		 */
12667 		freemsg(mp);
12668 		return;
12669 	default:
12670 		break;
12671 	}
12672 
12673 	/*
12674 	 * Already on the correct queue/perimeter.
12675 	 * If this is a detached connection and not an eager
12676 	 * connection hanging off a listener then new data
12677 	 * (past the FIN) will cause a reset.
12678 	 * We do a special check here where it
12679 	 * is out of the main line, rather than check
12680 	 * if we are detached every time we see new
12681 	 * data down below.
12682 	 */
12683 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
12684 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
12685 		BUMP_MIB(&tcp_mib, tcpInClosed);
12686 		TCP_RECORD_TRACE(tcp,
12687 		    mp, TCP_TRACE_RECV_PKT);
12688 
12689 		freemsg(mp);
12690 		/*
12691 		 * This could be an SSL closure alert. We're detached so just
12692 		 * acknowledge it this last time.
12693 		 */
12694 		if (tcp->tcp_kssl_ctx != NULL) {
12695 			kssl_release_ctx(tcp->tcp_kssl_ctx);
12696 			tcp->tcp_kssl_ctx = NULL;
12697 
12698 			tcp->tcp_rnxt += seg_len;
12699 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
12700 			flags |= TH_ACK_NEEDED;
12701 			goto ack_check;
12702 		}
12703 
12704 		tcp_xmit_ctl("new data when detached", tcp,
12705 		    tcp->tcp_snxt, 0, TH_RST);
12706 		(void) tcp_clean_death(tcp, EPROTO, 12);
12707 		return;
12708 	}
12709 
12710 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
12711 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
12712 	new_swnd = BE16_TO_U16(tcph->th_win) <<
12713 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
12714 	mss = tcp->tcp_mss;
12715 
12716 	if (tcp->tcp_snd_ts_ok) {
12717 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
12718 			/*
12719 			 * This segment is not acceptable.
12720 			 * Drop it and send back an ACK.
12721 			 */
12722 			freemsg(mp);
12723 			flags |= TH_ACK_NEEDED;
12724 			goto ack_check;
12725 		}
12726 	} else if (tcp->tcp_snd_sack_ok) {
12727 		ASSERT(tcp->tcp_sack_info != NULL);
12728 		tcpopt.tcp = tcp;
12729 		/*
12730 		 * SACK info in already updated in tcp_parse_options.  Ignore
12731 		 * all other TCP options...
12732 		 */
12733 		(void) tcp_parse_options(tcph, &tcpopt);
12734 	}
12735 try_again:;
12736 	gap = seg_seq - tcp->tcp_rnxt;
12737 	rgap = tcp->tcp_rwnd - (gap + seg_len);
12738 	/*
12739 	 * gap is the amount of sequence space between what we expect to see
12740 	 * and what we got for seg_seq.  A positive value for gap means
12741 	 * something got lost.  A negative value means we got some old stuff.
12742 	 */
12743 	if (gap < 0) {
12744 		/* Old stuff present.  Is the SYN in there? */
12745 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
12746 		    (seg_len != 0)) {
12747 			flags &= ~TH_SYN;
12748 			seg_seq++;
12749 			urp--;
12750 			/* Recompute the gaps after noting the SYN. */
12751 			goto try_again;
12752 		}
12753 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
12754 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
12755 		    (seg_len > -gap ? -gap : seg_len));
12756 		/* Remove the old stuff from seg_len. */
12757 		seg_len += gap;
12758 		/*
12759 		 * Anything left?
12760 		 * Make sure to check for unack'd FIN when rest of data
12761 		 * has been previously ack'd.
12762 		 */
12763 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
12764 			/*
12765 			 * Resets are only valid if they lie within our offered
12766 			 * window.  If the RST bit is set, we just ignore this
12767 			 * segment.
12768 			 */
12769 			if (flags & TH_RST) {
12770 				freemsg(mp);
12771 				return;
12772 			}
12773 
12774 			/*
12775 			 * The arriving of dup data packets indicate that we
12776 			 * may have postponed an ack for too long, or the other
12777 			 * side's RTT estimate is out of shape. Start acking
12778 			 * more often.
12779 			 */
12780 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
12781 			    tcp->tcp_rack_cnt >= 1 &&
12782 			    tcp->tcp_rack_abs_max > 2) {
12783 				tcp->tcp_rack_abs_max--;
12784 			}
12785 			tcp->tcp_rack_cur_max = 1;
12786 
12787 			/*
12788 			 * This segment is "unacceptable".  None of its
12789 			 * sequence space lies within our advertized window.
12790 			 *
12791 			 * Adjust seg_len to the original value for tracing.
12792 			 */
12793 			seg_len -= gap;
12794 			if (tcp->tcp_debug) {
12795 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12796 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
12797 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
12798 				    "seg_len %d, rnxt %u, snxt %u, %s",
12799 				    gap, rgap, flags, seg_seq, seg_ack,
12800 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
12801 				    tcp_display(tcp, NULL,
12802 				    DISP_ADDR_AND_PORT));
12803 			}
12804 
12805 			/*
12806 			 * Arrange to send an ACK in response to the
12807 			 * unacceptable segment per RFC 793 page 69. There
12808 			 * is only one small difference between ours and the
12809 			 * acceptability test in the RFC - we accept ACK-only
12810 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
12811 			 * will be generated.
12812 			 *
12813 			 * Note that we have to ACK an ACK-only packet at least
12814 			 * for stacks that send 0-length keep-alives with
12815 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
12816 			 * section 4.2.3.6. As long as we don't ever generate
12817 			 * an unacceptable packet in response to an incoming
12818 			 * packet that is unacceptable, it should not cause
12819 			 * "ACK wars".
12820 			 */
12821 			flags |=  TH_ACK_NEEDED;
12822 
12823 			/*
12824 			 * Continue processing this segment in order to use the
12825 			 * ACK information it contains, but skip all other
12826 			 * sequence-number processing.	Processing the ACK
12827 			 * information is necessary in order to
12828 			 * re-synchronize connections that may have lost
12829 			 * synchronization.
12830 			 *
12831 			 * We clear seg_len and flag fields related to
12832 			 * sequence number processing as they are not
12833 			 * to be trusted for an unacceptable segment.
12834 			 */
12835 			seg_len = 0;
12836 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
12837 			goto process_ack;
12838 		}
12839 
12840 		/* Fix seg_seq, and chew the gap off the front. */
12841 		seg_seq = tcp->tcp_rnxt;
12842 		urp += gap;
12843 		do {
12844 			mblk_t	*mp2;
12845 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
12846 			    (uintptr_t)UINT_MAX);
12847 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
12848 			if (gap > 0) {
12849 				mp->b_rptr = mp->b_wptr - gap;
12850 				break;
12851 			}
12852 			mp2 = mp;
12853 			mp = mp->b_cont;
12854 			freeb(mp2);
12855 		} while (gap < 0);
12856 		/*
12857 		 * If the urgent data has already been acknowledged, we
12858 		 * should ignore TH_URG below
12859 		 */
12860 		if (urp < 0)
12861 			flags &= ~TH_URG;
12862 	}
12863 	/*
12864 	 * rgap is the amount of stuff received out of window.  A negative
12865 	 * value is the amount out of window.
12866 	 */
12867 	if (rgap < 0) {
12868 		mblk_t	*mp2;
12869 
12870 		if (tcp->tcp_rwnd == 0) {
12871 			BUMP_MIB(&tcp_mib, tcpInWinProbe);
12872 		} else {
12873 			BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
12874 			UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
12875 		}
12876 
12877 		/*
12878 		 * seg_len does not include the FIN, so if more than
12879 		 * just the FIN is out of window, we act like we don't
12880 		 * see it.  (If just the FIN is out of window, rgap
12881 		 * will be zero and we will go ahead and acknowledge
12882 		 * the FIN.)
12883 		 */
12884 		flags &= ~TH_FIN;
12885 
12886 		/* Fix seg_len and make sure there is something left. */
12887 		seg_len += rgap;
12888 		if (seg_len <= 0) {
12889 			/*
12890 			 * Resets are only valid if they lie within our offered
12891 			 * window.  If the RST bit is set, we just ignore this
12892 			 * segment.
12893 			 */
12894 			if (flags & TH_RST) {
12895 				freemsg(mp);
12896 				return;
12897 			}
12898 
12899 			/* Per RFC 793, we need to send back an ACK. */
12900 			flags |= TH_ACK_NEEDED;
12901 
12902 			/*
12903 			 * Send SIGURG as soon as possible i.e. even
12904 			 * if the TH_URG was delivered in a window probe
12905 			 * packet (which will be unacceptable).
12906 			 *
12907 			 * We generate a signal if none has been generated
12908 			 * for this connection or if this is a new urgent
12909 			 * byte. Also send a zero-length "unmarked" message
12910 			 * to inform SIOCATMARK that this is not the mark.
12911 			 *
12912 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
12913 			 * is sent up. This plus the check for old data
12914 			 * (gap >= 0) handles the wraparound of the sequence
12915 			 * number space without having to always track the
12916 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
12917 			 * this max in its rcv_up variable).
12918 			 *
12919 			 * This prevents duplicate SIGURGS due to a "late"
12920 			 * zero-window probe when the T_EXDATA_IND has already
12921 			 * been sent up.
12922 			 */
12923 			if ((flags & TH_URG) &&
12924 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
12925 			    tcp->tcp_urp_last))) {
12926 				mp1 = allocb(0, BPRI_MED);
12927 				if (mp1 == NULL) {
12928 					freemsg(mp);
12929 					return;
12930 				}
12931 				if (!TCP_IS_DETACHED(tcp) &&
12932 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
12933 				    SIGURG)) {
12934 					/* Try again on the rexmit. */
12935 					freemsg(mp1);
12936 					freemsg(mp);
12937 					return;
12938 				}
12939 				/*
12940 				 * If the next byte would be the mark
12941 				 * then mark with MARKNEXT else mark
12942 				 * with NOTMARKNEXT.
12943 				 */
12944 				if (gap == 0 && urp == 0)
12945 					mp1->b_flag |= MSGMARKNEXT;
12946 				else
12947 					mp1->b_flag |= MSGNOTMARKNEXT;
12948 				freemsg(tcp->tcp_urp_mark_mp);
12949 				tcp->tcp_urp_mark_mp = mp1;
12950 				flags |= TH_SEND_URP_MARK;
12951 				tcp->tcp_urp_last_valid = B_TRUE;
12952 				tcp->tcp_urp_last = urp + seg_seq;
12953 			}
12954 			/*
12955 			 * If this is a zero window probe, continue to
12956 			 * process the ACK part.  But we need to set seg_len
12957 			 * to 0 to avoid data processing.  Otherwise just
12958 			 * drop the segment and send back an ACK.
12959 			 */
12960 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
12961 				flags &= ~(TH_SYN | TH_URG);
12962 				seg_len = 0;
12963 				goto process_ack;
12964 			} else {
12965 				freemsg(mp);
12966 				goto ack_check;
12967 			}
12968 		}
12969 		/* Pitch out of window stuff off the end. */
12970 		rgap = seg_len;
12971 		mp2 = mp;
12972 		do {
12973 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
12974 			    (uintptr_t)INT_MAX);
12975 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
12976 			if (rgap < 0) {
12977 				mp2->b_wptr += rgap;
12978 				if ((mp1 = mp2->b_cont) != NULL) {
12979 					mp2->b_cont = NULL;
12980 					freemsg(mp1);
12981 				}
12982 				break;
12983 			}
12984 		} while ((mp2 = mp2->b_cont) != NULL);
12985 	}
12986 ok:;
12987 	/*
12988 	 * TCP should check ECN info for segments inside the window only.
12989 	 * Therefore the check should be done here.
12990 	 */
12991 	if (tcp->tcp_ecn_ok) {
12992 		if (flags & TH_CWR) {
12993 			tcp->tcp_ecn_echo_on = B_FALSE;
12994 		}
12995 		/*
12996 		 * Note that both ECN_CE and CWR can be set in the
12997 		 * same segment.  In this case, we once again turn
12998 		 * on ECN_ECHO.
12999 		 */
13000 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13001 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13002 
13003 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13004 				tcp->tcp_ecn_echo_on = B_TRUE;
13005 			}
13006 		} else {
13007 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13008 
13009 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13010 			    htonl(IPH_ECN_CE << 20)) {
13011 				tcp->tcp_ecn_echo_on = B_TRUE;
13012 			}
13013 		}
13014 	}
13015 
13016 	/*
13017 	 * Check whether we can update tcp_ts_recent.  This test is
13018 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13019 	 * Extensions for High Performance: An Update", Internet Draft.
13020 	 */
13021 	if (tcp->tcp_snd_ts_ok &&
13022 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13023 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13024 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13025 		tcp->tcp_last_rcv_lbolt = lbolt64;
13026 	}
13027 
13028 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13029 		/*
13030 		 * FIN in an out of order segment.  We record this in
13031 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13032 		 * Clear the FIN so that any check on FIN flag will fail.
13033 		 * Remember that FIN also counts in the sequence number
13034 		 * space.  So we need to ack out of order FIN only segments.
13035 		 */
13036 		if (flags & TH_FIN) {
13037 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13038 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13039 			flags &= ~TH_FIN;
13040 			flags |= TH_ACK_NEEDED;
13041 		}
13042 		if (seg_len > 0) {
13043 			/* Fill in the SACK blk list. */
13044 			if (tcp->tcp_snd_sack_ok) {
13045 				ASSERT(tcp->tcp_sack_info != NULL);
13046 				tcp_sack_insert(tcp->tcp_sack_list,
13047 				    seg_seq, seg_seq + seg_len,
13048 				    &(tcp->tcp_num_sack_blk));
13049 			}
13050 
13051 			/*
13052 			 * Attempt reassembly and see if we have something
13053 			 * ready to go.
13054 			 */
13055 			mp = tcp_reass(tcp, mp, seg_seq);
13056 			/* Always ack out of order packets */
13057 			flags |= TH_ACK_NEEDED | TH_PUSH;
13058 			if (mp) {
13059 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13060 				    (uintptr_t)INT_MAX);
13061 				seg_len = mp->b_cont ? msgdsize(mp) :
13062 					(int)(mp->b_wptr - mp->b_rptr);
13063 				seg_seq = tcp->tcp_rnxt;
13064 				/*
13065 				 * A gap is filled and the seq num and len
13066 				 * of the gap match that of a previously
13067 				 * received FIN, put the FIN flag back in.
13068 				 */
13069 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13070 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13071 					flags |= TH_FIN;
13072 					tcp->tcp_valid_bits &=
13073 					    ~TCP_OFO_FIN_VALID;
13074 				}
13075 			} else {
13076 				/*
13077 				 * Keep going even with NULL mp.
13078 				 * There may be a useful ACK or something else
13079 				 * we don't want to miss.
13080 				 *
13081 				 * But TCP should not perform fast retransmit
13082 				 * because of the ack number.  TCP uses
13083 				 * seg_len == 0 to determine if it is a pure
13084 				 * ACK.  And this is not a pure ACK.
13085 				 */
13086 				seg_len = 0;
13087 				ofo_seg = B_TRUE;
13088 			}
13089 		}
13090 	} else if (seg_len > 0) {
13091 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
13092 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
13093 		/*
13094 		 * If an out of order FIN was received before, and the seq
13095 		 * num and len of the new segment match that of the FIN,
13096 		 * put the FIN flag back in.
13097 		 */
13098 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13099 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13100 			flags |= TH_FIN;
13101 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13102 		}
13103 	}
13104 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13105 	if (flags & TH_RST) {
13106 		freemsg(mp);
13107 		switch (tcp->tcp_state) {
13108 		case TCPS_SYN_RCVD:
13109 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13110 			break;
13111 		case TCPS_ESTABLISHED:
13112 		case TCPS_FIN_WAIT_1:
13113 		case TCPS_FIN_WAIT_2:
13114 		case TCPS_CLOSE_WAIT:
13115 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13116 			break;
13117 		case TCPS_CLOSING:
13118 		case TCPS_LAST_ACK:
13119 			(void) tcp_clean_death(tcp, 0, 16);
13120 			break;
13121 		default:
13122 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13123 			(void) tcp_clean_death(tcp, ENXIO, 17);
13124 			break;
13125 		}
13126 		return;
13127 	}
13128 	if (flags & TH_SYN) {
13129 		/*
13130 		 * See RFC 793, Page 71
13131 		 *
13132 		 * The seq number must be in the window as it should
13133 		 * be "fixed" above.  If it is outside window, it should
13134 		 * be already rejected.  Note that we allow seg_seq to be
13135 		 * rnxt + rwnd because we want to accept 0 window probe.
13136 		 */
13137 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13138 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13139 		freemsg(mp);
13140 		/*
13141 		 * If the ACK flag is not set, just use our snxt as the
13142 		 * seq number of the RST segment.
13143 		 */
13144 		if (!(flags & TH_ACK)) {
13145 			seg_ack = tcp->tcp_snxt;
13146 		}
13147 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13148 		    TH_RST|TH_ACK);
13149 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13150 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13151 		return;
13152 	}
13153 	/*
13154 	 * urp could be -1 when the urp field in the packet is 0
13155 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13156 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13157 	 */
13158 	if (flags & TH_URG && urp >= 0) {
13159 		if (!tcp->tcp_urp_last_valid ||
13160 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13161 			/*
13162 			 * If we haven't generated the signal yet for this
13163 			 * urgent pointer value, do it now.  Also, send up a
13164 			 * zero-length M_DATA indicating whether or not this is
13165 			 * the mark. The latter is not needed when a
13166 			 * T_EXDATA_IND is sent up. However, if there are
13167 			 * allocation failures this code relies on the sender
13168 			 * retransmitting and the socket code for determining
13169 			 * the mark should not block waiting for the peer to
13170 			 * transmit. Thus, for simplicity we always send up the
13171 			 * mark indication.
13172 			 */
13173 			mp1 = allocb(0, BPRI_MED);
13174 			if (mp1 == NULL) {
13175 				freemsg(mp);
13176 				return;
13177 			}
13178 			if (!TCP_IS_DETACHED(tcp) &&
13179 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13180 				/* Try again on the rexmit. */
13181 				freemsg(mp1);
13182 				freemsg(mp);
13183 				return;
13184 			}
13185 			/*
13186 			 * Mark with NOTMARKNEXT for now.
13187 			 * The code below will change this to MARKNEXT
13188 			 * if we are at the mark.
13189 			 *
13190 			 * If there are allocation failures (e.g. in dupmsg
13191 			 * below) the next time tcp_rput_data sees the urgent
13192 			 * segment it will send up the MSG*MARKNEXT message.
13193 			 */
13194 			mp1->b_flag |= MSGNOTMARKNEXT;
13195 			freemsg(tcp->tcp_urp_mark_mp);
13196 			tcp->tcp_urp_mark_mp = mp1;
13197 			flags |= TH_SEND_URP_MARK;
13198 #ifdef DEBUG
13199 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13200 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13201 			    "last %x, %s",
13202 			    seg_seq, urp, tcp->tcp_urp_last,
13203 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13204 #endif /* DEBUG */
13205 			tcp->tcp_urp_last_valid = B_TRUE;
13206 			tcp->tcp_urp_last = urp + seg_seq;
13207 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13208 			/*
13209 			 * An allocation failure prevented the previous
13210 			 * tcp_rput_data from sending up the allocated
13211 			 * MSG*MARKNEXT message - send it up this time
13212 			 * around.
13213 			 */
13214 			flags |= TH_SEND_URP_MARK;
13215 		}
13216 
13217 		/*
13218 		 * If the urgent byte is in this segment, make sure that it is
13219 		 * all by itself.  This makes it much easier to deal with the
13220 		 * possibility of an allocation failure on the T_exdata_ind.
13221 		 * Note that seg_len is the number of bytes in the segment, and
13222 		 * urp is the offset into the segment of the urgent byte.
13223 		 * urp < seg_len means that the urgent byte is in this segment.
13224 		 */
13225 		if (urp < seg_len) {
13226 			if (seg_len != 1) {
13227 				uint32_t  tmp_rnxt;
13228 				/*
13229 				 * Break it up and feed it back in.
13230 				 * Re-attach the IP header.
13231 				 */
13232 				mp->b_rptr = iphdr;
13233 				if (urp > 0) {
13234 					/*
13235 					 * There is stuff before the urgent
13236 					 * byte.
13237 					 */
13238 					mp1 = dupmsg(mp);
13239 					if (!mp1) {
13240 						/*
13241 						 * Trim from urgent byte on.
13242 						 * The rest will come back.
13243 						 */
13244 						(void) adjmsg(mp,
13245 						    urp - seg_len);
13246 						tcp_rput_data(connp,
13247 						    mp, NULL);
13248 						return;
13249 					}
13250 					(void) adjmsg(mp1, urp - seg_len);
13251 					/* Feed this piece back in. */
13252 					tmp_rnxt = tcp->tcp_rnxt;
13253 					tcp_rput_data(connp, mp1, NULL);
13254 					/*
13255 					 * If the data passed back in was not
13256 					 * processed (ie: bad ACK) sending
13257 					 * the remainder back in will cause a
13258 					 * loop. In this case, drop the
13259 					 * packet and let the sender try
13260 					 * sending a good packet.
13261 					 */
13262 					if (tmp_rnxt == tcp->tcp_rnxt) {
13263 						freemsg(mp);
13264 						return;
13265 					}
13266 				}
13267 				if (urp != seg_len - 1) {
13268 					uint32_t  tmp_rnxt;
13269 					/*
13270 					 * There is stuff after the urgent
13271 					 * byte.
13272 					 */
13273 					mp1 = dupmsg(mp);
13274 					if (!mp1) {
13275 						/*
13276 						 * Trim everything beyond the
13277 						 * urgent byte.  The rest will
13278 						 * come back.
13279 						 */
13280 						(void) adjmsg(mp,
13281 						    urp + 1 - seg_len);
13282 						tcp_rput_data(connp,
13283 						    mp, NULL);
13284 						return;
13285 					}
13286 					(void) adjmsg(mp1, urp + 1 - seg_len);
13287 					tmp_rnxt = tcp->tcp_rnxt;
13288 					tcp_rput_data(connp, mp1, NULL);
13289 					/*
13290 					 * If the data passed back in was not
13291 					 * processed (ie: bad ACK) sending
13292 					 * the remainder back in will cause a
13293 					 * loop. In this case, drop the
13294 					 * packet and let the sender try
13295 					 * sending a good packet.
13296 					 */
13297 					if (tmp_rnxt == tcp->tcp_rnxt) {
13298 						freemsg(mp);
13299 						return;
13300 					}
13301 				}
13302 				tcp_rput_data(connp, mp, NULL);
13303 				return;
13304 			}
13305 			/*
13306 			 * This segment contains only the urgent byte.  We
13307 			 * have to allocate the T_exdata_ind, if we can.
13308 			 */
13309 			if (!tcp->tcp_urp_mp) {
13310 				struct T_exdata_ind *tei;
13311 				mp1 = allocb(sizeof (struct T_exdata_ind),
13312 				    BPRI_MED);
13313 				if (!mp1) {
13314 					/*
13315 					 * Sigh... It'll be back.
13316 					 * Generate any MSG*MARK message now.
13317 					 */
13318 					freemsg(mp);
13319 					seg_len = 0;
13320 					if (flags & TH_SEND_URP_MARK) {
13321 
13322 
13323 						ASSERT(tcp->tcp_urp_mark_mp);
13324 						tcp->tcp_urp_mark_mp->b_flag &=
13325 							~MSGNOTMARKNEXT;
13326 						tcp->tcp_urp_mark_mp->b_flag |=
13327 							MSGMARKNEXT;
13328 					}
13329 					goto ack_check;
13330 				}
13331 				mp1->b_datap->db_type = M_PROTO;
13332 				tei = (struct T_exdata_ind *)mp1->b_rptr;
13333 				tei->PRIM_type = T_EXDATA_IND;
13334 				tei->MORE_flag = 0;
13335 				mp1->b_wptr = (uchar_t *)&tei[1];
13336 				tcp->tcp_urp_mp = mp1;
13337 #ifdef DEBUG
13338 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13339 				    "tcp_rput: allocated exdata_ind %s",
13340 				    tcp_display(tcp, NULL,
13341 				    DISP_PORT_ONLY));
13342 #endif /* DEBUG */
13343 				/*
13344 				 * There is no need to send a separate MSG*MARK
13345 				 * message since the T_EXDATA_IND will be sent
13346 				 * now.
13347 				 */
13348 				flags &= ~TH_SEND_URP_MARK;
13349 				freemsg(tcp->tcp_urp_mark_mp);
13350 				tcp->tcp_urp_mark_mp = NULL;
13351 			}
13352 			/*
13353 			 * Now we are all set.  On the next putnext upstream,
13354 			 * tcp_urp_mp will be non-NULL and will get prepended
13355 			 * to what has to be this piece containing the urgent
13356 			 * byte.  If for any reason we abort this segment below,
13357 			 * if it comes back, we will have this ready, or it
13358 			 * will get blown off in close.
13359 			 */
13360 		} else if (urp == seg_len) {
13361 			/*
13362 			 * The urgent byte is the next byte after this sequence
13363 			 * number. If there is data it is marked with
13364 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
13365 			 * since it is not needed. Otherwise, if the code
13366 			 * above just allocated a zero-length tcp_urp_mark_mp
13367 			 * message, that message is tagged with MSGMARKNEXT.
13368 			 * Sending up these MSGMARKNEXT messages makes
13369 			 * SIOCATMARK work correctly even though
13370 			 * the T_EXDATA_IND will not be sent up until the
13371 			 * urgent byte arrives.
13372 			 */
13373 			if (seg_len != 0) {
13374 				flags |= TH_MARKNEXT_NEEDED;
13375 				freemsg(tcp->tcp_urp_mark_mp);
13376 				tcp->tcp_urp_mark_mp = NULL;
13377 				flags &= ~TH_SEND_URP_MARK;
13378 			} else if (tcp->tcp_urp_mark_mp != NULL) {
13379 				flags |= TH_SEND_URP_MARK;
13380 				tcp->tcp_urp_mark_mp->b_flag &=
13381 					~MSGNOTMARKNEXT;
13382 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
13383 			}
13384 #ifdef DEBUG
13385 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13386 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
13387 			    seg_len, flags,
13388 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13389 #endif /* DEBUG */
13390 		} else {
13391 			/* Data left until we hit mark */
13392 #ifdef DEBUG
13393 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13394 			    "tcp_rput: URP %d bytes left, %s",
13395 			    urp - seg_len, tcp_display(tcp, NULL,
13396 			    DISP_PORT_ONLY));
13397 #endif /* DEBUG */
13398 		}
13399 	}
13400 
13401 process_ack:
13402 	if (!(flags & TH_ACK)) {
13403 		freemsg(mp);
13404 		goto xmit_check;
13405 	}
13406 	}
13407 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
13408 
13409 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
13410 		tcp->tcp_ip_forward_progress = B_TRUE;
13411 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
13412 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
13413 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
13414 			/* 3-way handshake complete - pass up the T_CONN_IND */
13415 			tcp_t	*listener = tcp->tcp_listener;
13416 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
13417 
13418 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
13419 			/*
13420 			 * We are here means eager is fine but it can
13421 			 * get a TH_RST at any point between now and till
13422 			 * accept completes and disappear. We need to
13423 			 * ensure that reference to eager is valid after
13424 			 * we get out of eager's perimeter. So we do
13425 			 * an extra refhold.
13426 			 */
13427 			CONN_INC_REF(connp);
13428 
13429 			/*
13430 			 * The listener also exists because of the refhold
13431 			 * done in tcp_conn_request. Its possible that it
13432 			 * might have closed. We will check that once we
13433 			 * get inside listeners context.
13434 			 */
13435 			CONN_INC_REF(listener->tcp_connp);
13436 			if (listener->tcp_connp->conn_sqp ==
13437 			    connp->conn_sqp) {
13438 				tcp_send_conn_ind(listener->tcp_connp, mp,
13439 				    listener->tcp_connp->conn_sqp);
13440 				CONN_DEC_REF(listener->tcp_connp);
13441 			} else if (!tcp->tcp_loopback) {
13442 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
13443 				    tcp_send_conn_ind,
13444 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
13445 			} else {
13446 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
13447 				    tcp_send_conn_ind, listener->tcp_connp,
13448 				    SQTAG_TCP_CONN_IND);
13449 			}
13450 		}
13451 
13452 		if (tcp->tcp_active_open) {
13453 			/*
13454 			 * We are seeing the final ack in the three way
13455 			 * hand shake of a active open'ed connection
13456 			 * so we must send up a T_CONN_CON
13457 			 */
13458 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
13459 				freemsg(mp);
13460 				return;
13461 			}
13462 			/*
13463 			 * Don't fuse the loopback endpoints for
13464 			 * simultaneous active opens.
13465 			 */
13466 			if (tcp->tcp_loopback) {
13467 				TCP_STAT(tcp_fusion_unfusable);
13468 				tcp->tcp_unfusable = B_TRUE;
13469 			}
13470 		}
13471 
13472 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
13473 		bytes_acked--;
13474 		/* SYN was acked - making progress */
13475 		if (tcp->tcp_ipversion == IPV6_VERSION)
13476 			tcp->tcp_ip_forward_progress = B_TRUE;
13477 
13478 		/*
13479 		 * If SYN was retransmitted, need to reset all
13480 		 * retransmission info as this segment will be
13481 		 * treated as a dup ACK.
13482 		 */
13483 		if (tcp->tcp_rexmit) {
13484 			tcp->tcp_rexmit = B_FALSE;
13485 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13486 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
13487 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13488 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13489 			tcp->tcp_ms_we_have_waited = 0;
13490 			tcp->tcp_cwnd = mss;
13491 		}
13492 
13493 		/*
13494 		 * We set the send window to zero here.
13495 		 * This is needed if there is data to be
13496 		 * processed already on the queue.
13497 		 * Later (at swnd_update label), the
13498 		 * "new_swnd > tcp_swnd" condition is satisfied
13499 		 * the XMIT_NEEDED flag is set in the current
13500 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
13501 		 * called if there is already data on queue in
13502 		 * this state.
13503 		 */
13504 		tcp->tcp_swnd = 0;
13505 
13506 		if (new_swnd > tcp->tcp_max_swnd)
13507 			tcp->tcp_max_swnd = new_swnd;
13508 		tcp->tcp_swl1 = seg_seq;
13509 		tcp->tcp_swl2 = seg_ack;
13510 		tcp->tcp_state = TCPS_ESTABLISHED;
13511 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13512 
13513 		/* Fuse when both sides are in ESTABLISHED state */
13514 		if (tcp->tcp_loopback && do_tcp_fusion)
13515 			tcp_fuse(tcp, iphdr, tcph);
13516 
13517 	}
13518 	/* This code follows 4.4BSD-Lite2 mostly. */
13519 	if (bytes_acked < 0)
13520 		goto est;
13521 
13522 	/*
13523 	 * If TCP is ECN capable and the congestion experience bit is
13524 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
13525 	 * done once per window (or more loosely, per RTT).
13526 	 */
13527 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
13528 		tcp->tcp_cwr = B_FALSE;
13529 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
13530 		if (!tcp->tcp_cwr) {
13531 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
13532 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
13533 			tcp->tcp_cwnd = npkt * mss;
13534 			/*
13535 			 * If the cwnd is 0, use the timer to clock out
13536 			 * new segments.  This is required by the ECN spec.
13537 			 */
13538 			if (npkt == 0) {
13539 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13540 				/*
13541 				 * This makes sure that when the ACK comes
13542 				 * back, we will increase tcp_cwnd by 1 MSS.
13543 				 */
13544 				tcp->tcp_cwnd_cnt = 0;
13545 			}
13546 			tcp->tcp_cwr = B_TRUE;
13547 			/*
13548 			 * This marks the end of the current window of in
13549 			 * flight data.  That is why we don't use
13550 			 * tcp_suna + tcp_swnd.  Only data in flight can
13551 			 * provide ECN info.
13552 			 */
13553 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13554 			tcp->tcp_ecn_cwr_sent = B_FALSE;
13555 		}
13556 	}
13557 
13558 	mp1 = tcp->tcp_xmit_head;
13559 	if (bytes_acked == 0) {
13560 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
13561 			int dupack_cnt;
13562 
13563 			BUMP_MIB(&tcp_mib, tcpInDupAck);
13564 			/*
13565 			 * Fast retransmit.  When we have seen exactly three
13566 			 * identical ACKs while we have unacked data
13567 			 * outstanding we take it as a hint that our peer
13568 			 * dropped something.
13569 			 *
13570 			 * If TCP is retransmitting, don't do fast retransmit.
13571 			 */
13572 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
13573 			    ! tcp->tcp_rexmit) {
13574 				/* Do Limited Transmit */
13575 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
13576 				    tcp_dupack_fast_retransmit) {
13577 					/*
13578 					 * RFC 3042
13579 					 *
13580 					 * What we need to do is temporarily
13581 					 * increase tcp_cwnd so that new
13582 					 * data can be sent if it is allowed
13583 					 * by the receive window (tcp_rwnd).
13584 					 * tcp_wput_data() will take care of
13585 					 * the rest.
13586 					 *
13587 					 * If the connection is SACK capable,
13588 					 * only do limited xmit when there
13589 					 * is SACK info.
13590 					 *
13591 					 * Note how tcp_cwnd is incremented.
13592 					 * The first dup ACK will increase
13593 					 * it by 1 MSS.  The second dup ACK
13594 					 * will increase it by 2 MSS.  This
13595 					 * means that only 1 new segment will
13596 					 * be sent for each dup ACK.
13597 					 */
13598 					if (tcp->tcp_unsent > 0 &&
13599 					    (!tcp->tcp_snd_sack_ok ||
13600 					    (tcp->tcp_snd_sack_ok &&
13601 					    tcp->tcp_notsack_list != NULL))) {
13602 						tcp->tcp_cwnd += mss <<
13603 						    (tcp->tcp_dupack_cnt - 1);
13604 						flags |= TH_LIMIT_XMIT;
13605 					}
13606 				} else if (dupack_cnt ==
13607 				    tcp_dupack_fast_retransmit) {
13608 
13609 				/*
13610 				 * If we have reduced tcp_ssthresh
13611 				 * because of ECN, do not reduce it again
13612 				 * unless it is already one window of data
13613 				 * away.  After one window of data, tcp_cwr
13614 				 * should then be cleared.  Note that
13615 				 * for non ECN capable connection, tcp_cwr
13616 				 * should always be false.
13617 				 *
13618 				 * Adjust cwnd since the duplicate
13619 				 * ack indicates that a packet was
13620 				 * dropped (due to congestion.)
13621 				 */
13622 				if (!tcp->tcp_cwr) {
13623 					npkt = ((tcp->tcp_snxt -
13624 					    tcp->tcp_suna) >> 1) / mss;
13625 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13626 					    mss;
13627 					tcp->tcp_cwnd = (npkt +
13628 					    tcp->tcp_dupack_cnt) * mss;
13629 				}
13630 				if (tcp->tcp_ecn_ok) {
13631 					tcp->tcp_cwr = B_TRUE;
13632 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13633 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13634 				}
13635 
13636 				/*
13637 				 * We do Hoe's algorithm.  Refer to her
13638 				 * paper "Improving the Start-up Behavior
13639 				 * of a Congestion Control Scheme for TCP,"
13640 				 * appeared in SIGCOMM'96.
13641 				 *
13642 				 * Save highest seq no we have sent so far.
13643 				 * Be careful about the invisible FIN byte.
13644 				 */
13645 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13646 				    (tcp->tcp_unsent == 0)) {
13647 					tcp->tcp_rexmit_max = tcp->tcp_fss;
13648 				} else {
13649 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
13650 				}
13651 
13652 				/*
13653 				 * Do not allow bursty traffic during.
13654 				 * fast recovery.  Refer to Fall and Floyd's
13655 				 * paper "Simulation-based Comparisons of
13656 				 * Tahoe, Reno and SACK TCP" (in CCR?)
13657 				 * This is a best current practise.
13658 				 */
13659 				tcp->tcp_snd_burst = TCP_CWND_SS;
13660 
13661 				/*
13662 				 * For SACK:
13663 				 * Calculate tcp_pipe, which is the
13664 				 * estimated number of bytes in
13665 				 * network.
13666 				 *
13667 				 * tcp_fack is the highest sack'ed seq num
13668 				 * TCP has received.
13669 				 *
13670 				 * tcp_pipe is explained in the above quoted
13671 				 * Fall and Floyd's paper.  tcp_fack is
13672 				 * explained in Mathis and Mahdavi's
13673 				 * "Forward Acknowledgment: Refining TCP
13674 				 * Congestion Control" in SIGCOMM '96.
13675 				 */
13676 				if (tcp->tcp_snd_sack_ok) {
13677 					ASSERT(tcp->tcp_sack_info != NULL);
13678 					if (tcp->tcp_notsack_list != NULL) {
13679 						tcp->tcp_pipe = tcp->tcp_snxt -
13680 						    tcp->tcp_fack;
13681 						tcp->tcp_sack_snxt = seg_ack;
13682 						flags |= TH_NEED_SACK_REXMIT;
13683 					} else {
13684 						/*
13685 						 * Always initialize tcp_pipe
13686 						 * even though we don't have
13687 						 * any SACK info.  If later
13688 						 * we get SACK info and
13689 						 * tcp_pipe is not initialized,
13690 						 * funny things will happen.
13691 						 */
13692 						tcp->tcp_pipe =
13693 						    tcp->tcp_cwnd_ssthresh;
13694 					}
13695 				} else {
13696 					flags |= TH_REXMIT_NEEDED;
13697 				} /* tcp_snd_sack_ok */
13698 
13699 				} else {
13700 					/*
13701 					 * Here we perform congestion
13702 					 * avoidance, but NOT slow start.
13703 					 * This is known as the Fast
13704 					 * Recovery Algorithm.
13705 					 */
13706 					if (tcp->tcp_snd_sack_ok &&
13707 					    tcp->tcp_notsack_list != NULL) {
13708 						flags |= TH_NEED_SACK_REXMIT;
13709 						tcp->tcp_pipe -= mss;
13710 						if (tcp->tcp_pipe < 0)
13711 							tcp->tcp_pipe = 0;
13712 					} else {
13713 					/*
13714 					 * We know that one more packet has
13715 					 * left the pipe thus we can update
13716 					 * cwnd.
13717 					 */
13718 					cwnd = tcp->tcp_cwnd + mss;
13719 					if (cwnd > tcp->tcp_cwnd_max)
13720 						cwnd = tcp->tcp_cwnd_max;
13721 					tcp->tcp_cwnd = cwnd;
13722 					if (tcp->tcp_unsent > 0)
13723 						flags |= TH_XMIT_NEEDED;
13724 					}
13725 				}
13726 			}
13727 		} else if (tcp->tcp_zero_win_probe) {
13728 			/*
13729 			 * If the window has opened, need to arrange
13730 			 * to send additional data.
13731 			 */
13732 			if (new_swnd != 0) {
13733 				/* tcp_suna != tcp_snxt */
13734 				/* Packet contains a window update */
13735 				BUMP_MIB(&tcp_mib, tcpInWinUpdate);
13736 				tcp->tcp_zero_win_probe = 0;
13737 				tcp->tcp_timer_backoff = 0;
13738 				tcp->tcp_ms_we_have_waited = 0;
13739 
13740 				/*
13741 				 * Transmit starting with tcp_suna since
13742 				 * the one byte probe is not ack'ed.
13743 				 * If TCP has sent more than one identical
13744 				 * probe, tcp_rexmit will be set.  That means
13745 				 * tcp_ss_rexmit() will send out the one
13746 				 * byte along with new data.  Otherwise,
13747 				 * fake the retransmission.
13748 				 */
13749 				flags |= TH_XMIT_NEEDED;
13750 				if (!tcp->tcp_rexmit) {
13751 					tcp->tcp_rexmit = B_TRUE;
13752 					tcp->tcp_dupack_cnt = 0;
13753 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13754 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
13755 				}
13756 			}
13757 		}
13758 		goto swnd_update;
13759 	}
13760 
13761 	/*
13762 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
13763 	 * If the ACK value acks something that we have not yet sent, it might
13764 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
13765 	 * other side.
13766 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
13767 	 * state is handled above, so we can always just drop the segment and
13768 	 * send an ACK here.
13769 	 *
13770 	 * Should we send ACKs in response to ACK only segments?
13771 	 */
13772 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13773 		BUMP_MIB(&tcp_mib, tcpInAckUnsent);
13774 		/* drop the received segment */
13775 		freemsg(mp);
13776 
13777 		/*
13778 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
13779 		 * greater than 0, check if the number of such
13780 		 * bogus ACks is greater than that count.  If yes,
13781 		 * don't send back any ACK.  This prevents TCP from
13782 		 * getting into an ACK storm if somehow an attacker
13783 		 * successfully spoofs an acceptable segment to our
13784 		 * peer.
13785 		 */
13786 		if (tcp_drop_ack_unsent_cnt > 0 &&
13787 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
13788 			TCP_STAT(tcp_in_ack_unsent_drop);
13789 			return;
13790 		}
13791 		mp = tcp_ack_mp(tcp);
13792 		if (mp != NULL) {
13793 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
13794 			BUMP_LOCAL(tcp->tcp_obsegs);
13795 			BUMP_MIB(&tcp_mib, tcpOutAck);
13796 			tcp_send_data(tcp, tcp->tcp_wq, mp);
13797 		}
13798 		return;
13799 	}
13800 
13801 	/*
13802 	 * TCP gets a new ACK, update the notsack'ed list to delete those
13803 	 * blocks that are covered by this ACK.
13804 	 */
13805 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
13806 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
13807 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
13808 	}
13809 
13810 	/*
13811 	 * If we got an ACK after fast retransmit, check to see
13812 	 * if it is a partial ACK.  If it is not and the congestion
13813 	 * window was inflated to account for the other side's
13814 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
13815 	 */
13816 	if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) {
13817 		ASSERT(tcp->tcp_rexmit == B_FALSE);
13818 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
13819 			tcp->tcp_dupack_cnt = 0;
13820 			/*
13821 			 * Restore the orig tcp_cwnd_ssthresh after
13822 			 * fast retransmit phase.
13823 			 */
13824 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
13825 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
13826 			}
13827 			tcp->tcp_rexmit_max = seg_ack;
13828 			tcp->tcp_cwnd_cnt = 0;
13829 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
13830 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13831 
13832 			/*
13833 			 * Remove all notsack info to avoid confusion with
13834 			 * the next fast retrasnmit/recovery phase.
13835 			 */
13836 			if (tcp->tcp_snd_sack_ok &&
13837 			    tcp->tcp_notsack_list != NULL) {
13838 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
13839 			}
13840 		} else {
13841 			if (tcp->tcp_snd_sack_ok &&
13842 			    tcp->tcp_notsack_list != NULL) {
13843 				flags |= TH_NEED_SACK_REXMIT;
13844 				tcp->tcp_pipe -= mss;
13845 				if (tcp->tcp_pipe < 0)
13846 					tcp->tcp_pipe = 0;
13847 			} else {
13848 				/*
13849 				 * Hoe's algorithm:
13850 				 *
13851 				 * Retransmit the unack'ed segment and
13852 				 * restart fast recovery.  Note that we
13853 				 * need to scale back tcp_cwnd to the
13854 				 * original value when we started fast
13855 				 * recovery.  This is to prevent overly
13856 				 * aggressive behaviour in sending new
13857 				 * segments.
13858 				 */
13859 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
13860 					tcp_dupack_fast_retransmit * mss;
13861 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
13862 				flags |= TH_REXMIT_NEEDED;
13863 			}
13864 		}
13865 	} else {
13866 		tcp->tcp_dupack_cnt = 0;
13867 		if (tcp->tcp_rexmit) {
13868 			/*
13869 			 * TCP is retranmitting.  If the ACK ack's all
13870 			 * outstanding data, update tcp_rexmit_max and
13871 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
13872 			 * to the correct value.
13873 			 *
13874 			 * Note that SEQ_LEQ() is used.  This is to avoid
13875 			 * unnecessary fast retransmit caused by dup ACKs
13876 			 * received when TCP does slow start retransmission
13877 			 * after a time out.  During this phase, TCP may
13878 			 * send out segments which are already received.
13879 			 * This causes dup ACKs to be sent back.
13880 			 */
13881 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
13882 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
13883 					tcp->tcp_rexmit_nxt = seg_ack;
13884 				}
13885 				if (seg_ack != tcp->tcp_rexmit_max) {
13886 					flags |= TH_XMIT_NEEDED;
13887 				}
13888 			} else {
13889 				tcp->tcp_rexmit = B_FALSE;
13890 				tcp->tcp_xmit_zc_clean = B_FALSE;
13891 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13892 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13893 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13894 			}
13895 			tcp->tcp_ms_we_have_waited = 0;
13896 		}
13897 	}
13898 
13899 	BUMP_MIB(&tcp_mib, tcpInAckSegs);
13900 	UPDATE_MIB(&tcp_mib, tcpInAckBytes, bytes_acked);
13901 	tcp->tcp_suna = seg_ack;
13902 	if (tcp->tcp_zero_win_probe != 0) {
13903 		tcp->tcp_zero_win_probe = 0;
13904 		tcp->tcp_timer_backoff = 0;
13905 	}
13906 
13907 	/*
13908 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
13909 	 * Note that it cannot be the SYN being ack'ed.  The code flow
13910 	 * will not reach here.
13911 	 */
13912 	if (mp1 == NULL) {
13913 		goto fin_acked;
13914 	}
13915 
13916 	/*
13917 	 * Update the congestion window.
13918 	 *
13919 	 * If TCP is not ECN capable or TCP is ECN capable but the
13920 	 * congestion experience bit is not set, increase the tcp_cwnd as
13921 	 * usual.
13922 	 */
13923 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
13924 		cwnd = tcp->tcp_cwnd;
13925 		add = mss;
13926 
13927 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
13928 			/*
13929 			 * This is to prevent an increase of less than 1 MSS of
13930 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
13931 			 * may send out tinygrams in order to preserve mblk
13932 			 * boundaries.
13933 			 *
13934 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
13935 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
13936 			 * increased by 1 MSS for every RTTs.
13937 			 */
13938 			if (tcp->tcp_cwnd_cnt <= 0) {
13939 				tcp->tcp_cwnd_cnt = cwnd + add;
13940 			} else {
13941 				tcp->tcp_cwnd_cnt -= add;
13942 				add = 0;
13943 			}
13944 		}
13945 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
13946 	}
13947 
13948 	/* See if the latest urgent data has been acknowledged */
13949 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
13950 	    SEQ_GT(seg_ack, tcp->tcp_urg))
13951 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
13952 
13953 	/* Can we update the RTT estimates? */
13954 	if (tcp->tcp_snd_ts_ok) {
13955 		/* Ignore zero timestamp echo-reply. */
13956 		if (tcpopt.tcp_opt_ts_ecr != 0) {
13957 			tcp_set_rto(tcp, (int32_t)lbolt -
13958 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
13959 		}
13960 
13961 		/* If needed, restart the timer. */
13962 		if (tcp->tcp_set_timer == 1) {
13963 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13964 			tcp->tcp_set_timer = 0;
13965 		}
13966 		/*
13967 		 * Update tcp_csuna in case the other side stops sending
13968 		 * us timestamps.
13969 		 */
13970 		tcp->tcp_csuna = tcp->tcp_snxt;
13971 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
13972 		/*
13973 		 * An ACK sequence we haven't seen before, so get the RTT
13974 		 * and update the RTO. But first check if the timestamp is
13975 		 * valid to use.
13976 		 */
13977 		if ((mp1->b_next != NULL) &&
13978 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
13979 			tcp_set_rto(tcp, (int32_t)lbolt -
13980 			    (int32_t)(intptr_t)mp1->b_prev);
13981 		else
13982 			BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13983 
13984 		/* Remeber the last sequence to be ACKed */
13985 		tcp->tcp_csuna = seg_ack;
13986 		if (tcp->tcp_set_timer == 1) {
13987 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13988 			tcp->tcp_set_timer = 0;
13989 		}
13990 	} else {
13991 		BUMP_MIB(&tcp_mib, tcpRttNoUpdate);
13992 	}
13993 
13994 	/* Eat acknowledged bytes off the xmit queue. */
13995 	for (;;) {
13996 		mblk_t	*mp2;
13997 		uchar_t	*wptr;
13998 
13999 		wptr = mp1->b_wptr;
14000 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14001 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14002 		if (bytes_acked < 0) {
14003 			mp1->b_rptr = wptr + bytes_acked;
14004 			/*
14005 			 * Set a new timestamp if all the bytes timed by the
14006 			 * old timestamp have been ack'ed.
14007 			 */
14008 			if (SEQ_GT(seg_ack,
14009 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14010 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14011 				mp1->b_next = NULL;
14012 			}
14013 			break;
14014 		}
14015 		mp1->b_next = NULL;
14016 		mp1->b_prev = NULL;
14017 		mp2 = mp1;
14018 		mp1 = mp1->b_cont;
14019 
14020 		/*
14021 		 * This notification is required for some zero-copy
14022 		 * clients to maintain a copy semantic. After the data
14023 		 * is ack'ed, client is safe to modify or reuse the buffer.
14024 		 */
14025 		if (tcp->tcp_snd_zcopy_aware &&
14026 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14027 			tcp_zcopy_notify(tcp);
14028 		freeb(mp2);
14029 		if (bytes_acked == 0) {
14030 			if (mp1 == NULL) {
14031 				/* Everything is ack'ed, clear the tail. */
14032 				tcp->tcp_xmit_tail = NULL;
14033 				/*
14034 				 * Cancel the timer unless we are still
14035 				 * waiting for an ACK for the FIN packet.
14036 				 */
14037 				if (tcp->tcp_timer_tid != 0 &&
14038 				    tcp->tcp_snxt == tcp->tcp_suna) {
14039 					(void) TCP_TIMER_CANCEL(tcp,
14040 					    tcp->tcp_timer_tid);
14041 					tcp->tcp_timer_tid = 0;
14042 				}
14043 				goto pre_swnd_update;
14044 			}
14045 			if (mp2 != tcp->tcp_xmit_tail)
14046 				break;
14047 			tcp->tcp_xmit_tail = mp1;
14048 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14049 			    (uintptr_t)INT_MAX);
14050 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14051 			    mp1->b_rptr);
14052 			break;
14053 		}
14054 		if (mp1 == NULL) {
14055 			/*
14056 			 * More was acked but there is nothing more
14057 			 * outstanding.  This means that the FIN was
14058 			 * just acked or that we're talking to a clown.
14059 			 */
14060 fin_acked:
14061 			ASSERT(tcp->tcp_fin_sent);
14062 			tcp->tcp_xmit_tail = NULL;
14063 			if (tcp->tcp_fin_sent) {
14064 				/* FIN was acked - making progress */
14065 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14066 				    !tcp->tcp_fin_acked)
14067 					tcp->tcp_ip_forward_progress = B_TRUE;
14068 				tcp->tcp_fin_acked = B_TRUE;
14069 				if (tcp->tcp_linger_tid != 0 &&
14070 				    TCP_TIMER_CANCEL(tcp,
14071 					tcp->tcp_linger_tid) >= 0) {
14072 					tcp_stop_lingering(tcp);
14073 				}
14074 			} else {
14075 				/*
14076 				 * We should never get here because
14077 				 * we have already checked that the
14078 				 * number of bytes ack'ed should be
14079 				 * smaller than or equal to what we
14080 				 * have sent so far (it is the
14081 				 * acceptability check of the ACK).
14082 				 * We can only get here if the send
14083 				 * queue is corrupted.
14084 				 *
14085 				 * Terminate the connection and
14086 				 * panic the system.  It is better
14087 				 * for us to panic instead of
14088 				 * continuing to avoid other disaster.
14089 				 */
14090 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14091 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14092 				panic("Memory corruption "
14093 				    "detected for connection %s.",
14094 				    tcp_display(tcp, NULL,
14095 					DISP_ADDR_AND_PORT));
14096 				/*NOTREACHED*/
14097 			}
14098 			goto pre_swnd_update;
14099 		}
14100 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14101 	}
14102 	if (tcp->tcp_unsent) {
14103 		flags |= TH_XMIT_NEEDED;
14104 	}
14105 pre_swnd_update:
14106 	tcp->tcp_xmit_head = mp1;
14107 swnd_update:
14108 	/*
14109 	 * The following check is different from most other implementations.
14110 	 * For bi-directional transfer, when segments are dropped, the
14111 	 * "normal" check will not accept a window update in those
14112 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14113 	 * segments which are outside receiver's window.  As TCP accepts
14114 	 * the ack in those retransmitted segments, if the window update in
14115 	 * the same segment is not accepted, TCP will incorrectly calculates
14116 	 * that it can send more segments.  This can create a deadlock
14117 	 * with the receiver if its window becomes zero.
14118 	 */
14119 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14120 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14121 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14122 		/*
14123 		 * The criteria for update is:
14124 		 *
14125 		 * 1. the segment acknowledges some data.  Or
14126 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14127 		 * 3. the segment is not old and the advertised window is
14128 		 * larger than the previous advertised window.
14129 		 */
14130 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14131 			flags |= TH_XMIT_NEEDED;
14132 		tcp->tcp_swnd = new_swnd;
14133 		if (new_swnd > tcp->tcp_max_swnd)
14134 			tcp->tcp_max_swnd = new_swnd;
14135 		tcp->tcp_swl1 = seg_seq;
14136 		tcp->tcp_swl2 = seg_ack;
14137 	}
14138 est:
14139 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14140 
14141 		switch (tcp->tcp_state) {
14142 		case TCPS_FIN_WAIT_1:
14143 			if (tcp->tcp_fin_acked) {
14144 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14145 				/*
14146 				 * We implement the non-standard BSD/SunOS
14147 				 * FIN_WAIT_2 flushing algorithm.
14148 				 * If there is no user attached to this
14149 				 * TCP endpoint, then this TCP struct
14150 				 * could hang around forever in FIN_WAIT_2
14151 				 * state if the peer forgets to send us
14152 				 * a FIN.  To prevent this, we wait only
14153 				 * 2*MSL (a convenient time value) for
14154 				 * the FIN to arrive.  If it doesn't show up,
14155 				 * we flush the TCP endpoint.  This algorithm,
14156 				 * though a violation of RFC-793, has worked
14157 				 * for over 10 years in BSD systems.
14158 				 * Note: SunOS 4.x waits 675 seconds before
14159 				 * flushing the FIN_WAIT_2 connection.
14160 				 */
14161 				TCP_TIMER_RESTART(tcp,
14162 				    tcp_fin_wait_2_flush_interval);
14163 			}
14164 			break;
14165 		case TCPS_FIN_WAIT_2:
14166 			break;	/* Shutdown hook? */
14167 		case TCPS_LAST_ACK:
14168 			freemsg(mp);
14169 			if (tcp->tcp_fin_acked) {
14170 				(void) tcp_clean_death(tcp, 0, 19);
14171 				return;
14172 			}
14173 			goto xmit_check;
14174 		case TCPS_CLOSING:
14175 			if (tcp->tcp_fin_acked) {
14176 				tcp->tcp_state = TCPS_TIME_WAIT;
14177 				if (!TCP_IS_DETACHED(tcp)) {
14178 					TCP_TIMER_RESTART(tcp,
14179 					    tcp_time_wait_interval);
14180 				} else {
14181 					tcp_time_wait_append(tcp);
14182 					TCP_DBGSTAT(tcp_rput_time_wait);
14183 				}
14184 			}
14185 			/*FALLTHRU*/
14186 		case TCPS_CLOSE_WAIT:
14187 			freemsg(mp);
14188 			goto xmit_check;
14189 		default:
14190 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14191 			break;
14192 		}
14193 	}
14194 	if (flags & TH_FIN) {
14195 		/* Make sure we ack the fin */
14196 		flags |= TH_ACK_NEEDED;
14197 		if (!tcp->tcp_fin_rcvd) {
14198 			tcp->tcp_fin_rcvd = B_TRUE;
14199 			tcp->tcp_rnxt++;
14200 			tcph = tcp->tcp_tcph;
14201 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14202 
14203 			/*
14204 			 * Generate the ordrel_ind at the end unless we
14205 			 * are an eager guy.
14206 			 * In the eager case tcp_rsrv will do this when run
14207 			 * after tcp_accept is done.
14208 			 */
14209 			if (tcp->tcp_listener == NULL &&
14210 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14211 				flags |= TH_ORDREL_NEEDED;
14212 			switch (tcp->tcp_state) {
14213 			case TCPS_SYN_RCVD:
14214 			case TCPS_ESTABLISHED:
14215 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14216 				/* Keepalive? */
14217 				break;
14218 			case TCPS_FIN_WAIT_1:
14219 				if (!tcp->tcp_fin_acked) {
14220 					tcp->tcp_state = TCPS_CLOSING;
14221 					break;
14222 				}
14223 				/* FALLTHRU */
14224 			case TCPS_FIN_WAIT_2:
14225 				tcp->tcp_state = TCPS_TIME_WAIT;
14226 				if (!TCP_IS_DETACHED(tcp)) {
14227 					TCP_TIMER_RESTART(tcp,
14228 					    tcp_time_wait_interval);
14229 				} else {
14230 					tcp_time_wait_append(tcp);
14231 					TCP_DBGSTAT(tcp_rput_time_wait);
14232 				}
14233 				if (seg_len) {
14234 					/*
14235 					 * implies data piggybacked on FIN.
14236 					 * break to handle data.
14237 					 */
14238 					break;
14239 				}
14240 				freemsg(mp);
14241 				goto ack_check;
14242 			}
14243 		}
14244 	}
14245 	if (mp == NULL)
14246 		goto xmit_check;
14247 	if (seg_len == 0) {
14248 		freemsg(mp);
14249 		goto xmit_check;
14250 	}
14251 	if (mp->b_rptr == mp->b_wptr) {
14252 		/*
14253 		 * The header has been consumed, so we remove the
14254 		 * zero-length mblk here.
14255 		 */
14256 		mp1 = mp;
14257 		mp = mp->b_cont;
14258 		freeb(mp1);
14259 	}
14260 	tcph = tcp->tcp_tcph;
14261 	tcp->tcp_rack_cnt++;
14262 	{
14263 		uint32_t cur_max;
14264 
14265 		cur_max = tcp->tcp_rack_cur_max;
14266 		if (tcp->tcp_rack_cnt >= cur_max) {
14267 			/*
14268 			 * We have more unacked data than we should - send
14269 			 * an ACK now.
14270 			 */
14271 			flags |= TH_ACK_NEEDED;
14272 			cur_max++;
14273 			if (cur_max > tcp->tcp_rack_abs_max)
14274 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14275 			else
14276 				tcp->tcp_rack_cur_max = cur_max;
14277 		} else if (TCP_IS_DETACHED(tcp)) {
14278 			/* We don't have an ACK timer for detached TCP. */
14279 			flags |= TH_ACK_NEEDED;
14280 		} else if (seg_len < mss) {
14281 			/*
14282 			 * If we get a segment that is less than an mss, and we
14283 			 * already have unacknowledged data, and the amount
14284 			 * unacknowledged is not a multiple of mss, then we
14285 			 * better generate an ACK now.  Otherwise, this may be
14286 			 * the tail piece of a transaction, and we would rather
14287 			 * wait for the response.
14288 			 */
14289 			uint32_t udif;
14290 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14291 			    (uintptr_t)INT_MAX);
14292 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14293 			if (udif && (udif % mss))
14294 				flags |= TH_ACK_NEEDED;
14295 			else
14296 				flags |= TH_ACK_TIMER_NEEDED;
14297 		} else {
14298 			/* Start delayed ack timer */
14299 			flags |= TH_ACK_TIMER_NEEDED;
14300 		}
14301 	}
14302 	tcp->tcp_rnxt += seg_len;
14303 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14304 
14305 	/* Update SACK list */
14306 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
14307 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
14308 		    &(tcp->tcp_num_sack_blk));
14309 	}
14310 
14311 	if (tcp->tcp_urp_mp) {
14312 		tcp->tcp_urp_mp->b_cont = mp;
14313 		mp = tcp->tcp_urp_mp;
14314 		tcp->tcp_urp_mp = NULL;
14315 		/* Ready for a new signal. */
14316 		tcp->tcp_urp_last_valid = B_FALSE;
14317 #ifdef DEBUG
14318 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14319 		    "tcp_rput: sending exdata_ind %s",
14320 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14321 #endif /* DEBUG */
14322 	}
14323 
14324 	/*
14325 	 * Check for ancillary data changes compared to last segment.
14326 	 */
14327 	if (tcp->tcp_ipv6_recvancillary != 0) {
14328 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
14329 		if (mp == NULL)
14330 			return;
14331 	}
14332 
14333 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
14334 		/*
14335 		 * Side queue inbound data until the accept happens.
14336 		 * tcp_accept/tcp_rput drains this when the accept happens.
14337 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
14338 		 * T_EXDATA_IND) it is queued on b_next.
14339 		 * XXX Make urgent data use this. Requires:
14340 		 *	Removing tcp_listener check for TH_URG
14341 		 *	Making M_PCPROTO and MARK messages skip the eager case
14342 		 */
14343 
14344 		if (tcp->tcp_kssl_pending) {
14345 			tcp_kssl_input(tcp, mp);
14346 		} else {
14347 			tcp_rcv_enqueue(tcp, mp, seg_len);
14348 		}
14349 	} else {
14350 		if (mp->b_datap->db_type != M_DATA ||
14351 		    (flags & TH_MARKNEXT_NEEDED)) {
14352 			if (tcp->tcp_rcv_list != NULL) {
14353 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14354 			}
14355 			ASSERT(tcp->tcp_rcv_list == NULL ||
14356 			    tcp->tcp_fused_sigurg);
14357 			if (flags & TH_MARKNEXT_NEEDED) {
14358 #ifdef DEBUG
14359 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14360 				    "tcp_rput: sending MSGMARKNEXT %s",
14361 				    tcp_display(tcp, NULL,
14362 				    DISP_PORT_ONLY));
14363 #endif /* DEBUG */
14364 				mp->b_flag |= MSGMARKNEXT;
14365 				flags &= ~TH_MARKNEXT_NEEDED;
14366 			}
14367 
14368 			/* Does this need SSL processing first? */
14369 			if ((tcp->tcp_kssl_ctx  != NULL) &&
14370 			    (DB_TYPE(mp) == M_DATA)) {
14371 				tcp_kssl_input(tcp, mp);
14372 			} else {
14373 				putnext(tcp->tcp_rq, mp);
14374 				if (!canputnext(tcp->tcp_rq))
14375 					tcp->tcp_rwnd -= seg_len;
14376 			}
14377 		} else if (((flags & (TH_PUSH|TH_FIN)) ||
14378 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) &&
14379 		    (sqp != NULL)) {
14380 			if (tcp->tcp_rcv_list != NULL) {
14381 				/*
14382 				 * Enqueue the new segment first and then
14383 				 * call tcp_rcv_drain() to send all data
14384 				 * up.  The other way to do this is to
14385 				 * send all queued data up and then call
14386 				 * putnext() to send the new segment up.
14387 				 * This way can remove the else part later
14388 				 * on.
14389 				 *
14390 				 * We don't this to avoid one more call to
14391 				 * canputnext() as tcp_rcv_drain() needs to
14392 				 * call canputnext().
14393 				 */
14394 				tcp_rcv_enqueue(tcp, mp, seg_len);
14395 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14396 			} else {
14397 				/* Does this need SSL processing first? */
14398 				if ((tcp->tcp_kssl_ctx  != NULL) &&
14399 				    (DB_TYPE(mp) == M_DATA)) {
14400 					tcp_kssl_input(tcp, mp);
14401 				} else {
14402 					putnext(tcp->tcp_rq, mp);
14403 					if (!canputnext(tcp->tcp_rq))
14404 						tcp->tcp_rwnd -= seg_len;
14405 				}
14406 			}
14407 		} else {
14408 			/*
14409 			 * Enqueue all packets when processing an mblk
14410 			 * from the co queue and also enqueue normal packets.
14411 			 */
14412 			tcp_rcv_enqueue(tcp, mp, seg_len);
14413 		}
14414 		/*
14415 		 * Make sure the timer is running if we have data waiting
14416 		 * for a push bit. This provides resiliency against
14417 		 * implementations that do not correctly generate push bits.
14418 		 */
14419 		if ((sqp != NULL) && tcp->tcp_rcv_list != NULL &&
14420 		    tcp->tcp_push_tid == 0) {
14421 			/*
14422 			 * The connection may be closed at this point, so don't
14423 			 * do anything for a detached tcp.
14424 			 */
14425 			if (!TCP_IS_DETACHED(tcp))
14426 				tcp->tcp_push_tid = TCP_TIMER(tcp,
14427 				    tcp_push_timer,
14428 				    MSEC_TO_TICK(tcp_push_timer_interval));
14429 		}
14430 	}
14431 xmit_check:
14432 	/* Is there anything left to do? */
14433 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14434 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
14435 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
14436 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14437 		goto done;
14438 
14439 	/* Any transmit work to do and a non-zero window? */
14440 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
14441 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
14442 		if (flags & TH_REXMIT_NEEDED) {
14443 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
14444 
14445 			BUMP_MIB(&tcp_mib, tcpOutFastRetrans);
14446 			if (snd_size > mss)
14447 				snd_size = mss;
14448 			if (snd_size > tcp->tcp_swnd)
14449 				snd_size = tcp->tcp_swnd;
14450 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
14451 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
14452 			    B_TRUE);
14453 
14454 			if (mp1 != NULL) {
14455 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14456 				tcp->tcp_csuna = tcp->tcp_snxt;
14457 				BUMP_MIB(&tcp_mib, tcpRetransSegs);
14458 				UPDATE_MIB(&tcp_mib, tcpRetransBytes, snd_size);
14459 				TCP_RECORD_TRACE(tcp, mp1,
14460 				    TCP_TRACE_SEND_PKT);
14461 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
14462 			}
14463 		}
14464 		if (flags & TH_NEED_SACK_REXMIT) {
14465 			tcp_sack_rxmit(tcp, &flags);
14466 		}
14467 		/*
14468 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
14469 		 * out new segment.  Note that tcp_rexmit should not be
14470 		 * set, otherwise TH_LIMIT_XMIT should not be set.
14471 		 */
14472 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
14473 			if (!tcp->tcp_rexmit) {
14474 				tcp_wput_data(tcp, NULL, B_FALSE);
14475 			} else {
14476 				tcp_ss_rexmit(tcp);
14477 			}
14478 		}
14479 		/*
14480 		 * Adjust tcp_cwnd back to normal value after sending
14481 		 * new data segments.
14482 		 */
14483 		if (flags & TH_LIMIT_XMIT) {
14484 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
14485 			/*
14486 			 * This will restart the timer.  Restarting the
14487 			 * timer is used to avoid a timeout before the
14488 			 * limited transmitted segment's ACK gets back.
14489 			 */
14490 			if (tcp->tcp_xmit_head != NULL)
14491 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
14492 		}
14493 
14494 		/* Anything more to do? */
14495 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
14496 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
14497 			goto done;
14498 	}
14499 ack_check:
14500 	if (flags & TH_SEND_URP_MARK) {
14501 		ASSERT(tcp->tcp_urp_mark_mp);
14502 		/*
14503 		 * Send up any queued data and then send the mark message
14504 		 */
14505 		if (tcp->tcp_rcv_list != NULL) {
14506 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14507 		}
14508 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14509 
14510 		mp1 = tcp->tcp_urp_mark_mp;
14511 		tcp->tcp_urp_mark_mp = NULL;
14512 #ifdef DEBUG
14513 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14514 		    "tcp_rput: sending zero-length %s %s",
14515 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
14516 		    "MSGNOTMARKNEXT"),
14517 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14518 #endif /* DEBUG */
14519 		putnext(tcp->tcp_rq, mp1);
14520 		flags &= ~TH_SEND_URP_MARK;
14521 	}
14522 	if (flags & TH_ACK_NEEDED) {
14523 		/*
14524 		 * Time to send an ack for some reason.
14525 		 */
14526 		mp1 = tcp_ack_mp(tcp);
14527 
14528 		if (mp1 != NULL) {
14529 			TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
14530 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
14531 			BUMP_LOCAL(tcp->tcp_obsegs);
14532 			BUMP_MIB(&tcp_mib, tcpOutAck);
14533 		}
14534 		if (tcp->tcp_ack_tid != 0) {
14535 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
14536 			tcp->tcp_ack_tid = 0;
14537 		}
14538 	}
14539 	if (flags & TH_ACK_TIMER_NEEDED) {
14540 		/*
14541 		 * Arrange for deferred ACK or push wait timeout.
14542 		 * Start timer if it is not already running.
14543 		 */
14544 		if (tcp->tcp_ack_tid == 0) {
14545 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
14546 			    MSEC_TO_TICK(tcp->tcp_localnet ?
14547 			    (clock_t)tcp_local_dack_interval :
14548 			    (clock_t)tcp_deferred_ack_interval));
14549 		}
14550 	}
14551 	if (flags & TH_ORDREL_NEEDED) {
14552 		/*
14553 		 * Send up the ordrel_ind unless we are an eager guy.
14554 		 * In the eager case tcp_rsrv will do this when run
14555 		 * after tcp_accept is done.
14556 		 */
14557 		ASSERT(tcp->tcp_listener == NULL);
14558 		if (tcp->tcp_rcv_list != NULL) {
14559 			/*
14560 			 * Push any mblk(s) enqueued from co processing.
14561 			 */
14562 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
14563 		}
14564 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14565 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
14566 			tcp->tcp_ordrel_done = B_TRUE;
14567 			putnext(tcp->tcp_rq, mp1);
14568 			if (tcp->tcp_deferred_clean_death) {
14569 				/*
14570 				 * tcp_clean_death was deferred
14571 				 * for T_ORDREL_IND - do it now
14572 				 */
14573 				(void) tcp_clean_death(tcp,
14574 				    tcp->tcp_client_errno, 20);
14575 				tcp->tcp_deferred_clean_death =	B_FALSE;
14576 			}
14577 		} else {
14578 			/*
14579 			 * Run the orderly release in the
14580 			 * service routine.
14581 			 */
14582 			qenable(tcp->tcp_rq);
14583 			/*
14584 			 * Caveat(XXX): The machine may be so
14585 			 * overloaded that tcp_rsrv() is not scheduled
14586 			 * until after the endpoint has transitioned
14587 			 * to TCPS_TIME_WAIT
14588 			 * and tcp_time_wait_interval expires. Then
14589 			 * tcp_timer() will blow away state in tcp_t
14590 			 * and T_ORDREL_IND will never be delivered
14591 			 * upstream. Unlikely but potentially
14592 			 * a problem.
14593 			 */
14594 		}
14595 	}
14596 done:
14597 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
14598 }
14599 
14600 /*
14601  * This function does PAWS protection check. Returns B_TRUE if the
14602  * segment passes the PAWS test, else returns B_FALSE.
14603  */
14604 boolean_t
14605 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
14606 {
14607 	uint8_t	flags;
14608 	int	options;
14609 	uint8_t *up;
14610 
14611 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
14612 	/*
14613 	 * If timestamp option is aligned nicely, get values inline,
14614 	 * otherwise call general routine to parse.  Only do that
14615 	 * if timestamp is the only option.
14616 	 */
14617 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
14618 	    TCPOPT_REAL_TS_LEN &&
14619 	    OK_32PTR((up = ((uint8_t *)tcph) +
14620 	    TCP_MIN_HEADER_LENGTH)) &&
14621 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
14622 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
14623 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
14624 
14625 		options = TCP_OPT_TSTAMP_PRESENT;
14626 	} else {
14627 		if (tcp->tcp_snd_sack_ok) {
14628 			tcpoptp->tcp = tcp;
14629 		} else {
14630 			tcpoptp->tcp = NULL;
14631 		}
14632 		options = tcp_parse_options(tcph, tcpoptp);
14633 	}
14634 
14635 	if (options & TCP_OPT_TSTAMP_PRESENT) {
14636 		/*
14637 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
14638 		 * regardless of the timestamp, page 18 RFC 1323.bis.
14639 		 */
14640 		if ((flags & TH_RST) == 0 &&
14641 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
14642 		    tcp->tcp_ts_recent)) {
14643 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
14644 			    PAWS_TIMEOUT)) {
14645 				/* This segment is not acceptable. */
14646 				return (B_FALSE);
14647 			} else {
14648 				/*
14649 				 * Connection has been idle for
14650 				 * too long.  Reset the timestamp
14651 				 * and assume the segment is valid.
14652 				 */
14653 				tcp->tcp_ts_recent =
14654 				    tcpoptp->tcp_opt_ts_val;
14655 			}
14656 		}
14657 	} else {
14658 		/*
14659 		 * If we don't get a timestamp on every packet, we
14660 		 * figure we can't really trust 'em, so we stop sending
14661 		 * and parsing them.
14662 		 */
14663 		tcp->tcp_snd_ts_ok = B_FALSE;
14664 
14665 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14666 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
14667 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
14668 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
14669 		if (tcp->tcp_snd_sack_ok) {
14670 			ASSERT(tcp->tcp_sack_info != NULL);
14671 			tcp->tcp_max_sack_blk = 4;
14672 		}
14673 	}
14674 	return (B_TRUE);
14675 }
14676 
14677 /*
14678  * Attach ancillary data to a received TCP segments for the
14679  * ancillary pieces requested by the application that are
14680  * different than they were in the previous data segment.
14681  *
14682  * Save the "current" values once memory allocation is ok so that
14683  * when memory allocation fails we can just wait for the next data segment.
14684  */
14685 static mblk_t *
14686 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
14687 {
14688 	struct T_optdata_ind *todi;
14689 	int optlen;
14690 	uchar_t *optptr;
14691 	struct T_opthdr *toh;
14692 	uint_t addflag;	/* Which pieces to add */
14693 	mblk_t *mp1;
14694 
14695 	optlen = 0;
14696 	addflag = 0;
14697 	/* If app asked for pktinfo and the index has changed ... */
14698 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
14699 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
14700 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
14701 		optlen += sizeof (struct T_opthdr) +
14702 		    sizeof (struct in6_pktinfo);
14703 		addflag |= TCP_IPV6_RECVPKTINFO;
14704 	}
14705 	/* If app asked for hoplimit and it has changed ... */
14706 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
14707 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
14708 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
14709 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14710 		addflag |= TCP_IPV6_RECVHOPLIMIT;
14711 	}
14712 	/* If app asked for tclass and it has changed ... */
14713 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
14714 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
14715 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
14716 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
14717 		addflag |= TCP_IPV6_RECVTCLASS;
14718 	}
14719 	/* If app asked for hopbyhop headers and it has changed ... */
14720 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
14721 	    tcp_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
14722 		(ipp->ipp_fields & IPPF_HOPOPTS),
14723 		ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
14724 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
14725 		addflag |= TCP_IPV6_RECVHOPOPTS;
14726 		if (!tcp_allocbuf((void **)&tcp->tcp_hopopts,
14727 		    &tcp->tcp_hopoptslen,
14728 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14729 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
14730 			return (mp);
14731 	}
14732 	/* If app asked for dst headers before routing headers ... */
14733 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
14734 	    tcp_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
14735 		(ipp->ipp_fields & IPPF_RTDSTOPTS),
14736 		ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
14737 		optlen += sizeof (struct T_opthdr) +
14738 		    ipp->ipp_rtdstoptslen;
14739 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
14740 		if (!tcp_allocbuf((void **)&tcp->tcp_rtdstopts,
14741 		    &tcp->tcp_rtdstoptslen,
14742 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14743 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
14744 			return (mp);
14745 	}
14746 	/* If app asked for routing headers and it has changed ... */
14747 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
14748 	    tcp_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
14749 		(ipp->ipp_fields & IPPF_RTHDR),
14750 		ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
14751 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
14752 		addflag |= TCP_IPV6_RECVRTHDR;
14753 		if (!tcp_allocbuf((void **)&tcp->tcp_rthdr,
14754 		    &tcp->tcp_rthdrlen,
14755 		    (ipp->ipp_fields & IPPF_RTHDR),
14756 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
14757 			return (mp);
14758 	}
14759 	/* If app asked for dest headers and it has changed ... */
14760 	if ((tcp->tcp_ipv6_recvancillary &
14761 		(TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
14762 	    tcp_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
14763 		(ipp->ipp_fields & IPPF_DSTOPTS),
14764 		ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
14765 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
14766 		addflag |= TCP_IPV6_RECVDSTOPTS;
14767 		if (!tcp_allocbuf((void **)&tcp->tcp_dstopts,
14768 		    &tcp->tcp_dstoptslen,
14769 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14770 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
14771 			return (mp);
14772 	}
14773 
14774 	if (optlen == 0) {
14775 		/* Nothing to add */
14776 		return (mp);
14777 	}
14778 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
14779 	if (mp1 == NULL) {
14780 		/*
14781 		 * Defer sending ancillary data until the next TCP segment
14782 		 * arrives.
14783 		 */
14784 		return (mp);
14785 	}
14786 	mp1->b_cont = mp;
14787 	mp = mp1;
14788 	mp->b_wptr += sizeof (*todi) + optlen;
14789 	mp->b_datap->db_type = M_PROTO;
14790 	todi = (struct T_optdata_ind *)mp->b_rptr;
14791 	todi->PRIM_type = T_OPTDATA_IND;
14792 	todi->DATA_flag = 1;	/* MORE data */
14793 	todi->OPT_length = optlen;
14794 	todi->OPT_offset = sizeof (*todi);
14795 	optptr = (uchar_t *)&todi[1];
14796 	/*
14797 	 * If app asked for pktinfo and the index has changed ...
14798 	 * Note that the local address never changes for the connection.
14799 	 */
14800 	if (addflag & TCP_IPV6_RECVPKTINFO) {
14801 		struct in6_pktinfo *pkti;
14802 
14803 		toh = (struct T_opthdr *)optptr;
14804 		toh->level = IPPROTO_IPV6;
14805 		toh->name = IPV6_PKTINFO;
14806 		toh->len = sizeof (*toh) + sizeof (*pkti);
14807 		toh->status = 0;
14808 		optptr += sizeof (*toh);
14809 		pkti = (struct in6_pktinfo *)optptr;
14810 		if (tcp->tcp_ipversion == IPV6_VERSION)
14811 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
14812 		else
14813 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
14814 			    &pkti->ipi6_addr);
14815 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
14816 		optptr += sizeof (*pkti);
14817 		ASSERT(OK_32PTR(optptr));
14818 		/* Save as "last" value */
14819 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
14820 	}
14821 	/* If app asked for hoplimit and it has changed ... */
14822 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
14823 		toh = (struct T_opthdr *)optptr;
14824 		toh->level = IPPROTO_IPV6;
14825 		toh->name = IPV6_HOPLIMIT;
14826 		toh->len = sizeof (*toh) + sizeof (uint_t);
14827 		toh->status = 0;
14828 		optptr += sizeof (*toh);
14829 		*(uint_t *)optptr = ipp->ipp_hoplimit;
14830 		optptr += sizeof (uint_t);
14831 		ASSERT(OK_32PTR(optptr));
14832 		/* Save as "last" value */
14833 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
14834 	}
14835 	/* If app asked for tclass and it has changed ... */
14836 	if (addflag & TCP_IPV6_RECVTCLASS) {
14837 		toh = (struct T_opthdr *)optptr;
14838 		toh->level = IPPROTO_IPV6;
14839 		toh->name = IPV6_TCLASS;
14840 		toh->len = sizeof (*toh) + sizeof (uint_t);
14841 		toh->status = 0;
14842 		optptr += sizeof (*toh);
14843 		*(uint_t *)optptr = ipp->ipp_tclass;
14844 		optptr += sizeof (uint_t);
14845 		ASSERT(OK_32PTR(optptr));
14846 		/* Save as "last" value */
14847 		tcp->tcp_recvtclass = ipp->ipp_tclass;
14848 	}
14849 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
14850 		toh = (struct T_opthdr *)optptr;
14851 		toh->level = IPPROTO_IPV6;
14852 		toh->name = IPV6_HOPOPTS;
14853 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
14854 		toh->status = 0;
14855 		optptr += sizeof (*toh);
14856 		bcopy(ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
14857 		optptr += ipp->ipp_hopoptslen;
14858 		ASSERT(OK_32PTR(optptr));
14859 		/* Save as last value */
14860 		tcp_savebuf((void **)&tcp->tcp_hopopts,
14861 		    &tcp->tcp_hopoptslen,
14862 		    (ipp->ipp_fields & IPPF_HOPOPTS),
14863 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14864 	}
14865 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
14866 		toh = (struct T_opthdr *)optptr;
14867 		toh->level = IPPROTO_IPV6;
14868 		toh->name = IPV6_RTHDRDSTOPTS;
14869 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
14870 		toh->status = 0;
14871 		optptr += sizeof (*toh);
14872 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
14873 		optptr += ipp->ipp_rtdstoptslen;
14874 		ASSERT(OK_32PTR(optptr));
14875 		/* Save as last value */
14876 		tcp_savebuf((void **)&tcp->tcp_rtdstopts,
14877 		    &tcp->tcp_rtdstoptslen,
14878 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
14879 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
14880 	}
14881 	if (addflag & TCP_IPV6_RECVRTHDR) {
14882 		toh = (struct T_opthdr *)optptr;
14883 		toh->level = IPPROTO_IPV6;
14884 		toh->name = IPV6_RTHDR;
14885 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
14886 		toh->status = 0;
14887 		optptr += sizeof (*toh);
14888 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
14889 		optptr += ipp->ipp_rthdrlen;
14890 		ASSERT(OK_32PTR(optptr));
14891 		/* Save as last value */
14892 		tcp_savebuf((void **)&tcp->tcp_rthdr,
14893 		    &tcp->tcp_rthdrlen,
14894 		    (ipp->ipp_fields & IPPF_RTHDR),
14895 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14896 	}
14897 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
14898 		toh = (struct T_opthdr *)optptr;
14899 		toh->level = IPPROTO_IPV6;
14900 		toh->name = IPV6_DSTOPTS;
14901 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
14902 		toh->status = 0;
14903 		optptr += sizeof (*toh);
14904 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
14905 		optptr += ipp->ipp_dstoptslen;
14906 		ASSERT(OK_32PTR(optptr));
14907 		/* Save as last value */
14908 		tcp_savebuf((void **)&tcp->tcp_dstopts,
14909 		    &tcp->tcp_dstoptslen,
14910 		    (ipp->ipp_fields & IPPF_DSTOPTS),
14911 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14912 	}
14913 	ASSERT(optptr == mp->b_wptr);
14914 	return (mp);
14915 }
14916 
14917 
14918 /*
14919  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
14920  * or a "bad" IRE detected by tcp_adapt_ire.
14921  * We can't tell if the failure was due to the laddr or the faddr
14922  * thus we clear out all addresses and ports.
14923  */
14924 static void
14925 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
14926 {
14927 	queue_t	*q = tcp->tcp_rq;
14928 	tcph_t	*tcph;
14929 	struct T_error_ack *tea;
14930 	conn_t	*connp = tcp->tcp_connp;
14931 
14932 
14933 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
14934 
14935 	if (mp->b_cont) {
14936 		freemsg(mp->b_cont);
14937 		mp->b_cont = NULL;
14938 	}
14939 	tea = (struct T_error_ack *)mp->b_rptr;
14940 	switch (tea->PRIM_type) {
14941 	case T_BIND_ACK:
14942 		/*
14943 		 * Need to unbind with classifier since we were just told that
14944 		 * our bind succeeded.
14945 		 */
14946 		tcp->tcp_hard_bound = B_FALSE;
14947 		tcp->tcp_hard_binding = B_FALSE;
14948 
14949 		ipcl_hash_remove(connp);
14950 		/* Reuse the mblk if possible */
14951 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
14952 			sizeof (*tea));
14953 		mp->b_rptr = mp->b_datap->db_base;
14954 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
14955 		tea = (struct T_error_ack *)mp->b_rptr;
14956 		tea->PRIM_type = T_ERROR_ACK;
14957 		tea->TLI_error = TSYSERR;
14958 		tea->UNIX_error = error;
14959 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
14960 			tea->ERROR_prim = T_CONN_REQ;
14961 		} else {
14962 			tea->ERROR_prim = O_T_BIND_REQ;
14963 		}
14964 		break;
14965 
14966 	case T_ERROR_ACK:
14967 		if (tcp->tcp_state >= TCPS_SYN_SENT)
14968 			tea->ERROR_prim = T_CONN_REQ;
14969 		break;
14970 	default:
14971 		panic("tcp_bind_failed: unexpected TPI type");
14972 		/*NOTREACHED*/
14973 	}
14974 
14975 	tcp->tcp_state = TCPS_IDLE;
14976 	if (tcp->tcp_ipversion == IPV4_VERSION)
14977 		tcp->tcp_ipha->ipha_src = 0;
14978 	else
14979 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
14980 	/*
14981 	 * Copy of the src addr. in tcp_t is needed since
14982 	 * the lookup funcs. can only look at tcp_t
14983 	 */
14984 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
14985 
14986 	tcph = tcp->tcp_tcph;
14987 	tcph->th_lport[0] = 0;
14988 	tcph->th_lport[1] = 0;
14989 	tcp_bind_hash_remove(tcp);
14990 	bzero(&connp->u_port, sizeof (connp->u_port));
14991 	/* blow away saved option results if any */
14992 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
14993 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
14994 
14995 	conn_delete_ire(tcp->tcp_connp, NULL);
14996 	putnext(q, mp);
14997 }
14998 
14999 /*
15000  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15001  * messages.
15002  */
15003 void
15004 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15005 {
15006 	mblk_t	*mp1;
15007 	uchar_t	*rptr = mp->b_rptr;
15008 	queue_t	*q = tcp->tcp_rq;
15009 	struct T_error_ack *tea;
15010 	uint32_t mss;
15011 	mblk_t *syn_mp;
15012 	mblk_t *mdti;
15013 	int	retval;
15014 	mblk_t *ire_mp;
15015 
15016 	switch (mp->b_datap->db_type) {
15017 	case M_PROTO:
15018 	case M_PCPROTO:
15019 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15020 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15021 			break;
15022 		tea = (struct T_error_ack *)rptr;
15023 		switch (tea->PRIM_type) {
15024 		case T_BIND_ACK:
15025 			/*
15026 			 * Adapt Multidata information, if any.  The
15027 			 * following tcp_mdt_update routine will free
15028 			 * the message.
15029 			 */
15030 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15031 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15032 				    b_rptr)->mdt_capab, B_TRUE);
15033 				freemsg(mdti);
15034 			}
15035 
15036 			/* Get the IRE, if we had requested for it */
15037 			ire_mp = tcp_ire_mp(mp);
15038 
15039 			if (tcp->tcp_hard_binding) {
15040 				tcp->tcp_hard_binding = B_FALSE;
15041 				tcp->tcp_hard_bound = B_TRUE;
15042 				CL_INET_CONNECT(tcp);
15043 			} else {
15044 				if (ire_mp != NULL)
15045 					freeb(ire_mp);
15046 				goto after_syn_sent;
15047 			}
15048 
15049 			retval = tcp_adapt_ire(tcp, ire_mp);
15050 			if (ire_mp != NULL)
15051 				freeb(ire_mp);
15052 			if (retval == 0) {
15053 				tcp_bind_failed(tcp, mp,
15054 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15055 				    ENETUNREACH : EADDRNOTAVAIL));
15056 				return;
15057 			}
15058 			/*
15059 			 * Don't let an endpoint connect to itself.
15060 			 * Also checked in tcp_connect() but that
15061 			 * check can't handle the case when the
15062 			 * local IP address is INADDR_ANY.
15063 			 */
15064 			if (tcp->tcp_ipversion == IPV4_VERSION) {
15065 				if ((tcp->tcp_ipha->ipha_dst ==
15066 				    tcp->tcp_ipha->ipha_src) &&
15067 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15068 				    tcp->tcp_tcph->th_fport))) {
15069 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15070 					return;
15071 				}
15072 			} else {
15073 				if (IN6_ARE_ADDR_EQUAL(
15074 				    &tcp->tcp_ip6h->ip6_dst,
15075 				    &tcp->tcp_ip6h->ip6_src) &&
15076 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
15077 				    tcp->tcp_tcph->th_fport))) {
15078 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
15079 					return;
15080 				}
15081 			}
15082 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
15083 			/*
15084 			 * This should not be possible!  Just for
15085 			 * defensive coding...
15086 			 */
15087 			if (tcp->tcp_state != TCPS_SYN_SENT)
15088 				goto after_syn_sent;
15089 
15090 			ASSERT(q == tcp->tcp_rq);
15091 			/*
15092 			 * tcp_adapt_ire() does not adjust
15093 			 * for TCP/IP header length.
15094 			 */
15095 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
15096 
15097 			/*
15098 			 * Just make sure our rwnd is at
15099 			 * least tcp_recv_hiwat_mss * MSS
15100 			 * large, and round up to the nearest
15101 			 * MSS.
15102 			 *
15103 			 * We do the round up here because
15104 			 * we need to get the interface
15105 			 * MTU first before we can do the
15106 			 * round up.
15107 			 */
15108 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
15109 			    tcp_recv_hiwat_minmss * mss);
15110 			q->q_hiwat = tcp->tcp_rwnd;
15111 			tcp_set_ws_value(tcp);
15112 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
15113 			    tcp->tcp_tcph->th_win);
15114 			if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always)
15115 				tcp->tcp_snd_ws_ok = B_TRUE;
15116 
15117 			/*
15118 			 * Set tcp_snd_ts_ok to true
15119 			 * so that tcp_xmit_mp will
15120 			 * include the timestamp
15121 			 * option in the SYN segment.
15122 			 */
15123 			if (tcp_tstamp_always ||
15124 			    (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) {
15125 				tcp->tcp_snd_ts_ok = B_TRUE;
15126 			}
15127 
15128 			/*
15129 			 * tcp_snd_sack_ok can be set in
15130 			 * tcp_adapt_ire() if the sack metric
15131 			 * is set.  So check it here also.
15132 			 */
15133 			if (tcp_sack_permitted == 2 ||
15134 			    tcp->tcp_snd_sack_ok) {
15135 				if (tcp->tcp_sack_info == NULL) {
15136 					tcp->tcp_sack_info =
15137 					kmem_cache_alloc(tcp_sack_info_cache,
15138 					    KM_SLEEP);
15139 				}
15140 				tcp->tcp_snd_sack_ok = B_TRUE;
15141 			}
15142 
15143 			/*
15144 			 * Should we use ECN?  Note that the current
15145 			 * default value (SunOS 5.9) of tcp_ecn_permitted
15146 			 * is 1.  The reason for doing this is that there
15147 			 * are equipments out there that will drop ECN
15148 			 * enabled IP packets.  Setting it to 1 avoids
15149 			 * compatibility problems.
15150 			 */
15151 			if (tcp_ecn_permitted == 2)
15152 				tcp->tcp_ecn_ok = B_TRUE;
15153 
15154 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15155 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
15156 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
15157 			if (syn_mp) {
15158 				cred_t *cr;
15159 				pid_t pid;
15160 
15161 				/*
15162 				 * Obtain the credential from the
15163 				 * thread calling connect(); the credential
15164 				 * lives on in the second mblk which
15165 				 * originated from T_CONN_REQ and is echoed
15166 				 * with the T_BIND_ACK from ip.  If none
15167 				 * can be found, default to the creator
15168 				 * of the socket.
15169 				 */
15170 				if (mp->b_cont == NULL ||
15171 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
15172 					cr = tcp->tcp_cred;
15173 					pid = tcp->tcp_cpid;
15174 				} else {
15175 					pid = DB_CPID(mp->b_cont);
15176 				}
15177 
15178 				TCP_RECORD_TRACE(tcp, syn_mp,
15179 				    TCP_TRACE_SEND_PKT);
15180 				mblk_setcred(syn_mp, cr);
15181 				DB_CPID(syn_mp) = pid;
15182 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
15183 			}
15184 		after_syn_sent:
15185 			/*
15186 			 * A trailer mblk indicates a waiting client upstream.
15187 			 * We complete here the processing begun in
15188 			 * either tcp_bind() or tcp_connect() by passing
15189 			 * upstream the reply message they supplied.
15190 			 */
15191 			mp1 = mp;
15192 			mp = mp->b_cont;
15193 			freeb(mp1);
15194 			if (mp)
15195 				break;
15196 			return;
15197 		case T_ERROR_ACK:
15198 			if (tcp->tcp_debug) {
15199 				(void) strlog(TCP_MOD_ID, 0, 1,
15200 				    SL_TRACE|SL_ERROR,
15201 				    "tcp_rput_other: case T_ERROR_ACK, "
15202 				    "ERROR_prim == %d",
15203 				    tea->ERROR_prim);
15204 			}
15205 			switch (tea->ERROR_prim) {
15206 			case O_T_BIND_REQ:
15207 			case T_BIND_REQ:
15208 				tcp_bind_failed(tcp, mp,
15209 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15210 				    ENETUNREACH : EADDRNOTAVAIL));
15211 				return;
15212 			case T_UNBIND_REQ:
15213 				tcp->tcp_hard_binding = B_FALSE;
15214 				tcp->tcp_hard_bound = B_FALSE;
15215 				if (mp->b_cont) {
15216 					freemsg(mp->b_cont);
15217 					mp->b_cont = NULL;
15218 				}
15219 				if (tcp->tcp_unbind_pending)
15220 					tcp->tcp_unbind_pending = 0;
15221 				else {
15222 					/* From tcp_ip_unbind() - free */
15223 					freemsg(mp);
15224 					return;
15225 				}
15226 				break;
15227 			case T_SVR4_OPTMGMT_REQ:
15228 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15229 					/* T_OPTMGMT_REQ generated by TCP */
15230 					printf("T_SVR4_OPTMGMT_REQ failed "
15231 					    "%d/%d - dropped (cnt %d)\n",
15232 					    tea->TLI_error, tea->UNIX_error,
15233 					    tcp->tcp_drop_opt_ack_cnt);
15234 					freemsg(mp);
15235 					tcp->tcp_drop_opt_ack_cnt--;
15236 					return;
15237 				}
15238 				break;
15239 			}
15240 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15241 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15242 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15243 				    "- dropped (cnt %d)\n",
15244 				    tea->TLI_error, tea->UNIX_error,
15245 				    tcp->tcp_drop_opt_ack_cnt);
15246 				freemsg(mp);
15247 				tcp->tcp_drop_opt_ack_cnt--;
15248 				return;
15249 			}
15250 			break;
15251 		case T_OPTMGMT_ACK:
15252 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15253 				/* T_OPTMGMT_REQ generated by TCP */
15254 				freemsg(mp);
15255 				tcp->tcp_drop_opt_ack_cnt--;
15256 				return;
15257 			}
15258 			break;
15259 		default:
15260 			break;
15261 		}
15262 		break;
15263 	case M_CTL:
15264 		/*
15265 		 * ICMP messages.
15266 		 */
15267 		tcp_icmp_error(tcp, mp);
15268 		return;
15269 	case M_FLUSH:
15270 		if (*rptr & FLUSHR)
15271 			flushq(q, FLUSHDATA);
15272 		break;
15273 	default:
15274 		break;
15275 	}
15276 	/*
15277 	 * Make sure we set this bit before sending the ACK for
15278 	 * bind. Otherwise accept could possibly run and free
15279 	 * this tcp struct.
15280 	 */
15281 	putnext(q, mp);
15282 }
15283 
15284 /*
15285  * Called as the result of a qbufcall or a qtimeout to remedy a failure
15286  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
15287  * tcp_rsrv() try again.
15288  */
15289 static void
15290 tcp_ordrel_kick(void *arg)
15291 {
15292 	conn_t 	*connp = (conn_t *)arg;
15293 	tcp_t	*tcp = connp->conn_tcp;
15294 
15295 	tcp->tcp_ordrelid = 0;
15296 	tcp->tcp_timeout = B_FALSE;
15297 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
15298 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15299 		qenable(tcp->tcp_rq);
15300 	}
15301 }
15302 
15303 /* ARGSUSED */
15304 static void
15305 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15306 {
15307 	conn_t	*connp = (conn_t *)arg;
15308 	tcp_t	*tcp = connp->conn_tcp;
15309 	queue_t	*q = tcp->tcp_rq;
15310 	uint_t	thwin;
15311 
15312 	freeb(mp);
15313 
15314 	TCP_STAT(tcp_rsrv_calls);
15315 
15316 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15317 		return;
15318 	}
15319 
15320 	if (tcp->tcp_fused) {
15321 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15322 
15323 		ASSERT(tcp->tcp_fused);
15324 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15325 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15326 		ASSERT(!TCP_IS_DETACHED(tcp));
15327 		ASSERT(tcp->tcp_connp->conn_sqp ==
15328 		    peer_tcp->tcp_connp->conn_sqp);
15329 
15330 		/*
15331 		 * Normally we would not get backenabled in synchronous
15332 		 * streams mode, but in case this happens, we need to stop
15333 		 * synchronous streams temporarily to prevent a race with
15334 		 * tcp_fuse_rrw() or tcp_fuse_rinfop().  It is safe to access
15335 		 * tcp_rcv_list here because those entry points will return
15336 		 * right away when synchronous streams is stopped.
15337 		 */
15338 		TCP_FUSE_SYNCSTR_STOP(tcp);
15339 		if (tcp->tcp_rcv_list != NULL)
15340 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
15341 
15342 		tcp_clrqfull(peer_tcp);
15343 		TCP_FUSE_SYNCSTR_RESUME(tcp);
15344 		TCP_STAT(tcp_fusion_backenabled);
15345 		return;
15346 	}
15347 
15348 	if (canputnext(q)) {
15349 		tcp->tcp_rwnd = q->q_hiwat;
15350 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
15351 		    << tcp->tcp_rcv_ws;
15352 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
15353 		/*
15354 		 * Send back a window update immediately if TCP is above
15355 		 * ESTABLISHED state and the increase of the rcv window
15356 		 * that the other side knows is at least 1 MSS after flow
15357 		 * control is lifted.
15358 		 */
15359 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
15360 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
15361 			tcp_xmit_ctl(NULL, tcp,
15362 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
15363 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
15364 			BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
15365 		}
15366 	}
15367 	/* Handle a failure to allocate a T_ORDREL_IND here */
15368 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
15369 		ASSERT(tcp->tcp_listener == NULL);
15370 		if (tcp->tcp_rcv_list != NULL) {
15371 			(void) tcp_rcv_drain(q, tcp);
15372 		}
15373 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
15374 		mp = mi_tpi_ordrel_ind();
15375 		if (mp) {
15376 			tcp->tcp_ordrel_done = B_TRUE;
15377 			putnext(q, mp);
15378 			if (tcp->tcp_deferred_clean_death) {
15379 				/*
15380 				 * tcp_clean_death was deferred for
15381 				 * T_ORDREL_IND - do it now
15382 				 */
15383 				tcp->tcp_deferred_clean_death = B_FALSE;
15384 				(void) tcp_clean_death(tcp,
15385 				    tcp->tcp_client_errno, 22);
15386 			}
15387 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15388 			/*
15389 			 * If there isn't already a timer running
15390 			 * start one.  Use a 4 second
15391 			 * timer as a fallback since it can't fail.
15392 			 */
15393 			tcp->tcp_timeout = B_TRUE;
15394 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15395 			    MSEC_TO_TICK(4000));
15396 		}
15397 	}
15398 }
15399 
15400 /*
15401  * The read side service routine is called mostly when we get back-enabled as a
15402  * result of flow control relief.  Since we don't actually queue anything in
15403  * TCP, we have no data to send out of here.  What we do is clear the receive
15404  * window, and send out a window update.
15405  * This routine is also called to drive an orderly release message upstream
15406  * if the attempt in tcp_rput failed.
15407  */
15408 static void
15409 tcp_rsrv(queue_t *q)
15410 {
15411 	conn_t *connp = Q_TO_CONN(q);
15412 	tcp_t	*tcp = connp->conn_tcp;
15413 	mblk_t	*mp;
15414 
15415 	/* No code does a putq on the read side */
15416 	ASSERT(q->q_first == NULL);
15417 
15418 	/* Nothing to do for the default queue */
15419 	if (q == tcp_g_q) {
15420 		return;
15421 	}
15422 
15423 	mp = allocb(0, BPRI_HI);
15424 	if (mp == NULL) {
15425 		/*
15426 		 * We are under memory pressure. Return for now and we
15427 		 * we will be called again later.
15428 		 */
15429 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
15430 			/*
15431 			 * If there isn't already a timer running
15432 			 * start one.  Use a 4 second
15433 			 * timer as a fallback since it can't fail.
15434 			 */
15435 			tcp->tcp_timeout = B_TRUE;
15436 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
15437 			    MSEC_TO_TICK(4000));
15438 		}
15439 		return;
15440 	}
15441 	CONN_INC_REF(connp);
15442 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
15443 	    SQTAG_TCP_RSRV);
15444 }
15445 
15446 /*
15447  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
15448  * We do not allow the receive window to shrink.  After setting rwnd,
15449  * set the flow control hiwat of the stream.
15450  *
15451  * This function is called in 2 cases:
15452  *
15453  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
15454  *    connection (passive open) and in tcp_rput_data() for active connect.
15455  *    This is called after tcp_mss_set() when the desired MSS value is known.
15456  *    This makes sure that our window size is a mutiple of the other side's
15457  *    MSS.
15458  * 2) Handling SO_RCVBUF option.
15459  *
15460  * It is ASSUMED that the requested size is a multiple of the current MSS.
15461  *
15462  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
15463  * user requests so.
15464  */
15465 static int
15466 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
15467 {
15468 	uint32_t	mss = tcp->tcp_mss;
15469 	uint32_t	old_max_rwnd;
15470 	uint32_t	max_transmittable_rwnd;
15471 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
15472 
15473 	if (tcp->tcp_fused) {
15474 		size_t sth_hiwat;
15475 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15476 
15477 		ASSERT(peer_tcp != NULL);
15478 		/*
15479 		 * Record the stream head's high water mark for
15480 		 * this endpoint; this is used for flow-control
15481 		 * purposes in tcp_fuse_output().
15482 		 */
15483 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
15484 		if (!tcp_detached)
15485 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
15486 
15487 		/*
15488 		 * In the fusion case, the maxpsz stream head value of
15489 		 * our peer is set according to its send buffer size
15490 		 * and our receive buffer size; since the latter may
15491 		 * have changed we need to update the peer's maxpsz.
15492 		 */
15493 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
15494 		return (rwnd);
15495 	}
15496 
15497 	if (tcp_detached)
15498 		old_max_rwnd = tcp->tcp_rwnd;
15499 	else
15500 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
15501 
15502 	/*
15503 	 * Insist on a receive window that is at least
15504 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
15505 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
15506 	 * and delayed acknowledgement.
15507 	 */
15508 	rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss);
15509 
15510 	/*
15511 	 * If window size info has already been exchanged, TCP should not
15512 	 * shrink the window.  Shrinking window is doable if done carefully.
15513 	 * We may add that support later.  But so far there is not a real
15514 	 * need to do that.
15515 	 */
15516 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
15517 		/* MSS may have changed, do a round up again. */
15518 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
15519 	}
15520 
15521 	/*
15522 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
15523 	 * can be applied even before the window scale option is decided.
15524 	 */
15525 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
15526 	if (rwnd > max_transmittable_rwnd) {
15527 		rwnd = max_transmittable_rwnd -
15528 		    (max_transmittable_rwnd % mss);
15529 		if (rwnd < mss)
15530 			rwnd = max_transmittable_rwnd;
15531 		/*
15532 		 * If we're over the limit we may have to back down tcp_rwnd.
15533 		 * The increment below won't work for us. So we set all three
15534 		 * here and the increment below will have no effect.
15535 		 */
15536 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
15537 	}
15538 	if (tcp->tcp_localnet) {
15539 		tcp->tcp_rack_abs_max =
15540 		    MIN(tcp_local_dacks_max, rwnd / mss / 2);
15541 	} else {
15542 		/*
15543 		 * For a remote host on a different subnet (through a router),
15544 		 * we ack every other packet to be conforming to RFC1122.
15545 		 * tcp_deferred_acks_max is default to 2.
15546 		 */
15547 		tcp->tcp_rack_abs_max =
15548 		    MIN(tcp_deferred_acks_max, rwnd / mss / 2);
15549 	}
15550 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
15551 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15552 	else
15553 		tcp->tcp_rack_cur_max = 0;
15554 	/*
15555 	 * Increment the current rwnd by the amount the maximum grew (we
15556 	 * can not overwrite it since we might be in the middle of a
15557 	 * connection.)
15558 	 */
15559 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
15560 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
15561 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
15562 		tcp->tcp_cwnd_max = rwnd;
15563 
15564 	if (tcp_detached)
15565 		return (rwnd);
15566 	/*
15567 	 * We set the maximum receive window into rq->q_hiwat.
15568 	 * This is not actually used for flow control.
15569 	 */
15570 	tcp->tcp_rq->q_hiwat = rwnd;
15571 	/*
15572 	 * Set the Stream head high water mark. This doesn't have to be
15573 	 * here, since we are simply using default values, but we would
15574 	 * prefer to choose these values algorithmically, with a likely
15575 	 * relationship to rwnd.
15576 	 */
15577 	(void) mi_set_sth_hiwat(tcp->tcp_rq, MAX(rwnd, tcp_sth_rcv_hiwat));
15578 	return (rwnd);
15579 }
15580 
15581 /*
15582  * Return SNMP stuff in buffer in mpdata.
15583  */
15584 int
15585 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
15586 {
15587 	mblk_t			*mpdata;
15588 	mblk_t			*mp_conn_ctl = NULL;
15589 	mblk_t			*mp_conn_data;
15590 	mblk_t			*mp6_conn_ctl = NULL;
15591 	mblk_t			*mp6_conn_data;
15592 	mblk_t			*mp_conn_tail = NULL;
15593 	mblk_t			*mp6_conn_tail = NULL;
15594 	struct opthdr		*optp;
15595 	mib2_tcpConnEntry_t	tce;
15596 	mib2_tcp6ConnEntry_t	tce6;
15597 	connf_t			*connfp;
15598 	conn_t			*connp;
15599 	int			i;
15600 	boolean_t 		ispriv;
15601 	zoneid_t 		zoneid;
15602 
15603 	if (mpctl == NULL ||
15604 	    (mpdata = mpctl->b_cont) == NULL ||
15605 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
15606 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL) {
15607 		if (mp_conn_ctl != NULL)
15608 			freemsg(mp_conn_ctl);
15609 		if (mp6_conn_ctl != NULL)
15610 			freemsg(mp6_conn_ctl);
15611 		return (0);
15612 	}
15613 
15614 	/* build table of connections -- need count in fixed part */
15615 	mp_conn_data = mp_conn_ctl->b_cont;
15616 	mp6_conn_data = mp6_conn_ctl->b_cont;
15617 	SET_MIB(tcp_mib.tcpRtoAlgorithm, 4);   /* vanj */
15618 	SET_MIB(tcp_mib.tcpRtoMin, tcp_rexmit_interval_min);
15619 	SET_MIB(tcp_mib.tcpRtoMax, tcp_rexmit_interval_max);
15620 	SET_MIB(tcp_mib.tcpMaxConn, -1);
15621 	SET_MIB(tcp_mib.tcpCurrEstab, 0);
15622 
15623 	ispriv =
15624 	    secpolicy_net_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
15625 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15626 
15627 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15628 
15629 		connfp = &ipcl_globalhash_fanout[i];
15630 
15631 		connp = NULL;
15632 
15633 		while ((connp =
15634 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
15635 			tcp_t *tcp;
15636 
15637 			if (connp->conn_zoneid != zoneid)
15638 				continue;	/* not in this zone */
15639 
15640 			tcp = connp->conn_tcp;
15641 			UPDATE_MIB(&tcp_mib, tcpInSegs, tcp->tcp_ibsegs);
15642 			tcp->tcp_ibsegs = 0;
15643 			UPDATE_MIB(&tcp_mib, tcpOutSegs, tcp->tcp_obsegs);
15644 			tcp->tcp_obsegs = 0;
15645 
15646 			tce6.tcp6ConnState = tce.tcpConnState =
15647 			    tcp_snmp_state(tcp);
15648 			if (tce.tcpConnState == MIB2_TCP_established ||
15649 			    tce.tcpConnState == MIB2_TCP_closeWait)
15650 				BUMP_MIB(&tcp_mib, tcpCurrEstab);
15651 
15652 			/* Create a message to report on IPv6 entries */
15653 			if (tcp->tcp_ipversion == IPV6_VERSION) {
15654 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
15655 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
15656 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
15657 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
15658 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
15659 			/* Don't want just anybody seeing these... */
15660 			if (ispriv) {
15661 				tce6.tcp6ConnEntryInfo.ce_snxt =
15662 				    tcp->tcp_snxt;
15663 				tce6.tcp6ConnEntryInfo.ce_suna =
15664 				    tcp->tcp_suna;
15665 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15666 				    tcp->tcp_rnxt;
15667 				tce6.tcp6ConnEntryInfo.ce_rack =
15668 				    tcp->tcp_rack;
15669 			} else {
15670 				/*
15671 				 * Netstat, unfortunately, uses this to
15672 				 * get send/receive queue sizes.  How to fix?
15673 				 * Why not compute the difference only?
15674 				 */
15675 				tce6.tcp6ConnEntryInfo.ce_snxt =
15676 				    tcp->tcp_snxt - tcp->tcp_suna;
15677 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
15678 				tce6.tcp6ConnEntryInfo.ce_rnxt =
15679 				    tcp->tcp_rnxt - tcp->tcp_rack;
15680 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
15681 			}
15682 
15683 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15684 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15685 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
15686 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
15687 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
15688 			(void) snmp_append_data2(mp6_conn_data, &mp6_conn_tail,
15689 			    (char *)&tce6, sizeof (tce6));
15690 			}
15691 			/*
15692 			 * Create an IPv4 table entry for IPv4 entries and also
15693 			 * for IPv6 entries which are bound to in6addr_any
15694 			 * but don't have IPV6_V6ONLY set.
15695 			 * (i.e. anything an IPv4 peer could connect to)
15696 			 */
15697 			if (tcp->tcp_ipversion == IPV4_VERSION ||
15698 			    (tcp->tcp_state <= TCPS_LISTEN &&
15699 			    !tcp->tcp_connp->conn_ipv6_v6only &&
15700 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
15701 				if (tcp->tcp_ipversion == IPV6_VERSION) {
15702 					tce.tcpConnRemAddress = INADDR_ANY;
15703 					tce.tcpConnLocalAddress = INADDR_ANY;
15704 				} else {
15705 					tce.tcpConnRemAddress =
15706 					    tcp->tcp_remote;
15707 					tce.tcpConnLocalAddress =
15708 					    tcp->tcp_ip_src;
15709 				}
15710 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
15711 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
15712 				/* Don't want just anybody seeing these... */
15713 				if (ispriv) {
15714 					tce.tcpConnEntryInfo.ce_snxt =
15715 					    tcp->tcp_snxt;
15716 					tce.tcpConnEntryInfo.ce_suna =
15717 					    tcp->tcp_suna;
15718 					tce.tcpConnEntryInfo.ce_rnxt =
15719 					    tcp->tcp_rnxt;
15720 					tce.tcpConnEntryInfo.ce_rack =
15721 					    tcp->tcp_rack;
15722 				} else {
15723 					/*
15724 					 * Netstat, unfortunately, uses this to
15725 					 * get send/receive queue sizes.  How
15726 					 * to fix?
15727 					 * Why not compute the difference only?
15728 					 */
15729 					tce.tcpConnEntryInfo.ce_snxt =
15730 					    tcp->tcp_snxt - tcp->tcp_suna;
15731 					tce.tcpConnEntryInfo.ce_suna = 0;
15732 					tce.tcpConnEntryInfo.ce_rnxt =
15733 					    tcp->tcp_rnxt - tcp->tcp_rack;
15734 					tce.tcpConnEntryInfo.ce_rack = 0;
15735 				}
15736 
15737 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
15738 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
15739 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
15740 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
15741 				tce.tcpConnEntryInfo.ce_state =
15742 				    tcp->tcp_state;
15743 				(void) snmp_append_data2(mp_conn_data,
15744 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
15745 			}
15746 		}
15747 	}
15748 
15749 	/* fixed length structure for IPv4 and IPv6 counters */
15750 	SET_MIB(tcp_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
15751 	SET_MIB(tcp_mib.tcp6ConnTableSize, sizeof (mib2_tcp6ConnEntry_t));
15752 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
15753 	optp->level = MIB2_TCP;
15754 	optp->name = 0;
15755 	(void) snmp_append_data(mpdata, (char *)&tcp_mib, sizeof (tcp_mib));
15756 	optp->len = msgdsize(mpdata);
15757 	qreply(q, mpctl);
15758 
15759 	/* table of connections... */
15760 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
15761 	    sizeof (struct T_optmgmt_ack)];
15762 	optp->level = MIB2_TCP;
15763 	optp->name = MIB2_TCP_CONN;
15764 	optp->len = msgdsize(mp_conn_data);
15765 	qreply(q, mp_conn_ctl);
15766 
15767 	/* table of IPv6 connections... */
15768 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
15769 	    sizeof (struct T_optmgmt_ack)];
15770 	optp->level = MIB2_TCP6;
15771 	optp->name = MIB2_TCP6_CONN;
15772 	optp->len = msgdsize(mp6_conn_data);
15773 	qreply(q, mp6_conn_ctl);
15774 	return (1);
15775 }
15776 
15777 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
15778 /* ARGSUSED */
15779 int
15780 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
15781 {
15782 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
15783 
15784 	switch (level) {
15785 	case MIB2_TCP:
15786 		switch (name) {
15787 		case 13:
15788 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
15789 				return (0);
15790 			/* TODO: delete entry defined by tce */
15791 			return (1);
15792 		default:
15793 			return (0);
15794 		}
15795 	default:
15796 		return (1);
15797 	}
15798 }
15799 
15800 /* Translate TCP state to MIB2 TCP state. */
15801 static int
15802 tcp_snmp_state(tcp_t *tcp)
15803 {
15804 	if (tcp == NULL)
15805 		return (0);
15806 
15807 	switch (tcp->tcp_state) {
15808 	case TCPS_CLOSED:
15809 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
15810 	case TCPS_BOUND:
15811 		return (MIB2_TCP_closed);
15812 	case TCPS_LISTEN:
15813 		return (MIB2_TCP_listen);
15814 	case TCPS_SYN_SENT:
15815 		return (MIB2_TCP_synSent);
15816 	case TCPS_SYN_RCVD:
15817 		return (MIB2_TCP_synReceived);
15818 	case TCPS_ESTABLISHED:
15819 		return (MIB2_TCP_established);
15820 	case TCPS_CLOSE_WAIT:
15821 		return (MIB2_TCP_closeWait);
15822 	case TCPS_FIN_WAIT_1:
15823 		return (MIB2_TCP_finWait1);
15824 	case TCPS_CLOSING:
15825 		return (MIB2_TCP_closing);
15826 	case TCPS_LAST_ACK:
15827 		return (MIB2_TCP_lastAck);
15828 	case TCPS_FIN_WAIT_2:
15829 		return (MIB2_TCP_finWait2);
15830 	case TCPS_TIME_WAIT:
15831 		return (MIB2_TCP_timeWait);
15832 	default:
15833 		return (0);
15834 	}
15835 }
15836 
15837 static char tcp_report_header[] =
15838 	"TCP     " MI_COL_HDRPAD_STR
15839 	"zone dest            snxt     suna     "
15840 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
15841 	"recent   [lport,fport] state";
15842 
15843 /*
15844  * TCP status report triggered via the Named Dispatch mechanism.
15845  */
15846 /* ARGSUSED */
15847 static void
15848 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
15849     cred_t *cr)
15850 {
15851 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
15852 	boolean_t ispriv = secpolicy_net_config(cr, B_TRUE) == 0;
15853 	char cflag;
15854 	in6_addr_t	v6dst;
15855 	char buf[80];
15856 	uint_t print_len, buf_len;
15857 
15858 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15859 	if (buf_len <= 0)
15860 		return;
15861 
15862 	if (hashval >= 0)
15863 		(void) sprintf(hash, "%03d ", hashval);
15864 	else
15865 		hash[0] = '\0';
15866 
15867 	/*
15868 	 * Note that we use the remote address in the tcp_b  structure.
15869 	 * This means that it will print out the real destination address,
15870 	 * not the next hop's address if source routing is used.  This
15871 	 * avoid the confusion on the output because user may not
15872 	 * know that source routing is used for a connection.
15873 	 */
15874 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15875 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
15876 	} else {
15877 		v6dst = tcp->tcp_remote_v6;
15878 	}
15879 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15880 	/*
15881 	 * the ispriv checks are so that normal users cannot determine
15882 	 * sequence number information using NDD.
15883 	 */
15884 
15885 	if (TCP_IS_DETACHED(tcp))
15886 		cflag = '*';
15887 	else
15888 		cflag = ' ';
15889 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15890 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
15891 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
15892 	    hash,
15893 	    (void *)tcp,
15894 	    tcp->tcp_connp->conn_zoneid,
15895 	    addrbuf,
15896 	    (ispriv) ? tcp->tcp_snxt : 0,
15897 	    (ispriv) ? tcp->tcp_suna : 0,
15898 	    tcp->tcp_swnd,
15899 	    (ispriv) ? tcp->tcp_rnxt : 0,
15900 	    (ispriv) ? tcp->tcp_rack : 0,
15901 	    tcp->tcp_rwnd,
15902 	    tcp->tcp_rto,
15903 	    tcp->tcp_mss,
15904 	    tcp->tcp_snd_ws_ok,
15905 	    tcp->tcp_snd_ws,
15906 	    tcp->tcp_rcv_ws,
15907 	    tcp->tcp_snd_ts_ok,
15908 	    tcp->tcp_ts_recent,
15909 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
15910 	if (print_len < buf_len) {
15911 		((mblk_t *)mp)->b_wptr += print_len;
15912 	} else {
15913 		((mblk_t *)mp)->b_wptr += buf_len;
15914 	}
15915 }
15916 
15917 /*
15918  * TCP status report (for listeners only) triggered via the Named Dispatch
15919  * mechanism.
15920  */
15921 /* ARGSUSED */
15922 static void
15923 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
15924 {
15925 	char addrbuf[INET6_ADDRSTRLEN];
15926 	in6_addr_t	v6dst;
15927 	uint_t print_len, buf_len;
15928 
15929 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
15930 	if (buf_len <= 0)
15931 		return;
15932 
15933 	if (tcp->tcp_ipversion == IPV4_VERSION) {
15934 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
15935 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
15936 	} else {
15937 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
15938 		    addrbuf, sizeof (addrbuf));
15939 	}
15940 	print_len = snprintf((char *)mp->b_wptr, buf_len,
15941 	    "%03d "
15942 	    MI_COL_PTRFMT_STR
15943 	    "%d %s %05u %08u %d/%d/%d%c\n",
15944 	    hashval, (void *)tcp,
15945 	    tcp->tcp_connp->conn_zoneid,
15946 	    addrbuf,
15947 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
15948 	    tcp->tcp_conn_req_seqnum,
15949 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
15950 	    tcp->tcp_conn_req_max,
15951 	    tcp->tcp_syn_defense ? '*' : ' ');
15952 	if (print_len < buf_len) {
15953 		((mblk_t *)mp)->b_wptr += print_len;
15954 	} else {
15955 		((mblk_t *)mp)->b_wptr += buf_len;
15956 	}
15957 }
15958 
15959 /* TCP status report triggered via the Named Dispatch mechanism. */
15960 /* ARGSUSED */
15961 static int
15962 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
15963 {
15964 	tcp_t	*tcp;
15965 	int	i;
15966 	conn_t	*connp;
15967 	connf_t	*connfp;
15968 	zoneid_t zoneid;
15969 
15970 	/*
15971 	 * Because of the ndd constraint, at most we can have 64K buffer
15972 	 * to put in all TCP info.  So to be more efficient, just
15973 	 * allocate a 64K buffer here, assuming we need that large buffer.
15974 	 * This may be a problem as any user can read tcp_status.  Therefore
15975 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
15976 	 * This should be OK as normal users should not do this too often.
15977 	 */
15978 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
15979 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
15980 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
15981 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
15982 			return (0);
15983 		}
15984 	}
15985 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
15986 		/* The following may work even if we cannot get a large buf. */
15987 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
15988 		return (0);
15989 	}
15990 
15991 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
15992 
15993 	zoneid = Q_TO_CONN(q)->conn_zoneid;
15994 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
15995 
15996 		connfp = &ipcl_globalhash_fanout[i];
15997 
15998 		connp = NULL;
15999 
16000 		while ((connp =
16001 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16002 			tcp = connp->conn_tcp;
16003 			if (zoneid != GLOBAL_ZONEID &&
16004 			    zoneid != connp->conn_zoneid)
16005 				continue;
16006 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16007 			    cr);
16008 		}
16009 
16010 	}
16011 
16012 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16013 	return (0);
16014 }
16015 
16016 /* TCP status report triggered via the Named Dispatch mechanism. */
16017 /* ARGSUSED */
16018 static int
16019 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16020 {
16021 	tf_t	*tbf;
16022 	tcp_t	*tcp;
16023 	int	i;
16024 	zoneid_t zoneid;
16025 
16026 	/* Refer to comments in tcp_status_report(). */
16027 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16028 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16029 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16030 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16031 			return (0);
16032 		}
16033 	}
16034 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16035 		/* The following may work even if we cannot get a large buf. */
16036 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16037 		return (0);
16038 	}
16039 
16040 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16041 
16042 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16043 
16044 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
16045 		tbf = &tcp_bind_fanout[i];
16046 		mutex_enter(&tbf->tf_lock);
16047 		for (tcp = tbf->tf_tcp; tcp != NULL;
16048 		    tcp = tcp->tcp_bind_hash) {
16049 			if (zoneid != GLOBAL_ZONEID &&
16050 			    zoneid != tcp->tcp_connp->conn_zoneid)
16051 				continue;
16052 			CONN_INC_REF(tcp->tcp_connp);
16053 			tcp_report_item(mp->b_cont, tcp, i,
16054 			    Q_TO_TCP(q), cr);
16055 			CONN_DEC_REF(tcp->tcp_connp);
16056 		}
16057 		mutex_exit(&tbf->tf_lock);
16058 	}
16059 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16060 	return (0);
16061 }
16062 
16063 /* TCP status report triggered via the Named Dispatch mechanism. */
16064 /* ARGSUSED */
16065 static int
16066 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16067 {
16068 	connf_t	*connfp;
16069 	conn_t	*connp;
16070 	tcp_t	*tcp;
16071 	int	i;
16072 	zoneid_t zoneid;
16073 
16074 	/* Refer to comments in tcp_status_report(). */
16075 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16076 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16077 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16078 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16079 			return (0);
16080 		}
16081 	}
16082 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16083 		/* The following may work even if we cannot get a large buf. */
16084 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16085 		return (0);
16086 	}
16087 
16088 	(void) mi_mpprintf(mp,
16089 	    "    TCP    " MI_COL_HDRPAD_STR
16090 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
16091 
16092 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16093 
16094 	for (i = 0; i < ipcl_bind_fanout_size; i++) {
16095 		connfp =  &ipcl_bind_fanout[i];
16096 		connp = NULL;
16097 		while ((connp =
16098 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16099 			tcp = connp->conn_tcp;
16100 			if (zoneid != GLOBAL_ZONEID &&
16101 			    zoneid != connp->conn_zoneid)
16102 				continue;
16103 			tcp_report_listener(mp->b_cont, tcp, i);
16104 		}
16105 	}
16106 
16107 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16108 	return (0);
16109 }
16110 
16111 /* TCP status report triggered via the Named Dispatch mechanism. */
16112 /* ARGSUSED */
16113 static int
16114 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16115 {
16116 	connf_t	*connfp;
16117 	conn_t	*connp;
16118 	tcp_t	*tcp;
16119 	int	i;
16120 	zoneid_t zoneid;
16121 
16122 	/* Refer to comments in tcp_status_report(). */
16123 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16124 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16125 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16126 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16127 			return (0);
16128 		}
16129 	}
16130 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16131 		/* The following may work even if we cannot get a large buf. */
16132 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16133 		return (0);
16134 	}
16135 
16136 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16137 	    ipcl_conn_fanout_size);
16138 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16139 
16140 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16141 
16142 	for (i = 0; i < ipcl_conn_fanout_size; i++) {
16143 		connfp =  &ipcl_conn_fanout[i];
16144 		connp = NULL;
16145 		while ((connp =
16146 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16147 			tcp = connp->conn_tcp;
16148 			if (zoneid != GLOBAL_ZONEID &&
16149 			    zoneid != connp->conn_zoneid)
16150 				continue;
16151 			tcp_report_item(mp->b_cont, tcp, i,
16152 			    Q_TO_TCP(q), cr);
16153 		}
16154 	}
16155 
16156 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16157 	return (0);
16158 }
16159 
16160 /* TCP status report triggered via the Named Dispatch mechanism. */
16161 /* ARGSUSED */
16162 static int
16163 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16164 {
16165 	tf_t	*tf;
16166 	tcp_t	*tcp;
16167 	int	i;
16168 	zoneid_t zoneid;
16169 
16170 	/* Refer to comments in tcp_status_report(). */
16171 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
16172 		if (ddi_get_lbolt() - tcp_last_ndd_get_info_time <
16173 		    drv_usectohz(tcp_ndd_get_info_interval * 1000)) {
16174 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16175 			return (0);
16176 		}
16177 	}
16178 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16179 		/* The following may work even if we cannot get a large buf. */
16180 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16181 		return (0);
16182 	}
16183 
16184 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16185 
16186 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16187 
16188 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
16189 		tf = &tcp_acceptor_fanout[i];
16190 		mutex_enter(&tf->tf_lock);
16191 		for (tcp = tf->tf_tcp; tcp != NULL;
16192 		    tcp = tcp->tcp_acceptor_hash) {
16193 			if (zoneid != GLOBAL_ZONEID &&
16194 			    zoneid != tcp->tcp_connp->conn_zoneid)
16195 				continue;
16196 			tcp_report_item(mp->b_cont, tcp, i,
16197 			    Q_TO_TCP(q), cr);
16198 		}
16199 		mutex_exit(&tf->tf_lock);
16200 	}
16201 	tcp_last_ndd_get_info_time = ddi_get_lbolt();
16202 	return (0);
16203 }
16204 
16205 /*
16206  * tcp_timer is the timer service routine.  It handles the retransmission,
16207  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16208  * from the state of the tcp instance what kind of action needs to be done
16209  * at the time it is called.
16210  */
16211 static void
16212 tcp_timer(void *arg)
16213 {
16214 	mblk_t		*mp;
16215 	clock_t		first_threshold;
16216 	clock_t		second_threshold;
16217 	clock_t		ms;
16218 	uint32_t	mss;
16219 	conn_t		*connp = (conn_t *)arg;
16220 	tcp_t		*tcp = connp->conn_tcp;
16221 
16222 	tcp->tcp_timer_tid = 0;
16223 
16224 	if (tcp->tcp_fused)
16225 		return;
16226 
16227 	first_threshold =  tcp->tcp_first_timer_threshold;
16228 	second_threshold = tcp->tcp_second_timer_threshold;
16229 	switch (tcp->tcp_state) {
16230 	case TCPS_IDLE:
16231 	case TCPS_BOUND:
16232 	case TCPS_LISTEN:
16233 		return;
16234 	case TCPS_SYN_RCVD: {
16235 		tcp_t	*listener = tcp->tcp_listener;
16236 
16237 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16238 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16239 			/* it's our first timeout */
16240 			tcp->tcp_syn_rcvd_timeout = 1;
16241 			mutex_enter(&listener->tcp_eager_lock);
16242 			listener->tcp_syn_rcvd_timeout++;
16243 			if (!listener->tcp_syn_defense &&
16244 			    (listener->tcp_syn_rcvd_timeout >
16245 			    (tcp_conn_req_max_q0 >> 2)) &&
16246 			    (tcp_conn_req_max_q0 > 200)) {
16247 				/* We may be under attack. Put on a defense. */
16248 				listener->tcp_syn_defense = B_TRUE;
16249 				cmn_err(CE_WARN, "High TCP connect timeout "
16250 				    "rate! System (port %d) may be under a "
16251 				    "SYN flood attack!",
16252 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
16253 
16254 				listener->tcp_ip_addr_cache = kmem_zalloc(
16255 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
16256 				    KM_NOSLEEP);
16257 			}
16258 			mutex_exit(&listener->tcp_eager_lock);
16259 		}
16260 	}
16261 		/* FALLTHRU */
16262 	case TCPS_SYN_SENT:
16263 		first_threshold =  tcp->tcp_first_ctimer_threshold;
16264 		second_threshold = tcp->tcp_second_ctimer_threshold;
16265 		break;
16266 	case TCPS_ESTABLISHED:
16267 	case TCPS_FIN_WAIT_1:
16268 	case TCPS_CLOSING:
16269 	case TCPS_CLOSE_WAIT:
16270 	case TCPS_LAST_ACK:
16271 		/* If we have data to rexmit */
16272 		if (tcp->tcp_suna != tcp->tcp_snxt) {
16273 			clock_t	time_to_wait;
16274 
16275 			BUMP_MIB(&tcp_mib, tcpTimRetrans);
16276 			if (!tcp->tcp_xmit_head)
16277 				break;
16278 			time_to_wait = lbolt -
16279 			    (clock_t)tcp->tcp_xmit_head->b_prev;
16280 			time_to_wait = tcp->tcp_rto -
16281 			    TICK_TO_MSEC(time_to_wait);
16282 			/*
16283 			 * If the timer fires too early, 1 clock tick earlier,
16284 			 * restart the timer.
16285 			 */
16286 			if (time_to_wait > msec_per_tick) {
16287 				TCP_STAT(tcp_timer_fire_early);
16288 				TCP_TIMER_RESTART(tcp, time_to_wait);
16289 				return;
16290 			}
16291 			/*
16292 			 * When we probe zero windows, we force the swnd open.
16293 			 * If our peer acks with a closed window swnd will be
16294 			 * set to zero by tcp_rput(). As long as we are
16295 			 * receiving acks tcp_rput will
16296 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
16297 			 * first and second interval actions.  NOTE: the timer
16298 			 * interval is allowed to continue its exponential
16299 			 * backoff.
16300 			 */
16301 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
16302 				if (tcp->tcp_debug) {
16303 					(void) strlog(TCP_MOD_ID, 0, 1,
16304 					    SL_TRACE, "tcp_timer: zero win");
16305 				}
16306 			} else {
16307 				/*
16308 				 * After retransmission, we need to do
16309 				 * slow start.  Set the ssthresh to one
16310 				 * half of current effective window and
16311 				 * cwnd to one MSS.  Also reset
16312 				 * tcp_cwnd_cnt.
16313 				 *
16314 				 * Note that if tcp_ssthresh is reduced because
16315 				 * of ECN, do not reduce it again unless it is
16316 				 * already one window of data away (tcp_cwr
16317 				 * should then be cleared) or this is a
16318 				 * timeout for a retransmitted segment.
16319 				 */
16320 				uint32_t npkt;
16321 
16322 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
16323 					npkt = ((tcp->tcp_timer_backoff ?
16324 					    tcp->tcp_cwnd_ssthresh :
16325 					    tcp->tcp_snxt -
16326 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
16327 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
16328 					    tcp->tcp_mss;
16329 				}
16330 				tcp->tcp_cwnd = tcp->tcp_mss;
16331 				tcp->tcp_cwnd_cnt = 0;
16332 				if (tcp->tcp_ecn_ok) {
16333 					tcp->tcp_cwr = B_TRUE;
16334 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
16335 					tcp->tcp_ecn_cwr_sent = B_FALSE;
16336 				}
16337 			}
16338 			break;
16339 		}
16340 		/*
16341 		 * We have something to send yet we cannot send.  The
16342 		 * reason can be:
16343 		 *
16344 		 * 1. Zero send window: we need to do zero window probe.
16345 		 * 2. Zero cwnd: because of ECN, we need to "clock out
16346 		 * segments.
16347 		 * 3. SWS avoidance: receiver may have shrunk window,
16348 		 * reset our knowledge.
16349 		 *
16350 		 * Note that condition 2 can happen with either 1 or
16351 		 * 3.  But 1 and 3 are exclusive.
16352 		 */
16353 		if (tcp->tcp_unsent != 0) {
16354 			if (tcp->tcp_cwnd == 0) {
16355 				/*
16356 				 * Set tcp_cwnd to 1 MSS so that a
16357 				 * new segment can be sent out.  We
16358 				 * are "clocking out" new data when
16359 				 * the network is really congested.
16360 				 */
16361 				ASSERT(tcp->tcp_ecn_ok);
16362 				tcp->tcp_cwnd = tcp->tcp_mss;
16363 			}
16364 			if (tcp->tcp_swnd == 0) {
16365 				/* Extend window for zero window probe */
16366 				tcp->tcp_swnd++;
16367 				tcp->tcp_zero_win_probe = B_TRUE;
16368 				BUMP_MIB(&tcp_mib, tcpOutWinProbe);
16369 			} else {
16370 				/*
16371 				 * Handle timeout from sender SWS avoidance.
16372 				 * Reset our knowledge of the max send window
16373 				 * since the receiver might have reduced its
16374 				 * receive buffer.  Avoid setting tcp_max_swnd
16375 				 * to one since that will essentially disable
16376 				 * the SWS checks.
16377 				 *
16378 				 * Note that since we don't have a SWS
16379 				 * state variable, if the timeout is set
16380 				 * for ECN but not for SWS, this
16381 				 * code will also be executed.  This is
16382 				 * fine as tcp_max_swnd is updated
16383 				 * constantly and it will not affect
16384 				 * anything.
16385 				 */
16386 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
16387 			}
16388 			tcp_wput_data(tcp, NULL, B_FALSE);
16389 			return;
16390 		}
16391 		/* Is there a FIN that needs to be to re retransmitted? */
16392 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16393 		    !tcp->tcp_fin_acked)
16394 			break;
16395 		/* Nothing to do, return without restarting timer. */
16396 		TCP_STAT(tcp_timer_fire_miss);
16397 		return;
16398 	case TCPS_FIN_WAIT_2:
16399 		/*
16400 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
16401 		 * We waited some time for for peer's FIN, but it hasn't
16402 		 * arrived.  We flush the connection now to avoid
16403 		 * case where the peer has rebooted.
16404 		 */
16405 		if (TCP_IS_DETACHED(tcp)) {
16406 			(void) tcp_clean_death(tcp, 0, 23);
16407 		} else {
16408 			TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval);
16409 		}
16410 		return;
16411 	case TCPS_TIME_WAIT:
16412 		(void) tcp_clean_death(tcp, 0, 24);
16413 		return;
16414 	default:
16415 		if (tcp->tcp_debug) {
16416 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
16417 			    "tcp_timer: strange state (%d) %s",
16418 			    tcp->tcp_state, tcp_display(tcp, NULL,
16419 			    DISP_PORT_ONLY));
16420 		}
16421 		return;
16422 	}
16423 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
16424 		/*
16425 		 * For zero window probe, we need to send indefinitely,
16426 		 * unless we have not heard from the other side for some
16427 		 * time...
16428 		 */
16429 		if ((tcp->tcp_zero_win_probe == 0) ||
16430 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
16431 		    second_threshold)) {
16432 			BUMP_MIB(&tcp_mib, tcpTimRetransDrop);
16433 			/*
16434 			 * If TCP is in SYN_RCVD state, send back a
16435 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
16436 			 * should be zero in TCPS_SYN_RCVD state.
16437 			 */
16438 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
16439 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
16440 				    "in SYN_RCVD",
16441 				    tcp, tcp->tcp_snxt,
16442 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
16443 			}
16444 			(void) tcp_clean_death(tcp,
16445 			    tcp->tcp_client_errno ?
16446 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
16447 			return;
16448 		} else {
16449 			/*
16450 			 * Set tcp_ms_we_have_waited to second_threshold
16451 			 * so that in next timeout, we will do the above
16452 			 * check (lbolt - tcp_last_recv_time).  This is
16453 			 * also to avoid overflow.
16454 			 *
16455 			 * We don't need to decrement tcp_timer_backoff
16456 			 * to avoid overflow because it will be decremented
16457 			 * later if new timeout value is greater than
16458 			 * tcp_rexmit_interval_max.  In the case when
16459 			 * tcp_rexmit_interval_max is greater than
16460 			 * second_threshold, it means that we will wait
16461 			 * longer than second_threshold to send the next
16462 			 * window probe.
16463 			 */
16464 			tcp->tcp_ms_we_have_waited = second_threshold;
16465 		}
16466 	} else if (ms > first_threshold) {
16467 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
16468 		    tcp->tcp_xmit_head != NULL) {
16469 			tcp->tcp_xmit_head =
16470 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
16471 		}
16472 		/*
16473 		 * We have been retransmitting for too long...  The RTT
16474 		 * we calculated is probably incorrect.  Reinitialize it.
16475 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
16476 		 * tcp_rtt_update so that we won't accidentally cache a
16477 		 * bad value.  But only do this if this is not a zero
16478 		 * window probe.
16479 		 */
16480 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
16481 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
16482 			    (tcp->tcp_rtt_sa >> 5);
16483 			tcp->tcp_rtt_sa = 0;
16484 			tcp_ip_notify(tcp);
16485 			tcp->tcp_rtt_update = 0;
16486 		}
16487 	}
16488 	tcp->tcp_timer_backoff++;
16489 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
16490 	    tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
16491 	    tcp_rexmit_interval_min) {
16492 		/*
16493 		 * This means the original RTO is tcp_rexmit_interval_min.
16494 		 * So we will use tcp_rexmit_interval_min as the RTO value
16495 		 * and do the backoff.
16496 		 */
16497 		ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff;
16498 	} else {
16499 		ms <<= tcp->tcp_timer_backoff;
16500 	}
16501 	if (ms > tcp_rexmit_interval_max) {
16502 		ms = tcp_rexmit_interval_max;
16503 		/*
16504 		 * ms is at max, decrement tcp_timer_backoff to avoid
16505 		 * overflow.
16506 		 */
16507 		tcp->tcp_timer_backoff--;
16508 	}
16509 	tcp->tcp_ms_we_have_waited += ms;
16510 	if (tcp->tcp_zero_win_probe == 0) {
16511 		tcp->tcp_rto = ms;
16512 	}
16513 	TCP_TIMER_RESTART(tcp, ms);
16514 	/*
16515 	 * This is after a timeout and tcp_rto is backed off.  Set
16516 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
16517 	 * restart the timer with a correct value.
16518 	 */
16519 	tcp->tcp_set_timer = 1;
16520 	mss = tcp->tcp_snxt - tcp->tcp_suna;
16521 	if (mss > tcp->tcp_mss)
16522 		mss = tcp->tcp_mss;
16523 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
16524 		mss = tcp->tcp_swnd;
16525 
16526 	if ((mp = tcp->tcp_xmit_head) != NULL)
16527 		mp->b_prev = (mblk_t *)lbolt;
16528 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
16529 	    B_TRUE);
16530 
16531 	/*
16532 	 * When slow start after retransmission begins, start with
16533 	 * this seq no.  tcp_rexmit_max marks the end of special slow
16534 	 * start phase.  tcp_snd_burst controls how many segments
16535 	 * can be sent because of an ack.
16536 	 */
16537 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
16538 	tcp->tcp_snd_burst = TCP_CWND_SS;
16539 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
16540 	    (tcp->tcp_unsent == 0)) {
16541 		tcp->tcp_rexmit_max = tcp->tcp_fss;
16542 	} else {
16543 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
16544 	}
16545 	tcp->tcp_rexmit = B_TRUE;
16546 	tcp->tcp_dupack_cnt = 0;
16547 
16548 	/*
16549 	 * Remove all rexmit SACK blk to start from fresh.
16550 	 */
16551 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16552 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
16553 		tcp->tcp_num_notsack_blk = 0;
16554 		tcp->tcp_cnt_notsack_list = 0;
16555 	}
16556 	if (mp == NULL) {
16557 		return;
16558 	}
16559 	/* Attach credentials to retransmitted initial SYNs. */
16560 	if (tcp->tcp_state == TCPS_SYN_SENT) {
16561 		mblk_setcred(mp, tcp->tcp_cred);
16562 		DB_CPID(mp) = tcp->tcp_cpid;
16563 	}
16564 
16565 	tcp->tcp_csuna = tcp->tcp_snxt;
16566 	BUMP_MIB(&tcp_mib, tcpRetransSegs);
16567 	UPDATE_MIB(&tcp_mib, tcpRetransBytes, mss);
16568 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
16569 	tcp_send_data(tcp, tcp->tcp_wq, mp);
16570 
16571 }
16572 
16573 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
16574 static void
16575 tcp_unbind(tcp_t *tcp, mblk_t *mp)
16576 {
16577 	conn_t	*connp;
16578 
16579 	switch (tcp->tcp_state) {
16580 	case TCPS_BOUND:
16581 	case TCPS_LISTEN:
16582 		break;
16583 	default:
16584 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
16585 		return;
16586 	}
16587 
16588 	/*
16589 	 * Need to clean up all the eagers since after the unbind, segments
16590 	 * will no longer be delivered to this listener stream.
16591 	 */
16592 	mutex_enter(&tcp->tcp_eager_lock);
16593 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
16594 		tcp_eager_cleanup(tcp, 0);
16595 	}
16596 	mutex_exit(&tcp->tcp_eager_lock);
16597 
16598 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16599 		tcp->tcp_ipha->ipha_src = 0;
16600 	} else {
16601 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
16602 	}
16603 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
16604 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
16605 	tcp_bind_hash_remove(tcp);
16606 	tcp->tcp_state = TCPS_IDLE;
16607 	tcp->tcp_mdt = B_FALSE;
16608 	/* Send M_FLUSH according to TPI */
16609 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
16610 	connp = tcp->tcp_connp;
16611 	connp->conn_mdt_ok = B_FALSE;
16612 	ipcl_hash_remove(connp);
16613 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
16614 	mp = mi_tpi_ok_ack_alloc(mp);
16615 	putnext(tcp->tcp_rq, mp);
16616 }
16617 
16618 /*
16619  * Don't let port fall into the privileged range.
16620  * Since the extra privileged ports can be arbitrary we also
16621  * ensure that we exclude those from consideration.
16622  * tcp_g_epriv_ports is not sorted thus we loop over it until
16623  * there are no changes.
16624  *
16625  * Note: No locks are held when inspecting tcp_g_*epriv_ports
16626  * but instead the code relies on:
16627  * - the fact that the address of the array and its size never changes
16628  * - the atomic assignment of the elements of the array
16629  */
16630 static in_port_t
16631 tcp_update_next_port(in_port_t port, boolean_t random)
16632 {
16633 	int i;
16634 
16635 	if (random && tcp_random_anon_port != 0) {
16636 		(void) random_get_pseudo_bytes((uint8_t *)&port,
16637 		    sizeof (in_port_t));
16638 		/*
16639 		 * Unless changed by a sys admin, the smallest anon port
16640 		 * is 32768 and the largest anon port is 65535.  It is
16641 		 * very likely (50%) for the random port to be smaller
16642 		 * than the smallest anon port.  When that happens,
16643 		 * add port % (anon port range) to the smallest anon
16644 		 * port to get the random port.  It should fall into the
16645 		 * valid anon port range.
16646 		 */
16647 		if (port < tcp_smallest_anon_port) {
16648 			port = tcp_smallest_anon_port +
16649 			    port % (tcp_largest_anon_port -
16650 				tcp_smallest_anon_port);
16651 		}
16652 	}
16653 
16654 retry:
16655 	if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port)
16656 		port = (in_port_t)tcp_smallest_anon_port;
16657 
16658 	if (port < tcp_smallest_nonpriv_port)
16659 		port = (in_port_t)tcp_smallest_nonpriv_port;
16660 
16661 	for (i = 0; i < tcp_g_num_epriv_ports; i++) {
16662 		if (port == tcp_g_epriv_ports[i]) {
16663 			port++;
16664 			/*
16665 			 * Make sure whether the port is in the
16666 			 * valid range.
16667 			 *
16668 			 * XXX Note that if tcp_g_epriv_ports contains
16669 			 * all the anonymous ports this will be an
16670 			 * infinite loop.
16671 			 */
16672 			goto retry;
16673 		}
16674 	}
16675 	return (port);
16676 }
16677 
16678 /*
16679  * Return the next anonymous port in the priviledged port range for
16680  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
16681  * downwards.  This is the same behavior as documented in the userland
16682  * library call rresvport(3N).
16683  */
16684 static in_port_t
16685 tcp_get_next_priv_port(void)
16686 {
16687 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
16688 
16689 	if (next_priv_port < tcp_min_anonpriv_port) {
16690 		next_priv_port = IPPORT_RESERVED - 1;
16691 	}
16692 	return (next_priv_port--);
16693 }
16694 
16695 /* The write side r/w procedure. */
16696 
16697 #if CCS_STATS
16698 struct {
16699 	struct {
16700 		int64_t count, bytes;
16701 	} tot, hit;
16702 } wrw_stats;
16703 #endif
16704 
16705 /*
16706  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
16707  * messages.
16708  */
16709 /* ARGSUSED */
16710 static void
16711 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
16712 {
16713 	conn_t	*connp = (conn_t *)arg;
16714 	tcp_t	*tcp = connp->conn_tcp;
16715 	queue_t	*q = tcp->tcp_wq;
16716 
16717 	ASSERT(DB_TYPE(mp) != M_IOCTL);
16718 	/*
16719 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
16720 	 * Once the close starts, streamhead and sockfs will not let any data
16721 	 * packets come down (close ensures that there are no threads using the
16722 	 * queue and no new threads will come down) but since qprocsoff()
16723 	 * hasn't happened yet, a M_FLUSH or some non data message might
16724 	 * get reflected back (in response to our own FLUSHRW) and get
16725 	 * processed after tcp_close() is done. The conn would still be valid
16726 	 * because a ref would have added but we need to check the state
16727 	 * before actually processing the packet.
16728 	 */
16729 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
16730 		freemsg(mp);
16731 		return;
16732 	}
16733 
16734 	switch (DB_TYPE(mp)) {
16735 	case M_IOCDATA:
16736 		tcp_wput_iocdata(tcp, mp);
16737 		break;
16738 	case M_FLUSH:
16739 		tcp_wput_flush(tcp, mp);
16740 		break;
16741 	default:
16742 		CALL_IP_WPUT(connp, q, mp);
16743 		break;
16744 	}
16745 }
16746 
16747 /*
16748  * The TCP fast path write put procedure.
16749  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
16750  */
16751 /* ARGSUSED */
16752 void
16753 tcp_output(void *arg, mblk_t *mp, void *arg2)
16754 {
16755 	int		len;
16756 	int		hdrlen;
16757 	int		plen;
16758 	mblk_t		*mp1;
16759 	uchar_t		*rptr;
16760 	uint32_t	snxt;
16761 	tcph_t		*tcph;
16762 	struct datab	*db;
16763 	uint32_t	suna;
16764 	uint32_t	mss;
16765 	ipaddr_t	*dst;
16766 	ipaddr_t	*src;
16767 	uint32_t	sum;
16768 	int		usable;
16769 	conn_t		*connp = (conn_t *)arg;
16770 	tcp_t		*tcp = connp->conn_tcp;
16771 	uint32_t	msize;
16772 
16773 	/*
16774 	 * Try and ASSERT the minimum possible references on the
16775 	 * conn early enough. Since we are executing on write side,
16776 	 * the connection is obviously not detached and that means
16777 	 * there is a ref each for TCP and IP. Since we are behind
16778 	 * the squeue, the minimum references needed are 3. If the
16779 	 * conn is in classifier hash list, there should be an
16780 	 * extra ref for that (we check both the possibilities).
16781 	 */
16782 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16783 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16784 
16785 	/* Bypass tcp protocol for fused tcp loopback */
16786 	if (tcp->tcp_fused) {
16787 		msize = msgdsize(mp);
16788 		mutex_enter(&connp->conn_lock);
16789 		tcp->tcp_squeue_bytes -= msize;
16790 		mutex_exit(&connp->conn_lock);
16791 
16792 		if (tcp_fuse_output(tcp, mp, msize))
16793 			return;
16794 	}
16795 
16796 	mss = tcp->tcp_mss;
16797 	if (tcp->tcp_xmit_zc_clean)
16798 		mp = tcp_zcopy_backoff(tcp, mp, 0);
16799 
16800 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
16801 	len = (int)(mp->b_wptr - mp->b_rptr);
16802 
16803 	/*
16804 	 * Criteria for fast path:
16805 	 *
16806 	 *   1. no unsent data
16807 	 *   2. single mblk in request
16808 	 *   3. connection established
16809 	 *   4. data in mblk
16810 	 *   5. len <= mss
16811 	 *   6. no tcp_valid bits
16812 	 */
16813 	if ((tcp->tcp_unsent != 0) ||
16814 	    (tcp->tcp_cork) ||
16815 	    (mp->b_cont != NULL) ||
16816 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
16817 	    (len == 0) ||
16818 	    (len > mss) ||
16819 	    (tcp->tcp_valid_bits != 0)) {
16820 		msize = msgdsize(mp);
16821 		mutex_enter(&connp->conn_lock);
16822 		tcp->tcp_squeue_bytes -= msize;
16823 		mutex_exit(&connp->conn_lock);
16824 
16825 		tcp_wput_data(tcp, mp, B_FALSE);
16826 		return;
16827 	}
16828 
16829 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
16830 	ASSERT(tcp->tcp_fin_sent == 0);
16831 
16832 	mutex_enter(&connp->conn_lock);
16833 	tcp->tcp_squeue_bytes -= len;
16834 	mutex_exit(&connp->conn_lock);
16835 
16836 	/* queue new packet onto retransmission queue */
16837 	if (tcp->tcp_xmit_head == NULL) {
16838 		tcp->tcp_xmit_head = mp;
16839 	} else {
16840 		tcp->tcp_xmit_last->b_cont = mp;
16841 	}
16842 	tcp->tcp_xmit_last = mp;
16843 	tcp->tcp_xmit_tail = mp;
16844 
16845 	/* find out how much we can send */
16846 	/* BEGIN CSTYLED */
16847 	/*
16848 	 *    un-acked           usable
16849 	 *  |--------------|-----------------|
16850 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
16851 	 */
16852 	/* END CSTYLED */
16853 
16854 	/* start sending from tcp_snxt */
16855 	snxt = tcp->tcp_snxt;
16856 
16857 	/*
16858 	 * Check to see if this connection has been idled for some
16859 	 * time and no ACK is expected.  If it is, we need to slow
16860 	 * start again to get back the connection's "self-clock" as
16861 	 * described in VJ's paper.
16862 	 *
16863 	 * Refer to the comment in tcp_mss_set() for the calculation
16864 	 * of tcp_cwnd after idle.
16865 	 */
16866 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
16867 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
16868 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
16869 	}
16870 
16871 	usable = tcp->tcp_swnd;		/* tcp window size */
16872 	if (usable > tcp->tcp_cwnd)
16873 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
16874 	usable -= snxt;		/* subtract stuff already sent */
16875 	suna = tcp->tcp_suna;
16876 	usable += suna;
16877 	/* usable can be < 0 if the congestion window is smaller */
16878 	if (len > usable) {
16879 		/* Can't send complete M_DATA in one shot */
16880 		goto slow;
16881 	}
16882 
16883 	if (tcp->tcp_flow_stopped &&
16884 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
16885 		tcp_clrqfull(tcp);
16886 	}
16887 
16888 	/*
16889 	 * determine if anything to send (Nagle).
16890 	 *
16891 	 *   1. len < tcp_mss (i.e. small)
16892 	 *   2. unacknowledged data present
16893 	 *   3. len < nagle limit
16894 	 *   4. last packet sent < nagle limit (previous packet sent)
16895 	 */
16896 	if ((len < mss) && (snxt != suna) &&
16897 	    (len < (int)tcp->tcp_naglim) &&
16898 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
16899 		/*
16900 		 * This was the first unsent packet and normally
16901 		 * mss < xmit_hiwater so there is no need to worry
16902 		 * about flow control. The next packet will go
16903 		 * through the flow control check in tcp_wput_data().
16904 		 */
16905 		/* leftover work from above */
16906 		tcp->tcp_unsent = len;
16907 		tcp->tcp_xmit_tail_unsent = len;
16908 
16909 		return;
16910 	}
16911 
16912 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
16913 
16914 	if (snxt == suna) {
16915 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16916 	}
16917 
16918 	/* we have always sent something */
16919 	tcp->tcp_rack_cnt = 0;
16920 
16921 	tcp->tcp_snxt = snxt + len;
16922 	tcp->tcp_rack = tcp->tcp_rnxt;
16923 
16924 	if ((mp1 = dupb(mp)) == 0)
16925 		goto no_memory;
16926 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
16927 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
16928 
16929 	/* adjust tcp header information */
16930 	tcph = tcp->tcp_tcph;
16931 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
16932 
16933 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
16934 	sum = (sum >> 16) + (sum & 0xFFFF);
16935 	U16_TO_ABE16(sum, tcph->th_sum);
16936 
16937 	U32_TO_ABE32(snxt, tcph->th_seq);
16938 
16939 	BUMP_MIB(&tcp_mib, tcpOutDataSegs);
16940 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
16941 	BUMP_LOCAL(tcp->tcp_obsegs);
16942 
16943 	/* Update the latest receive window size in TCP header. */
16944 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
16945 	    tcph->th_win);
16946 
16947 	tcp->tcp_last_sent_len = (ushort_t)len;
16948 
16949 	plen = len + tcp->tcp_hdr_len;
16950 
16951 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16952 		tcp->tcp_ipha->ipha_length = htons(plen);
16953 	} else {
16954 		tcp->tcp_ip6h->ip6_plen = htons(plen -
16955 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
16956 	}
16957 
16958 	/* see if we need to allocate a mblk for the headers */
16959 	hdrlen = tcp->tcp_hdr_len;
16960 	rptr = mp1->b_rptr - hdrlen;
16961 	db = mp1->b_datap;
16962 	if ((db->db_ref != 2) || rptr < db->db_base ||
16963 	    (!OK_32PTR(rptr))) {
16964 		/* NOTE: we assume allocb returns an OK_32PTR */
16965 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
16966 		    tcp_wroff_xtra, BPRI_MED);
16967 		if (!mp) {
16968 			freemsg(mp1);
16969 			goto no_memory;
16970 		}
16971 		mp->b_cont = mp1;
16972 		mp1 = mp;
16973 		/* Leave room for Link Level header */
16974 		/* hdrlen = tcp->tcp_hdr_len; */
16975 		rptr = &mp1->b_rptr[tcp_wroff_xtra];
16976 		mp1->b_wptr = &rptr[hdrlen];
16977 	}
16978 	mp1->b_rptr = rptr;
16979 
16980 	/* Fill in the timestamp option. */
16981 	if (tcp->tcp_snd_ts_ok) {
16982 		U32_TO_BE32((uint32_t)lbolt,
16983 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
16984 		U32_TO_BE32(tcp->tcp_ts_recent,
16985 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
16986 	} else {
16987 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
16988 	}
16989 
16990 	/* copy header into outgoing packet */
16991 	dst = (ipaddr_t *)rptr;
16992 	src = (ipaddr_t *)tcp->tcp_iphc;
16993 	dst[0] = src[0];
16994 	dst[1] = src[1];
16995 	dst[2] = src[2];
16996 	dst[3] = src[3];
16997 	dst[4] = src[4];
16998 	dst[5] = src[5];
16999 	dst[6] = src[6];
17000 	dst[7] = src[7];
17001 	dst[8] = src[8];
17002 	dst[9] = src[9];
17003 	if (hdrlen -= 40) {
17004 		hdrlen >>= 2;
17005 		dst += 10;
17006 		src += 10;
17007 		do {
17008 			*dst++ = *src++;
17009 		} while (--hdrlen);
17010 	}
17011 
17012 	/*
17013 	 * Set the ECN info in the TCP header.  Note that this
17014 	 * is not the template header.
17015 	 */
17016 	if (tcp->tcp_ecn_ok) {
17017 		SET_ECT(tcp, rptr);
17018 
17019 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17020 		if (tcp->tcp_ecn_echo_on)
17021 			tcph->th_flags[0] |= TH_ECE;
17022 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17023 			tcph->th_flags[0] |= TH_CWR;
17024 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17025 		}
17026 	}
17027 
17028 	if (tcp->tcp_ip_forward_progress) {
17029 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17030 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17031 		tcp->tcp_ip_forward_progress = B_FALSE;
17032 	}
17033 	TCP_RECORD_TRACE(tcp, mp1, TCP_TRACE_SEND_PKT);
17034 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17035 	return;
17036 
17037 	/*
17038 	 * If we ran out of memory, we pretend to have sent the packet
17039 	 * and that it was lost on the wire.
17040 	 */
17041 no_memory:
17042 	return;
17043 
17044 slow:
17045 	/* leftover work from above */
17046 	tcp->tcp_unsent = len;
17047 	tcp->tcp_xmit_tail_unsent = len;
17048 	tcp_wput_data(tcp, NULL, B_FALSE);
17049 }
17050 
17051 /*
17052  * The function called through squeue to get behind eager's perimeter to
17053  * finish the accept processing.
17054  */
17055 /* ARGSUSED */
17056 void
17057 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17058 {
17059 	conn_t			*connp = (conn_t *)arg;
17060 	tcp_t			*tcp = connp->conn_tcp;
17061 	queue_t			*q = tcp->tcp_rq;
17062 	mblk_t			*mp1;
17063 	mblk_t			*stropt_mp = mp;
17064 	struct  stroptions	*stropt;
17065 	uint_t			thwin;
17066 
17067 	/*
17068 	 * Drop the eager's ref on the listener, that was placed when
17069 	 * this eager began life in tcp_conn_request.
17070 	 */
17071 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17072 
17073 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17074 		/*
17075 		 * Someone blewoff the eager before we could finish
17076 		 * the accept.
17077 		 *
17078 		 * The only reason eager exists it because we put in
17079 		 * a ref on it when conn ind went up. We need to send
17080 		 * a disconnect indication up while the last reference
17081 		 * on the eager will be dropped by the squeue when we
17082 		 * return.
17083 		 */
17084 		ASSERT(tcp->tcp_listener == NULL);
17085 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17086 			struct	T_discon_ind	*tdi;
17087 
17088 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17089 			/*
17090 			 * Let us reuse the incoming mblk to avoid memory
17091 			 * allocation failure problems. We know that the
17092 			 * size of the incoming mblk i.e. stroptions is greater
17093 			 * than sizeof T_discon_ind. So the reallocb below
17094 			 * can't fail.
17095 			 */
17096 			freemsg(mp->b_cont);
17097 			mp->b_cont = NULL;
17098 			ASSERT(DB_REF(mp) == 1);
17099 			mp = reallocb(mp, sizeof (struct T_discon_ind),
17100 			    B_FALSE);
17101 			ASSERT(mp != NULL);
17102 			DB_TYPE(mp) = M_PROTO;
17103 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
17104 			tdi = (struct T_discon_ind *)mp->b_rptr;
17105 			if (tcp->tcp_issocket) {
17106 				tdi->DISCON_reason = ECONNREFUSED;
17107 				tdi->SEQ_number = 0;
17108 			} else {
17109 				tdi->DISCON_reason = ENOPROTOOPT;
17110 				tdi->SEQ_number =
17111 				    tcp->tcp_conn_req_seqnum;
17112 			}
17113 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
17114 			putnext(q, mp);
17115 		} else {
17116 			freemsg(mp);
17117 		}
17118 		if (tcp->tcp_hard_binding) {
17119 			tcp->tcp_hard_binding = B_FALSE;
17120 			tcp->tcp_hard_bound = B_TRUE;
17121 		}
17122 		tcp->tcp_detached = B_FALSE;
17123 		return;
17124 	}
17125 
17126 	mp1 = stropt_mp->b_cont;
17127 	stropt_mp->b_cont = NULL;
17128 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
17129 	stropt = (struct stroptions *)stropt_mp->b_rptr;
17130 
17131 	while (mp1 != NULL) {
17132 		mp = mp1;
17133 		mp1 = mp1->b_cont;
17134 		mp->b_cont = NULL;
17135 		tcp->tcp_drop_opt_ack_cnt++;
17136 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
17137 	}
17138 	mp = NULL;
17139 
17140 	/*
17141 	 * For a loopback connection with tcp_direct_sockfs on, note that
17142 	 * we don't have to protect tcp_rcv_list yet because synchronous
17143 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17144 	 * possibly race with us.
17145 	 */
17146 
17147 	/*
17148 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
17149 	 * properly.  This is the first time we know of the acceptor'
17150 	 * queue.  So we do it here.
17151 	 */
17152 	if (tcp->tcp_rcv_list == NULL) {
17153 		/*
17154 		 * Recv queue is empty, tcp_rwnd should not have changed.
17155 		 * That means it should be equal to the listener's tcp_rwnd.
17156 		 */
17157 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
17158 	} else {
17159 #ifdef DEBUG
17160 		uint_t cnt = 0;
17161 
17162 		mp1 = tcp->tcp_rcv_list;
17163 		while ((mp = mp1) != NULL) {
17164 			mp1 = mp->b_next;
17165 			cnt += msgdsize(mp);
17166 		}
17167 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
17168 #endif
17169 		/* There is some data, add them back to get the max. */
17170 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
17171 	}
17172 
17173 	stropt->so_flags = SO_HIWAT;
17174 	stropt->so_hiwat = MAX(q->q_hiwat, tcp_sth_rcv_hiwat);
17175 
17176 	stropt->so_flags |= SO_MAXBLK;
17177 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
17178 
17179 	/*
17180 	 * This is the first time we run on the correct
17181 	 * queue after tcp_accept. So fix all the q parameters
17182 	 * here.
17183 	 */
17184 	/* Allocate room for SACK options if needed. */
17185 	stropt->so_flags |= SO_WROFF;
17186 	if (tcp->tcp_fused) {
17187 		ASSERT(tcp->tcp_loopback);
17188 		ASSERT(tcp->tcp_loopback_peer != NULL);
17189 		/*
17190 		 * For fused tcp loopback, set the stream head's write
17191 		 * offset value to zero since we won't be needing any room
17192 		 * for TCP/IP headers.  This would also improve performance
17193 		 * since it would reduce the amount of work done by kmem.
17194 		 * Non-fused tcp loopback case is handled separately below.
17195 		 */
17196 		stropt->so_wroff = 0;
17197 		/*
17198 		 * Record the stream head's high water mark for this endpoint;
17199 		 * this is used for flow-control purposes in tcp_fuse_output().
17200 		 */
17201 		stropt->so_hiwat = tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat);
17202 		/*
17203 		 * Update the peer's transmit parameters according to
17204 		 * our recently calculated high water mark value.
17205 		 */
17206 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
17207 	} else if (tcp->tcp_snd_sack_ok) {
17208 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
17209 		    (tcp->tcp_loopback ? 0 : tcp_wroff_xtra);
17210 	} else {
17211 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
17212 		    tcp_wroff_xtra);
17213 	}
17214 
17215 	/*
17216 	 * If this is endpoint is handling SSL, then reserve extra
17217 	 * offset and space at the end.
17218 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
17219 	 * overriding the previous setting. The extra cost of signing and
17220 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
17221 	 * instead of a single contiguous one by the stream head
17222 	 * largely outweighs the statistical reduction of ACKs, when
17223 	 * applicable. The peer will also save on decyption and verification
17224 	 * costs.
17225 	 */
17226 	if (tcp->tcp_kssl_ctx != NULL) {
17227 		stropt->so_wroff += SSL3_WROFFSET;
17228 
17229 		stropt->so_flags |= SO_TAIL;
17230 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
17231 
17232 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
17233 	}
17234 
17235 	/* Send the options up */
17236 	putnext(q, stropt_mp);
17237 
17238 	/*
17239 	 * Pass up any data and/or a fin that has been received.
17240 	 *
17241 	 * Adjust receive window in case it had decreased
17242 	 * (because there is data <=> tcp_rcv_list != NULL)
17243 	 * while the connection was detached. Note that
17244 	 * in case the eager was flow-controlled, w/o this
17245 	 * code, the rwnd may never open up again!
17246 	 */
17247 	if (tcp->tcp_rcv_list != NULL) {
17248 		/* We drain directly in case of fused tcp loopback */
17249 		if (!tcp->tcp_fused && canputnext(q)) {
17250 			tcp->tcp_rwnd = q->q_hiwat;
17251 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
17252 			    << tcp->tcp_rcv_ws;
17253 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
17254 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
17255 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
17256 				tcp_xmit_ctl(NULL,
17257 				    tcp, (tcp->tcp_swnd == 0) ?
17258 				    tcp->tcp_suna : tcp->tcp_snxt,
17259 				    tcp->tcp_rnxt, TH_ACK);
17260 				BUMP_MIB(&tcp_mib, tcpOutWinUpdate);
17261 			}
17262 
17263 		}
17264 		(void) tcp_rcv_drain(q, tcp);
17265 
17266 		/*
17267 		 * For fused tcp loopback, back-enable peer endpoint
17268 		 * if it's currently flow-controlled.
17269 		 */
17270 		if (tcp->tcp_fused &&
17271 		    tcp->tcp_loopback_peer->tcp_flow_stopped) {
17272 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
17273 
17274 			ASSERT(peer_tcp != NULL);
17275 			ASSERT(peer_tcp->tcp_fused);
17276 
17277 			tcp_clrqfull(peer_tcp);
17278 			TCP_STAT(tcp_fusion_backenabled);
17279 		}
17280 	}
17281 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
17282 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
17283 		mp = mi_tpi_ordrel_ind();
17284 		if (mp) {
17285 			tcp->tcp_ordrel_done = B_TRUE;
17286 			putnext(q, mp);
17287 			if (tcp->tcp_deferred_clean_death) {
17288 				/*
17289 				 * tcp_clean_death was deferred
17290 				 * for T_ORDREL_IND - do it now
17291 				 */
17292 				(void) tcp_clean_death(tcp,
17293 				    tcp->tcp_client_errno, 21);
17294 				tcp->tcp_deferred_clean_death = B_FALSE;
17295 			}
17296 		} else {
17297 			/*
17298 			 * Run the orderly release in the
17299 			 * service routine.
17300 			 */
17301 			qenable(q);
17302 		}
17303 	}
17304 	if (tcp->tcp_hard_binding) {
17305 		tcp->tcp_hard_binding = B_FALSE;
17306 		tcp->tcp_hard_bound = B_TRUE;
17307 	}
17308 
17309 	tcp->tcp_detached = B_FALSE;
17310 
17311 	/* We can enable synchronous streams now */
17312 	if (tcp->tcp_fused) {
17313 		tcp_fuse_syncstr_enable_pair(tcp);
17314 	}
17315 
17316 	if (tcp->tcp_ka_enabled) {
17317 		tcp->tcp_ka_last_intrvl = 0;
17318 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
17319 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
17320 	}
17321 
17322 	/*
17323 	 * At this point, eager is fully established and will
17324 	 * have the following references -
17325 	 *
17326 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
17327 	 * 1 reference for the squeue which will be dropped by the squeue as
17328 	 *	soon as this function returns.
17329 	 * There will be 1 additonal reference for being in classifier
17330 	 *	hash list provided something bad hasn't happened.
17331 	 */
17332 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17333 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17334 }
17335 
17336 /*
17337  * The function called through squeue to get behind listener's perimeter to
17338  * send a deffered conn_ind.
17339  */
17340 /* ARGSUSED */
17341 void
17342 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
17343 {
17344 	conn_t	*connp = (conn_t *)arg;
17345 	tcp_t *listener = connp->conn_tcp;
17346 
17347 	if (listener->tcp_state == TCPS_CLOSED ||
17348 	    TCP_IS_DETACHED(listener)) {
17349 		/*
17350 		 * If listener has closed, it would have caused a
17351 		 * a cleanup/blowoff to happen for the eager.
17352 		 */
17353 		tcp_t *tcp;
17354 		struct T_conn_ind	*conn_ind;
17355 
17356 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
17357 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
17358 		    conn_ind->OPT_length);
17359 		/*
17360 		 * We need to drop the ref on eager that was put
17361 		 * tcp_rput_data() before trying to send the conn_ind
17362 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
17363 		 * and tcp_wput_accept() is sending this deferred conn_ind but
17364 		 * listener is closed so we drop the ref.
17365 		 */
17366 		CONN_DEC_REF(tcp->tcp_connp);
17367 		freemsg(mp);
17368 		return;
17369 	}
17370 	putnext(listener->tcp_rq, mp);
17371 }
17372 
17373 
17374 /*
17375  * This is the STREAMS entry point for T_CONN_RES coming down on
17376  * Acceptor STREAM when  sockfs listener does accept processing.
17377  * Read the block comment on top pf tcp_conn_request().
17378  */
17379 void
17380 tcp_wput_accept(queue_t *q, mblk_t *mp)
17381 {
17382 	queue_t *rq = RD(q);
17383 	struct T_conn_res *conn_res;
17384 	tcp_t *eager;
17385 	tcp_t *listener;
17386 	struct T_ok_ack *ok;
17387 	t_scalar_t PRIM_type;
17388 	mblk_t *opt_mp;
17389 	conn_t *econnp;
17390 
17391 	ASSERT(DB_TYPE(mp) == M_PROTO);
17392 
17393 	conn_res = (struct T_conn_res *)mp->b_rptr;
17394 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17395 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
17396 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17397 		if (mp != NULL)
17398 			putnext(rq, mp);
17399 		return;
17400 	}
17401 	switch (conn_res->PRIM_type) {
17402 	case O_T_CONN_RES:
17403 	case T_CONN_RES:
17404 		/*
17405 		 * We pass up an err ack if allocb fails. This will
17406 		 * cause sockfs to issue a T_DISCON_REQ which will cause
17407 		 * tcp_eager_blowoff to be called. sockfs will then call
17408 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
17409 		 * we need to do the allocb up here because we have to
17410 		 * make sure rq->q_qinfo->qi_qclose still points to the
17411 		 * correct function (tcpclose_accept) in case allocb
17412 		 * fails.
17413 		 */
17414 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
17415 		if (opt_mp == NULL) {
17416 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
17417 			if (mp != NULL)
17418 				putnext(rq, mp);
17419 			return;
17420 		}
17421 
17422 		bcopy(mp->b_rptr + conn_res->OPT_offset,
17423 		    &eager, conn_res->OPT_length);
17424 		PRIM_type = conn_res->PRIM_type;
17425 		mp->b_datap->db_type = M_PCPROTO;
17426 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
17427 		ok = (struct T_ok_ack *)mp->b_rptr;
17428 		ok->PRIM_type = T_OK_ACK;
17429 		ok->CORRECT_prim = PRIM_type;
17430 		econnp = eager->tcp_connp;
17431 		econnp->conn_dev = (dev_t)q->q_ptr;
17432 		eager->tcp_rq = rq;
17433 		eager->tcp_wq = q;
17434 		rq->q_ptr = econnp;
17435 		rq->q_qinfo = &tcp_rinit;
17436 		q->q_ptr = econnp;
17437 		q->q_qinfo = &tcp_winit;
17438 		listener = eager->tcp_listener;
17439 		eager->tcp_issocket = B_TRUE;
17440 		eager->tcp_cred = econnp->conn_cred =
17441 		    listener->tcp_connp->conn_cred;
17442 		crhold(econnp->conn_cred);
17443 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
17444 
17445 		/* Put the ref for IP */
17446 		CONN_INC_REF(econnp);
17447 
17448 		/*
17449 		 * We should have minimum of 3 references on the conn
17450 		 * at this point. One each for TCP and IP and one for
17451 		 * the T_conn_ind that was sent up when the 3-way handshake
17452 		 * completed. In the normal case we would also have another
17453 		 * reference (making a total of 4) for the conn being in the
17454 		 * classifier hash list. However the eager could have received
17455 		 * an RST subsequently and tcp_closei_local could have removed
17456 		 * the eager from the classifier hash list, hence we can't
17457 		 * assert that reference.
17458 		 */
17459 		ASSERT(econnp->conn_ref >= 3);
17460 
17461 		/*
17462 		 * Send the new local address also up to sockfs. There
17463 		 * should already be enough space in the mp that came
17464 		 * down from soaccept().
17465 		 */
17466 		if (eager->tcp_family == AF_INET) {
17467 			sin_t *sin;
17468 
17469 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17470 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
17471 			sin = (sin_t *)mp->b_wptr;
17472 			mp->b_wptr += sizeof (sin_t);
17473 			sin->sin_family = AF_INET;
17474 			sin->sin_port = eager->tcp_lport;
17475 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
17476 		} else {
17477 			sin6_t *sin6;
17478 
17479 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
17480 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
17481 			sin6 = (sin6_t *)mp->b_wptr;
17482 			mp->b_wptr += sizeof (sin6_t);
17483 			sin6->sin6_family = AF_INET6;
17484 			sin6->sin6_port = eager->tcp_lport;
17485 			if (eager->tcp_ipversion == IPV4_VERSION) {
17486 				sin6->sin6_flowinfo = 0;
17487 				IN6_IPADDR_TO_V4MAPPED(
17488 					eager->tcp_ipha->ipha_src,
17489 					    &sin6->sin6_addr);
17490 			} else {
17491 				ASSERT(eager->tcp_ip6h != NULL);
17492 				sin6->sin6_flowinfo =
17493 				    eager->tcp_ip6h->ip6_vcf &
17494 				    ~IPV6_VERS_AND_FLOW_MASK;
17495 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
17496 			}
17497 			sin6->sin6_scope_id = 0;
17498 			sin6->__sin6_src_id = 0;
17499 		}
17500 
17501 		putnext(rq, mp);
17502 
17503 		opt_mp->b_datap->db_type = M_SETOPTS;
17504 		opt_mp->b_wptr += sizeof (struct stroptions);
17505 
17506 		/*
17507 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
17508 		 * from listener to acceptor. The message is chained on the
17509 		 * bind_mp which tcp_rput_other will send down to IP.
17510 		 */
17511 		if (listener->tcp_bound_if != 0) {
17512 			/* allocate optmgmt req */
17513 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17514 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
17515 			    sizeof (int));
17516 			if (mp != NULL)
17517 				linkb(opt_mp, mp);
17518 		}
17519 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
17520 			uint_t on = 1;
17521 
17522 			/* allocate optmgmt req */
17523 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
17524 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
17525 			if (mp != NULL)
17526 				linkb(opt_mp, mp);
17527 		}
17528 
17529 
17530 		mutex_enter(&listener->tcp_eager_lock);
17531 
17532 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
17533 
17534 			tcp_t *tail;
17535 			tcp_t *tcp;
17536 			mblk_t *mp1;
17537 
17538 			tcp = listener->tcp_eager_prev_q0;
17539 			/*
17540 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
17541 			 * deferred T_conn_ind queue. We need to get to the head
17542 			 * of the queue in order to send up T_conn_ind the same
17543 			 * order as how the 3WHS is completed.
17544 			 */
17545 			while (tcp != listener) {
17546 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
17547 				    !tcp->tcp_kssl_pending)
17548 					break;
17549 				else
17550 					tcp = tcp->tcp_eager_prev_q0;
17551 			}
17552 			/* None of the pending eagers can be sent up now */
17553 			if (tcp == listener)
17554 				goto no_more_eagers;
17555 
17556 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
17557 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17558 			/* Move from q0 to q */
17559 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
17560 			listener->tcp_conn_req_cnt_q0--;
17561 			listener->tcp_conn_req_cnt_q++;
17562 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
17563 			    tcp->tcp_eager_prev_q0;
17564 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
17565 			    tcp->tcp_eager_next_q0;
17566 			tcp->tcp_eager_prev_q0 = NULL;
17567 			tcp->tcp_eager_next_q0 = NULL;
17568 			tcp->tcp_conn_def_q0 = B_FALSE;
17569 
17570 			/*
17571 			 * Insert at end of the queue because sockfs sends
17572 			 * down T_CONN_RES in chronological order. Leaving
17573 			 * the older conn indications at front of the queue
17574 			 * helps reducing search time.
17575 			 */
17576 			tail = listener->tcp_eager_last_q;
17577 			if (tail != NULL) {
17578 				tail->tcp_eager_next_q = tcp;
17579 			} else {
17580 				listener->tcp_eager_next_q = tcp;
17581 			}
17582 			listener->tcp_eager_last_q = tcp;
17583 			tcp->tcp_eager_next_q = NULL;
17584 
17585 			/* Need to get inside the listener perimeter */
17586 			CONN_INC_REF(listener->tcp_connp);
17587 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
17588 			    tcp_send_pending, listener->tcp_connp,
17589 			    SQTAG_TCP_SEND_PENDING);
17590 		}
17591 no_more_eagers:
17592 		tcp_eager_unlink(eager);
17593 		mutex_exit(&listener->tcp_eager_lock);
17594 
17595 		/*
17596 		 * At this point, the eager is detached from the listener
17597 		 * but we still have an extra refs on eager (apart from the
17598 		 * usual tcp references). The ref was placed in tcp_rput_data
17599 		 * before sending the conn_ind in tcp_send_conn_ind.
17600 		 * The ref will be dropped in tcp_accept_finish().
17601 		 */
17602 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
17603 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
17604 		return;
17605 	default:
17606 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
17607 		if (mp != NULL)
17608 			putnext(rq, mp);
17609 		return;
17610 	}
17611 }
17612 
17613 void
17614 tcp_wput(queue_t *q, mblk_t *mp)
17615 {
17616 	conn_t	*connp = Q_TO_CONN(q);
17617 	tcp_t	*tcp;
17618 	void (*output_proc)();
17619 	t_scalar_t type;
17620 	uchar_t *rptr;
17621 	struct iocblk	*iocp;
17622 	uint32_t	msize;
17623 
17624 	ASSERT(connp->conn_ref >= 2);
17625 
17626 	switch (DB_TYPE(mp)) {
17627 	case M_DATA:
17628 		tcp = connp->conn_tcp;
17629 		ASSERT(tcp != NULL);
17630 
17631 		msize = msgdsize(mp);
17632 
17633 		mutex_enter(&connp->conn_lock);
17634 		CONN_INC_REF_LOCKED(connp);
17635 
17636 		tcp->tcp_squeue_bytes += msize;
17637 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
17638 			mutex_exit(&connp->conn_lock);
17639 			tcp_setqfull(tcp);
17640 		} else
17641 			mutex_exit(&connp->conn_lock);
17642 
17643 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17644 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
17645 		return;
17646 	case M_PROTO:
17647 	case M_PCPROTO:
17648 		/*
17649 		 * if it is a snmp message, don't get behind the squeue
17650 		 */
17651 		tcp = connp->conn_tcp;
17652 		rptr = mp->b_rptr;
17653 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
17654 			type = ((union T_primitives *)rptr)->type;
17655 		} else {
17656 			if (tcp->tcp_debug) {
17657 				(void) strlog(TCP_MOD_ID, 0, 1,
17658 				    SL_ERROR|SL_TRACE,
17659 				    "tcp_wput_proto, dropping one...");
17660 			}
17661 			freemsg(mp);
17662 			return;
17663 		}
17664 		if (type == T_SVR4_OPTMGMT_REQ) {
17665 			cred_t	*cr = DB_CREDDEF(mp,
17666 			    tcp->tcp_cred);
17667 			if (snmpcom_req(q, mp, tcp_snmp_set, tcp_snmp_get,
17668 			    cr)) {
17669 				/*
17670 				 * This was a SNMP request
17671 				 */
17672 				return;
17673 			} else {
17674 				output_proc = tcp_wput_proto;
17675 			}
17676 		} else {
17677 			output_proc = tcp_wput_proto;
17678 		}
17679 		break;
17680 	case M_IOCTL:
17681 		/*
17682 		 * Most ioctls can be processed right away without going via
17683 		 * squeues - process them right here. Those that do require
17684 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
17685 		 * are processed by tcp_wput_ioctl().
17686 		 */
17687 		iocp = (struct iocblk *)mp->b_rptr;
17688 		tcp = connp->conn_tcp;
17689 
17690 		switch (iocp->ioc_cmd) {
17691 		case TCP_IOC_ABORT_CONN:
17692 			tcp_ioctl_abort_conn(q, mp);
17693 			return;
17694 		case TI_GETPEERNAME:
17695 			if (tcp->tcp_state < TCPS_SYN_RCVD) {
17696 				iocp->ioc_error = ENOTCONN;
17697 				iocp->ioc_count = 0;
17698 				mp->b_datap->db_type = M_IOCACK;
17699 				qreply(q, mp);
17700 				return;
17701 			}
17702 			/* FALLTHRU */
17703 		case TI_GETMYNAME:
17704 			mi_copyin(q, mp, NULL,
17705 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
17706 			return;
17707 		case ND_SET:
17708 			/* nd_getset does the necessary checks */
17709 		case ND_GET:
17710 			if (!nd_getset(q, tcp_g_nd, mp)) {
17711 				CALL_IP_WPUT(connp, q, mp);
17712 				return;
17713 			}
17714 			qreply(q, mp);
17715 			return;
17716 		case TCP_IOC_DEFAULT_Q:
17717 			/*
17718 			 * Wants to be the default wq. Check the credentials
17719 			 * first, the rest is executed via squeue.
17720 			 */
17721 			if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
17722 				iocp->ioc_error = EPERM;
17723 				iocp->ioc_count = 0;
17724 				mp->b_datap->db_type = M_IOCACK;
17725 				qreply(q, mp);
17726 				return;
17727 			}
17728 			output_proc = tcp_wput_ioctl;
17729 			break;
17730 		default:
17731 			output_proc = tcp_wput_ioctl;
17732 			break;
17733 		}
17734 		break;
17735 	default:
17736 		output_proc = tcp_wput_nondata;
17737 		break;
17738 	}
17739 
17740 	CONN_INC_REF(connp);
17741 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
17742 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
17743 }
17744 
17745 /*
17746  * Initial STREAMS write side put() procedure for sockets. It tries to
17747  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
17748  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
17749  * are handled by tcp_wput() as usual.
17750  *
17751  * All further messages will also be handled by tcp_wput() because we cannot
17752  * be sure that the above short cut is safe later.
17753  */
17754 static void
17755 tcp_wput_sock(queue_t *wq, mblk_t *mp)
17756 {
17757 	conn_t			*connp = Q_TO_CONN(wq);
17758 	tcp_t			*tcp = connp->conn_tcp;
17759 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
17760 
17761 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
17762 	wq->q_qinfo = &tcp_winit;
17763 
17764 	ASSERT(IPCL_IS_TCP(connp));
17765 	ASSERT(TCP_IS_SOCKET(tcp));
17766 
17767 	if (DB_TYPE(mp) == M_PCPROTO &&
17768 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
17769 	    car->PRIM_type == T_CAPABILITY_REQ) {
17770 		tcp_capability_req(tcp, mp);
17771 		return;
17772 	}
17773 
17774 	tcp_wput(wq, mp);
17775 }
17776 
17777 static boolean_t
17778 tcp_zcopy_check(tcp_t *tcp)
17779 {
17780 	conn_t	*connp = tcp->tcp_connp;
17781 	ire_t	*ire;
17782 	boolean_t	zc_enabled = B_FALSE;
17783 
17784 	if (do_tcpzcopy == 2)
17785 		zc_enabled = B_TRUE;
17786 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
17787 	    IPCL_IS_CONNECTED(connp) &&
17788 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
17789 	    connp->conn_dontroute == 0 &&
17790 	    !connp->conn_nexthop_set &&
17791 	    connp->conn_xmit_if_ill == NULL &&
17792 	    connp->conn_nofailover_ill == NULL &&
17793 	    do_tcpzcopy == 1) {
17794 		/*
17795 		 * the checks above  closely resemble the fast path checks
17796 		 * in tcp_send_data().
17797 		 */
17798 		mutex_enter(&connp->conn_lock);
17799 		ire = connp->conn_ire_cache;
17800 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17801 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17802 			IRE_REFHOLD(ire);
17803 			if (ire->ire_stq != NULL) {
17804 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
17805 
17806 				zc_enabled = ill && (ill->ill_capabilities &
17807 				    ILL_CAPAB_ZEROCOPY) &&
17808 				    (ill->ill_zerocopy_capab->
17809 				    ill_zerocopy_flags != 0);
17810 			}
17811 			IRE_REFRELE(ire);
17812 		}
17813 		mutex_exit(&connp->conn_lock);
17814 	}
17815 	tcp->tcp_snd_zcopy_on = zc_enabled;
17816 	if (!TCP_IS_DETACHED(tcp)) {
17817 		if (zc_enabled) {
17818 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
17819 			TCP_STAT(tcp_zcopy_on);
17820 		} else {
17821 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17822 			TCP_STAT(tcp_zcopy_off);
17823 		}
17824 	}
17825 	return (zc_enabled);
17826 }
17827 
17828 static mblk_t *
17829 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
17830 {
17831 	if (do_tcpzcopy == 2)
17832 		return (bp);
17833 	else if (tcp->tcp_snd_zcopy_on) {
17834 		tcp->tcp_snd_zcopy_on = B_FALSE;
17835 		if (!TCP_IS_DETACHED(tcp)) {
17836 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
17837 			TCP_STAT(tcp_zcopy_disable);
17838 		}
17839 	}
17840 	return (tcp_zcopy_backoff(tcp, bp, 0));
17841 }
17842 
17843 /*
17844  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
17845  * the original desballoca'ed segmapped mblk.
17846  */
17847 static mblk_t *
17848 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
17849 {
17850 	mblk_t *head, *tail, *nbp;
17851 	if (IS_VMLOANED_MBLK(bp)) {
17852 		TCP_STAT(tcp_zcopy_backoff);
17853 		if ((head = copyb(bp)) == NULL) {
17854 			/* fail to backoff; leave it for the next backoff */
17855 			tcp->tcp_xmit_zc_clean = B_FALSE;
17856 			return (bp);
17857 		}
17858 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17859 			if (fix_xmitlist)
17860 				tcp_zcopy_notify(tcp);
17861 			else
17862 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
17863 		}
17864 		nbp = bp->b_cont;
17865 		if (fix_xmitlist) {
17866 			head->b_prev = bp->b_prev;
17867 			head->b_next = bp->b_next;
17868 			if (tcp->tcp_xmit_tail == bp)
17869 				tcp->tcp_xmit_tail = head;
17870 		}
17871 		bp->b_next = NULL;
17872 		bp->b_prev = NULL;
17873 		freeb(bp);
17874 	} else {
17875 		head = bp;
17876 		nbp = bp->b_cont;
17877 	}
17878 	tail = head;
17879 	while (nbp) {
17880 		if (IS_VMLOANED_MBLK(nbp)) {
17881 			TCP_STAT(tcp_zcopy_backoff);
17882 			if ((tail->b_cont = copyb(nbp)) == NULL) {
17883 				tcp->tcp_xmit_zc_clean = B_FALSE;
17884 				tail->b_cont = nbp;
17885 				return (head);
17886 			}
17887 			tail = tail->b_cont;
17888 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
17889 				if (fix_xmitlist)
17890 					tcp_zcopy_notify(tcp);
17891 				else
17892 					tail->b_datap->db_struioflag |=
17893 					    STRUIO_ZCNOTIFY;
17894 			}
17895 			bp = nbp;
17896 			nbp = nbp->b_cont;
17897 			if (fix_xmitlist) {
17898 				tail->b_prev = bp->b_prev;
17899 				tail->b_next = bp->b_next;
17900 				if (tcp->tcp_xmit_tail == bp)
17901 					tcp->tcp_xmit_tail = tail;
17902 			}
17903 			bp->b_next = NULL;
17904 			bp->b_prev = NULL;
17905 			freeb(bp);
17906 		} else {
17907 			tail->b_cont = nbp;
17908 			tail = nbp;
17909 			nbp = nbp->b_cont;
17910 		}
17911 	}
17912 	if (fix_xmitlist) {
17913 		tcp->tcp_xmit_last = tail;
17914 		tcp->tcp_xmit_zc_clean = B_TRUE;
17915 	}
17916 	return (head);
17917 }
17918 
17919 static void
17920 tcp_zcopy_notify(tcp_t *tcp)
17921 {
17922 	struct stdata	*stp;
17923 
17924 	if (tcp->tcp_detached)
17925 		return;
17926 	stp = STREAM(tcp->tcp_rq);
17927 	mutex_enter(&stp->sd_lock);
17928 	stp->sd_flag |= STZCNOTIFY;
17929 	cv_broadcast(&stp->sd_zcopy_wait);
17930 	mutex_exit(&stp->sd_lock);
17931 }
17932 
17933 static void
17934 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
17935 {
17936 	ipha_t		*ipha;
17937 	ipaddr_t	src;
17938 	ipaddr_t	dst;
17939 	uint32_t	cksum;
17940 	ire_t		*ire;
17941 	uint16_t	*up;
17942 	ill_t		*ill;
17943 	conn_t		*connp = tcp->tcp_connp;
17944 	uint32_t	hcksum_txflags = 0;
17945 	mblk_t		*ire_fp_mp;
17946 	uint_t		ire_fp_mp_len;
17947 
17948 	ASSERT(DB_TYPE(mp) == M_DATA);
17949 
17950 	ipha = (ipha_t *)mp->b_rptr;
17951 	src = ipha->ipha_src;
17952 	dst = ipha->ipha_dst;
17953 
17954 	/*
17955 	 * Drop off slow path for IPv6 and also if options are present.
17956 	 */
17957 	if (tcp->tcp_ipversion != IPV4_VERSION ||
17958 	    !IPCL_IS_CONNECTED(connp) ||
17959 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
17960 	    connp->conn_dontroute ||
17961 	    connp->conn_nexthop_set ||
17962 	    connp->conn_xmit_if_ill != NULL ||
17963 	    connp->conn_nofailover_ill != NULL ||
17964 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
17965 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
17966 	    IPP_ENABLED(IPP_LOCAL_OUT)) {
17967 		if (tcp->tcp_snd_zcopy_aware)
17968 			mp = tcp_zcopy_disable(tcp, mp);
17969 		TCP_STAT(tcp_ip_send);
17970 		CALL_IP_WPUT(connp, q, mp);
17971 		return;
17972 	}
17973 
17974 	mutex_enter(&connp->conn_lock);
17975 	ire = connp->conn_ire_cache;
17976 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
17977 	if (ire != NULL && ire->ire_addr == dst &&
17978 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
17979 		IRE_REFHOLD(ire);
17980 		mutex_exit(&connp->conn_lock);
17981 	} else {
17982 		boolean_t cached = B_FALSE;
17983 
17984 		/* force a recheck later on */
17985 		tcp->tcp_ire_ill_check_done = B_FALSE;
17986 
17987 		TCP_DBGSTAT(tcp_ire_null1);
17988 		connp->conn_ire_cache = NULL;
17989 		mutex_exit(&connp->conn_lock);
17990 		if (ire != NULL)
17991 			IRE_REFRELE_NOTR(ire);
17992 		ire = ire_cache_lookup(dst, connp->conn_zoneid);
17993 		if (ire == NULL) {
17994 			if (tcp->tcp_snd_zcopy_aware)
17995 				mp = tcp_zcopy_backoff(tcp, mp, 0);
17996 			TCP_STAT(tcp_ire_null);
17997 			CALL_IP_WPUT(connp, q, mp);
17998 			return;
17999 		}
18000 		IRE_REFHOLD_NOTR(ire);
18001 		/*
18002 		 * Since we are inside the squeue, there cannot be another
18003 		 * thread in TCP trying to set the conn_ire_cache now.  The
18004 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18005 		 * unplumb thread has not yet started cleaning up the conns.
18006 		 * Hence we don't need to grab the conn lock.
18007 		 */
18008 		if (!(connp->conn_state_flags & CONN_CLOSING)) {
18009 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18010 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18011 				connp->conn_ire_cache = ire;
18012 				cached = B_TRUE;
18013 			}
18014 			rw_exit(&ire->ire_bucket->irb_lock);
18015 		}
18016 
18017 		/*
18018 		 * We can continue to use the ire but since it was
18019 		 * not cached, we should drop the extra reference.
18020 		 */
18021 		if (!cached)
18022 			IRE_REFRELE_NOTR(ire);
18023 	}
18024 
18025 	if (ire->ire_flags & RTF_MULTIRT ||
18026 	    ire->ire_stq == NULL ||
18027 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
18028 	    (ire_fp_mp = ire->ire_fp_mp) == NULL ||
18029 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
18030 		if (tcp->tcp_snd_zcopy_aware)
18031 			mp = tcp_zcopy_disable(tcp, mp);
18032 		TCP_STAT(tcp_ip_ire_send);
18033 		IRE_REFRELE(ire);
18034 		CALL_IP_WPUT(connp, q, mp);
18035 		return;
18036 	}
18037 
18038 	ill = ire_to_ill(ire);
18039 	if (connp->conn_outgoing_ill != NULL) {
18040 		ill_t *conn_outgoing_ill = NULL;
18041 		/*
18042 		 * Choose a good ill in the group to send the packets on.
18043 		 */
18044 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
18045 		ill = ire_to_ill(ire);
18046 	}
18047 	ASSERT(ill != NULL);
18048 
18049 	if (!tcp->tcp_ire_ill_check_done) {
18050 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18051 		tcp->tcp_ire_ill_check_done = B_TRUE;
18052 	}
18053 
18054 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
18055 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
18056 #ifndef _BIG_ENDIAN
18057 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
18058 #endif
18059 
18060 	/*
18061 	 * Check to see if we need to re-enable MDT for this connection
18062 	 * because it was previously disabled due to changes in the ill;
18063 	 * note that by doing it here, this re-enabling only applies when
18064 	 * the packet is not dispatched through CALL_IP_WPUT().
18065 	 *
18066 	 * That means for IPv4, it is worth re-enabling MDT for the fastpath
18067 	 * case, since that's how we ended up here.  For IPv6, we do the
18068 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
18069 	 */
18070 	if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
18071 		/*
18072 		 * Restore MDT for this connection, so that next time around
18073 		 * it is eligible to go through tcp_multisend() path again.
18074 		 */
18075 		TCP_STAT(tcp_mdt_conn_resumed1);
18076 		tcp->tcp_mdt = B_TRUE;
18077 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
18078 		    "interface %s\n", (void *)connp, ill->ill_name));
18079 	}
18080 
18081 	if (tcp->tcp_snd_zcopy_aware) {
18082 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
18083 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
18084 			mp = tcp_zcopy_disable(tcp, mp);
18085 		/*
18086 		 * we shouldn't need to reset ipha as the mp containing
18087 		 * ipha should never be a zero-copy mp.
18088 		 */
18089 	}
18090 
18091 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
18092 		ASSERT(ill->ill_hcksum_capab != NULL);
18093 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
18094 	}
18095 
18096 	/* pseudo-header checksum (do it in parts for IP header checksum) */
18097 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
18098 
18099 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
18100 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
18101 
18102 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
18103 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
18104 
18105 	/* Software checksum? */
18106 	if (DB_CKSUMFLAGS(mp) == 0) {
18107 		TCP_STAT(tcp_out_sw_cksum);
18108 		TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
18109 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
18110 	}
18111 
18112 	ipha->ipha_fragment_offset_and_flags |=
18113 	    (uint32_t)htons(ire->ire_frag_flag);
18114 
18115 	/* Calculate IP header checksum if hardware isn't capable */
18116 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
18117 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
18118 		    ((uint16_t *)ipha)[4]);
18119 	}
18120 
18121 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
18122 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
18123 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
18124 
18125 	UPDATE_OB_PKT_COUNT(ire);
18126 	ire->ire_last_used_time = lbolt;
18127 	BUMP_MIB(&ip_mib, ipOutRequests);
18128 
18129 	if (ILL_POLL_CAPABLE(ill)) {
18130 		/*
18131 		 * Send the packet directly to DLD, where it may be queued
18132 		 * depending on the availability of transmit resources at
18133 		 * the media layer.
18134 		 */
18135 		IP_POLL_ILL_TX(ill, mp);
18136 	} else {
18137 		putnext(ire->ire_stq, mp);
18138 	}
18139 	IRE_REFRELE(ire);
18140 }
18141 
18142 /*
18143  * This handles the case when the receiver has shrunk its win. Per RFC 1122
18144  * if the receiver shrinks the window, i.e. moves the right window to the
18145  * left, the we should not send new data, but should retransmit normally the
18146  * old unacked data between suna and suna + swnd. We might has sent data
18147  * that is now outside the new window, pretend that we didn't send  it.
18148  */
18149 static void
18150 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
18151 {
18152 	uint32_t	snxt = tcp->tcp_snxt;
18153 	mblk_t		*xmit_tail;
18154 	int32_t		offset;
18155 
18156 	ASSERT(shrunk_count > 0);
18157 
18158 	/* Pretend we didn't send the data outside the window */
18159 	snxt -= shrunk_count;
18160 
18161 	/* Get the mblk and the offset in it per the shrunk window */
18162 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
18163 
18164 	ASSERT(xmit_tail != NULL);
18165 
18166 	/* Reset all the values per the now shrunk window */
18167 	tcp->tcp_snxt = snxt;
18168 	tcp->tcp_xmit_tail = xmit_tail;
18169 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
18170 	    offset;
18171 	tcp->tcp_unsent += shrunk_count;
18172 
18173 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
18174 		/*
18175 		 * Make sure the timer is running so that we will probe a zero
18176 		 * window.
18177 		 */
18178 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18179 }
18180 
18181 
18182 /*
18183  * The TCP normal data output path.
18184  * NOTE: the logic of the fast path is duplicated from this function.
18185  */
18186 static void
18187 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
18188 {
18189 	int		len;
18190 	mblk_t		*local_time;
18191 	mblk_t		*mp1;
18192 	uint32_t	snxt;
18193 	int		tail_unsent;
18194 	int		tcpstate;
18195 	int		usable = 0;
18196 	mblk_t		*xmit_tail;
18197 	queue_t		*q = tcp->tcp_wq;
18198 	int32_t		mss;
18199 	int32_t		num_sack_blk = 0;
18200 	int32_t		tcp_hdr_len;
18201 	int32_t		tcp_tcp_hdr_len;
18202 	int		mdt_thres;
18203 	int		rc;
18204 
18205 	tcpstate = tcp->tcp_state;
18206 	if (mp == NULL) {
18207 		/*
18208 		 * tcp_wput_data() with NULL mp should only be called when
18209 		 * there is unsent data.
18210 		 */
18211 		ASSERT(tcp->tcp_unsent > 0);
18212 		/* Really tacky... but we need this for detached closes. */
18213 		len = tcp->tcp_unsent;
18214 		goto data_null;
18215 	}
18216 
18217 #if CCS_STATS
18218 	wrw_stats.tot.count++;
18219 	wrw_stats.tot.bytes += msgdsize(mp);
18220 #endif
18221 	ASSERT(mp->b_datap->db_type == M_DATA);
18222 	/*
18223 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
18224 	 * or before a connection attempt has begun.
18225 	 */
18226 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
18227 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18228 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
18229 #ifdef DEBUG
18230 			cmn_err(CE_WARN,
18231 			    "tcp_wput_data: data after ordrel, %s",
18232 			    tcp_display(tcp, NULL,
18233 			    DISP_ADDR_AND_PORT));
18234 #else
18235 			if (tcp->tcp_debug) {
18236 				(void) strlog(TCP_MOD_ID, 0, 1,
18237 				    SL_TRACE|SL_ERROR,
18238 				    "tcp_wput_data: data after ordrel, %s\n",
18239 				    tcp_display(tcp, NULL,
18240 				    DISP_ADDR_AND_PORT));
18241 			}
18242 #endif /* DEBUG */
18243 		}
18244 		if (tcp->tcp_snd_zcopy_aware &&
18245 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
18246 			tcp_zcopy_notify(tcp);
18247 		freemsg(mp);
18248 		if (tcp->tcp_flow_stopped &&
18249 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18250 			tcp_clrqfull(tcp);
18251 		}
18252 		return;
18253 	}
18254 
18255 	/* Strip empties */
18256 	for (;;) {
18257 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
18258 		    (uintptr_t)INT_MAX);
18259 		len = (int)(mp->b_wptr - mp->b_rptr);
18260 		if (len > 0)
18261 			break;
18262 		mp1 = mp;
18263 		mp = mp->b_cont;
18264 		freeb(mp1);
18265 		if (!mp) {
18266 			return;
18267 		}
18268 	}
18269 
18270 	/* If we are the first on the list ... */
18271 	if (tcp->tcp_xmit_head == NULL) {
18272 		tcp->tcp_xmit_head = mp;
18273 		tcp->tcp_xmit_tail = mp;
18274 		tcp->tcp_xmit_tail_unsent = len;
18275 	} else {
18276 		/* If tiny tx and room in txq tail, pullup to save mblks. */
18277 		struct datab *dp;
18278 
18279 		mp1 = tcp->tcp_xmit_last;
18280 		if (len < tcp_tx_pull_len &&
18281 		    (dp = mp1->b_datap)->db_ref == 1 &&
18282 		    dp->db_lim - mp1->b_wptr >= len) {
18283 			ASSERT(len > 0);
18284 			ASSERT(!mp1->b_cont);
18285 			if (len == 1) {
18286 				*mp1->b_wptr++ = *mp->b_rptr;
18287 			} else {
18288 				bcopy(mp->b_rptr, mp1->b_wptr, len);
18289 				mp1->b_wptr += len;
18290 			}
18291 			if (mp1 == tcp->tcp_xmit_tail)
18292 				tcp->tcp_xmit_tail_unsent += len;
18293 			mp1->b_cont = mp->b_cont;
18294 			if (tcp->tcp_snd_zcopy_aware &&
18295 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
18296 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
18297 			freeb(mp);
18298 			mp = mp1;
18299 		} else {
18300 			tcp->tcp_xmit_last->b_cont = mp;
18301 		}
18302 		len += tcp->tcp_unsent;
18303 	}
18304 
18305 	/* Tack on however many more positive length mblks we have */
18306 	if ((mp1 = mp->b_cont) != NULL) {
18307 		do {
18308 			int tlen;
18309 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
18310 			    (uintptr_t)INT_MAX);
18311 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
18312 			if (tlen <= 0) {
18313 				mp->b_cont = mp1->b_cont;
18314 				freeb(mp1);
18315 			} else {
18316 				len += tlen;
18317 				mp = mp1;
18318 			}
18319 		} while ((mp1 = mp->b_cont) != NULL);
18320 	}
18321 	tcp->tcp_xmit_last = mp;
18322 	tcp->tcp_unsent = len;
18323 
18324 	if (urgent)
18325 		usable = 1;
18326 
18327 data_null:
18328 	snxt = tcp->tcp_snxt;
18329 	xmit_tail = tcp->tcp_xmit_tail;
18330 	tail_unsent = tcp->tcp_xmit_tail_unsent;
18331 
18332 	/*
18333 	 * Note that tcp_mss has been adjusted to take into account the
18334 	 * timestamp option if applicable.  Because SACK options do not
18335 	 * appear in every TCP segments and they are of variable lengths,
18336 	 * they cannot be included in tcp_mss.  Thus we need to calculate
18337 	 * the actual segment length when we need to send a segment which
18338 	 * includes SACK options.
18339 	 */
18340 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18341 		int32_t	opt_len;
18342 
18343 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18344 		    tcp->tcp_num_sack_blk);
18345 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
18346 		    2 + TCPOPT_HEADER_LEN;
18347 		mss = tcp->tcp_mss - opt_len;
18348 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
18349 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
18350 	} else {
18351 		mss = tcp->tcp_mss;
18352 		tcp_hdr_len = tcp->tcp_hdr_len;
18353 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
18354 	}
18355 
18356 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18357 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18358 		SET_TCP_INIT_CWND(tcp, mss, tcp_slow_start_after_idle);
18359 	}
18360 	if (tcpstate == TCPS_SYN_RCVD) {
18361 		/*
18362 		 * The three-way connection establishment handshake is not
18363 		 * complete yet. We want to queue the data for transmission
18364 		 * after entering ESTABLISHED state (RFC793). A jump to
18365 		 * "done" label effectively leaves data on the queue.
18366 		 */
18367 		goto done;
18368 	} else {
18369 		int usable_r = tcp->tcp_swnd;
18370 
18371 		/*
18372 		 * In the special case when cwnd is zero, which can only
18373 		 * happen if the connection is ECN capable, return now.
18374 		 * New segments is sent using tcp_timer().  The timer
18375 		 * is set in tcp_rput_data().
18376 		 */
18377 		if (tcp->tcp_cwnd == 0) {
18378 			/*
18379 			 * Note that tcp_cwnd is 0 before 3-way handshake is
18380 			 * finished.
18381 			 */
18382 			ASSERT(tcp->tcp_ecn_ok ||
18383 			    tcp->tcp_state < TCPS_ESTABLISHED);
18384 			return;
18385 		}
18386 
18387 		/* NOTE: trouble if xmitting while SYN not acked? */
18388 		usable_r -= snxt;
18389 		usable_r += tcp->tcp_suna;
18390 
18391 		/*
18392 		 * Check if the receiver has shrunk the window.  If
18393 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
18394 		 * cannot be set as there is unsent data, so FIN cannot
18395 		 * be sent out.  Otherwise, we need to take into account
18396 		 * of FIN as it consumes an "invisible" sequence number.
18397 		 */
18398 		ASSERT(tcp->tcp_fin_sent == 0);
18399 		if (usable_r < 0) {
18400 			/*
18401 			 * The receiver has shrunk the window and we have sent
18402 			 * -usable_r date beyond the window, re-adjust.
18403 			 *
18404 			 * If TCP window scaling is enabled, there can be
18405 			 * round down error as the advertised receive window
18406 			 * is actually right shifted n bits.  This means that
18407 			 * the lower n bits info is wiped out.  It will look
18408 			 * like the window is shrunk.  Do a check here to
18409 			 * see if the shrunk amount is actually within the
18410 			 * error in window calculation.  If it is, just
18411 			 * return.  Note that this check is inside the
18412 			 * shrunk window check.  This makes sure that even
18413 			 * though tcp_process_shrunk_swnd() is not called,
18414 			 * we will stop further processing.
18415 			 */
18416 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
18417 				tcp_process_shrunk_swnd(tcp, -usable_r);
18418 			}
18419 			return;
18420 		}
18421 
18422 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
18423 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
18424 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
18425 
18426 		/* usable = MIN(usable, unsent) */
18427 		if (usable_r > len)
18428 			usable_r = len;
18429 
18430 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
18431 		if (usable_r > 0) {
18432 			usable = usable_r;
18433 		} else {
18434 			/* Bypass all other unnecessary processing. */
18435 			goto done;
18436 		}
18437 	}
18438 
18439 	local_time = (mblk_t *)lbolt;
18440 
18441 	/*
18442 	 * "Our" Nagle Algorithm.  This is not the same as in the old
18443 	 * BSD.  This is more in line with the true intent of Nagle.
18444 	 *
18445 	 * The conditions are:
18446 	 * 1. The amount of unsent data (or amount of data which can be
18447 	 *    sent, whichever is smaller) is less than Nagle limit.
18448 	 * 2. The last sent size is also less than Nagle limit.
18449 	 * 3. There is unack'ed data.
18450 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
18451 	 *    Nagle algorithm.  This reduces the probability that urgent
18452 	 *    bytes get "merged" together.
18453 	 * 5. The app has not closed the connection.  This eliminates the
18454 	 *    wait time of the receiving side waiting for the last piece of
18455 	 *    (small) data.
18456 	 *
18457 	 * If all are satisified, exit without sending anything.  Note
18458 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
18459 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
18460 	 * 4095).
18461 	 */
18462 	if (usable < (int)tcp->tcp_naglim &&
18463 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
18464 	    snxt != tcp->tcp_suna &&
18465 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
18466 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
18467 		goto done;
18468 	}
18469 
18470 	if (tcp->tcp_cork) {
18471 		/*
18472 		 * if the tcp->tcp_cork option is set, then we have to force
18473 		 * TCP not to send partial segment (smaller than MSS bytes).
18474 		 * We are calculating the usable now based on full mss and
18475 		 * will save the rest of remaining data for later.
18476 		 */
18477 		if (usable < mss)
18478 			goto done;
18479 		usable = (usable / mss) * mss;
18480 	}
18481 
18482 	/* Update the latest receive window size in TCP header. */
18483 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18484 	    tcp->tcp_tcph->th_win);
18485 
18486 	/*
18487 	 * Determine if it's worthwhile to attempt MDT, based on:
18488 	 *
18489 	 * 1. Simple TCP/IP{v4,v6} (no options).
18490 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
18491 	 * 3. If the TCP connection is in ESTABLISHED state.
18492 	 * 4. The TCP is not detached.
18493 	 *
18494 	 * If any of the above conditions have changed during the
18495 	 * connection, stop using MDT and restore the stream head
18496 	 * parameters accordingly.
18497 	 */
18498 	if (tcp->tcp_mdt &&
18499 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
18500 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
18501 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18502 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
18503 	    tcp->tcp_state != TCPS_ESTABLISHED ||
18504 	    TCP_IS_DETACHED(tcp) || !CONN_IS_MD_FASTPATH(tcp->tcp_connp) ||
18505 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
18506 	    IPP_ENABLED(IPP_LOCAL_OUT))) {
18507 		tcp->tcp_connp->conn_mdt_ok = B_FALSE;
18508 		tcp->tcp_mdt = B_FALSE;
18509 
18510 		/* Anything other than detached is considered pathological */
18511 		if (!TCP_IS_DETACHED(tcp)) {
18512 			TCP_STAT(tcp_mdt_conn_halted1);
18513 			(void) tcp_maxpsz_set(tcp, B_TRUE);
18514 		}
18515 	}
18516 
18517 	/* Use MDT if sendable amount is greater than the threshold */
18518 	if (tcp->tcp_mdt &&
18519 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
18520 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
18521 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
18522 	    (tcp->tcp_valid_bits == 0 ||
18523 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
18524 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
18525 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18526 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18527 		    local_time, mdt_thres);
18528 	} else {
18529 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
18530 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
18531 		    local_time, INT_MAX);
18532 	}
18533 
18534 	/* Pretend that all we were trying to send really got sent */
18535 	if (rc < 0 && tail_unsent < 0) {
18536 		do {
18537 			xmit_tail = xmit_tail->b_cont;
18538 			xmit_tail->b_prev = local_time;
18539 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
18540 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
18541 			tail_unsent += (int)(xmit_tail->b_wptr -
18542 			    xmit_tail->b_rptr);
18543 		} while (tail_unsent < 0);
18544 	}
18545 done:;
18546 	tcp->tcp_xmit_tail = xmit_tail;
18547 	tcp->tcp_xmit_tail_unsent = tail_unsent;
18548 	len = tcp->tcp_snxt - snxt;
18549 	if (len) {
18550 		/*
18551 		 * If new data was sent, need to update the notsack
18552 		 * list, which is, afterall, data blocks that have
18553 		 * not been sack'ed by the receiver.  New data is
18554 		 * not sack'ed.
18555 		 */
18556 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
18557 			/* len is a negative value. */
18558 			tcp->tcp_pipe -= len;
18559 			tcp_notsack_update(&(tcp->tcp_notsack_list),
18560 			    tcp->tcp_snxt, snxt,
18561 			    &(tcp->tcp_num_notsack_blk),
18562 			    &(tcp->tcp_cnt_notsack_list));
18563 		}
18564 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
18565 		tcp->tcp_rack = tcp->tcp_rnxt;
18566 		tcp->tcp_rack_cnt = 0;
18567 		if ((snxt + len) == tcp->tcp_suna) {
18568 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18569 		}
18570 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
18571 		/*
18572 		 * Didn't send anything. Make sure the timer is running
18573 		 * so that we will probe a zero window.
18574 		 */
18575 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18576 	}
18577 	/* Note that len is the amount we just sent but with a negative sign */
18578 	tcp->tcp_unsent += len;
18579 	if (tcp->tcp_flow_stopped) {
18580 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18581 			tcp_clrqfull(tcp);
18582 		}
18583 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
18584 		tcp_setqfull(tcp);
18585 	}
18586 }
18587 
18588 /*
18589  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
18590  * outgoing TCP header with the template header, as well as other
18591  * options such as time-stamp, ECN and/or SACK.
18592  */
18593 static void
18594 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
18595 {
18596 	tcph_t *tcp_tmpl, *tcp_h;
18597 	uint32_t *dst, *src;
18598 	int hdrlen;
18599 
18600 	ASSERT(OK_32PTR(rptr));
18601 
18602 	/* Template header */
18603 	tcp_tmpl = tcp->tcp_tcph;
18604 
18605 	/* Header of outgoing packet */
18606 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18607 
18608 	/* dst and src are opaque 32-bit fields, used for copying */
18609 	dst = (uint32_t *)rptr;
18610 	src = (uint32_t *)tcp->tcp_iphc;
18611 	hdrlen = tcp->tcp_hdr_len;
18612 
18613 	/* Fill time-stamp option if needed */
18614 	if (tcp->tcp_snd_ts_ok) {
18615 		U32_TO_BE32((uint32_t)now,
18616 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
18617 		U32_TO_BE32(tcp->tcp_ts_recent,
18618 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
18619 	} else {
18620 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18621 	}
18622 
18623 	/*
18624 	 * Copy the template header; is this really more efficient than
18625 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
18626 	 * but perhaps not for other scenarios.
18627 	 */
18628 	dst[0] = src[0];
18629 	dst[1] = src[1];
18630 	dst[2] = src[2];
18631 	dst[3] = src[3];
18632 	dst[4] = src[4];
18633 	dst[5] = src[5];
18634 	dst[6] = src[6];
18635 	dst[7] = src[7];
18636 	dst[8] = src[8];
18637 	dst[9] = src[9];
18638 	if (hdrlen -= 40) {
18639 		hdrlen >>= 2;
18640 		dst += 10;
18641 		src += 10;
18642 		do {
18643 			*dst++ = *src++;
18644 		} while (--hdrlen);
18645 	}
18646 
18647 	/*
18648 	 * Set the ECN info in the TCP header if it is not a zero
18649 	 * window probe.  Zero window probe is only sent in
18650 	 * tcp_wput_data() and tcp_timer().
18651 	 */
18652 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
18653 		SET_ECT(tcp, rptr);
18654 
18655 		if (tcp->tcp_ecn_echo_on)
18656 			tcp_h->th_flags[0] |= TH_ECE;
18657 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18658 			tcp_h->th_flags[0] |= TH_CWR;
18659 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18660 		}
18661 	}
18662 
18663 	/* Fill in SACK options */
18664 	if (num_sack_blk > 0) {
18665 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
18666 		sack_blk_t *tmp;
18667 		int32_t	i;
18668 
18669 		wptr[0] = TCPOPT_NOP;
18670 		wptr[1] = TCPOPT_NOP;
18671 		wptr[2] = TCPOPT_SACK;
18672 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18673 		    sizeof (sack_blk_t);
18674 		wptr += TCPOPT_REAL_SACK_LEN;
18675 
18676 		tmp = tcp->tcp_sack_list;
18677 		for (i = 0; i < num_sack_blk; i++) {
18678 			U32_TO_BE32(tmp[i].begin, wptr);
18679 			wptr += sizeof (tcp_seq);
18680 			U32_TO_BE32(tmp[i].end, wptr);
18681 			wptr += sizeof (tcp_seq);
18682 		}
18683 		tcp_h->th_offset_and_rsrvd[0] +=
18684 		    ((num_sack_blk * 2 + 1) << 4);
18685 	}
18686 }
18687 
18688 /*
18689  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
18690  * the destination address and SAP attribute, and if necessary, the
18691  * hardware checksum offload attribute to a Multidata message.
18692  */
18693 static int
18694 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
18695     const uint32_t start, const uint32_t stuff, const uint32_t end,
18696     const uint32_t flags)
18697 {
18698 	/* Add global destination address & SAP attribute */
18699 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
18700 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
18701 		    "destination address+SAP\n"));
18702 
18703 		if (dlmp != NULL)
18704 			TCP_STAT(tcp_mdt_allocfail);
18705 		return (-1);
18706 	}
18707 
18708 	/* Add global hwcksum attribute */
18709 	if (hwcksum &&
18710 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
18711 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
18712 		    "checksum attribute\n"));
18713 
18714 		TCP_STAT(tcp_mdt_allocfail);
18715 		return (-1);
18716 	}
18717 
18718 	return (0);
18719 }
18720 
18721 /*
18722  * Smaller and private version of pdescinfo_t used specifically for TCP,
18723  * which allows for only two payload spans per packet.
18724  */
18725 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
18726 
18727 /*
18728  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
18729  * scheme, and returns one the following:
18730  *
18731  * -1 = failed allocation.
18732  *  0 = success; burst count reached, or usable send window is too small,
18733  *      and that we'd rather wait until later before sending again.
18734  */
18735 static int
18736 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
18737     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
18738     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
18739     const int mdt_thres)
18740 {
18741 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
18742 	multidata_t	*mmd;
18743 	uint_t		obsegs, obbytes, hdr_frag_sz;
18744 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
18745 	int		num_burst_seg, max_pld;
18746 	pdesc_t		*pkt;
18747 	tcp_pdescinfo_t	tcp_pkt_info;
18748 	pdescinfo_t	*pkt_info;
18749 	int		pbuf_idx, pbuf_idx_nxt;
18750 	int		seg_len, len, spill, af;
18751 	boolean_t	add_buffer, zcopy, clusterwide;
18752 	boolean_t	rconfirm = B_FALSE;
18753 	boolean_t	done = B_FALSE;
18754 	uint32_t	cksum;
18755 	uint32_t	hwcksum_flags;
18756 	ire_t		*ire;
18757 	ill_t		*ill;
18758 	ipha_t		*ipha;
18759 	ip6_t		*ip6h;
18760 	ipaddr_t	src, dst;
18761 	ill_zerocopy_capab_t *zc_cap = NULL;
18762 	uint16_t	*up;
18763 	int		err;
18764 
18765 #ifdef	_BIG_ENDIAN
18766 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
18767 #else
18768 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
18769 #endif
18770 
18771 #define	PREP_NEW_MULTIDATA() {			\
18772 	mmd = NULL;				\
18773 	md_mp = md_hbuf = NULL;			\
18774 	cur_hdr_off = 0;			\
18775 	max_pld = tcp->tcp_mdt_max_pld;		\
18776 	pbuf_idx = pbuf_idx_nxt = -1;		\
18777 	add_buffer = B_TRUE;			\
18778 	zcopy = B_FALSE;			\
18779 }
18780 
18781 #define	PREP_NEW_PBUF() {			\
18782 	md_pbuf = md_pbuf_nxt = NULL;		\
18783 	pbuf_idx = pbuf_idx_nxt = -1;		\
18784 	cur_pld_off = 0;			\
18785 	first_snxt = *snxt;			\
18786 	ASSERT(*tail_unsent > 0);		\
18787 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
18788 }
18789 
18790 	ASSERT(mdt_thres >= mss);
18791 	ASSERT(*usable > 0 && *usable > mdt_thres);
18792 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
18793 	ASSERT(!TCP_IS_DETACHED(tcp));
18794 	ASSERT(tcp->tcp_valid_bits == 0 ||
18795 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
18796 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
18797 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
18798 	    (tcp->tcp_ipversion == IPV6_VERSION &&
18799 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
18800 	ASSERT(tcp->tcp_connp != NULL);
18801 	ASSERT(CONN_IS_MD_FASTPATH(tcp->tcp_connp));
18802 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp));
18803 
18804 	/*
18805 	 * Note that tcp will only declare at most 2 payload spans per
18806 	 * packet, which is much lower than the maximum allowable number
18807 	 * of packet spans per Multidata.  For this reason, we use the
18808 	 * privately declared and smaller descriptor info structure, in
18809 	 * order to save some stack space.
18810 	 */
18811 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
18812 
18813 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
18814 	if (af == AF_INET) {
18815 		dst = tcp->tcp_ipha->ipha_dst;
18816 		src = tcp->tcp_ipha->ipha_src;
18817 		ASSERT(!CLASSD(dst));
18818 	}
18819 	ASSERT(af == AF_INET ||
18820 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
18821 
18822 	obsegs = obbytes = 0;
18823 	num_burst_seg = tcp->tcp_snd_burst;
18824 	md_mp_head = NULL;
18825 	PREP_NEW_MULTIDATA();
18826 
18827 	/*
18828 	 * Before we go on further, make sure there is an IRE that we can
18829 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
18830 	 * in proceeding any further, and we should just hand everything
18831 	 * off to the legacy path.
18832 	 */
18833 	mutex_enter(&tcp->tcp_connp->conn_lock);
18834 	ire = tcp->tcp_connp->conn_ire_cache;
18835 	ASSERT(!(tcp->tcp_connp->conn_state_flags & CONN_INCIPIENT));
18836 	if (ire != NULL && ((af == AF_INET && ire->ire_addr == dst) ||
18837 	    (af == AF_INET6 && IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6,
18838 	    &tcp->tcp_ip6h->ip6_dst))) &&
18839 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18840 		IRE_REFHOLD(ire);
18841 		mutex_exit(&tcp->tcp_connp->conn_lock);
18842 	} else {
18843 		boolean_t cached = B_FALSE;
18844 
18845 		/* force a recheck later on */
18846 		tcp->tcp_ire_ill_check_done = B_FALSE;
18847 
18848 		TCP_DBGSTAT(tcp_ire_null1);
18849 		tcp->tcp_connp->conn_ire_cache = NULL;
18850 		mutex_exit(&tcp->tcp_connp->conn_lock);
18851 
18852 		/* Release the old ire */
18853 		if (ire != NULL)
18854 			IRE_REFRELE_NOTR(ire);
18855 
18856 		ire = (af == AF_INET) ?
18857 		    ire_cache_lookup(dst, tcp->tcp_connp->conn_zoneid) :
18858 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
18859 		    tcp->tcp_connp->conn_zoneid);
18860 
18861 		if (ire == NULL) {
18862 			TCP_STAT(tcp_ire_null);
18863 			goto legacy_send_no_md;
18864 		}
18865 
18866 		IRE_REFHOLD_NOTR(ire);
18867 		/*
18868 		 * Since we are inside the squeue, there cannot be another
18869 		 * thread in TCP trying to set the conn_ire_cache now. The
18870 		 * check for IRE_MARK_CONDEMNED ensures that an interface
18871 		 * unplumb thread has not yet started cleaning up the conns.
18872 		 * Hence we don't need to grab the conn lock.
18873 		 */
18874 		if (!(tcp->tcp_connp->conn_state_flags & CONN_CLOSING)) {
18875 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18876 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18877 				tcp->tcp_connp->conn_ire_cache = ire;
18878 				cached = B_TRUE;
18879 			}
18880 			rw_exit(&ire->ire_bucket->irb_lock);
18881 		}
18882 
18883 		/*
18884 		 * We can continue to use the ire but since it was not
18885 		 * cached, we should drop the extra reference.
18886 		 */
18887 		if (!cached)
18888 			IRE_REFRELE_NOTR(ire);
18889 	}
18890 
18891 	ASSERT(ire != NULL);
18892 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
18893 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
18894 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
18895 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18896 	/*
18897 	 * If we do support loopback for MDT (which requires modifications
18898 	 * to the receiving paths), the following assertions should go away,
18899 	 * and we would be sending the Multidata to loopback conn later on.
18900 	 */
18901 	ASSERT(!IRE_IS_LOCAL(ire));
18902 	ASSERT(ire->ire_stq != NULL);
18903 
18904 	ill = ire_to_ill(ire);
18905 	ASSERT(ill != NULL);
18906 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
18907 
18908 	if (!tcp->tcp_ire_ill_check_done) {
18909 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
18910 		tcp->tcp_ire_ill_check_done = B_TRUE;
18911 	}
18912 
18913 	/*
18914 	 * If the underlying interface conditions have changed, or if the
18915 	 * new interface does not support MDT, go back to legacy path.
18916 	 */
18917 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
18918 		/* don't go through this path anymore for this connection */
18919 		TCP_STAT(tcp_mdt_conn_halted2);
18920 		tcp->tcp_mdt = B_FALSE;
18921 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
18922 		    "interface %s\n", (void *)tcp->tcp_connp, ill->ill_name));
18923 		/* IRE will be released prior to returning */
18924 		goto legacy_send_no_md;
18925 	}
18926 
18927 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
18928 		zc_cap = ill->ill_zerocopy_capab;
18929 
18930 	/* go to legacy path if interface doesn't support zerocopy */
18931 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
18932 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
18933 		/* IRE will be released prior to returning */
18934 		goto legacy_send_no_md;
18935 	}
18936 
18937 	/* does the interface support hardware checksum offload? */
18938 	hwcksum_flags = 0;
18939 	if (ILL_HCKSUM_CAPABLE(ill) &&
18940 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
18941 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
18942 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
18943 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18944 		    HCKSUM_IPHDRCKSUM)
18945 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
18946 
18947 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18948 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
18949 			hwcksum_flags |= HCK_FULLCKSUM;
18950 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
18951 		    HCKSUM_INET_PARTIAL)
18952 			hwcksum_flags |= HCK_PARTIALCKSUM;
18953 	}
18954 
18955 	/*
18956 	 * Each header fragment consists of the leading extra space,
18957 	 * followed by the TCP/IP header, and the trailing extra space.
18958 	 * We make sure that each header fragment begins on a 32-bit
18959 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
18960 	 * aligned in tcp_mdt_update).
18961 	 */
18962 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
18963 	    tcp->tcp_mdt_hdr_tail), 4);
18964 
18965 	/* are we starting from the beginning of data block? */
18966 	if (*tail_unsent == 0) {
18967 		*xmit_tail = (*xmit_tail)->b_cont;
18968 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
18969 		*tail_unsent = (int)MBLKL(*xmit_tail);
18970 	}
18971 
18972 	/*
18973 	 * Here we create one or more Multidata messages, each made up of
18974 	 * one header buffer and up to N payload buffers.  This entire
18975 	 * operation is done within two loops:
18976 	 *
18977 	 * The outer loop mostly deals with creating the Multidata message,
18978 	 * as well as the header buffer that gets added to it.  It also
18979 	 * links the Multidata messages together such that all of them can
18980 	 * be sent down to the lower layer in a single putnext call; this
18981 	 * linking behavior depends on the tcp_mdt_chain tunable.
18982 	 *
18983 	 * The inner loop takes an existing Multidata message, and adds
18984 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
18985 	 * packetizes those buffers by filling up the corresponding header
18986 	 * buffer fragments with the proper IP and TCP headers, and by
18987 	 * describing the layout of each packet in the packet descriptors
18988 	 * that get added to the Multidata.
18989 	 */
18990 	do {
18991 		/*
18992 		 * If usable send window is too small, or data blocks in
18993 		 * transmit list are smaller than our threshold (i.e. app
18994 		 * performs large writes followed by small ones), we hand
18995 		 * off the control over to the legacy path.  Note that we'll
18996 		 * get back the control once it encounters a large block.
18997 		 */
18998 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
18999 		    (*xmit_tail)->b_cont != NULL &&
19000 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
19001 			/* send down what we've got so far */
19002 			if (md_mp_head != NULL) {
19003 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
19004 				    obsegs, obbytes, &rconfirm);
19005 			}
19006 			/*
19007 			 * Pass control over to tcp_send(), but tell it to
19008 			 * return to us once a large-size transmission is
19009 			 * possible.
19010 			 */
19011 			TCP_STAT(tcp_mdt_legacy_small);
19012 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
19013 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
19014 			    tail_unsent, xmit_tail, local_time,
19015 			    mdt_thres)) <= 0) {
19016 				/* burst count reached, or alloc failed */
19017 				IRE_REFRELE(ire);
19018 				return (err);
19019 			}
19020 
19021 			/* tcp_send() may have sent everything, so check */
19022 			if (*usable <= 0) {
19023 				IRE_REFRELE(ire);
19024 				return (0);
19025 			}
19026 
19027 			TCP_STAT(tcp_mdt_legacy_ret);
19028 			/*
19029 			 * We may have delivered the Multidata, so make sure
19030 			 * to re-initialize before the next round.
19031 			 */
19032 			md_mp_head = NULL;
19033 			obsegs = obbytes = 0;
19034 			num_burst_seg = tcp->tcp_snd_burst;
19035 			PREP_NEW_MULTIDATA();
19036 
19037 			/* are we starting from the beginning of data block? */
19038 			if (*tail_unsent == 0) {
19039 				*xmit_tail = (*xmit_tail)->b_cont;
19040 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19041 				    (uintptr_t)INT_MAX);
19042 				*tail_unsent = (int)MBLKL(*xmit_tail);
19043 			}
19044 		}
19045 
19046 		/*
19047 		 * max_pld limits the number of mblks in tcp's transmit
19048 		 * queue that can be added to a Multidata message.  Once
19049 		 * this counter reaches zero, no more additional mblks
19050 		 * can be added to it.  What happens afterwards depends
19051 		 * on whether or not we are set to chain the Multidata
19052 		 * messages.  If we are to link them together, reset
19053 		 * max_pld to its original value (tcp_mdt_max_pld) and
19054 		 * prepare to create a new Multidata message which will
19055 		 * get linked to md_mp_head.  Else, leave it alone and
19056 		 * let the inner loop break on its own.
19057 		 */
19058 		if (tcp_mdt_chain && max_pld == 0)
19059 			PREP_NEW_MULTIDATA();
19060 
19061 		/* adding a payload buffer; re-initialize values */
19062 		if (add_buffer)
19063 			PREP_NEW_PBUF();
19064 
19065 		/*
19066 		 * If we don't have a Multidata, either because we just
19067 		 * (re)entered this outer loop, or after we branched off
19068 		 * to tcp_send above, setup the Multidata and header
19069 		 * buffer to be used.
19070 		 */
19071 		if (md_mp == NULL) {
19072 			int md_hbuflen;
19073 			uint32_t start, stuff;
19074 
19075 			/*
19076 			 * Calculate Multidata header buffer size large enough
19077 			 * to hold all of the headers that can possibly be
19078 			 * sent at this moment.  We'd rather over-estimate
19079 			 * the size than running out of space; this is okay
19080 			 * since this buffer is small anyway.
19081 			 */
19082 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
19083 
19084 			/*
19085 			 * Start and stuff offset for partial hardware
19086 			 * checksum offload; these are currently for IPv4.
19087 			 * For full checksum offload, they are set to zero.
19088 			 */
19089 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
19090 				if (af == AF_INET) {
19091 					start = IP_SIMPLE_HDR_LENGTH;
19092 					stuff = IP_SIMPLE_HDR_LENGTH +
19093 					    TCP_CHECKSUM_OFFSET;
19094 				} else {
19095 					start = IPV6_HDR_LEN;
19096 					stuff = IPV6_HDR_LEN +
19097 					    TCP_CHECKSUM_OFFSET;
19098 				}
19099 			} else {
19100 				start = stuff = 0;
19101 			}
19102 
19103 			/*
19104 			 * Create the header buffer, Multidata, as well as
19105 			 * any necessary attributes (destination address,
19106 			 * SAP and hardware checksum offload) that should
19107 			 * be associated with the Multidata message.
19108 			 */
19109 			ASSERT(cur_hdr_off == 0);
19110 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
19111 			    ((md_hbuf->b_wptr += md_hbuflen),
19112 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
19113 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
19114 			    /* fastpath mblk */
19115 			    (af == AF_INET) ? ire->ire_dlureq_mp :
19116 			    ire->ire_nce->nce_res_mp,
19117 			    /* hardware checksum enabled */
19118 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
19119 			    /* hardware checksum offsets */
19120 			    start, stuff, 0,
19121 			    /* hardware checksum flag */
19122 			    hwcksum_flags) != 0)) {
19123 legacy_send:
19124 				if (md_mp != NULL) {
19125 					/* Unlink message from the chain */
19126 					if (md_mp_head != NULL) {
19127 						err = (intptr_t)rmvb(md_mp_head,
19128 						    md_mp);
19129 						/*
19130 						 * We can't assert that rmvb
19131 						 * did not return -1, since we
19132 						 * may get here before linkb
19133 						 * happens.  We do, however,
19134 						 * check if we just removed the
19135 						 * only element in the list.
19136 						 */
19137 						if (err == 0)
19138 							md_mp_head = NULL;
19139 					}
19140 					/* md_hbuf gets freed automatically */
19141 					TCP_STAT(tcp_mdt_discarded);
19142 					freeb(md_mp);
19143 				} else {
19144 					/* Either allocb or mmd_alloc failed */
19145 					TCP_STAT(tcp_mdt_allocfail);
19146 					if (md_hbuf != NULL)
19147 						freeb(md_hbuf);
19148 				}
19149 
19150 				/* send down what we've got so far */
19151 				if (md_mp_head != NULL) {
19152 					tcp_multisend_data(tcp, ire, ill,
19153 					    md_mp_head, obsegs, obbytes,
19154 					    &rconfirm);
19155 				}
19156 legacy_send_no_md:
19157 				if (ire != NULL)
19158 					IRE_REFRELE(ire);
19159 				/*
19160 				 * Too bad; let the legacy path handle this.
19161 				 * We specify INT_MAX for the threshold, since
19162 				 * we gave up with the Multidata processings
19163 				 * and let the old path have it all.
19164 				 */
19165 				TCP_STAT(tcp_mdt_legacy_all);
19166 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
19167 				    tcp_tcp_hdr_len, num_sack_blk, usable,
19168 				    snxt, tail_unsent, xmit_tail, local_time,
19169 				    INT_MAX));
19170 			}
19171 
19172 			/* link to any existing ones, if applicable */
19173 			TCP_STAT(tcp_mdt_allocd);
19174 			if (md_mp_head == NULL) {
19175 				md_mp_head = md_mp;
19176 			} else if (tcp_mdt_chain) {
19177 				TCP_STAT(tcp_mdt_linked);
19178 				linkb(md_mp_head, md_mp);
19179 			}
19180 		}
19181 
19182 		ASSERT(md_mp_head != NULL);
19183 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
19184 		ASSERT(md_mp != NULL && mmd != NULL);
19185 		ASSERT(md_hbuf != NULL);
19186 
19187 		/*
19188 		 * Packetize the transmittable portion of the data block;
19189 		 * each data block is essentially added to the Multidata
19190 		 * as a payload buffer.  We also deal with adding more
19191 		 * than one payload buffers, which happens when the remaining
19192 		 * packetized portion of the current payload buffer is less
19193 		 * than MSS, while the next data block in transmit queue
19194 		 * has enough data to make up for one.  This "spillover"
19195 		 * case essentially creates a split-packet, where portions
19196 		 * of the packet's payload fragments may span across two
19197 		 * virtually discontiguous address blocks.
19198 		 */
19199 		seg_len = mss;
19200 		do {
19201 			len = seg_len;
19202 
19203 			ASSERT(len > 0);
19204 			ASSERT(max_pld >= 0);
19205 			ASSERT(!add_buffer || cur_pld_off == 0);
19206 
19207 			/*
19208 			 * First time around for this payload buffer; note
19209 			 * in the case of a spillover, the following has
19210 			 * been done prior to adding the split-packet
19211 			 * descriptor to Multidata, and we don't want to
19212 			 * repeat the process.
19213 			 */
19214 			if (add_buffer) {
19215 				ASSERT(mmd != NULL);
19216 				ASSERT(md_pbuf == NULL);
19217 				ASSERT(md_pbuf_nxt == NULL);
19218 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
19219 
19220 				/*
19221 				 * Have we reached the limit?  We'd get to
19222 				 * this case when we're not chaining the
19223 				 * Multidata messages together, and since
19224 				 * we're done, terminate this loop.
19225 				 */
19226 				if (max_pld == 0)
19227 					break; /* done */
19228 
19229 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
19230 					TCP_STAT(tcp_mdt_allocfail);
19231 					goto legacy_send; /* out_of_mem */
19232 				}
19233 
19234 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
19235 				    zc_cap != NULL) {
19236 					if (!ip_md_zcopy_attr(mmd, NULL,
19237 					    zc_cap->ill_zerocopy_flags)) {
19238 						freeb(md_pbuf);
19239 						TCP_STAT(tcp_mdt_allocfail);
19240 						/* out_of_mem */
19241 						goto legacy_send;
19242 					}
19243 					zcopy = B_TRUE;
19244 				}
19245 
19246 				md_pbuf->b_rptr += base_pld_off;
19247 
19248 				/*
19249 				 * Add a payload buffer to the Multidata; this
19250 				 * operation must not fail, or otherwise our
19251 				 * logic in this routine is broken.  There
19252 				 * is no memory allocation done by the
19253 				 * routine, so any returned failure simply
19254 				 * tells us that we've done something wrong.
19255 				 *
19256 				 * A failure tells us that either we're adding
19257 				 * the same payload buffer more than once, or
19258 				 * we're trying to add more buffers than
19259 				 * allowed (max_pld calculation is wrong).
19260 				 * None of the above cases should happen, and
19261 				 * we panic because either there's horrible
19262 				 * heap corruption, and/or programming mistake.
19263 				 */
19264 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
19265 				if (pbuf_idx < 0) {
19266 					cmn_err(CE_PANIC, "tcp_multisend: "
19267 					    "payload buffer logic error "
19268 					    "detected for tcp %p mmd %p "
19269 					    "pbuf %p (%d)\n",
19270 					    (void *)tcp, (void *)mmd,
19271 					    (void *)md_pbuf, pbuf_idx);
19272 				}
19273 
19274 				ASSERT(max_pld > 0);
19275 				--max_pld;
19276 				add_buffer = B_FALSE;
19277 			}
19278 
19279 			ASSERT(md_mp_head != NULL);
19280 			ASSERT(md_pbuf != NULL);
19281 			ASSERT(md_pbuf_nxt == NULL);
19282 			ASSERT(pbuf_idx != -1);
19283 			ASSERT(pbuf_idx_nxt == -1);
19284 			ASSERT(*usable > 0);
19285 
19286 			/*
19287 			 * We spillover to the next payload buffer only
19288 			 * if all of the following is true:
19289 			 *
19290 			 *   1. There is not enough data on the current
19291 			 *	payload buffer to make up `len',
19292 			 *   2. We are allowed to send `len',
19293 			 *   3. The next payload buffer length is large
19294 			 *	enough to accomodate `spill'.
19295 			 */
19296 			if ((spill = len - *tail_unsent) > 0 &&
19297 			    *usable >= len &&
19298 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
19299 			    max_pld > 0) {
19300 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
19301 				if (md_pbuf_nxt == NULL) {
19302 					TCP_STAT(tcp_mdt_allocfail);
19303 					goto legacy_send; /* out_of_mem */
19304 				}
19305 
19306 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
19307 				    zc_cap != NULL) {
19308 					if (!ip_md_zcopy_attr(mmd, NULL,
19309 					    zc_cap->ill_zerocopy_flags)) {
19310 						freeb(md_pbuf_nxt);
19311 						TCP_STAT(tcp_mdt_allocfail);
19312 						/* out_of_mem */
19313 						goto legacy_send;
19314 					}
19315 					zcopy = B_TRUE;
19316 				}
19317 
19318 				/*
19319 				 * See comments above on the first call to
19320 				 * mmd_addpldbuf for explanation on the panic.
19321 				 */
19322 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
19323 				if (pbuf_idx_nxt < 0) {
19324 					panic("tcp_multisend: "
19325 					    "next payload buffer logic error "
19326 					    "detected for tcp %p mmd %p "
19327 					    "pbuf %p (%d)\n",
19328 					    (void *)tcp, (void *)mmd,
19329 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
19330 				}
19331 
19332 				ASSERT(max_pld > 0);
19333 				--max_pld;
19334 			} else if (spill > 0) {
19335 				/*
19336 				 * If there's a spillover, but the following
19337 				 * xmit_tail couldn't give us enough octets
19338 				 * to reach "len", then stop the current
19339 				 * Multidata creation and let the legacy
19340 				 * tcp_send() path take over.  We don't want
19341 				 * to send the tiny segment as part of this
19342 				 * Multidata for performance reasons; instead,
19343 				 * we let the legacy path deal with grouping
19344 				 * it with the subsequent small mblks.
19345 				 */
19346 				if (*usable >= len &&
19347 				    MBLKL((*xmit_tail)->b_cont) < spill) {
19348 					max_pld = 0;
19349 					break;	/* done */
19350 				}
19351 
19352 				/*
19353 				 * We can't spillover, and we are near
19354 				 * the end of the current payload buffer,
19355 				 * so send what's left.
19356 				 */
19357 				ASSERT(*tail_unsent > 0);
19358 				len = *tail_unsent;
19359 			}
19360 
19361 			/* tail_unsent is negated if there is a spillover */
19362 			*tail_unsent -= len;
19363 			*usable -= len;
19364 			ASSERT(*usable >= 0);
19365 
19366 			if (*usable < mss)
19367 				seg_len = *usable;
19368 			/*
19369 			 * Sender SWS avoidance; see comments in tcp_send();
19370 			 * everything else is the same, except that we only
19371 			 * do this here if there is no more data to be sent
19372 			 * following the current xmit_tail.  We don't check
19373 			 * for 1-byte urgent data because we shouldn't get
19374 			 * here if TCP_URG_VALID is set.
19375 			 */
19376 			if (*usable > 0 && *usable < mss &&
19377 			    ((md_pbuf_nxt == NULL &&
19378 			    (*xmit_tail)->b_cont == NULL) ||
19379 			    (md_pbuf_nxt != NULL &&
19380 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
19381 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
19382 			    (tcp->tcp_unsent -
19383 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
19384 			    !tcp->tcp_zero_win_probe) {
19385 				if ((*snxt + len) == tcp->tcp_snxt &&
19386 				    (*snxt + len) == tcp->tcp_suna) {
19387 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19388 				}
19389 				done = B_TRUE;
19390 			}
19391 
19392 			/*
19393 			 * Prime pump for IP's checksumming on our behalf;
19394 			 * include the adjustment for a source route if any.
19395 			 * Do this only for software/partial hardware checksum
19396 			 * offload, as this field gets zeroed out later for
19397 			 * the full hardware checksum offload case.
19398 			 */
19399 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
19400 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19401 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
19402 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
19403 			}
19404 
19405 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
19406 			*snxt += len;
19407 
19408 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
19409 			/*
19410 			 * We set the PUSH bit only if TCP has no more buffered
19411 			 * data to be transmitted (or if sender SWS avoidance
19412 			 * takes place), as opposed to setting it for every
19413 			 * last packet in the burst.
19414 			 */
19415 			if (done ||
19416 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
19417 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
19418 
19419 			/*
19420 			 * Set FIN bit if this is our last segment; snxt
19421 			 * already includes its length, and it will not
19422 			 * be adjusted after this point.
19423 			 */
19424 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
19425 			    *snxt == tcp->tcp_fss) {
19426 				if (!tcp->tcp_fin_acked) {
19427 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
19428 					BUMP_MIB(&tcp_mib, tcpOutControl);
19429 				}
19430 				if (!tcp->tcp_fin_sent) {
19431 					tcp->tcp_fin_sent = B_TRUE;
19432 					/*
19433 					 * tcp state must be ESTABLISHED
19434 					 * in order for us to get here in
19435 					 * the first place.
19436 					 */
19437 					tcp->tcp_state = TCPS_FIN_WAIT_1;
19438 
19439 					/*
19440 					 * Upon returning from this routine,
19441 					 * tcp_wput_data() will set tcp_snxt
19442 					 * to be equal to snxt + tcp_fin_sent.
19443 					 * This is essentially the same as
19444 					 * setting it to tcp_fss + 1.
19445 					 */
19446 				}
19447 			}
19448 
19449 			tcp->tcp_last_sent_len = (ushort_t)len;
19450 
19451 			len += tcp_hdr_len;
19452 			if (tcp->tcp_ipversion == IPV4_VERSION)
19453 				tcp->tcp_ipha->ipha_length = htons(len);
19454 			else
19455 				tcp->tcp_ip6h->ip6_plen = htons(len -
19456 				    ((char *)&tcp->tcp_ip6h[1] -
19457 				    tcp->tcp_iphc));
19458 
19459 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
19460 
19461 			/* setup header fragment */
19462 			PDESC_HDR_ADD(pkt_info,
19463 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
19464 			    tcp->tcp_mdt_hdr_head,		/* head room */
19465 			    tcp_hdr_len,			/* len */
19466 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
19467 
19468 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
19469 			    hdr_frag_sz);
19470 			ASSERT(MBLKIN(md_hbuf,
19471 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
19472 			    PDESC_HDRSIZE(pkt_info)));
19473 
19474 			/* setup first payload fragment */
19475 			PDESC_PLD_INIT(pkt_info);
19476 			PDESC_PLD_SPAN_ADD(pkt_info,
19477 			    pbuf_idx,				/* index */
19478 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
19479 			    tcp->tcp_last_sent_len);		/* len */
19480 
19481 			/* create a split-packet in case of a spillover */
19482 			if (md_pbuf_nxt != NULL) {
19483 				ASSERT(spill > 0);
19484 				ASSERT(pbuf_idx_nxt > pbuf_idx);
19485 				ASSERT(!add_buffer);
19486 
19487 				md_pbuf = md_pbuf_nxt;
19488 				md_pbuf_nxt = NULL;
19489 				pbuf_idx = pbuf_idx_nxt;
19490 				pbuf_idx_nxt = -1;
19491 				cur_pld_off = spill;
19492 
19493 				/* trim out first payload fragment */
19494 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
19495 
19496 				/* setup second payload fragment */
19497 				PDESC_PLD_SPAN_ADD(pkt_info,
19498 				    pbuf_idx,			/* index */
19499 				    md_pbuf->b_rptr,		/* start */
19500 				    spill);			/* len */
19501 
19502 				if ((*xmit_tail)->b_next == NULL) {
19503 					/*
19504 					 * Store the lbolt used for RTT
19505 					 * estimation. We can only record one
19506 					 * timestamp per mblk so we do it when
19507 					 * we reach the end of the payload
19508 					 * buffer.  Also we only take a new
19509 					 * timestamp sample when the previous
19510 					 * timed data from the same mblk has
19511 					 * been ack'ed.
19512 					 */
19513 					(*xmit_tail)->b_prev = local_time;
19514 					(*xmit_tail)->b_next =
19515 					    (mblk_t *)(uintptr_t)first_snxt;
19516 				}
19517 
19518 				first_snxt = *snxt - spill;
19519 
19520 				/*
19521 				 * Advance xmit_tail; usable could be 0 by
19522 				 * the time we got here, but we made sure
19523 				 * above that we would only spillover to
19524 				 * the next data block if usable includes
19525 				 * the spilled-over amount prior to the
19526 				 * subtraction.  Therefore, we are sure
19527 				 * that xmit_tail->b_cont can't be NULL.
19528 				 */
19529 				ASSERT((*xmit_tail)->b_cont != NULL);
19530 				*xmit_tail = (*xmit_tail)->b_cont;
19531 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19532 				    (uintptr_t)INT_MAX);
19533 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
19534 			} else {
19535 				cur_pld_off += tcp->tcp_last_sent_len;
19536 			}
19537 
19538 			/*
19539 			 * Fill in the header using the template header, and
19540 			 * add options such as time-stamp, ECN and/or SACK,
19541 			 * as needed.
19542 			 */
19543 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
19544 			    (clock_t)local_time, num_sack_blk);
19545 
19546 			/* take care of some IP header businesses */
19547 			if (af == AF_INET) {
19548 				ipha = (ipha_t *)pkt_info->hdr_rptr;
19549 
19550 				ASSERT(OK_32PTR((uchar_t *)ipha));
19551 				ASSERT(PDESC_HDRL(pkt_info) >=
19552 				    IP_SIMPLE_HDR_LENGTH);
19553 				ASSERT(ipha->ipha_version_and_hdr_length ==
19554 				    IP_SIMPLE_HDR_VERSION);
19555 
19556 				/*
19557 				 * Assign ident value for current packet; see
19558 				 * related comments in ip_wput_ire() about the
19559 				 * contract private interface with clustering
19560 				 * group.
19561 				 */
19562 				clusterwide = B_FALSE;
19563 				if (cl_inet_ipident != NULL) {
19564 					ASSERT(cl_inet_isclusterwide != NULL);
19565 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
19566 					    AF_INET,
19567 					    (uint8_t *)(uintptr_t)src)) {
19568 						ipha->ipha_ident =
19569 						    (*cl_inet_ipident)
19570 						    (IPPROTO_IP, AF_INET,
19571 						    (uint8_t *)(uintptr_t)src,
19572 						    (uint8_t *)(uintptr_t)dst);
19573 						clusterwide = B_TRUE;
19574 					}
19575 				}
19576 
19577 				if (!clusterwide) {
19578 					ipha->ipha_ident = (uint16_t)
19579 					    atomic_add_32_nv(
19580 						&ire->ire_ident, 1);
19581 				}
19582 #ifndef _BIG_ENDIAN
19583 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
19584 				    (ipha->ipha_ident >> 8);
19585 #endif
19586 			} else {
19587 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
19588 
19589 				ASSERT(OK_32PTR((uchar_t *)ip6h));
19590 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
19591 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
19592 				ASSERT(PDESC_HDRL(pkt_info) >=
19593 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
19594 				    TCP_CHECKSUM_SIZE));
19595 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
19596 
19597 				if (tcp->tcp_ip_forward_progress) {
19598 					rconfirm = B_TRUE;
19599 					tcp->tcp_ip_forward_progress = B_FALSE;
19600 				}
19601 			}
19602 
19603 			/* at least one payload span, and at most two */
19604 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
19605 
19606 			/* add the packet descriptor to Multidata */
19607 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
19608 			    KM_NOSLEEP)) == NULL) {
19609 				/*
19610 				 * Any failure other than ENOMEM indicates
19611 				 * that we have passed in invalid pkt_info
19612 				 * or parameters to mmd_addpdesc, which must
19613 				 * not happen.
19614 				 *
19615 				 * EINVAL is a result of failure on boundary
19616 				 * checks against the pkt_info contents.  It
19617 				 * should not happen, and we panic because
19618 				 * either there's horrible heap corruption,
19619 				 * and/or programming mistake.
19620 				 */
19621 				if (err != ENOMEM) {
19622 					cmn_err(CE_PANIC, "tcp_multisend: "
19623 					    "pdesc logic error detected for "
19624 					    "tcp %p mmd %p pinfo %p (%d)\n",
19625 					    (void *)tcp, (void *)mmd,
19626 					    (void *)pkt_info, err);
19627 				}
19628 				TCP_STAT(tcp_mdt_addpdescfail);
19629 				goto legacy_send; /* out_of_mem */
19630 			}
19631 			ASSERT(pkt != NULL);
19632 
19633 			/* calculate IP header and TCP checksums */
19634 			if (af == AF_INET) {
19635 				/* calculate pseudo-header checksum */
19636 				cksum = (dst >> 16) + (dst & 0xFFFF) +
19637 				    (src >> 16) + (src & 0xFFFF);
19638 
19639 				/* offset for TCP header checksum */
19640 				up = IPH_TCPH_CHECKSUMP(ipha,
19641 				    IP_SIMPLE_HDR_LENGTH);
19642 			} else {
19643 				up = (uint16_t *)&ip6h->ip6_src;
19644 
19645 				/* calculate pseudo-header checksum */
19646 				cksum = up[0] + up[1] + up[2] + up[3] +
19647 				    up[4] + up[5] + up[6] + up[7] +
19648 				    up[8] + up[9] + up[10] + up[11] +
19649 				    up[12] + up[13] + up[14] + up[15];
19650 
19651 				/* Fold the initial sum */
19652 				cksum = (cksum & 0xffff) + (cksum >> 16);
19653 
19654 				up = (uint16_t *)(((uchar_t *)ip6h) +
19655 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
19656 			}
19657 
19658 			if (hwcksum_flags & HCK_FULLCKSUM) {
19659 				/* clear checksum field for hardware */
19660 				*up = 0;
19661 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
19662 				uint32_t sum;
19663 
19664 				/* pseudo-header checksumming */
19665 				sum = *up + cksum + IP_TCP_CSUM_COMP;
19666 				sum = (sum & 0xFFFF) + (sum >> 16);
19667 				*up = (sum & 0xFFFF) + (sum >> 16);
19668 			} else {
19669 				/* software checksumming */
19670 				TCP_STAT(tcp_out_sw_cksum);
19671 				TCP_STAT_UPDATE(tcp_out_sw_cksum_bytes,
19672 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
19673 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
19674 				    cksum + IP_TCP_CSUM_COMP);
19675 				if (*up == 0)
19676 					*up = 0xFFFF;
19677 			}
19678 
19679 			/* IPv4 header checksum */
19680 			if (af == AF_INET) {
19681 				ipha->ipha_fragment_offset_and_flags |=
19682 				    (uint32_t)htons(ire->ire_frag_flag);
19683 
19684 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
19685 					ipha->ipha_hdr_checksum = 0;
19686 				} else {
19687 					IP_HDR_CKSUM(ipha, cksum,
19688 					    ((uint32_t *)ipha)[0],
19689 					    ((uint16_t *)ipha)[4]);
19690 				}
19691 			}
19692 
19693 			/* advance header offset */
19694 			cur_hdr_off += hdr_frag_sz;
19695 
19696 			obbytes += tcp->tcp_last_sent_len;
19697 			++obsegs;
19698 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
19699 		    *tail_unsent > 0);
19700 
19701 		if ((*xmit_tail)->b_next == NULL) {
19702 			/*
19703 			 * Store the lbolt used for RTT estimation. We can only
19704 			 * record one timestamp per mblk so we do it when we
19705 			 * reach the end of the payload buffer. Also we only
19706 			 * take a new timestamp sample when the previous timed
19707 			 * data from the same mblk has been ack'ed.
19708 			 */
19709 			(*xmit_tail)->b_prev = local_time;
19710 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
19711 		}
19712 
19713 		ASSERT(*tail_unsent >= 0);
19714 		if (*tail_unsent > 0) {
19715 			/*
19716 			 * We got here because we broke out of the above
19717 			 * loop due to of one of the following cases:
19718 			 *
19719 			 *   1. len < adjusted MSS (i.e. small),
19720 			 *   2. Sender SWS avoidance,
19721 			 *   3. max_pld is zero.
19722 			 *
19723 			 * We are done for this Multidata, so trim our
19724 			 * last payload buffer (if any) accordingly.
19725 			 */
19726 			if (md_pbuf != NULL)
19727 				md_pbuf->b_wptr -= *tail_unsent;
19728 		} else if (*usable > 0) {
19729 			*xmit_tail = (*xmit_tail)->b_cont;
19730 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
19731 			    (uintptr_t)INT_MAX);
19732 			*tail_unsent = (int)MBLKL(*xmit_tail);
19733 			add_buffer = B_TRUE;
19734 		}
19735 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
19736 	    (tcp_mdt_chain || max_pld > 0));
19737 
19738 	/* send everything down */
19739 	tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
19740 	    &rconfirm);
19741 
19742 #undef PREP_NEW_MULTIDATA
19743 #undef PREP_NEW_PBUF
19744 #undef IPVER
19745 
19746 	IRE_REFRELE(ire);
19747 	return (0);
19748 }
19749 
19750 /*
19751  * A wrapper function for sending one or more Multidata messages down to
19752  * the module below ip; this routine does not release the reference of the
19753  * IRE (caller does that).  This routine is analogous to tcp_send_data().
19754  */
19755 static void
19756 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
19757     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
19758 {
19759 	uint64_t delta;
19760 	nce_t *nce;
19761 
19762 	ASSERT(ire != NULL && ill != NULL);
19763 	ASSERT(ire->ire_stq != NULL);
19764 	ASSERT(md_mp_head != NULL);
19765 	ASSERT(rconfirm != NULL);
19766 
19767 	/* adjust MIBs and IRE timestamp */
19768 	TCP_RECORD_TRACE(tcp, md_mp_head, TCP_TRACE_SEND_PKT);
19769 	tcp->tcp_obsegs += obsegs;
19770 	UPDATE_MIB(&tcp_mib, tcpOutDataSegs, obsegs);
19771 	UPDATE_MIB(&tcp_mib, tcpOutDataBytes, obbytes);
19772 	TCP_STAT_UPDATE(tcp_mdt_pkt_out, obsegs);
19773 
19774 	if (tcp->tcp_ipversion == IPV4_VERSION) {
19775 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v4, obsegs);
19776 		UPDATE_MIB(&ip_mib, ipOutRequests, obsegs);
19777 	} else {
19778 		TCP_STAT_UPDATE(tcp_mdt_pkt_out_v6, obsegs);
19779 		UPDATE_MIB(&ip6_mib, ipv6OutRequests, obsegs);
19780 	}
19781 
19782 	ire->ire_ob_pkt_count += obsegs;
19783 	if (ire->ire_ipif != NULL)
19784 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
19785 	ire->ire_last_used_time = lbolt;
19786 
19787 	/* send it down */
19788 	putnext(ire->ire_stq, md_mp_head);
19789 
19790 	/* we're done for TCP/IPv4 */
19791 	if (tcp->tcp_ipversion == IPV4_VERSION)
19792 		return;
19793 
19794 	nce = ire->ire_nce;
19795 
19796 	ASSERT(nce != NULL);
19797 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
19798 	ASSERT(nce->nce_state != ND_INCOMPLETE);
19799 
19800 	/* reachability confirmation? */
19801 	if (*rconfirm) {
19802 		nce->nce_last = TICK_TO_MSEC(lbolt64);
19803 		if (nce->nce_state != ND_REACHABLE) {
19804 			mutex_enter(&nce->nce_lock);
19805 			nce->nce_state = ND_REACHABLE;
19806 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
19807 			mutex_exit(&nce->nce_lock);
19808 			(void) untimeout(nce->nce_timeout_id);
19809 			if (ip_debug > 2) {
19810 				/* ip1dbg */
19811 				pr_addr_dbg("tcp_multisend_data: state "
19812 				    "for %s changed to REACHABLE\n",
19813 				    AF_INET6, &ire->ire_addr_v6);
19814 			}
19815 		}
19816 		/* reset transport reachability confirmation */
19817 		*rconfirm = B_FALSE;
19818 	}
19819 
19820 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
19821 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
19822 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
19823 
19824 	if (delta > (uint64_t)ill->ill_reachable_time) {
19825 		mutex_enter(&nce->nce_lock);
19826 		switch (nce->nce_state) {
19827 		case ND_REACHABLE:
19828 		case ND_STALE:
19829 			/*
19830 			 * ND_REACHABLE is identical to ND_STALE in this
19831 			 * specific case. If reachable time has expired for
19832 			 * this neighbor (delta is greater than reachable
19833 			 * time), conceptually, the neighbor cache is no
19834 			 * longer in REACHABLE state, but already in STALE
19835 			 * state.  So the correct transition here is to
19836 			 * ND_DELAY.
19837 			 */
19838 			nce->nce_state = ND_DELAY;
19839 			mutex_exit(&nce->nce_lock);
19840 			NDP_RESTART_TIMER(nce, delay_first_probe_time);
19841 			if (ip_debug > 3) {
19842 				/* ip2dbg */
19843 				pr_addr_dbg("tcp_multisend_data: state "
19844 				    "for %s changed to DELAY\n",
19845 				    AF_INET6, &ire->ire_addr_v6);
19846 			}
19847 			break;
19848 		case ND_DELAY:
19849 		case ND_PROBE:
19850 			mutex_exit(&nce->nce_lock);
19851 			/* Timers have already started */
19852 			break;
19853 		case ND_UNREACHABLE:
19854 			/*
19855 			 * ndp timer has detected that this nce is
19856 			 * unreachable and initiated deleting this nce
19857 			 * and all its associated IREs. This is a race
19858 			 * where we found the ire before it was deleted
19859 			 * and have just sent out a packet using this
19860 			 * unreachable nce.
19861 			 */
19862 			mutex_exit(&nce->nce_lock);
19863 			break;
19864 		default:
19865 			ASSERT(0);
19866 		}
19867 	}
19868 }
19869 
19870 /*
19871  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
19872  * scheme, and returns one of the following:
19873  *
19874  * -1 = failed allocation.
19875  *  0 = success; burst count reached, or usable send window is too small,
19876  *      and that we'd rather wait until later before sending again.
19877  *  1 = success; we are called from tcp_multisend(), and both usable send
19878  *      window and tail_unsent are greater than the MDT threshold, and thus
19879  *      Multidata Transmit should be used instead.
19880  */
19881 static int
19882 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
19883     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
19884     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
19885     const int mdt_thres)
19886 {
19887 	int num_burst_seg = tcp->tcp_snd_burst;
19888 
19889 	for (;;) {
19890 		struct datab	*db;
19891 		tcph_t		*tcph;
19892 		uint32_t	sum;
19893 		mblk_t		*mp, *mp1;
19894 		uchar_t		*rptr;
19895 		int		len;
19896 
19897 		/*
19898 		 * If we're called by tcp_multisend(), and the amount of
19899 		 * sendable data as well as the size of current xmit_tail
19900 		 * is beyond the MDT threshold, return to the caller and
19901 		 * let the large data transmit be done using MDT.
19902 		 */
19903 		if (*usable > 0 && *usable > mdt_thres &&
19904 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
19905 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
19906 			ASSERT(tcp->tcp_mdt);
19907 			return (1);	/* success; do large send */
19908 		}
19909 
19910 		if (num_burst_seg-- == 0)
19911 			break;		/* success; burst count reached */
19912 
19913 		len = mss;
19914 		if (len > *usable) {
19915 			len = *usable;
19916 			if (len <= 0) {
19917 				/* Terminate the loop */
19918 				break;	/* success; too small */
19919 			}
19920 			/*
19921 			 * Sender silly-window avoidance.
19922 			 * Ignore this if we are going to send a
19923 			 * zero window probe out.
19924 			 *
19925 			 * TODO: force data into microscopic window?
19926 			 *	==> (!pushed || (unsent > usable))
19927 			 */
19928 			if (len < (tcp->tcp_max_swnd >> 1) &&
19929 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
19930 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
19931 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
19932 				/*
19933 				 * If the retransmit timer is not running
19934 				 * we start it so that we will retransmit
19935 				 * in the case when the the receiver has
19936 				 * decremented the window.
19937 				 */
19938 				if (*snxt == tcp->tcp_snxt &&
19939 				    *snxt == tcp->tcp_suna) {
19940 					/*
19941 					 * We are not supposed to send
19942 					 * anything.  So let's wait a little
19943 					 * bit longer before breaking SWS
19944 					 * avoidance.
19945 					 *
19946 					 * What should the value be?
19947 					 * Suggestion: MAX(init rexmit time,
19948 					 * tcp->tcp_rto)
19949 					 */
19950 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19951 				}
19952 				break;	/* success; too small */
19953 			}
19954 		}
19955 
19956 		tcph = tcp->tcp_tcph;
19957 
19958 		*usable -= len; /* Approximate - can be adjusted later */
19959 		if (*usable > 0)
19960 			tcph->th_flags[0] = TH_ACK;
19961 		else
19962 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
19963 
19964 		/*
19965 		 * Prime pump for IP's checksumming on our behalf
19966 		 * Include the adjustment for a source route if any.
19967 		 */
19968 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
19969 		sum = (sum >> 16) + (sum & 0xFFFF);
19970 		U16_TO_ABE16(sum, tcph->th_sum);
19971 
19972 		U32_TO_ABE32(*snxt, tcph->th_seq);
19973 
19974 		/*
19975 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
19976 		 * set.  For the case when TCP_FSS_VALID is the only valid
19977 		 * bit (normal active close), branch off only when we think
19978 		 * that the FIN flag needs to be set.  Note for this case,
19979 		 * that (snxt + len) may not reflect the actual seg_len,
19980 		 * as len may be further reduced in tcp_xmit_mp().  If len
19981 		 * gets modified, we will end up here again.
19982 		 */
19983 		if (tcp->tcp_valid_bits != 0 &&
19984 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
19985 		    ((*snxt + len) == tcp->tcp_fss))) {
19986 			uchar_t		*prev_rptr;
19987 			uint32_t	prev_snxt = tcp->tcp_snxt;
19988 
19989 			if (*tail_unsent == 0) {
19990 				ASSERT((*xmit_tail)->b_cont != NULL);
19991 				*xmit_tail = (*xmit_tail)->b_cont;
19992 				prev_rptr = (*xmit_tail)->b_rptr;
19993 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
19994 				    (*xmit_tail)->b_rptr);
19995 			} else {
19996 				prev_rptr = (*xmit_tail)->b_rptr;
19997 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
19998 				    *tail_unsent;
19999 			}
20000 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
20001 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
20002 			/* Restore tcp_snxt so we get amount sent right. */
20003 			tcp->tcp_snxt = prev_snxt;
20004 			if (prev_rptr == (*xmit_tail)->b_rptr) {
20005 				/*
20006 				 * If the previous timestamp is still in use,
20007 				 * don't stomp on it.
20008 				 */
20009 				if ((*xmit_tail)->b_next == NULL) {
20010 					(*xmit_tail)->b_prev = local_time;
20011 					(*xmit_tail)->b_next =
20012 					    (mblk_t *)(uintptr_t)(*snxt);
20013 				}
20014 			} else
20015 				(*xmit_tail)->b_rptr = prev_rptr;
20016 
20017 			if (mp == NULL)
20018 				return (-1);
20019 			mp1 = mp->b_cont;
20020 
20021 			tcp->tcp_last_sent_len = (ushort_t)len;
20022 			while (mp1->b_cont) {
20023 				*xmit_tail = (*xmit_tail)->b_cont;
20024 				(*xmit_tail)->b_prev = local_time;
20025 				(*xmit_tail)->b_next =
20026 				    (mblk_t *)(uintptr_t)(*snxt);
20027 				mp1 = mp1->b_cont;
20028 			}
20029 			*snxt += len;
20030 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
20031 			BUMP_LOCAL(tcp->tcp_obsegs);
20032 			BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20033 			UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20034 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20035 			tcp_send_data(tcp, q, mp);
20036 			continue;
20037 		}
20038 
20039 		*snxt += len;	/* Adjust later if we don't send all of len */
20040 		BUMP_MIB(&tcp_mib, tcpOutDataSegs);
20041 		UPDATE_MIB(&tcp_mib, tcpOutDataBytes, len);
20042 
20043 		if (*tail_unsent) {
20044 			/* Are the bytes above us in flight? */
20045 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
20046 			if (rptr != (*xmit_tail)->b_rptr) {
20047 				*tail_unsent -= len;
20048 				tcp->tcp_last_sent_len = (ushort_t)len;
20049 				len += tcp_hdr_len;
20050 				if (tcp->tcp_ipversion == IPV4_VERSION)
20051 					tcp->tcp_ipha->ipha_length = htons(len);
20052 				else
20053 					tcp->tcp_ip6h->ip6_plen =
20054 					    htons(len -
20055 					    ((char *)&tcp->tcp_ip6h[1] -
20056 					    tcp->tcp_iphc));
20057 				mp = dupb(*xmit_tail);
20058 				if (!mp)
20059 					return (-1);	/* out_of_mem */
20060 				mp->b_rptr = rptr;
20061 				/*
20062 				 * If the old timestamp is no longer in use,
20063 				 * sample a new timestamp now.
20064 				 */
20065 				if ((*xmit_tail)->b_next == NULL) {
20066 					(*xmit_tail)->b_prev = local_time;
20067 					(*xmit_tail)->b_next =
20068 					    (mblk_t *)(uintptr_t)(*snxt-len);
20069 				}
20070 				goto must_alloc;
20071 			}
20072 		} else {
20073 			*xmit_tail = (*xmit_tail)->b_cont;
20074 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
20075 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
20076 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
20077 			    (*xmit_tail)->b_rptr);
20078 		}
20079 
20080 		(*xmit_tail)->b_prev = local_time;
20081 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
20082 
20083 		*tail_unsent -= len;
20084 		tcp->tcp_last_sent_len = (ushort_t)len;
20085 
20086 		len += tcp_hdr_len;
20087 		if (tcp->tcp_ipversion == IPV4_VERSION)
20088 			tcp->tcp_ipha->ipha_length = htons(len);
20089 		else
20090 			tcp->tcp_ip6h->ip6_plen = htons(len -
20091 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20092 
20093 		mp = dupb(*xmit_tail);
20094 		if (!mp)
20095 			return (-1);	/* out_of_mem */
20096 
20097 		len = tcp_hdr_len;
20098 		/*
20099 		 * There are four reasons to allocate a new hdr mblk:
20100 		 *  1) The bytes above us are in use by another packet
20101 		 *  2) We don't have good alignment
20102 		 *  3) The mblk is being shared
20103 		 *  4) We don't have enough room for a header
20104 		 */
20105 		rptr = mp->b_rptr - len;
20106 		if (!OK_32PTR(rptr) ||
20107 		    ((db = mp->b_datap), db->db_ref != 2) ||
20108 		    rptr < db->db_base) {
20109 			/* NOTE: we assume allocb returns an OK_32PTR */
20110 
20111 		must_alloc:;
20112 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
20113 			    tcp_wroff_xtra, BPRI_MED);
20114 			if (!mp1) {
20115 				freemsg(mp);
20116 				return (-1);	/* out_of_mem */
20117 			}
20118 			mp1->b_cont = mp;
20119 			mp = mp1;
20120 			/* Leave room for Link Level header */
20121 			len = tcp_hdr_len;
20122 			rptr = &mp->b_rptr[tcp_wroff_xtra];
20123 			mp->b_wptr = &rptr[len];
20124 		}
20125 
20126 		/*
20127 		 * Fill in the header using the template header, and add
20128 		 * options such as time-stamp, ECN and/or SACK, as needed.
20129 		 */
20130 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
20131 
20132 		mp->b_rptr = rptr;
20133 
20134 		if (*tail_unsent) {
20135 			int spill = *tail_unsent;
20136 
20137 			mp1 = mp->b_cont;
20138 			if (!mp1)
20139 				mp1 = mp;
20140 
20141 			/*
20142 			 * If we're a little short, tack on more mblks until
20143 			 * there is no more spillover.
20144 			 */
20145 			while (spill < 0) {
20146 				mblk_t *nmp;
20147 				int nmpsz;
20148 
20149 				nmp = (*xmit_tail)->b_cont;
20150 				nmpsz = MBLKL(nmp);
20151 
20152 				/*
20153 				 * Excess data in mblk; can we split it?
20154 				 * If MDT is enabled for the connection,
20155 				 * keep on splitting as this is a transient
20156 				 * send path.
20157 				 */
20158 				if (!tcp->tcp_mdt && (spill + nmpsz > 0)) {
20159 					/*
20160 					 * Don't split if stream head was
20161 					 * told to break up larger writes
20162 					 * into smaller ones.
20163 					 */
20164 					if (tcp->tcp_maxpsz > 0)
20165 						break;
20166 
20167 					/*
20168 					 * Next mblk is less than SMSS/2
20169 					 * rounded up to nearest 64-byte;
20170 					 * let it get sent as part of the
20171 					 * next segment.
20172 					 */
20173 					if (tcp->tcp_localnet &&
20174 					    !tcp->tcp_cork &&
20175 					    (nmpsz < roundup((mss >> 1), 64)))
20176 						break;
20177 				}
20178 
20179 				*xmit_tail = nmp;
20180 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
20181 				/* Stash for rtt use later */
20182 				(*xmit_tail)->b_prev = local_time;
20183 				(*xmit_tail)->b_next =
20184 				    (mblk_t *)(uintptr_t)(*snxt - len);
20185 				mp1->b_cont = dupb(*xmit_tail);
20186 				mp1 = mp1->b_cont;
20187 
20188 				spill += nmpsz;
20189 				if (mp1 == NULL) {
20190 					*tail_unsent = spill;
20191 					freemsg(mp);
20192 					return (-1);	/* out_of_mem */
20193 				}
20194 			}
20195 
20196 			/* Trim back any surplus on the last mblk */
20197 			if (spill >= 0) {
20198 				mp1->b_wptr -= spill;
20199 				*tail_unsent = spill;
20200 			} else {
20201 				/*
20202 				 * We did not send everything we could in
20203 				 * order to remain within the b_cont limit.
20204 				 */
20205 				*usable -= spill;
20206 				*snxt += spill;
20207 				tcp->tcp_last_sent_len += spill;
20208 				UPDATE_MIB(&tcp_mib, tcpOutDataBytes, spill);
20209 				/*
20210 				 * Adjust the checksum
20211 				 */
20212 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20213 				sum += spill;
20214 				sum = (sum >> 16) + (sum & 0xFFFF);
20215 				U16_TO_ABE16(sum, tcph->th_sum);
20216 				if (tcp->tcp_ipversion == IPV4_VERSION) {
20217 					sum = ntohs(
20218 					    ((ipha_t *)rptr)->ipha_length) +
20219 					    spill;
20220 					((ipha_t *)rptr)->ipha_length =
20221 					    htons(sum);
20222 				} else {
20223 					sum = ntohs(
20224 					    ((ip6_t *)rptr)->ip6_plen) +
20225 					    spill;
20226 					((ip6_t *)rptr)->ip6_plen =
20227 					    htons(sum);
20228 				}
20229 				*tail_unsent = 0;
20230 			}
20231 		}
20232 		if (tcp->tcp_ip_forward_progress) {
20233 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20234 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
20235 			tcp->tcp_ip_forward_progress = B_FALSE;
20236 		}
20237 
20238 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
20239 		tcp_send_data(tcp, q, mp);
20240 		BUMP_LOCAL(tcp->tcp_obsegs);
20241 	}
20242 
20243 	return (0);
20244 }
20245 
20246 /* Unlink and return any mblk that looks like it contains a MDT info */
20247 static mblk_t *
20248 tcp_mdt_info_mp(mblk_t *mp)
20249 {
20250 	mblk_t	*prev_mp;
20251 
20252 	for (;;) {
20253 		prev_mp = mp;
20254 		/* no more to process? */
20255 		if ((mp = mp->b_cont) == NULL)
20256 			break;
20257 
20258 		switch (DB_TYPE(mp)) {
20259 		case M_CTL:
20260 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
20261 				continue;
20262 			ASSERT(prev_mp != NULL);
20263 			prev_mp->b_cont = mp->b_cont;
20264 			mp->b_cont = NULL;
20265 			return (mp);
20266 		default:
20267 			break;
20268 		}
20269 	}
20270 	return (mp);
20271 }
20272 
20273 /* MDT info update routine, called when IP notifies us about MDT */
20274 static void
20275 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
20276 {
20277 	boolean_t prev_state;
20278 
20279 	/*
20280 	 * IP is telling us to abort MDT on this connection?  We know
20281 	 * this because the capability is only turned off when IP
20282 	 * encounters some pathological cases, e.g. link-layer change
20283 	 * where the new driver doesn't support MDT, or in situation
20284 	 * where MDT usage on the link-layer has been switched off.
20285 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
20286 	 * if the link-layer doesn't support MDT, and if it does, it
20287 	 * will indicate that the feature is to be turned on.
20288 	 */
20289 	prev_state = tcp->tcp_mdt;
20290 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
20291 	if (!tcp->tcp_mdt && !first) {
20292 		TCP_STAT(tcp_mdt_conn_halted3);
20293 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
20294 		    (void *)tcp->tcp_connp));
20295 	}
20296 
20297 	/*
20298 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
20299 	 * so disable MDT otherwise.  The checks are done here
20300 	 * and in tcp_wput_data().
20301 	 */
20302 	if (tcp->tcp_mdt &&
20303 	    (tcp->tcp_ipversion == IPV4_VERSION &&
20304 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
20305 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20306 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
20307 		tcp->tcp_mdt = B_FALSE;
20308 
20309 	if (tcp->tcp_mdt) {
20310 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
20311 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
20312 			    "version (%d), expected version is %d",
20313 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
20314 			tcp->tcp_mdt = B_FALSE;
20315 			return;
20316 		}
20317 
20318 		/*
20319 		 * We need the driver to be able to handle at least three
20320 		 * spans per packet in order for tcp MDT to be utilized.
20321 		 * The first is for the header portion, while the rest are
20322 		 * needed to handle a packet that straddles across two
20323 		 * virtually non-contiguous buffers; a typical tcp packet
20324 		 * therefore consists of only two spans.  Note that we take
20325 		 * a zero as "don't care".
20326 		 */
20327 		if (mdt_capab->ill_mdt_span_limit > 0 &&
20328 		    mdt_capab->ill_mdt_span_limit < 3) {
20329 			tcp->tcp_mdt = B_FALSE;
20330 			return;
20331 		}
20332 
20333 		/* a zero means driver wants default value */
20334 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
20335 		    tcp_mdt_max_pbufs);
20336 		if (tcp->tcp_mdt_max_pld == 0)
20337 			tcp->tcp_mdt_max_pld = tcp_mdt_max_pbufs;
20338 
20339 		/* ensure 32-bit alignment */
20340 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcp_mdt_hdr_head_min,
20341 		    mdt_capab->ill_mdt_hdr_head), 4);
20342 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcp_mdt_hdr_tail_min,
20343 		    mdt_capab->ill_mdt_hdr_tail), 4);
20344 
20345 		if (!first && !prev_state) {
20346 			TCP_STAT(tcp_mdt_conn_resumed2);
20347 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
20348 			    (void *)tcp->tcp_connp));
20349 		}
20350 	}
20351 }
20352 
20353 static void
20354 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_mdt)
20355 {
20356 	conn_t *connp = tcp->tcp_connp;
20357 
20358 	ASSERT(ire != NULL);
20359 
20360 	/*
20361 	 * We may be in the fastpath here, and although we essentially do
20362 	 * similar checks as in ip_bind_connected{_v6}/ip_mdinfo_return,
20363 	 * we try to keep things as brief as possible.  After all, these
20364 	 * are only best-effort checks, and we do more thorough ones prior
20365 	 * to calling tcp_multisend().
20366 	 */
20367 	if (ip_multidata_outbound && check_mdt &&
20368 	    !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
20369 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
20370 	    !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
20371 	    !(ire->ire_flags & RTF_MULTIRT) &&
20372 	    !IPP_ENABLED(IPP_LOCAL_OUT) &&
20373 	    CONN_IS_MD_FASTPATH(connp)) {
20374 		/* Remember the result */
20375 		connp->conn_mdt_ok = B_TRUE;
20376 
20377 		ASSERT(ill->ill_mdt_capab != NULL);
20378 		if (!ill->ill_mdt_capab->ill_mdt_on) {
20379 			/*
20380 			 * If MDT has been previously turned off in the past,
20381 			 * and we currently can do MDT (due to IPQoS policy
20382 			 * removal, etc.) then enable it for this interface.
20383 			 */
20384 			ill->ill_mdt_capab->ill_mdt_on = 1;
20385 			ip1dbg(("tcp_ire_ill_check: connp %p enables MDT for "
20386 			    "interface %s\n", (void *)connp, ill->ill_name));
20387 		}
20388 		tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
20389 	}
20390 
20391 	/*
20392 	 * The goal is to reduce the number of generated tcp segments by
20393 	 * setting the maxpsz multiplier to 0; this will have an affect on
20394 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
20395 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
20396 	 * of outbound segments and incoming ACKs, thus allowing for better
20397 	 * network and system performance.  In contrast the legacy behavior
20398 	 * may result in sending less than SMSS size, because the last mblk
20399 	 * for some packets may have more data than needed to make up SMSS,
20400 	 * and the legacy code refused to "split" it.
20401 	 *
20402 	 * We apply the new behavior on following situations:
20403 	 *
20404 	 *   1) Loopback connections,
20405 	 *   2) Connections in which the remote peer is not on local subnet,
20406 	 *   3) Local subnet connections over the bge interface (see below).
20407 	 *
20408 	 * Ideally, we would like this behavior to apply for interfaces other
20409 	 * than bge.  However, doing so would negatively impact drivers which
20410 	 * perform dynamic mapping and unmapping of DMA resources, which are
20411 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
20412 	 * packet will be generated by tcp).  The bge driver does not suffer
20413 	 * from this, as it copies the mblks into pre-mapped buffers, and
20414 	 * therefore does not require more I/O resources than before.
20415 	 *
20416 	 * Otherwise, this behavior is present on all network interfaces when
20417 	 * the destination endpoint is non-local, since reducing the number
20418 	 * of packets in general is good for the network.
20419 	 *
20420 	 * TODO We need to remove this hard-coded conditional for bge once
20421 	 *	a better "self-tuning" mechanism, or a way to comprehend
20422 	 *	the driver transmit strategy is devised.  Until the solution
20423 	 *	is found and well understood, we live with this hack.
20424 	 */
20425 	if (!tcp_static_maxpsz &&
20426 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
20427 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
20428 		/* override the default value */
20429 		tcp->tcp_maxpsz = 0;
20430 
20431 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
20432 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
20433 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
20434 	}
20435 
20436 	/* set the stream head parameters accordingly */
20437 	(void) tcp_maxpsz_set(tcp, B_TRUE);
20438 }
20439 
20440 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
20441 static void
20442 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
20443 {
20444 	uchar_t	fval = *mp->b_rptr;
20445 	mblk_t	*tail;
20446 	queue_t	*q = tcp->tcp_wq;
20447 
20448 	/* TODO: How should flush interact with urgent data? */
20449 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
20450 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
20451 		/*
20452 		 * Flush only data that has not yet been put on the wire.  If
20453 		 * we flush data that we have already transmitted, life, as we
20454 		 * know it, may come to an end.
20455 		 */
20456 		tail = tcp->tcp_xmit_tail;
20457 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
20458 		tcp->tcp_xmit_tail_unsent = 0;
20459 		tcp->tcp_unsent = 0;
20460 		if (tail->b_wptr != tail->b_rptr)
20461 			tail = tail->b_cont;
20462 		if (tail) {
20463 			mblk_t **excess = &tcp->tcp_xmit_head;
20464 			for (;;) {
20465 				mblk_t *mp1 = *excess;
20466 				if (mp1 == tail)
20467 					break;
20468 				tcp->tcp_xmit_tail = mp1;
20469 				tcp->tcp_xmit_last = mp1;
20470 				excess = &mp1->b_cont;
20471 			}
20472 			*excess = NULL;
20473 			tcp_close_mpp(&tail);
20474 			if (tcp->tcp_snd_zcopy_aware)
20475 				tcp_zcopy_notify(tcp);
20476 		}
20477 		/*
20478 		 * We have no unsent data, so unsent must be less than
20479 		 * tcp_xmit_lowater, so re-enable flow.
20480 		 */
20481 		if (tcp->tcp_flow_stopped) {
20482 			tcp_clrqfull(tcp);
20483 		}
20484 	}
20485 	/*
20486 	 * TODO: you can't just flush these, you have to increase rwnd for one
20487 	 * thing.  For another, how should urgent data interact?
20488 	 */
20489 	if (fval & FLUSHR) {
20490 		*mp->b_rptr = fval & ~FLUSHW;
20491 		/* XXX */
20492 		qreply(q, mp);
20493 		return;
20494 	}
20495 	freemsg(mp);
20496 }
20497 
20498 /*
20499  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
20500  * messages.
20501  */
20502 static void
20503 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
20504 {
20505 	mblk_t	*mp1;
20506 	STRUCT_HANDLE(strbuf, sb);
20507 	uint16_t port;
20508 	queue_t 	*q = tcp->tcp_wq;
20509 	in6_addr_t	v6addr;
20510 	ipaddr_t	v4addr;
20511 	uint32_t	flowinfo = 0;
20512 	int		addrlen;
20513 
20514 	/* Make sure it is one of ours. */
20515 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20516 	case TI_GETMYNAME:
20517 	case TI_GETPEERNAME:
20518 		break;
20519 	default:
20520 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
20521 		return;
20522 	}
20523 	switch (mi_copy_state(q, mp, &mp1)) {
20524 	case -1:
20525 		return;
20526 	case MI_COPY_CASE(MI_COPY_IN, 1):
20527 		break;
20528 	case MI_COPY_CASE(MI_COPY_OUT, 1):
20529 		/* Copy out the strbuf. */
20530 		mi_copyout(q, mp);
20531 		return;
20532 	case MI_COPY_CASE(MI_COPY_OUT, 2):
20533 		/* All done. */
20534 		mi_copy_done(q, mp, 0);
20535 		return;
20536 	default:
20537 		mi_copy_done(q, mp, EPROTO);
20538 		return;
20539 	}
20540 	/* Check alignment of the strbuf */
20541 	if (!OK_32PTR(mp1->b_rptr)) {
20542 		mi_copy_done(q, mp, EINVAL);
20543 		return;
20544 	}
20545 
20546 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
20547 	    (void *)mp1->b_rptr);
20548 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
20549 
20550 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
20551 		mi_copy_done(q, mp, EINVAL);
20552 		return;
20553 	}
20554 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
20555 	case TI_GETMYNAME:
20556 		if (tcp->tcp_family == AF_INET) {
20557 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20558 				v4addr = tcp->tcp_ipha->ipha_src;
20559 			} else {
20560 				/* can't return an address in this case */
20561 				v4addr = 0;
20562 			}
20563 		} else {
20564 			/* tcp->tcp_family == AF_INET6 */
20565 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20566 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
20567 				    &v6addr);
20568 			} else {
20569 				v6addr = tcp->tcp_ip6h->ip6_src;
20570 			}
20571 		}
20572 		port = tcp->tcp_lport;
20573 		break;
20574 	case TI_GETPEERNAME:
20575 		if (tcp->tcp_family == AF_INET) {
20576 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20577 				IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
20578 				    v4addr);
20579 			} else {
20580 				/* can't return an address in this case */
20581 				v4addr = 0;
20582 			}
20583 		} else {
20584 			/* tcp->tcp_family == AF_INET6) */
20585 			v6addr = tcp->tcp_remote_v6;
20586 			if (tcp->tcp_ipversion == IPV6_VERSION) {
20587 				/*
20588 				 * No flowinfo if tcp->tcp_ipversion is v4.
20589 				 *
20590 				 * flowinfo was already initialized to zero
20591 				 * where it was declared above, so only
20592 				 * set it if ipversion is v6.
20593 				 */
20594 				flowinfo = tcp->tcp_ip6h->ip6_vcf &
20595 				    ~IPV6_VERS_AND_FLOW_MASK;
20596 			}
20597 		}
20598 		port = tcp->tcp_fport;
20599 		break;
20600 	default:
20601 		mi_copy_done(q, mp, EPROTO);
20602 		return;
20603 	}
20604 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
20605 	if (!mp1)
20606 		return;
20607 
20608 	if (tcp->tcp_family == AF_INET) {
20609 		sin_t *sin;
20610 
20611 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
20612 		sin = (sin_t *)mp1->b_rptr;
20613 		mp1->b_wptr = (uchar_t *)&sin[1];
20614 		*sin = sin_null;
20615 		sin->sin_family = AF_INET;
20616 		sin->sin_addr.s_addr = v4addr;
20617 		sin->sin_port = port;
20618 	} else {
20619 		/* tcp->tcp_family == AF_INET6 */
20620 		sin6_t *sin6;
20621 
20622 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
20623 		sin6 = (sin6_t *)mp1->b_rptr;
20624 		mp1->b_wptr = (uchar_t *)&sin6[1];
20625 		*sin6 = sin6_null;
20626 		sin6->sin6_family = AF_INET6;
20627 		sin6->sin6_flowinfo = flowinfo;
20628 		sin6->sin6_addr = v6addr;
20629 		sin6->sin6_port = port;
20630 	}
20631 	/* Copy out the address */
20632 	mi_copyout(q, mp);
20633 }
20634 
20635 /*
20636  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
20637  * messages.
20638  */
20639 /* ARGSUSED */
20640 static void
20641 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
20642 {
20643 	conn_t 	*connp = (conn_t *)arg;
20644 	tcp_t	*tcp = connp->conn_tcp;
20645 	queue_t	*q = tcp->tcp_wq;
20646 	struct iocblk	*iocp;
20647 
20648 	ASSERT(DB_TYPE(mp) == M_IOCTL);
20649 	/*
20650 	 * Try and ASSERT the minimum possible references on the
20651 	 * conn early enough. Since we are executing on write side,
20652 	 * the connection is obviously not detached and that means
20653 	 * there is a ref each for TCP and IP. Since we are behind
20654 	 * the squeue, the minimum references needed are 3. If the
20655 	 * conn is in classifier hash list, there should be an
20656 	 * extra ref for that (we check both the possibilities).
20657 	 */
20658 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20659 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20660 
20661 	iocp = (struct iocblk *)mp->b_rptr;
20662 	switch (iocp->ioc_cmd) {
20663 	case TCP_IOC_DEFAULT_Q:
20664 		/* Wants to be the default wq. */
20665 		if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
20666 			iocp->ioc_error = EPERM;
20667 			iocp->ioc_count = 0;
20668 			mp->b_datap->db_type = M_IOCACK;
20669 			qreply(q, mp);
20670 			return;
20671 		}
20672 		tcp_def_q_set(tcp, mp);
20673 		return;
20674 	case _SIOCSOCKFALLBACK:
20675 		/*
20676 		 * Either sockmod is about to be popped and the socket
20677 		 * would now be treated as a plain stream, or a module
20678 		 * is about to be pushed so we could no longer use read-
20679 		 * side synchronous streams for fused loopback tcp.
20680 		 * Drain any queued data and disable direct sockfs
20681 		 * interface from now on.
20682 		 */
20683 		if (!tcp->tcp_issocket) {
20684 			DB_TYPE(mp) = M_IOCNAK;
20685 			iocp->ioc_error = EINVAL;
20686 		} else {
20687 #ifdef	_ILP32
20688 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
20689 #else
20690 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
20691 #endif
20692 			/*
20693 			 * Insert this socket into the acceptor hash.
20694 			 * We might need it for T_CONN_RES message
20695 			 */
20696 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
20697 
20698 			if (tcp->tcp_fused) {
20699 				/*
20700 				 * This is a fused loopback tcp; disable
20701 				 * read-side synchronous streams interface
20702 				 * and drain any queued data.  It is okay
20703 				 * to do this for non-synchronous streams
20704 				 * fused tcp as well.
20705 				 */
20706 				tcp_fuse_disable_pair(tcp, B_FALSE);
20707 			}
20708 			tcp->tcp_issocket = B_FALSE;
20709 			TCP_STAT(tcp_sock_fallback);
20710 
20711 			DB_TYPE(mp) = M_IOCACK;
20712 			iocp->ioc_error = 0;
20713 		}
20714 		iocp->ioc_count = 0;
20715 		iocp->ioc_rval = 0;
20716 		qreply(q, mp);
20717 		return;
20718 	}
20719 	CALL_IP_WPUT(connp, q, mp);
20720 }
20721 
20722 /*
20723  * This routine is called by tcp_wput() to handle all TPI requests.
20724  */
20725 /* ARGSUSED */
20726 static void
20727 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
20728 {
20729 	conn_t 	*connp = (conn_t *)arg;
20730 	tcp_t	*tcp = connp->conn_tcp;
20731 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
20732 	uchar_t *rptr;
20733 	t_scalar_t type;
20734 	int len;
20735 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
20736 
20737 	/*
20738 	 * Try and ASSERT the minimum possible references on the
20739 	 * conn early enough. Since we are executing on write side,
20740 	 * the connection is obviously not detached and that means
20741 	 * there is a ref each for TCP and IP. Since we are behind
20742 	 * the squeue, the minimum references needed are 3. If the
20743 	 * conn is in classifier hash list, there should be an
20744 	 * extra ref for that (we check both the possibilities).
20745 	 */
20746 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
20747 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
20748 
20749 	rptr = mp->b_rptr;
20750 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
20751 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
20752 		type = ((union T_primitives *)rptr)->type;
20753 		if (type == T_EXDATA_REQ) {
20754 			uint32_t msize = msgdsize(mp->b_cont);
20755 
20756 			len = msize - 1;
20757 			if (len < 0) {
20758 				freemsg(mp);
20759 				return;
20760 			}
20761 			/*
20762 			 * Try to force urgent data out on the wire.
20763 			 * Even if we have unsent data this will
20764 			 * at least send the urgent flag.
20765 			 * XXX does not handle more flag correctly.
20766 			 */
20767 			len += tcp->tcp_unsent;
20768 			len += tcp->tcp_snxt;
20769 			tcp->tcp_urg = len;
20770 			tcp->tcp_valid_bits |= TCP_URG_VALID;
20771 
20772 			/* Bypass tcp protocol for fused tcp loopback */
20773 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20774 				return;
20775 		} else if (type != T_DATA_REQ) {
20776 			goto non_urgent_data;
20777 		}
20778 		/* TODO: options, flags, ... from user */
20779 		/* Set length to zero for reclamation below */
20780 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
20781 		freeb(mp);
20782 		return;
20783 	} else {
20784 		if (tcp->tcp_debug) {
20785 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20786 			    "tcp_wput_proto, dropping one...");
20787 		}
20788 		freemsg(mp);
20789 		return;
20790 	}
20791 
20792 non_urgent_data:
20793 
20794 	switch ((int)tprim->type) {
20795 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
20796 		/*
20797 		 * save the kssl_ent_t from the next block, and convert this
20798 		 * back to a normal bind_req.
20799 		 */
20800 		if (mp->b_cont != NULL) {
20801 		    ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
20802 
20803 			if (tcp->tcp_kssl_ent != NULL) {
20804 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
20805 				    KSSL_NO_PROXY);
20806 				tcp->tcp_kssl_ent = NULL;
20807 			}
20808 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
20809 			    sizeof (kssl_ent_t));
20810 			kssl_hold_ent(tcp->tcp_kssl_ent);
20811 			freemsg(mp->b_cont);
20812 			mp->b_cont = NULL;
20813 		}
20814 		tprim->type = T_BIND_REQ;
20815 
20816 	/* FALLTHROUGH */
20817 	case O_T_BIND_REQ:	/* bind request */
20818 	case T_BIND_REQ:	/* new semantics bind request */
20819 		tcp_bind(tcp, mp);
20820 		break;
20821 	case T_UNBIND_REQ:	/* unbind request */
20822 		tcp_unbind(tcp, mp);
20823 		break;
20824 	case O_T_CONN_RES:	/* old connection response XXX */
20825 	case T_CONN_RES:	/* connection response */
20826 		tcp_accept(tcp, mp);
20827 		break;
20828 	case T_CONN_REQ:	/* connection request */
20829 		tcp_connect(tcp, mp);
20830 		break;
20831 	case T_DISCON_REQ:	/* disconnect request */
20832 		tcp_disconnect(tcp, mp);
20833 		break;
20834 	case T_CAPABILITY_REQ:
20835 		tcp_capability_req(tcp, mp);	/* capability request */
20836 		break;
20837 	case T_INFO_REQ:	/* information request */
20838 		tcp_info_req(tcp, mp);
20839 		break;
20840 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
20841 		/* Only IP is allowed to return meaningful value */
20842 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20843 		break;
20844 	case T_OPTMGMT_REQ:
20845 		/*
20846 		 * Note:  no support for snmpcom_req() through new
20847 		 * T_OPTMGMT_REQ. See comments in ip.c
20848 		 */
20849 		/* Only IP is allowed to return meaningful value */
20850 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj);
20851 		break;
20852 
20853 	case T_UNITDATA_REQ:	/* unitdata request */
20854 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20855 		break;
20856 	case T_ORDREL_REQ:	/* orderly release req */
20857 		freemsg(mp);
20858 
20859 		if (tcp->tcp_fused)
20860 			tcp_unfuse(tcp);
20861 
20862 		if (tcp_xmit_end(tcp) != 0) {
20863 			/*
20864 			 * We were crossing FINs and got a reset from
20865 			 * the other side. Just ignore it.
20866 			 */
20867 			if (tcp->tcp_debug) {
20868 				(void) strlog(TCP_MOD_ID, 0, 1,
20869 				    SL_ERROR|SL_TRACE,
20870 				    "tcp_wput_proto, T_ORDREL_REQ out of "
20871 				    "state %s",
20872 				    tcp_display(tcp, NULL,
20873 				    DISP_ADDR_AND_PORT));
20874 			}
20875 		}
20876 		break;
20877 	case T_ADDR_REQ:
20878 		tcp_addr_req(tcp, mp);
20879 		break;
20880 	default:
20881 		if (tcp->tcp_debug) {
20882 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20883 			    "tcp_wput_proto, bogus TPI msg, type %d",
20884 			    tprim->type);
20885 		}
20886 		/*
20887 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
20888 		 * to recover.
20889 		 */
20890 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
20891 		break;
20892 	}
20893 }
20894 
20895 /*
20896  * The TCP write service routine should never be called...
20897  */
20898 /* ARGSUSED */
20899 static void
20900 tcp_wsrv(queue_t *q)
20901 {
20902 	TCP_STAT(tcp_wsrv_called);
20903 }
20904 
20905 /* Non overlapping byte exchanger */
20906 static void
20907 tcp_xchg(uchar_t *a, uchar_t *b, int len)
20908 {
20909 	uchar_t	uch;
20910 
20911 	while (len-- > 0) {
20912 		uch = a[len];
20913 		a[len] = b[len];
20914 		b[len] = uch;
20915 	}
20916 }
20917 
20918 /*
20919  * Send out a control packet on the tcp connection specified.  This routine
20920  * is typically called where we need a simple ACK or RST generated.
20921  */
20922 static void
20923 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
20924 {
20925 	uchar_t		*rptr;
20926 	tcph_t		*tcph;
20927 	ipha_t		*ipha = NULL;
20928 	ip6_t		*ip6h = NULL;
20929 	uint32_t	sum;
20930 	int		tcp_hdr_len;
20931 	int		tcp_ip_hdr_len;
20932 	mblk_t		*mp;
20933 
20934 	/*
20935 	 * Save sum for use in source route later.
20936 	 */
20937 	ASSERT(tcp != NULL);
20938 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
20939 	tcp_hdr_len = tcp->tcp_hdr_len;
20940 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
20941 
20942 	/* If a text string is passed in with the request, pass it to strlog. */
20943 	if (str != NULL && tcp->tcp_debug) {
20944 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
20945 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
20946 		    str, seq, ack, ctl);
20947 	}
20948 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
20949 	    BPRI_MED);
20950 	if (mp == NULL) {
20951 		return;
20952 	}
20953 	rptr = &mp->b_rptr[tcp_wroff_xtra];
20954 	mp->b_rptr = rptr;
20955 	mp->b_wptr = &rptr[tcp_hdr_len];
20956 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
20957 
20958 	if (tcp->tcp_ipversion == IPV4_VERSION) {
20959 		ipha = (ipha_t *)rptr;
20960 		ipha->ipha_length = htons(tcp_hdr_len);
20961 	} else {
20962 		ip6h = (ip6_t *)rptr;
20963 		ASSERT(tcp != NULL);
20964 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
20965 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
20966 	}
20967 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
20968 	tcph->th_flags[0] = (uint8_t)ctl;
20969 	if (ctl & TH_RST) {
20970 		BUMP_MIB(&tcp_mib, tcpOutRsts);
20971 		BUMP_MIB(&tcp_mib, tcpOutControl);
20972 		/*
20973 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
20974 		 */
20975 		if (tcp->tcp_snd_ts_ok &&
20976 		    tcp->tcp_state > TCPS_SYN_SENT) {
20977 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
20978 			*(mp->b_wptr) = TCPOPT_EOL;
20979 			if (tcp->tcp_ipversion == IPV4_VERSION) {
20980 				ipha->ipha_length = htons(tcp_hdr_len -
20981 				    TCPOPT_REAL_TS_LEN);
20982 			} else {
20983 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
20984 				    TCPOPT_REAL_TS_LEN);
20985 			}
20986 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
20987 			sum -= TCPOPT_REAL_TS_LEN;
20988 		}
20989 	}
20990 	if (ctl & TH_ACK) {
20991 		if (tcp->tcp_snd_ts_ok) {
20992 			U32_TO_BE32(lbolt,
20993 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
20994 			U32_TO_BE32(tcp->tcp_ts_recent,
20995 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
20996 		}
20997 
20998 		/* Update the latest receive window size in TCP header. */
20999 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21000 		    tcph->th_win);
21001 		tcp->tcp_rack = ack;
21002 		tcp->tcp_rack_cnt = 0;
21003 		BUMP_MIB(&tcp_mib, tcpOutAck);
21004 	}
21005 	BUMP_LOCAL(tcp->tcp_obsegs);
21006 	U32_TO_BE32(seq, tcph->th_seq);
21007 	U32_TO_BE32(ack, tcph->th_ack);
21008 	/*
21009 	 * Include the adjustment for a source route if any.
21010 	 */
21011 	sum = (sum >> 16) + (sum & 0xFFFF);
21012 	U16_TO_BE16(sum, tcph->th_sum);
21013 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21014 	tcp_send_data(tcp, tcp->tcp_wq, mp);
21015 }
21016 
21017 /*
21018  * If this routine returns B_TRUE, TCP can generate a RST in response
21019  * to a segment.  If it returns B_FALSE, TCP should not respond.
21020  */
21021 static boolean_t
21022 tcp_send_rst_chk(void)
21023 {
21024 	clock_t	now;
21025 
21026 	/*
21027 	 * TCP needs to protect itself from generating too many RSTs.
21028 	 * This can be a DoS attack by sending us random segments
21029 	 * soliciting RSTs.
21030 	 *
21031 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
21032 	 * in each 1 second interval.  In this way, TCP still generate
21033 	 * RSTs in normal cases but when under attack, the impact is
21034 	 * limited.
21035 	 */
21036 	if (tcp_rst_sent_rate_enabled != 0) {
21037 		now = lbolt;
21038 		/* lbolt can wrap around. */
21039 		if ((tcp_last_rst_intrvl > now) ||
21040 		    (TICK_TO_MSEC(now - tcp_last_rst_intrvl) > 1*SECONDS)) {
21041 			tcp_last_rst_intrvl = now;
21042 			tcp_rst_cnt = 1;
21043 		} else if (++tcp_rst_cnt > tcp_rst_sent_rate) {
21044 			return (B_FALSE);
21045 		}
21046 	}
21047 	return (B_TRUE);
21048 }
21049 
21050 /*
21051  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
21052  */
21053 static void
21054 tcp_ip_ire_mark_advice(tcp_t *tcp)
21055 {
21056 	mblk_t *mp;
21057 	ipic_t *ipic;
21058 
21059 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21060 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21061 		    &ipic);
21062 	} else {
21063 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21064 		    &ipic);
21065 	}
21066 	if (mp == NULL)
21067 		return;
21068 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21069 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21070 }
21071 
21072 /*
21073  * Return an IP advice ioctl mblk and set ipic to be the pointer
21074  * to the advice structure.
21075  */
21076 static mblk_t *
21077 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
21078 {
21079 	struct iocblk *ioc;
21080 	mblk_t *mp, *mp1;
21081 
21082 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
21083 	if (mp == NULL)
21084 		return (NULL);
21085 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
21086 	*ipic = (ipic_t *)mp->b_rptr;
21087 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
21088 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
21089 
21090 	bcopy(addr, *ipic + 1, addr_len);
21091 
21092 	(*ipic)->ipic_addr_length = addr_len;
21093 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
21094 
21095 	mp1 = mkiocb(IP_IOCTL);
21096 	if (mp1 == NULL) {
21097 		freemsg(mp);
21098 		return (NULL);
21099 	}
21100 	mp1->b_cont = mp;
21101 	ioc = (struct iocblk *)mp1->b_rptr;
21102 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
21103 
21104 	return (mp1);
21105 }
21106 
21107 /*
21108  * Generate a reset based on an inbound packet for which there is no active
21109  * tcp state that we can find.
21110  *
21111  * IPSEC NOTE : Try to send the reply with the same protection as it came
21112  * in.  We still have the ipsec_mp that the packet was attached to. Thus
21113  * the packet will go out at the same level of protection as it came in by
21114  * converting the IPSEC_IN to IPSEC_OUT.
21115  */
21116 static void
21117 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
21118     uint32_t ack, int ctl, uint_t ip_hdr_len)
21119 {
21120 	ipha_t		*ipha = NULL;
21121 	ip6_t		*ip6h = NULL;
21122 	ushort_t	len;
21123 	tcph_t		*tcph;
21124 	int		i;
21125 	mblk_t		*ipsec_mp;
21126 	boolean_t	mctl_present;
21127 	ipic_t		*ipic;
21128 	ipaddr_t	v4addr;
21129 	in6_addr_t	v6addr;
21130 	int		addr_len;
21131 	void		*addr;
21132 	queue_t		*q = tcp_g_q;
21133 	tcp_t		*tcp = Q_TO_TCP(q);
21134 
21135 	if (!tcp_send_rst_chk()) {
21136 		tcp_rst_unsent++;
21137 		freemsg(mp);
21138 		return;
21139 	}
21140 
21141 	if (mp->b_datap->db_type == M_CTL) {
21142 		ipsec_mp = mp;
21143 		mp = mp->b_cont;
21144 		mctl_present = B_TRUE;
21145 	} else {
21146 		ipsec_mp = mp;
21147 		mctl_present = B_FALSE;
21148 	}
21149 
21150 	if (str && q && tcp_dbg) {
21151 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
21152 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
21153 		    "flags 0x%x",
21154 		    str, seq, ack, ctl);
21155 	}
21156 	if (mp->b_datap->db_ref != 1) {
21157 		mblk_t *mp1 = copyb(mp);
21158 		freemsg(mp);
21159 		mp = mp1;
21160 		if (!mp) {
21161 			if (mctl_present)
21162 				freeb(ipsec_mp);
21163 			return;
21164 		} else {
21165 			if (mctl_present) {
21166 				ipsec_mp->b_cont = mp;
21167 			} else {
21168 				ipsec_mp = mp;
21169 			}
21170 		}
21171 	} else if (mp->b_cont) {
21172 		freemsg(mp->b_cont);
21173 		mp->b_cont = NULL;
21174 	}
21175 	/*
21176 	 * We skip reversing source route here.
21177 	 * (for now we replace all IP options with EOL)
21178 	 */
21179 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21180 		ipha = (ipha_t *)mp->b_rptr;
21181 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
21182 			mp->b_rptr[i] = IPOPT_EOL;
21183 		/*
21184 		 * Make sure that src address isn't flagrantly invalid.
21185 		 * Not all broadcast address checking for the src address
21186 		 * is possible, since we don't know the netmask of the src
21187 		 * addr.  No check for destination address is done, since
21188 		 * IP will not pass up a packet with a broadcast dest
21189 		 * address to TCP.  Similar checks are done below for IPv6.
21190 		 */
21191 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
21192 		    CLASSD(ipha->ipha_src)) {
21193 			freemsg(ipsec_mp);
21194 			BUMP_MIB(&ip_mib, ipInDiscards);
21195 			return;
21196 		}
21197 	} else {
21198 		ip6h = (ip6_t *)mp->b_rptr;
21199 
21200 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
21201 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
21202 			freemsg(ipsec_mp);
21203 			BUMP_MIB(&ip6_mib, ipv6InDiscards);
21204 			return;
21205 		}
21206 
21207 		/* Remove any extension headers assuming partial overlay */
21208 		if (ip_hdr_len > IPV6_HDR_LEN) {
21209 			uint8_t *to;
21210 
21211 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
21212 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
21213 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
21214 			ip_hdr_len = IPV6_HDR_LEN;
21215 			ip6h = (ip6_t *)mp->b_rptr;
21216 			ip6h->ip6_nxt = IPPROTO_TCP;
21217 		}
21218 	}
21219 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
21220 	if (tcph->th_flags[0] & TH_RST) {
21221 		freemsg(ipsec_mp);
21222 		return;
21223 	}
21224 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
21225 	len = ip_hdr_len + sizeof (tcph_t);
21226 	mp->b_wptr = &mp->b_rptr[len];
21227 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21228 		ipha->ipha_length = htons(len);
21229 		/* Swap addresses */
21230 		v4addr = ipha->ipha_src;
21231 		ipha->ipha_src = ipha->ipha_dst;
21232 		ipha->ipha_dst = v4addr;
21233 		ipha->ipha_ident = 0;
21234 		ipha->ipha_ttl = (uchar_t)tcp_ipv4_ttl;
21235 		addr_len = IP_ADDR_LEN;
21236 		addr = &v4addr;
21237 	} else {
21238 		/* No ip6i_t in this case */
21239 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
21240 		/* Swap addresses */
21241 		v6addr = ip6h->ip6_src;
21242 		ip6h->ip6_src = ip6h->ip6_dst;
21243 		ip6h->ip6_dst = v6addr;
21244 		ip6h->ip6_hops = (uchar_t)tcp_ipv6_hoplimit;
21245 		addr_len = IPV6_ADDR_LEN;
21246 		addr = &v6addr;
21247 	}
21248 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
21249 	U32_TO_BE32(ack, tcph->th_ack);
21250 	U32_TO_BE32(seq, tcph->th_seq);
21251 	U16_TO_BE16(0, tcph->th_win);
21252 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
21253 	tcph->th_flags[0] = (uint8_t)ctl;
21254 	if (ctl & TH_RST) {
21255 		BUMP_MIB(&tcp_mib, tcpOutRsts);
21256 		BUMP_MIB(&tcp_mib, tcpOutControl);
21257 	}
21258 	if (mctl_present) {
21259 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21260 
21261 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21262 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
21263 			return;
21264 		}
21265 	}
21266 	/*
21267 	 * NOTE:  one might consider tracing a TCP packet here, but
21268 	 * this function has no active TCP state nd no tcp structure
21269 	 * which has trace buffer.  If we traced here, we would have
21270 	 * to keep a local trace buffer in tcp_record_trace().
21271 	 */
21272 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
21273 
21274 	/*
21275 	 * Tell IP to mark the IRE used for this destination temporary.
21276 	 * This way, we can limit our exposure to DoS attack because IP
21277 	 * creates an IRE for each destination.  If there are too many,
21278 	 * the time to do any routing lookup will be extremely long.  And
21279 	 * the lookup can be in interrupt context.
21280 	 *
21281 	 * Note that in normal circumstances, this marking should not
21282 	 * affect anything.  It would be nice if only 1 message is
21283 	 * needed to inform IP that the IRE created for this RST should
21284 	 * not be added to the cache table.  But there is currently
21285 	 * not such communication mechanism between TCP and IP.  So
21286 	 * the best we can do now is to send the advice ioctl to IP
21287 	 * to mark the IRE temporary.
21288 	 */
21289 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
21290 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
21291 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21292 	}
21293 }
21294 
21295 /*
21296  * Initiate closedown sequence on an active connection.  (May be called as
21297  * writer.)  Return value zero for OK return, non-zero for error return.
21298  */
21299 static int
21300 tcp_xmit_end(tcp_t *tcp)
21301 {
21302 	ipic_t	*ipic;
21303 	mblk_t	*mp;
21304 
21305 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
21306 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
21307 		/*
21308 		 * Invalid state, only states TCPS_SYN_RCVD,
21309 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
21310 		 */
21311 		return (-1);
21312 	}
21313 
21314 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
21315 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
21316 	/*
21317 	 * If there is nothing more unsent, send the FIN now.
21318 	 * Otherwise, it will go out with the last segment.
21319 	 */
21320 	if (tcp->tcp_unsent == 0) {
21321 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21322 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
21323 
21324 		if (mp) {
21325 			TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21326 			tcp_send_data(tcp, tcp->tcp_wq, mp);
21327 		} else {
21328 			/*
21329 			 * Couldn't allocate msg.  Pretend we got it out.
21330 			 * Wait for rexmit timeout.
21331 			 */
21332 			tcp->tcp_snxt = tcp->tcp_fss + 1;
21333 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21334 		}
21335 
21336 		/*
21337 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
21338 		 * changed.
21339 		 */
21340 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
21341 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
21342 		}
21343 	} else {
21344 		/*
21345 		 * If tcp->tcp_cork is set, then the data will not get sent,
21346 		 * so we have to check that and unset it first.
21347 		 */
21348 		if (tcp->tcp_cork)
21349 			tcp->tcp_cork = B_FALSE;
21350 		tcp_wput_data(tcp, NULL, B_FALSE);
21351 	}
21352 
21353 	/*
21354 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
21355 	 * is 0, don't update the cache.
21356 	 */
21357 	if (tcp_rtt_updates == 0 || tcp->tcp_rtt_update < tcp_rtt_updates)
21358 		return (0);
21359 
21360 	/*
21361 	 * NOTE: should not update if source routes i.e. if tcp_remote if
21362 	 * different from the destination.
21363 	 */
21364 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21365 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
21366 			return (0);
21367 		}
21368 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
21369 		    &ipic);
21370 	} else {
21371 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
21372 		    &tcp->tcp_ip6h->ip6_dst))) {
21373 			return (0);
21374 		}
21375 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
21376 		    &ipic);
21377 	}
21378 
21379 	/* Record route attributes in the IRE for use by future connections. */
21380 	if (mp == NULL)
21381 		return (0);
21382 
21383 	/*
21384 	 * We do not have a good algorithm to update ssthresh at this time.
21385 	 * So don't do any update.
21386 	 */
21387 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
21388 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
21389 
21390 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
21391 	return (0);
21392 }
21393 
21394 /*
21395  * Generate a "no listener here" RST in response to an "unknown" segment.
21396  * Note that we are reusing the incoming mp to construct the outgoing
21397  * RST.
21398  */
21399 void
21400 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len)
21401 {
21402 	uchar_t		*rptr;
21403 	uint32_t	seg_len;
21404 	tcph_t		*tcph;
21405 	uint32_t	seg_seq;
21406 	uint32_t	seg_ack;
21407 	uint_t		flags;
21408 	mblk_t		*ipsec_mp;
21409 	ipha_t 		*ipha;
21410 	ip6_t 		*ip6h;
21411 	boolean_t	mctl_present = B_FALSE;
21412 	boolean_t	check = B_TRUE;
21413 	boolean_t	policy_present;
21414 
21415 	TCP_STAT(tcp_no_listener);
21416 
21417 	ipsec_mp = mp;
21418 
21419 	if (mp->b_datap->db_type == M_CTL) {
21420 		ipsec_in_t *ii;
21421 
21422 		mctl_present = B_TRUE;
21423 		mp = mp->b_cont;
21424 
21425 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21426 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
21427 		if (ii->ipsec_in_dont_check) {
21428 			check = B_FALSE;
21429 			if (!ii->ipsec_in_secure) {
21430 				freeb(ipsec_mp);
21431 				mctl_present = B_FALSE;
21432 				ipsec_mp = mp;
21433 			}
21434 		}
21435 	}
21436 
21437 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
21438 		policy_present = ipsec_inbound_v4_policy_present;
21439 		ipha = (ipha_t *)mp->b_rptr;
21440 		ip6h = NULL;
21441 	} else {
21442 		policy_present = ipsec_inbound_v6_policy_present;
21443 		ipha = NULL;
21444 		ip6h = (ip6_t *)mp->b_rptr;
21445 	}
21446 
21447 	if (check && policy_present) {
21448 		/*
21449 		 * The conn_t parameter is NULL because we already know
21450 		 * nobody's home.
21451 		 */
21452 		ipsec_mp = ipsec_check_global_policy(
21453 			ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present);
21454 		if (ipsec_mp == NULL)
21455 			return;
21456 	}
21457 
21458 
21459 	rptr = mp->b_rptr;
21460 
21461 	tcph = (tcph_t *)&rptr[ip_hdr_len];
21462 	seg_seq = BE32_TO_U32(tcph->th_seq);
21463 	seg_ack = BE32_TO_U32(tcph->th_ack);
21464 	flags = tcph->th_flags[0];
21465 
21466 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
21467 	if (flags & TH_RST) {
21468 		freemsg(ipsec_mp);
21469 	} else if (flags & TH_ACK) {
21470 		tcp_xmit_early_reset("no tcp, reset",
21471 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len);
21472 	} else {
21473 		if (flags & TH_SYN) {
21474 			seg_len++;
21475 		} else {
21476 			/*
21477 			 * Here we violate the RFC.  Note that a normal
21478 			 * TCP will never send a segment without the ACK
21479 			 * flag, except for RST or SYN segment.  This
21480 			 * segment is neither.  Just drop it on the
21481 			 * floor.
21482 			 */
21483 			freemsg(ipsec_mp);
21484 			tcp_rst_unsent++;
21485 			return;
21486 		}
21487 
21488 		tcp_xmit_early_reset("no tcp, reset/ack",
21489 		    ipsec_mp, 0, seg_seq + seg_len,
21490 		    TH_RST | TH_ACK, ip_hdr_len);
21491 	}
21492 }
21493 
21494 /*
21495  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
21496  * ip and tcp header ready to pass down to IP.  If the mp passed in is
21497  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
21498  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
21499  * otherwise it will dup partial mblks.)
21500  * Otherwise, an appropriate ACK packet will be generated.  This
21501  * routine is not usually called to send new data for the first time.  It
21502  * is mostly called out of the timer for retransmits, and to generate ACKs.
21503  *
21504  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
21505  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
21506  * of the original mblk chain will be returned in *offset and *end_mp.
21507  */
21508 static mblk_t *
21509 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
21510     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
21511     boolean_t rexmit)
21512 {
21513 	int	data_length;
21514 	int32_t	off = 0;
21515 	uint_t	flags;
21516 	mblk_t	*mp1;
21517 	mblk_t	*mp2;
21518 	uchar_t	*rptr;
21519 	tcph_t	*tcph;
21520 	int32_t	num_sack_blk = 0;
21521 	int32_t	sack_opt_len = 0;
21522 
21523 	/* Allocate for our maximum TCP header + link-level */
21524 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra,
21525 	    BPRI_MED);
21526 	if (!mp1)
21527 		return (NULL);
21528 	data_length = 0;
21529 
21530 	/*
21531 	 * Note that tcp_mss has been adjusted to take into account the
21532 	 * timestamp option if applicable.  Because SACK options do not
21533 	 * appear in every TCP segments and they are of variable lengths,
21534 	 * they cannot be included in tcp_mss.  Thus we need to calculate
21535 	 * the actual segment length when we need to send a segment which
21536 	 * includes SACK options.
21537 	 */
21538 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
21539 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
21540 		    tcp->tcp_num_sack_blk);
21541 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
21542 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
21543 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
21544 			max_to_send -= sack_opt_len;
21545 	}
21546 
21547 	if (offset != NULL) {
21548 		off = *offset;
21549 		/* We use offset as an indicator that end_mp is not NULL. */
21550 		*end_mp = NULL;
21551 	}
21552 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
21553 		/* This could be faster with cooperation from downstream */
21554 		if (mp2 != mp1 && !sendall &&
21555 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
21556 		    max_to_send)
21557 			/*
21558 			 * Don't send the next mblk since the whole mblk
21559 			 * does not fit.
21560 			 */
21561 			break;
21562 		mp2->b_cont = dupb(mp);
21563 		mp2 = mp2->b_cont;
21564 		if (!mp2) {
21565 			freemsg(mp1);
21566 			return (NULL);
21567 		}
21568 		mp2->b_rptr += off;
21569 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
21570 		    (uintptr_t)INT_MAX);
21571 
21572 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
21573 		if (data_length > max_to_send) {
21574 			mp2->b_wptr -= data_length - max_to_send;
21575 			data_length = max_to_send;
21576 			off = mp2->b_wptr - mp->b_rptr;
21577 			break;
21578 		} else {
21579 			off = 0;
21580 		}
21581 	}
21582 	if (offset != NULL) {
21583 		*offset = off;
21584 		*end_mp = mp;
21585 	}
21586 	if (seg_len != NULL) {
21587 		*seg_len = data_length;
21588 	}
21589 
21590 	/* Update the latest receive window size in TCP header. */
21591 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
21592 	    tcp->tcp_tcph->th_win);
21593 
21594 	rptr = mp1->b_rptr + tcp_wroff_xtra;
21595 	mp1->b_rptr = rptr;
21596 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
21597 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
21598 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
21599 	U32_TO_ABE32(seq, tcph->th_seq);
21600 
21601 	/*
21602 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
21603 	 * that this function was called from tcp_wput_data. Thus, when called
21604 	 * to retransmit data the setting of the PUSH bit may appear some
21605 	 * what random in that it might get set when it should not. This
21606 	 * should not pose any performance issues.
21607 	 */
21608 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
21609 	    tcp->tcp_unsent == data_length)) {
21610 		flags = TH_ACK | TH_PUSH;
21611 	} else {
21612 		flags = TH_ACK;
21613 	}
21614 
21615 	if (tcp->tcp_ecn_ok) {
21616 		if (tcp->tcp_ecn_echo_on)
21617 			flags |= TH_ECE;
21618 
21619 		/*
21620 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
21621 		 * There is no TCP flow control for non-data segments, and
21622 		 * only data segment is transmitted reliably.
21623 		 */
21624 		if (data_length > 0 && !rexmit) {
21625 			SET_ECT(tcp, rptr);
21626 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
21627 				flags |= TH_CWR;
21628 				tcp->tcp_ecn_cwr_sent = B_TRUE;
21629 			}
21630 		}
21631 	}
21632 
21633 	if (tcp->tcp_valid_bits) {
21634 		uint32_t u1;
21635 
21636 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
21637 		    seq == tcp->tcp_iss) {
21638 			uchar_t	*wptr;
21639 
21640 			/*
21641 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
21642 			 * TCP can only be in SYN-SENT, SYN-RCVD or
21643 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
21644 			 * our SYN is not ack'ed but the app closes this
21645 			 * TCP connection.
21646 			 */
21647 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
21648 			    tcp->tcp_state == TCPS_SYN_RCVD ||
21649 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
21650 
21651 			/*
21652 			 * Tack on the MSS option.  It is always needed
21653 			 * for both active and passive open.
21654 			 *
21655 			 * MSS option value should be interface MTU - MIN
21656 			 * TCP/IP header according to RFC 793 as it means
21657 			 * the maximum segment size TCP can receive.  But
21658 			 * to get around some broken middle boxes/end hosts
21659 			 * out there, we allow the option value to be the
21660 			 * same as the MSS option size on the peer side.
21661 			 * In this way, the other side will not send
21662 			 * anything larger than they can receive.
21663 			 *
21664 			 * Note that for SYN_SENT state, the ndd param
21665 			 * tcp_use_smss_as_mss_opt has no effect as we
21666 			 * don't know the peer's MSS option value. So
21667 			 * the only case we need to take care of is in
21668 			 * SYN_RCVD state, which is done later.
21669 			 */
21670 			wptr = mp1->b_wptr;
21671 			wptr[0] = TCPOPT_MAXSEG;
21672 			wptr[1] = TCPOPT_MAXSEG_LEN;
21673 			wptr += 2;
21674 			u1 = tcp->tcp_if_mtu -
21675 			    (tcp->tcp_ipversion == IPV4_VERSION ?
21676 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
21677 			    TCP_MIN_HEADER_LENGTH;
21678 			U16_TO_BE16(u1, wptr);
21679 			mp1->b_wptr = wptr + 2;
21680 			/* Update the offset to cover the additional word */
21681 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
21682 
21683 			/*
21684 			 * Note that the following way of filling in
21685 			 * TCP options are not optimal.  Some NOPs can
21686 			 * be saved.  But there is no need at this time
21687 			 * to optimize it.  When it is needed, we will
21688 			 * do it.
21689 			 */
21690 			switch (tcp->tcp_state) {
21691 			case TCPS_SYN_SENT:
21692 				flags = TH_SYN;
21693 
21694 				if (tcp->tcp_snd_ts_ok) {
21695 					uint32_t llbolt = (uint32_t)lbolt;
21696 
21697 					wptr = mp1->b_wptr;
21698 					wptr[0] = TCPOPT_NOP;
21699 					wptr[1] = TCPOPT_NOP;
21700 					wptr[2] = TCPOPT_TSTAMP;
21701 					wptr[3] = TCPOPT_TSTAMP_LEN;
21702 					wptr += 4;
21703 					U32_TO_BE32(llbolt, wptr);
21704 					wptr += 4;
21705 					ASSERT(tcp->tcp_ts_recent == 0);
21706 					U32_TO_BE32(0L, wptr);
21707 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
21708 					tcph->th_offset_and_rsrvd[0] +=
21709 					    (3 << 4);
21710 				}
21711 
21712 				/*
21713 				 * Set up all the bits to tell other side
21714 				 * we are ECN capable.
21715 				 */
21716 				if (tcp->tcp_ecn_ok) {
21717 					flags |= (TH_ECE | TH_CWR);
21718 				}
21719 				break;
21720 			case TCPS_SYN_RCVD:
21721 				flags |= TH_SYN;
21722 
21723 				/*
21724 				 * Reset the MSS option value to be SMSS
21725 				 * We should probably add back the bytes
21726 				 * for timestamp option and IPsec.  We
21727 				 * don't do that as this is a workaround
21728 				 * for broken middle boxes/end hosts, it
21729 				 * is better for us to be more cautious.
21730 				 * They may not take these things into
21731 				 * account in their SMSS calculation.  Thus
21732 				 * the peer's calculated SMSS may be smaller
21733 				 * than what it can be.  This should be OK.
21734 				 */
21735 				if (tcp_use_smss_as_mss_opt) {
21736 					u1 = tcp->tcp_mss;
21737 					U16_TO_BE16(u1, wptr);
21738 				}
21739 
21740 				/*
21741 				 * If the other side is ECN capable, reply
21742 				 * that we are also ECN capable.
21743 				 */
21744 				if (tcp->tcp_ecn_ok)
21745 					flags |= TH_ECE;
21746 				break;
21747 			default:
21748 				/*
21749 				 * The above ASSERT() makes sure that this
21750 				 * must be FIN-WAIT-1 state.  Our SYN has
21751 				 * not been ack'ed so retransmit it.
21752 				 */
21753 				flags |= TH_SYN;
21754 				break;
21755 			}
21756 
21757 			if (tcp->tcp_snd_ws_ok) {
21758 				wptr = mp1->b_wptr;
21759 				wptr[0] =  TCPOPT_NOP;
21760 				wptr[1] =  TCPOPT_WSCALE;
21761 				wptr[2] =  TCPOPT_WS_LEN;
21762 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
21763 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
21764 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21765 			}
21766 
21767 			if (tcp->tcp_snd_sack_ok) {
21768 				wptr = mp1->b_wptr;
21769 				wptr[0] = TCPOPT_NOP;
21770 				wptr[1] = TCPOPT_NOP;
21771 				wptr[2] = TCPOPT_SACK_PERMITTED;
21772 				wptr[3] = TCPOPT_SACK_OK_LEN;
21773 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
21774 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
21775 			}
21776 
21777 			/* allocb() of adequate mblk assures space */
21778 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
21779 			    (uintptr_t)INT_MAX);
21780 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
21781 			/*
21782 			 * Get IP set to checksum on our behalf
21783 			 * Include the adjustment for a source route if any.
21784 			 */
21785 			u1 += tcp->tcp_sum;
21786 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
21787 			U16_TO_BE16(u1, tcph->th_sum);
21788 			BUMP_MIB(&tcp_mib, tcpOutControl);
21789 		}
21790 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
21791 		    (seq + data_length) == tcp->tcp_fss) {
21792 			if (!tcp->tcp_fin_acked) {
21793 				flags |= TH_FIN;
21794 				BUMP_MIB(&tcp_mib, tcpOutControl);
21795 			}
21796 			if (!tcp->tcp_fin_sent) {
21797 				tcp->tcp_fin_sent = B_TRUE;
21798 				switch (tcp->tcp_state) {
21799 				case TCPS_SYN_RCVD:
21800 				case TCPS_ESTABLISHED:
21801 					tcp->tcp_state = TCPS_FIN_WAIT_1;
21802 					break;
21803 				case TCPS_CLOSE_WAIT:
21804 					tcp->tcp_state = TCPS_LAST_ACK;
21805 					break;
21806 				}
21807 				if (tcp->tcp_suna == tcp->tcp_snxt)
21808 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21809 				tcp->tcp_snxt = tcp->tcp_fss + 1;
21810 			}
21811 		}
21812 		/*
21813 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
21814 		 * is smaller than seq, u1 will become a very huge value.
21815 		 * So the comparison will fail.  Also note that tcp_urp
21816 		 * should be positive, see RFC 793 page 17.
21817 		 */
21818 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
21819 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
21820 		    u1 < (uint32_t)(64 * 1024)) {
21821 			flags |= TH_URG;
21822 			BUMP_MIB(&tcp_mib, tcpOutUrg);
21823 			U32_TO_ABE16(u1, tcph->th_urp);
21824 		}
21825 	}
21826 	tcph->th_flags[0] = (uchar_t)flags;
21827 	tcp->tcp_rack = tcp->tcp_rnxt;
21828 	tcp->tcp_rack_cnt = 0;
21829 
21830 	if (tcp->tcp_snd_ts_ok) {
21831 		if (tcp->tcp_state != TCPS_SYN_SENT) {
21832 			uint32_t llbolt = (uint32_t)lbolt;
21833 
21834 			U32_TO_BE32(llbolt,
21835 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
21836 			U32_TO_BE32(tcp->tcp_ts_recent,
21837 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
21838 		}
21839 	}
21840 
21841 	if (num_sack_blk > 0) {
21842 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
21843 		sack_blk_t *tmp;
21844 		int32_t	i;
21845 
21846 		wptr[0] = TCPOPT_NOP;
21847 		wptr[1] = TCPOPT_NOP;
21848 		wptr[2] = TCPOPT_SACK;
21849 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
21850 		    sizeof (sack_blk_t);
21851 		wptr += TCPOPT_REAL_SACK_LEN;
21852 
21853 		tmp = tcp->tcp_sack_list;
21854 		for (i = 0; i < num_sack_blk; i++) {
21855 			U32_TO_BE32(tmp[i].begin, wptr);
21856 			wptr += sizeof (tcp_seq);
21857 			U32_TO_BE32(tmp[i].end, wptr);
21858 			wptr += sizeof (tcp_seq);
21859 		}
21860 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
21861 	}
21862 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
21863 	data_length += (int)(mp1->b_wptr - rptr);
21864 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21865 		((ipha_t *)rptr)->ipha_length = htons(data_length);
21866 	} else {
21867 		ip6_t *ip6 = (ip6_t *)(rptr +
21868 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
21869 		    sizeof (ip6i_t) : 0));
21870 
21871 		ip6->ip6_plen = htons(data_length -
21872 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21873 	}
21874 
21875 	/*
21876 	 * Prime pump for IP
21877 	 * Include the adjustment for a source route if any.
21878 	 */
21879 	data_length -= tcp->tcp_ip_hdr_len;
21880 	data_length += tcp->tcp_sum;
21881 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
21882 	U16_TO_ABE16(data_length, tcph->th_sum);
21883 	if (tcp->tcp_ip_forward_progress) {
21884 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21885 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
21886 		tcp->tcp_ip_forward_progress = B_FALSE;
21887 	}
21888 	return (mp1);
21889 }
21890 
21891 /* This function handles the push timeout. */
21892 void
21893 tcp_push_timer(void *arg)
21894 {
21895 	conn_t	*connp = (conn_t *)arg;
21896 	tcp_t *tcp = connp->conn_tcp;
21897 
21898 	TCP_DBGSTAT(tcp_push_timer_cnt);
21899 
21900 	ASSERT(tcp->tcp_listener == NULL);
21901 
21902 	/*
21903 	 * We need to stop synchronous streams temporarily to prevent a race
21904 	 * with tcp_fuse_rrw() or tcp_fusion rinfop().  It is safe to access
21905 	 * tcp_rcv_list here because those entry points will return right
21906 	 * away when synchronous streams is stopped.
21907 	 */
21908 	TCP_FUSE_SYNCSTR_STOP(tcp);
21909 	tcp->tcp_push_tid = 0;
21910 	if ((tcp->tcp_rcv_list != NULL) &&
21911 	    (tcp_rcv_drain(tcp->tcp_rq, tcp) == TH_ACK_NEEDED))
21912 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21913 	TCP_FUSE_SYNCSTR_RESUME(tcp);
21914 }
21915 
21916 /*
21917  * This function handles delayed ACK timeout.
21918  */
21919 static void
21920 tcp_ack_timer(void *arg)
21921 {
21922 	conn_t	*connp = (conn_t *)arg;
21923 	tcp_t *tcp = connp->conn_tcp;
21924 	mblk_t *mp;
21925 
21926 	TCP_DBGSTAT(tcp_ack_timer_cnt);
21927 
21928 	tcp->tcp_ack_tid = 0;
21929 
21930 	if (tcp->tcp_fused)
21931 		return;
21932 
21933 	/*
21934 	 * Do not send ACK if there is no outstanding unack'ed data.
21935 	 */
21936 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
21937 		return;
21938 	}
21939 
21940 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
21941 		/*
21942 		 * Make sure we don't allow deferred ACKs to result in
21943 		 * timer-based ACKing.  If we have held off an ACK
21944 		 * when there was more than an mss here, and the timer
21945 		 * goes off, we have to worry about the possibility
21946 		 * that the sender isn't doing slow-start, or is out
21947 		 * of step with us for some other reason.  We fall
21948 		 * permanently back in the direction of
21949 		 * ACK-every-other-packet as suggested in RFC 1122.
21950 		 */
21951 		if (tcp->tcp_rack_abs_max > 2)
21952 			tcp->tcp_rack_abs_max--;
21953 		tcp->tcp_rack_cur_max = 2;
21954 	}
21955 	mp = tcp_ack_mp(tcp);
21956 
21957 	if (mp != NULL) {
21958 		TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_SEND_PKT);
21959 		BUMP_LOCAL(tcp->tcp_obsegs);
21960 		BUMP_MIB(&tcp_mib, tcpOutAck);
21961 		BUMP_MIB(&tcp_mib, tcpOutAckDelayed);
21962 		tcp_send_data(tcp, tcp->tcp_wq, mp);
21963 	}
21964 }
21965 
21966 
21967 /* Generate an ACK-only (no data) segment for a TCP endpoint */
21968 static mblk_t *
21969 tcp_ack_mp(tcp_t *tcp)
21970 {
21971 	uint32_t	seq_no;
21972 
21973 	/*
21974 	 * There are a few cases to be considered while setting the sequence no.
21975 	 * Essentially, we can come here while processing an unacceptable pkt
21976 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
21977 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
21978 	 * If we are here for a zero window probe, stick with suna. In all
21979 	 * other cases, we check if suna + swnd encompasses snxt and set
21980 	 * the sequence number to snxt, if so. If snxt falls outside the
21981 	 * window (the receiver probably shrunk its window), we will go with
21982 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
21983 	 * receiver.
21984 	 */
21985 	if (tcp->tcp_zero_win_probe) {
21986 		seq_no = tcp->tcp_suna;
21987 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
21988 		ASSERT(tcp->tcp_swnd == 0);
21989 		seq_no = tcp->tcp_snxt;
21990 	} else {
21991 		seq_no = SEQ_GT(tcp->tcp_snxt,
21992 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
21993 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
21994 	}
21995 
21996 	if (tcp->tcp_valid_bits) {
21997 		/*
21998 		 * For the complex case where we have to send some
21999 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
22000 		 */
22001 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
22002 		    NULL, B_FALSE));
22003 	} else {
22004 		/* Generate a simple ACK */
22005 		int	data_length;
22006 		uchar_t	*rptr;
22007 		tcph_t	*tcph;
22008 		mblk_t	*mp1;
22009 		int32_t	tcp_hdr_len;
22010 		int32_t	tcp_tcp_hdr_len;
22011 		int32_t	num_sack_blk = 0;
22012 		int32_t sack_opt_len;
22013 
22014 		/*
22015 		 * Allocate space for TCP + IP headers
22016 		 * and link-level header
22017 		 */
22018 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
22019 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
22020 			    tcp->tcp_num_sack_blk);
22021 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
22022 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
22023 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
22024 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
22025 		} else {
22026 			tcp_hdr_len = tcp->tcp_hdr_len;
22027 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
22028 		}
22029 		mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, BPRI_MED);
22030 		if (!mp1)
22031 			return (NULL);
22032 
22033 		/* Update the latest receive window size in TCP header. */
22034 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22035 		    tcp->tcp_tcph->th_win);
22036 		/* copy in prototype TCP + IP header */
22037 		rptr = mp1->b_rptr + tcp_wroff_xtra;
22038 		mp1->b_rptr = rptr;
22039 		mp1->b_wptr = rptr + tcp_hdr_len;
22040 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
22041 
22042 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
22043 
22044 		/* Set the TCP sequence number. */
22045 		U32_TO_ABE32(seq_no, tcph->th_seq);
22046 
22047 		/* Set up the TCP flag field. */
22048 		tcph->th_flags[0] = (uchar_t)TH_ACK;
22049 		if (tcp->tcp_ecn_echo_on)
22050 			tcph->th_flags[0] |= TH_ECE;
22051 
22052 		tcp->tcp_rack = tcp->tcp_rnxt;
22053 		tcp->tcp_rack_cnt = 0;
22054 
22055 		/* fill in timestamp option if in use */
22056 		if (tcp->tcp_snd_ts_ok) {
22057 			uint32_t llbolt = (uint32_t)lbolt;
22058 
22059 			U32_TO_BE32(llbolt,
22060 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22061 			U32_TO_BE32(tcp->tcp_ts_recent,
22062 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22063 		}
22064 
22065 		/* Fill in SACK options */
22066 		if (num_sack_blk > 0) {
22067 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
22068 			sack_blk_t *tmp;
22069 			int32_t	i;
22070 
22071 			wptr[0] = TCPOPT_NOP;
22072 			wptr[1] = TCPOPT_NOP;
22073 			wptr[2] = TCPOPT_SACK;
22074 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
22075 			    sizeof (sack_blk_t);
22076 			wptr += TCPOPT_REAL_SACK_LEN;
22077 
22078 			tmp = tcp->tcp_sack_list;
22079 			for (i = 0; i < num_sack_blk; i++) {
22080 				U32_TO_BE32(tmp[i].begin, wptr);
22081 				wptr += sizeof (tcp_seq);
22082 				U32_TO_BE32(tmp[i].end, wptr);
22083 				wptr += sizeof (tcp_seq);
22084 			}
22085 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
22086 			    << 4);
22087 		}
22088 
22089 		if (tcp->tcp_ipversion == IPV4_VERSION) {
22090 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
22091 		} else {
22092 			/* Check for ip6i_t header in sticky hdrs */
22093 			ip6_t *ip6 = (ip6_t *)(rptr +
22094 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
22095 			    sizeof (ip6i_t) : 0));
22096 
22097 			ip6->ip6_plen = htons(tcp_hdr_len -
22098 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22099 		}
22100 
22101 		/*
22102 		 * Prime pump for checksum calculation in IP.  Include the
22103 		 * adjustment for a source route if any.
22104 		 */
22105 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
22106 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
22107 		U16_TO_ABE16(data_length, tcph->th_sum);
22108 
22109 		if (tcp->tcp_ip_forward_progress) {
22110 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22111 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
22112 			tcp->tcp_ip_forward_progress = B_FALSE;
22113 		}
22114 		return (mp1);
22115 	}
22116 }
22117 
22118 /*
22119  * To create a temporary tcp structure for inserting into bind hash list.
22120  * The parameter is assumed to be in network byte order, ready for use.
22121  */
22122 /* ARGSUSED */
22123 static tcp_t *
22124 tcp_alloc_temp_tcp(in_port_t port)
22125 {
22126 	conn_t	*connp;
22127 	tcp_t	*tcp;
22128 
22129 	connp = ipcl_conn_create(IPCL_TCPCONN, KM_SLEEP);
22130 	if (connp == NULL)
22131 		return (NULL);
22132 
22133 	tcp = connp->conn_tcp;
22134 
22135 	/*
22136 	 * Only initialize the necessary info in those structures.  Note
22137 	 * that since INADDR_ANY is all 0, we do not need to set
22138 	 * tcp_bound_source to INADDR_ANY here.
22139 	 */
22140 	tcp->tcp_state = TCPS_BOUND;
22141 	tcp->tcp_lport = port;
22142 	tcp->tcp_exclbind = 1;
22143 	tcp->tcp_reserved_port = 1;
22144 
22145 	/* Just for place holding... */
22146 	tcp->tcp_ipversion = IPV4_VERSION;
22147 
22148 	return (tcp);
22149 }
22150 
22151 /*
22152  * To remove a port range specified by lo_port and hi_port from the
22153  * reserved port ranges.  This is one of the three public functions of
22154  * the reserved port interface.  Note that a port range has to be removed
22155  * as a whole.  Ports in a range cannot be removed individually.
22156  *
22157  * Params:
22158  *	in_port_t lo_port: the beginning port of the reserved port range to
22159  *		be deleted.
22160  *	in_port_t hi_port: the ending port of the reserved port range to
22161  *		be deleted.
22162  *
22163  * Return:
22164  *	B_TRUE if the deletion is successful, B_FALSE otherwise.
22165  */
22166 boolean_t
22167 tcp_reserved_port_del(in_port_t lo_port, in_port_t hi_port)
22168 {
22169 	int	i, j;
22170 	int	size;
22171 	tcp_t	**temp_tcp_array;
22172 	tcp_t	*tcp;
22173 
22174 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22175 
22176 	/* First make sure that the port ranage is indeed reserved. */
22177 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22178 		if (tcp_reserved_port[i].lo_port == lo_port) {
22179 			hi_port = tcp_reserved_port[i].hi_port;
22180 			temp_tcp_array = tcp_reserved_port[i].temp_tcp_array;
22181 			break;
22182 		}
22183 	}
22184 	if (i == tcp_reserved_port_array_size) {
22185 		rw_exit(&tcp_reserved_port_lock);
22186 		return (B_FALSE);
22187 	}
22188 
22189 	/*
22190 	 * Remove the range from the array.  This simple loop is possible
22191 	 * because port ranges are inserted in ascending order.
22192 	 */
22193 	for (j = i; j < tcp_reserved_port_array_size - 1; j++) {
22194 		tcp_reserved_port[j].lo_port = tcp_reserved_port[j+1].lo_port;
22195 		tcp_reserved_port[j].hi_port = tcp_reserved_port[j+1].hi_port;
22196 		tcp_reserved_port[j].temp_tcp_array =
22197 		    tcp_reserved_port[j+1].temp_tcp_array;
22198 	}
22199 
22200 	/* Remove all the temporary tcp structures. */
22201 	size = hi_port - lo_port + 1;
22202 	while (size > 0) {
22203 		tcp = temp_tcp_array[size - 1];
22204 		ASSERT(tcp != NULL);
22205 		tcp_bind_hash_remove(tcp);
22206 		CONN_DEC_REF(tcp->tcp_connp);
22207 		size--;
22208 	}
22209 	kmem_free(temp_tcp_array, (hi_port - lo_port + 1) * sizeof (tcp_t *));
22210 	tcp_reserved_port_array_size--;
22211 	rw_exit(&tcp_reserved_port_lock);
22212 	return (B_TRUE);
22213 }
22214 
22215 /*
22216  * Macro to remove temporary tcp structure from the bind hash list.  The
22217  * first parameter is the list of tcp to be removed.  The second parameter
22218  * is the number of tcps in the array.
22219  */
22220 #define	TCP_TMP_TCP_REMOVE(tcp_array, num) \
22221 { \
22222 	while ((num) > 0) { \
22223 		tcp_t *tcp = (tcp_array)[(num) - 1]; \
22224 		tf_t *tbf; \
22225 		tcp_t *tcpnext; \
22226 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)]; \
22227 		mutex_enter(&tbf->tf_lock); \
22228 		tcpnext = tcp->tcp_bind_hash; \
22229 		if (tcpnext) { \
22230 			tcpnext->tcp_ptpbhn = \
22231 				tcp->tcp_ptpbhn; \
22232 		} \
22233 		*tcp->tcp_ptpbhn = tcpnext; \
22234 		mutex_exit(&tbf->tf_lock); \
22235 		kmem_free(tcp, sizeof (tcp_t)); \
22236 		(tcp_array)[(num) - 1] = NULL; \
22237 		(num)--; \
22238 	} \
22239 }
22240 
22241 /*
22242  * The public interface for other modules to call to reserve a port range
22243  * in TCP.  The caller passes in how large a port range it wants.  TCP
22244  * will try to find a range and return it via lo_port and hi_port.  This is
22245  * used by NCA's nca_conn_init.
22246  * NCA can only be used in the global zone so this only affects the global
22247  * zone's ports.
22248  *
22249  * Params:
22250  *	int size: the size of the port range to be reserved.
22251  *	in_port_t *lo_port (referenced): returns the beginning port of the
22252  *		reserved port range added.
22253  *	in_port_t *hi_port (referenced): returns the ending port of the
22254  *		reserved port range added.
22255  *
22256  * Return:
22257  *	B_TRUE if the port reservation is successful, B_FALSE otherwise.
22258  */
22259 boolean_t
22260 tcp_reserved_port_add(int size, in_port_t *lo_port, in_port_t *hi_port)
22261 {
22262 	tcp_t		*tcp;
22263 	tcp_t		*tmp_tcp;
22264 	tcp_t		**temp_tcp_array;
22265 	tf_t		*tbf;
22266 	in_port_t	net_port;
22267 	in_port_t	port;
22268 	int32_t		cur_size;
22269 	int		i, j;
22270 	boolean_t	used;
22271 	tcp_rport_t 	tmp_ports[TCP_RESERVED_PORTS_ARRAY_MAX_SIZE];
22272 	zoneid_t	zoneid = GLOBAL_ZONEID;
22273 
22274 	/* Sanity check. */
22275 	if (size <= 0 || size > TCP_RESERVED_PORTS_RANGE_MAX) {
22276 		return (B_FALSE);
22277 	}
22278 
22279 	rw_enter(&tcp_reserved_port_lock, RW_WRITER);
22280 	if (tcp_reserved_port_array_size == TCP_RESERVED_PORTS_ARRAY_MAX_SIZE) {
22281 		rw_exit(&tcp_reserved_port_lock);
22282 		return (B_FALSE);
22283 	}
22284 
22285 	/*
22286 	 * Find the starting port to try.  Since the port ranges are ordered
22287 	 * in the reserved port array, we can do a simple search here.
22288 	 */
22289 	*lo_port = TCP_SMALLEST_RESERVED_PORT;
22290 	*hi_port = TCP_LARGEST_RESERVED_PORT;
22291 	for (i = 0; i < tcp_reserved_port_array_size;
22292 	    *lo_port = tcp_reserved_port[i].hi_port + 1, i++) {
22293 		if (tcp_reserved_port[i].lo_port - *lo_port >= size) {
22294 			*hi_port = tcp_reserved_port[i].lo_port - 1;
22295 			break;
22296 		}
22297 	}
22298 	/* No available port range. */
22299 	if (i == tcp_reserved_port_array_size && *hi_port - *lo_port < size) {
22300 		rw_exit(&tcp_reserved_port_lock);
22301 		return (B_FALSE);
22302 	}
22303 
22304 	temp_tcp_array = kmem_zalloc(size * sizeof (tcp_t *), KM_NOSLEEP);
22305 	if (temp_tcp_array == NULL) {
22306 		rw_exit(&tcp_reserved_port_lock);
22307 		return (B_FALSE);
22308 	}
22309 
22310 	/* Go thru the port range to see if some ports are already bound. */
22311 	for (port = *lo_port, cur_size = 0;
22312 	    cur_size < size && port <= *hi_port;
22313 	    cur_size++, port++) {
22314 		used = B_FALSE;
22315 		net_port = htons(port);
22316 		tbf = &tcp_bind_fanout[TCP_BIND_HASH(net_port)];
22317 		mutex_enter(&tbf->tf_lock);
22318 		for (tcp = tbf->tf_tcp; tcp != NULL;
22319 		    tcp = tcp->tcp_bind_hash) {
22320 			if (zoneid == tcp->tcp_connp->conn_zoneid &&
22321 			    net_port == tcp->tcp_lport) {
22322 				/*
22323 				 * A port is already bound.  Search again
22324 				 * starting from port + 1.  Release all
22325 				 * temporary tcps.
22326 				 */
22327 				mutex_exit(&tbf->tf_lock);
22328 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22329 				*lo_port = port + 1;
22330 				cur_size = -1;
22331 				used = B_TRUE;
22332 				break;
22333 			}
22334 		}
22335 		if (!used) {
22336 			if ((tmp_tcp = tcp_alloc_temp_tcp(net_port)) == NULL) {
22337 				/*
22338 				 * Allocation failure.  Just fail the request.
22339 				 * Need to remove all those temporary tcp
22340 				 * structures.
22341 				 */
22342 				mutex_exit(&tbf->tf_lock);
22343 				TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22344 				rw_exit(&tcp_reserved_port_lock);
22345 				kmem_free(temp_tcp_array,
22346 				    (hi_port - lo_port + 1) *
22347 				    sizeof (tcp_t *));
22348 				return (B_FALSE);
22349 			}
22350 			temp_tcp_array[cur_size] = tmp_tcp;
22351 			tcp_bind_hash_insert(tbf, tmp_tcp, B_TRUE);
22352 			mutex_exit(&tbf->tf_lock);
22353 		}
22354 	}
22355 
22356 	/*
22357 	 * The current range is not large enough.  We can actually do another
22358 	 * search if this search is done between 2 reserved port ranges.  But
22359 	 * for first release, we just stop here and return saying that no port
22360 	 * range is available.
22361 	 */
22362 	if (cur_size < size) {
22363 		TCP_TMP_TCP_REMOVE(temp_tcp_array, cur_size);
22364 		rw_exit(&tcp_reserved_port_lock);
22365 		kmem_free(temp_tcp_array, size * sizeof (tcp_t *));
22366 		return (B_FALSE);
22367 	}
22368 	*hi_port = port - 1;
22369 
22370 	/*
22371 	 * Insert range into array in ascending order.  Since this function
22372 	 * must not be called often, we choose to use the simplest method.
22373 	 * The above array should not consume excessive stack space as
22374 	 * the size must be very small.  If in future releases, we find
22375 	 * that we should provide more reserved port ranges, this function
22376 	 * has to be modified to be more efficient.
22377 	 */
22378 	if (tcp_reserved_port_array_size == 0) {
22379 		tcp_reserved_port[0].lo_port = *lo_port;
22380 		tcp_reserved_port[0].hi_port = *hi_port;
22381 		tcp_reserved_port[0].temp_tcp_array = temp_tcp_array;
22382 	} else {
22383 		for (i = 0, j = 0; i < tcp_reserved_port_array_size; i++, j++) {
22384 			if (*lo_port < tcp_reserved_port[i].lo_port && i == j) {
22385 				tmp_ports[j].lo_port = *lo_port;
22386 				tmp_ports[j].hi_port = *hi_port;
22387 				tmp_ports[j].temp_tcp_array = temp_tcp_array;
22388 				j++;
22389 			}
22390 			tmp_ports[j].lo_port = tcp_reserved_port[i].lo_port;
22391 			tmp_ports[j].hi_port = tcp_reserved_port[i].hi_port;
22392 			tmp_ports[j].temp_tcp_array =
22393 			    tcp_reserved_port[i].temp_tcp_array;
22394 		}
22395 		if (j == i) {
22396 			tmp_ports[j].lo_port = *lo_port;
22397 			tmp_ports[j].hi_port = *hi_port;
22398 			tmp_ports[j].temp_tcp_array = temp_tcp_array;
22399 		}
22400 		bcopy(tmp_ports, tcp_reserved_port, sizeof (tmp_ports));
22401 	}
22402 	tcp_reserved_port_array_size++;
22403 	rw_exit(&tcp_reserved_port_lock);
22404 	return (B_TRUE);
22405 }
22406 
22407 /*
22408  * Check to see if a port is in any reserved port range.
22409  *
22410  * Params:
22411  *	in_port_t port: the port to be verified.
22412  *
22413  * Return:
22414  *	B_TRUE is the port is inside a reserved port range, B_FALSE otherwise.
22415  */
22416 boolean_t
22417 tcp_reserved_port_check(in_port_t port)
22418 {
22419 	int i;
22420 
22421 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22422 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22423 		if (port >= tcp_reserved_port[i].lo_port ||
22424 		    port <= tcp_reserved_port[i].hi_port) {
22425 			rw_exit(&tcp_reserved_port_lock);
22426 			return (B_TRUE);
22427 		}
22428 	}
22429 	rw_exit(&tcp_reserved_port_lock);
22430 	return (B_FALSE);
22431 }
22432 
22433 /*
22434  * To list all reserved port ranges.  This is the function to handle
22435  * ndd tcp_reserved_port_list.
22436  */
22437 /* ARGSUSED */
22438 static int
22439 tcp_reserved_port_list(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22440 {
22441 	int i;
22442 
22443 	rw_enter(&tcp_reserved_port_lock, RW_READER);
22444 	if (tcp_reserved_port_array_size > 0)
22445 		(void) mi_mpprintf(mp, "The following ports are reserved:");
22446 	else
22447 		(void) mi_mpprintf(mp, "No port is reserved.");
22448 	for (i = 0; i < tcp_reserved_port_array_size; i++) {
22449 		(void) mi_mpprintf(mp, "%d-%d",
22450 		    tcp_reserved_port[i].lo_port, tcp_reserved_port[i].hi_port);
22451 	}
22452 	rw_exit(&tcp_reserved_port_lock);
22453 	return (0);
22454 }
22455 
22456 /*
22457  * Hash list insertion routine for tcp_t structures.
22458  * Inserts entries with the ones bound to a specific IP address first
22459  * followed by those bound to INADDR_ANY.
22460  */
22461 static void
22462 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
22463 {
22464 	tcp_t	**tcpp;
22465 	tcp_t	*tcpnext;
22466 
22467 	if (tcp->tcp_ptpbhn != NULL) {
22468 		ASSERT(!caller_holds_lock);
22469 		tcp_bind_hash_remove(tcp);
22470 	}
22471 	tcpp = &tbf->tf_tcp;
22472 	if (!caller_holds_lock) {
22473 		mutex_enter(&tbf->tf_lock);
22474 	} else {
22475 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
22476 	}
22477 	tcpnext = tcpp[0];
22478 	if (tcpnext) {
22479 		/*
22480 		 * If the new tcp bound to the INADDR_ANY address
22481 		 * and the first one in the list is not bound to
22482 		 * INADDR_ANY we skip all entries until we find the
22483 		 * first one bound to INADDR_ANY.
22484 		 * This makes sure that applications binding to a
22485 		 * specific address get preference over those binding to
22486 		 * INADDR_ANY.
22487 		 */
22488 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
22489 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
22490 			while ((tcpnext = tcpp[0]) != NULL &&
22491 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
22492 				tcpp = &(tcpnext->tcp_bind_hash);
22493 			if (tcpnext)
22494 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22495 		} else
22496 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
22497 	}
22498 	tcp->tcp_bind_hash = tcpnext;
22499 	tcp->tcp_ptpbhn = tcpp;
22500 	tcpp[0] = tcp;
22501 	if (!caller_holds_lock)
22502 		mutex_exit(&tbf->tf_lock);
22503 }
22504 
22505 /*
22506  * Hash list removal routine for tcp_t structures.
22507  */
22508 static void
22509 tcp_bind_hash_remove(tcp_t *tcp)
22510 {
22511 	tcp_t	*tcpnext;
22512 	kmutex_t *lockp;
22513 
22514 	if (tcp->tcp_ptpbhn == NULL)
22515 		return;
22516 
22517 	/*
22518 	 * Extract the lock pointer in case there are concurrent
22519 	 * hash_remove's for this instance.
22520 	 */
22521 	ASSERT(tcp->tcp_lport != 0);
22522 	lockp = &tcp_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
22523 
22524 	ASSERT(lockp != NULL);
22525 	mutex_enter(lockp);
22526 	if (tcp->tcp_ptpbhn) {
22527 		tcpnext = tcp->tcp_bind_hash;
22528 		if (tcpnext) {
22529 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
22530 			tcp->tcp_bind_hash = NULL;
22531 		}
22532 		*tcp->tcp_ptpbhn = tcpnext;
22533 		tcp->tcp_ptpbhn = NULL;
22534 	}
22535 	mutex_exit(lockp);
22536 }
22537 
22538 
22539 /*
22540  * Hash list lookup routine for tcp_t structures.
22541  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
22542  */
22543 static tcp_t *
22544 tcp_acceptor_hash_lookup(t_uscalar_t id)
22545 {
22546 	tf_t	*tf;
22547 	tcp_t	*tcp;
22548 
22549 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22550 	mutex_enter(&tf->tf_lock);
22551 	for (tcp = tf->tf_tcp; tcp != NULL;
22552 	    tcp = tcp->tcp_acceptor_hash) {
22553 		if (tcp->tcp_acceptor_id == id) {
22554 			CONN_INC_REF(tcp->tcp_connp);
22555 			mutex_exit(&tf->tf_lock);
22556 			return (tcp);
22557 		}
22558 	}
22559 	mutex_exit(&tf->tf_lock);
22560 	return (NULL);
22561 }
22562 
22563 
22564 /*
22565  * Hash list insertion routine for tcp_t structures.
22566  */
22567 void
22568 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
22569 {
22570 	tf_t	*tf;
22571 	tcp_t	**tcpp;
22572 	tcp_t	*tcpnext;
22573 
22574 	tf = &tcp_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
22575 
22576 	if (tcp->tcp_ptpahn != NULL)
22577 		tcp_acceptor_hash_remove(tcp);
22578 	tcpp = &tf->tf_tcp;
22579 	mutex_enter(&tf->tf_lock);
22580 	tcpnext = tcpp[0];
22581 	if (tcpnext)
22582 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
22583 	tcp->tcp_acceptor_hash = tcpnext;
22584 	tcp->tcp_ptpahn = tcpp;
22585 	tcpp[0] = tcp;
22586 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
22587 	mutex_exit(&tf->tf_lock);
22588 }
22589 
22590 /*
22591  * Hash list removal routine for tcp_t structures.
22592  */
22593 static void
22594 tcp_acceptor_hash_remove(tcp_t *tcp)
22595 {
22596 	tcp_t	*tcpnext;
22597 	kmutex_t *lockp;
22598 
22599 	/*
22600 	 * Extract the lock pointer in case there are concurrent
22601 	 * hash_remove's for this instance.
22602 	 */
22603 	lockp = tcp->tcp_acceptor_lockp;
22604 
22605 	if (tcp->tcp_ptpahn == NULL)
22606 		return;
22607 
22608 	ASSERT(lockp != NULL);
22609 	mutex_enter(lockp);
22610 	if (tcp->tcp_ptpahn) {
22611 		tcpnext = tcp->tcp_acceptor_hash;
22612 		if (tcpnext) {
22613 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
22614 			tcp->tcp_acceptor_hash = NULL;
22615 		}
22616 		*tcp->tcp_ptpahn = tcpnext;
22617 		tcp->tcp_ptpahn = NULL;
22618 	}
22619 	mutex_exit(lockp);
22620 	tcp->tcp_acceptor_lockp = NULL;
22621 }
22622 
22623 /* ARGSUSED */
22624 static int
22625 tcp_host_param_setvalue(queue_t *q, mblk_t *mp, char *value, caddr_t cp, int af)
22626 {
22627 	int error = 0;
22628 	int retval;
22629 	char *end;
22630 
22631 	tcp_hsp_t *hsp;
22632 	tcp_hsp_t *hspprev;
22633 
22634 	ipaddr_t addr = 0;		/* Address we're looking for */
22635 	in6_addr_t v6addr;		/* Address we're looking for */
22636 	uint32_t hash;			/* Hash of that address */
22637 
22638 	/*
22639 	 * If the following variables are still zero after parsing the input
22640 	 * string, the user didn't specify them and we don't change them in
22641 	 * the HSP.
22642 	 */
22643 
22644 	ipaddr_t mask = 0;		/* Subnet mask */
22645 	in6_addr_t v6mask;
22646 	long sendspace = 0;		/* Send buffer size */
22647 	long recvspace = 0;		/* Receive buffer size */
22648 	long timestamp = 0;	/* Originate TCP TSTAMP option, 1 = yes */
22649 	boolean_t delete = B_FALSE;	/* User asked to delete this HSP */
22650 
22651 	rw_enter(&tcp_hsp_lock, RW_WRITER);
22652 
22653 	/* Parse and validate address */
22654 	if (af == AF_INET) {
22655 		retval = inet_pton(af, value, &addr);
22656 		if (retval == 1)
22657 			IN6_IPADDR_TO_V4MAPPED(addr, &v6addr);
22658 	} else if (af == AF_INET6) {
22659 		retval = inet_pton(af, value, &v6addr);
22660 	} else {
22661 		error = EINVAL;
22662 		goto done;
22663 	}
22664 	if (retval == 0) {
22665 		error = EINVAL;
22666 		goto done;
22667 	}
22668 
22669 	while ((*value) && *value != ' ')
22670 		value++;
22671 
22672 	/* Parse individual keywords, set variables if found */
22673 	while (*value) {
22674 		/* Skip leading blanks */
22675 
22676 		while (*value == ' ' || *value == '\t')
22677 			value++;
22678 
22679 		/* If at end of string, we're done */
22680 
22681 		if (!*value)
22682 			break;
22683 
22684 		/* We have a word, figure out what it is */
22685 
22686 		if (strncmp("mask", value, 4) == 0) {
22687 			value += 4;
22688 			while (*value == ' ' || *value == '\t')
22689 				value++;
22690 			/* Parse subnet mask */
22691 			if (af == AF_INET) {
22692 				retval = inet_pton(af, value, &mask);
22693 				if (retval == 1) {
22694 					V4MASK_TO_V6(mask, v6mask);
22695 				}
22696 			} else if (af == AF_INET6) {
22697 				retval = inet_pton(af, value, &v6mask);
22698 			}
22699 			if (retval != 1) {
22700 				error = EINVAL;
22701 				goto done;
22702 			}
22703 			while ((*value) && *value != ' ')
22704 				value++;
22705 		} else if (strncmp("sendspace", value, 9) == 0) {
22706 			value += 9;
22707 
22708 			if (ddi_strtol(value, &end, 0, &sendspace) != 0 ||
22709 			    sendspace < TCP_XMIT_HIWATER ||
22710 			    sendspace >= (1L<<30)) {
22711 				error = EINVAL;
22712 				goto done;
22713 			}
22714 			value = end;
22715 		} else if (strncmp("recvspace", value, 9) == 0) {
22716 			value += 9;
22717 
22718 			if (ddi_strtol(value, &end, 0, &recvspace) != 0 ||
22719 			    recvspace < TCP_RECV_HIWATER ||
22720 			    recvspace >= (1L<<30)) {
22721 				error = EINVAL;
22722 				goto done;
22723 			}
22724 			value = end;
22725 		} else if (strncmp("timestamp", value, 9) == 0) {
22726 			value += 9;
22727 
22728 			if (ddi_strtol(value, &end, 0, &timestamp) != 0 ||
22729 			    timestamp < 0 || timestamp > 1) {
22730 				error = EINVAL;
22731 				goto done;
22732 			}
22733 
22734 			/*
22735 			 * We increment timestamp so we know it's been set;
22736 			 * this is undone when we put it in the HSP
22737 			 */
22738 			timestamp++;
22739 			value = end;
22740 		} else if (strncmp("delete", value, 6) == 0) {
22741 			value += 6;
22742 			delete = B_TRUE;
22743 		} else {
22744 			error = EINVAL;
22745 			goto done;
22746 		}
22747 	}
22748 
22749 	/* Hash address for lookup */
22750 
22751 	hash = TCP_HSP_HASH(addr);
22752 
22753 	if (delete) {
22754 		/*
22755 		 * Note that deletes don't return an error if the thing
22756 		 * we're trying to delete isn't there.
22757 		 */
22758 		if (tcp_hsp_hash == NULL)
22759 			goto done;
22760 		hsp = tcp_hsp_hash[hash];
22761 
22762 		if (hsp) {
22763 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
22764 			    &v6addr)) {
22765 				tcp_hsp_hash[hash] = hsp->tcp_hsp_next;
22766 				mi_free((char *)hsp);
22767 			} else {
22768 				hspprev = hsp;
22769 				while ((hsp = hsp->tcp_hsp_next) != NULL) {
22770 					if (IN6_ARE_ADDR_EQUAL(
22771 					    &hsp->tcp_hsp_addr_v6, &v6addr)) {
22772 						hspprev->tcp_hsp_next =
22773 						    hsp->tcp_hsp_next;
22774 						mi_free((char *)hsp);
22775 						break;
22776 					}
22777 					hspprev = hsp;
22778 				}
22779 			}
22780 		}
22781 	} else {
22782 		/*
22783 		 * We're adding/modifying an HSP.  If we haven't already done
22784 		 * so, allocate the hash table.
22785 		 */
22786 
22787 		if (!tcp_hsp_hash) {
22788 			tcp_hsp_hash = (tcp_hsp_t **)
22789 			    mi_zalloc(sizeof (tcp_hsp_t *) * TCP_HSP_HASH_SIZE);
22790 			if (!tcp_hsp_hash) {
22791 				error = EINVAL;
22792 				goto done;
22793 			}
22794 		}
22795 
22796 		/* Get head of hash chain */
22797 
22798 		hsp = tcp_hsp_hash[hash];
22799 
22800 		/* Try to find pre-existing hsp on hash chain */
22801 		/* Doesn't handle CIDR prefixes. */
22802 		while (hsp) {
22803 			if (IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6, &v6addr))
22804 				break;
22805 			hsp = hsp->tcp_hsp_next;
22806 		}
22807 
22808 		/*
22809 		 * If we didn't, create one with default values and put it
22810 		 * at head of hash chain
22811 		 */
22812 
22813 		if (!hsp) {
22814 			hsp = (tcp_hsp_t *)mi_zalloc(sizeof (tcp_hsp_t));
22815 			if (!hsp) {
22816 				error = EINVAL;
22817 				goto done;
22818 			}
22819 			hsp->tcp_hsp_next = tcp_hsp_hash[hash];
22820 			tcp_hsp_hash[hash] = hsp;
22821 		}
22822 
22823 		/* Set values that the user asked us to change */
22824 
22825 		hsp->tcp_hsp_addr_v6 = v6addr;
22826 		if (IN6_IS_ADDR_V4MAPPED(&v6addr))
22827 			hsp->tcp_hsp_vers = IPV4_VERSION;
22828 		else
22829 			hsp->tcp_hsp_vers = IPV6_VERSION;
22830 		hsp->tcp_hsp_subnet_v6 = v6mask;
22831 		if (sendspace > 0)
22832 			hsp->tcp_hsp_sendspace = sendspace;
22833 		if (recvspace > 0)
22834 			hsp->tcp_hsp_recvspace = recvspace;
22835 		if (timestamp > 0)
22836 			hsp->tcp_hsp_tstamp = timestamp - 1;
22837 	}
22838 
22839 done:
22840 	rw_exit(&tcp_hsp_lock);
22841 	return (error);
22842 }
22843 
22844 /* Set callback routine passed to nd_load by tcp_param_register. */
22845 /* ARGSUSED */
22846 static int
22847 tcp_host_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
22848 {
22849 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET));
22850 }
22851 /* ARGSUSED */
22852 static int
22853 tcp_host_param_set_ipv6(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22854     cred_t *cr)
22855 {
22856 	return (tcp_host_param_setvalue(q, mp, value, cp, AF_INET6));
22857 }
22858 
22859 /* TCP host parameters report triggered via the Named Dispatch mechanism. */
22860 /* ARGSUSED */
22861 static int
22862 tcp_host_param_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22863 {
22864 	tcp_hsp_t *hsp;
22865 	int i;
22866 	char addrbuf[INET6_ADDRSTRLEN], subnetbuf[INET6_ADDRSTRLEN];
22867 
22868 	rw_enter(&tcp_hsp_lock, RW_READER);
22869 	(void) mi_mpprintf(mp,
22870 	    "Hash HSP     " MI_COL_HDRPAD_STR
22871 	    "Address         Subnet Mask     Send       Receive    TStamp");
22872 	if (tcp_hsp_hash) {
22873 		for (i = 0; i < TCP_HSP_HASH_SIZE; i++) {
22874 			hsp = tcp_hsp_hash[i];
22875 			while (hsp) {
22876 				if (hsp->tcp_hsp_vers == IPV4_VERSION) {
22877 					(void) inet_ntop(AF_INET,
22878 					    &hsp->tcp_hsp_addr,
22879 					    addrbuf, sizeof (addrbuf));
22880 					(void) inet_ntop(AF_INET,
22881 					    &hsp->tcp_hsp_subnet,
22882 					    subnetbuf, sizeof (subnetbuf));
22883 				} else {
22884 					(void) inet_ntop(AF_INET6,
22885 					    &hsp->tcp_hsp_addr_v6,
22886 					    addrbuf, sizeof (addrbuf));
22887 					(void) inet_ntop(AF_INET6,
22888 					    &hsp->tcp_hsp_subnet_v6,
22889 					    subnetbuf, sizeof (subnetbuf));
22890 				}
22891 				(void) mi_mpprintf(mp,
22892 				    " %03d " MI_COL_PTRFMT_STR
22893 				    "%s %s %010d %010d      %d",
22894 				    i,
22895 				    (void *)hsp,
22896 				    addrbuf,
22897 				    subnetbuf,
22898 				    hsp->tcp_hsp_sendspace,
22899 				    hsp->tcp_hsp_recvspace,
22900 				    hsp->tcp_hsp_tstamp);
22901 
22902 				hsp = hsp->tcp_hsp_next;
22903 			}
22904 		}
22905 	}
22906 	rw_exit(&tcp_hsp_lock);
22907 	return (0);
22908 }
22909 
22910 
22911 /* Data for fast netmask macro used by tcp_hsp_lookup */
22912 
22913 static ipaddr_t netmasks[] = {
22914 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
22915 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
22916 };
22917 
22918 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
22919 
22920 /*
22921  * XXX This routine should go away and instead we should use the metrics
22922  * associated with the routes to determine the default sndspace and rcvspace.
22923  */
22924 static tcp_hsp_t *
22925 tcp_hsp_lookup(ipaddr_t addr)
22926 {
22927 	tcp_hsp_t *hsp = NULL;
22928 
22929 	/* Quick check without acquiring the lock. */
22930 	if (tcp_hsp_hash == NULL)
22931 		return (NULL);
22932 
22933 	rw_enter(&tcp_hsp_lock, RW_READER);
22934 
22935 	/* This routine finds the best-matching HSP for address addr. */
22936 
22937 	if (tcp_hsp_hash) {
22938 		int i;
22939 		ipaddr_t srchaddr;
22940 		tcp_hsp_t *hsp_net;
22941 
22942 		/* We do three passes: host, network, and subnet. */
22943 
22944 		srchaddr = addr;
22945 
22946 		for (i = 1; i <= 3; i++) {
22947 			/* Look for exact match on srchaddr */
22948 
22949 			hsp = tcp_hsp_hash[TCP_HSP_HASH(srchaddr)];
22950 			while (hsp) {
22951 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
22952 				    hsp->tcp_hsp_addr == srchaddr)
22953 					break;
22954 				hsp = hsp->tcp_hsp_next;
22955 			}
22956 			ASSERT(hsp == NULL ||
22957 			    hsp->tcp_hsp_vers == IPV4_VERSION);
22958 
22959 			/*
22960 			 * If this is the first pass:
22961 			 *   If we found a match, great, return it.
22962 			 *   If not, search for the network on the second pass.
22963 			 */
22964 
22965 			if (i == 1)
22966 				if (hsp)
22967 					break;
22968 				else
22969 				{
22970 					srchaddr = addr & netmask(addr);
22971 					continue;
22972 				}
22973 
22974 			/*
22975 			 * If this is the second pass:
22976 			 *   If we found a match, but there's a subnet mask,
22977 			 *    save the match but try again using the subnet
22978 			 *    mask on the third pass.
22979 			 *   Otherwise, return whatever we found.
22980 			 */
22981 
22982 			if (i == 2) {
22983 				if (hsp && hsp->tcp_hsp_subnet) {
22984 					hsp_net = hsp;
22985 					srchaddr = addr & hsp->tcp_hsp_subnet;
22986 					continue;
22987 				} else {
22988 					break;
22989 				}
22990 			}
22991 
22992 			/*
22993 			 * This must be the third pass.  If we didn't find
22994 			 * anything, return the saved network HSP instead.
22995 			 */
22996 
22997 			if (!hsp)
22998 				hsp = hsp_net;
22999 		}
23000 	}
23001 
23002 	rw_exit(&tcp_hsp_lock);
23003 	return (hsp);
23004 }
23005 
23006 /*
23007  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
23008  * match lookup.
23009  */
23010 static tcp_hsp_t *
23011 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr)
23012 {
23013 	tcp_hsp_t *hsp = NULL;
23014 
23015 	/* Quick check without acquiring the lock. */
23016 	if (tcp_hsp_hash == NULL)
23017 		return (NULL);
23018 
23019 	rw_enter(&tcp_hsp_lock, RW_READER);
23020 
23021 	/* This routine finds the best-matching HSP for address addr. */
23022 
23023 	if (tcp_hsp_hash) {
23024 		int i;
23025 		in6_addr_t v6srchaddr;
23026 		tcp_hsp_t *hsp_net;
23027 
23028 		/* We do three passes: host, network, and subnet. */
23029 
23030 		v6srchaddr = *v6addr;
23031 
23032 		for (i = 1; i <= 3; i++) {
23033 			/* Look for exact match on srchaddr */
23034 
23035 			hsp = tcp_hsp_hash[TCP_HSP_HASH(
23036 			    V4_PART_OF_V6(v6srchaddr))];
23037 			while (hsp) {
23038 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
23039 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
23040 				    &v6srchaddr))
23041 					break;
23042 				hsp = hsp->tcp_hsp_next;
23043 			}
23044 
23045 			/*
23046 			 * If this is the first pass:
23047 			 *   If we found a match, great, return it.
23048 			 *   If not, search for the network on the second pass.
23049 			 */
23050 
23051 			if (i == 1)
23052 				if (hsp)
23053 					break;
23054 				else {
23055 					/* Assume a 64 bit mask */
23056 					v6srchaddr.s6_addr32[0] =
23057 					    v6addr->s6_addr32[0];
23058 					v6srchaddr.s6_addr32[1] =
23059 					    v6addr->s6_addr32[1];
23060 					v6srchaddr.s6_addr32[2] = 0;
23061 					v6srchaddr.s6_addr32[3] = 0;
23062 					continue;
23063 				}
23064 
23065 			/*
23066 			 * If this is the second pass:
23067 			 *   If we found a match, but there's a subnet mask,
23068 			 *    save the match but try again using the subnet
23069 			 *    mask on the third pass.
23070 			 *   Otherwise, return whatever we found.
23071 			 */
23072 
23073 			if (i == 2) {
23074 				ASSERT(hsp == NULL ||
23075 				    hsp->tcp_hsp_vers == IPV6_VERSION);
23076 				if (hsp &&
23077 				    !IN6_IS_ADDR_UNSPECIFIED(
23078 				    &hsp->tcp_hsp_subnet_v6)) {
23079 					hsp_net = hsp;
23080 					V6_MASK_COPY(*v6addr,
23081 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
23082 					continue;
23083 				} else {
23084 					break;
23085 				}
23086 			}
23087 
23088 			/*
23089 			 * This must be the third pass.  If we didn't find
23090 			 * anything, return the saved network HSP instead.
23091 			 */
23092 
23093 			if (!hsp)
23094 				hsp = hsp_net;
23095 		}
23096 	}
23097 
23098 	rw_exit(&tcp_hsp_lock);
23099 	return (hsp);
23100 }
23101 
23102 /*
23103  * Type three generator adapted from the random() function in 4.4 BSD:
23104  */
23105 
23106 /*
23107  * Copyright (c) 1983, 1993
23108  *	The Regents of the University of California.  All rights reserved.
23109  *
23110  * Redistribution and use in source and binary forms, with or without
23111  * modification, are permitted provided that the following conditions
23112  * are met:
23113  * 1. Redistributions of source code must retain the above copyright
23114  *    notice, this list of conditions and the following disclaimer.
23115  * 2. Redistributions in binary form must reproduce the above copyright
23116  *    notice, this list of conditions and the following disclaimer in the
23117  *    documentation and/or other materials provided with the distribution.
23118  * 3. All advertising materials mentioning features or use of this software
23119  *    must display the following acknowledgement:
23120  *	This product includes software developed by the University of
23121  *	California, Berkeley and its contributors.
23122  * 4. Neither the name of the University nor the names of its contributors
23123  *    may be used to endorse or promote products derived from this software
23124  *    without specific prior written permission.
23125  *
23126  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23127  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23128  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23129  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23130  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23131  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23132  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23133  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23134  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23135  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23136  * SUCH DAMAGE.
23137  */
23138 
23139 /* Type 3 -- x**31 + x**3 + 1 */
23140 #define	DEG_3		31
23141 #define	SEP_3		3
23142 
23143 
23144 /* Protected by tcp_random_lock */
23145 static int tcp_randtbl[DEG_3 + 1];
23146 
23147 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
23148 static int *tcp_random_rptr = &tcp_randtbl[1];
23149 
23150 static int *tcp_random_state = &tcp_randtbl[1];
23151 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
23152 
23153 kmutex_t tcp_random_lock;
23154 
23155 void
23156 tcp_random_init(void)
23157 {
23158 	int i;
23159 	hrtime_t hrt;
23160 	time_t wallclock;
23161 	uint64_t result;
23162 
23163 	/*
23164 	 * Use high-res timer and current time for seed.  Gethrtime() returns
23165 	 * a longlong, which may contain resolution down to nanoseconds.
23166 	 * The current time will either be a 32-bit or a 64-bit quantity.
23167 	 * XOR the two together in a 64-bit result variable.
23168 	 * Convert the result to a 32-bit value by multiplying the high-order
23169 	 * 32-bits by the low-order 32-bits.
23170 	 */
23171 
23172 	hrt = gethrtime();
23173 	(void) drv_getparm(TIME, &wallclock);
23174 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
23175 	mutex_enter(&tcp_random_lock);
23176 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
23177 	    (result & 0xffffffff);
23178 
23179 	for (i = 1; i < DEG_3; i++)
23180 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
23181 			+ 12345;
23182 	tcp_random_fptr = &tcp_random_state[SEP_3];
23183 	tcp_random_rptr = &tcp_random_state[0];
23184 	mutex_exit(&tcp_random_lock);
23185 	for (i = 0; i < 10 * DEG_3; i++)
23186 		(void) tcp_random();
23187 }
23188 
23189 /*
23190  * tcp_random: Return a random number in the range [1 - (128K + 1)].
23191  * This range is selected to be approximately centered on TCP_ISS / 2,
23192  * and easy to compute. We get this value by generating a 32-bit random
23193  * number, selecting out the high-order 17 bits, and then adding one so
23194  * that we never return zero.
23195  */
23196 int
23197 tcp_random(void)
23198 {
23199 	int i;
23200 
23201 	mutex_enter(&tcp_random_lock);
23202 	*tcp_random_fptr += *tcp_random_rptr;
23203 
23204 	/*
23205 	 * The high-order bits are more random than the low-order bits,
23206 	 * so we select out the high-order 17 bits and add one so that
23207 	 * we never return zero.
23208 	 */
23209 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
23210 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
23211 		tcp_random_fptr = tcp_random_state;
23212 		++tcp_random_rptr;
23213 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
23214 		tcp_random_rptr = tcp_random_state;
23215 
23216 	mutex_exit(&tcp_random_lock);
23217 	return (i);
23218 }
23219 
23220 /*
23221  * XXX This will go away when TPI is extended to send
23222  * info reqs to sockfs/timod .....
23223  * Given a queue, set the max packet size for the write
23224  * side of the queue below stream head.  This value is
23225  * cached on the stream head.
23226  * Returns 1 on success, 0 otherwise.
23227  */
23228 static int
23229 setmaxps(queue_t *q, int maxpsz)
23230 {
23231 	struct stdata	*stp;
23232 	queue_t		*wq;
23233 	stp = STREAM(q);
23234 
23235 	/*
23236 	 * At this point change of a queue parameter is not allowed
23237 	 * when a multiplexor is sitting on top.
23238 	 */
23239 	if (stp->sd_flag & STPLEX)
23240 		return (0);
23241 
23242 	claimstr(stp->sd_wrq);
23243 	wq = stp->sd_wrq->q_next;
23244 	ASSERT(wq != NULL);
23245 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
23246 	releasestr(stp->sd_wrq);
23247 	return (1);
23248 }
23249 
23250 static int
23251 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
23252     int *t_errorp, int *sys_errorp)
23253 {
23254 	int error;
23255 	int is_absreq_failure;
23256 	t_scalar_t *opt_lenp;
23257 	t_scalar_t opt_offset;
23258 	int prim_type;
23259 	struct T_conn_req *tcreqp;
23260 	struct T_conn_res *tcresp;
23261 	cred_t *cr;
23262 
23263 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
23264 
23265 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
23266 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
23267 	    prim_type == T_CONN_RES);
23268 
23269 	switch (prim_type) {
23270 	case T_CONN_REQ:
23271 		tcreqp = (struct T_conn_req *)mp->b_rptr;
23272 		opt_offset = tcreqp->OPT_offset;
23273 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
23274 		break;
23275 	case O_T_CONN_RES:
23276 	case T_CONN_RES:
23277 		tcresp = (struct T_conn_res *)mp->b_rptr;
23278 		opt_offset = tcresp->OPT_offset;
23279 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
23280 		break;
23281 	}
23282 
23283 	*t_errorp = 0;
23284 	*sys_errorp = 0;
23285 	*do_disconnectp = 0;
23286 
23287 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
23288 	    opt_offset, cr, &tcp_opt_obj,
23289 	    NULL, &is_absreq_failure);
23290 
23291 	switch (error) {
23292 	case  0:		/* no error */
23293 		ASSERT(is_absreq_failure == 0);
23294 		return (0);
23295 	case ENOPROTOOPT:
23296 		*t_errorp = TBADOPT;
23297 		break;
23298 	case EACCES:
23299 		*t_errorp = TACCES;
23300 		break;
23301 	default:
23302 		*t_errorp = TSYSERR; *sys_errorp = error;
23303 		break;
23304 	}
23305 	if (is_absreq_failure != 0) {
23306 		/*
23307 		 * The connection request should get the local ack
23308 		 * T_OK_ACK and then a T_DISCON_IND.
23309 		 */
23310 		*do_disconnectp = 1;
23311 	}
23312 	return (-1);
23313 }
23314 
23315 /*
23316  * Split this function out so that if the secret changes, I'm okay.
23317  *
23318  * Initialize the tcp_iss_cookie and tcp_iss_key.
23319  */
23320 
23321 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
23322 
23323 static void
23324 tcp_iss_key_init(uint8_t *phrase, int len)
23325 {
23326 	struct {
23327 		int32_t current_time;
23328 		uint32_t randnum;
23329 		uint16_t pad;
23330 		uint8_t ether[6];
23331 		uint8_t passwd[PASSWD_SIZE];
23332 	} tcp_iss_cookie;
23333 	time_t t;
23334 
23335 	/*
23336 	 * Start with the current absolute time.
23337 	 */
23338 	(void) drv_getparm(TIME, &t);
23339 	tcp_iss_cookie.current_time = t;
23340 
23341 	/*
23342 	 * XXX - Need a more random number per RFC 1750, not this crap.
23343 	 * OTOH, if what follows is pretty random, then I'm in better shape.
23344 	 */
23345 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
23346 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
23347 
23348 	/*
23349 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
23350 	 * as a good template.
23351 	 */
23352 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
23353 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
23354 
23355 	/*
23356 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
23357 	 */
23358 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
23359 
23360 	/*
23361 	 * See 4010593 if this section becomes a problem again,
23362 	 * but the local ethernet address is useful here.
23363 	 */
23364 	(void) localetheraddr(NULL,
23365 	    (struct ether_addr *)&tcp_iss_cookie.ether);
23366 
23367 	/*
23368 	 * Hash 'em all together.  The MD5Final is called per-connection.
23369 	 */
23370 	mutex_enter(&tcp_iss_key_lock);
23371 	MD5Init(&tcp_iss_key);
23372 	MD5Update(&tcp_iss_key, (uchar_t *)&tcp_iss_cookie,
23373 	    sizeof (tcp_iss_cookie));
23374 	mutex_exit(&tcp_iss_key_lock);
23375 }
23376 
23377 /*
23378  * Set the RFC 1948 pass phrase
23379  */
23380 /* ARGSUSED */
23381 static int
23382 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
23383     cred_t *cr)
23384 {
23385 	/*
23386 	 * Basically, value contains a new pass phrase.  Pass it along!
23387 	 */
23388 	tcp_iss_key_init((uint8_t *)value, strlen(value));
23389 	return (0);
23390 }
23391 
23392 /* ARGSUSED */
23393 static int
23394 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
23395 {
23396 	bzero(buf, sizeof (tcp_sack_info_t));
23397 	return (0);
23398 }
23399 
23400 /* ARGSUSED */
23401 static int
23402 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
23403 {
23404 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
23405 	return (0);
23406 }
23407 
23408 void
23409 tcp_ddi_init(void)
23410 {
23411 	int i;
23412 
23413 	/* Initialize locks */
23414 	rw_init(&tcp_hsp_lock, NULL, RW_DEFAULT, NULL);
23415 	mutex_init(&tcp_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
23416 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
23417 	mutex_init(&tcp_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
23418 	mutex_init(&tcp_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
23419 	rw_init(&tcp_reserved_port_lock, NULL, RW_DEFAULT, NULL);
23420 
23421 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23422 		mutex_init(&tcp_bind_fanout[i].tf_lock, NULL,
23423 		    MUTEX_DEFAULT, NULL);
23424 	}
23425 
23426 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23427 		mutex_init(&tcp_acceptor_fanout[i].tf_lock, NULL,
23428 		    MUTEX_DEFAULT, NULL);
23429 	}
23430 
23431 	/* TCP's IPsec code calls the packet dropper. */
23432 	ip_drop_register(&tcp_dropper, "TCP IPsec policy enforcement");
23433 
23434 	if (!tcp_g_nd) {
23435 		if (!tcp_param_register(tcp_param_arr, A_CNT(tcp_param_arr))) {
23436 			nd_free(&tcp_g_nd);
23437 		}
23438 	}
23439 
23440 	/*
23441 	 * Note: To really walk the device tree you need the devinfo
23442 	 * pointer to your device which is only available after probe/attach.
23443 	 * The following is safe only because it uses ddi_root_node()
23444 	 */
23445 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
23446 	    tcp_opt_obj.odb_opt_arr_cnt);
23447 
23448 	tcp_timercache = kmem_cache_create("tcp_timercache",
23449 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
23450 	    NULL, NULL, NULL, NULL, NULL, 0);
23451 
23452 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
23453 	    sizeof (tcp_sack_info_t), 0,
23454 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
23455 
23456 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
23457 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
23458 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
23459 
23460 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
23461 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
23462 
23463 	ip_squeue_init(tcp_squeue_add);
23464 
23465 	/* Initialize the random number generator */
23466 	tcp_random_init();
23467 
23468 	/*
23469 	 * Initialize RFC 1948 secret values.  This will probably be reset once
23470 	 * by the boot scripts.
23471 	 *
23472 	 * Use NULL name, as the name is caught by the new lockstats.
23473 	 *
23474 	 * Initialize with some random, non-guessable string, like the global
23475 	 * T_INFO_ACK.
23476 	 */
23477 
23478 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
23479 	    sizeof (tcp_g_t_info_ack));
23480 
23481 	if ((tcp_kstat = kstat_create(TCP_MOD_NAME, 0, "tcpstat",
23482 		"net", KSTAT_TYPE_NAMED,
23483 		sizeof (tcp_statistics) / sizeof (kstat_named_t),
23484 		KSTAT_FLAG_VIRTUAL)) != NULL) {
23485 		tcp_kstat->ks_data = &tcp_statistics;
23486 		kstat_install(tcp_kstat);
23487 	}
23488 
23489 	tcp_kstat_init();
23490 }
23491 
23492 void
23493 tcp_ddi_destroy(void)
23494 {
23495 	int i;
23496 
23497 	nd_free(&tcp_g_nd);
23498 
23499 	for (i = 0; i < A_CNT(tcp_bind_fanout); i++) {
23500 		mutex_destroy(&tcp_bind_fanout[i].tf_lock);
23501 	}
23502 
23503 	for (i = 0; i < A_CNT(tcp_acceptor_fanout); i++) {
23504 		mutex_destroy(&tcp_acceptor_fanout[i].tf_lock);
23505 	}
23506 
23507 	mutex_destroy(&tcp_iss_key_lock);
23508 	rw_destroy(&tcp_hsp_lock);
23509 	mutex_destroy(&tcp_g_q_lock);
23510 	mutex_destroy(&tcp_random_lock);
23511 	mutex_destroy(&tcp_epriv_port_lock);
23512 	rw_destroy(&tcp_reserved_port_lock);
23513 
23514 	ip_drop_unregister(&tcp_dropper);
23515 
23516 	kmem_cache_destroy(tcp_timercache);
23517 	kmem_cache_destroy(tcp_sack_info_cache);
23518 	kmem_cache_destroy(tcp_iphc_cache);
23519 
23520 	tcp_kstat_fini();
23521 }
23522 
23523 /*
23524  * Generate ISS, taking into account NDD changes may happen halfway through.
23525  * (If the iss is not zero, set it.)
23526  */
23527 
23528 static void
23529 tcp_iss_init(tcp_t *tcp)
23530 {
23531 	MD5_CTX context;
23532 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
23533 	uint32_t answer[4];
23534 
23535 	tcp_iss_incr_extra += (ISS_INCR >> 1);
23536 	tcp->tcp_iss = tcp_iss_incr_extra;
23537 	switch (tcp_strong_iss) {
23538 	case 2:
23539 		mutex_enter(&tcp_iss_key_lock);
23540 		context = tcp_iss_key;
23541 		mutex_exit(&tcp_iss_key_lock);
23542 		arg.ports = tcp->tcp_ports;
23543 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23544 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
23545 			    &arg.src);
23546 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
23547 			    &arg.dst);
23548 		} else {
23549 			arg.src = tcp->tcp_ip6h->ip6_src;
23550 			arg.dst = tcp->tcp_ip6h->ip6_dst;
23551 		}
23552 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
23553 		MD5Final((uchar_t *)answer, &context);
23554 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
23555 		/*
23556 		 * Now that we've hashed into a unique per-connection sequence
23557 		 * space, add a random increment per strong_iss == 1.  So I
23558 		 * guess we'll have to...
23559 		 */
23560 		/* FALLTHRU */
23561 	case 1:
23562 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
23563 		break;
23564 	default:
23565 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
23566 		break;
23567 	}
23568 	tcp->tcp_valid_bits = TCP_ISS_VALID;
23569 	tcp->tcp_fss = tcp->tcp_iss - 1;
23570 	tcp->tcp_suna = tcp->tcp_iss;
23571 	tcp->tcp_snxt = tcp->tcp_iss + 1;
23572 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23573 	tcp->tcp_csuna = tcp->tcp_snxt;
23574 }
23575 
23576 /*
23577  * Exported routine for extracting active tcp connection status.
23578  *
23579  * This is used by the Solaris Cluster Networking software to
23580  * gather a list of connections that need to be forwarded to
23581  * specific nodes in the cluster when configuration changes occur.
23582  *
23583  * The callback is invoked for each tcp_t structure. Returning
23584  * non-zero from the callback routine terminates the search.
23585  */
23586 int
23587 cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg)
23588 {
23589 	tcp_t *tcp;
23590 	cl_tcp_info_t	cl_tcpi;
23591 	connf_t	*connfp;
23592 	conn_t	*connp;
23593 	int	i;
23594 
23595 	ASSERT(callback != NULL);
23596 
23597 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
23598 
23599 		connfp = &ipcl_globalhash_fanout[i];
23600 		connp = NULL;
23601 
23602 		while ((connp =
23603 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
23604 
23605 			tcp = connp->conn_tcp;
23606 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
23607 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
23608 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
23609 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
23610 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
23611 			/*
23612 			 * The macros tcp_laddr and tcp_faddr give the IPv4
23613 			 * addresses. They are copied implicitly below as
23614 			 * mapped addresses.
23615 			 */
23616 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
23617 			if (tcp->tcp_ipversion == IPV4_VERSION) {
23618 				cl_tcpi.cl_tcpi_faddr =
23619 				    tcp->tcp_ipha->ipha_dst;
23620 			} else {
23621 				cl_tcpi.cl_tcpi_faddr_v6 =
23622 				    tcp->tcp_ip6h->ip6_dst;
23623 			}
23624 
23625 			/*
23626 			 * If the callback returns non-zero
23627 			 * we terminate the traversal.
23628 			 */
23629 			if ((*callback)(&cl_tcpi, arg) != 0) {
23630 				CONN_DEC_REF(tcp->tcp_connp);
23631 				return (1);
23632 			}
23633 		}
23634 	}
23635 
23636 	return (0);
23637 }
23638 
23639 /*
23640  * Macros used for accessing the different types of sockaddr
23641  * structures inside a tcp_ioc_abort_conn_t.
23642  */
23643 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
23644 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
23645 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
23646 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
23647 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
23648 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
23649 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
23650 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
23651 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
23652 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
23653 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
23654 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
23655 
23656 /*
23657  * Return the correct error code to mimic the behavior
23658  * of a connection reset.
23659  */
23660 #define	TCP_AC_GET_ERRCODE(state, err) {	\
23661 		switch ((state)) {		\
23662 		case TCPS_SYN_SENT:		\
23663 		case TCPS_SYN_RCVD:		\
23664 			(err) = ECONNREFUSED;	\
23665 			break;			\
23666 		case TCPS_ESTABLISHED:		\
23667 		case TCPS_FIN_WAIT_1:		\
23668 		case TCPS_FIN_WAIT_2:		\
23669 		case TCPS_CLOSE_WAIT:		\
23670 			(err) = ECONNRESET;	\
23671 			break;			\
23672 		case TCPS_CLOSING:		\
23673 		case TCPS_LAST_ACK:		\
23674 		case TCPS_TIME_WAIT:		\
23675 			(err) = 0;		\
23676 			break;			\
23677 		default:			\
23678 			(err) = ENXIO;		\
23679 		}				\
23680 	}
23681 
23682 /*
23683  * Check if a tcp structure matches the info in acp.
23684  */
23685 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
23686 	(((acp)->ac_local.ss_family == AF_INET) ?		\
23687 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
23688 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
23689 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
23690 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
23691 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
23692 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
23693 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
23694 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
23695 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23696 	(acp)->ac_end >= (tcp)->tcp_state) :		\
23697 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
23698 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
23699 	&(tcp)->tcp_ip_src_v6)) &&				\
23700 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
23701 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
23702 	&(tcp)->tcp_remote_v6)) &&				\
23703 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
23704 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
23705 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
23706 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
23707 	(acp)->ac_start <= (tcp)->tcp_state &&	\
23708 	(acp)->ac_end >= (tcp)->tcp_state))
23709 
23710 #define	TCP_AC_MATCH(acp, tcp)					\
23711 	(((acp)->ac_zoneid == ALL_ZONES ||			\
23712 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
23713 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
23714 
23715 /*
23716  * Build a message containing a tcp_ioc_abort_conn_t structure
23717  * which is filled in with information from acp and tp.
23718  */
23719 static mblk_t *
23720 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
23721 {
23722 	mblk_t *mp;
23723 	tcp_ioc_abort_conn_t *tacp;
23724 
23725 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
23726 	if (mp == NULL)
23727 		return (NULL);
23728 
23729 	mp->b_datap->db_type = M_CTL;
23730 
23731 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
23732 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
23733 		sizeof (uint32_t));
23734 
23735 	tacp->ac_start = acp->ac_start;
23736 	tacp->ac_end = acp->ac_end;
23737 	tacp->ac_zoneid = acp->ac_zoneid;
23738 
23739 	if (acp->ac_local.ss_family == AF_INET) {
23740 		tacp->ac_local.ss_family = AF_INET;
23741 		tacp->ac_remote.ss_family = AF_INET;
23742 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
23743 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
23744 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
23745 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
23746 	} else {
23747 		tacp->ac_local.ss_family = AF_INET6;
23748 		tacp->ac_remote.ss_family = AF_INET6;
23749 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
23750 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
23751 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
23752 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
23753 	}
23754 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
23755 	return (mp);
23756 }
23757 
23758 /*
23759  * Print a tcp_ioc_abort_conn_t structure.
23760  */
23761 static void
23762 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
23763 {
23764 	char lbuf[128];
23765 	char rbuf[128];
23766 	sa_family_t af;
23767 	in_port_t lport, rport;
23768 	ushort_t logflags;
23769 
23770 	af = acp->ac_local.ss_family;
23771 
23772 	if (af == AF_INET) {
23773 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
23774 				lbuf, 128);
23775 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
23776 				rbuf, 128);
23777 		lport = ntohs(TCP_AC_V4LPORT(acp));
23778 		rport = ntohs(TCP_AC_V4RPORT(acp));
23779 	} else {
23780 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
23781 				lbuf, 128);
23782 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
23783 				rbuf, 128);
23784 		lport = ntohs(TCP_AC_V6LPORT(acp));
23785 		rport = ntohs(TCP_AC_V6RPORT(acp));
23786 	}
23787 
23788 	logflags = SL_TRACE | SL_NOTE;
23789 	/*
23790 	 * Don't print this message to the console if the operation was done
23791 	 * to a non-global zone.
23792 	 */
23793 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23794 		logflags |= SL_CONSOLE;
23795 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
23796 		"TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
23797 		"start = %d, end = %d\n", lbuf, lport, rbuf, rport,
23798 		acp->ac_start, acp->ac_end);
23799 }
23800 
23801 /*
23802  * Called inside tcp_rput when a message built using
23803  * tcp_ioctl_abort_build_msg is put into a queue.
23804  * Note that when we get here there is no wildcard in acp any more.
23805  */
23806 static void
23807 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
23808 {
23809 	tcp_ioc_abort_conn_t *acp;
23810 
23811 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
23812 	if (tcp->tcp_state <= acp->ac_end) {
23813 		/*
23814 		 * If we get here, we are already on the correct
23815 		 * squeue. This ioctl follows the following path
23816 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
23817 		 * ->tcp_ioctl_abort->squeue_fill (if on a
23818 		 * different squeue)
23819 		 */
23820 		int errcode;
23821 
23822 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
23823 		(void) tcp_clean_death(tcp, errcode, 26);
23824 	}
23825 	freemsg(mp);
23826 }
23827 
23828 /*
23829  * Abort all matching connections on a hash chain.
23830  */
23831 static int
23832 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
23833     boolean_t exact)
23834 {
23835 	int nmatch, err = 0;
23836 	tcp_t *tcp;
23837 	MBLKP mp, last, listhead = NULL;
23838 	conn_t	*tconnp;
23839 	connf_t	*connfp = &ipcl_conn_fanout[index];
23840 
23841 startover:
23842 	nmatch = 0;
23843 
23844 	mutex_enter(&connfp->connf_lock);
23845 	for (tconnp = connfp->connf_head; tconnp != NULL;
23846 	    tconnp = tconnp->conn_next) {
23847 		tcp = tconnp->conn_tcp;
23848 		if (TCP_AC_MATCH(acp, tcp)) {
23849 			CONN_INC_REF(tcp->tcp_connp);
23850 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
23851 			if (mp == NULL) {
23852 				err = ENOMEM;
23853 				CONN_DEC_REF(tcp->tcp_connp);
23854 				break;
23855 			}
23856 			mp->b_prev = (mblk_t *)tcp;
23857 
23858 			if (listhead == NULL) {
23859 				listhead = mp;
23860 				last = mp;
23861 			} else {
23862 				last->b_next = mp;
23863 				last = mp;
23864 			}
23865 			nmatch++;
23866 			if (exact)
23867 				break;
23868 		}
23869 
23870 		/* Avoid holding lock for too long. */
23871 		if (nmatch >= 500)
23872 			break;
23873 	}
23874 	mutex_exit(&connfp->connf_lock);
23875 
23876 	/* Pass mp into the correct tcp */
23877 	while ((mp = listhead) != NULL) {
23878 		listhead = listhead->b_next;
23879 		tcp = (tcp_t *)mp->b_prev;
23880 		mp->b_next = mp->b_prev = NULL;
23881 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
23882 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
23883 	}
23884 
23885 	*count += nmatch;
23886 	if (nmatch >= 500 && err == 0)
23887 		goto startover;
23888 	return (err);
23889 }
23890 
23891 /*
23892  * Abort all connections that matches the attributes specified in acp.
23893  */
23894 static int
23895 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp)
23896 {
23897 	sa_family_t af;
23898 	uint32_t  ports;
23899 	uint16_t *pports;
23900 	int err = 0, count = 0;
23901 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
23902 	int index = -1;
23903 	ushort_t logflags;
23904 
23905 	af = acp->ac_local.ss_family;
23906 
23907 	if (af == AF_INET) {
23908 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
23909 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
23910 			pports = (uint16_t *)&ports;
23911 			pports[1] = TCP_AC_V4LPORT(acp);
23912 			pports[0] = TCP_AC_V4RPORT(acp);
23913 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
23914 		}
23915 	} else {
23916 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
23917 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
23918 			pports = (uint16_t *)&ports;
23919 			pports[1] = TCP_AC_V6LPORT(acp);
23920 			pports[0] = TCP_AC_V6RPORT(acp);
23921 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
23922 		}
23923 	}
23924 
23925 	/*
23926 	 * For cases where remote addr, local port, and remote port are non-
23927 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
23928 	 */
23929 	if (index != -1) {
23930 		err = tcp_ioctl_abort_bucket(acp, index,
23931 			    &count, exact);
23932 	} else {
23933 		/*
23934 		 * loop through all entries for wildcard case
23935 		 */
23936 		for (index = 0; index < ipcl_conn_fanout_size; index++) {
23937 			err = tcp_ioctl_abort_bucket(acp, index,
23938 			    &count, exact);
23939 			if (err != 0)
23940 				break;
23941 		}
23942 	}
23943 
23944 	logflags = SL_TRACE | SL_NOTE;
23945 	/*
23946 	 * Don't print this message to the console if the operation was done
23947 	 * to a non-global zone.
23948 	 */
23949 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
23950 		logflags |= SL_CONSOLE;
23951 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
23952 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
23953 	if (err == 0 && count == 0)
23954 		err = ENOENT;
23955 	return (err);
23956 }
23957 
23958 /*
23959  * Process the TCP_IOC_ABORT_CONN ioctl request.
23960  */
23961 static void
23962 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
23963 {
23964 	int	err;
23965 	IOCP    iocp;
23966 	MBLKP   mp1;
23967 	sa_family_t laf, raf;
23968 	tcp_ioc_abort_conn_t *acp;
23969 	zone_t *zptr;
23970 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
23971 
23972 	iocp = (IOCP)mp->b_rptr;
23973 
23974 	if ((mp1 = mp->b_cont) == NULL ||
23975 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
23976 		err = EINVAL;
23977 		goto out;
23978 	}
23979 
23980 	/* check permissions */
23981 	if (secpolicy_net_config(iocp->ioc_cr, B_FALSE) != 0) {
23982 		err = EPERM;
23983 		goto out;
23984 	}
23985 
23986 	if (mp1->b_cont != NULL) {
23987 		freemsg(mp1->b_cont);
23988 		mp1->b_cont = NULL;
23989 	}
23990 
23991 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
23992 	laf = acp->ac_local.ss_family;
23993 	raf = acp->ac_remote.ss_family;
23994 
23995 	/* check that a zone with the supplied zoneid exists */
23996 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
23997 		zptr = zone_find_by_id(zoneid);
23998 		if (zptr != NULL) {
23999 			zone_rele(zptr);
24000 		} else {
24001 			err = EINVAL;
24002 			goto out;
24003 		}
24004 	}
24005 
24006 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
24007 	    acp->ac_start > acp->ac_end || laf != raf ||
24008 	    (laf != AF_INET && laf != AF_INET6)) {
24009 		err = EINVAL;
24010 		goto out;
24011 	}
24012 
24013 	tcp_ioctl_abort_dump(acp);
24014 	err = tcp_ioctl_abort(acp);
24015 
24016 out:
24017 	if (mp1 != NULL) {
24018 		freemsg(mp1);
24019 		mp->b_cont = NULL;
24020 	}
24021 
24022 	if (err != 0)
24023 		miocnak(q, mp, 0, err);
24024 	else
24025 		miocack(q, mp, 0, 0);
24026 }
24027 
24028 /*
24029  * tcp_time_wait_processing() handles processing of incoming packets when
24030  * the tcp is in the TIME_WAIT state.
24031  * A TIME_WAIT tcp that has an associated open TCP stream is never put
24032  * on the time wait list.
24033  */
24034 void
24035 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
24036     uint32_t seg_ack, int seg_len, tcph_t *tcph)
24037 {
24038 	int32_t		bytes_acked;
24039 	int32_t		gap;
24040 	int32_t		rgap;
24041 	tcp_opt_t	tcpopt;
24042 	uint_t		flags;
24043 	uint32_t	new_swnd = 0;
24044 	conn_t		*connp;
24045 
24046 	BUMP_LOCAL(tcp->tcp_ibsegs);
24047 	TCP_RECORD_TRACE(tcp, mp, TCP_TRACE_RECV_PKT);
24048 
24049 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
24050 	new_swnd = BE16_TO_U16(tcph->th_win) <<
24051 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
24052 	if (tcp->tcp_snd_ts_ok) {
24053 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
24054 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24055 			    tcp->tcp_rnxt, TH_ACK);
24056 			goto done;
24057 		}
24058 	}
24059 	gap = seg_seq - tcp->tcp_rnxt;
24060 	rgap = tcp->tcp_rwnd - (gap + seg_len);
24061 	if (gap < 0) {
24062 		BUMP_MIB(&tcp_mib, tcpInDataDupSegs);
24063 		UPDATE_MIB(&tcp_mib, tcpInDataDupBytes,
24064 		    (seg_len > -gap ? -gap : seg_len));
24065 		seg_len += gap;
24066 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
24067 			if (flags & TH_RST) {
24068 				goto done;
24069 			}
24070 			if ((flags & TH_FIN) && seg_len == -1) {
24071 				/*
24072 				 * When TCP receives a duplicate FIN in
24073 				 * TIME_WAIT state, restart the 2 MSL timer.
24074 				 * See page 73 in RFC 793. Make sure this TCP
24075 				 * is already on the TIME_WAIT list. If not,
24076 				 * just restart the timer.
24077 				 */
24078 				if (TCP_IS_DETACHED(tcp)) {
24079 					tcp_time_wait_remove(tcp, NULL);
24080 					tcp_time_wait_append(tcp);
24081 					TCP_DBGSTAT(tcp_rput_time_wait);
24082 				} else {
24083 					ASSERT(tcp != NULL);
24084 					TCP_TIMER_RESTART(tcp,
24085 					    tcp_time_wait_interval);
24086 				}
24087 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24088 				    tcp->tcp_rnxt, TH_ACK);
24089 				goto done;
24090 			}
24091 			flags |=  TH_ACK_NEEDED;
24092 			seg_len = 0;
24093 			goto process_ack;
24094 		}
24095 
24096 		/* Fix seg_seq, and chew the gap off the front. */
24097 		seg_seq = tcp->tcp_rnxt;
24098 	}
24099 
24100 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
24101 		/*
24102 		 * Make sure that when we accept the connection, pick
24103 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
24104 		 * old connection.
24105 		 *
24106 		 * The next ISS generated is equal to tcp_iss_incr_extra
24107 		 * + ISS_INCR/2 + other components depending on the
24108 		 * value of tcp_strong_iss.  We pre-calculate the new
24109 		 * ISS here and compare with tcp_snxt to determine if
24110 		 * we need to make adjustment to tcp_iss_incr_extra.
24111 		 *
24112 		 * The above calculation is ugly and is a
24113 		 * waste of CPU cycles...
24114 		 */
24115 		uint32_t new_iss = tcp_iss_incr_extra;
24116 		int32_t adj;
24117 
24118 		switch (tcp_strong_iss) {
24119 		case 2: {
24120 			/* Add time and MD5 components. */
24121 			uint32_t answer[4];
24122 			struct {
24123 				uint32_t ports;
24124 				in6_addr_t src;
24125 				in6_addr_t dst;
24126 			} arg;
24127 			MD5_CTX context;
24128 
24129 			mutex_enter(&tcp_iss_key_lock);
24130 			context = tcp_iss_key;
24131 			mutex_exit(&tcp_iss_key_lock);
24132 			arg.ports = tcp->tcp_ports;
24133 			/* We use MAPPED addresses in tcp_iss_init */
24134 			arg.src = tcp->tcp_ip_src_v6;
24135 			if (tcp->tcp_ipversion == IPV4_VERSION) {
24136 				IN6_IPADDR_TO_V4MAPPED(
24137 					tcp->tcp_ipha->ipha_dst,
24138 					    &arg.dst);
24139 			} else {
24140 				arg.dst =
24141 				    tcp->tcp_ip6h->ip6_dst;
24142 			}
24143 			MD5Update(&context, (uchar_t *)&arg,
24144 			    sizeof (arg));
24145 			MD5Final((uchar_t *)answer, &context);
24146 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
24147 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
24148 			break;
24149 		}
24150 		case 1:
24151 			/* Add time component and min random (i.e. 1). */
24152 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
24153 			break;
24154 		default:
24155 			/* Add only time component. */
24156 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
24157 			break;
24158 		}
24159 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
24160 			/*
24161 			 * New ISS not guaranteed to be ISS_INCR/2
24162 			 * ahead of the current tcp_snxt, so add the
24163 			 * difference to tcp_iss_incr_extra.
24164 			 */
24165 			tcp_iss_incr_extra += adj;
24166 		}
24167 		/*
24168 		 * If tcp_clean_death() can not perform the task now,
24169 		 * drop the SYN packet and let the other side re-xmit.
24170 		 * Otherwise pass the SYN packet back in, since the
24171 		 * old tcp state has been cleaned up or freed.
24172 		 */
24173 		if (tcp_clean_death(tcp, 0, 27) == -1)
24174 			goto done;
24175 		/*
24176 		 * We will come back to tcp_rput_data
24177 		 * on the global queue. Packets destined
24178 		 * for the global queue will be checked
24179 		 * with global policy. But the policy for
24180 		 * this packet has already been checked as
24181 		 * this was destined for the detached
24182 		 * connection. We need to bypass policy
24183 		 * check this time by attaching a dummy
24184 		 * ipsec_in with ipsec_in_dont_check set.
24185 		 */
24186 		if ((connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid)) !=
24187 		    NULL) {
24188 			TCP_STAT(tcp_time_wait_syn_success);
24189 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
24190 			return;
24191 		}
24192 		goto done;
24193 	}
24194 
24195 	/*
24196 	 * rgap is the amount of stuff received out of window.  A negative
24197 	 * value is the amount out of window.
24198 	 */
24199 	if (rgap < 0) {
24200 		BUMP_MIB(&tcp_mib, tcpInDataPastWinSegs);
24201 		UPDATE_MIB(&tcp_mib, tcpInDataPastWinBytes, -rgap);
24202 		/* Fix seg_len and make sure there is something left. */
24203 		seg_len += rgap;
24204 		if (seg_len <= 0) {
24205 			if (flags & TH_RST) {
24206 				goto done;
24207 			}
24208 			flags |=  TH_ACK_NEEDED;
24209 			seg_len = 0;
24210 			goto process_ack;
24211 		}
24212 	}
24213 	/*
24214 	 * Check whether we can update tcp_ts_recent.  This test is
24215 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
24216 	 * Extensions for High Performance: An Update", Internet Draft.
24217 	 */
24218 	if (tcp->tcp_snd_ts_ok &&
24219 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
24220 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
24221 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
24222 		tcp->tcp_last_rcv_lbolt = lbolt64;
24223 	}
24224 
24225 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
24226 		/* Always ack out of order packets */
24227 		flags |= TH_ACK_NEEDED;
24228 		seg_len = 0;
24229 	} else if (seg_len > 0) {
24230 		BUMP_MIB(&tcp_mib, tcpInClosed);
24231 		BUMP_MIB(&tcp_mib, tcpInDataInorderSegs);
24232 		UPDATE_MIB(&tcp_mib, tcpInDataInorderBytes, seg_len);
24233 	}
24234 	if (flags & TH_RST) {
24235 		(void) tcp_clean_death(tcp, 0, 28);
24236 		goto done;
24237 	}
24238 	if (flags & TH_SYN) {
24239 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
24240 		    TH_RST|TH_ACK);
24241 		/*
24242 		 * Do not delete the TCP structure if it is in
24243 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
24244 		 */
24245 		goto done;
24246 	}
24247 process_ack:
24248 	if (flags & TH_ACK) {
24249 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
24250 		if (bytes_acked <= 0) {
24251 			if (bytes_acked == 0 && seg_len == 0 &&
24252 			    new_swnd == tcp->tcp_swnd)
24253 				BUMP_MIB(&tcp_mib, tcpInDupAck);
24254 		} else {
24255 			/* Acks something not sent */
24256 			flags |= TH_ACK_NEEDED;
24257 		}
24258 	}
24259 	if (flags & TH_ACK_NEEDED) {
24260 		/*
24261 		 * Time to send an ack for some reason.
24262 		 */
24263 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
24264 		    tcp->tcp_rnxt, TH_ACK);
24265 	}
24266 done:
24267 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24268 		DB_CKSUMSTART(mp) = 0;
24269 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
24270 		TCP_STAT(tcp_time_wait_syn_fail);
24271 	}
24272 	freemsg(mp);
24273 }
24274 
24275 /*
24276  * Return zero if the buffers are identical in length and content.
24277  * This is used for comparing extension header buffers.
24278  * Note that an extension header would be declared different
24279  * even if all that changed was the next header value in that header i.e.
24280  * what really changed is the next extension header.
24281  */
24282 static boolean_t
24283 tcp_cmpbuf(void *a, uint_t alen, boolean_t b_valid, void *b, uint_t blen)
24284 {
24285 	if (!b_valid)
24286 		blen = 0;
24287 
24288 	if (alen != blen)
24289 		return (B_TRUE);
24290 	if (alen == 0)
24291 		return (B_FALSE);	/* Both zero length */
24292 	return (bcmp(a, b, alen));
24293 }
24294 
24295 /*
24296  * Preallocate memory for tcp_savebuf(). Returns B_TRUE if ok.
24297  * Return B_FALSE if memory allocation fails - don't change any state!
24298  */
24299 static boolean_t
24300 tcp_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24301     void *src, uint_t srclen)
24302 {
24303 	void *dst;
24304 
24305 	if (!src_valid)
24306 		srclen = 0;
24307 
24308 	ASSERT(*dstlenp == 0);
24309 	if (src != NULL && srclen != 0) {
24310 		dst = mi_alloc(srclen, BPRI_MED);
24311 		if (dst == NULL)
24312 			return (B_FALSE);
24313 	} else {
24314 		dst = NULL;
24315 	}
24316 	if (*dstp != NULL) {
24317 		mi_free(*dstp);
24318 		*dstp = NULL;
24319 		*dstlenp = 0;
24320 	}
24321 	*dstp = dst;
24322 	if (dst != NULL)
24323 		*dstlenp = srclen;
24324 	else
24325 		*dstlenp = 0;
24326 	return (B_TRUE);
24327 }
24328 
24329 /*
24330  * Replace what is in *dst, *dstlen with the source.
24331  * Assumes tcp_allocbuf has already been called.
24332  */
24333 static void
24334 tcp_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
24335     void *src, uint_t srclen)
24336 {
24337 	if (!src_valid)
24338 		srclen = 0;
24339 
24340 	ASSERT(*dstlenp == srclen);
24341 	if (src != NULL && srclen != 0) {
24342 		bcopy(src, *dstp, srclen);
24343 	}
24344 }
24345 
24346 /*
24347  * Allocate a T_SVR4_OPTMGMT_REQ.
24348  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
24349  * that tcp_rput_other can drop the acks.
24350  */
24351 static mblk_t *
24352 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
24353 {
24354 	mblk_t *mp;
24355 	struct T_optmgmt_req *tor;
24356 	struct opthdr *oh;
24357 	uint_t size;
24358 	char *optptr;
24359 
24360 	size = sizeof (*tor) + sizeof (*oh) + optlen;
24361 	mp = allocb(size, BPRI_MED);
24362 	if (mp == NULL)
24363 		return (NULL);
24364 
24365 	mp->b_wptr += size;
24366 	mp->b_datap->db_type = M_PROTO;
24367 	tor = (struct T_optmgmt_req *)mp->b_rptr;
24368 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
24369 	tor->MGMT_flags = T_NEGOTIATE;
24370 	tor->OPT_length = sizeof (*oh) + optlen;
24371 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
24372 
24373 	oh = (struct opthdr *)&tor[1];
24374 	oh->level = level;
24375 	oh->name = cmd;
24376 	oh->len = optlen;
24377 	if (optlen != 0) {
24378 		optptr = (char *)&oh[1];
24379 		bcopy(opt, optptr, optlen);
24380 	}
24381 	return (mp);
24382 }
24383 
24384 /*
24385  * TCP Timers Implementation.
24386  */
24387 timeout_id_t
24388 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
24389 {
24390 	mblk_t *mp;
24391 	tcp_timer_t *tcpt;
24392 	tcp_t *tcp = connp->conn_tcp;
24393 
24394 	ASSERT(connp->conn_sqp != NULL);
24395 
24396 	TCP_DBGSTAT(tcp_timeout_calls);
24397 
24398 	if (tcp->tcp_timercache == NULL) {
24399 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
24400 	} else {
24401 		TCP_DBGSTAT(tcp_timeout_cached_alloc);
24402 		mp = tcp->tcp_timercache;
24403 		tcp->tcp_timercache = mp->b_next;
24404 		mp->b_next = NULL;
24405 		ASSERT(mp->b_wptr == NULL);
24406 	}
24407 
24408 	CONN_INC_REF(connp);
24409 	tcpt = (tcp_timer_t *)mp->b_rptr;
24410 	tcpt->connp = connp;
24411 	tcpt->tcpt_proc = f;
24412 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
24413 	return ((timeout_id_t)mp);
24414 }
24415 
24416 static void
24417 tcp_timer_callback(void *arg)
24418 {
24419 	mblk_t *mp = (mblk_t *)arg;
24420 	tcp_timer_t *tcpt;
24421 	conn_t	*connp;
24422 
24423 	tcpt = (tcp_timer_t *)mp->b_rptr;
24424 	connp = tcpt->connp;
24425 	squeue_fill(connp->conn_sqp, mp,
24426 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
24427 }
24428 
24429 static void
24430 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
24431 {
24432 	tcp_timer_t *tcpt;
24433 	conn_t *connp = (conn_t *)arg;
24434 	tcp_t *tcp = connp->conn_tcp;
24435 
24436 	tcpt = (tcp_timer_t *)mp->b_rptr;
24437 	ASSERT(connp == tcpt->connp);
24438 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
24439 
24440 	/*
24441 	 * If the TCP has reached the closed state, don't proceed any
24442 	 * further. This TCP logically does not exist on the system.
24443 	 * tcpt_proc could for example access queues, that have already
24444 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
24445 	 */
24446 	if (tcp->tcp_state != TCPS_CLOSED) {
24447 		(*tcpt->tcpt_proc)(connp);
24448 	} else {
24449 		tcp->tcp_timer_tid = 0;
24450 	}
24451 	tcp_timer_free(connp->conn_tcp, mp);
24452 }
24453 
24454 /*
24455  * There is potential race with untimeout and the handler firing at the same
24456  * time. The mblock may be freed by the handler while we are trying to use
24457  * it. But since both should execute on the same squeue, this race should not
24458  * occur.
24459  */
24460 clock_t
24461 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
24462 {
24463 	mblk_t	*mp = (mblk_t *)id;
24464 	tcp_timer_t *tcpt;
24465 	clock_t delta;
24466 
24467 	TCP_DBGSTAT(tcp_timeout_cancel_reqs);
24468 
24469 	if (mp == NULL)
24470 		return (-1);
24471 
24472 	tcpt = (tcp_timer_t *)mp->b_rptr;
24473 	ASSERT(tcpt->connp == connp);
24474 
24475 	delta = untimeout(tcpt->tcpt_tid);
24476 
24477 	if (delta >= 0) {
24478 		TCP_DBGSTAT(tcp_timeout_canceled);
24479 		tcp_timer_free(connp->conn_tcp, mp);
24480 		CONN_DEC_REF(connp);
24481 	}
24482 
24483 	return (delta);
24484 }
24485 
24486 /*
24487  * Allocate space for the timer event. The allocation looks like mblk, but it is
24488  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
24489  *
24490  * Dealing with failures: If we can't allocate from the timer cache we try
24491  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
24492  * points to b_rptr.
24493  * If we can't allocate anything using allocb_tryhard(), we perform a last
24494  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
24495  * save the actual allocation size in b_datap.
24496  */
24497 mblk_t *
24498 tcp_timermp_alloc(int kmflags)
24499 {
24500 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
24501 	    kmflags & ~KM_PANIC);
24502 
24503 	if (mp != NULL) {
24504 		mp->b_next = mp->b_prev = NULL;
24505 		mp->b_rptr = (uchar_t *)(&mp[1]);
24506 		mp->b_wptr = NULL;
24507 		mp->b_datap = NULL;
24508 		mp->b_queue = NULL;
24509 	} else if (kmflags & KM_PANIC) {
24510 		/*
24511 		 * Failed to allocate memory for the timer. Try allocating from
24512 		 * dblock caches.
24513 		 */
24514 		TCP_STAT(tcp_timermp_allocfail);
24515 		mp = allocb_tryhard(sizeof (tcp_timer_t));
24516 		if (mp == NULL) {
24517 			size_t size = 0;
24518 			/*
24519 			 * Memory is really low. Try tryhard allocation.
24520 			 */
24521 			TCP_STAT(tcp_timermp_allocdblfail);
24522 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
24523 			    sizeof (tcp_timer_t), &size, kmflags);
24524 			mp->b_rptr = (uchar_t *)(&mp[1]);
24525 			mp->b_next = mp->b_prev = NULL;
24526 			mp->b_wptr = (uchar_t *)-1;
24527 			mp->b_datap = (dblk_t *)size;
24528 			mp->b_queue = NULL;
24529 		}
24530 		ASSERT(mp->b_wptr != NULL);
24531 	}
24532 	TCP_DBGSTAT(tcp_timermp_alloced);
24533 
24534 	return (mp);
24535 }
24536 
24537 /*
24538  * Free per-tcp timer cache.
24539  * It can only contain entries from tcp_timercache.
24540  */
24541 void
24542 tcp_timermp_free(tcp_t *tcp)
24543 {
24544 	mblk_t *mp;
24545 
24546 	while ((mp = tcp->tcp_timercache) != NULL) {
24547 		ASSERT(mp->b_wptr == NULL);
24548 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
24549 		kmem_cache_free(tcp_timercache, mp);
24550 	}
24551 }
24552 
24553 /*
24554  * Free timer event. Put it on the per-tcp timer cache if there is not too many
24555  * events there already (currently at most two events are cached).
24556  * If the event is not allocated from the timer cache, free it right away.
24557  */
24558 static void
24559 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
24560 {
24561 	mblk_t *mp1 = tcp->tcp_timercache;
24562 
24563 	if (mp->b_wptr != NULL) {
24564 		/*
24565 		 * This allocation is not from a timer cache, free it right
24566 		 * away.
24567 		 */
24568 		if (mp->b_wptr != (uchar_t *)-1)
24569 			freeb(mp);
24570 		else
24571 			kmem_free(mp, (size_t)mp->b_datap);
24572 	} else if (mp1 == NULL || mp1->b_next == NULL) {
24573 		/* Cache this timer block for future allocations */
24574 		mp->b_rptr = (uchar_t *)(&mp[1]);
24575 		mp->b_next = mp1;
24576 		tcp->tcp_timercache = mp;
24577 	} else {
24578 		kmem_cache_free(tcp_timercache, mp);
24579 		TCP_DBGSTAT(tcp_timermp_freed);
24580 	}
24581 }
24582 
24583 /*
24584  * End of TCP Timers implementation.
24585  */
24586 
24587 /*
24588  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
24589  * on the specified backing STREAMS q. Note, the caller may make the
24590  * decision to call based on the tcp_t.tcp_flow_stopped value which
24591  * when check outside the q's lock is only an advisory check ...
24592  */
24593 
24594 void
24595 tcp_setqfull(tcp_t *tcp)
24596 {
24597 	queue_t *q = tcp->tcp_wq;
24598 
24599 	if (!(q->q_flag & QFULL)) {
24600 		mutex_enter(QLOCK(q));
24601 		if (!(q->q_flag & QFULL)) {
24602 			/* still need to set QFULL */
24603 			q->q_flag |= QFULL;
24604 			tcp->tcp_flow_stopped = B_TRUE;
24605 			mutex_exit(QLOCK(q));
24606 			TCP_STAT(tcp_flwctl_on);
24607 		} else {
24608 			mutex_exit(QLOCK(q));
24609 		}
24610 	}
24611 }
24612 
24613 void
24614 tcp_clrqfull(tcp_t *tcp)
24615 {
24616 	queue_t *q = tcp->tcp_wq;
24617 
24618 	if (q->q_flag & QFULL) {
24619 		mutex_enter(QLOCK(q));
24620 		if (q->q_flag & QFULL) {
24621 			q->q_flag &= ~QFULL;
24622 			tcp->tcp_flow_stopped = B_FALSE;
24623 			mutex_exit(QLOCK(q));
24624 			if (q->q_flag & QWANTW)
24625 				qbackenable(q, 0);
24626 		} else {
24627 			mutex_exit(QLOCK(q));
24628 		}
24629 	}
24630 }
24631 
24632 /*
24633  * TCP Kstats implementation
24634  */
24635 static void
24636 tcp_kstat_init(void)
24637 {
24638 	tcp_named_kstat_t template = {
24639 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
24640 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
24641 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
24642 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
24643 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
24644 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
24645 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
24646 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
24647 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
24648 		{ "inSegs",		KSTAT_DATA_UINT32, 0 },
24649 		{ "outSegs",		KSTAT_DATA_UINT32, 0 },
24650 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
24651 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
24652 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
24653 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
24654 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
24655 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
24656 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
24657 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
24658 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
24659 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
24660 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
24661 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
24662 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
24663 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
24664 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
24665 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
24666 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
24667 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
24668 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
24669 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
24670 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
24671 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
24672 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
24673 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
24674 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
24675 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
24676 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
24677 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
24678 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
24679 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
24680 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
24681 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
24682 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
24683 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
24684 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
24685 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
24686 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
24687 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
24688 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
24689 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
24690 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
24691 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
24692 	};
24693 
24694 	tcp_mibkp = kstat_create(TCP_MOD_NAME, 0, TCP_MOD_NAME,
24695 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0);
24696 
24697 	if (tcp_mibkp == NULL)
24698 		return;
24699 
24700 	template.rtoAlgorithm.value.ui32 = 4;
24701 	template.rtoMin.value.ui32 = tcp_rexmit_interval_min;
24702 	template.rtoMax.value.ui32 = tcp_rexmit_interval_max;
24703 	template.maxConn.value.i32 = -1;
24704 
24705 	bcopy(&template, tcp_mibkp->ks_data, sizeof (template));
24706 
24707 	tcp_mibkp->ks_update = tcp_kstat_update;
24708 
24709 	kstat_install(tcp_mibkp);
24710 }
24711 
24712 static void
24713 tcp_kstat_fini(void)
24714 {
24715 
24716 	if (tcp_mibkp != NULL) {
24717 		kstat_delete(tcp_mibkp);
24718 		tcp_mibkp = NULL;
24719 	}
24720 }
24721 
24722 static int
24723 tcp_kstat_update(kstat_t *kp, int rw)
24724 {
24725 	tcp_named_kstat_t	*tcpkp;
24726 	tcp_t			*tcp;
24727 	connf_t			*connfp;
24728 	conn_t			*connp;
24729 	int 			i;
24730 
24731 	if (!kp || !kp->ks_data)
24732 		return (EIO);
24733 
24734 	if (rw == KSTAT_WRITE)
24735 		return (EACCES);
24736 
24737 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
24738 
24739 	tcpkp->currEstab.value.ui32 = 0;
24740 
24741 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
24742 		connfp = &ipcl_globalhash_fanout[i];
24743 		connp = NULL;
24744 		while ((connp =
24745 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
24746 			tcp = connp->conn_tcp;
24747 			switch (tcp_snmp_state(tcp)) {
24748 			case MIB2_TCP_established:
24749 			case MIB2_TCP_closeWait:
24750 				tcpkp->currEstab.value.ui32++;
24751 				break;
24752 			}
24753 		}
24754 	}
24755 
24756 	tcpkp->activeOpens.value.ui32 = tcp_mib.tcpActiveOpens;
24757 	tcpkp->passiveOpens.value.ui32 = tcp_mib.tcpPassiveOpens;
24758 	tcpkp->attemptFails.value.ui32 = tcp_mib.tcpAttemptFails;
24759 	tcpkp->estabResets.value.ui32 = tcp_mib.tcpEstabResets;
24760 	tcpkp->inSegs.value.ui32 = tcp_mib.tcpInSegs;
24761 	tcpkp->outSegs.value.ui32 = tcp_mib.tcpOutSegs;
24762 	tcpkp->retransSegs.value.ui32 =	tcp_mib.tcpRetransSegs;
24763 	tcpkp->connTableSize.value.i32 = tcp_mib.tcpConnTableSize;
24764 	tcpkp->outRsts.value.ui32 = tcp_mib.tcpOutRsts;
24765 	tcpkp->outDataSegs.value.ui32 = tcp_mib.tcpOutDataSegs;
24766 	tcpkp->outDataBytes.value.ui32 = tcp_mib.tcpOutDataBytes;
24767 	tcpkp->retransBytes.value.ui32 = tcp_mib.tcpRetransBytes;
24768 	tcpkp->outAck.value.ui32 = tcp_mib.tcpOutAck;
24769 	tcpkp->outAckDelayed.value.ui32 = tcp_mib.tcpOutAckDelayed;
24770 	tcpkp->outUrg.value.ui32 = tcp_mib.tcpOutUrg;
24771 	tcpkp->outWinUpdate.value.ui32 = tcp_mib.tcpOutWinUpdate;
24772 	tcpkp->outWinProbe.value.ui32 = tcp_mib.tcpOutWinProbe;
24773 	tcpkp->outControl.value.ui32 = tcp_mib.tcpOutControl;
24774 	tcpkp->outFastRetrans.value.ui32 = tcp_mib.tcpOutFastRetrans;
24775 	tcpkp->inAckSegs.value.ui32 = tcp_mib.tcpInAckSegs;
24776 	tcpkp->inAckBytes.value.ui32 = tcp_mib.tcpInAckBytes;
24777 	tcpkp->inDupAck.value.ui32 = tcp_mib.tcpInDupAck;
24778 	tcpkp->inAckUnsent.value.ui32 = tcp_mib.tcpInAckUnsent;
24779 	tcpkp->inDataInorderSegs.value.ui32 = tcp_mib.tcpInDataInorderSegs;
24780 	tcpkp->inDataInorderBytes.value.ui32 = tcp_mib.tcpInDataInorderBytes;
24781 	tcpkp->inDataUnorderSegs.value.ui32 = tcp_mib.tcpInDataUnorderSegs;
24782 	tcpkp->inDataUnorderBytes.value.ui32 = tcp_mib.tcpInDataUnorderBytes;
24783 	tcpkp->inDataDupSegs.value.ui32 = tcp_mib.tcpInDataDupSegs;
24784 	tcpkp->inDataDupBytes.value.ui32 = tcp_mib.tcpInDataDupBytes;
24785 	tcpkp->inDataPartDupSegs.value.ui32 = tcp_mib.tcpInDataPartDupSegs;
24786 	tcpkp->inDataPartDupBytes.value.ui32 = tcp_mib.tcpInDataPartDupBytes;
24787 	tcpkp->inDataPastWinSegs.value.ui32 = tcp_mib.tcpInDataPastWinSegs;
24788 	tcpkp->inDataPastWinBytes.value.ui32 = tcp_mib.tcpInDataPastWinBytes;
24789 	tcpkp->inWinProbe.value.ui32 = tcp_mib.tcpInWinProbe;
24790 	tcpkp->inWinUpdate.value.ui32 = tcp_mib.tcpInWinUpdate;
24791 	tcpkp->inClosed.value.ui32 = tcp_mib.tcpInClosed;
24792 	tcpkp->rttNoUpdate.value.ui32 = tcp_mib.tcpRttNoUpdate;
24793 	tcpkp->rttUpdate.value.ui32 = tcp_mib.tcpRttUpdate;
24794 	tcpkp->timRetrans.value.ui32 = tcp_mib.tcpTimRetrans;
24795 	tcpkp->timRetransDrop.value.ui32 = tcp_mib.tcpTimRetransDrop;
24796 	tcpkp->timKeepalive.value.ui32 = tcp_mib.tcpTimKeepalive;
24797 	tcpkp->timKeepaliveProbe.value.ui32 = tcp_mib.tcpTimKeepaliveProbe;
24798 	tcpkp->timKeepaliveDrop.value.ui32 = tcp_mib.tcpTimKeepaliveDrop;
24799 	tcpkp->listenDrop.value.ui32 = tcp_mib.tcpListenDrop;
24800 	tcpkp->listenDropQ0.value.ui32 = tcp_mib.tcpListenDropQ0;
24801 	tcpkp->halfOpenDrop.value.ui32 = tcp_mib.tcpHalfOpenDrop;
24802 	tcpkp->outSackRetransSegs.value.ui32 = tcp_mib.tcpOutSackRetransSegs;
24803 	tcpkp->connTableSize6.value.i32 = tcp_mib.tcp6ConnTableSize;
24804 
24805 	return (0);
24806 }
24807 
24808 void
24809 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
24810 {
24811 	uint16_t	hdr_len;
24812 	ipha_t		*ipha;
24813 	uint8_t		*nexthdrp;
24814 	tcph_t		*tcph;
24815 
24816 	/* Already has an eager */
24817 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
24818 		TCP_STAT(tcp_reinput_syn);
24819 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
24820 		    connp, SQTAG_TCP_REINPUT_EAGER);
24821 		return;
24822 	}
24823 
24824 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
24825 	case IPV4_VERSION:
24826 		ipha = (ipha_t *)mp->b_rptr;
24827 		hdr_len = IPH_HDR_LENGTH(ipha);
24828 		break;
24829 	case IPV6_VERSION:
24830 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
24831 		    &hdr_len, &nexthdrp)) {
24832 			CONN_DEC_REF(connp);
24833 			freemsg(mp);
24834 			return;
24835 		}
24836 		break;
24837 	}
24838 
24839 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
24840 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
24841 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
24842 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
24843 	}
24844 
24845 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
24846 	    SQTAG_TCP_REINPUT);
24847 }
24848 
24849 static squeue_func_t
24850 tcp_squeue_switch(int val)
24851 {
24852 	squeue_func_t rval = squeue_fill;
24853 
24854 	switch (val) {
24855 	case 1:
24856 		rval = squeue_enter_nodrain;
24857 		break;
24858 	case 2:
24859 		rval = squeue_enter;
24860 		break;
24861 	default:
24862 		break;
24863 	}
24864 	return (rval);
24865 }
24866 
24867 static void
24868 tcp_squeue_add(squeue_t *sqp)
24869 {
24870 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
24871 		sizeof (tcp_squeue_priv_t), KM_SLEEP);
24872 
24873 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
24874 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
24875 	    sqp, TCP_TIME_WAIT_DELAY);
24876 	if (tcp_free_list_max_cnt == 0) {
24877 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
24878 			max_ncpus : boot_max_ncpus);
24879 
24880 		/*
24881 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
24882 		 */
24883 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
24884 			(tcp_ncpus * sizeof (tcp_t) * 100);
24885 	}
24886 	tcp_time_wait->tcp_free_list_cnt = 0;
24887 }
24888